answer
stringlengths 17
10.2M
|
|---|
package org.bouncycastle.crypto.tls;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
/**
* An implementation of all high level protocols in TLS 1.0/1.1.
*/
public abstract class TlsProtocol {
protected static final Integer EXT_RenegotiationInfo = Integers.valueOf(ExtensionType.renegotiation_info);
protected static final Integer EXT_SessionTicket = Integers.valueOf(ExtensionType.session_ticket);
private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack";
/*
* Our Connection states
*/
protected static final short CS_START = 0;
protected static final short CS_CLIENT_HELLO = 1;
protected static final short CS_SERVER_HELLO = 2;
protected static final short CS_SERVER_SUPPLEMENTAL_DATA = 3;
protected static final short CS_SERVER_CERTIFICATE = 4;
protected static final short CS_SERVER_KEY_EXCHANGE = 5;
protected static final short CS_CERTIFICATE_REQUEST = 6;
protected static final short CS_SERVER_HELLO_DONE = 7;
protected static final short CS_CLIENT_SUPPLEMENTAL_DATA = 8;
protected static final short CS_CLIENT_CERTIFICATE = 9;
protected static final short CS_CLIENT_KEY_EXCHANGE = 10;
protected static final short CS_CERTIFICATE_VERIFY = 11;
protected static final short CS_CLIENT_CHANGE_CIPHER_SPEC = 12;
protected static final short CS_CLIENT_FINISHED = 13;
protected static final short CS_SERVER_SESSION_TICKET = 14;
protected static final short CS_SERVER_CHANGE_CIPHER_SPEC = 15;
protected static final short CS_SERVER_FINISHED = 16;
/*
* Queues for data from some protocols.
*/
private ByteQueue applicationDataQueue = new ByteQueue();
private ByteQueue changeCipherSpecQueue = new ByteQueue();
private ByteQueue alertQueue = new ByteQueue();
private ByteQueue handshakeQueue = new ByteQueue();
/*
* The Record Stream we use
*/
protected RecordStream recordStream;
protected SecureRandom secureRandom;
private TlsInputStream tlsInputStream = null;
private TlsOutputStream tlsOutputStream = null;
private volatile boolean closed = false;
private volatile boolean failedWithError = false;
private volatile boolean appDataReady = false;
private volatile boolean writeExtraEmptyRecords = true;
private byte[] expected_verify_data = null;
protected SecurityParameters securityParameters = null;
protected short connection_state = CS_START;
protected boolean secure_renegotiation = false;
protected boolean expectSessionTicket = false;
public TlsProtocol(InputStream input, OutputStream output, SecureRandom secureRandom) {
this.recordStream = new RecordStream(this, input, output);
this.secureRandom = secureRandom;
}
protected abstract TlsContext getContext();
protected abstract TlsPeer getPeer();
protected abstract void handleChangeCipherSpecMessage() throws IOException;
protected abstract void handleHandshakeMessage(short type, byte[] buf) throws IOException;
protected void handleWarningMessage(short description) {
}
protected void completeHandshake() throws IOException {
this.expected_verify_data = null;
/*
* We will now read data, until we have completed the handshake.
*/
while (this.connection_state != CS_SERVER_FINISHED) {
safeReadRecord();
}
this.recordStream.finaliseHandshake();
ProtocolVersion version = getContext().getServerVersion();
this.writeExtraEmptyRecords = version.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv10);
/*
* If this was an initial handshake, we are now ready to send and receive application data.
*/
if (!appDataReady) {
this.appDataReady = true;
this.tlsInputStream = new TlsInputStream(this);
this.tlsOutputStream = new TlsOutputStream(this);
}
}
protected void processRecord(short protocol, byte[] buf, int offset, int len) throws IOException {
/*
* Have a look at the protocol type, and add it to the correct queue.
*/
switch (protocol) {
case ContentType.change_cipher_spec:
changeCipherSpecQueue.addData(buf, offset, len);
processChangeCipherSpec();
break;
case ContentType.alert:
alertQueue.addData(buf, offset, len);
processAlert();
break;
case ContentType.handshake:
handshakeQueue.addData(buf, offset, len);
processHandshake();
break;
case ContentType.application_data:
if (!appDataReady) {
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
applicationDataQueue.addData(buf, offset, len);
processApplicationData();
break;
default:
/*
* Uh, we don't know this protocol.
*
* RFC2246 defines on page 13, that we should ignore this.
*/
}
}
private void processHandshake() throws IOException {
boolean read;
do {
read = false;
/*
* We need the first 4 bytes, they contain type and length of the message.
*/
if (handshakeQueue.size() >= 4) {
byte[] beginning = new byte[4];
handshakeQueue.read(beginning, 0, 4, 0);
ByteArrayInputStream bis = new ByteArrayInputStream(beginning);
short type = TlsUtils.readUint8(bis);
int len = TlsUtils.readUint24(bis);
/*
* Check if we have enough bytes in the buffer to read the full message.
*/
if (handshakeQueue.size() >= (len + 4)) {
/*
* Read the message.
*/
byte[] buf = new byte[len];
handshakeQueue.read(buf, 0, len, 4);
handshakeQueue.removeData(len + 4);
/*
* RFC 2246 7.4.9. The value handshake_messages includes all handshake messages
* starting at client hello up to, but not including, this finished message.
* [..] Note: [Also,] Hello Request messages are omitted from handshake hashes.
*/
switch (type) {
case HandshakeType.hello_request:
break;
case HandshakeType.finished: {
if (this.expected_verify_data == null) {
this.expected_verify_data = createVerifyData(!getContext().isServer());
}
// NB: Fall through to next case label
}
default:
recordStream.updateHandshakeData(beginning, 0, 4);
recordStream.updateHandshakeData(buf, 0, len);
break;
}
/*
* Now, parse the message.
*/
handleHandshakeMessage(type, buf);
read = true;
}
}
} while (read);
}
private void processApplicationData() {
/*
* There is nothing we need to do here.
*
* This function could be used for callbacks when application data arrives in the future.
*/
}
private void processAlert() throws IOException {
while (alertQueue.size() >= 2) {
/*
* An alert is always 2 bytes. Read the alert.
*/
byte[] tmp = new byte[2];
alertQueue.read(tmp, 0, 2, 0);
alertQueue.removeData(2);
short level = tmp[0];
short description = tmp[1];
getPeer().notifyAlertReceived(level, description);
if (level == AlertLevel.fatal) {
this.failedWithError = true;
this.closed = true;
/*
* Now try to close the stream, ignore errors.
*/
try {
recordStream.close();
} catch (Exception e) {
}
throw new IOException(TLS_ERROR_MESSAGE);
} else {
/*
* RFC 5246 7.2.1. The other party MUST respond with a close_notify alert of its own
* and close down the connection immediately, discarding any pending writes.
*/
if (description == AlertDescription.close_notify) {
close();
}
/*
* If it is just a warning, we continue.
*/
handleWarningMessage(description);
}
}
}
/**
* This method is called, when a change cipher spec message is received.
*
* @throws IOException
* If the message has an invalid content or the handshake is not in the correct
* state.
*/
private void processChangeCipherSpec() throws IOException {
while (changeCipherSpecQueue.size() > 0) {
/*
* A change cipher spec message is only one byte with the value 1.
*/
byte[] b = new byte[1];
changeCipherSpecQueue.read(b, 0, 1, 0);
changeCipherSpecQueue.removeData(1);
if (b[0] != 1) {
/*
* This should never happen.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
recordStream.receivedReadCipherSpec();
handleChangeCipherSpecMessage();
}
}
/**
* Read data from the network. The method will return immediately, if there is still some data
* left in the buffer, or block until some application data has been read from the network.
*
* @param buf
* The buffer where the data will be copied to.
* @param offset
* The position where the data will be placed in the buffer.
* @param len
* The maximum number of bytes to read.
* @return The number of bytes read.
* @throws IOException
* If something goes wrong during reading data.
*/
protected int readApplicationData(byte[] buf, int offset, int len) throws IOException {
if (len < 1) {
return 0;
}
while (applicationDataQueue.size() == 0) {
/*
* We need to read some data.
*/
if (this.closed) {
if (this.failedWithError) {
/*
* Something went terribly wrong, we should throw an IOException
*/
throw new IOException(TLS_ERROR_MESSAGE);
}
/*
* Connection has been closed, there is no more data to read.
*/
return -1;
}
safeReadRecord();
}
len = Math.min(len, applicationDataQueue.size());
applicationDataQueue.read(buf, offset, len, 0);
applicationDataQueue.removeData(len);
return len;
}
protected void safeReadRecord() throws IOException {
try {
recordStream.readRecord();
} catch (TlsFatalAlert e) {
if (!this.closed) {
this.failWithError(AlertLevel.fatal, e.getAlertDescription());
}
throw e;
} catch (IOException e) {
if (!this.closed) {
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
} catch (RuntimeException e) {
if (!this.closed) {
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
}
protected void safeWriteRecord(short type, byte[] buf, int offset, int len) throws IOException {
try {
recordStream.writeRecord(type, buf, offset, len);
} catch (TlsFatalAlert e) {
if (!this.closed) {
this.failWithError(AlertLevel.fatal, e.getAlertDescription());
}
throw e;
} catch (IOException e) {
if (!closed) {
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
} catch (RuntimeException e) {
if (!closed) {
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
}
/**
* Send some application data to the remote system.
* <p/>
* The method will handle fragmentation internally.
*
* @param buf
* The buffer with the data.
* @param offset
* The position in the buffer where the data is placed.
* @param len
* The length of the data.
* @throws IOException
* If something goes wrong during sending.
*/
protected void writeData(byte[] buf, int offset, int len) throws IOException {
if (this.closed) {
if (this.failedWithError) {
throw new IOException(TLS_ERROR_MESSAGE);
}
throw new IOException("Sorry, connection has been closed, you cannot write more data");
}
while (len > 0) {
/*
* RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are
* potentially useful as a traffic analysis countermeasure.
*/
if (this.writeExtraEmptyRecords) {
/*
* Protect against known IV attack!
*
* DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE.
*/
safeWriteRecord(ContentType.application_data, TlsUtils.EMPTY_BYTES, 0, 0);
}
/*
* We are only allowed to write fragments up to 2^14 bytes.
*/
int toWrite = Math.min(len, 1 << 14);
safeWriteRecord(ContentType.application_data, buf, offset, toWrite);
offset += toWrite;
len -= toWrite;
}
}
/**
* @return An OutputStream which can be used to send data.
*/
public OutputStream getOutputStream() {
return this.tlsOutputStream;
}
/**
* @return An InputStream which can be used to read data.
*/
public InputStream getInputStream() {
return this.tlsInputStream;
}
/**
* Terminate this connection with an alert.
* <p/>
* Can be used for normal closure too.
*
* @param alertLevel
* The level of the alert, an be AlertLevel.fatal or AL_warning.
* @param alertDescription
* The exact alert message.
* @throws IOException
* If alert was fatal.
*/
protected void failWithError(short alertLevel, short alertDescription) throws IOException {
/*
* Check if the connection is still open.
*/
if (!closed) {
/*
* Prepare the message
*/
this.closed = true;
if (alertLevel == AlertLevel.fatal) {
/*
* This is a fatal message.
*/
this.failedWithError = true;
}
raiseAlert(alertLevel, alertDescription, null, null);
recordStream.close();
if (alertLevel == AlertLevel.fatal) {
throw new IOException(TLS_ERROR_MESSAGE);
}
} else {
throw new IOException(TLS_ERROR_MESSAGE);
}
}
protected void processFinishedMessage(ByteArrayInputStream buf) throws IOException {
TlsContext context = getContext();
/*
* Read the checksum from the finished message, it has always 12 bytes for TLS 1.0 and 36
* for SSLv3.
*/
int checksumLength = context.getServerVersion().isSSL() ? 36 : 12;
byte[] verify_data = TlsUtils.readFully(checksumLength, buf);
assertEmpty(buf);
/*
* Compare both checksums.
*/
if (!Arrays.constantTimeAreEqual(expected_verify_data, verify_data)) {
/*
* Wrong checksum in the finished message.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
}
protected void raiseAlert(short alertLevel, short alertDescription, String message, Exception cause)
throws IOException {
getPeer().notifyAlertRaised(alertLevel, alertDescription, message, cause);
byte[] error = new byte[2];
error[0] = (byte) alertLevel;
error[1] = (byte) alertDescription;
safeWriteRecord(ContentType.alert, error, 0, 2);
}
protected void raiseWarning(short alertDescription, String message) throws IOException {
raiseAlert(AlertLevel.warning, alertDescription, message, null);
}
protected void sendCertificateMessage(Certificate certificate) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.certificate, bos);
// Reserve space for length
TlsUtils.writeUint24(0, bos);
certificate.encode(bos);
byte[] message = bos.toByteArray();
// Patch actual length back in
TlsUtils.writeUint24(message.length - 4, message, 1);
safeWriteRecord(ContentType.handshake, message, 0, message.length);
}
protected void sendChangeCipherSpecMessage() throws IOException {
byte[] message = new byte[] { 1 };
safeWriteRecord(ContentType.change_cipher_spec, message, 0, message.length);
recordStream.sentWriteCipherSpec();
}
protected void sendFinishedMessage() throws IOException {
byte[] verify_data = createVerifyData(getContext().isServer());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.finished, bos);
TlsUtils.writeUint24(verify_data.length, bos);
bos.write(verify_data);
byte[] message = bos.toByteArray();
safeWriteRecord(ContentType.handshake, message, 0, message.length);
}
protected void sendSupplementalDataMessage(Vector supplementalData) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.supplemental_data, buf);
// Reserve space for length
TlsUtils.writeUint24(0, buf);
writeSupplementalData(buf, supplementalData);
byte[] message = buf.toByteArray();
// Patch actual length back in
TlsUtils.writeUint24(message.length - 4, message, 1);
safeWriteRecord(ContentType.handshake, message, 0, message.length);
}
protected byte[] createVerifyData(boolean isServer) {
TlsContext context = getContext();
if (isServer) {
return TlsUtils.calculateVerifyData(context, "server finished",
recordStream.getCurrentHash(TlsUtils.SSL_SERVER));
}
return TlsUtils.calculateVerifyData(context, "client finished",
recordStream.getCurrentHash(TlsUtils.SSL_CLIENT));
}
/**
* Closes this connection.
*
* @throws IOException
* If something goes wrong during closing.
*/
public void close() throws IOException {
if (!closed) {
this.failWithError(AlertLevel.warning, AlertDescription.close_notify);
}
}
protected void flush() throws IOException {
recordStream.flush();
}
protected static boolean arrayContains(short[] a, short n) {
for (int i = 0; i < a.length; ++i) {
if (a[i] == n) {
return true;
}
}
return false;
}
protected static boolean arrayContains(int[] a, int n) {
for (int i = 0; i < a.length; ++i) {
if (a[i] == n) {
return true;
}
}
return false;
}
/**
* Make sure the InputStream 'buf' now empty. Fail otherwise.
*
* @param buf
* The InputStream to check.
* @throws IOException
* If 'buf' is not empty.
*/
protected static void assertEmpty(ByteArrayInputStream buf) throws IOException {
if (buf.available() > 0) {
throw new TlsFatalAlert(AlertDescription.decode_error);
}
}
protected static byte[] createRandomBlock(SecureRandom random) {
byte[] result = new byte[32];
random.nextBytes(result);
TlsUtils.writeGMTUnixTime(result, 0);
return result;
}
protected static byte[] createRenegotiationInfo(byte[] renegotiated_connection) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
TlsUtils.writeOpaque8(renegotiated_connection, buf);
return buf.toByteArray();
}
protected static void establishMasterSecret(TlsContext context, TlsKeyExchange keyExchange) throws IOException {
byte[] pre_master_secret = keyExchange.generatePremasterSecret();
try {
context.getSecurityParameters().masterSecret = TlsUtils.calculateMasterSecret(context, pre_master_secret);
} finally {
// TODO Is there a way to ensure the data is really overwritten?
/*
* RFC 2246 8.1. The pre_master_secret should be deleted from memory once the
* master_secret has been computed.
*/
if (pre_master_secret != null) {
Arrays.fill(pre_master_secret, (byte) 0);
}
}
}
protected static Hashtable readExtensions(ByteArrayInputStream input) throws IOException {
if (input.available() < 1) {
return null;
}
byte[] extBytes = TlsUtils.readOpaque16(input);
assertEmpty(input);
ByteArrayInputStream buf = new ByteArrayInputStream(extBytes);
// Integer -> byte[]
Hashtable extensions = new Hashtable();
while (buf.available() > 0) {
Integer extType = Integers.valueOf(TlsUtils.readUint16(buf));
byte[] extValue = TlsUtils.readOpaque16(buf);
/*
* RFC 3546 2.3 There MUST NOT be more than one extension of the same type.
*/
if (null != extensions.put(extType, extValue)) {
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
return extensions;
}
protected static Vector readSupplementalDataMessage(ByteArrayInputStream input) throws IOException {
byte[] supp_data = TlsUtils.readOpaque24(input);
assertEmpty(input);
ByteArrayInputStream buf = new ByteArrayInputStream(supp_data);
Vector supplementalData = new Vector();
while (buf.available() > 0) {
int supp_data_type = TlsUtils.readUint16(buf);
byte[] data = TlsUtils.readOpaque16(buf);
supplementalData.addElement(new SupplementalDataEntry(supp_data_type, data));
}
return supplementalData;
}
protected static void writeExtensions(OutputStream output, Hashtable extensions) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Enumeration keys = extensions.keys();
while (keys.hasMoreElements()) {
Integer extType = (Integer) keys.nextElement();
byte[] extValue = (byte[]) extensions.get(extType);
TlsUtils.writeUint16(extType.intValue(), buf);
TlsUtils.writeOpaque16(extValue, buf);
}
byte[] extBytes = buf.toByteArray();
TlsUtils.writeOpaque16(extBytes, output);
}
protected static void writeSupplementalData(OutputStream output, Vector supplementalData) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int i = 0; i < supplementalData.size(); ++i) {
SupplementalDataEntry entry = (SupplementalDataEntry) supplementalData.elementAt(i);
TlsUtils.writeUint16(entry.getDataType(), buf);
TlsUtils.writeOpaque16(entry.getData(), buf);
}
byte[] supp_data = buf.toByteArray();
TlsUtils.writeOpaque24(supp_data, output);
}
protected static int getPRFAlgorithm(int ciphersuite) {
switch (ciphersuite) {
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return PRFAlgorithm.tls_prf_sha256;
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
return PRFAlgorithm.tls_prf_sha384;
default:
return PRFAlgorithm.tls_prf_legacy;
}
}
}
|
package org.cryptonit.cloud.interfaces;
import java.security.PrivateKey;
import java.security.PublicKey;
public interface KeyStore {
public enum KeyParameters {
RSA_2048("RSA", null, 2048),
final private String algorithm;
final private String parameter;
final private int size;
KeyParameters(String algorithm, String parameter, int size) {
this.algorithm = algorithm;
this.parameter = parameter;
this.size = size;
}
};
PrivateKey getPrivateKey(String domain, String keyIdentifier);
PublicKey getPublicKey(String domain, String keyIdentifier);
}
|
package org.deidentifier.arx.examples;
import java.io.IOException;
import java.sql.SQLException;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.DataSource;
import org.deidentifier.arx.DataType;
/**
* This class demonstrates the use of the data import facilities provided by the
* ARX framework. Data can be imported from various types of sources, e.g. CSV
* files, Excel files and databases (using JDBC). The API is mostly the same for
* all of these sources, although not all options might be available in each
* case. Refer to the comments further down below for details about particular
* sources.
*
* @author Karol Babioch
* @author Fabian Prasser
*/
public class Example21 extends Example {
/**
* Main entry point
*
* @throws IOException
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(final String[] args) throws IOException,
SQLException,
ClassNotFoundException {
exampleCSV();
exampleExcel();
exampleJDBC();
}
/**
* This method demonstrates the import of data from a simple CSV file. It
* uses more advanced features than {@link #Example2}. Columns are renamed,
* and individual columns can be ignored. Furthermore a data type for each
* column is specified, which describes the format of the appropriate data.
*/
private static void exampleCSV() throws IOException {
// Define configuration for CSV file
// The most interesting parameter is the last one, which defines
// whether or not the file contains a header assigning a name to each
// individual column, which can be used to address the column later on
DataSource source = DataSource.createCSVSource("data/test.csv", ';', true);
// Add columns
// Note that there are different means to specify a column. The first
// two columns are addressed based on their name. It is also possible
// to rename columns, which might be an interesting option to manipulate
// the output. Be aware however, that name based addressing will only
// work for types that implement the {@link IImportColumnNamed}
// interface. CSV and Excel files need to contain a header for this to
// work. "Index based" addressing on the other hand is currently
// supported by all types and is therefore guaranteed to work. This
// is the way the last column is addressed by. If the source does not
// contain a dedicated name for this column one will be assigned
// automatically, following the "Column #x" style, where x will be
// the number of the column.
source.addColumn(2, DataType.STRING); // zipcode (index based addressing)
source.addColumn("gender", DataType.STRING); // gender (named addressing)
source.addColumn("age", "renamed", DataType.INTEGER); // age (named addressing + alias name)
// In the output dataset, the columns will appear in the same order as
// specified by the order of calls to addColumn().
// Create data object
final Data data = Data.create(source);
// Print to console
print(data.getHandle());
System.out.println("\n");
}
private static void exampleExcel() throws IOException {
// Define configuration for Excel file
DataSource source = DataSource.createExcelSource("data/test.xls", 0, true);
// Add columns
source.addColumn(2, DataType.STRING); // zipcode (index based addressing)
source.addColumn("gender", DataType.STRING); // gender (named addressing)
source.addColumn("age", "renamed", DataType.INTEGER); // age (named addressing + alias name)
// Create data object
final Data data = Data.create(source);
// Print to console
print(data.getHandle());
System.out.println("\n");
}
/**
* This method demonstrates the import of data from a JDBC data source.
* Columns can be renamed, or selected individually. Furthermore a data type
* for each column is specified, which describes the format of the
* appropriate data.
*
* This example uses SQLite, and uses the example database that is contained
* within the `data` directory. Note however, that in principal every JDBC
* connection can be used here.
*
* Refer to {@link #exampleCSV()} for detailed comments about the meaning of
* certain parameters, as basically everything mentioned there also applies
* here. Obviously columns can always be addressed by name in this scenario.
*
* @throws IOException
* In case of IO errors with the given file
* @throws SQLException
* In case of SQL errors with given database
* @throws ClassNotFoundException
* In case there is no JDBC driver
*/
private static void exampleJDBC() throws IOException,
SQLException,
ClassNotFoundException {
// Load JDBC driver
Class.forName("org.sqlite.JDBC");
// Configuration for JDBC source
DataSource source = DataSource.createJDBCSource("jdbc:sqlite:data/test.db",
"test");
// Add columns
source.addColumn(2, DataType.STRING); // zipcode (index based addressing)
source.addColumn("gender", DataType.STRING); // gender (named addressing)
source.addColumn("age", "renamed", DataType.INTEGER); // age (named addressing + alias name)
// Create data object
final Data data = Data.create(source);
// Print to console
print(data.getHandle());
System.out.println("\n");
}
}
|
package org.cytoscape.rest.internal;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.io.BasicCyFileFilter;
import org.cytoscape.io.DataCategory;
import org.cytoscape.io.read.InputStreamTaskFactory;
import org.cytoscape.io.util.StreamUtil;
import org.cytoscape.io.write.CyNetworkViewWriterFactory;
import org.cytoscape.io.write.PresentationWriterFactory;
import org.cytoscape.io.write.VizmapWriterFactory;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyTableFactory;
import org.cytoscape.model.CyTableManager;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.property.CyProperty;
import org.cytoscape.rest.internal.reader.EdgeListReaderFactory;
import org.cytoscape.rest.internal.task.CyBinder;
import org.cytoscape.rest.internal.task.GrizzlyServerManager;
import org.cytoscape.rest.internal.task.HeadlessTaskMonitor;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.session.CySessionManager;
import org.cytoscape.task.NetworkCollectionTaskFactory;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.task.create.NewNetworkSelectedNodesAndEdgesTaskFactory;
import org.cytoscape.task.create.NewSessionTaskFactory;
import org.cytoscape.task.read.LoadNetworkURLTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.select.SelectFirstNeighborsTaskFactory;
import org.cytoscape.task.write.ExportNetworkViewTaskFactory;
import org.cytoscape.task.write.SaveSessionAsTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.presentation.RenderingEngineManager;
import org.cytoscape.view.vizmap.VisualMappingFunctionFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.TaskMonitor;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CyActivator extends AbstractCyActivator {
private static final Logger logger = LoggerFactory.getLogger(CyActivator.class);
private static final Integer MAX_RETRY = 10;
private static final Integer INTERVAL = 5000; // Seconds
public class WriterListener {
private VizmapWriterFactory jsFactory;
@SuppressWarnings("rawtypes")
public void registerFactory(final VizmapWriterFactory factory, final Map props) {
if (factory != null && factory.getClass().getSimpleName().equals("CytoscapeJsVisualStyleWriterFactory")) {
this.jsFactory = factory;
}
}
@SuppressWarnings("rawtypes")
public void unregisterFactory(final VizmapWriterFactory factory, final Map props) {
}
public VizmapWriterFactory getFactory() {
return this.jsFactory;
}
}
private GrizzlyServerManager grizzlyServerManager = null;
public CyActivator() {
super();
}
public void start(BundleContext bc) {
logger.info("Initializing cyREST API server...");
long start = System.currentTimeMillis();
// Start Grizzly server in separate thread
final ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(()-> {
try {
this.initDependencies(bc);
this.grizzlyServerManager.startServer();
} catch (Exception e) {
e.printStackTrace();
logger.warn("Failed to initialize cyREST server.", e);
}
});
logger.info("cyREST dependency import took: " + (System.currentTimeMillis() - start) + " msec.");
}
private final void initDependencies(final BundleContext bc) throws Exception {
final MappingFactoryManager mappingFactoryManager = new MappingFactoryManager();
registerServiceListener(bc, mappingFactoryManager, "addFactory", "removeFactory",
VisualMappingFunctionFactory.class);
final GraphicsWriterManager graphicsWriterManager = new GraphicsWriterManager();
registerServiceListener(bc, graphicsWriterManager, "addFactory", "removeFactory",
PresentationWriterFactory.class);
@SuppressWarnings("unchecked")
final CyProperty<Properties> cyPropertyServiceRef = getService(bc, CyProperty.class,
"(cyPropertyName=cytoscape3.props)");
final TaskMonitor headlessTaskMonitor = new HeadlessTaskMonitor();
final CyNetworkFactory netFact = getService(bc, CyNetworkFactory.class);
final CyNetworkViewFactory netViewFact = getService(bc, CyNetworkViewFactory.class);
final CyNetworkManager netMan = getService(bc, CyNetworkManager.class);
final CyRootNetworkManager cyRootNetworkManager = getService(bc, CyRootNetworkManager.class);
final CyNetworkViewManager netViewMan = getService(bc, CyNetworkViewManager.class);
final VisualMappingManager visMan = getService(bc, VisualMappingManager.class);
final CyApplicationManager applicationManager = getService(bc, CyApplicationManager.class);
final CyLayoutAlgorithmManager layoutManager = getService(bc, CyLayoutAlgorithmManager.class);
final VisualStyleFactory vsFactory = getService(bc, VisualStyleFactory.class);
final CyGroupFactory groupFactory = getService(bc, CyGroupFactory.class);
final CyGroupManager groupManager = getService(bc, CyGroupManager.class);
final CyTableManager tableManager = getService(bc, CyTableManager.class);
final CyTableFactory tableFactory = getService(bc, CyTableFactory.class);
final StreamUtil streamUtil = getService(bc, StreamUtil.class);
final CySessionManager sessionManager = getService(bc, CySessionManager.class);
final SaveSessionAsTaskFactory saveSessionAsTaskFactory = getService(bc, SaveSessionAsTaskFactory.class);
final OpenSessionTaskFactory openSessionTaskFactory = getService(bc, OpenSessionTaskFactory.class);
final NewSessionTaskFactory newSessionTaskFactory = getService(bc, NewSessionTaskFactory.class);
final CySwingApplication desktop = getService(bc, CySwingApplication.class);
final ExportNetworkViewTaskFactory exportNetworkViewTaskFactory = getService(bc, ExportNetworkViewTaskFactory.class);
// For commands
final AvailableCommands available = getService(bc, AvailableCommands.class);
final CommandExecutorTaskFactory ceTaskFactory = getService(bc, CommandExecutorTaskFactory.class);
final SynchronousTaskManager<?> synchronousTaskManager = getService(bc, SynchronousTaskManager.class);
// Get any command line arguments. The "-R" is ours
@SuppressWarnings("unchecked")
final CyProperty<Properties> commandLineProps = getService(bc, CyProperty.class, "(cyPropertyName=commandline.props)");
final Properties clProps = commandLineProps.getProperties();
String restPortNumber = cyPropertyServiceRef.getProperties().getProperty(GrizzlyServerManager.PORT_NUMBER_PROP);
if (clProps.getProperty(GrizzlyServerManager.PORT_NUMBER_PROP) != null)
restPortNumber = clProps.getProperty(GrizzlyServerManager.PORT_NUMBER_PROP);
if(restPortNumber == null) {
restPortNumber = GrizzlyServerManager.DEF_PORT_NUMBER.toString();
}
// Set Port number
cyPropertyServiceRef.getProperties().setProperty(GrizzlyServerManager.PORT_NUMBER_PROP, restPortNumber);
// Task factories
final NewNetworkSelectedNodesAndEdgesTaskFactory networkSelectedNodesAndEdgesTaskFactory = getService(bc,
NewNetworkSelectedNodesAndEdgesTaskFactory.class);
CyNetworkViewWriterFactory cytoscapeJsWriterFactory = null;
InputStreamTaskFactory cytoscapeJsReaderFactory = null;
CyNetworkViewWriterFactory cxWriterFactory = null;
Boolean jsonDependencyFound = false;
Integer retryCount = 0;
while(jsonDependencyFound == false && retryCount <= MAX_RETRY) {
try {
cytoscapeJsWriterFactory = getService(bc, CyNetworkViewWriterFactory.class,
"(id=cytoscapejsNetworkWriterFactory)");
cytoscapeJsReaderFactory = getService(bc, InputStreamTaskFactory.class,
"(id=cytoscapejsNetworkReaderFactory)");
jsonDependencyFound = true;
} catch(Exception ex) {
Thread.sleep(INTERVAL);
}
retryCount++;
}
if(jsonDependencyFound == false) {
throw new IllegalStateException("Could not find dependency: JSON support services are missing.");
}
retryCount = 0;
while(cxWriterFactory == null && retryCount <= MAX_RETRY) {
try {
cxWriterFactory = getService(bc, CyNetworkViewWriterFactory.class, "(id=cxNetworkWriterFactory)");
} catch(Exception ex) {
Thread.sleep(INTERVAL);
}
retryCount++;
}
if(cxWriterFactory == null) {
logger.warn("CX Support is not available. Some of the API does not work.");
}
final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory = getService(bc, LoadNetworkURLTaskFactory.class);
final SelectFirstNeighborsTaskFactory selectFirstNeighborsTaskFactory = getService(bc, SelectFirstNeighborsTaskFactory.class);
// TODO: need ID for these services.
final NetworkTaskFactory fitContent = getService(bc, NetworkTaskFactory.class, "(title=Fit Content)");
final NetworkTaskFactory edgeBundler = getService(bc, NetworkTaskFactory.class, "(title=All Nodes and Edges)");
final NetworkTaskFactory showDetailsTaskFactory = getService(bc, NetworkTaskFactory.class,
"(title=Show/Hide Graphics Details)");
final RenderingEngineManager renderingEngineManager = getService(bc,RenderingEngineManager.class);
final WriterListener writerListsner = new WriterListener();
registerServiceListener(bc, writerListsner, "registerFactory", "unregisterFactory", VizmapWriterFactory.class);
final TaskFactoryManager taskFactoryManagerManager = new TaskFactoryManagerImpl();
// Get all compatible tasks
registerServiceListener(bc, taskFactoryManagerManager, "addTaskFactory", "removeTaskFactory", TaskFactory.class);
registerServiceListener(bc, taskFactoryManagerManager,
"addInputStreamTaskFactory", "removeInputStreamTaskFactory", InputStreamTaskFactory.class);
registerServiceListener(bc, taskFactoryManagerManager, "addNetworkTaskFactory", "removeNetworkTaskFactory",
NetworkTaskFactory.class);
registerServiceListener(bc, taskFactoryManagerManager, "addNetworkCollectionTaskFactory",
"removeNetworkCollectionTaskFactory", NetworkCollectionTaskFactory.class);
// Extra readers and writers
final BasicCyFileFilter elFilter = new BasicCyFileFilter(new String[] { "el" },
new String[] { "text/edgelist" }, "Edgelist files", DataCategory.NETWORK, streamUtil);
final EdgeListReaderFactory edgeListReaderFactory = new EdgeListReaderFactory(elFilter, netViewFact, netFact,
netMan, cyRootNetworkManager);
final Properties edgeListReaderFactoryProps = new Properties();
edgeListReaderFactoryProps.setProperty("ID", "edgeListReaderFactory");
registerService(bc, edgeListReaderFactory, InputStreamTaskFactory.class, edgeListReaderFactoryProps);
// Start REST Server
final CyBinder binder = new CyBinder(netMan, netViewMan, netFact, taskFactoryManagerManager,
applicationManager, visMan, cytoscapeJsWriterFactory, cytoscapeJsReaderFactory, layoutManager,
writerListsner, headlessTaskMonitor, tableManager, vsFactory, mappingFactoryManager, groupFactory,
groupManager, cyRootNetworkManager, loadNetworkURLTaskFactory, cyPropertyServiceRef,
networkSelectedNodesAndEdgesTaskFactory, edgeListReaderFactory, netViewFact, tableFactory, fitContent,
new EdgeBundlerImpl(edgeBundler), renderingEngineManager, sessionManager,
saveSessionAsTaskFactory, openSessionTaskFactory, newSessionTaskFactory, desktop,
new LevelOfDetails(showDetailsTaskFactory), selectFirstNeighborsTaskFactory, graphicsWriterManager,
exportNetworkViewTaskFactory, available, ceTaskFactory, synchronousTaskManager, cxWriterFactory);
this.grizzlyServerManager = new GrizzlyServerManager(binder, cyPropertyServiceRef);
}
@Override
public void shutDown() {
logger.info("Shutting down REST server...");
if (grizzlyServerManager != null) {
grizzlyServerManager.stopServer();
}
}
class EdgeBundlerImpl implements EdgeBundler {
private final NetworkTaskFactory bundler;
public EdgeBundlerImpl(final NetworkTaskFactory tf) {
this.bundler = tf;
}
@Override
public NetworkTaskFactory getBundlerTF() {
return bundler;
}
}
public class LevelOfDetails {
private final NetworkTaskFactory lod;
public LevelOfDetails(final NetworkTaskFactory tf) {
this.lod = tf;
}
public NetworkTaskFactory getLodTF() {
return lod;
}
}
}
|
package foam.nanos.notification.email;
import com.google.common.base.Optional;
import foam.dao.DAO;
import foam.dao.Sink;
import foam.dao.ListSink;
import foam.nanos.notification.email.EmailTemplate;
import org.jtwig.resource.loader.ResourceLoader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import static foam.mlang.MLang.*;
public class DAOResourceLoader
implements ResourceLoader
{
public static EmailTemplate findTemplate(DAO dao, String templateName, String groupName) {
Sink list = new ListSink();
list = dao.where(AND(
EQ(EmailTemplate.NAME, templateName),
EQ(EmailTemplate.GROUP, groupName))).limit(1).select(null);
List data = ((ListSink) list).getData();
if ( data.size() == 0 ) {
list = dao.where(AND(
EQ(EmailTemplate.NAME, templateName),
EQ(EmailTemplate.GROUP, "*"))).limit(1).select(null);
}
return (EmailTemplate) data.get(0);
}
protected DAO dao_;
protected String groupName_;
public DAOResourceLoader(DAO dao, String groupName) {
dao_ = dao;
groupName_ = groupName;
}
@Override
public Optional<Charset> getCharset(String s) {
return Optional.absent();
}
@Override
public InputStream load(String s) {
EmailTemplate template = DAOResourceLoader.findTemplate(dao_, s, groupName_);
return template == null ? null : new ByteArrayInputStream(template.getBodyAsByteArray());
}
@Override
public boolean exists(String s) {
return load(s) != null;
}
@Override
public Optional<URL> toUrl(String s) {
return Optional.absent();
}
}
|
package org.helioviewer.jhv.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.AbstractList;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import org.helioviewer.jhv.JHVGlobals;
import org.helioviewer.jhv.base.logging.Log;
import org.helioviewer.jhv.camera.Camera;
import org.helioviewer.jhv.camera.Interaction;
import org.helioviewer.jhv.camera.InteractionAnnotate;
import org.helioviewer.jhv.camera.InteractionPan;
import org.helioviewer.jhv.camera.InteractionRotate;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.actions.ExitProgramAction;
import org.helioviewer.jhv.gui.components.MainComponent;
import org.helioviewer.jhv.gui.components.MainContentPanel;
import org.helioviewer.jhv.gui.components.MenuBar;
import org.helioviewer.jhv.gui.components.MoviePanel;
import org.helioviewer.jhv.gui.components.SideContentPane;
import org.helioviewer.jhv.gui.components.StatusPanel;
import org.helioviewer.jhv.gui.components.TopToolBar;
import org.helioviewer.jhv.gui.components.statusplugins.CarringtonStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugins.FramerateStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugins.PositionStatusPanel;
import org.helioviewer.jhv.gui.components.statusplugins.ZoomStatusPanel;
import org.helioviewer.jhv.gui.controller.InputController;
import org.helioviewer.jhv.io.CommandLineProcessor;
import org.helioviewer.jhv.io.LoadURIDownloadTask;
import org.helioviewer.jhv.io.LoadURITask;
import org.helioviewer.jhv.renderable.components.RenderableGrid;
import org.helioviewer.jhv.renderable.components.RenderableMiniview;
import org.helioviewer.jhv.renderable.components.RenderableTimeStamp;
import org.helioviewer.jhv.renderable.components.RenderableViewpoint;
import org.helioviewer.jhv.renderable.gui.RenderableContainer;
import org.helioviewer.jhv.renderable.gui.RenderableContainerPanel;
public class ImageViewerGui {
public static final int SIDE_PANEL_WIDTH = 320;
public static final int SIDE_PANEL_WIDTH_EXTRA = 20;
public static final int SPLIT_DIVIDER_SIZE = 3;
private static JFrame mainFrame;
private static JSplitPane midSplitPane;
private static JScrollPane leftScrollPane;
private static SideContentPane leftPane;
private static InputController inputController;
private static MainComponent mainComponent;
private static MainContentPanel mainContentPanel;
private static ZoomStatusPanel zoomStatus;
private static CarringtonStatusPanel carringtonStatus;
private static FramerateStatusPanel framerateStatus;
private static RenderableContainer renderableContainer;
private static RenderableViewpoint renderableViewpoint;
private static RenderableGrid renderableGrid;
private static RenderableMiniview renderableMiniview;
private static InteractionRotate rotationInteraction;
private static InteractionPan panInteraction;
private static InteractionAnnotate annotateInteraction;
private static Interaction currentInteraction;
public static void prepareGui() {
mainFrame = createMainFrame();
JMenuBar menuBar = new MenuBar();
mainFrame.setJMenuBar(menuBar);
JPanel contentPanel = new JPanel(new BorderLayout());
mainFrame.setContentPane(contentPanel);
midSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);
midSplitPane.setBorder(null);
midSplitPane.setOneTouchExpandable(false);
midSplitPane.setDividerSize(6);
contentPanel.add(midSplitPane, BorderLayout.CENTER);
Camera camera = Displayer.getCamera();
rotationInteraction = new InteractionRotate(camera);
panInteraction = new InteractionPan(camera);
annotateInteraction = new InteractionAnnotate(camera);
currentInteraction = rotationInteraction;
// STATUS PANEL
zoomStatus = new ZoomStatusPanel(); // zoomStatus has to be initialised before topToolBar
carringtonStatus = new CarringtonStatusPanel();
framerateStatus = new FramerateStatusPanel();
TopToolBar topToolBar = new TopToolBar();
contentPanel.add(topToolBar, BorderLayout.PAGE_START);
leftPane = new SideContentPane();
// Movie control
leftPane.add("Movie Controls", MoviePanel.getInstance(), true);
// Layer control
renderableContainer = new RenderableContainer();
renderableGrid = new RenderableGrid();
renderableContainer.addRenderable(renderableGrid);
renderableViewpoint = new RenderableViewpoint();
renderableContainer.addRenderable(renderableViewpoint);
renderableContainer.addRenderable(new RenderableTimeStamp());
renderableMiniview = new RenderableMiniview();
renderableContainer.addRenderable(renderableMiniview);
RenderableContainerPanel renderableContainerPanel = new RenderableContainerPanel(renderableContainer);
leftPane.add("Image Layers", renderableContainerPanel, true);
leftScrollPane = new JScrollPane(leftPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
leftScrollPane.setFocusable(false);
leftScrollPane.setBorder(null);
leftScrollPane.getVerticalScrollBar().setUnitIncrement(renderableContainerPanel.getGridRowHeight());
mainComponent = new MainComponent();
inputController = new InputController(camera, mainComponent);
mainContentPanel = new MainContentPanel(mainComponent);
midSplitPane.setLeftComponent(leftScrollPane);
midSplitPane.setRightComponent(mainContentPanel);
midSplitPane.setDividerSize(SPLIT_DIVIDER_SIZE);
PositionStatusPanel positionStatus = new PositionStatusPanel();
inputController.addPlugin(positionStatus);
StatusPanel statusPanel = new StatusPanel(leftScrollPane.getPreferredSize().width + SIDE_PANEL_WIDTH_EXTRA, 5);
statusPanel.addPlugin(zoomStatus, StatusPanel.Alignment.LEFT);
statusPanel.addPlugin(carringtonStatus, StatusPanel.Alignment.LEFT);
statusPanel.addPlugin(framerateStatus, StatusPanel.Alignment.LEFT);
statusPanel.addPlugin(positionStatus, StatusPanel.Alignment.RIGHT);
contentPanel.add(statusPanel, BorderLayout.PAGE_END);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
// force GLCanvas initialisation for pixel scale
mainComponent.display();
}
private static JFrame createMainFrame() {
JFrame frame = new JFrame(JHVGlobals.getProgramName());
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
ExitProgramAction exitAction = new ExitProgramAction();
exitAction.actionPerformed(new ActionEvent(this, 0, ""));
}
});
Dimension maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getSize();
Dimension minSize = new Dimension(800, 600);
minSize.width = Math.min(minSize.width, maxSize.width);
minSize.height = Math.min(minSize.height, maxSize.height);
frame.setMinimumSize(minSize);
frame.setPreferredSize(new Dimension(maxSize.width - 100, maxSize.height - 100));
enableFullScreen(frame);
return frame;
}
private static void enableFullScreen(Window window) {
if (System.getProperty("jhv.os").equals("mac")) {
try {
Class<?> fullScreenUtilities = Class.forName("com.apple.eawt.FullScreenUtilities");
Method setWindowCanFullScreen = fullScreenUtilities.getMethod("setWindowCanFullScreen", Window.class, boolean.class);
setWindowCanFullScreen.invoke(fullScreenUtilities, window, true);
System.setProperty("apple.laf.useScreenMenuBar", "true");
} catch (Exception e) {
Log.error(">> FullScreen utilities not available");
e.printStackTrace();
}
}
}
/**
* Loads the images which have to be displayed when the program starts.
*
* If there are any images defined in the command line, than this messages
* tries to load this images. Otherwise it tries to load a default image
* which is defined by the default entries of the observation panel.
* */
public static void loadImagesAtStartup() {
// get values for different command line options
AbstractList<URI> jpipUris = CommandLineProcessor.getJPIPOptionValues();
AbstractList<URI> downloadAddresses = CommandLineProcessor.getDownloadOptionValues();
AbstractList<URI> jpxUrls = CommandLineProcessor.getJPXOptionValues();
// Do nothing if no resource is specified
if (jpipUris.isEmpty() && downloadAddresses.isEmpty() && jpxUrls.isEmpty()) {
return;
}
// -jpx
for (URI jpxUrl : jpxUrls) {
if (jpxUrl != null) {
LoadURITask uriTask = new LoadURITask(jpxUrl, jpxUrl);
JHVGlobals.getExecutorService().execute(uriTask);
}
}
// -jpip
for (URI jpipUri : jpipUris) {
if (jpipUri != null) {
LoadURITask uriTask = new LoadURITask(jpipUri, jpipUri);
JHVGlobals.getExecutorService().execute(uriTask);
}
}
// -download
for (URI downloadAddress : downloadAddresses) {
if (downloadAddress != null) {
LoadURIDownloadTask uriTask = new LoadURIDownloadTask(downloadAddress, downloadAddress);
JHVGlobals.getExecutorService().execute(uriTask);
}
}
}
/**
* Toggles the visibility of the control panel on the left side.
*/
public static void toggleSidePanel() {
leftScrollPane.setVisible(!leftScrollPane.isVisible());
int lastLocation = midSplitPane.getLastDividerLocation();
if (lastLocation > 10) {
midSplitPane.setDividerLocation(lastLocation);
} else {
midSplitPane.setDividerLocation(leftScrollPane.getPreferredSize().width + SIDE_PANEL_WIDTH_EXTRA);
}
}
public static JFrame getMainFrame() {
return mainFrame;
}
public static SideContentPane getLeftContentPane() {
return leftPane;
}
public static JScrollPane getLeftScrollPane() {
return leftScrollPane;
}
public static MainComponent getMainComponent() {
return mainComponent;
}
public static MainContentPanel getMainContentPanel() {
return mainContentPanel;
}
public static InputController getInputController() {
return inputController;
}
public static ZoomStatusPanel getZoomStatusPanel() {
return zoomStatus;
}
public static CarringtonStatusPanel getCarringtonStatusPanel() {
return carringtonStatus;
}
public static FramerateStatusPanel getFramerateStatusPanel() {
return framerateStatus;
}
public static RenderableViewpoint getRenderableViewpoint() {
return renderableViewpoint;
}
public static RenderableGrid getRenderableGrid() {
return renderableGrid;
}
public static RenderableMiniview getRenderableMiniview() {
return renderableMiniview;
}
public static RenderableContainer getRenderableContainer() {
return renderableContainer;
}
public static void setCurrentInteraction(Interaction _currentInteraction) {
currentInteraction = _currentInteraction;
}
public static Interaction getCurrentInteraction() {
return currentInteraction;
}
public static Interaction getPanInteraction() {
return panInteraction;
}
public static Interaction getRotateInteraction() {
return rotationInteraction;
}
public static InteractionAnnotate getAnnotateInteraction() {
return annotateInteraction;
}
}
|
package org.dasein.cloud.test;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.test.compute.ComputeResources;
import org.dasein.cloud.test.identity.IdentityResources;
import org.dasein.cloud.test.network.NetworkResources;
import org.json.JSONException;
import org.json.JSONObject;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.TreeSet;
public class DaseinTestManager {
static private ComputeResources computeResources;
static private String defaultDataCenterId;
static private TreeSet<String> exclusions;
static private IdentityResources identityResources;
static private NetworkResources networkResources;
static private TreeSet<String> inclusions;
static public @Nonnull CloudProvider constructProvider() {
String cname = System.getProperty("providerClass");
CloudProvider provider;
if( cname == null ) {
throw new RuntimeException("Invalid class name for provider: " + cname);
}
try {
provider = (CloudProvider)Class.forName(cname).newInstance();
}
catch( Exception e ) {
throw new RuntimeException("Invalid class name " + cname + " for provider: " + e.getMessage());
}
ProviderContext ctx = new ProviderContext();
try {
String prop;
prop = System.getProperty("accountNumber");
if( prop != null ) {
ctx.setAccountNumber(prop);
}
prop = System.getProperty("accessPublic");
if( prop != null ) {
ctx.setAccessPublic(prop.getBytes("utf-8"));
}
prop = System.getProperty("accessPrivate");
if( prop != null ) {
ctx.setAccessPrivate(prop.getBytes("utf-8"));
}
prop = System.getProperty("x509CertFile");
if( prop != null ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(prop)));
StringBuilder str = new StringBuilder();
String line;
while( (line = reader.readLine()) != null ) {
str.append(line);
str.append("\n");
}
ctx.setX509Cert(str.toString().getBytes("utf-8"));
}
prop = System.getProperty("x509KeyFile");
if( prop != null ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(prop)));
StringBuilder str = new StringBuilder();
String line;
while( (line = reader.readLine()) != null ) {
str.append(line);
str.append("\n");
}
ctx.setX509Key(str.toString().getBytes("utf-8"));
}
prop = System.getProperty("endpoint");
if( prop != null ) {
ctx.setEndpoint(prop);
}
prop= System.getProperty("cloudName");
if( prop != null ) {
ctx.setCloudName(prop);
}
prop = System.getProperty("providerName");
if( prop != null ) {
ctx.setProviderName(prop);
}
prop = System.getProperty("regionId");
if( prop != null ) {
ctx.setRegionId(prop);
}
prop = System.getProperty("customProperties");
if( prop != null ) {
JSONObject json = new JSONObject(prop);
String[] names = JSONObject.getNames(json);
if( names != null ) {
Properties properties = new Properties();
for( String name : names ) {
properties.put(name, json.getString(name));
}
ctx.setCustomProperties(properties);
}
}
}
catch( UnsupportedEncodingException e ) {
throw new RuntimeException("UTF-8 unsupported: " + e.getMessage());
}
catch( FileNotFoundException e ) {
throw new RuntimeException("No such file: " + e.getMessage());
}
catch( IOException e ) {
throw new RuntimeException("Failed to read file: " + e.getMessage());
}
catch( JSONException e ) {
throw new RuntimeException("Failed to understand custom properties JSON: " + e.getMessage());
}
provider.connect(ctx);
return provider;
}
static public @Nullable ComputeResources getComputeResources() {
return computeResources;
}
static public @Nullable String getDefaultDataCenterId() {
return defaultDataCenterId;
}
static public @Nullable IdentityResources getIdentityResources() {
return identityResources;
}
static public @Nullable NetworkResources getNetworkResources() {
return networkResources;
}
static public void init(boolean stateful) {
CloudProvider provider = constructProvider();
networkResources = new NetworkResources(provider);
networkResources.init(stateful);
identityResources = new IdentityResources(provider);
identityResources.init(stateful);
computeResources = new ComputeResources(provider);
defaultDataCenterId = computeResources.init(stateful);
String prop = System.getProperty("dasein.inclusions");
if( prop != null && !prop.equals("") ) {
inclusions = new TreeSet<String>();
if( prop.contains(",") ) {
for( String which : prop.split(",") ) {
inclusions.add(which.toLowerCase());
}
}
else {
inclusions.add(prop.toLowerCase());
}
}
prop = System.getProperty("dasein.exclusions");
if( prop != null && !prop.equals("") ) {
exclusions = new TreeSet<String>();
if( prop.contains(",") ) {
for( String which : prop.split(",") ) {
exclusions.add(which.toLowerCase());
}
}
else {
exclusions.add(prop.toLowerCase());
}
}
}
static public void cleanUp() {
computeResources.close();
}
private Logger logger;
private String name;
private String prefix;
private CloudProvider provider;
private String suite;
public DaseinTestManager(@Nonnull Class<?> testClass) {
logger = Logger.getLogger(testClass);
suite = testClass.getSimpleName();
provider = constructProvider();
changePrefix();
}
public void begin(@Nonnull String name) {
this.name = name;
changePrefix();
out("");
out(">>> BEGIN
}
private void changePrefix() {
StringBuilder str = new StringBuilder();
String s;
if( suite.endsWith("Test") ) {
s = suite.substring(0, suite.length()-4);
}
else if( suite.endsWith("Tests") ) {
s = suite.substring(0, suite.length()-5);
}
else {
s = suite;
}
str.append(provider.getProviderName()).append("/").append(provider.getCloudName()).append(".").append(s);
if( name != null ) {
str.append(".").append(name);
}
if( str.length() > 44 ) {
prefix = str.substring(str.length()-44) + "> ";
}
else {
str.append("> ");
while( str.length() < 46 ) {
str.append(" ");
}
prefix = str.toString();
}
}
public void close() {
getProvider().close();
}
public void end() {
out("<<< END
out("");
name = null;
changePrefix();
}
public void error(@Nonnull String message) {
logger.error(prefix + " ERROR: " + message);
}
public @Nonnull ProviderContext getContext() {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new RuntimeException("Provider context went away");
}
return ctx;
}
public @Nullable String getName() {
return name;
}
public @Nonnull String getSuite() {
return suite;
}
public @Nullable String getTestImageId() {
return (computeResources == null ? null : computeResources.getTestImageId());
}
public @Nullable String getTestKeypairId() {
return (identityResources == null ? null : identityResources.getTestKeypairId());
}
public @Nullable String getTestStaticIpId(boolean shared) {
return networkResources == null ? null : networkResources.getTestStaticIpId(shared);
}
public @Nullable String getTestSubnetId(boolean shared) {
return (networkResources == null ? null : networkResources.getTestSubnetId(shared));
}
public @Nullable String getTestVLANId(boolean shared) {
return (networkResources == null ? null : networkResources.getTestVLANId(shared));
}
public @Nullable String getTestVMId(boolean shared, @Nullable VmState desiredState) {
if( computeResources == null ) {
return null;
}
return computeResources.getTestVMId(shared, desiredState);
}
public @Nullable String getTestVMProductId() {
return (computeResources == null ? null : computeResources.getTestVMProductId());
}
public @Nullable String getTestVolumeId(boolean shared) {
return (computeResources == null ? null : computeResources.getTestVolumeId(shared));
}
public @Nullable String getTestVolumeProductId() {
return (computeResources == null ? null : computeResources.getTestVolumeProductId());
}
public @Nonnull CloudProvider getProvider() {
return provider;
}
/**
* Checks to see if the test currently being executed is supposed to be skipped.
* A test is assumed to be run unless there are a list of inclusions and the test is not
* in the list or there is a list of exclusions and the test is in the list. If there are
* inclusions and exclusions, any conflict is resolved in favor of executing the test.
* Exclusions and inclusions are set as the {@link System} properties dasein.inclusions and
* dasein.exclusions. You may specify an entire suite (e.g. "StatelessVMTests") or a specific
* test (e.g. "StatelessVMTests.listVirtualMachines"). You may also specify multiple tests:
* <pre>
* -Ddasein.inclusions=StatelessVMTests.listVirtualMachines,StatelessDCTests
* </pre>
* This will execute only the listVirtualMachines test from StatelessVMTests and all StatelessDCTests. All other
* tests will be skipped.
* @return true if the current test is to be skipped
*/
public boolean isTestSkipped() {
if( inclusions == null && exclusions == null ) {
return false;
}
String s = suite.toLowerCase();
String t = (name == null ? null : name.toLowerCase());
boolean suiteIncluded = true;
boolean testIncluded = true;
if( inclusions != null ) {
suiteIncluded = false;
testIncluded = false;
if( inclusions.contains(s) ) {
suiteIncluded = true;
}
if( t != null && inclusions.contains(s + "." + t) ) {
testIncluded = true;
}
if( !suiteIncluded && !testIncluded ) {
return false;
}
}
if( exclusions != null ) {
if( t != null && exclusions.contains(s + "." + t) ) {
return !testIncluded;
}
if( exclusions.contains(s) ) {
if( testIncluded ) {
return false;
}
// otherwise you have a conflict and the conflict is resolved by including it
}
}
return (!suiteIncluded && !testIncluded);
}
public void ok(@Nonnull String message) {
logger.info(prefix + message + " (OK)");
}
public void out(@Nonnull String message) {
logger.info(prefix + message);
}
public void out(@Nonnull String key, boolean value) {
out(key, String.valueOf(value));
}
public void out(@Nonnull String key, int value) {
out(key, String.valueOf(value));
}
public void out(@Nonnull String key, long value) {
out(key, String.valueOf(value));
}
public void out(@Nonnull String key, double value) {
out(key, String.valueOf(value));
}
public void out(@Nonnull String key, float value) {
out(key, String.valueOf(value));
}
public void out(@Nonnull String key, Object value) {
out(key, value == null ? "null" : value.toString());
}
public void out(@Nonnull String key, @Nullable String value) {
StringBuilder str = new StringBuilder();
if( key.length() > 31 ) {
str.append(key.substring(0, 31)).append(": ");
}
else {
str.append(key).append(": ");
while( str.length() < 33 ) {
str.append(" ");
}
}
out( str.toString() + value);
}
public void skip() {
out("SKIPPING");
}
public void warn(@Nonnull String message) {
logger.warn(prefix + "WARNING: " + message);
}
}
|
package org.helioviewer.jhv.layers;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import org.helioviewer.gl3d.GL3DImageLayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.components.MoviePanel;
import org.helioviewer.jhv.gui.dialogs.MetaDataDialog;
import org.helioviewer.jhv.io.FileDownloader;
import org.helioviewer.viewmodel.view.AbstractView;
import org.helioviewer.viewmodel.view.LinkedMovieManager;
import org.helioviewer.viewmodel.view.TimedMovieView;
import org.helioviewer.viewmodel.view.View;
import org.helioviewer.viewmodel.view.jp2view.JHVJP2View;
import org.helioviewer.viewmodel.view.jp2view.JHVJPXView;
import org.helioviewer.viewmodel.view.jp2view.datetime.ImmutableDateTime;
/**
* This class is a (redundant) representation of the ViewChain state, and, in
* addition to this, introduces the concept of an "activeLayer", which is the
* Layer that is currently operated on by the user/GUI.
*
* This class is mainly used by the LayerTable(Model) as an abstraction to the
* ViewChain.
*
* Future development plans still have to show if it is worth to keep this
* class, or if the abstraction should be avoided and direct access to the
* viewChain should be used in all GUI classes.
*
* @author Malte Nuhn
*/
public class LayersModel {
private int activeLayer = -1;
private final ArrayList<LayersListener> layerListeners = new ArrayList<LayersListener>();
/**
* Return the view associated with the active Layer
*
* @return View associated with the active Layer
*/
public AbstractView getActiveView() {
return getLayer(activeLayer);
}
/**
* @return Index of the currently active Layer
*/
public int getActiveLayer() {
return activeLayer;
}
/**
* Set the activeLayer to the Layer associated with the given index
*
* @param idx
* - index of the layer to be set as active Layer
*/
public void setActiveLayer(int idx) {
AbstractView view = getLayer(idx);
if (view == null && idx != -1) {
return;
}
activeLayer = idx;
fireActiveLayerChanged(view);
}
public void setActiveLayer(AbstractView view) {
setActiveLayer(findView(view));
}
/**
* Return the timestamp of the first available image data of the layer in
* question
*
* @param view
* - View that can be associated with the layer in question
* @return timestamp of the first available image data, null if no
* information available
*/
public ImmutableDateTime getStartDate(AbstractView view) {
ImmutableDateTime result = null;
if (view instanceof JHVJPXView) {
result = ((JHVJPXView) view).getFrameDateTime(0);
} else {
result = view.getMetaData().getDateTime();
}
return result;
}
/**
* Return the timestamp of the first available image data of the layer in
* question
*
* @param idx
* - index of the layer in question
* @return timestamp of the first available image data, null if no
* information available
*/
public ImmutableDateTime getStartDate(int idx) {
return getStartDate(getLayer(idx));
}
/**
* Return the timestamp of the first available image data
*
* @return timestamp of the first available image data, null if no
* information available
*/
public Date getFirstDate() {
ImmutableDateTime earliest = null;
for (int idx = 0; idx < getNumLayers(); idx++) {
ImmutableDateTime start = getStartDate(idx);
if (start == null) {
continue;
}
if (earliest == null || start.compareTo(earliest) < 0) {
earliest = start;
}
}
return earliest == null ? null : earliest.getTime();
}
/**
* Return the timestamp of the last available image data of the layer in
* question
*
* @param view
* - View that can be associated with the layer in question
* @return timestamp of the last available image data, null if no
* information available
*/
public ImmutableDateTime getEndDate(AbstractView view) {
ImmutableDateTime result = null;
if (view instanceof JHVJPXView) {
JHVJPXView tmv = (JHVJPXView) view;
int lastFrame = tmv.getMaximumFrameNumber();
result = tmv.getFrameDateTime(lastFrame);
} else {
result = view.getMetaData().getDateTime();
}
return result;
}
/**
* Return the timestamp of the last available image data
*
* @return timestamp of the last available image data, null if no
* information available
*/
public Date getLastDate() {
ImmutableDateTime latest = null;
for (int idx = 0; idx < getNumLayers(); idx++) {
ImmutableDateTime end = getEndDate(idx);
if (end == null) {
continue;
}
if (latest == null || end.compareTo(latest) > 0) {
latest = end;
}
}
return latest == null ? null : latest.getTime();
}
/**
* Return the timestamp of the last available image data of the layer in
* question
*
* @param idx
* - index of the layer in question
* @return timestamp of the last available image data, null if no
* information available
*/
public ImmutableDateTime getEndDate(int idx) {
return getEndDate(getLayer(idx));
}
/**
* Find the index of the layer that can be associated with the given view
*
* @param view
* - View that can be associated with the layer in question
* @return index of the layer that can be associated with the given view
*/
public int findView(AbstractView view) {
int idx = -1;
if (view != null) {
idx = this.getLayerLevel(view);
}
return idx;
}
/**
* Check if the given index is valid, given the current state of the
* ViewChain
*
* @param idx
* - index of the layer in question
* @return true if the index is valid
*/
private boolean isValidIndex(int idx) {
if (idx >= 0 && idx < getNumLayers()) {
return true;
}
return false;
}
/**
* Calulate a new activeLayer after the old Layer has been deleted
*
* @param oldActiveLayerIdx
* - index of old active, but deleted, layer
* @return the index of the new active layer to choose, or -1 if no suitable
* new layer can be found
*/
private int determineNewActiveLayer(int oldActiveLayerIdx) {
int candidate = oldActiveLayerIdx;
if (!isValidIndex(candidate)) {
candidate = getNumLayers() - 1;
}
return candidate;
}
/**
* Trigger downloading the layer in question
*
* @param view
* - View that can be associated with the layer in question
*/
public void downloadLayer(JHVJP2View view) {
if (view == null) {
return;
}
Thread downloadThread = new Thread(new Runnable() {
private JHVJP2View theView;
@Override
public void run() {
downloadFromJPIP(theView);
}
public Runnable init(JHVJP2View theView) {
this.theView = theView;
return this;
}
}.init(view), "DownloadFromJPIPThread");
downloadThread.start();
}
/**
* Downloads the complete image from the JPIP server.
*
* Changes the source of the View afterwards, since a local file is always
* faster.
*/
private void downloadFromJPIP(JHVJP2View v) {
FileDownloader fileDownloader = new FileDownloader();
URI downloadUri = v.getDownloadURI();
URI uri = v.getUri();
// the http server to download the file from is unknown
if (downloadUri.equals(uri) && !downloadUri.toString().contains("delphi.nascom.nasa.gov")) {
String inputValue = JOptionPane.showInputDialog("To download this file, please specify a concurrent HTTP server address to the JPIP server: ", uri);
if (inputValue != null) {
try {
downloadUri = new URI(inputValue);
} catch (URISyntaxException e) {
}
}
}
File downloadDestination = fileDownloader.getDefaultDownloadLocation(uri);
try {
if (!fileDownloader.get(downloadUri, downloadDestination, "Downloading " + v.getName())) {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
/**
* Trigger showing a dialog displaying the meta data of the layer in
* question.
*
* @param view
* - View that can be associated with the layer in question
*
* @see org.helioviewer.jhv.gui.dialogs.MetaDataDialog
*/
public void showMetaInfo(JHVJP2View view) {
MetaDataDialog dialog = new MetaDataDialog();
dialog.setMetaData(view);
dialog.showDialog();
}
public void addLayer(AbstractView view) {
movieManager.pauseLinkedMovies();
GL3DImageLayer imageLayer = new GL3DImageLayer("", view);
view.setImageLayer(imageLayer);
layers.add(view);
if (view instanceof JHVJPXView) {
MoviePanel moviePanel = new MoviePanel((JHVJPXView) view);
setLink(view, true);
ImageViewerGui.getMoviePanelContainer().addLayer(view, moviePanel);
} else {
MoviePanel moviePanel = new MoviePanel(null);
ImageViewerGui.getMoviePanelContainer().addLayer(view, moviePanel);
}
int newIndex = layers.size() - 1;
fireLayerAdded(newIndex);
setActiveLayer(newIndex);
}
/**
* Remove the layer in question
*
* @param view
* - View that can be associated with the layer in question
*/
public void removeLayer(View view) {
if (view == null)
return;
if (view instanceof JHVJPXView) {
MoviePanel moviePanel = MoviePanel.getMoviePanel((JHVJPXView) view);
if (moviePanel != null) {
((JHVJPXView) view).pauseMovie();
moviePanel.remove();
}
}
int index = layers.indexOf(view);
layers.remove(view);
if (view instanceof JHVJPXView) {
((JHVJPXView) view).abolish();
((JHVJPXView) view).removeRenderListener();
}
fireLayerRemoved(index);
int newIndex = determineNewActiveLayer(index);
setActiveLayer(newIndex);
}
public void removeLayer(int idx) {
removeLayer(getLayer(idx));
}
/**
* Set the link-state of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @param link
* - true if the layer in question should be linked
*/
private void setLink(AbstractView view, boolean link) {
if (view == null) {
return;
}
if (view instanceof JHVJPXView) {
MoviePanel moviePanel = MoviePanel.getMoviePanel((JHVJPXView) view);
if (moviePanel != null) {
moviePanel.setMovieLink(link);
}
}
}
/**
* Return the current framerate for the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @return the current framerate or 0 if the movie is not playing, or if an
* error occurs
*/
public int getFPS(JHVJP2View view) {
int result = 0;
if (view instanceof JHVJPXView) {
result = Math.round(((JHVJPXView) view).getActualFramerate() * 100) / 100;
}
return result;
}
private void fireLayerRemoved(int oldIndex) {
for (LayersListener ll : layerListeners) {
ll.layerRemoved(oldIndex);
}
}
private void fireLayerAdded(int newIndex) {
for (LayersListener ll : layerListeners) {
ll.layerAdded(newIndex);
}
}
private void fireActiveLayerChanged(AbstractView view) {
for (LayersListener ll : layerListeners) {
ll.activeLayerChanged(view);
}
}
public void addLayersListener(LayersListener layerListener) {
layerListeners.add(layerListener);
}
public void removeLayersListener(LayersListener layerListener) {
layerListeners.remove(layerListener);
}
public LinkedList<TimedMovieView> getLayers() {
return null;
}
private final LinkedMovieManager movieManager = LinkedMovieManager.getSingletonInstance();
private final ArrayList<AbstractView> layers = new ArrayList<AbstractView>();
/**
* Returns the view at a given position within the stack of layers.
*
* @param index
* Position within the stack of layers
* @return View at given position
*/
public AbstractView getLayer(int index) {
try {
return layers.get(index);
} catch (Exception e) {
return null;
}
}
/**
* Returns number of layers
*
* @return Number of layers
* @see #getNumberOfVisibleLayer
*/
public int getNumLayers() {
return layers.size();
}
/**
* Returns the position of the view within the stack of layers.
*
* Zero indicates the most bottom view. If the given view is not a direct
* child, the function returns -1.
*
* @param view
* View to search for within the stack of layers
* @return Position of the view within stack
* @see #moveView
*/
public int getLayerLevel(AbstractView view) {
return layers.indexOf(view);
}
}
|
package gov.bnl.channelfinder.api;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
class DummyX509TrustManager implements X509TrustManager {
/*
* The default PKIX X509TrustManager9. We'll delegate decisions to it, and
* fall back to the logic in this class if the default X509TrustManager
* doesn't trust it.
*/
X509TrustManager pkixTrustManager;
DummyX509TrustManager() {
}
DummyX509TrustManager(String trustStore, char[] password) throws Exception {
this(new File(trustStore), password);
}
DummyX509TrustManager(File trustStore, char[] password) throws Exception {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(trustStore), password);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO implement checks for certificate and provide options to
// automatically acccept all, reject all or promt user
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO implement checks for certificate and provide options to
// automatically acccept all, reject all or promt user
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
if (pkixTrustManager == null)
return new X509Certificate[0];
return pkixTrustManager.getAcceptedIssuers();
}
}
|
/**
* @author sguruswami
*
* $Id: ViewModelAction.java,v 1.61 2008-07-21 18:08:31 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.60 2008/07/17 19:05:26 pandyas
* Modified to clean header to prevent SQL injection/Cross-Site Scripting
* Scan performed on July 16, 2008 by IRT
*
* Revision 1.59 2008/06/30 18:18:28 pandyas
* Removed code originally added for security scan when it caused null pointer errors
*
* Revision 1.58 2008/06/30 15:29:05 pandyas
* Modified to prevent Cross-Site Scripting
* Cleaned parameter name before proceeding
* Fixed code added in previous version
*
* Revision 1.57 2008/05/27 14:36:40 pandyas
* Modified to prevent SQL injection
* Cleaned HTTP Header before proceeding
* Re: Apps Scan run 05/23/2008
*
* Revision 1.56 2008/02/05 17:10:09 pandyas
* Removed debug statement for build to dev
*
* Revision 1.55 2008/02/05 17:09:34 pandyas
* Removed debug statement for build to dev
*
* Revision 1.54 2008/01/31 22:27:52 pandyas
* remove log printouts now that bug is resolved
*
* Revision 1.53 2008/01/31 22:23:22 pandyas
* remove log printouts now that bug is resolved
*
* Revision 1.52 2008/01/31 17:09:54 pandyas
* Modified to send new gene identifier (entrez gene id) to caBIO from new object location
*
* Revision 1.51 2008/01/28 18:45:18 pandyas
* Modified to debug caBIO data not returning to caMOD on dev
*
* Revision 1.50 2008/01/16 20:09:31 pandyas
* removed caBIO logging so the page renders when connection to caBIO fails
*
* Revision 1.49 2008/01/16 18:29:57 pandyas
* Renamed value to Transplant for #8290
*
* Revision 1.48 2008/01/10 15:55:01 pandyas
* modify output for final dev deployment
*
* Revision 1.47 2008/01/02 17:57:44 pandyas
* modified for #816 Connection to caELMIR - retrieve data for therapy search page
*
* Revision 1.46 2007/12/27 22:32:33 pandyas
* Modified for feature #8816 Connection to caELMIR - retrieve data for therapy search page
* Also added code to display Therapy link when only caELMIR data is available for a study
*
* Revision 1.45 2007/12/27 21:44:00 pandyas
* re-commit - changes did not show up in project
*
* Revision 1.44 2007/12/18 13:31:32 pandyas
* Added populate method for study data from caELMIRE for integration of Therapy study data
*
* Revision 1.43 2007/12/17 18:03:22 pandyas
* Removed * in searchFilter used for getting e-mail from LDAP
* Apps Support ticket was submitted (31169 - incorrect e-mail associated with my caMOD account) stating:
*
* Cheryl Marks submitted a ticket to NCICB Application Support in which she requested that the e-mail address associated with her account in the "User Settings" screen in caMOD be corrected. She has attempted to correct it herself, but because the program queries the LDAP Server for the e-mail address, her corrections were not retained.
*
* Revision 1.42 2007/12/04 13:49:19 pandyas
* Modified code for #8816 Connection to caELMIR - retrieve data for therapy search page
*
* Revision 1.41 2007/11/25 23:34:23 pandyas
* Initial version for feature #8816 Connection to caELMIR - retrieve data for therapy search page
*
* Revision 1.40 2007/10/31 18:39:30 pandyas
* Fixed #8188 Rename UnctrlVocab items to text entries
* Fixed #8290 Rename graft object into transplant object
*
* Revision 1.39 2007/09/14 18:53:37 pandyas
* Fixed Bug #8954: link to invivo detail page does not work
*
* Revision 1.38 2007/09/12 19:36:40 pandyas
* modified debug statements for build to stage tier
*
* Revision 1.37 2007/08/07 19:49:46 pandyas
* Removed reference to Transplant as per VCDE comments and after modification to object definition for CDE
*
* Revision 1.36 2007/08/07 18:26:20 pandyas
* Renamed to GRAFT as per VCDE comments
*
* Revision 1.35 2007/07/31 12:02:55 pandyas
* VCDE silver level and caMOD 2.3 changes
*
* Revision 1.34 2007/06/19 20:42:59 pandyas
* Users not logged in can not access the session property to check the model species. Therefore, we must show the attribute for all models.
*
* Revision 1.33 2007/06/19 18:39:21 pandyas
* Constant for species common name needs to be set for viewModelCharacteristics so it shows up for Zebrafish models
*
* Revision 1.32 2006/08/17 18:10:44 pandyas
* Defect# 410: Externalize properties files - Code changes to get properties
*
* Revision 1.31 2006/05/24 18:37:27 georgeda
* Workaround for bug in caBIO
*
* Revision 1.30 2006/05/09 18:57:54 georgeda
* Changes for searching on transient interfaces
*
* Revision 1.29 2006/05/08 13:43:15 georgeda
* Reformat and clean up warnings
*
* Revision 1.28 2006/04/19 19:31:58 georgeda
* Fixed display issue w/ GeneDelivery
*
* Revision 1.27 2006/04/19 18:50:01 georgeda
* Fixed issue w/ engineered genes displaying
*
* Revision 1.26 2006/04/17 19:09:41 pandyas
* caMod 2.1 OM changes
*
* Revision 1.25 2005/11/21 18:38:31 georgeda
* Defect #35. Trim whitespace from items that are freeform text
*
* Revision 1.24 2005/11/15 22:13:46 georgeda
* Cleanup of drug screening
*
* Revision 1.23 2005/11/14 14:21:44 georgeda
* Added sorting and spontaneous mutation
*
* Revision 1.22 2005/11/11 18:39:30 georgeda
* Removed unneeded call
*
* Revision 1.21 2005/11/10 22:07:36 georgeda
* Fixed part of bug #21
*
* Revision 1.20 2005/11/10 18:12:23 georgeda
* Use constant
*
* Revision 1.19 2005/11/07 13:57:39 georgeda
* Minor tweaks
*
* Revision 1.18 2005/11/03 15:47:11 georgeda
* Fixed slow invivo results
*
* Revision 1.17 2005/10/27 18:13:48 guruswas
* Show all publications in the publications display page.
*
* Revision 1.16 2005/10/20 21:35:37 georgeda
* Fixed xenograft display bug
*
* Revision 1.15 2005/10/19 18:56:00 guruswas
* implemented invivo details page
*
* Revision 1.14 2005/10/11 18:15:25 georgeda
* More comment changes
*
* Revision 1.13 2005/10/10 14:12:24 georgeda
* Changes for comment curation
*
* Revision 1.12 2005/10/07 21:15:03 georgeda
* Added caarray variables
*
* Revision 1.11 2005/10/06 13:37:01 georgeda
* Removed informational message
*
* Revision 1.10 2005/09/30 18:42:24 guruswas
* intial implementation of drug screening search and display page
*
* Revision 1.9 2005/09/22 21:34:51 guruswas
* First stab at carcinogenic intervention pages
*
* Revision 1.8 2005/09/22 15:23:41 georgeda
* Cleaned up warnings
*
* Revision 1.7 2005/09/21 21:02:24 guruswas
* Display the organ, disease names from NCI Thesaurus
*
* Revision 1.6 2005/09/21 20:47:16 georgeda
* Cleaned up
*
* Revision 1.5 2005/09/16 19:30:00 guruswas
* Display invivo data (from DTP) in the therapuetic approaches page
*
* Revision 1.4 2005/09/16 15:52:56 georgeda
* Changes due to manager re-write
*
*
*/
package gov.nih.nci.camod.webapp.action;
import edu.wustl.common.util.CaElmirInterfaceManager;
import gov.nih.nci.cabio.domain.Gene;
import gov.nih.nci.cabio.domain.impl.GeneImpl;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.Agent;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.CaelmirStudyData;
import gov.nih.nci.camod.domain.CarcinogenExposure;
import gov.nih.nci.camod.domain.Comments;
import gov.nih.nci.camod.domain.EngineeredGene;
import gov.nih.nci.camod.domain.GeneIdentifier;
import gov.nih.nci.camod.domain.GenomicSegment;
import gov.nih.nci.camod.domain.Transplant;
import gov.nih.nci.camod.domain.InducedMutation;
import gov.nih.nci.camod.domain.Person;
import gov.nih.nci.camod.domain.SpontaneousMutation;
import gov.nih.nci.camod.domain.TargetedModification;
import gov.nih.nci.camod.domain.Therapy;
import gov.nih.nci.camod.domain.Transgene;
import gov.nih.nci.camod.service.AgentManager;
import gov.nih.nci.camod.service.AnimalModelManager;
import gov.nih.nci.camod.service.CommentsManager;
import gov.nih.nci.camod.service.PersonManager;
import gov.nih.nci.camod.service.TransplantManager;
import gov.nih.nci.camod.service.impl.QueryManagerSingleton;
import gov.nih.nci.camod.util.EvsTreeUtil;
import gov.nih.nci.camod.util.SafeHTMLUtil;
import gov.nih.nci.common.domain.DatabaseCrossReference;
import gov.nih.nci.common.domain.impl.DatabaseCrossReferenceImpl;
import gov.nih.nci.system.applicationservice.ApplicationService;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class ViewModelAction extends BaseAction
{
/**
* sets the cancer model object in the session
*
* @param request
* the httpRequest
*/
private void setCancerModel(HttpServletRequest request)
{
String modelID = request.getParameter(Constants.Parameters.MODELID);
log.debug("<setCancerModel> modelID: " + modelID);
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel am = null;
try
{
am = animalModelManager.get(modelID);
}
catch (Exception e)
{
log.error("Unable to get cancer model in setCancerModel");
e.printStackTrace();
}
request.getSession().setAttribute(Constants.ANIMALMODEL, am);
// Set model id to display on subViewModelMenu on left menu bar
request.getSession().setAttribute(Constants.MODELID, am.getId().toString());
}
/**
* sets the cancer model object in the session
*
* @param request
* the httpRequest
* @throws Exception
*/
private void setComments(HttpServletRequest request,
String inSection) throws Exception
{
String theCommentsId = request.getParameter(Constants.Parameters.COMMENTSID);
CommentsManager theCommentsManager = (CommentsManager) getBean("commentsManager");
log.debug("Comments id: " + theCommentsId);
List<Comments> theCommentsList = new ArrayList<Comments>();
if (theCommentsId != null && theCommentsId.length() > 0)
{
Comments theComments = theCommentsManager.get(theCommentsId);
if (theComments != null)
{
System.out.println("Found a comment: " + theComments.getRemark());
theCommentsList.add(theComments);
}
}
// Get all comments that are either approved or owned by this user
else
{
PersonManager thePersonManager = (PersonManager) getBean("personManager");
Person theCurrentUser = thePersonManager.getByUsername((String) request.getSession().getAttribute(Constants.CURRENTUSER));
AnimalModel theAnimalModel = (AnimalModel) request.getSession().getAttribute(Constants.ANIMALMODEL);
theCommentsList = theCommentsManager.getAllBySection(inSection, theCurrentUser, theAnimalModel);
}
request.setAttribute(Constants.Parameters.COMMENTSLIST, theCommentsList);
}
/**
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward populateModelCharacteristics(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
request.getSession(true);
try {
/* get and clean header to prevent SQL injection/Cross-Site Scripting
*/
if (request.getHeader("HTTP header") != null){
String sID = request.getHeader("HTTP header");
log.info("sID: " + sID);
sID = SafeHTMLUtil.clean(sID);
}
// Get and clean method to prevent Cross-Site Scripting - another attempt
String methodName = request.getParameter("unprotected_method");
log.info("methodName: " + methodName);
if (!methodName.equals("populateModelCharacteristics")){
methodName = SafeHTMLUtil.clean(methodName);
log.info("methodName: " + methodName);
}
setCancerModel(request);
setComments(request, Constants.Pages.MODEL_CHARACTERISTICS);
// Call method so therapy link displays for models with caELMIR-only data
populateCaelmirTherapyDetails(mapping, form, request, response);
}
catch (Exception e)
{
log.error("Error in populateModelCharacteristics", e);
}
return mapping.findForward("viewModelCharacteristics");
}
public ActionForward populateEngineeredGene(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
log.debug("<populateEngineeredGene> modelID" + request.getParameter("aModelID"));
String modelID = request.getParameter("aModelID");
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel am = animalModelManager.get(modelID);
final Set egc = am.getEngineeredGeneCollection();
final int egcCnt = (egc != null) ? egc.size() : 0;
final List<EngineeredGene> tgc = new ArrayList<EngineeredGene>();
int tgCnt = 0;// Transgene
final List<EngineeredGene> gsc = new ArrayList<EngineeredGene>();
int gsCnt = 0;// GenomicSegment
final List<EngineeredGene> tmc = new ArrayList<EngineeredGene>();
int tmCnt = 0;// TargetedModification
final Map<Long, Gene> tmGeneMap = new HashMap<Long, Gene>();
final List<EngineeredGene> imc = new ArrayList<EngineeredGene>();
final List<SpontaneousMutation> smc = new ArrayList<SpontaneousMutation>(am.getSpontaneousMutationCollection());
Iterator it = egc.iterator();
int imCnt = 0;// InducedMutation
while (it.hasNext())
{
EngineeredGene eg = (EngineeredGene) it.next();
if (eg instanceof Transgene)
{
tgc.add(eg);
tgCnt++;
}
else if (eg instanceof GenomicSegment)
{
gsc.add(eg);
gsCnt++;
}
else if (eg instanceof TargetedModification)
{
tmc.add(eg);
tmCnt++;
// now go to caBIO and query the gene object....
TargetedModification tm = (TargetedModification) eg;
GeneIdentifier geneIdentifier = tm.getGeneIdentifier();
//log.debug("geneIdentifier.getEntrezGeneID() " + geneIdentifier.getEntrezGeneID());
if (geneIdentifier != null)
{
//log.debug("Connecting to caBIO to look up gene " + geneIdentifier);
// the geneId is available
try
{
ApplicationService appService = EvsTreeUtil.getApplicationService();
DatabaseCrossReference dcr = new DatabaseCrossReferenceImpl();
dcr.setCrossReferenceId(geneIdentifier.getEntrezGeneID());
dcr.setType("gov.nih.nci.cabio.domain.Gene");
dcr.setDataSourceName("LOCUS_LINK_ID");
List<DatabaseCrossReference> cfcoll = new ArrayList<DatabaseCrossReference>();
cfcoll.add(dcr);
Gene myGene = new GeneImpl();
myGene.setDatabaseCrossReferenceCollection(cfcoll);
List resultList = appService.search(Gene.class, myGene);
final int geneCount = (resultList != null) ? resultList.size() : 0;
//log.debug("Got " + geneCount + " Gene Objects");
if (geneCount > 0)
{
myGene = (Gene) resultList.get(0);
//log.info("Gene:" + geneIdentifier + " ==>" + myGene);
tmGeneMap.put(tm.getId(), myGene);
}
}
catch (Exception e)
{
log.error("Unable to get information from caBIO", e);
}
}
}
else if (eg instanceof InducedMutation)
{
imc.add(eg);
imCnt++;
}
}
log.debug("<populateEngineeredGene> " + "egcCnt=" + egcCnt + "tgc=" + tgCnt + "gsc=" + gsCnt + "tmc=" + tmCnt + "imc=" + imCnt);
request.getSession().setAttribute(Constants.ANIMALMODEL, am);
request.getSession().setAttribute(Constants.TRANSGENE_COLL, tgc);
request.getSession().setAttribute(Constants.GENOMIC_SEG_COLL, gsc);
request.getSession().setAttribute(Constants.TARGETED_MOD_COLL, tmc);
request.getSession().setAttribute(Constants.TARGETED_MOD_GENE_MAP, tmGeneMap);
request.getSession().setAttribute(Constants.INDUCED_MUT_COLL, imc);
request.getSession().setAttribute(Constants.SPONTANEOUS_MUT_COLL, smc);
log.debug("<populateEngineeredGene> set attributes done.");
setComments(request, Constants.Pages.GENETIC_DESCRIPTION);
return mapping.findForward("viewGeneticDescription");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateCarcinogenicInterventions(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
String modelID = request.getParameter(Constants.Parameters.MODELID);
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel am = animalModelManager.get(modelID);
final Set ceColl = am.getCarcinogenExposureCollection();
Iterator it = ceColl.iterator();
final Map<String, List<Object>> interventionTypeMap = new HashMap<String, List<Object>>();
while (it.hasNext())
{
CarcinogenExposure ce = (CarcinogenExposure) it.next();
if (ce != null)
{
log.debug("Checking agent:" + ce.getEnvironmentalFactor().getNscNumber());
String theType = ce.getEnvironmentalFactor().getType();
if (theType == null || theType.length() == 0)
{
theType = ce.getEnvironmentalFactor().getTypeAlternEntry();
if (theType == null || theType.length() == 0)
{
theType = "Not specified";
}
}
List<Object> theTypeColl = interventionTypeMap.get(theType);
if (theTypeColl == null)
{
theTypeColl = new ArrayList<Object>();
interventionTypeMap.put(theType, theTypeColl);
}
theTypeColl.add(ce);
}
}
if (am.getGeneDeliveryCollection().size() > 0)
{
List<Object> theGeneDeliveryCollection = new ArrayList<Object>(am.getGeneDeliveryCollection());
interventionTypeMap.put("GeneDelivery", theGeneDeliveryCollection);
}
request.getSession().setAttribute(Constants.CARCINOGENIC_INTERVENTIONS_COLL, interventionTypeMap);
setComments(request, Constants.Pages.CARCINOGENIC_INTERVENTION);
return mapping.findForward("viewCarcinogenicInterventions");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populatePublications(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
String modelID = request.getParameter("aModelID");
List pubs = null;
try
{
pubs = QueryManagerSingleton.instance().getAllPublications(Long.valueOf(modelID).longValue());
log.debug("pubs.size(): " + pubs.size());
}
catch (Exception e)
{
log.error("Unable to get publications");
e.printStackTrace();
}
request.getSession().setAttribute(Constants.PUBLICATIONS, pubs);
setComments(request, Constants.Pages.PUBLICATIONS);
return mapping.findForward("viewPublications");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateHistopathology(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
setComments(request, Constants.Pages.HISTOPATHOLOGY);
return mapping.findForward("viewHistopathology");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateTherapeuticApproaches(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
log.debug("<ViewModelAction> populateTherapeuticApproaches");
setCancerModel(request);
// query caBIO and load clinical protocols information
// store clinicalProtocol info in a hashmap keyed by NSC
final HashMap<Long, Collection> clinProtocols = new HashMap<Long, Collection>();
final HashMap<Long, Collection> yeastResults = new HashMap<Long, Collection>();
final HashMap<Long, Collection> invivoResults = new HashMap<Long, Collection>();
final List<Therapy> therapeuticApprochesColl = new ArrayList<Therapy>();
String modelID = request.getParameter(Constants.Parameters.MODELID);
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel am = animalModelManager.get(modelID);
final Set therapyColl = am.getTherapyCollection();
Iterator it = therapyColl.iterator();
final int cc = (therapyColl != null) ? therapyColl.size() : 0;
log.debug("Looking up clinical protocols for " + cc + " agents...");
while (it.hasNext())
{
Therapy t = (Therapy) it.next();
if (t != null)
{
therapeuticApprochesColl.add(t);
}
Agent a = t.getAgent();
AgentManager myAgentManager = (AgentManager) getBean("agentManager");
if (a != null)
{
Long nscNumber = a.getNscNumber();
if (nscNumber != null)
{
Collection protocols = myAgentManager.getClinicalProtocols(a);
clinProtocols.put(nscNumber, protocols);
// get the yeast data
List yeastStages = myAgentManager.getYeastResults(a, true);
if (yeastStages.size() > 0)
{
yeastResults.put(a.getId(), yeastStages);
}
// now get invivo/Transplant data
List transplantResults = QueryManagerSingleton.instance().getInvivoResults(a, true);
invivoResults.put(a.getId(), transplantResults);
}
}
}
request.getSession().setAttribute(Constants.THERAPEUTIC_APPROACHES_COLL, therapeuticApprochesColl);
request.getSession().setAttribute(Constants.CLINICAL_PROTOCOLS, clinProtocols);
request.getSession().setAttribute(Constants.YEAST_DATA, yeastResults);
request.getSession().setAttribute(Constants.INVIVO_DATA, invivoResults);
setComments(request, Constants.Pages.THERAPEUTIC_APPROACHES);
populateCaelmirTherapyDetails(mapping, form, request, response);
return mapping.findForward("viewTherapeuticApproaches");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateCaelmirTherapyDetails(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//log.debug<"<ViewModelAction> populateCaelmirTherapyDetails Enter");
setCancerModel(request);
JSONArray jsonArray = new JSONArray();
JSONObject jobj = new JSONObject();
Vector h = new Vector();
ArrayList caelmirStudyData = new ArrayList();
String modelID = request.getParameter(Constants.Parameters.MODELID);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel theAnimalModel = theAnimalModelManager.get(modelID);
try {
log.debug("<ViewModelAction> populateCaelmirTherapyDetails Enter try");
// Link to the inteface provided by caElmir
URL url = new URL("http://chichen-itza.compmed.ucdavis.edu:8080/"
+ CaElmirInterfaceManager.getStudyInfoUrl());
// set your proxy server and port
//System.setProperty("proxyHost", "ptproxy.persistent.co.in");
//System.setProperty("proxyPort", "8080");
URLConnection urlConnection = url.openConnection();
//log.debug("populateCaelmirTherapyDetails open connection");
// needs to be set to True for writing to the output stream.This
// allows to pass data to the url.
urlConnection.setDoOutput(true);
JSONObject jsonObj = new JSONObject();
// setting the model id.
jsonObj.put(CaElmirInterfaceManager.getModelIdParameter(), modelID);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.write(jsonObj.toString());
out.flush();
out.close();
//log.debug("populateCaelmirTherapyDetails created JSONObject");
// start reading the responce
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
if (bufferedReader != null) {
String resultStr = (String) bufferedReader.readLine();
jsonArray = new JSONArray(resultStr);
String status = null;
status = ((JSONObject) jsonArray.get(0)).get(
CaElmirInterfaceManager.getStatusMessageKey())
.toString();
//log.debug("populateCaelmirTherapyDetails status: " + status);
// Imporatant:first check for the status
if (!CaElmirInterfaceManager.getSuccessKey().equals(status)) {
// prints the error message and return
System.out.println(status);
// return;
}
CaelmirStudyData studyData = new CaelmirStudyData();
// start reading study data from index 1
for (int i = 1; i < jsonArray.length(); i++) {
jobj = (JSONObject) jsonArray.get(i);
studyData = new CaelmirStudyData();
studyData.setDescription(jobj.getString(CaElmirInterfaceManager.getStudyDesrciptionKey()));
studyData.setEmail(jobj.getString(CaElmirInterfaceManager.getEmailKey()));
studyData.setHypothesis(jobj.getString(CaElmirInterfaceManager.getStudyHypothesisKey()));
studyData.setInstitution(jobj.getString(CaElmirInterfaceManager.getInstitutionKey()));
studyData.setInvestigatorName(jobj.getString(CaElmirInterfaceManager.getPrimaryInvestigatorKey()));
studyData.setStudyName(jobj.getString(CaElmirInterfaceManager.getStudyName()));
studyData.setUrl(jobj.getString(CaElmirInterfaceManager.getStudyUrlKey()));
caelmirStudyData.add(studyData);
//log.debug("studyData.toString(): " + studyData.toString());
}
}
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
// Set collection so therapy link will display if caELMIR data is available
// Needed for models with caELMIR data but no caMOD data
theAnimalModel.setCaelmirStudyDataCollection(caelmirStudyData);
request.getSession().setAttribute(Constants.CAELMIR_STUDY_DATA,
caelmirStudyData);
//log.debug("caelmirStudyData.toString(): " + caelmirStudyData.toString());
return mapping.findForward("viewTherapeuticApproaches");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateCellLines(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
setComments(request, Constants.Pages.CELL_LINES);
return mapping.findForward("viewCellLines");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateTransientInterference(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
setComments(request, Constants.Pages.TRANSIENT_INTERFERENCE);
return mapping.findForward("viewTransientInterference");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateImages(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
setComments(request, Constants.Pages.IMAGES);
return mapping.findForward("viewImages");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateMicroarrays(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
setCancerModel(request);
//Get external properties file
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
request.setAttribute("uri_start", camodProperties.getProperty("caarray.uri_start"));
request.setAttribute("uri_end", camodProperties.getProperty("caarray.uri_end"));
setComments(request, Constants.Pages.MICROARRAY);
return mapping.findForward("viewMicroarrays");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateTransplant(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
log.debug("<populateTransplant> Enter:");
setCancerModel(request);
setComments(request, Constants.Pages.TRANSPLANT);
log.debug("<populateTransplant> Exit:");
return mapping.findForward("viewTransplant");
}
/**
* Populate the session and/or request with the objects necessary to display
* the page.
*
* @param mapping
* the struts action mapping
* @param form
* the web form
* @param request
* HTTPRequest
* @param response
* HTTPResponse
* @return
* @throws Exception
*/
public ActionForward populateTransplantDetails(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
log.debug("<populateTransplantDetails> Enter:");
String modelID = request.getParameter("tModelID");
request.getSession().setAttribute(Constants.MODELID, modelID);
String nsc = request.getParameter("nsc");
if (nsc != null && nsc.length() == 0)
return mapping.findForward("viewModelCharacteristics");
log.debug("<populateTransplantDetails> modelID:" + modelID);
log.debug("<populateTransplantDetails> nsc:" + nsc);
TransplantManager mgr = (TransplantManager) getBean("transplantManager");
Transplant t = mgr.get(modelID);
request.getSession().setAttribute(Constants.TRANSPLANTMODEL, t);
request.getSession().setAttribute(Constants.NSC_NUMBER, nsc);
request.getSession().setAttribute(Constants.TRANSPLANTRESULTLIST, t.getInvivoResultCollectionByNSC(nsc));
return mapping.findForward("viewInvivoDetails");
}
}
|
package io.kamax.hboxc.gui.vm.edit;
import io.kamax.hbox.comm.Command;
import io.kamax.hbox.comm.HypervisorTasks;
import io.kamax.hbox.comm.Request;
import io.kamax.hbox.comm.in.MachineIn;
import io.kamax.hbox.comm.out.hypervisor.MachineOut;
import io.kamax.hbox.constant.EntityType;
import io.kamax.hboxc.gui.Gui;
import io.kamax.hboxc.gui._Cancelable;
import io.kamax.hboxc.gui._Saveable;
import io.kamax.hboxc.gui.action.CancelAction;
import io.kamax.hboxc.gui.action.SaveAction;
import io.kamax.hboxc.gui.builder.IconBuilder;
import io.kamax.hboxc.gui.builder.JDialogBuilder;
import io.kamax.hboxc.gui.utils.AxSwingWorker;
import io.kamax.hboxc.gui.worker.receiver._MachineReceiver;
import io.kamax.hboxc.gui.workers.MachineGetWorker;
import io.kamax.hboxc.gui.workers._WorkerTracker;
import io.kamax.tool.logging.Logger;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.miginfocom.swing.MigLayout;
public class VmEditDialog implements _Saveable, _Cancelable, _WorkerTracker {
private final String GENERAL = "General";
private final String SYSTEM = "System";
private final String OUTPUT = "Output";
private final String STORAGE = "Storage";
private final String AUDIO = "Audio";
private final String NETWORK = "Network";
private JDialog mainDialog;
private JProgressBar refreshProgress;
private boolean loadingFailed = false;
private List<SwingWorker<?, ?>> remainingWorkers = new ArrayList<SwingWorker<?, ?>>();
private List<SwingWorker<?, ?>> finishedWorkers = new ArrayList<SwingWorker<?, ?>>();
private JSplitPane split;
private JPanel buttonsPanel;
private JButton saveButton;
private JButton cancelButton;
private JScrollPane leftPane;
private JScrollPane rightPane;
private DefaultListModel listModel;
private JList itemList;
private JPanel sectionPanels;
private CardLayout layout;
private GeneralVmEdit generalEdit;
private SystemVmEdit systemEdit;
private OutputVmEdit outputEdit;
private StorageVmEdit storageEdit;
private AudioVmEdit audioEdit;
private NetworkVmEdit networkEdit;
private MachineIn mIn;
public VmEditDialog() {
generalEdit = new GeneralVmEdit(this);
systemEdit = new SystemVmEdit(this);
outputEdit = new OutputVmEdit(this);
storageEdit = new StorageVmEdit(this);
audioEdit = new AudioVmEdit(this);
networkEdit = new NetworkVmEdit(this);
layout = new CardLayout();
sectionPanels = new JPanel(layout);
sectionPanels.add(generalEdit.getComp(), GENERAL);
sectionPanels.add(systemEdit.getComp(), SYSTEM);
sectionPanels.add(outputEdit.getComp(), OUTPUT);
sectionPanels.add(storageEdit.getComp(), STORAGE);
sectionPanels.add(audioEdit.getComp(), AUDIO);
sectionPanels.add(networkEdit.getComp(), NETWORK);
listModel = new DefaultListModel();
listModel.addElement(GENERAL);
listModel.addElement(SYSTEM);
listModel.addElement(OUTPUT);
listModel.addElement(STORAGE);
listModel.addElement(AUDIO);
listModel.addElement(NETWORK);
itemList = new JList(listModel);
itemList.setCellRenderer(new LabelCellRenderer());
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
itemList.addListSelectionListener(new ListSelect());
if (!listModel.isEmpty()) {
itemList.setSelectedValue(listModel.getElementAt(0), true);
}
leftPane = new JScrollPane(itemList);
leftPane.setMinimumSize(new Dimension(100, 50));
rightPane = new JScrollPane(sectionPanels);
rightPane.setMinimumSize(new Dimension(300, 100));
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
split.setBorder(null);
saveButton = new JButton(new SaveAction(this));
saveButton.setEnabled(false);
cancelButton = new JButton(new CancelAction(this));
refreshProgress = new JProgressBar();
refreshProgress.setVisible(false);
refreshProgress.setStringPainted(true);
buttonsPanel = new JPanel(new MigLayout());
buttonsPanel.add(saveButton);
buttonsPanel.add(cancelButton);
buttonsPanel.add(refreshProgress, "growx,pushx");
mainDialog = JDialogBuilder.get(saveButton);
mainDialog.setIconImage(IconBuilder.getTask(HypervisorTasks.MachineModify).getImage());
mainDialog.setModalityType(ModalityType.DOCUMENT_MODAL);
mainDialog.setSize(1000, 600);
mainDialog.getContentPane().setLayout(new MigLayout());
mainDialog.getContentPane().add(split, "grow,push,wrap");
mainDialog.getContentPane().add(buttonsPanel, "grow x");
}
private void show(MachineOut mOut) {
mIn = new MachineIn(mOut);
MachineGetWorker.execute(this, new MachineReceiver(), mOut);
mainDialog.setTitle(mOut.getName() + " - Settings");
mainDialog.setLocationRelativeTo(mainDialog.getParent());
mainDialog.setVisible(true);
}
public static void edit(MachineOut mOut) {
new VmEditDialog().show(mOut);
}
private void hide() {
itemList.clearSelection();
mainDialog.setVisible(false);
mainDialog.dispose();
mIn = null;
}
@Override
public void save() {
generalEdit.save();
systemEdit.save();
outputEdit.save();
storageEdit.save();
audioEdit.save();
networkEdit.save();
Gui.post(new Request(Command.VBOX, HypervisorTasks.MachineModify, mIn));
hide();
}
@Override
public void cancel() {
hide();
}
private class ListSelect implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent lsEv) {
if (itemList.getSelectedValue() != null) {
layout.show(sectionPanels, itemList.getSelectedValue().toString());
}
}
}
@SuppressWarnings("serial")
private class LabelCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (label.getText() == GENERAL) {
label.setIcon(IconBuilder.getEntityType(EntityType.Machine));
} else if (label.getText() == SYSTEM) {
label.setIcon(IconBuilder.getEntityType(EntityType.CPU));
} else if (label.getText() == OUTPUT) {
label.setIcon(IconBuilder.getEntityType(EntityType.Display));
} else if (label.getText() == STORAGE) {
label.setIcon(IconBuilder.getEntityType(EntityType.HardDisk));
} else if (label.getText() == AUDIO) {
label.setIcon(IconBuilder.getEntityType(EntityType.Audio));
} else if (label.getText() == NETWORK) {
label.setIcon(IconBuilder.getEntityType(EntityType.Network));
} else {
label.setIcon(null);
}
return label;
}
}
private class MachineReceiver implements _MachineReceiver {
@Override
public void loadingStarted() {
saveButton.setEnabled(false);
refreshProgress.setIndeterminate(true);
refreshProgress.setVisible(true);
}
@Override
public void loadingFinished(boolean isFinished, String message) {
refreshProgress.setMinimum(0);
refreshProgress.setMaximum(100);
refreshProgress.setValue(0);
refreshProgress.setIndeterminate(false);
}
@Override
public void put(final MachineOut mOut) {
generalEdit.update(mOut, mIn);
systemEdit.update(mOut, mIn);
outputEdit.update(mOut, mIn);
storageEdit.update(mOut, mIn);
audioEdit.update(mOut, mIn);
networkEdit.update(mOut, mIn);
}
}
private void refreshLoadingStatus() {
int remaining = remainingWorkers.size();
int finished = finishedWorkers.size();
int total = remaining + finished;
refreshProgress.setMinimum(0);
refreshProgress.setMaximum(total);
if (remainingWorkers.isEmpty()) {
finishedWorkers.clear();
refreshProgress.setValue(refreshProgress.getMaximum());
} else {
if (finishedWorkers.isEmpty()) {
refreshProgress.setIndeterminate(true);
} else {
refreshProgress.setValue(finished);
}
}
refreshProgress.setVisible(!remainingWorkers.isEmpty());
saveButton.setEnabled(remainingWorkers.isEmpty() && !loadingFailed);
}
@Override
public AxSwingWorker<?, ?, ?> register(AxSwingWorker<?, ?, ?> worker) {
if (worker.isDone()) {
Logger.debug("Skipping registration of already finished worker: " + worker);
}
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent ev) {
AxSwingWorker<?, ?, ?> worker = AxSwingWorker.class.cast(ev.getSource());
if (worker.hasFailed()) {
loadingFailed = true;
}
if ("state".equals(ev.getPropertyName()) && (SwingWorker.StateValue.DONE == ev.getNewValue())) {
remainingWorkers.remove(ev.getSource());
finishedWorkers.add((SwingWorker<?, ?>) ev.getSource());
refreshLoadingStatus();
}
}
});
remainingWorkers.add(worker);
return worker;
}
}
|
package io.github.Aaron1011.InventoryBomb;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.server.v1_7_R3.EntityTypes;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Wither;
import org.bukkit.entity.Zombie;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.permissions.BroadcastPermissions;
import de.ntcomputer.minecraft.controllablemobs.*;
import de.ntcomputer.minecraft.controllablemobs.api.ControllableMob;
import de.ntcomputer.minecraft.controllablemobs.api.ControllableMobs;
public final class InventoryBomb extends JavaPlugin implements Listener {
HashMap<ItemStack, HashMap<String, Object>> bombs;
ItemStack bombItem = new ItemStack(Material.BLAZE_ROD);
@Override
public void onDisable() {
this.bombs = new HashMap<ItemStack, HashMap<String, Object>>();
}
@Override
public void onEnable() {
this.bombs = new HashMap<ItemStack, HashMap<String, Object>>();
this.getServer().getPluginManager().registerEvents(this, this);
ItemMeta meta = bombItem.getItemMeta();
meta.setDisplayName(ChatColor.RESET + "" + ChatColor.RED + "Bomb!");
this.bombItem.setItemMeta(meta);
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
@Override
public void run() {
HashMap<ItemStack, HashMap<String, Object>> toAdd = new HashMap<ItemStack, HashMap<String, Object>>();
for (Map.Entry<ItemStack, HashMap<String, Object>> entry : bombs.entrySet()) {
HashMap<String, Object> data = entry.getValue();
int time = ((int) data.get("Timer")) - 1;
ItemStack item = entry.getKey();
Bukkit.broadcastMessage("Time: " + time);
data.put("Timer", time);
if (time <= 0) {
Bukkit.broadcastMessage("Boom!");
if (data.containsKey("Owner")) {
Player player = (Player) data.get("Owner");
player.sendMessage("Your bomb blew up!");
player.damage(0.0);
}
if (bombs.containsKey(item)) {
Bukkit.broadcastMessage("Yes!");
}
else {
Bukkit.broadcastMessage("No!");
Bukkit.broadcastMessage(bombs.keySet().toString());
}
bombs.remove(item);
continue;
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.RESET + "" + ChatColor.RED + "Bomb!" + ChatColor.YELLOW + time + ChatColor.RESET + " seconds");
bombs.remove(item);
item.setItemMeta(meta);
toAdd.put(item, data);
}
bombs.putAll(toAdd);
}
}, 0L, 20L);
}
@EventHandler
public void onEntityDeath(EntityDeathEvent event) {
if (event.getEntityType() == EntityType.PLAYER) {
ItemStack item = new ItemStack(bombItem);
ItemMeta meta = item.getItemMeta();
event.getDrops().add(item);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Timer", 5);
meta.setDisplayName(ChatColor.RESET + "" + ChatColor.RED + "Bomb!" + ChatColor.YELLOW + "5" + ChatColor.RESET + " seconds");
item.setItemMeta(meta);
bombs.put(item, map);
Bukkit.broadcastMessage("Hello!");
}
}
@EventHandler
public void onItemPickup(PlayerPickupItemEvent event) {
ItemStack item = event.getItem().getItemStack();
if (bombs.containsKey(item)) {
bombs.get(item).put("Owner", event.getPlayer());
}
}
}
|
package alec_wam.CrystalMod.util;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
public class ProfileUtil {
public static final ConcurrentMap<String, UUID> uuidCache = buildCache(3 * 60 * 60, 1024 * 5);
public static final ConcurrentMap<UUID, String> nameCache = buildCache(3 * 60 * 60, 1024 * 5);
public static <K, V> ConcurrentMap<K, V> buildCache(int seconds, int maxSize) {
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (seconds > 0) {
builder.expireAfterWrite(seconds, TimeUnit.SECONDS);
}
if (maxSize > 0) {
builder.maximumSize(maxSize);
}
return builder.build(new CacheLoader<K, V>() {
@Override
public V load(K key) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
}).asMap();
}
public static String downloadJsonData(String urlLoc){
URL url;
String string = "";
try
{
url = new URL(urlLoc);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
if(connection !=null){
InputStream io = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(io));
String line;
while ((line = bufferedReader.readLine()) != null)
{
if (!line.startsWith("//") && !line.isEmpty())
{
string+=(line);
}
}
bufferedReader.close();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
e.printStackTrace();
}
return string;
}
public static JSONObject getJSONObject(String urlLoc){
final String data = downloadJsonData(urlLoc);
String jsonString = data.replace("[", "").replace("]", "");
try{
return new JSONObject(jsonString);
} catch(JSONException e){
ModLogger.warning(data);
e.printStackTrace();
}
return null;
}
public static UUID getUUID(String username){
if(!uuidCache.containsKey(username)){
UUID uuid = getUnCachedUUID(username);
if(uuid !=null){
uuidCache.put(username, uuid);
}
return uuid;
}
return uuidCache.get(username);
}
public static String getUsername(UUID uuid){
if(!nameCache.containsKey(uuid)){
String name = getUnCachedName(uuid);
if(!name.equalsIgnoreCase(ERROR)){
nameCache.put(uuid, name);
}
return name;
}
return nameCache.get(uuid);
}
private static UUID getUnCachedUUID(String username){
JSONObject jsonResult = getJSONObject(getURL(username, RequestType.NAMETOUUID));
if(jsonResult == null || !jsonResult.has("id"))return null;
Object object = jsonResult.get("id");
if(object == null || !(object instanceof String))return null;
String uuid = jsonResult.getString("id");
if(!Strings.isNullOrEmpty(uuid)){
return UUIDUtils.fromString(uuid);
}
return null;
}
private static String getUnCachedName(UUID uuid){
JSONObject jsonResult = getJSONObject(getURL(UUIDUtils.fromUUID(uuid), RequestType.UUIDTONAME));
if(jsonResult == null || !jsonResult.has("name"))return ERROR;
Object object = jsonResult.get("name");
if(object == null || !(object instanceof String))return ERROR;
String name = jsonResult.getString("name");
if(!Strings.isNullOrEmpty(name)){
return name;
}
return ERROR;
}
public static final String ERROR = "<ERROR>";
protected final static int timeout = 5000;
public static String getURL(String value, RequestType type){
if(type == RequestType.NAMETOUUID){
return String.format("https://api.mojang.com/users/profiles/minecraft/%s", value);
}
return String.format("https://sessionserver.mojang.com/session/minecraft/profile/%s", value);
}
public static enum RequestType{
UUIDTONAME, NAMETOUUID;
}
}
|
package nl.b3p.viewer.stripes;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.geotools.filter.visitor.RemoveDistanceUnit;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.ApplicationLayer;
import nl.b3p.viewer.config.app.ConfiguredAttribute;
import nl.b3p.viewer.config.security.Authorizations;
import nl.b3p.viewer.config.services.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.codehaus.httpcache4j.cache.HTTPCache;
//import org.codehaus.httpcache4j.cache.MemoryCacheStorage;
//import org.codehaus.httpcache4j.client.HTTPClientResponseResolver;
import org.geotools.data.FeatureSource;
import org.geotools.data.Query;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.GeoTools;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.cql2.CQL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/attributes")
@StrictBinding
public class AttributesActionBean implements ActionBean {
private static final Log log = LogFactory.getLog(AttributesActionBean.class);
private static final int MAX_FEATURES = 50;
private ActionBeanContext context;
@Validate
private Application application;
@Validate
private ApplicationLayer appLayer;
private Layer layer = null;
@Validate
private int limit;
@Validate
private int page;
@Validate
private int start;
@Validate
private String dir;
@Validate
private String sort;
@Validate
private boolean arrays;
@Validate
private String filter;
@Validate
private boolean debug;
@Validate
private boolean noCache;
private boolean unauthorized;
//<editor-fold defaultstate="collapsed" desc="getters en setters">
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public ApplicationLayer getAppLayer() {
return appLayer;
}
public void setAppLayer(ApplicationLayer appLayer) {
this.appLayer = appLayer;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public boolean isArrays() {
return arrays;
}
public void setArrays(boolean arrays) {
this.arrays = arrays;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public boolean isNoCache() {
return noCache;
}
public void setNoCache(boolean noCache) {
this.noCache = noCache;
}
//</editor-fold>
@After(stages=LifecycleStage.BindingAndValidation)
public void loadLayer() {
try {
layer = (Layer)Stripersist.getEntityManager().createQuery("from Layer where service = :service and name = :n order by virtual desc")
.setParameter("service", appLayer.getService())
.setParameter("n", appLayer.getLayerName())
.setMaxResults(1)
.getSingleResult();
} catch(NoResultException nre) {
}
}
@Before(stages=LifecycleStage.EventHandling)
public void checkAuthorization() {
if(application == null || appLayer == null
|| !Authorizations.isAppLayerReadAuthorized(application, appLayer, context.getRequest())) {
unauthorized = true;
}
}
public Resolution attributes() throws JSONException {
JSONObject json = new JSONObject();
json.put("success", Boolean.FALSE);
String error = null;
if(appLayer == null) {
error = "Invalid parameters";
} else if(unauthorized) {
error = "Not authorized";
} else {
Map<String,AttributeDescriptor> featureTypeAttributes = new HashMap<String,AttributeDescriptor>();
SimpleFeatureType ft = null;
if(layer != null) {
ft = layer.getFeatureType();
if(ft != null) {
for(AttributeDescriptor ad: ft.getAttributes()) {
featureTypeAttributes.put(ad.getName(), ad);
}
}
}
Integer geometryAttributeIndex = null;
JSONArray attributes = new JSONArray();
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
JSONObject j = ca.toJSONObject();
AttributeDescriptor ad = featureTypeAttributes.get(ca.getAttributeName());
if(ad != null) {
j.put("alias", ad.getAlias());
j.put("type", ad.getType());
if(ft != null && ca.getAttributeName().equals(ft.getGeometryAttribute())) {
geometryAttributeIndex = attributes.length();
}
}
attributes.put(j);
}
if(ft != null) {
json.put("geometryAttribute", ft.getGeometryAttribute());
}
if(geometryAttributeIndex != null) {
json.put("geometryAttributeIndex", geometryAttributeIndex);
}
json.put("attributes", attributes);
json.put("success", Boolean.TRUE);
}
if(error != null) {
json.put("error", error);
}
return new StreamingResolution("application/json", new StringReader(json.toString()));
}
private static final String CACHE_APPLAYER = "total_count_cache_applayer";
private static final String CACHE_FILTER = "total_count_cache_filter";
private static final String CACHE_TIME = "total_count_cache_time";
private static final String CACHE_COUNT = "total_count_cache";
private static final int CACHE_MAX_AGE = 60 * 1000;
/**
* Call this to clear the "total feature count" cached value when a new feature
* is added to a feature source. Only clears the cache for the current session.
*/
public static void clearTotalCountCache(ActionBeanContext context) {
HttpSession sess = context.getRequest().getSession();
sess.removeAttribute(CACHE_APPLAYER);
sess.removeAttribute(CACHE_FILTER);
sess.removeAttribute(CACHE_TIME);
sess.removeAttribute(CACHE_COUNT);
}
private int lookupTotalCountCache(Callable<Integer> countProducer) throws Exception {
HttpSession session = context.getRequest().getSession();
Integer total = null;
Long age = null;
Long cacheAppLayerId = (Long)session.getAttribute(CACHE_APPLAYER);
if(appLayer.getId().equals(cacheAppLayerId)) {
if((filter == null && session.getAttribute(CACHE_FILTER) == null)
|| (filter != null && filter.equals(session.getAttribute(CACHE_FILTER)) )) {
Long time = (Long)session.getAttribute(CACHE_TIME);
if(time != null) {
age = System.currentTimeMillis() - time;
if(age <= CACHE_MAX_AGE) {
total = (Integer)session.getAttribute(CACHE_COUNT);
}
}
}
}
if(total != null) {
log.debug(String.format("Returning cached total count value %d which was cached %s ms ago for app layer id %d",
total,
age,
appLayer.getId()));
return total;
} else {
long startTime = System.currentTimeMillis();
total = countProducer.call();
log.debug(String.format("Caching total count value %d which took %d ms to get for app layer id %d",
total,
System.currentTimeMillis() - startTime,
appLayer.getId()));
// Maybe only cache if getting total took longer than threshold?
// Now a new feature is only counted for all users after CACHE_MAX_AGE
// If clearTotalCountCache() is called then the new feature will be
// counted for the current user/session).
session.setAttribute(CACHE_APPLAYER, appLayer.getId());
session.setAttribute(CACHE_FILTER, filter);
session.setAttribute(CACHE_TIME, System.currentTimeMillis());
session.setAttribute(CACHE_COUNT, total);
return total;
}
}
private List<String> setPropertyNames(Query q) {
List<String> propertyNames = new ArrayList<String>();
boolean haveInvisibleProperties = false;
for(ConfiguredAttribute ca: appLayer.getAttributes()) {
if(ca.isVisible()) {
propertyNames.add(ca.getAttributeName());
} else {
haveInvisibleProperties = true;
}
}
if(haveInvisibleProperties) {
// By default Query retrieves Query.ALL_NAMES
// Query.NO_NAMES is an empty String array
q.setPropertyNames(propertyNames);
}
return propertyNames;
}
private void setSortBy(Query q, List<String> propertyNames) {
FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
if(sort != null) {
String sortAttribute = null;
if(arrays) {
int i = Integer.parseInt(sort.substring(1));
int j = 0;
for(String name: propertyNames) {
if(j == i) {
sortAttribute = name;
}
j++;
}
} else {
sortAttribute = sort;
}
if(sortAttribute != null) {
q.setSortBy(new SortBy[] {
ff2.sort(sortAttribute, "DESC".equals(dir) ? SortOrder.DESCENDING : SortOrder.ASCENDING)
});
}
}
}
private void setFilter(Query q) throws Exception {
if(filter != null && filter.trim().length() > 0) {
Filter f = CQL.toFilter(filter);
f = (Filter)f.accept(new RemoveDistanceUnit(), null);
q.setFilter(f);
}
}
private static final int MAX_CACHE_SIZE = 50;
/*
private static HTTPCache cache;
private static synchronized HTTPCache getHTTPCache() {
if(cache != null) {
if(cache.getStorage().size() > MAX_CACHE_SIZE) {
log.debug("Clearing HTTP cache after reaching max size of " + MAX_CACHE_SIZE);
// XXX No way to remove items according to strategy?
cache.clear();
} else {
if(log.isDebugEnabled()) {
log.debug(String.format("Using HTTP cache; size=%d hits=%d misses=%d hit ratio=%f",
cache.getStorage().size(),
cache.getStatistics().getHits(),
cache.getStatistics().getMisses(),
cache.getStatistics().getHitRatio())
);
}
}
return cache;
}
log.debug("Creating new HTTP cache");
cache = new HTTPCache(
new MemoryCacheStorage(), // XXX unchangeable capacity of 1000 is way too high
// should cache based on body size...
// So clear cache if size exceeds MAX_CACHE_SIZE
HTTPClientResponseResolver.createMultithreadedInstance()
);
return cache;
}
*/
public Resolution store() throws JSONException, Exception {
JSONObject json = new JSONObject();
if(unauthorized) {
json.put("success", false);
json.put("message", "Not authorized");
return new StreamingResolution("application/json", new StringReader(json.toString(4)));
}
JSONArray features = new JSONArray();
json.put("features", features);
try {
int total = 0;
if(layer != null && layer.getFeatureType() != null) {
FeatureSource fs;
if(isDebug() && layer.getFeatureType().getFeatureSource() instanceof WFSFeatureSource) {
Map extraDataStoreParams = new HashMap();
extraDataStoreParams.put(WFSDataStoreFactory.TRY_GZIP.key, Boolean.FALSE);
fs = ((WFSFeatureSource)layer.getFeatureType().getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams);
} /*else if(layer.getFeatureType().getFeatureSource() instanceof ArcGISFeatureSource) {
Map extraDataStoreParams = new HashMap();
if(isDebug()) {
extraDataStoreParams.put(ArcGISDataStoreFactory.TRY_GZIP.key, Boolean.FALSE);
}
if(!isNoCache()) {
extraDataStoreParams.put(ArcGISDataStoreFactory.HTTP_CACHE.key, getHTTPCache());
}
fs = ((ArcGISFeatureSource)layer.getFeatureType().getFeatureSource()).openGeoToolsFeatureSource(layer.getFeatureType(), extraDataStoreParams);
}*/ else {
fs = layer.getFeatureType().openGeoToolsFeatureSource();
}
boolean startIndexSupported = fs.getQueryCapabilities().isOffsetSupported();
final Query q = new Query(fs.getName().toString());
List<String> propertyNames = setPropertyNames(q);
setSortBy(q, propertyNames);
setFilter(q);
final FeatureSource fs2 = fs;
total = lookupTotalCountCache(new Callable<Integer>() {
public Integer call() throws Exception {
return fs2.getCount(q);
}
});
if(total == -1) {
total = MAX_FEATURES;
}
q.setStartIndex(start);
q.setMaxFeatures(Math.min(limit + (startIndexSupported ? 0 : start),MAX_FEATURES));
FeatureCollection fc = fs.getFeatures(q);
FeatureIterator<SimpleFeature> it = fc.features();
try {
while(it.hasNext()) {
SimpleFeature f = it.next();
if(!startIndexSupported && start > 0) {
start
continue;
}
if(arrays) {
JSONObject j = new JSONObject();
int idx = 0;
for(String name: propertyNames) {
Object value = f.getAttribute(name);
j.put("c" + idx++, formatValue(value));
}
features.put(j);
} else {
JSONObject j = new JSONObject();
for(String name: propertyNames) {
j.put(name, formatValue(f.getAttribute(name)));
}
features.put(j);
}
}
} finally {
it.close();
fs.getDataStore().dispose();
}
}
json.put("total", total);
} catch(Exception e) {
log.error("Error loading features", e);
json.put("success", false);
String message = "Fout bij ophalen features: " + e.toString();
Throwable cause = e.getCause();
while(cause != null) {
message += "; " + cause.toString();
cause = cause.getCause();
}
json.put("message", message);
}
return new StreamingResolution("application/json", new StringReader(json.toString(4)));
}
private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private Object formatValue(Object value) {
if(value instanceof Date) {
// JSON has no date type so format the date as it is used for
// display, not calculation
return dateFormat.format((Date)value);
} else {
return value;
}
}
}
|
package org.kitteh.irc.client.library;
import org.kitteh.irc.client.library.element.Actor;
import org.kitteh.irc.client.library.element.User;
import org.kitteh.irc.client.library.event.channel.ChannelCTCPEvent;
import org.kitteh.irc.client.library.event.channel.ChannelInviteEvent;
import org.kitteh.irc.client.library.event.channel.ChannelJoinEvent;
import org.kitteh.irc.client.library.event.channel.ChannelKickEvent;
import org.kitteh.irc.client.library.event.channel.ChannelModeEvent;
import org.kitteh.irc.client.library.event.channel.ChannelNoticeEvent;
import org.kitteh.irc.client.library.event.user.PrivateCTCPReplyEvent;
import org.kitteh.irc.client.library.event.user.PrivateNoticeEvent;
import org.kitteh.irc.client.library.event.user.UserNickChangeEvent;
import org.kitteh.irc.client.library.util.LCSet;
import org.kitteh.irc.client.library.util.Sanity;
import org.kitteh.irc.client.library.element.Channel;
import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent;
import org.kitteh.irc.client.library.event.channel.ChannelPartEvent;
import org.kitteh.irc.client.library.event.channel.ChannelTopicEvent;
import org.kitteh.irc.client.library.event.user.PrivateCTCPQueryEvent;
import org.kitteh.irc.client.library.event.user.PrivateMessageEvent;
import org.kitteh.irc.client.library.event.user.UserQuitEvent;
import org.kitteh.irc.client.library.util.StringUtil;
import java.util.Date;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final class IRCClient implements Client {
private class InputProcessor extends Thread {
private final Queue<String> queue = new ConcurrentLinkedQueue<>();
private InputProcessor() {
this.setName("Kitteh IRC Client Input Processor (" + IRCClient.this.getName() + ")");
this.start();
}
@Override
public void run() {
IRCClient.this.connect();
while (!this.isInterrupted()) {
synchronized (this.queue) {
if (this.queue.isEmpty()) {
try {
this.queue.wait();
} catch (InterruptedException e) {
break;
}
}
}
try {
IRCClient.this.handleLine(this.queue.poll());
} catch (final Throwable thrown) {
// NOOP
}
}
}
private void queue(String message) {
synchronized (this.queue) {
this.queue.add(message);
this.queue.notify();
}
}
}
private enum MessageTarget {
CHANNEL,
PRIVATE,
UNKNOWN
}
private final Config config;
private final InputProcessor processor;
private String goalNick;
private String currentNick;
private String requestedNick;
// RFC 2812 section 1.3 'Channel names are case insensitive.'
private final Set<String> channels = new LCSet();
private AuthType authType;
private String auth;
private String authReclaim;
private NettyManager.ClientConnection connection;
private long lastCheck;
private final EventManager eventManager = new EventManager(this);
private final Listener<Exception> exceptionListener;
private final Listener<String> inputListener;
private final Listener<String> outputListener;
private Map<Character, Character> prefixes = new ConcurrentHashMap<Character, Character>() {
{
put('o', '@');
put('v', '+');
}
};
private static final Pattern PREFIX_PATTERN = Pattern.compile("PREFIX=\\(([a-zA-Z]+)\\)([^ ]+)");
private Map<Character, ChannelModeType> modes = ChannelModeType.getDefaultModes();
private static final Pattern CHANMODES_PATTERN = Pattern.compile("CHANMODES=(([,A-Za-z]+)(,([,A-Za-z]+)){0,3})");
IRCClient(Config config) {
this.config = config;
this.currentNick = this.requestedNick = this.goalNick = this.config.get(Config.NICK);
Config.ExceptionConsumerWrapper exceptionListenerWrapper = this.config.get(Config.LISTENER_EXCEPTION);
this.exceptionListener = new Listener<>(exceptionListenerWrapper == null ? null : exceptionListenerWrapper.getConsumer());
Config.StringConsumerWrapper inputListenerWrapper = this.config.get(Config.LISTENER_INPUT);
this.inputListener = new Listener<>(inputListenerWrapper == null ? null : inputListenerWrapper.getConsumer());
Config.StringConsumerWrapper outputListenerWrapper = this.config.get(Config.LISTENER_OUTPUT);
this.outputListener = new Listener<>(outputListenerWrapper == null ? null : outputListenerWrapper.getConsumer());
this.processor = new InputProcessor();
}
@Override
public void addChannel(String... channels) {
Sanity.nullCheck(channels, "Channels cannot be null");
Sanity.truthiness(channels.length > 0, "Channels cannot be empty array");
for (String channel : channels) {
if (!Channel.isChannel(channel)) {
continue;
}
this.channels.add(channel);
this.sendRawLine("JOIN :" + channel);
}
}
@Override
public EventManager getEventManager() {
return this.eventManager;
}
@Override
public String getIntendedNick() {
return this.goalNick;
}
@Override
public String getName() {
return this.config.get(Config.NAME);
}
@Override
public String getNick() {
return this.currentNick;
}
@Override
public void sendCTCPMessage(String target, String message) {
Sanity.nullCheck(target, "Target cannot be null");
Sanity.nullCheck(message, "Message cannot be null");
Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces");
this.sendRawLine("PRIVMSG " + target + " :" + CTCPUtil.toCTCP(message));
}
@Override
public void sendMessage(String target, String message) {
Sanity.nullCheck(target, "Target cannot be null");
Sanity.nullCheck(message, "Message cannot be null");
Sanity.truthiness(target.indexOf(' ') == -1, "Target cannot have spaces");
this.sendRawLine("PRIVMSG " + target + " :" + message);
}
@Override
public void sendRawLine(String message) {
Sanity.nullCheck(message, "Message cannot be null");
this.connection.sendMessage(message, false);
}
@Override
public void setAuth(AuthType type, String nick, String pass) {
Sanity.nullCheck(type, "Auth type cannot be null");
this.authType = type;
switch (type) {
case GAMESURGE:
this.auth = "PRIVMSG AuthServ@services.gamesurge.net :auth " + nick + " " + pass;
this.authReclaim = "";
break;
case NICKSERV:
default:
this.auth = "PRIVMSG NickServ :identify " + pass;
this.authReclaim = "PRIVMSG NickServ :ghost " + nick + " " + pass;
}
}
@Override
public void setMessageDelay(int delay) {
Sanity.truthiness(delay > -1, "Delay must be a positive value");
this.config.set(Config.MESSAGE_DELAY, delay);
if (this.connection != null) {
this.connection.scheduleSending(delay);
}
}
@Override
public void setNick(String nick) {
Sanity.nullCheck(nick, "Nick cannot be null");
this.goalNick = nick.trim();
this.sendNickChange(this.goalNick);
}
@Override
public void shutdown(String reason) {
this.processor.interrupt();
this.connection.shutdown(reason != null && reason.isEmpty() ? null : reason);
// Shut these down last, so they get any last firings
this.exceptionListener.shutdown();
this.inputListener.shutdown();
this.outputListener.shutdown();
}
/**
* Queue up a line for processing.
*
* @param line line to be processed
*/
void processLine(String line) {
if (line.startsWith("PING ")) {
this.sendPriorityRawLine("PONG " + line.substring(5));
} else {
this.processor.queue(line);
}
}
Config getConfig() {
return this.config;
}
Listener<Exception> getExceptionListener() {
return this.exceptionListener;
}
Listener<String> getInputListener() {
return this.inputListener;
}
Listener<String> getOutputListener() {
return this.outputListener;
}
void connect() {
this.connection = NettyManager.connect(this);
// If the server has a password, send that along first
if (this.config.get(Config.SERVER_PASSWORD) != null) {
this.sendPriorityRawLine("PASS " + this.config.get(Config.SERVER_PASSWORD));
}
// Initial USER and NICK messages. Let's just assume we want +iw (send 8)
this.sendPriorityRawLine("USER " + this.config.get(Config.USER) + " 8 * :" + this.config.get(Config.REAL_NAME));
this.sendNickChange(this.goalNick);
// Figure out auth
if (this.authReclaim != null && !this.currentNick.equals(this.goalNick) && this.authType.isNickOwned()) {
this.sendPriorityRawLine(this.authReclaim);
this.sendNickChange(this.goalNick);
}
if (this.auth != null) {
this.sendPriorityRawLine(this.auth);
}
}
private String handleColon(String string) {
return string.startsWith(":") ? string.substring(1) : string;
}
private void handleLine(String line) throws Throwable {
if ((line == null) || (line.length() == 0)) {
return;
}
final String[] split = line.split(" ");
if ((split.length <= 1) || !split[0].startsWith(":")) {
return; // Invalid!
}
final Actor actor = Actor.getActor(split[0].substring(1));
int numeric = -1;
try {
numeric = Integer.parseInt(split[1]);
} catch (NumberFormatException ignored) {
}
if (numeric > -1) {
switch (numeric) {
case 1: // Welcome
break;
case 2: // Your host is...
break;
case 3: // server created
break;
case 4: // version / modes
// We're in! Start sending all messages.
this.connection.scheduleSending(this.config.get(Config.MESSAGE_DELAY));
break;
case 5:
for (int i = 2; i < split.length; i++) {
Matcher prefixMatcher = PREFIX_PATTERN.matcher(split[i]);
if (prefixMatcher.find()) {
String modes = prefixMatcher.group(1);
String display = prefixMatcher.group(2);
if (modes.length() == display.length()) {
Map<Character, Character> prefixMap = new ConcurrentHashMap<>();
for (int index = 0; index < modes.length(); index++) {
prefixMap.put(modes.charAt(index), display.charAt(index));
}
this.prefixes = prefixMap;
}
continue;
}
Matcher modeMatcher = CHANMODES_PATTERN.matcher(split[i]);
if (modeMatcher.find()) {
String[] modes = modeMatcher.group(1).split(",");
Map<Character, ChannelModeType> modesMap = new ConcurrentHashMap<>();
for (int typeId = 0; typeId < modes.length; typeId++) {
for (char mode : modes[typeId].toCharArray()) {
ChannelModeType type = null;
switch (typeId) {
case 0:
type = ChannelModeType.A_MASK;
break;
case 1:
type = ChannelModeType.B_PARAMETER_ALWAYS;
break;
case 2:
type = ChannelModeType.C_PARAMETER_ON_SET;
break;
case 3:
type = ChannelModeType.D_PARAMETER_NEVER;
}
modesMap.put(mode, type);
}
}
this.modes = modesMap;
}
}
break;
case 250: // Highest connection count
case 251: // There are X users
case 252: // X IRC OPs
case 253: // X unknown connections
case 254: // X channels formed
case 255: // X clients, X servers
case 265: // Local users, max
case 266: // global users, max
case 372: // info, such as continued motd
case 375: // motd start
case 376: // motd end
break;
// Channel info
case 332: // Channel topic
case 333: // Topic set by
case 353: // Channel users list (/names). format is 353 nick = #channel :names
case 366: // End of /names
case 422: // MOTD missing
break;
// Nick errors, try for new nick below
case 431: // No nick given
case 432: // Erroneous nickname
case 433: // Nick in use
this.sendNickChange(this.requestedNick + '`');
break;
}
} else {
final Command command = Command.getByName(split[1]);
if (command == null) {
return; // Unknown command
}
// CTCP
if ((command == Command.NOTICE || command == Command.PRIVMSG) && CTCPUtil.isCTCP(this.handleColon(StringUtil.combineSplit(split, 3)))) {
final String ctcpMessage = CTCPUtil.fromCTCP(this.handleColon(StringUtil.combineSplit(split, 3)));
switch (command) {
case NOTICE:
if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE) {
this.eventManager.callEvent(new PrivateCTCPReplyEvent(actor, ctcpMessage));
}
break;
case PRIVMSG:
switch (this.getTypeByTarget(split[2])) {
case PRIVATE:
String reply = null; // Message to send as CTCP reply (NOTICE). Send nothing if null.
if (ctcpMessage.equals("VERSION")) {
reply = "VERSION I am Kitteh!";
} else if (ctcpMessage.equals("TIME")) {
reply = "TIME " + new Date().toString();
} else if (ctcpMessage.equals("FINGER")) {
reply = "FINGER om nom nom tasty finger";
} else if (ctcpMessage.startsWith("PING ")) {
reply = ctcpMessage;
}
PrivateCTCPQueryEvent event = new PrivateCTCPQueryEvent(actor, ctcpMessage, reply);
this.eventManager.callEvent(event);
reply = event.getReply();
if (reply != null) {
this.sendRawLine("NOTICE " + actor.getName() + " :" + CTCPUtil.toCTCP(reply));
}
break;
case CHANNEL:
this.eventManager.callEvent(new ChannelCTCPEvent(actor, (Channel) Actor.getActor(split[2]), ctcpMessage));
break;
}
break;
}
return; // If handled as CTCP we don't care about further handling.
}
switch (command) {
case NOTICE:
final String noticeMessage = this.handleColon(StringUtil.combineSplit(split, 3));
switch (this.getTypeByTarget(split[2])) {
case CHANNEL:
this.eventManager.callEvent(new ChannelNoticeEvent(actor, (Channel) Actor.getActor(split[2]), noticeMessage));
break;
case PRIVATE:
this.eventManager.callEvent(new PrivateNoticeEvent(actor, noticeMessage));
break;
}
break;
case PRIVMSG:
final String message = this.handleColon(StringUtil.combineSplit(split, 3));
switch (this.getTypeByTarget(split[2])) {
case CHANNEL:
this.eventManager.callEvent(new ChannelMessageEvent(actor, (Channel) Actor.getActor(split[2]), message));
break;
case PRIVATE:
this.eventManager.callEvent(new PrivateMessageEvent(actor, message));
break;
}
break;
case MODE:
if (this.getTypeByTarget(split[2]) == MessageTarget.CHANNEL) {
Channel channel = (Channel) Actor.getActor(split[2]);
String modechanges = split[3];
int currentArg = 4;
boolean add;
switch (modechanges.charAt(0)) {
case '+':
add = true;
break;
case '-':
add = false;
break;
default:
return;
}
for (int i = 1; i < modechanges.length() && currentArg < split.length; i++) {
char next = modechanges.charAt(i);
if (next == '+') {
add = true;
} else if (next == '-') {
add = false;
} else {
boolean hasArg;
if (this.prefixes.containsKey(next)) {
hasArg = true;
} else {
ChannelModeType type = this.modes.get(next);
if (type == null) {
// TODO clean up error handling
return;
}
hasArg = (add && type.isParameterRequiredOnSetting()) || (!add && type.isParameterRequiredOnRemoval());
}
this.eventManager.callEvent(new ChannelModeEvent(actor, channel, add, next, hasArg ? split[currentArg++] : null));
}
}
}
break;
case JOIN:
if (actor instanceof User) { // Just in case
this.eventManager.callEvent(new ChannelJoinEvent((Channel) Actor.getActor(split[2]), (User) actor));
}
break;
case PART:
if (actor instanceof User) { // Just in case
this.eventManager.callEvent(new ChannelPartEvent((Channel) Actor.getActor(split[2]), (User) actor, split.length > 2 ? this.handleColon(StringUtil.combineSplit(split, 3)) : ""));
}
break;
case QUIT:
if (actor instanceof User) { // Just in case
this.eventManager.callEvent(new UserQuitEvent((User) actor, split.length > 1 ? this.handleColon(StringUtil.combineSplit(split, 2)) : ""));
}
break;
case KICK:
this.eventManager.callEvent(new ChannelKickEvent((Channel) Actor.getActor(split[2]), actor, split[3], this.handleColon(StringUtil.combineSplit(split, 4))));
break;
case NICK:
if (actor instanceof User) {
User user = (User) actor;
if (user.getNick().equals(this.currentNick)) {
this.currentNick = split[2];
}
this.eventManager.callEvent(new UserNickChangeEvent(user, split[2]));
}
break;
case INVITE:
if (this.getTypeByTarget(split[2]) == MessageTarget.PRIVATE && this.channels.contains(split[3])) {
this.sendRawLine("JOIN " + split[3]);
}
this.eventManager.callEvent(new ChannelInviteEvent((Channel) Actor.getActor(split[3]), actor, split[2]));
break;
case TOPIC:
this.eventManager.callEvent(new ChannelTopicEvent(actor, (Channel) Actor.getActor(split[2]), this.handleColon(StringUtil.combineSplit(split, 3))));
break;
default:
// TODO: Unknown event?
break;
}
}
}
private MessageTarget getTypeByTarget(String target) {
if (this.currentNick.equalsIgnoreCase(target)) {
return MessageTarget.PRIVATE;
}
if (this.channels.contains(target)) {
return MessageTarget.CHANNEL;
}
return MessageTarget.UNKNOWN;
}
private void sendNickChange(String newnick) {
this.requestedNick = newnick;
this.sendPriorityRawLine("NICK " + newnick);
}
private void sendPriorityRawLine(String message) {
this.connection.sendMessage(message, true);
}
}
|
package at.ac.ait.ubicity.rss.impl;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom2.Element;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.xml.sax.InputSource;
import at.ac.ait.ubicity.contracts.rss.RssDTO;
import com.rometools.rome.feed.synd.SyndCategory;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
public class RssParser {
final static Logger logger = Logger.getLogger(RssParser.class);
private final URL url;
public RssParser(String urlString, String lastGuid)
throws MalformedURLException {
this.url = new URL(urlString);
}
public List<RssDTO> fetchUpdates() throws Exception {
List<RssDTO> list = new ArrayList<RssDTO>();
try {
InputSource is = new InputSource(url.openStream());
SyndFeed feed = new SyndFeedInput().build(is);
for (SyndEntry e : feed.getEntries()) {
RssDTO dto = new RssDTO();
dto.setId(e.getUri());
dto.setTitle(e.getTitle());
if (e.getDescription() != null) {
dto.setText(Jsoup.clean(e.getDescription().getValue(),
Whitelist.simpleText()));
}
dto.setSource(e.getLink());
dto.setPublishedAt(e.getPublishedDate());
dto.setAuthor(e.getAuthor());
List<String> cats = new ArrayList<String>();
for (SyndCategory cat : e.getCategories()) {
if (cat != null) {
cats.add(cat.getName());
}
}
dto.setCategories(cats);
dto.setLang(readForeignMarkup(e.getForeignMarkup(),
ForeignRssTag.LANG));
String geo = readForeignMarkup(e.getForeignMarkup(),
ForeignRssTag.GEO_POINT);
if (geo != null) {
String[] geoAr = geo.split(" ");
if (geoAr.length == 2) {
dto.setGeoRssPoint(Float.parseFloat(geoAr[1]),
Float.parseFloat(geoAr[0]));
}
}
list.add(dto);
}
} catch (Exception e) {
logger.warn("Exc caught while loading entries", e);
}
logger.info(list.size() + " new RSS Entries read from "
+ this.url.toString());
return list;
}
private String readForeignMarkup(List<Element> list, ForeignRssTag tag) {
for (Element e : list) {
if (tag.getName().equalsIgnoreCase(e.getName())) {
return e.getContent(0).getValue();
}
}
return null;
}
}
|
package boilerplate.common;
import java.util.Arrays;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;
public class ForgeEventHandler
{
@SubscribeEvent
public void tickPlayer(PlayerTickEvent event)
{
if (event.side.isClient() && (Boilerplate.instance.trailParticles > 0))
{
World world = event.player.worldObj;
EntityPlayer player = event.player;
if(player.isAirBorne)
{
if (Arrays.asList(Boilerplate.donors).contains(player.getCommandSenderName()))
{
for (int i = 0; i < Boilerplate.instance.trailParticles; i++)
world.spawnParticle("iconcrack_" + Item.getIdFromItem(Items.gold_ingot), (player.posX + world.rand.nextDouble()) - 0.7D,
(player.posY + world.rand.nextDouble()) - 2.2D, (player.posZ + world.rand.nextDouble()) - 0.7D, -player.motionX,
-player.motionY, -player.motionZ);
}
/* else */if (Arrays.asList(Boilerplate.devs).contains(player.getCommandSenderName()))
{
for (int i = 0; i < Boilerplate.instance.trailParticles; i++)
world.spawnParticle("flame", (player.posX + world.rand.nextDouble()) - 0.7D, (player.posY + world.rand.nextDouble()) - 3.2D,
(player.posZ + world.rand.nextDouble()) - 0.7D, -player.motionX, -player.motionY, -player.motionZ);
}
}
}
}
}
|
package br.com.caelum.brutal.dao;
import static org.hibernate.criterion.Order.desc;
import static org.hibernate.criterion.Projections.rowCount;
import static org.hibernate.criterion.Restrictions.and;
import static org.hibernate.criterion.Restrictions.eq;
import static org.hibernate.criterion.Restrictions.gt;
import static org.hibernate.criterion.Restrictions.isNull;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import br.com.caelum.brutal.dao.WithUserPaginatedDAO.OrderType;
import br.com.caelum.brutal.dao.WithUserPaginatedDAO.UserRole;
import br.com.caelum.brutal.model.Question;
import br.com.caelum.brutal.model.Tag;
import br.com.caelum.brutal.model.User;
import br.com.caelum.brutal.model.interfaces.RssContent;
import br.com.caelum.vraptor.ioc.Component;
@Component
@SuppressWarnings("unchecked")
public class QuestionDAO implements PaginatableDAO {
private static final Integer PAGE_SIZE = 35;
public static final long SPAM_BOUNDARY = -5;
private final Session session;
private final WithUserPaginatedDAO<Question> withAuthor;
private final InvisibleForUsersRule invisible;
public QuestionDAO(Session session, InvisibleForUsersRule invisible) {
this.session = session;
this.invisible = invisible;
this.withAuthor = new WithUserPaginatedDAO<Question>(session, Question.class, UserRole.AUTHOR, invisible);
}
public void save(Question q) {
session.save(q);
}
public Question getById(Long questionId) {
return (Question) session.load(Question.class, questionId);
}
public List<Question> allVisible(Integer page) {
Criteria criteria = session.createCriteria(Question.class, "q")
.createAlias("q.information", "qi")
.createAlias("q.author", "qa")
.createAlias("q.lastTouchedBy", "ql")
.createAlias("q.solution", "s", Criteria.LEFT_JOIN)
.createAlias("q.solution.information", "si", Criteria.LEFT_JOIN)
.add(criterionSpamFilter())
.addOrder(desc("q.lastUpdatedAt"))
.setFirstResult(firstResultOf(page))
.setMaxResults(PAGE_SIZE);
return addInvisibleFilter(criteria).list();
}
public List<Question> unsolvedVisible(Integer page) {
Criteria criteria = session.createCriteria(Question.class, "q")
.add(Restrictions.and(criterionSpamFilter(), isNull("q.solution")))
.addOrder(Order.desc("q.lastUpdatedAt"))
.setMaxResults(PAGE_SIZE)
.setFirstResult(firstResultOf(page))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return addInvisibleFilter(criteria).list();
}
public List<Question> unanswered(Integer page) {
Criteria criteria = session.createCriteria(Question.class, "q")
.add(Restrictions.eq("q.answerCount", 0l))
.addOrder(Order.desc("q.lastUpdatedAt"))
.setMaxResults(PAGE_SIZE)
.setFirstResult(firstResultOf(page))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return addInvisibleFilter(criteria).list();
}
public Question load(Question question) {
return getById(question.getId());
}
public List<Question> withTagVisible(Tag tag, Integer page) {
Criteria criteria = session.createCriteria(Question.class, "q")
.createAlias("q.information.tags", "t")
.add(Restrictions.eq("t.id", tag.getId()))
.addOrder(Order.desc("q.lastUpdatedAt"))
.setFirstResult(firstResultOf(page))
.setMaxResults(50)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return addInvisibleFilter(criteria).list();
}
public List<Question> postsToPaginateBy(User user, OrderType orderByWhat, Integer page) {
return withAuthor.by(user,orderByWhat, page);
}
public List<RssContent> orderedByCreationDate(int maxResults) {
return session.createCriteria(Question.class, "q")
.add(Restrictions.eq("q.moderationOptions.invisible", false))
.addOrder(Order.desc("q.createdAt"))
.setMaxResults(maxResults)
.list();
}
public List<RssContent> orderedByCreationDate(int maxResults, Tag tag) {
return session.createCriteria(Question.class, "q")
.createAlias("q.information.tags", "tags")
.add(Restrictions.and(Restrictions.eq("q.moderationOptions.invisible", false), Restrictions.eq("tags.id", tag.getId())))
.addOrder(Order.desc("q.createdAt"))
.setMaxResults(maxResults)
.list();
}
public List<Question> getRelatedTo(Question question) {
return session.createCriteria(Question.class, "q")
.createAlias("q.information.tags", "tags")
.add(Restrictions.eq("tags.id", question.getMostImportantTag().getId()))
.addOrder(Order.desc("q.createdAt"))
.setMaxResults(5)
.list();
}
public List<Question> hot(DateTime since, int count) {
return session.createCriteria(Question.class, "q")
.add(gt("q.createdAt", since))
.addOrder(Order.desc("q.voteCount"))
.setMaxResults(count)
.list();
}
public List<Question> randomUnanswered(DateTime after, DateTime before, int count) {
return session.createCriteria(Question.class, "q")
.add(and(isNull("q.solution"), Restrictions.between("q.createdAt", after, before)))
.add(Restrictions.sqlRestriction("1=1 order by rand()"))
.setMaxResults(count)
.list();
}
public Long countWithAuthor(User user) {
return withAuthor.count(user);
}
public Long numberOfPagesTo(User user) {
return withAuthor.numberOfPagesTo(user);
}
public long numberOfPages() {
Criteria criteria = session.createCriteria(Question.class, "q")
.add(criterionSpamFilter())
.setProjection(rowCount());
Long totalItems = (Long) addInvisibleFilter(criteria).list().get(0);
return calculatePages(totalItems);
}
public long numberOfPages(Tag tag) {
Criteria criteria = session.createCriteria(Question.class, "q")
.createAlias("q.information", "qi")
.createAlias("qi.tags", "t")
.add(criterionSpamFilter())
.add(eq("t.id", tag.getId()))
.setProjection(rowCount());
Long totalItems = (Long) addInvisibleFilter(criteria).list().get(0);
return calculatePages(totalItems);
}
public Long totalPagesUnsolvedVisible() {
Criteria criteria = session.createCriteria(Question.class, "q")
.add(isNull("q.solution"))
.setProjection(rowCount());
Long result = (Long) addInvisibleFilter(criteria).list().get(0);
return calculatePages(result);
}
public Long totalPagesWithoutAnswers() {
Criteria criteria = session.createCriteria(Question.class, "q")
.add(Restrictions.eq("q.answerCount", 0l))
.setProjection(rowCount());
Long result = (Long) addInvisibleFilter(criteria).list().get(0);
return calculatePages(result);
}
private int firstResultOf(Integer page) {
return PAGE_SIZE * (page-1);
}
private long calculatePages(Long count) {
long result = count/PAGE_SIZE.longValue();
if (count % PAGE_SIZE.longValue() != 0) {
result++;
}
return result;
}
private Criterion criterionSpamFilter() {
return Restrictions.gt("q.voteCount", SPAM_BOUNDARY);
}
private Criteria addInvisibleFilter(Criteria criteria) {
return invisible.addFilter("q", criteria);
}
}
|
package com.splicemachine.constants.bytes;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import com.carrotsearch.hppc.BitSet;
/**
*
* This class encapsulates byte[] manipulation with the IR applications. It relies heavily on HBase's Bytes class.
*
* @author John Leach
* @version %I%, %G%
*
* @see org.apache.hadoop.hbase.util.Bytes
*
*/
public class BytesUtil {
/**
* Concats a list of byte[].
*
* @param list
* @return the result byte array
*/
public static byte[] concat(List<byte[]> list) {
int length = 0;
for (byte[] bytes : list) {
length += bytes.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] bytes : list) {
System.arraycopy(bytes, 0, result, pos, bytes.length);
pos += bytes.length;
}
return result;
}
/**
*
* Increments a byte[]
*
* @param array
* @param index
*/
public static void unsignedIncrement(byte[] array,int index){
if(array.length<=0) return; //nothing to do
if(index<0){
/*
* looks like the array is something like [0xFF,0xFF,0xFF,...].
*
* In normal circumstances, we could increment this via rolling bytes over--
* e.g. the array becomes [1,0,0,0,...] which has 1 more byte to the left
* than the input array.
*
* However, our comparators will sort going from left to right, which means that
* rolling over like that will actually place the increment BEFORE the array, instead
* of after it like it should. As this violates sort-order restrictions, we are forced
* to explode here
*/
throw new AssertionError("Unable to increment byte[] "+ Arrays.toString(array) +", incrementing would violate sort order");
}
int value = array[index] & 0xff;
if(value==255){
array[index]=0;
//we've looped past the entry, so increment the next byte in the array
unsignedIncrement(array, index-1);
}else {
array[index]++;
}
}
public static void unsignedDecrement(byte[] array, int index){
if(index<0){
throw new AssertionError("Unable to decrement "+ Arrays.toString(array)+", as it would violate sort-order");
}
if(array[index]==0){
array[index] = (byte)0xff;
unsignedDecrement(array,index-1);
}else
array[index]
}
public static String debug(Object o) {
byte[] bytes = (byte[]) o;
String s = "" + bytes.length + "[";
for (int i=0; i<bytes.length; i++) {
// represent as hex for unsigned byte
s += " " + Integer.toHexString(bytes[i] & 0xFF);
}
s += " ]";
return s;
}
public static byte[] concatenate(byte headerByte,byte[] ... bytes){
int length = 2;
for(byte[] bytes1:bytes){
length+=bytes1.length;
}
byte[] concatenatedBytes = new byte[length+bytes.length-1];
concatenatedBytes[0] = headerByte;
concatenatedBytes[1] = 0x00;
copyInto(bytes,concatenatedBytes,2);
return concatenatedBytes;
}
public static byte[] concatenate(byte[] ... bytes){
int length = 0;
for(byte[] bytes1:bytes){
length+=bytes1.length;
}
byte[] concatenatedBytes = new byte[length+bytes.length-1];
copyInto(bytes,concatenatedBytes);
return concatenatedBytes;
}
public static byte[] concatenate(byte[][] bytes,int size){
byte[] concatedBytes;
if(bytes.length>1)
concatedBytes = new byte[size+bytes.length-1];
else
concatedBytes = new byte[size];
copyInto(bytes, concatedBytes);
return concatedBytes;
}
private static void copyInto(byte[][] bytes, byte[] concatedBytes,int initialPos){
int offset = initialPos;
boolean isStart=true;
for(byte[] nextBytes:bytes){
if(nextBytes==null) break;
if(!isStart){
concatedBytes[offset] = 0x00; //safe because we know that it's never used in our encoding
offset++;
}else
isStart = false;
System.arraycopy(nextBytes, 0, concatedBytes, offset, nextBytes.length);
offset+=nextBytes.length;
}
}
private static void copyInto(byte[][] bytes, byte[] concatedBytes) {
copyInto(bytes,concatedBytes,0);
}
/**
* Lexicographical byte[] comparator that places empty byte[] values before non-empty values.
*/
public static Comparator<byte[]> startComparator = new Comparator<byte[]>() {
@Override
public int compare(byte[] o1, byte[] o2) {
return compareBytes(false, o1, o2);
}
};
/**
* Lexicographical byte[] comparator that places empty byte[] values after non-empty values.
*/
public static Comparator<byte[]> endComparator = new Comparator<byte[]>() {
@Override
public int compare(byte[] o1, byte[] o2) {
return compareBytes(true, o1, o2);
}
};
/**
* Parameterized lexicographical byte[] comparison.
*
* @param emptyGreater indicates whether empty byte[] are greater or less than non-empty values.
*/
private static int compareBytes(boolean emptyGreater, byte[] x, byte[] y) {
if (empty(x)) {
if (empty(y)) {
return 0;
} else {
return emptyGreater ? 1 : -1;
}
} else if (empty(y)) {
return emptyGreater ? -1 : 1;
} else {
return Bytes.compareTo(x, y);
}
}
/**
* @return whether or not the given byte[] is empty
*/
private static boolean empty(byte[] x) {
return Bytes.compareTo(x, HConstants.EMPTY_BYTE_ARRAY) == 0;
}
/**
* @return a [start, end) pair identifying the ranges of values that are in both [start1, end1) and [start2, end2)
* under lexicographic sorting of values.
*/
public static Pair<byte[], byte[]> intersect(byte[] start1, byte[] end1, byte[] start2, byte[] end2) {
if (overlap(start1, end1, start2, end2)) {
return Pair.newPair(
max(startComparator, start1, start2),
min(endComparator, end1, end2));
} else {
return null;
}
}
/**
* @return whether [start1, end1) and [start2, end2) share any values
*/
private static boolean overlap(byte[] start1, byte[] end1, byte[] start2, byte[] end2) {
return startLessThanEnd(start1, end2) && startLessThanEnd(start2, end1);
}
/**
* @return whether the given start range value is less than the end range value considering lexicographical ordering
* and treating empty byte[] as -infinity in starting positions and infinity in ending positions
*/
private static boolean startLessThanEnd(byte[] start1, byte[] end2) {
return (empty(end2) || empty(start1) || Bytes.compareTo(start1, end2) < 0);
}
/**
* @return the value that sorts lowest.
*/
private static byte[] min(Comparator<byte[]> comparator, byte[] x, byte[] y) {
return (comparator.compare(y, x) <= 0) ? y : x;
}
/**
* @return the value that sorts highest.
*/
private static byte[] max(Comparator<byte[]> comparator, byte[] x, byte[] y) {
return (comparator.compare(x, y) <= 0) ? y : x;
}
private static final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String toHex(byte[] bytes) {
if(bytes==null || bytes.length<=0) return "";
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static String toHex(ByteBuffer bytes) {
if(bytes==null || bytes.remaining()<=0) return "";
byte[] bits = new byte[bytes.remaining()];
bytes.get(bits);
return toHex(bits);
}
public static void main(String... args) throws Exception{
byte[][] vals = new byte[3][];
vals[0] = new byte[]{0,1};
vals[1] = new byte[]{2,3};
vals[2] = new byte[]{4,5};
System.out.println(Arrays.toString(concatenate(vals,6)));
}
public static byte[] unsignedCopyAndIncrement(byte[] start) {
byte[] next = new byte[start.length];
System.arraycopy(start,0,next,0,next.length);
unsignedIncrement(next,next.length-1);
return next;
}
public static void intToBytes(int value,byte[] data,int offset) {
data[offset] = (byte)(value >>> 24);
data[offset+1] = (byte)(value >>> 16);
data[offset+2] = (byte)(value >>> 8);
data[offset+3] = (byte)(value);
}
public static int bytesToInt(byte[] data, int offset) {
int value = 0;
value |= (data[offset] & 0xff)<<24;
value |= (data[offset+1] & 0xff)<<16;
value |= (data[offset+2] & 0xff)<< 8;
value |= (data[offset+3] & 0xff);
return value;
}
public static byte[] toByteArray(BitSet bits) {
byte[] bytes = new byte[ (int) ((bits.length()+7)/8+4)];
intToBytes((int)(bits.length()+7)/8,bytes,0);
for (int i=0; i<bits.length(); i++) {
if (bits.get(i)) {
bytes[(bytes.length-4)-i/8-1+4] |= 1<<(i%8);
}
}
return bytes;
}
public static Pair<BitSet,Integer> fromByteArray(byte[] data, int offset){
int numBytes = bytesToInt(data,offset);
BitSet bitSet = new BitSet();
int currentPos=0;
for(int i=numBytes+offset+4-1;i>=offset+4;i
byte byt = data[i];
//a 1 in the position indicates the field is set
for(int pos=0;pos<8;pos++){
if((byt & (1<<pos))>0)
bitSet.set(currentPos);
currentPos++;
}
}
return Pair.newPair(bitSet,offset+numBytes+4);
}
public static byte[] slice(byte[] data, int offset, int length) {
byte[] slice = new byte[length];
System.arraycopy(data,offset,slice,0,length);
return slice;
}
}
|
package org.lightmare.scannotation;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.annotation.Annotation;
import org.apache.log4j.Logger;
import org.lightmare.utils.AbstractIOUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.StringUtils;
import org.scannotation.archiveiterator.Filter;
import org.scannotation.archiveiterator.IteratorFactory;
import org.scannotation.archiveiterator.StreamIterator;
/**
* Extension of {@link org.scannotation.AnnotationDB} for saving Map<
* {@link String}, {@link URL}> of class name and {@link URL} for its archive
*
* @author levan
*
*/
public class AnnotationDB extends org.scannotation.AnnotationDB {
private static final long serialVersionUID = 1L;
// To store which class in which URL is found
protected Map<String, URL> classOwnersURLs = new HashMap<String, URL>();
// To store which class in which File is found
protected Map<String, String> classOwnersFiles = new HashMap<String, String>();
private static final char FILE_EXTEWNTION_SELIM = '.';
private static final char FILE_SEPARATOR_CHAR = '/';
private static final Logger LOG = Logger.getLogger(AnnotationDB.class);
private String getFileName(URL url) {
String fileName = url.getFile();
int lastIndex = fileName.lastIndexOf(AbstractIOUtils.FILE_SEPARATOR);
if (lastIndex > -1) {
++lastIndex;
fileName = fileName.substring(lastIndex);
}
return fileName;
}
private boolean ignoreScan(String intf) {
String value;
for (String ignored : ignoredPackages) {
value = StringUtils.concat(ignored, FILE_EXTEWNTION_SELIM);
if (intf.startsWith(value)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
protected void populate(Annotation[] annotations, String className, URL url) {
if (ObjectUtils.notNull(annotations)) {
Set<String> classAnnotations = classIndex.get(className);
String fileName;
for (Annotation ann : annotations) {
Set<String> classes = annotationIndex.get(ann.getTypeName());
if (classes == null) {
classes = new HashSet<String>();
annotationIndex.put(ann.getTypeName(), classes);
}
classes.add(className);
if (!classOwnersURLs.containsKey(className)) {
classOwnersURLs.put(className, url);
}
if (!classOwnersFiles.containsKey(className)) {
fileName = getFileName(url);
classOwnersFiles.put(className, fileName);
}
classAnnotations.add(ann.getTypeName());
}
}
}
protected void scanClass(ClassFile cf, URL url) {
String className = cf.getName();
AnnotationsAttribute visible = (AnnotationsAttribute) cf
.getAttribute(AnnotationsAttribute.visibleTag);
AnnotationsAttribute invisible = (AnnotationsAttribute) cf
.getAttribute(AnnotationsAttribute.invisibleTag);
if (ObjectUtils.notNull(visible)) {
populate(visible.getAnnotations(), className, url);
}
if (ObjectUtils.notNull(invisible)) {
populate(invisible.getAnnotations(), className, url);
}
}
public void scanClass(InputStream bits, URL url) throws IOException {
DataInputStream dstream = new DataInputStream(new BufferedInputStream(
bits));
ClassFile cf = null;
try {
cf = new ClassFile(dstream);
classIndex.put(cf.getName(), new HashSet<String>());
if (scanClassAnnotations) {
scanClass(cf, url);
}
if (scanMethodAnnotations || scanParameterAnnotations) {
scanMethods(cf);
}
if (scanFieldAnnotations) {
scanFields(cf);
}
// create an index of interfaces the class implements
if (ObjectUtils.notNull(cf.getInterfaces())) {
Set<String> intfs = new HashSet<String>();
for (String intf : cf.getInterfaces()) {
intfs.add(intf);
}
implementsIndex.put(cf.getName(), intfs);
}
} finally {
dstream.close();
bits.close();
}
}
@Override
public void scanArchives(URL... urls) throws IOException {
LOG.info("Started scanning for archives on @Stateless annotation");
for (URL url : urls) {
Filter filter = new Filter() {
public boolean accepts(String subFileName) {
if (subFileName.endsWith(AbstractIOUtils.CLASS_FILE_EXT)) {
if (subFileName
.startsWith(AbstractIOUtils.FILE_SEPARATOR)) {
subFileName = subFileName.substring(1);
}
if (!ignoreScan(subFileName.replace(
FILE_SEPARATOR_CHAR, FILE_EXTEWNTION_SELIM))) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
};
LOG.info(String.format("Scanning URL %s ", url));
StreamIterator it = IteratorFactory.create(url, filter);
InputStream stream;
while (ObjectUtils.notNull((stream = it.next()))) {
scanClass(stream, url);
}
LOG.info(String.format("Finished URL %s scanning", url));
}
LOG.info("Finished scanning for archives on @Stateless annotation");
}
public Map<String, URL> getClassOwnersURLs() {
return classOwnersURLs;
}
public Map<String, String> getClassOwnersFiles() {
return classOwnersFiles;
}
}
|
package br.com.caelum.tubaina;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.log4j.Logger;
import br.com.caelum.tubaina.builder.BookBuilder;
import br.com.caelum.tubaina.parser.html.desktop.Generator;
import br.com.caelum.tubaina.resources.ResourceLocator;
public class TubainaBuilder {
public static final File DEFAULT_TEMPLATE_DIR = new File("templates");
public static final Logger LOG = Logger.getLogger(TubainaBuilder.class);
private static Integer codeLength = 93; // believe us... this is what
// fits in Latex A4 templates.
private static Integer maximumImageWidth = 175;
private File inputDir = new File(".");
private File outputDir = new File(".");
private String bookName = "book";
private final ParseType parseType;
private boolean dontCare = false;
private TubainaBuilderData data = new TubainaBuilderData(false, DEFAULT_TEMPLATE_DIR, false,
false, "book");
public TubainaBuilder(ParseType type) {
this.parseType = type;
}
public void build() throws IOException {
List<AfcFile> introductionAfcFiles = new ArrayList<AfcFile>();
ResourceLocator.initialize(inputDir);
List<AfcFile> afcFiles = getAfcsFrom(inputDir);
File introductionChapterDirs = new File(inputDir, "introduction");
if (introductionChapterDirs.exists()) {
introductionAfcFiles = getAfcsFrom(introductionChapterDirs);
}
BookBuilder builder = new BookBuilder(bookName);
builder.addAllReaders(afcFiles, introductionAfcFiles);
Book b = null;
try {
b = builder.build(data.isShowNotes());
} catch (TubainaException e) {
if (dontCare) {
LOG.warn(e);
} else {
throw e;
}
}
GeneratorFactory generatorFactory = new GeneratorFactory();
Generator generator = generatorFactory.generatorFor(parseType, data);
File file = new File(outputDir, parseType.getType());
FileUtils.forceMkdir(file);
File bibliographyFile = new File(inputDir, "bib.xml");
if (bibliographyFile.exists()) {
FileUtils.copyFileToDirectory(bibliographyFile, file);
}
try {
generator.generate(b, file);
} catch (TubainaException e) {
LOG.warn(e.getMessage());
}
}
static List<AfcFile> getAfcsFrom(final File file) throws UnsupportedEncodingException,
FileNotFoundException {
List<AfcFile> afcFiles = new ArrayList<AfcFile>();
List<String> files = new ArrayList<String>();
Collections.addAll(files, file.list(new SuffixFileFilter(".afc")));
Collections.sort(files);
for (String fileName : files) {
InputStreamReader reader = new InputStreamReader(new BOMInputStream(new FileInputStream(new File(file, fileName))), "UTF-8");
afcFiles.add(new AfcFile(reader, fileName));
}
return afcFiles;
}
public TubainaBuilder inputDir(File inputDir) {
this.inputDir = inputDir;
return this;
}
public TubainaBuilder outputDir(File outputDir) {
this.outputDir = outputDir;
return this;
}
public TubainaBuilder strictXhtml() {
this.data.setStrictXhtml(true);
return this;
}
public TubainaBuilder templateDir(File templateDir) {
this.data.setTemplateDir(templateDir);
return this;
}
public TubainaBuilder showNotes() {
this.data.setShowNotes(true);
return this;
}
public TubainaBuilder dontCare() {
this.dontCare = true;
return this;
}
public TubainaBuilder noAnswer() {
this.data.setNoAnswer(true);
return this;
}
public TubainaBuilder outputFileName(String fileName) {
this.data.setOutputFileName(fileName);
return this;
}
public TubainaBuilder bookName(String bookName) {
this.bookName = bookName;
return this;
}
public TubainaBuilder codeLength(Integer length) {
codeLength = length;
return this;
}
public TubainaBuilder maximumImageWidth(Integer width) {
maximumImageWidth = width;
return this;
}
public TubainaBuilder withIfdefs(List<String> ifdefs) {
this.data.setIfdefs(ifdefs);
return this;
}
public static Integer getCodeLength() {
return codeLength;
}
public static Integer getMaximumWidth() {
return maximumImageWidth;
}
public void withLinkParameter(String linkParameter) {
this.data.setLinkParameter(linkParameter);
}
}
|
package org.numenta.nupic.examples.qt;
import gnu.trove.list.array.TIntArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.numenta.nupic.ComputeCycle;
import org.numenta.nupic.Connections;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.algorithms.CLAClassifier;
import org.numenta.nupic.algorithms.SpatialPooler;
import org.numenta.nupic.algorithms.TemporalMemory;
//import org.numenta.nupic.algorithms.ClassifierResult;
import org.numenta.nupic.encoders.ScalarEncoder;
import org.numenta.nupic.model.Cell;
import org.numenta.nupic.util.ArrayUtils;
public class QuickTest {
static boolean isResetting = true;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Parameters params = getParameters();
System.out.println(params);
// Toggle this to switch between resetting on every week start day
isResetting = true;
//Layer components
ScalarEncoder.Builder dayBuilder =
ScalarEncoder.builder()
.n(12)
.w(3)
.radius(1.0)
.minVal(1.0)
.maxVal(8)
.periodic(true)
.forced(true)
.resolution(1);
ScalarEncoder encoder = dayBuilder.build();
SpatialPooler sp = new SpatialPooler();
TemporalMemory tm = new TemporalMemory();
CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0);
Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier);
for(double i = 0, x = 0, j = 0;j < 1500;j = (i == 6 ? j + 1: j), i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length
if (i == 0 && isResetting) {
System.out.println("reset:");
tm.reset(layer.getMemory());
}
// For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number)
runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x);
}
}
public static Parameters getParameters() {
Parameters parameters = Parameters.getAllDefaultParameters();
parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 12 });
parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 });
parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6);
//SpatialPooler specific
parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);
parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);
parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false);
parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0);
parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0);
parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0);
parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005);
parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015);
parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);
parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10);
parameters.setParameterByKey(KEY.MAX_BOOST, 10.0);
parameters.setParameterByKey(KEY.SEED, 42);
parameters.setParameterByKey(KEY.SP_VERBOSITY, 0);
//Temporal Memory specific
parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2);
parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8);
parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5);
parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6);
parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.1);//0.05
parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.1);//0.05
parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4);
return parameters;
}
public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) {
l.input(input, recordNum, sequenceNum);
}
public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
Layer<Double> l = new LayerImpl(p, e, s, t, c);
return l;
}
////////////////// Preliminary Network API Toy ///////////////////
interface Layer<T> {
public void input(T value, int recordNum, int iteration);
public int[] getPredicted();
public Connections getMemory();
public int[] getActual();
}
/**
* I'm going to make an actual Layer, this is just temporary so I can
* work out the details while I'm completing this for Peter
*
* @author David Ray
*
*/
static class LayerImpl implements Layer<Double> {
private Parameters params;
private Connections memory = new Connections();
private ScalarEncoder encoder;
private SpatialPooler spatialPooler;
private TemporalMemory temporalMemory;
// private CLAClassifier classifier;
private Map<String, Object> classification = new LinkedHashMap<String, Object>();
private int columnCount;
private int cellsPerColumn;
// private int theNum;
private int[] predictedColumns;
private int[] actual;
private int[] lastPredicted;
public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
this.params = p;
this.encoder = e;
this.spatialPooler = s;
this.temporalMemory = t;
// this.classifier = c;
params.apply(memory);
spatialPooler.init(memory);
temporalMemory.init(memory);
columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index
cellsPerColumn = memory.getCellsPerColumn();
}
public String stringValue(Double valueIndex) {
String recordOut = "";
BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN);
switch(bdValue.intValue()) {
case 1: recordOut = "Monday (1)";break;
case 2: recordOut = "Tuesday (2)";break;
case 3: recordOut = "Wednesday (3)";break;
case 4: recordOut = "Thursday (4)";break;
case 5: recordOut = "Friday (5)";break;
case 6: recordOut = "Saturday (6)";break;
case 7: recordOut = "Sunday (7)";break;
}
return recordOut;
}
@Override
public void input(Double value, int recordNum, int sequenceNum) {
// String recordOut = stringValue(value);
if(value.intValue() == 1) {
// theNum++;
System.out.println("
// System.out.println("Iteration: " + theNum);
}
int[] output = new int[columnCount];
//Input through encoder
// System.out.println("ScalarEncoder Input = " + value);
int[] encoding = encoder.encode(value);
// System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding));
int bucketIdx = encoder.getBucketIndices(value)[0];
//Input through spatial pooler
spatialPooler.compute(memory, encoding, output, true, true);
// System.out.println("SpatialPooler Output = " + Arrays.toString(output));
// Let the SpatialPooler train independently (warm up) first
// if(theNum < 200) return;
//Input through temporal memory
int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1);
ComputeCycle cc = temporalMemory.compute(memory, input, true);
lastPredicted = predictedColumns;
predictedColumns = getSDR(cc.predictiveCells()); //Get the predicted column indexes
// int[] activeColumns = getSDR(cc.activeCells()); //Get the active columns for classifier input
// System.out.println("TemporalMemory Input = " + Arrays.toString(input));
// System.out.println("TemporalMemory Prediction = " + Arrays.toString(predictedColumns));
classification.put("bucketIdx", bucketIdx);
classification.put("actValue", value);
// ClassifierResult<Double> result = classifier.compute(recordNum, classification, activeColumns, true, true);
// System.out.print("CLAClassifier prediction = " + stringValue(result.getMostProbableValue(1)));
// System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n");
// System.out.println("");
}
public int[] inflateSDR(int[] SDR, int len) {
int[] retVal = new int[len];
for(int i : SDR) {
retVal[i] = 1;
}
return retVal;
}
public int[] getSDR(Set<Cell> cells) {
int[] retVal = new int[cells.size()];
int i = 0;
for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) {
retVal[i] = it.next().getIndex();
retVal[i] /= cellsPerColumn; // Get the column index
}
Arrays.sort(retVal);
retVal = ArrayUtils.unique(retVal);
return retVal;
}
/**
* Returns the next predicted value.
*
* @return the SDR representing the prediction
*/
@Override
public int[] getPredicted() {
return lastPredicted;
}
/**
* Returns the actual columns in time t + 1 to compare
* with {@link #getPrediction()} which returns the prediction
* at time t for time t + 1.
* @return
*/
@Override
public int[] getActual() {
return actual;
}
/**
* Simple getter for external reset
* @return
*/
public Connections getMemory() {
return memory;
}
}
}
|
import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.config.ServerConfig;
import com.avaje.ebean.config.dbplatform.H2Platform;
import com.avaje.ebean.config.dbplatform.PostgresPlatform;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.ddl.DdlGenerator;
import controllers.ApplicationController;
import models.User;
import play.*;
import play.libs.F;
import play.libs.Yaml;
import play.mvc.*;
import play.mvc.Http.*;
import java.util.*;
import static play.mvc.Results.internalServerError;
public class Global extends GlobalSettings {
private static final boolean LOAD_TEST_DATA = true;
@Override
public void onStart(Application app) {
if(LOAD_TEST_DATA && !isJUnitTest()) {
cleanDatabase();
fillDatabase("testFiles/placeholder-data.yml");
Logger.info("test data loaded");
}
}
@Override
public F.Promise<Result> onBadRequest(RequestHeader request, String error) {
return F.Promise.<Result>pure(ApplicationController.errorBadRequest(error));
}
@Override
public F.Promise<Result> onHandlerNotFound(RequestHeader request) {
return F.Promise.<Result>pure(ApplicationController.errorNotFound("Die Seite '" + request.path() + "' wurde nicht gefunden."));
}
@Override
public F.Promise<Result> onError(RequestHeader request, Throwable t) {
Logger.error(t.toString());
return F.Promise.<Result>pure(internalServerError(
views.html.error.render(500,t.toString())
));
}
private void cleanDatabase(){
EbeanServer server = Ebean.getServer("default");
ServerConfig config = new ServerConfig();
DdlGenerator ddl = new DdlGenerator();
String databaseType = Play.application().configuration().getString("databaseType");
if(databaseType.equals("postgres")) {
ddl.setup((SpiEbeanServer) server, new PostgresPlatform(), config);
} else {
ddl.setup((SpiEbeanServer) server, new H2Platform(), config);
}
ddl.runScript(false, ddl.generateDropDdl());
ddl.runScript(false, ddl.generateCreateDdl());
assert User.find.all().size() == 0;
}
private void fillDatabase(String yamlFile) {
Object yam = Yaml.load(yamlFile);
if(yam instanceof ArrayList) {
Ebean.save((List) yam);
} else {
Map<String,List<Object>> yamMap = (Map) yam;
for(String s: yamMap.keySet()){
Ebean.save(yamMap.get(s));
}
}
}
private boolean isJUnitTest() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
List<StackTraceElement> list = Arrays.asList(stackTrace);
for (StackTraceElement element : list) {
if (element.getClassName().startsWith("org.junit.")) {
return true;
}
}
return false;
}
}
|
package br.uff.ic.provviewer.GUI;
import br.uff.ic.graphmatching.Matcher;
import br.uff.ic.utility.graph.Edge;
import static br.uff.ic.provviewer.GUI.GuiFunctions.PanCameraToFirstVertex;
import br.uff.ic.provviewer.GraphFrame;
import br.uff.ic.utility.IO.UnityReader;
import br.uff.ic.provviewer.Variables;
import br.uff.ic.utility.AttributeErrorMargin;
import br.uff.ic.utility.IO.InputReader;
import br.uff.ic.utility.IO.PROVNReader;
import br.uff.ic.utility.graph.Vertex;
import edu.uci.ics.jung.graph.DirectedGraph;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.apache.commons.io.FilenameUtils;
/**
* Class to read the graph and config files from the GUI button (File open)
* @author Kohwalter
*/
public class GuiReadFile {
static double similarityThreshold = 0.9;
static double defaultErrorMargin = 0.9;
/**
* Method to read the graph from the XML file
* @param graphFile is the XML file with the graph information
* @return
*/
public static DirectedGraph<Object, Edge> getGraph(File graphFile) {
DirectedGraph<Object, Edge> g = new DirectedSparseMultigraph<Object, Edge>();
try {
String extension = FilenameUtils.getExtension(graphFile.toPath().toString());
InputReader fileReader;
if(extension.equalsIgnoreCase("xml"))
fileReader = new UnityReader(graphFile);
else
fileReader = new PROVNReader(graphFile);
fileReader.readFile();
for (Edge edge : fileReader.getEdges()) {
g.addEdge(edge, edge.getSource(), edge.getTarget());
}
} catch (URISyntaxException ex) {
Logger.getLogger(GraphFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GraphFrame.class.getName()).log(Level.SEVERE, null, ex);
}
return g;
}
/**
* Method to read the XML configuration file
* @param variables
* @param fileChooser is the file chooser from the interface
* @param graphFrame is the tool's main frame
*/
public static void openConfigFile(Variables variables, JFileChooser fileChooser, JFrame graphFrame) {
int returnVal = fileChooser.showOpenDialog(graphFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
variables.config.Initialize(file);
variables.initConfig = true;
} else {
System.out.println("File access cancelled by user.");
}
}
private static void loadGraph(Variables variables, DirectedGraph<Object, Edge> openGraph) {
variables.graph = openGraph;
variables.collapsedGraph = variables.graph;
variables.collapser.Filters(variables);
variables.view.repaint();
variables.initialGraph = false;
}
/**
* Method to open the XML graph file
* @param variables
* @param fileChooser is the file chooser from the interface
* @param graphFrame is the tool's main frame
* @param Layouts is the tool's layout selection field
*/
public static void openGraphFile(Variables variables, JFileChooser fileChooser, JFrame graphFrame, JComboBox Layouts) {
if (variables.initConfig) {
int returnVal = fileChooser.showOpenDialog(graphFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
loadGraph(variables, GuiReadFile.getGraph(fileChooser.getSelectedFile()));
GuiInitialization.NormalizeTime(variables);
// variables.file = fileChooser.getSelectedFile();
// variables.graph = GuiReadFile.getGraph(variables.file);
// variables.collapsedGraph = variables.graph;
// variables.collapser.Filters(variables);
// variables.view.repaint();
// variables.initialGraph = false;
} else {
System.out.println("File access cancelled by user.");
}
GuiBackground.InitBackground(variables, Layouts);
GraphFrame.FilterList.setSelectedIndex(0);
PanCameraToFirstVertex(variables);
}
}
public static void MergeGraph(Variables variables, JFileChooser fileChooser, JFrame graphFrame, JComboBox Layouts) {
int returnVal = fileChooser.showOpenDialog(graphFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
DirectedGraph<Object, Edge> fileGraph = GuiReadFile.getGraph(fileChooser.getSelectedFile());
Map<String, AttributeErrorMargin> restrictionList = defaultRestriction();
Matcher merger = new Matcher();
DirectedGraph<Object, Edge> mergedGraph = merger.Matching(variables.graph, fileGraph, restrictionList, similarityThreshold, defaultErrorMargin);
loadGraph(variables, mergedGraph);
} else {
System.out.println("File access cancelled by user.");
}
GuiBackground.InitBackground(variables, Layouts);
GraphFrame.FilterList.setSelectedIndex(0);
PanCameraToFirstVertex(variables);
}
private static Map<String, AttributeErrorMargin> defaultRestriction(){
Map<String, AttributeErrorMargin> restrictionList = new HashMap<String, AttributeErrorMargin>();
AttributeErrorMargin epsilon;
epsilon = new AttributeErrorMargin("ObjectPosition_X", "0.5");
restrictionList.put("ObjectPosition_X", epsilon);
epsilon = new AttributeErrorMargin("ObjectPosition_Y", "0.25");
restrictionList.put("ObjectPosition_Y", epsilon);
epsilon = new AttributeErrorMargin("ObjectPosition_Z", "0.5");
restrictionList.put("ObjectPosition_Z", epsilon);
return restrictionList;
}
}
|
package org.numenta.nupic.examples.qt;
import gnu.trove.list.array.TIntArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.numenta.nupic.Connections;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.algorithms.CLAClassifier;
//import org.numenta.nupic.algorithms.ClassifierResult;
import org.numenta.nupic.encoders.ScalarEncoder;
import org.numenta.nupic.model.Cell;
import org.numenta.nupic.research.ComputeCycle;
import org.numenta.nupic.research.SpatialPooler;
import org.numenta.nupic.research.TemporalMemory;
import org.numenta.nupic.util.ArrayUtils;
public class QuickTest {
static boolean isResetting = true;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Parameters params = getParameters();
System.out.println(params);
// Toggle this to switch between resetting on every week start day
isResetting = true;
//Layer components
ScalarEncoder.Builder dayBuilder =
ScalarEncoder.builder()
.n(8)
.w(3)
.radius(1.0)
.minVal(1.0)
.maxVal(8)
.periodic(true)
.forced(true)
.resolution(1);
ScalarEncoder encoder = dayBuilder.build();
SpatialPooler sp = new SpatialPooler();
TemporalMemory tm = new TemporalMemory();
CLAClassifier classifier = new CLAClassifier(new TIntArrayList(new int[] { 1 }), 0.1, 0.3, 0);
Layer<Double> layer = getLayer(params, encoder, sp, tm, classifier);
for(double i = 0, x = 0;x < 10000;i = (i == 6 ? 0 : i + 1), x++) { // USE "X" here to control run length
if (i == 0 && isResetting) tm.reset(layer.getMemory());
// For 3rd argument: Use "i" for record num if re-cycling records (isResetting == true) - otherwise use "x" (the sequence number)
runThroughLayer(layer, i + 1, isResetting ? (int)i : (int)x, (int)x);
}
}
public static Parameters getParameters() {
Parameters parameters = Parameters.getAllDefaultParameters();
parameters.setParameterByKey(KEY.INPUT_DIMENSIONS, new int[] { 8 });
parameters.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 20 });
parameters.setParameterByKey(KEY.CELLS_PER_COLUMN, 6);
//SpatialPooler specific
parameters.setParameterByKey(KEY.POTENTIAL_RADIUS, 12);
parameters.setParameterByKey(KEY.POTENTIAL_PCT, 0.5);
parameters.setParameterByKey(KEY.GLOBAL_INHIBITIONS, false);
parameters.setParameterByKey(KEY.LOCAL_AREA_DENSITY, -1.0);
parameters.setParameterByKey(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 5.0);
parameters.setParameterByKey(KEY.STIMULUS_THRESHOLD, 1.0);
parameters.setParameterByKey(KEY.SYN_PERM_INACTIVE_DEC, 0.0005);
parameters.setParameterByKey(KEY.SYN_PERM_ACTIVE_INC, 0.0015);
parameters.setParameterByKey(KEY.SYN_PERM_TRIM_THRESHOLD, 0.05);
parameters.setParameterByKey(KEY.SYN_PERM_CONNECTED, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_OVERLAP_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.MIN_PCT_ACTIVE_DUTY_CYCLE, 0.1);
parameters.setParameterByKey(KEY.DUTY_CYCLE_PERIOD, 10);
parameters.setParameterByKey(KEY.MAX_BOOST, 10.0);
parameters.setParameterByKey(KEY.SEED, 42);
parameters.setParameterByKey(KEY.SP_VERBOSITY, 0);
//Temporal Memory specific
parameters.setParameterByKey(KEY.INITIAL_PERMANENCE, 0.2);
parameters.setParameterByKey(KEY.CONNECTED_PERMANENCE, 0.8);
parameters.setParameterByKey(KEY.MIN_THRESHOLD, 5);
parameters.setParameterByKey(KEY.MAX_NEW_SYNAPSE_COUNT, 6);
parameters.setParameterByKey(KEY.PERMANENCE_INCREMENT, 0.05);
parameters.setParameterByKey(KEY.PERMANENCE_DECREMENT, 0.05);
parameters.setParameterByKey(KEY.ACTIVATION_THRESHOLD, 4);
return parameters;
}
public static <T> void runThroughLayer(Layer<T> l, T input, int recordNum, int sequenceNum) {
l.input(input, recordNum, sequenceNum);
}
public static Layer<Double> getLayer(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
Layer<Double> l = new LayerImpl(p, e, s, t, c);
return l;
}
////////////////// Preliminary Network API Toy ///////////////////
interface Layer<T> {
public void input(T value, int recordNum, int iteration);
public int[] getPredicted();
public Connections getMemory();
public int[] getActual();
}
/**
* I'm going to make an actual Layer, this is just temporary so I can
* work out the details while I'm completing this for Peter
*
* @author David Ray
*
*/
static class LayerImpl implements Layer<Double> {
private Parameters params;
private Connections memory = new Connections();
private ScalarEncoder encoder;
private SpatialPooler spatialPooler;
private TemporalMemory temporalMemory;
// private CLAClassifier classifier;
private Map<String, Object> classification = new LinkedHashMap<String, Object>();
private int columnCount;
private int cellsPerColumn;
// private int theNum;
private int[] predictedColumns;
private int[] actual;
private int[] lastPredicted;
public LayerImpl(Parameters p, ScalarEncoder e, SpatialPooler s, TemporalMemory t, CLAClassifier c) {
this.params = p;
this.encoder = e;
this.spatialPooler = s;
this.temporalMemory = t;
// this.classifier = c;
params.apply(memory);
spatialPooler.init(memory);
temporalMemory.init(memory);
columnCount = memory.getPotentialPools().getMaxIndex() + 1; //If necessary, flatten multi-dimensional index
cellsPerColumn = memory.getCellsPerColumn();
}
@Override
public void input(Double value, int recordNum, int sequenceNum) {
// String recordOut = "";
// switch(value.intValue()) {
// case 1: recordOut = "Monday (1)";break;
// case 2: recordOut = "Tuesday (2)";break;
// case 3: recordOut = "Wednesday (3)";break;
// case 4: recordOut = "Thursday (4)";break;
// case 5: recordOut = "Friday (5)";break;
// case 6: recordOut = "Saturday (6)";break;
// case 7: recordOut = "Sunday (7)";break;
if(value.intValue() == 1) {
// theNum++;
// System.out.println("Iteration: " + theNum);
}
int[] output = new int[columnCount];
//Input through encoder
// System.out.println("ScalarEncoder Input = " + value);
int[] encoding = encoder.encode(value);
// System.out.println("ScalarEncoder Output = " + Arrays.toString(encoding));
int bucketIdx = encoder.getBucketIndices(value)[0];
//Input through spatial pooler
spatialPooler.compute(memory, encoding, output, true, true);
// System.out.println("SpatialPooler Output = " + Arrays.toString(output));
//Input through temporal memory
int[] input = actual = ArrayUtils.where(output, ArrayUtils.WHERE_1);
ComputeCycle cc = temporalMemory.compute(memory, input, true);
lastPredicted = predictedColumns;
predictedColumns = getSDR(cc.predictiveCells()); //Get the active column indexes
// System.out.println("TemporalMemory Input = " + Arrays.toString(input));
// System.out.print("TemporalMemory Prediction = " + Arrays.toString(predictedColumns));
classification.put("bucketIdx", bucketIdx);
classification.put("actValue", value);
// ClassifierResult<Double> result = classifier.compute(recordNum, classification, predictedColumns, true, true);
// System.out.println(" | CLAClassifier 1 step prob = " + Arrays.toString(result.getStats(1)) + "\n");
// System.out.println("");
}
public int[] inflateSDR(int[] SDR, int len) {
int[] retVal = new int[len];
for(int i : SDR) {
retVal[i] = 1;
}
return retVal;
}
public int[] getSDR(Set<Cell> cells) {
int[] retVal = new int[cells.size()];
int i = 0;
for(Iterator<Cell> it = cells.iterator();i < retVal.length;i++) {
retVal[i] = it.next().getIndex();
retVal[i] /= cellsPerColumn; // Get the column index
}
Arrays.sort(retVal);
retVal = ArrayUtils.unique(retVal);
return retVal;
}
/**
* Returns the next predicted value.
*
* @return the SDR representing the prediction
*/
@Override
public int[] getPredicted() {
return lastPredicted;
}
/**
* Returns the actual columns in time t + 1 to compare
* with {@link #getPrediction()} which returns the prediction
* at time t for time t + 1.
* @return
*/
@Override
public int[] getActual() {
return actual;
}
/**
* Simple getter for external reset
* @return
*/
public Connections getMemory() {
return memory;
}
}
}
|
import play.Application;
import play.GlobalSettings;
import play.libs.Akka;
import play.utils.crud.CRUDManager;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Global extends GlobalSettings {
private CRUDManager manager;
@Override
public <A> A getControllerInstance(Class<A> type) throws Exception {
A crudController = manager.getController(type);
if (crudController != null)
return crudController;
return super.getControllerInstance(type);
}
@Override
public void onStart(Application app) {
// Magic goes here
FiniteDuration delay = FiniteDuration.create(0, TimeUnit.SECONDS);
FiniteDuration frequency = FiniteDuration.create(20, TimeUnit.SECONDS);
Runnable showTime = cronProcess();
Akka.system()
.scheduler()
.schedule(delay, frequency, showTime,
Akka.system().dispatcher());
super.onStart(app);
manager = new CRUDManager(this);
manager.initialize(app);
}
private Runnable cronProcess() {
Runnable getPage = new Runnable() {
@Override
public void run() {
Document doc;
for (int cnt = 1; cnt < 2; cnt++) {
String url = "http://the-tale.org/game/map/places/"+cnt;
try {
doc = Jsoup.parse(Jsoup.connect(url).get().toString(), "UTF-8");
String description = doc.select("meta[name=description]").get(0).attr("content");
System.out.println("Meta description : " + description);
//System.out.println(size);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
};
return getPage;
}
}
|
package org.dellroad.stuff.schema;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.sql.DataSource;
/**
* Concrete extension of {@link AbstractSchemaUpdater} for SQL databases.
*
* <p>
* Required properties are the {@linkplain #setDatabaseInitialization database initialization},
* {@linkplain #setUpdateTableInitialization update table initialization}, and the {@linkplain #setUpdates updates} themselves.
* </p>
*
* <p>
* Applied updates are recorded in a special <i>update table</i>, which contains two columns: one for the unique
* {@linkplain SchemaUpdate#getName update name} and one for a timestamp. The update table and column names
* are configurable via {@link #setUpdateTableName setUpdateTableName()},
* {@link #setUpdateTableNameColumn setUpdateTableNameColumn()}, and {@link #setUpdateTableTimeColumn setUpdateTableTimeColumn()}.
* </p>
*
* <p>
* By default, this class detects a completely uninitialized database by the absence of the update table itself
* in the schema (see {@link #databaseNeedsInitialization databaseNeedsInitialization()}).
* When an uninitialized database is encountered, the configured {@linkplain #setDatabaseInitialization database initialization}
* and {@linkplain #setUpdateTableInitialization update table initialization} actions are applied first to initialize
* the database schema.
* </p>
*/
public class SQLSchemaUpdater extends AbstractSchemaUpdater<DataSource, Connection> {
/**
* Default nefault name of the table that tracks schema updates, <code>{@value}</code>.
*/
public static final String DEFAULT_UPDATE_TABLE_NAME = "SchemaUpdate";
/**
* Default name of the column in the updates table holding the unique update name, <code>{@value}</code>.
*/
public static final String DEFAULT_UPDATE_TABLE_NAME_COLUMN = "updateName";
/**
* Default name of the column in the updates table holding the update's time applied, <code>{@value}</code>.
*/
public static final String DEFAULT_UPDATE_TABLE_TIME_COLUMN = "updateTime";
private String updateTableName = DEFAULT_UPDATE_TABLE_NAME;
private String updateTableNameColumn = DEFAULT_UPDATE_TABLE_NAME_COLUMN;
private String updateTableTimeColumn = DEFAULT_UPDATE_TABLE_TIME_COLUMN;
private SQLCommandList databaseInitialization;
private SQLCommandList updateTableInitialization;
/**
* Get the name of the table that keeps track of applied updates.
*
* @see #setUpdateTableName setUpdateTableName()
*/
public String getUpdateTableName() {
return this.updateTableName;
}
/**
* Set the name of the table that keeps track of applied updates.
* Default value is {@link #DEFAULT_UPDATE_TABLE_NAME}.
*
* <p>
* This name must be consistent with the {@linkplain #setUpdateTableInitialization update table initialization}.
*/
public void setUpdateTableName(String updateTableName) {
this.updateTableName = updateTableName;
}
/**
* Get the name of the update name column in the table that keeps track of applied updates.
*
* @see #setUpdateTableNameColumn setUpdateTableNameColumn()
*/
public String getUpdateTableNameColumn() {
return this.updateTableNameColumn;
}
/**
* Set the name of the update name column in the table that keeps track of applied updates.
* Default value is {@link #DEFAULT_UPDATE_TABLE_NAME_COLUMN}.
*
* <p>
* This name must be consistent with the {@linkplain #setUpdateTableInitialization update table initialization}.
*/
public void setUpdateTableNameColumn(String updateTableNameColumn) {
this.updateTableNameColumn = updateTableNameColumn;
}
/**
* Get the name of the update timestamp column in the table that keeps track of applied updates.
*
* @see #setUpdateTableTimeColumn setUpdateTableTimeColumn()
*/
public String getUpdateTableTimeColumn() {
return this.updateTableTimeColumn;
}
/**
* Set the name of the update timestamp column in the table that keeps track of applied updates.
* Default value is {@link #DEFAULT_UPDATE_TABLE_TIME_COLUMN}.
*
* <p>
* This name must be consistent with the {@linkplain #setUpdateTableInitialization update table initialization}.
*/
public void setUpdateTableTimeColumn(String updateTableTimeColumn) {
this.updateTableTimeColumn = updateTableTimeColumn;
}
/**
* Get the update table initialization.
*
* @see #setUpdateTableInitialization setUpdateTableInitialization()
*/
public SQLCommandList getUpdateTableInitialization() {
return this.updateTableInitialization;
}
/**
* Configure how the update table itself gets initialized. This update is run when no update table found,
* which (we assume) implies an empty database with no tables or content. This is a required property.
*
* <p>
* This initialization should create the update table where the name column is the primary key.
* The name column must have a length limit greater than or equal to the longest schema update name.
*
* <p>
* The table and column names must be consistent with the values configured via
* {@link #setUpdateTableName setUpdateTableName()}, {@link #setUpdateTableNameColumn setUpdateTableNameColumn()},
* and {@link #setUpdateTableTimeColumn setUpdateTableTimeColumn()}.
*
* <p>
* For convenience, pre-defined initialization scripts using the default table and column names are available
* at the following resource locations. These can be used to configure a {@link SQLCommandList}:
* <table border="1" cellspacing="0" cellpadding="4">
* <tr>
* <th>Database</th>
* <th>Resource</th>
* </tr>
* <tr>
* </tr>
* <td>MySQL (InnoDB)</td>
* <td><code>classpath:org/dellroad/stuff/schema/updateTable-mysql.sql</code></td>
* </tr>
* </table>
*
* @param updateTableInitialization update table schema initialization
* @see #setUpdateTableName setUpdateTableName()
* @see #setUpdateTableNameColumn setUpdateTableNameColumn()
* @see #setUpdateTableTimeColumn setUpdateTableTimeColumn()
*/
public void setUpdateTableInitialization(SQLCommandList updateTableInitialization) {
this.updateTableInitialization = updateTableInitialization;
}
/**
* Get the empty database initialization.
*
* @see #setDatabaseInitialization setDatabaseInitialization()
*/
public SQLCommandList getDatabaseInitialization() {
return this.databaseInitialization;
}
/**
* Configure how an empty database gets initialized. This is a required property.
*
* <p>
* This update is run when no update table found, which (we assume) implies an empty database with no tables or content.
* Typically this contains the SQL script that gets automatically generated by your favorite schema generation tool.
*
* <p>
* This script is expected to initialize the database schema (i.e., creating all the tables) so that
* when completed the database is "up to date" with respect to the configured schema updates.
* That is, when this action completes, we assume all updates have already been (implicitly) applied
* (and they will be recorded as such).
*
* <p>
* Note this script is <i>not</i> expected to create the update table that tracks schema updates;
* that function is handled by the {@linkplain #setUpdateTableInitialization update table initialization}.
*
* @param databaseInitialization application database schema initialization
*/
public void setDatabaseInitialization(SQLCommandList databaseInitialization) {
this.databaseInitialization = databaseInitialization;
}
@Override
protected void apply(Connection c, DatabaseAction<Connection> action) throws SQLException {
try {
super.apply(c, action);
} catch (SQLException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public synchronized void initializeAndUpdateDatabase(DataSource dataSource) throws SQLException {
try {
super.initializeAndUpdateDatabase(dataSource);
} catch (SQLException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Begin a transaction on the given connection.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} creates a serializable-level transaction.
*
* @param dataSource the database on which to open the transaction
* @return new {@link Connection} with an open transaction
* @throws SQLException if an error occurs while accessing the database
*/
@Override
protected Connection openTransaction(DataSource dataSource) throws SQLException {
Connection c = dataSource.getConnection();
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
c.setAutoCommit(false);
return c;
}
/**
* Commit a previously opened transaction.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} just invokes {@link Connection#commit}.
*
* @param c the connection on which to commit the transaction
* @throws SQLException if an error occurs while accessing the database
*/
@Override
protected void commitTransaction(Connection c) throws SQLException {
c.commit();
c.close();
}
/**
* Roll back a previously opened transaction.
* This method will also be invoked if {@link #commitTransaction commitTransaction()} throws an exception.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} just invokes {@link Connection#rollback}.
*
* @param c the connection on which to roll back the transaction
* @throws SQLException if an error occurs while accessing the database
*/
@Override
protected void rollbackTransaction(Connection c) throws SQLException {
c.rollback();
c.close();
}
/**
* Determine if the database needs initialization.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} simply invokes <code>SELECT COUNT(*) FROM <i>UPDATETABLE</i></code>
* and checks for success or failure. If an exception is thrown, {@link #indicatesUninitializedDatabase} is used
* to distinguish between an exception caused by an uninitialized database and a truly unexpected one.
*
* @param c connection to the database
* @throws SQLException if an unexpected error occurs while accessing the database
*/
@Override
protected boolean databaseNeedsInitialization(Connection c) throws SQLException {
final boolean[] result = new boolean[1];
this.apply(c, new SQLCommand("SELECT COUNT(*) FROM " + this.getUpdateTableName()) {
@Override
public void apply(Connection c) throws SQLException {
Statement s = c.createStatement();
try {
ResultSet resultSet;
try {
resultSet = s.executeQuery(this.getSQL());
} catch (SQLException e) {
if (SQLSchemaUpdater.this.indicatesUninitializedDatabase(c, e)) {
SQLSchemaUpdater.this.log.info("detected an uninitialized database");
result[0] = true;
return;
}
throw e;
}
if (!resultSet.next())
throw new IllegalStateException("zero rows returned by `" + this.getSQL() + "'");
SQLSchemaUpdater.this.log.info("detected initialized database, with "
+ resultSet.getLong(1) + " update(s) already applied");
} finally {
s.close();
}
}
});
return result[0];
}
/**
* Determine if an exception thrown during {@link #databaseNeedsInitialization} is consistent with
* an uninitialized database.
*
* <p>
* This should return true if the exception would be thrown by an SQL query that attempts to access a non-existent table.
* For exceptions thrown by other causes, this should return false.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} always returns true. Subclasses are encouraged to override
* with a more precise implementation.
*
* @param c connection on which the exception occurred
* @param e exception thrown during database access in {@link #databaseNeedsInitialization}
* @see #databaseNeedsInitialization
* @throws SQLException if an error occurs
*/
protected boolean indicatesUninitializedDatabase(Connection c, SQLException e) throws SQLException {
return true;
}
@Override
protected void recordUpdateApplied(Connection c, final String updateName) throws SQLException {
this.apply(c, new SQLCommand("INSERT INTO " + this.getUpdateTableName()
+ " (" + this.getUpdateTableNameColumn() + ", " + this.getUpdateTableTimeColumn() + ") VALUES (?, ?)") {
@Override
public void apply(Connection c) throws SQLException {
PreparedStatement s = c.prepareStatement(this.getSQL());
try {
s.setString(1, updateName);
s.setDate(2, new java.sql.Date(new Date().getTime()));
int rows = s.executeUpdate();
if (rows != 1)
throw new IllegalStateException("got " + rows + " != 1 rows for `" + this.getSQL() + "'");
} finally {
s.close();
}
}
});
}
/**
* Determine which updates have already been applied.
*
* <p>
* The implementation in {@link SQLSchemaUpdater} does the standard JDBC thing using a SELECT statement
* from the update table.
*
* @throws SQLException if an error occurs while accessing the database
*/
@Override
protected Set<String> getAppliedUpdateNames(Connection c) throws SQLException {
final HashSet<String> updateNames = new HashSet<String>();
this.apply(c, new SQLCommand("SELECT " + this.getUpdateTableNameColumn() + " FROM " + this.getUpdateTableName()) {
@Override
public void apply(Connection c) throws SQLException {
Statement s = c.createStatement();
try {
for (ResultSet resultSet = s.executeQuery(this.getSQL()); resultSet.next(); )
updateNames.add(resultSet.getString(1));
} finally {
s.close();
}
}
});
return updateNames;
}
// Initialize the database
@Override
protected void initializeDatabase(Connection c) throws SQLException {
// Sanity check
if (this.getDatabaseInitialization() == null)
throw new IllegalArgumentException("database needs initialization but no database initialization is configured");
if (this.getUpdateTableInitialization() == null)
throw new IllegalArgumentException("database needs initialization but no update table initialization is configured");
// Initialize application schema
this.log.info("intializing database schema");
this.apply(c, this.getDatabaseInitialization());
// Initialize update table
this.log.info("intializing update table");
this.apply(c, this.getUpdateTableInitialization());
}
}
|
package ch.ethz.geco.gecko.command.core;
import ch.ethz.geco.gecko.command.Command;
import ch.ethz.geco.gecko.command.CommandUtils;
import sx.blah.discord.handle.obj.IMessage;
import java.time.ZoneOffset;
import java.util.List;
/**
* Really simple command to check if bot is still responsive
*/
public class Ping extends Command {
public Ping() {
this.setNames(new String[]{"ping", "p"});
this.setDescription("Used to test if bot is still responsive.");
}
@Override
public void execute(IMessage msg, List<String> args) {
IMessage pongMsg = CommandUtils.respond(msg, "Pong!");
long millis = pongMsg.getTimestamp().atZone(ZoneOffset.UTC).toInstant().toEpochMilli() - msg.getTimestamp().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();
CommandUtils.editMessage(pongMsg, "Pong! <" + millis + "ms>");
}
}
|
package org.jboss.weld.tests.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.jboss.weld.test.util.Utils;
/**
* This class generates file with TestClassToHashMapper#OUTPUT_FILE_NAME file name in TestClassToHashMapper#TARGET_DIR directory.
* Generated file contains fully qualified name of each test class and its related hash. Class is executed using exec-maven-plugin during
* install maven phase.
*/
public class TestClassToHashMapper {
public static final String TEST_SUFFIX = "Test.java";
public static final String OUTPUT_FILE_NAME = "test-classes-with-hash.txt";
public static final String TARGET_DIR = "target";
public static final String PREFIX = "org";
public static final String SUFFIX = ".java";
public static void main(String[] args) {
File userDir = new File(System.getProperty("user.dir"));
File outputFile = new File(userDir + File.separator + TARGET_DIR + File.separator + OUTPUT_FILE_NAME);
try {
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileWriter writer = new FileWriter(outputFile);
List<File> files = (List<File>) FileUtils.listFiles(userDir, new TestFileFilter(), new DirFileFilter());
for (File file : files) {
String fqcn = file.getPath().substring(file.getPath().indexOf(PREFIX), file.getPath().indexOf(SUFFIX));
fqcn = fqcn.replace(File.separator, ".");
writer.append(fqcn + " " + Utils.getHashOfTestClass(fqcn));
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
} catch (IOException e) {
}
}
static class TestFileFilter implements IOFileFilter {
@Override
public boolean accept(File file) {
return file.getName().endsWith(TEST_SUFFIX);
}
@Override
public boolean accept(File file, String s) {
return file.getName().endsWith(TEST_SUFFIX);
}
}
static class DirFileFilter implements IOFileFilter {
@Override
public boolean accept(File file) {
return true;
}
@Override
public boolean accept(File file, String s) {
return true;
}
}
}
|
package org.openremote.security;
import org.openremote.exception.OpenRemoteException;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
/**
* This is a password storage implementation using Java's keystore mechanism. It can
* be used in cases where an asymmetric key challenge (normally preferred) based on
* private key is not an option. <p>
*
* Where a password based credentials to access, for example a remote web service is
* required, this implementation allows storing password credentials in an encrypted
* format in a keystore implementation. This prevents locating stored passwords via a
* simple filesystem scan for example. However, it doesn't offer password security
* beyond hiding the password (obscurity) unless the keystore itself is protected by
* a master password. For non-interactive applications this creates a chicken-egg
* problem of storing the master password to access a securely stored passwords unless
* an external key storage (e.g. smart card, biometric hardware or similar) is present.
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class PasswordManager extends KeyManager
{
/**
* Location of the keystore, if persisted.
*/
private URI keystoreLocation = null;
/**
* The backing keystore instance.
*/
private KeyStore keystore = null;
/**
* Constructs an in-memory password manager backed by {@link StorageType#BKS} storage format. <p>
*
* Requires BouncyCastle security provider to be available on the classpath and installed
* as a security provider to the JVM.
*
* @see java.security.Security#addProvider(java.security.Provider)
* @see org.bouncycastle.jce.provider.BouncyCastleProvider
*/
public PasswordManager()
{
super(StorageType.BKS, SecurityProvider.BC.getProviderInstance());
//this.keystoreLocation = instantiateKeyStore(null);
}
/**
* Constructs a persistent password manager back by {@link StorageType#BKS} storage format.
* Requires BouncyCastle security provider to be available on the classpath and installed
* as a security provider to the JVM.
*
* @see java.security.Security#addProvider(java.security.Provider)
* @see org.bouncycastle.jce.provider.BouncyCastleProvider
*
* @param keystoreLocation
* location of the persisted password storage
*
* @param masterPassword
* The master password to access the password storage. Note that the character
* array will be cleared when this constructor completes.
*/
public PasswordManager(URI keystoreLocation, char[] masterPassword)
throws ConfigurationException, KeyManagerException
{
this();
try
{
if (masterPassword == null || masterPassword.length == 0)
{
throw new IllegalArgumentException(
"Implementation error: keystore master password is null or empty."
);
}
if (keystoreLocation == null)
{
throw new IllegalArgumentException("Implementation error: keystore location URI is null.");
}
this.keystoreLocation = keystoreLocation;
this.keystore = load(new File(keystoreLocation), masterPassword);
}
finally
{
if (masterPassword != null)
{
// Clear the password from memory...
for (int i = 0; i < masterPassword.length; ++i)
{
masterPassword[i] = 0;
}
}
}
}
/**
* Adds a new password to this password manager.
*
* @param alias
* A named alias for the password used to look it up.
*
* @param password
* The password to store. Note that the byte array will be set to zero bytes
* when this method completes.
*
* @param storeMasterPassword
* The master password to access this password storage. Note that the character
* array will be set to zero bytes when this method completes.
*
* @throws KeyManagerException
* if accessing the password store fails
*/
public void addPassword(String alias, byte[] password, char[] storeMasterPassword)
throws KeyManagerException
{
try
{
add(
alias,
new KeyStore.SecretKeyEntry(new SecretKeySpec(password, "password")),
new KeyStore.PasswordProtection(storeMasterPassword)
);
if (keystoreLocation != null)
{
save(new File(keystoreLocation), storeMasterPassword);
}
}
finally
{
if (password != null)
{
// Clear the password from memory...
for (int i = 0; i < password.length; ++i)
{
password[i] = 0;
}
}
if (storeMasterPassword != null)
{
// Clear the password from memory...
for (int i = 0; i < storeMasterPassword.length; ++i)
{
storeMasterPassword[i] = 0;
}
}
}
}
/**
* Removes a password from this password storage.
*
* @param alias
* The password alias (name) to be removed.
*
* @param storeMasterPassword
* The master password to access this password storage. Note that the character
* array will be cleared when this method completes.
*
* @throws KeyManagerException
* if accessing the password store fails
*/
public void removePassword(String alias, char[] storeMasterPassword) throws KeyManagerException
{
try
{
if (keystoreLocation != null)
{
remove(alias, new File(keystoreLocation), storeMasterPassword);
}
else
{
removePassword(alias);
}
}
finally
{
if (storeMasterPassword != null)
{
// Clear the password from memory...
for (int i = 0; i < storeMasterPassword.length; ++i)
{
storeMasterPassword[i] = 0;
}
}
}
}
public void removePassword(String alias)
{
remove(alias);
}
/**
* Fetches a password from this password storage. The password is returned as a byte array
* and should be erased immediately after it has been used.
*
* @param alias
* The password alias used to lookup the required password from the storage.
*
* @param storeMasterPassword
* The master password to access this password storage. Note that the character
* array will be cleared when this method completes.
*
* @return Password in a byte array. This byte array should be erased as soon as the
* password has been used.
*/
public byte[] getPassword(String alias, char[] storeMasterPassword)
throws PasswordNotFoundException
{
try
{
if (alias == null || alias.equals(""))
{
throw new PasswordNotFoundException(
"Implementation Error: null or empty password alias."
);
}
if (!keystore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class))
{
throw new PasswordNotFoundException(
"Implementation Error: password alias ''{0}'' does not correspond to secret " +
"key entry in the keystore."
);
}
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)keystore.getEntry(
alias, new KeyStore.PasswordProtection(storeMasterPassword)
);
return entry.getSecretKey().getEncoded();
}
catch (KeyStoreException e)
{
throw new PasswordNotFoundException(
"Implementation Error: password manager has not been loaded."
);
}
catch (NoSuchAlgorithmException e)
{
throw new PasswordNotFoundException(e.getMessage(), e); // TODO
}
catch (UnrecoverableKeyException e)
{
throw new PasswordNotFoundException(e.getMessage(), e); // TODO
}
catch (UnrecoverableEntryException e)
{
throw new PasswordNotFoundException(e.getMessage(), e); // TODO
}
finally
{
clearPassword(storeMasterPassword);
}
}
/**
* Clears the given password character array with zero values.
*
* @param password
* password character array to erase
*/
private void clearPassword(char[] password)
{
if (password != null)
{
for (int i = 0; i < password.length; ++i)
{
password[i] = 0;
}
}
}
/**
* Implementation specific exception type indicating that a requested password was not
* found in this password manager instance.
*/
public class PasswordNotFoundException extends OpenRemoteException
{
/**
* Constructs a password not found exception with a given message.
*
* @param msg
* exception message
*/
private PasswordNotFoundException(String msg)
{
super(msg);
}
/**
* Constructs a password not found exception with a given parameterized message.
*
* @see OpenRemoteException
*
* @param msg
* exception message
*
* @param params
* message parameters
*/
private PasswordNotFoundException(String msg, Object... params)
{
super(msg, params);
}
/**
* Constructs a password not found exception with a given message and root cause.
*
* @param msg
* exception message
*
* @param cause
* root cause for this exception
*/
private PasswordNotFoundException(String msg, Throwable cause)
{
super(msg, cause);
}
/**
* Constructs a password not found exception with a given parameterized message and root cause.
*
* @see OpenRemoteException
*
* @param msg
* exception message
*
* @param cause
* root cause for this exception
*
* @param params
* message parameters
*/
private PasswordNotFoundException(String msg, Throwable cause, Object... params)
{
super(msg, cause, params);
}
}
}
|
package org.opentdc.rates.file;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import org.opentdc.file.AbstractFileServiceProvider;
import org.opentdc.rates.Currency;
import org.opentdc.rates.RateType;
import org.opentdc.rates.RateModel;
import org.opentdc.rates.ServiceProvider;
import org.opentdc.service.exception.DuplicateException;
import org.opentdc.service.exception.InternalServerErrorException;
import org.opentdc.service.exception.NotFoundException;
import org.opentdc.service.exception.ValidationException;
import org.opentdc.util.PrettyPrinter;
/**
* A file-based or transient implementation of the Rates service.
* @author bruno
*
*/
public class FileServiceProvider extends AbstractFileServiceProvider<RateModel> implements ServiceProvider {
private static Map<String, RateModel> index = null;
private static final Logger logger = Logger.getLogger(FileServiceProvider.class.getName());
/**
* Constructor.
* @param context the servlet context.
* @param prefix the simple class name of the service provider
* @throws IOException
*/
public FileServiceProvider(
ServletContext context,
String prefix
) throws IOException {
super(context, prefix);
if (index == null) {
index = new HashMap<String, RateModel>();
List<RateModel> _rates = importJson();
for (RateModel _rate : _rates) {
index.put(_rate.getId(), _rate);
}
logger.info(_rates.size() + " Rates imported.");
}
}
/* (non-Javadoc)
* @see org.opentdc.rates.ServiceProvider#list(java.lang.String, java.lang.String, long, long)
*/
@Override
public ArrayList<RateModel> list(
String query,
String queryType,
int position,
int size
) {
ArrayList<RateModel> _rates = new ArrayList<RateModel>(index.values());
Collections.sort(_rates, RateModel.RateComparator);
ArrayList<RateModel> _selection = new ArrayList<RateModel>();
for (int i = 0; i < _rates.size(); i++) {
if (i >= position && i < (position + size)) {
_selection.add(_rates.get(i));
}
}
logger.info("list(<" + query + ">, <" + queryType +
">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " rates.");
return _selection;
}
/* (non-Javadoc)
* @see org.opentdc.rates.ServiceProvider#create(org.opentdc.rates.RatesModel)
*/
@Override
public RateModel create(
RateModel rate)
throws DuplicateException, ValidationException {
logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(rate) + ")");
String _id = rate.getId();
if (_id == null || _id == "") {
_id = UUID.randomUUID().toString();
} else {
if (index.get(_id) != null) {
// object with same ID exists already
throw new DuplicateException("rate <" + _id + "> exists already.");
}
else { // a new ID was set on the client; we do not allow this
throw new ValidationException("rate <" + _id +
"> contains an ID generated on the client. This is not allowed.");
}
}
if (rate.getTitle() == null || rate.getTitle().isEmpty()) {
throw new ValidationException("rate <" + _id + "> must contain a valid title.");
}
if (rate.getRate() < 0) {
throw new ValidationException("rate <" + _id + ">: negative rates are not allowed.");
}
if (rate.getCurrency() == null) {
rate.setCurrency(Currency.getDefaultCurrency());
}
if (rate.getType() == null) {
rate.setType(RateType.getDefaultRateType());
}
rate.setId(_id);
Date _date = new Date();
rate.setCreatedAt(_date);
rate.setCreatedBy(getPrincipal());
rate.setModifiedAt(_date);
rate.setModifiedBy(getPrincipal());
index.put(_id, rate);
logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(rate) + ")");
if (isPersistent) {
exportJson(index.values());
}
return rate;
}
/* (non-Javadoc)
* @see org.opentdc.rates.ServiceProvider#read(java.lang.String)
*/
@Override
public RateModel read(
String id)
throws NotFoundException {
return getRatesModel(id);
}
public static RateModel getRatesModel(
String id)
throws NotFoundException {
RateModel _rate = index.get(id);
if (_rate == null) {
throw new NotFoundException("no rate with ID <" + id + "> was found.");
}
logger.info("getRatesModel(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_rate));
return _rate;
}
/* (non-Javadoc)
* @see org.opentdc.rates.ServiceProvider#update(java.lang.String, org.opentdc.rates.RatesModel)
*/
@Override
public RateModel update(
String id,
RateModel rate
) throws NotFoundException, ValidationException {
RateModel _rate = index.get(id);
if(_rate == null) {
throw new NotFoundException("no rate with ID <" + id
+ "> was found.");
}
if (rate.getTitle() == null || rate.getTitle().isEmpty()) {
throw new ValidationException("rate <" + id + ">: title must be defined.");
}
if (rate.getRate() < 0) {
throw new ValidationException("rate <" + id + ">: negative rates are not allowed.");
}
if (! _rate.getCreatedAt().equals(rate.getCreatedAt())) {
logger.warning("rate <" + id + ">: ignoring createdAt value <" + rate.getCreatedAt().toString() +
"> because it was set on the client.");
}
if (! _rate.getCreatedBy().equalsIgnoreCase(rate.getCreatedBy())) {
logger.warning("rate <" + id + ">: ignoring createdBy value <" + rate.getCreatedBy() +
"> because it was set on the client.");
}
_rate.setTitle(rate.getTitle());
_rate.setRate(rate.getRate());
if (rate.getCurrency() == null) {
_rate.setCurrency(Currency.getDefaultCurrency());
} else {
_rate.setCurrency(rate.getCurrency());
}
if (rate.getType() == null) {
_rate.setType(RateType.getDefaultRateType());
} else {
_rate.setType(rate.getType());
}
_rate.setDescription(rate.getDescription());
_rate.setModifiedAt(new Date());
_rate.setModifiedBy(getPrincipal());
index.put(id, _rate);
logger.info("update(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_rate));
if (isPersistent) {
exportJson(index.values());
}
return _rate;
}
/* (non-Javadoc)
* @see org.opentdc.rates.ServiceProvider#delete(java.lang.String)
*/
@Override
public void delete(
String id)
throws NotFoundException, InternalServerErrorException {
RateModel _rate = index.get(id);
if (_rate == null) {
throw new NotFoundException("rate <" + id
+ "> was not found.");
}
if (index.remove(id) == null) {
throw new InternalServerErrorException("rate <" + id
+ "> can not be removed, because it does not exist in the index");
}
logger.info("delete(" + id + ")");
if (isPersistent) {
exportJson(index.values());
}
}
}
|
package chav1961.purelib.ui.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.JTextComponent;
import chav1961.purelib.basic.GettersAndSettersFactory;
import chav1961.purelib.basic.PureLibSettings;
import chav1961.purelib.basic.URIUtils;
import chav1961.purelib.basic.Utils;
import chav1961.purelib.basic.exceptions.ContentException;
import chav1961.purelib.basic.exceptions.FlowException;
import chav1961.purelib.basic.exceptions.LocalizationException;
import chav1961.purelib.basic.exceptions.SyntaxException;
import chav1961.purelib.basic.interfaces.LoggerFacade;
import chav1961.purelib.basic.interfaces.LoggerFacade.Severity;
import chav1961.purelib.enumerations.ContinueMode;
import chav1961.purelib.enumerations.MarkupOutputFormat;
import chav1961.purelib.enumerations.NodeEnterMode;
import chav1961.purelib.i18n.AbstractLocalizer;
import chav1961.purelib.i18n.LocalizerFactory;
import chav1961.purelib.i18n.interfaces.LocaleResource;
import chav1961.purelib.i18n.interfaces.Localizer;
import chav1961.purelib.i18n.interfaces.Localizer.LocaleChangeListener;
import chav1961.purelib.model.Constants;
import chav1961.purelib.model.FieldFormat;
import chav1961.purelib.model.ModelUtils;
import chav1961.purelib.model.interfaces.ContentMetadataInterface.ContentNodeMetadata;
import chav1961.purelib.model.interfaces.NodeMetadataOwner;
import chav1961.purelib.streams.StreamsUtil;
import chav1961.purelib.streams.char2byte.CompilerUtils;
import chav1961.purelib.ui.interfaces.FormManager;
import chav1961.purelib.ui.swing.interfaces.JComponentInterface;
import chav1961.purelib.ui.swing.interfaces.JComponentMonitor;
import chav1961.purelib.ui.swing.interfaces.OnAction;
import chav1961.purelib.ui.swing.useful.JLocalizedOptionPane;
import chav1961.purelib.ui.swing.useful.LocalizedFormatter;
/**
* <p>This utility class contains a set of useful methods to use in the Swing-based applications.</p>
*
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.3
* @lastUpdate 0.0.4
*/
public abstract class SwingUtils {
public static final Border TABLE_CELL_BORDER = new LineBorder(Color.BLACK,1);
public static final Border TABLE_HEADER_BORDER = new LineBorder(Color.BLACK,1);
public static final Border FOCUSED_TABLE_CELL_BORDER = new LineBorder(Color.BLUE,1);
public static final KeyStroke KS_BACKWARD = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.ALT_DOWN_MASK);
public static final KeyStroke KS_FORWARD = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.ALT_DOWN_MASK);
public static final KeyStroke KS_HELP = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
public static final KeyStroke KS_ACCEPT = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
public static final KeyStroke KS_EXIT = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
public static final KeyStroke KS_DROPDOWN = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.ALT_DOWN_MASK);
public static final KeyStroke KS_CLOSE = KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_DOWN_MASK);
public static final String ACTION_FORWARD = "forward";
public static final String ACTION_BACKWARD = "backward";
public static final String ACTION_HELP = "help";
public static final String ACTION_ACCEPT = "accept";
public static final String ACTION_EXIT = "exit";
private static final Map<Class<?>,Object> DEFAULT_VALUES = new HashMap<>();
private static final String UNKNOWN_ACTION_TITLE = "SwingUtils.unknownAction.title";
private static final String UNKNOWN_ACTION_CONTENT = "SwingUtils.unknownAction.content";
static {
DEFAULT_VALUES.put(byte.class,(byte)0);
DEFAULT_VALUES.put(Byte.class,(byte)0);
DEFAULT_VALUES.put(short.class,(short)0);
DEFAULT_VALUES.put(Short.class,(short)0);
DEFAULT_VALUES.put(int.class,0);
DEFAULT_VALUES.put(Integer.class,0);
DEFAULT_VALUES.put(long.class,0L);
DEFAULT_VALUES.put(Long.class,0L);
DEFAULT_VALUES.put(float.class,0.0f);
DEFAULT_VALUES.put(Float.class,0.0f);
DEFAULT_VALUES.put(double.class,0.0);
DEFAULT_VALUES.put(Double.class,0.0);
DEFAULT_VALUES.put(BigInteger.class,BigInteger.ZERO);
DEFAULT_VALUES.put(BigDecimal.class,BigDecimal.ZERO);
}
private SwingUtils() {}
/**
* <p>This interface describes callback for walking on the swing component's tree</p>
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.3
*/
@FunctionalInterface
public interface WalkCallback {
/**
* <p>Process current node</p>
* @param mode enter mode
* @param node current node
* @return continue mode
*/
ContinueMode process(final NodeEnterMode mode, final Component node);
}
@FunctionalInterface
interface InnerActionNode {
JComponent[] getActionNodes();
}
/**
* <p>Walk on the swing components tree</p>
* @param node root node to walk from
* @param callback callback to process nodes
* @return the same last continue mode (can't be null)
*/
public static ContinueMode walkDown(final Component node, final WalkCallback callback) {
if (callback == null) {
throw new NullPointerException("Root component can't be null");
}
else if (node == null) {
throw new NullPointerException("Node callback can't be null");
}
else {
return walkDownInternal(node,callback);
}
}
private static ContinueMode walkDownInternal(final Component node, final WalkCallback callback) {
switch (callback.process(NodeEnterMode.ENTER,node)) {
case CONTINUE :
loop: for (Component comp : children(node)) {
switch (walkDownInternal(comp,callback)) {
case CONTINUE:
break;
case SKIP_CHILDREN:
break loop;
case SKIP_SIBLINGS :
callback.process(NodeEnterMode.EXIT,node);
return ContinueMode.SKIP_CHILDREN;
case STOP:
callback.process(NodeEnterMode.EXIT,node);
return ContinueMode.STOP;
default:
break;
}
}
case SKIP_CHILDREN :
callback.process(NodeEnterMode.EXIT,node);
return ContinueMode.CONTINUE;
case SKIP_SIBLINGS :
callback.process(NodeEnterMode.EXIT,node);
return ContinueMode.SKIP_CHILDREN;
case STOP :
callback.process(NodeEnterMode.EXIT,node);
return ContinueMode.STOP;
default:
return ContinueMode.CONTINUE;
}
}
/**
* <p>Make iterable for all children of the given component</p>
* @param component component to make children iterable for
* @return iterable for children. Can be empty but not null
* @throws NullPointerException
*/
public static Iterable<Component> children(final Component component) throws NullPointerException {
if (component == null) {
throw new NullPointerException("Component to get children for can't be null");
}
else {
final List<Component> result = new ArrayList<>();
Component[] content;
if (component instanceof Container) {
if ((content = ((Container)component).getComponents()) != null) {
result.addAll(Arrays.asList(content));
}
}
if (component instanceof JMenu) {
if ((content = ((JMenu)component).getMenuComponents()) != null) {
result.addAll(Arrays.asList(content));
}
}
if (component instanceof JFrame) {
if ((content = ((JFrame)component).getRootPane().getComponents()) != null) {
result.addAll(Arrays.asList(content));
}
}
if (component instanceof JDialog) {
if ((content = ((JDialog)component).getRootPane().getComponents()) != null) {
result.addAll(Arrays.asList(content));
}
}
if (component instanceof JDesktopPane) {
if ((content = ((JDesktopPane)component).getComponents()) != null) {
result.addAll(Arrays.asList(((JDesktopPane)component).getComponents()));
}
}
if (component instanceof JLayeredPane) {
final JLayeredPane pane = ((JLayeredPane)component);
for (int index = pane.lowestLayer(), maxIndex = pane.highestLayer(); index <= maxIndex; index++) {
if (pane.getComponentCountInLayer(index) > 0 && (content = pane.getComponentsInLayer(index)) != null) {
result.addAll(Arrays.asList(content));
}
}
}
return result;
}
}
public static Container findComponentByName(final Component node, final String name) throws NullPointerException, IllegalArgumentException {
if (node == null) {
throw new NullPointerException("Node callbacl can't be null");
}
else if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Name to find can't be null or empty");
}
else {
final Component[] result = new Component[]{null};
walkDown(node,(mode,component)->{
if (mode == NodeEnterMode.ENTER && name.equals(component.getName())) {
result[0] = component;
return ContinueMode.STOP;
}
else {
return ContinueMode.CONTINUE;
}
});
return (Container)result[0];
}
}
public static void addPrefix2ComponentNames(final Component node, final String prefix) throws NullPointerException, IllegalArgumentException {
if (node == null) {
throw new NullPointerException("Node can't be null");
}
else if (prefix == null || prefix.isEmpty()) {
throw new IllegalArgumentException("Prefix name can't be null or empty");
}
else {
walkDown(node,(mode,component)->{
if (mode == NodeEnterMode.ENTER) {
final String name = component.getName();
if (name != null && !name.startsWith(prefix)) {
component.setName(prefix+name);
}
}
return ContinueMode.CONTINUE;
});
}
}
/**
* <p>Prepare renderer for the given meta data and field format</p>
* @param metadata meta data to prepare renderer for
* @param content field content format
* @param monitor field monitor
* @return component prepared
* @throws NullPointerException when any parameters are null
* @throws LocalizationException when there are problems with localizers
* @throws SyntaxException on format errors for the given control
*/
public static JComponent prepareRenderer(final ContentNodeMetadata metadata, final Localizer localizer, final FieldFormat.ContentType content, final JComponentMonitor monitor) throws NullPointerException, LocalizationException, SyntaxException {
if (metadata == null) {
throw new NullPointerException("Metadata can't be null");
}
else if (content == null) {
throw new NullPointerException("Content type can't be null");
}
else if (monitor == null) {
throw new NullPointerException("Monitor can't be null");
}
else {
JComponent result = null;
switch (content) {
case BooleanContent :
result = new JCheckBoxWithMeta(metadata,localizer,monitor);
break;
case DateContent :
result = new JDateFieldWithMeta(metadata,localizer,monitor);
break;
case EnumContent :
result = new JEnumFieldWithMeta(metadata,monitor);
break;
case FileContent :
result = new JFileFieldWithMeta(metadata,monitor);
break;
case FormattedStringContent :
result = new JFormattedTextFieldWithMeta(metadata,monitor);
break;
case IntegerContent :
result = new JIntegerFieldWithMeta(metadata,monitor);
break;
case NumericContent :
result = new JNumericFieldWithMeta(metadata,monitor);
break;
case StringContent :
result = new JTextFieldWithMeta(metadata,monitor);
break;
case URIContent :
result = new JTextFieldWithMeta(metadata,monitor);
break;
case ColorContent :
result = new JColorPickerWithMeta(metadata,localizer,monitor);
break;
case ColorPairContent :
result = new JColorPairPickerWithMeta(metadata,localizer,monitor);
break;
case Unclassified :
case ArrayContent :
case NestedContent :
case TimestampContent :
default:
throw new UnsupportedOperationException("Content type ["+content+"] for metadata ["+metadata.getName()+"] is not supported yet");
}
result.setName(metadata.getUIPath().toString());
return result;
}
}
@SuppressWarnings("unchecked")
public static <T extends JComponent> T toJComponent(final ContentNodeMetadata node, final Class<T> awaited) throws NullPointerException, IllegalArgumentException{
if (node == null) {
throw new NullPointerException("Model node can't be null");
}
else if (awaited == null) {
throw new NullPointerException("Awaited class can't be null");
}
else {
if (awaited.isAssignableFrom(JMenuBar.class)) {
if (!node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_TOP_PREFIX)) {
throw new IllegalArgumentException("Model node ["+node.getUIPath()+"] can't be converted to ["+awaited.getCanonicalName()+"] class");
}
else {
final JMenuBar result = new JMenuBarWithMeta(node);
for (ContentNodeMetadata child : node) {
toMenuEntity(child,result);
}
return (T) result;
}
}
else if (awaited.isAssignableFrom(JPopupMenu.class)) {
if (!node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_TOP_PREFIX)) {
throw new IllegalArgumentException("Model node ["+node.getUIPath()+"] can't be converted to ["+awaited.getCanonicalName()+"] class");
}
else {
final JPopupMenu result = new JMenuPopupWithMeta(node);
for (ContentNodeMetadata child : node) {
toMenuEntity(child,result);
}
return (T) result;
}
}
else if (awaited.isAssignableFrom(JToolBar.class)) {
if (!node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_TOP_PREFIX)) {
throw new IllegalArgumentException("Model node ["+node.getUIPath()+"] can't be converted to ["+awaited.getCanonicalName()+"] class");
}
else {
final JToolBar result = new JToolBarWithMeta(node);
for (ContentNodeMetadata child : node) {
if (child.getRelativeUIPath().toString().startsWith("./"+Constants.MODEL_NAVIGATION_NODE_PREFIX)) {
final JMenuPopupWithMeta menu = new JMenuPopupWithMeta(child);
final JButton btn = new JButtonWithMetaAndActions(child,JButtonWithMeta.LAFType.ICON_THEN_TEXT,menu);
for (ContentNodeMetadata item : child) {
toMenuEntity(item,menu);
}
btn.addActionListener((e)->{
menu.show(btn,btn.getWidth()/2,btn.getHeight()/2);
});
result.add(btn);
}
else if (child.getRelativeUIPath().toString().startsWith("./"+Constants.MODEL_NAVIGATION_LEAF_PREFIX)) {
result.add(new JButtonWithMeta(child,JButtonWithMeta.LAFType.ICON_THEN_TEXT));
}
else if (URI.create("./navigation.separator").equals(child.getRelativeUIPath())) {
result.addSeparator();
}
}
return (T) result;
}
}
else {
throw new IllegalArgumentException("Unsupported awaited class ["+awaited.getCanonicalName()+"]. Only JMenuBar, JPopupMenu or JToolBar are supported");
}
}
}
public static boolean putToScreen(final ContentNodeMetadata metadata, final Object content, final Container uiRoot) throws NullPointerException, ContentException, IllegalArgumentException {
if (metadata == null) {
throw new NullPointerException("Metadata can't be null");
}
else if (content == null) {
throw new NullPointerException("Content instance object can't be null");
}
else if (uiRoot == null) {
throw new NullPointerException("UI root component can't be null");
}
else if (!content.getClass().isAnnotationPresent(LocaleResource.class)) {
throw new IllegalArgumentException("Content instance class ["+content.getClass().getCanonicalName()+"] doesn't annotated with @LocaleResource, and can't be used here");
}
else {
final Component component = SwingUtils.findComponentByName(uiRoot,metadata.getUIPath().toString());
if (component instanceof JComponentInterface) {
((JComponentInterface)component).assignValueToComponent(
ModelUtils.getValueByGetter(content,
GettersAndSettersFactory.buildGetterAndSetter(metadata.getApplicationPath())
,metadata));
return true;
}
else {
return false;
}
}
}
public static boolean getFromScreen(final ContentNodeMetadata metadata, final Component uiRoot, final Object content) throws ContentException, NullPointerException, IllegalArgumentException {
if (metadata == null) {
throw new NullPointerException("Metadata can't be null");
}
else if (content == null) {
throw new NullPointerException("Content instance object can't be null");
}
else if (uiRoot == null) {
throw new NullPointerException("UI root component can't be null");
}
else if (!content.getClass().isAnnotationPresent(LocaleResource.class)) {
throw new IllegalArgumentException("Content instance class ["+content.getClass().getCanonicalName()+"] doesn't annotated with @LocaleResource, and can't be used here");
}
else {
final Component component = SwingUtils.findComponentByName(uiRoot,metadata.getUIPath().toString());
if (component instanceof JComponentInterface) {
ModelUtils.setValueBySetter(content,
((JComponentInterface)component).getChangedValueFromComponent(),
GettersAndSettersFactory.buildGetterAndSetter(metadata.getApplicationPath())
,metadata);
return true;
}
else {
return false;
}
}
}
/**
* <p>Prepare message in HTML format to show it in the JTextComponent controls</p>
* @param severity message severity
* @param format message format (see {@linkplain String#format(String, Object...)}
* @param parameters additional parameters
* @return HTML representation of the message
* @throws NullPointerException when any parameters are null
*/
public static String prepareHtmlMessage(final Severity severity, final String format, final Object... parameters) throws NullPointerException {
if (severity == null) {
throw new NullPointerException("Severity can't be null");
}
else if (format == null) {
throw new NullPointerException("Format string can't be null");
}
else {
final String value = (parameters.length == 0 ? format : String.format(format,parameters)).replace("\n","<br>");
final String wrappedValue;
switch (severity) {
case debug : wrappedValue = "<html><body><font color=gray>" + value + "</font></body></html>"; break;
case error : wrappedValue = "<html><body><font color=red>" + value + "</font></body></html>"; break;
case info : wrappedValue = "<html><body><font color=black>" + value + "</font></body></html>"; break;
case severe : wrappedValue = "<html><body><font color=red><b>" + value + "</b></font></body></html>"; break;
case trace : wrappedValue = "<html><body><font color=gray><i>" + value + "</i></font></body></html>"; break;
case warning: wrappedValue = "<html><body><font color=blue>" + value + "</font></body></html>"; break;
default : wrappedValue = "<html><body><font color=black>" + value + "</font></body></html>"; break;
}
return wrappedValue;
}
}
public static Object getDefaultValue4Class(final Class<?> clazz) {
return DEFAULT_VALUES.get(clazz);
}
public static int getSignum4Value(final Object value) {
if (value == null) {
throw new NullPointerException("Value to get signum can't be null");
}
else {
if (value instanceof BigInteger) {
return ((BigInteger)value).signum();
}
else if (value instanceof BigDecimal) {
return ((BigDecimal)value).signum();
}
else if (value instanceof Number) {
return (int) Math.signum(((Number)value).doubleValue());
}
else {
throw new IllegalArgumentException("Value type ["+value.getClass().getCanonicalName()+"] for value ["+value+"] is not a numerical type");
}
}
}
/**
* <p>Refresh localization content for all the GUI components tree. The method recursively walks on all the UI component tree, but doesn't walk down if the current
* UI component implements {@linkplain LocaleChangeListener} interface. All the implementers of this interface must refresh it's own content by self</p>
* @param root root of the GUI components to refresh localization
* @param oldLocale old locale
* @param newLocale new locale
* @throws NullPointerException if any parameter is null
* @throws LocalizationException in any localization errors
*/
public static void refreshLocale(final Component root, final Locale oldLocale, final Locale newLocale) throws NullPointerException, LocalizationException {
if (root == null) {
throw new NullPointerException("Root component can't be null");
}
else if (oldLocale == null) {
throw new NullPointerException("Old locale can't be null");
}
else if (newLocale == null) {
throw new NullPointerException("New locale can't be null");
}
else {
refreshLocaleInternal(root, oldLocale, newLocale);
}
}
private static void refreshLocaleInternal(final Component root, final Locale oldLocale, final Locale newLocale) throws LocalizationException {
if (root != null) {
if (root instanceof LocaleChangeListener) {
((LocaleChangeListener)root).localeChanged(oldLocale, newLocale);
}
else if (root instanceof Container) {
for (Component item : ((Container)root).getComponents()) {
refreshLocaleInternal(item,oldLocale,newLocale);
}
}
}
}
public static void assignActionKey(final JComponent component, final KeyStroke keyStroke, final ActionListener listener, final String actionId) throws NullPointerException, IllegalArgumentException {
assignActionKey(component,JPanel.WHEN_FOCUSED,keyStroke, listener, actionId);
}
public static void removeActionKey(final JComponent component, final KeyStroke keyStroke, final String actionId) throws NullPointerException, IllegalArgumentException {
removeActionKey(component,JPanel.WHEN_FOCUSED,keyStroke, actionId);
}
public static void assignActionKey(final JComponent component, final int mode, final KeyStroke keyStroke, final ActionListener listener, final String actionId) throws NullPointerException, IllegalArgumentException {
if (component == null) {
throw new NullPointerException("Component can't be null");
}
else if (keyStroke == null) {
throw new NullPointerException("KeyStroke can't be null");
}
else if (listener == null) {
throw new NullPointerException("Action listener can't be null");
}
else if (actionId == null || actionId.isEmpty()) {
throw new IllegalArgumentException("Action identifier can't be null or empty");
}
else {
component.getInputMap(mode).put(keyStroke,actionId);
component.getActionMap().put(actionId,new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
listener.actionPerformed(new ActionEvent(component,0,actionId));
}
});
}
}
public static void removeActionKey(final JComponent component, final int mode, final KeyStroke keyStroke, final String actionId) throws NullPointerException, IllegalArgumentException {
if (component == null) {
throw new NullPointerException("Component can't be null");
}
else if (keyStroke == null) {
throw new NullPointerException("KeyStroke can't be null");
}
else if (actionId == null || actionId.isEmpty()) {
throw new IllegalArgumentException("Action identifier can't be null or empty");
}
else {
component.getInputMap(mode).remove(keyStroke);
component.getActionMap().remove(actionId);
}
}
/**
* <p>Center main window on the screen</p>
* @param frame main window
* @throws NullPointerException if frame is null
*/
public static void centerMainWindow(final JFrame frame) throws NullPointerException {
centerMainWindow(frame,0.75f);
}
/**
* <p>Center main window on the screen</p>
* @param frame main window
* @param fillPercent filling percent on the screen. Must be in the range 0.0f..1.0f
* @throws NullPointerException if frame is null
*/
public static void centerMainWindow(final JFrame frame, final float fillPercent) throws NullPointerException {
if (frame == null) {
throw new NullPointerException("Frame window can't be null");
}
else if (fillPercent < 0 || fillPercent > 1) {
throw new IllegalArgumentException("Fill percent ["+fillPercent+"] out of range 0.0f..1.0f");
}
else {
final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
final Dimension size = new Dimension((int)(screen.getWidth()*fillPercent),(int)(screen.getHeight()*fillPercent));
final Point location = new Point((int)(screen.getWidth()*(1-fillPercent)/2),(int)(screen.getHeight()*(1-fillPercent)/2));
frame.setLocation(location);
frame.setSize(size);
frame.setPreferredSize(size);
}
}
/**
* <p>Center main window on the screen</p>
* @param dialog main window
* @throws NullPointerException if dialog is null
*/
public static void centerMainWindow(final JDialog dialog) throws NullPointerException {
centerMainWindow(dialog,0.5f);
}
/**
* <p>Center main window on the screen and resize it to the given screen percent</p>
* @param dialog main window
* @param fillPercent filling percent on the screen. Must be in the range 0.0f..1.0f
* @throws NullPointerException if dialog is null
*/
public static void centerMainWindow(final JDialog dialog, final float fillPercent) throws NullPointerException {
if (dialog == null) {
throw new NullPointerException("Dialog window can't be null");
}
else if (fillPercent < 0 || fillPercent > 1) {
throw new IllegalArgumentException("Fill percent ["+fillPercent+"] out of range 0.0f..1.0f");
}
else {
final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
final Dimension size = new Dimension((int)(screen.getWidth()*fillPercent),(int)(screen.getHeight()*fillPercent));
final Point location = new Point((int)(screen.getWidth()*(1-fillPercent)/2),(int)(screen.getHeight()*(1-fillPercent)/2));
dialog.setLocation(location);
dialog.setSize(size);
dialog.setPreferredSize(size);
}
}
/**
* <p>This interface describes callback for closing frame</p>
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.3
*/
@FunctionalInterface
public interface ExitMethodCallback {
/**
* <p>Process exit from main frame</p>
* @throws Exception on any errors on the exit
*/
void processExit() throws Exception;
}
/**
* <p>Assign exit method for the window when pressed close button on the title</p>
* @param frame window to assign method to
* @param callback callback to execute
*/
public static void assignExitMethod4MainWindow(final JFrame frame, final ExitMethodCallback callback) {
if (frame == null) {
throw new NullPointerException("Window to assign exit method can't be null");
}
else if (callback == null) {
throw new NullPointerException("Callback to assign to window can't be null");
}
else {
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
@Override public void windowOpened(WindowEvent e) {}
@Override public void windowIconified(WindowEvent e) {}
@Override public void windowDeiconified(WindowEvent e) {}
@Override public void windowDeactivated(WindowEvent e) {}
@Override public void windowClosed(WindowEvent e) {}
@Override public void windowActivated(WindowEvent e) {}
@Override
public void windowClosing(final WindowEvent e) {
try{callback.processExit();
} catch (Exception exc) {
}
}
});
}
}
/**
* <p>This interface describes callback for processing unknown action string</p>
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.3
*/
@FunctionalInterface
public interface FailedActionListenerCallback {
/**
* <p>Process unknown action command</p>
* @param actionCommand command to process
*/
void processUnknown(final String actionCommand);
}
/**
* <p>Prepare action listeners to call methods marked with {@linkplain OnAction} annotation</p>
* @param root root component to assign listeners to
* @param entity object to call it's annotated methods
*/
public static void assignActionListeners(final JComponent root, final Object entity) {
assignActionListeners(root,entity,(action)->{sayAboutUnknownAction(null,action);});
}
/**
* <p>Prepare action listeners to call methods marked with {@linkplain OnAction} annotation</p>
* @param root root component to assign listeners to
* @param entity object to call it's annotated methods
* @param onUnknown callback to process missing actions
*/
public static void assignActionListeners(final JComponent root, final Object entity, final FailedActionListenerCallback onUnknown) {
if (root == null) {
throw new NullPointerException("Root component can't be null");
}
else if (entity == null) {
throw new NullPointerException("Entity class can't be null");
}
else {
assignActionListeners(root,buildAnnotatedActionListener(entity, onUnknown));
}
}
/**
* <p>Prepare action listeners to call {@linkplain FormManager#onAction(Object, Object, String, Object)} method</p>
* @param <T> any entity is used for form manager
* @param root component with action sources inside
* @param entity instance to call onAction for
* @param manager form manager to process action on entity
* @since 0.0.4
*/
public static <T> void assignActionListeners(final JComponent root, final T entity, final FormManager<?,T> manager) {
if (root == null) {
throw new NullPointerException("Root component can't be null");
}
else if (entity == null) {
throw new NullPointerException("Entity class can't be null");
}
else if (manager == null) {
throw new NullPointerException("Form manager can't be null");
}
else {
assignActionListeners(root,(e)->{
try{manager.onAction(entity,null,e.getActionCommand(),null);
} catch (LocalizationException | FlowException exc) {
}
});
}
}
public static ActionListener buildAnnotatedActionListener(final Object entity) throws IllegalArgumentException, NullPointerException {
return buildAnnotatedActionListener(entity,(action)->{sayAboutUnknownAction(null,action);});
}
public static ActionListener buildAnnotatedActionListener(final Object entity, final FailedActionListenerCallback onUnknown) throws IllegalArgumentException, NullPointerException {
return buildAnnotatedActionListener(entity, onUnknown, PureLibSettings.CURRENT_LOGGER);
}
public static ActionListener buildAnnotatedActionListener(final Object entity, final FailedActionListenerCallback onUnknown, final LoggerFacade logger) throws IllegalArgumentException, NullPointerException {
if (entity == null) {
throw new NullPointerException("Entity class can't be null");
}
else if (onUnknown == null) {
throw new NullPointerException("OnUnknown callback can't be null");
}
else if (logger == null) {
throw new NullPointerException("Logger can't be null");
}
else {
final Map<String,Method> annotatedMethods = new HashMap<>();
Class<?> entityClass = entity.getClass();
CompilerUtils.walkMethods(entityClass,(clazz,m)->{
if (m.isAnnotationPresent(OnAction.class)) {
annotatedMethods.putIfAbsent(m.getAnnotation(OnAction.class).value(),m);
}
});
if (annotatedMethods.size() == 0) {
throw new IllegalArgumentException("No any methods in the entity object are annotated with ["+OnAction.class+"] annotation");
}
else {
final Map<String,MethodHandleAndAsync> calls = new HashMap<>();
for (Entry<String, Method> item : annotatedMethods.entrySet()) {
final Method m = item.getValue();
try{m.setAccessible(true);
calls.put(item.getKey(),new MethodHandleAndAsync(MethodHandles.lookup().unreflect(m),m.getAnnotation(OnAction.class).async()));
} catch (IllegalAccessException exc) {
throw new IllegalArgumentException("Can't get access to annotated method ["+m+"]: "+exc.getLocalizedMessage());
}
}
return (e)-> {
final URI action = URI.create(e.getActionCommand());
final Map<String,?> query = URIUtils.parseQuery(action);
final String actionKey = URIUtils.removeQueryFromURI(action).toString();
if (calls.containsKey(actionKey)) {
try{final MethodHandleAndAsync mha = calls.get(actionKey);
if (mha.async) {
final Thread t = new Thread(()->{
try{if (!query.isEmpty()) {
mha.handle.invoke(entity,query);
}
else {
mha.handle.invoke(entity);
}
} catch (ThreadDeath d) {
throw d;
} catch (Throwable exc) {
logger.message(Severity.error, exc, exc.getLocalizedMessage());
}
});
t.setDaemon(true);
t.start();
}
else {
if (!query.isEmpty()) {
mha.handle.invoke(entity,query);
}
else {
mha.handle.invoke(entity);
}
}
} catch (ThreadDeath d) {
throw d;
} catch (Throwable t) {
logger.message(Severity.error, t, t.getLocalizedMessage() == null ? t.getClass().getSimpleName() : t.getLocalizedMessage());
}
}
else {
onUnknown.processUnknown(e.getActionCommand());
}
};
}
}
}
private static void assignActionListeners(final JComponent root, final ActionListener listener) {
walkDownInternal(root,(mode,node)->{
if (mode == NodeEnterMode.ENTER) {
try{node.getClass().getMethod("addActionListener",ActionListener.class).invoke(node,listener);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
}
}
return ContinueMode.CONTINUE;
});
}
private static void sayAboutUnknownAction(final Component parent, final String actionName) {
try{new JLocalizedOptionPane(PureLibSettings.PURELIB_LOCALIZER).message(parent,new LocalizedFormatter(UNKNOWN_ACTION_CONTENT,actionName),UNKNOWN_ACTION_TITLE,JOptionPane.ERROR_MESSAGE);
} catch (LocalizationException exc) {
PureLibSettings.CURRENT_LOGGER.message(Severity.error, exc, exc.getLocalizedMessage());
}
}
/**
* <p>Build enable group on the screen. When group leader is turned on, all it's members will be enabled. When group leader is turned off, all it's members will be disabled
* @param leader group leader (usually {@linkplain JCheckBox})
* @param members members of the group
*/
public static void buildEnabledGroup(final AbstractButton leader, final JComponent... members) {
// TODO:
}
@FunctionalInterface
public interface FileGetter {
File get();
}
@FunctionalInterface
public interface FileSetter {
void set(File file) throws ContentException;
}
public static void buildFileSelectionGroup(final JTextComponent fileName, final AbstractButton selector, final FileGetter getter, final FileSetter setter) {
// TODO:
}
@FunctionalInterface
public interface FileListGetter {
File[] get();
}
@FunctionalInterface
public interface FileListSetter {
void set(File[] fileList) throws ContentException;
}
public static void buildFileListSelectionGroup(final JTextComponent fileName, final AbstractButton selector, final FileListGetter getter, final FileListSetter setter) {
// TODO:
}
public static void buildDirectorySelectionGroup(final JTextComponent fileName, final AbstractButton selector, final FileGetter getter, final FileSetter setter) {
// TODO:
}
/**
* <p>Show Creole-based help</p>
* @param owner help window owner
* @param helpContent help reference
* @throws IOException on any I/O errors
* @throws NullPointerException when any parameter is null
*/
public static void showCreoleHelpWindow(final Component owner, final URI helpContent) throws IOException, NullPointerException {
if (owner == null) {
throw new NullPointerException("Window owner can't be null");
}
else if (helpContent == null) {
throw new NullPointerException("Help content refrrence can't be null");
}
else {
final PopupFactory pf = PopupFactory.getSharedInstance();
final JEditorPane pane = new JEditorPane("text/html","");
final JScrollPane scroll = new JScrollPane(pane);
final Dimension ownerSize = owner.getSize(), helpSize = new Dimension(Math.max(200,ownerSize.width),Math.max(ownerSize.height,300));
final Point point = new Point((ownerSize.width-helpSize.width)/2,(ownerSize.height-helpSize.height)/2);
final HyperlinkListener hll = (e)->{
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
Utils.startBrowser(e.getURL());
}
};
pane.setEditable(false);
scroll.setPreferredSize(helpSize);
SwingUtilities.convertPointToScreen(point,owner);
final Popup popup = pf.getPopup(owner,scroll,point.x,point.y);
pane.setText(StreamsUtil.loadCreoleContent(helpContent.toURL(),MarkupOutputFormat.XML2HTML));
assignActionKey(pane,JPanel.WHEN_IN_FOCUSED_WINDOW,SwingUtils.KS_EXIT,(e)->{
popup.hide();
pane.removeHyperlinkListener(hll);
removeActionKey(pane,JPanel.WHEN_IN_FOCUSED_WINDOW,SwingUtils.KS_EXIT,SwingUtils.ACTION_EXIT);
},SwingUtils.ACTION_EXIT);
pane.addMouseListener(new MouseListener() {
@Override public void mouseReleased(MouseEvent e) {}
@Override public void mousePressed(MouseEvent e) {}
@Override public void mouseEntered(MouseEvent e) {}
@Override public void mouseClicked(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {
popup.hide();
pane.removeHyperlinkListener(hll);
removeActionKey(pane,JPanel.WHEN_IN_FOCUSED_WINDOW,SwingUtils.KS_EXIT,SwingUtils.ACTION_EXIT);
pane.removeMouseListener(this);
}
});
pane.addHyperlinkListener(hll);
popup.show();
}
}
/**
* <p>Calculate location of left-top corner for the window to fit in into screen.</p>
* @param xPosition x-coordinate of window anchor in the screen coordinates (for example, mouse hot spot)
* @param yPosition y-coordinate of window anchor in the screen coordinates (for example, mouse hot spot)
* @param popupWidth width of the window to fit
* @param popupHeight height of the window to fit
* @return left-top location of the window in the screen coordinates. If any moving is not required, returns window anchor coordinates
* @since 0.0.3
*/
public static Point locateRelativeToAnchor(final int xPosition, final int yPosition, final int popupWidth, final int popupHeight) {
final Point popupLocation = new Point(xPosition, yPosition);
if(GraphicsEnvironment.isHeadless()) {
return popupLocation;
}
final GraphicsConfiguration gc = getCurrentGraphicsConfiguration(popupLocation);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Rectangle scrBounds = gc != null ? gc.getBounds() : new Rectangle(toolkit.getScreenSize());
final long popupRightX = (long)popupLocation.x + (long)popupWidth;
final long popupBottomY = (long)popupLocation.y + (long)popupHeight;
final Insets scrInsets = toolkit.getScreenInsets(gc);
int scrWidth = scrBounds.width;
int scrHeight = scrBounds.height;
scrBounds.x += scrInsets.left;
scrBounds.y += scrInsets.top;
scrWidth -= scrInsets.left + scrInsets.right;
scrHeight -= scrInsets.top + scrInsets.bottom;
int scrRightX = scrBounds.x + scrWidth;
int scrBottomY = scrBounds.y + scrHeight;
if (popupRightX > (long) scrRightX) {
popupLocation.x = scrRightX - popupWidth;
}
if (popupBottomY > (long) scrBottomY) {
popupLocation.y = scrBottomY - popupHeight;
}
if (popupLocation.x < scrBounds.x) {
popupLocation.x = scrBounds.x;
}
if (popupLocation.y < scrBounds.y) {
popupLocation.y = scrBounds.y;
}
return popupLocation;
}
private static GraphicsConfiguration getCurrentGraphicsConfiguration(final Point popupLocation) {
final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice[] gd = ge.getScreenDevices();
for(int i = 0; i < gd.length; i++) {
if(gd[i].getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
final GraphicsConfiguration dgc = gd[i].getDefaultConfiguration();
if(dgc.getBounds().contains(popupLocation)) {
return dgc;
}
}
}
return gd[0].getDefaultConfiguration();
}
private static class MethodHandleAndAsync {
final MethodHandle handle;
final boolean async;
public MethodHandleAndAsync(MethodHandle handle, boolean async) {
this.handle = handle;
this.async = async;
}
}
private static void toMenuEntity(final ContentNodeMetadata node, final JMenuBar bar) throws NullPointerException, IllegalArgumentException{
if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_NODE_PREFIX)) {
final JMenu menu = new JMenuWithMeta(node);
for (ContentNodeMetadata child : node) {
toMenuEntity(child,menu);
}
buildRadioButtonGroups(menu);
bar.add(menu);
}
else if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_LEAF_PREFIX)) {
bar.add(new JMenuItemWithMeta(node));
}
}
private static void toMenuEntity(final ContentNodeMetadata node, final JPopupMenu popup) throws NullPointerException, IllegalArgumentException{
if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_NODE_PREFIX)) {
final JMenu menu = new JMenuWithMeta(node);
for (ContentNodeMetadata child : node) {
toMenuEntity(child,menu);
}
buildRadioButtonGroups(menu);
popup.add(menu);
}
else if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_LEAF_PREFIX)) {
popup.add(new JMenuItemWithMeta(node));
}
else if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_SEPARATOR)) {
popup.add(new JSeparator());
}
}
private static void buildRadioButtonGroups(final JMenu menu) {
final Set<String> availableGroups = new HashSet<>();
for (int index = 0, maxIndex = menu.getMenuComponentCount(); index < maxIndex; index++) {
if (menu.getMenuComponent(index) instanceof JRadioMenuItemWithMeta) {
availableGroups.add(((JRadioMenuItemWithMeta)menu.getMenuComponent(index)).getRadioGroup());
}
}
if (availableGroups.size() > 0) {
for (String group : availableGroups) {
final ButtonGroup buttonGroup = new ButtonGroup();
ButtonModel buttonModel = null;
for (int index = 0, maxIndex = menu.getMenuComponentCount(); index < maxIndex; index++) {
Component c = menu.getMenuComponent(index);
if ((c instanceof JRadioMenuItemWithMeta) && group.equals(((JRadioMenuItemWithMeta)c).getRadioGroup())) {
buttonGroup.add((JRadioMenuItemWithMeta)c);
if (buttonModel == null) {
buttonModel = ((JRadioMenuItemWithMeta)c).getModel();
}
}
}
if (buttonModel != null) {
buttonGroup.setSelected(buttonModel,true);
}
}
}
}
private static void toMenuEntity(final ContentNodeMetadata node, final JMenu menu) throws NullPointerException, IllegalArgumentException{
if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_NODE_PREFIX)) {
final JMenu submenu = new JMenuWithMeta(node);
if (node.getApplicationPath() != null && node.getApplicationPath().toString().contains(Constants.MODEL_APPLICATION_SCHEME_BUILTIN_ACTION)) {
switch (node.getName()) {
case Constants.MODEL_BUILTIN_LANGUAGE :
final String currentLang = Locale.getDefault().getLanguage();
final ButtonGroup langGroup = new ButtonGroup();
AbstractLocalizer.enumerateLocales((lang,langName,icon)->{
final JRadioButtonMenuItem radio = new JRadioButtonMenuItem(langName,icon);
radio.setActionCommand("action:/"+Constants.MODEL_BUILTIN_LANGUAGE+"?lang="+lang.name());
if (currentLang.equals(lang.toString())) { // Mark current lang
radio.setSelected(true);
}
langGroup.add(radio);
submenu.add(radio);
});
menu.add(submenu);
break;
case Constants.MODEL_BUILTIN_LAF :
final String currentLafDesc = UIManager.getLookAndFeel().getName();
final ButtonGroup lafGroup = new ButtonGroup();
for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
try{final String clazzName = laf.getClassName();
final Class<?> clazz = Class.forName(clazzName);
final JRadioButtonMenuItem radio = new JRadioButtonMenuItem(clazz.getSimpleName());
radio.setActionCommand("action:/"+Constants.MODEL_BUILTIN_LAF+"?laf="+clazzName);
radio.setToolTipText(laf.getName());
if (currentLafDesc.equals(laf.getName())) { // Mark current L&F
radio.setSelected(true);
}
lafGroup.add(radio);
submenu.add(radio);
} catch (ClassNotFoundException e) {
}
}
menu.add(submenu);
break;
default : throw new UnsupportedOperationException("Built-in name ["+node.getName()+"] is not suported yet");
}
}
else {
for (ContentNodeMetadata child : node) {
toMenuEntity(child,submenu);
}
buildRadioButtonGroups(submenu);
menu.add(submenu);
}
}
else if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_LEAF_PREFIX)) {
if (node.getApplicationPath().getFragment() != null) {
final JRadioMenuItemWithMeta item = new JRadioMenuItemWithMeta(node);
menu.add(item);
}
else {
final JMenuItemWithMeta item = new JMenuItemWithMeta(node);
menu.add(item);
}
}
else if (node.getRelativeUIPath().getPath().startsWith("./"+Constants.MODEL_NAVIGATION_SEPARATOR)) {
menu.add(new JSeparator());
}
}
private static class JMenuBarWithMeta extends JMenuBar implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = 2873312186080690483L;
private final ContentNodeMetadata metadata;
private JMenuBarWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.setName(metadata.getName());
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
for (int index = 0, maxIndex = this.getMenuCount(); index < maxIndex; index++) {
final JMenu item = this.getMenu(index);
if (item instanceof LocaleChangeListener) {
((LocaleChangeListener)item).localeChanged(oldLocale, newLocale);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
final String ttId = getNodeMetadata().getTooltipId();
if (ttId != null && !ttId.isEmpty()) {
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(ttId));
}
}
}
private static class JMenuPopupWithMeta extends JPopupMenu implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = 2873312186080690483L;
private final ContentNodeMetadata metadata;
private JMenuPopupWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.setName(metadata.getName());
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
for (int index = 0, maxIndex = this.getComponentCount(); index < maxIndex; index++) {
final Component item = this.getComponent(index);
if (item instanceof LocaleChangeListener) {
((LocaleChangeListener)item).localeChanged(oldLocale, newLocale);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
final String ttId = getNodeMetadata().getTooltipId();
if (ttId != null && !ttId.isEmpty()) {
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(ttId));
}
}
}
private static class JMenuItemWithMeta extends JMenuItem implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = -1731094524456032387L;
private final ContentNodeMetadata metadata;
private JMenuItemWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.setName(metadata.getName());
this.setActionCommand(metadata.getApplicationPath().getSchemeSpecificPart());
for (ContentNodeMetadata item : metadata.getOwner().byApplicationPath(metadata.getApplicationPath())) {
if (item.getRelativeUIPath().toString().startsWith("./keyset.key")) {
this.setAccelerator(KeyStroke.getKeyStroke(item.getLabelId()));
break;
}
}
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
setText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getLabelId()));
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getTooltipId()));
}
}
private static class JRadioMenuItemWithMeta extends JRadioButtonMenuItem implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = -1731094524456032387L;
private final ContentNodeMetadata metadata;
private final String radioGroup;
private JRadioMenuItemWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.radioGroup = metadata.getApplicationPath().getFragment();
this.setName(metadata.getName());
this.setActionCommand(metadata.getApplicationPath().getSchemeSpecificPart());
for (ContentNodeMetadata item : metadata.getOwner().byApplicationPath(metadata.getApplicationPath())) {
if (item.getRelativeUIPath().toString().startsWith("./keyset.key")) {
this.setAccelerator(KeyStroke.getKeyStroke(item.getLabelId()));
break;
}
}
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
public String getRadioGroup() {
return radioGroup;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
setText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getLabelId()));
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getTooltipId()));
}
}
private static class JMenuWithMeta extends JMenu implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = 366031204608808220L;
private final ContentNodeMetadata metadata;
private JMenuWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.setName(metadata.getName());
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
for (int index = 0, maxIndex = this.getMenuComponentCount(); index < maxIndex; index++) {
final Component item = this.getMenuComponent(index);
if (item instanceof LocaleChangeListener) {
((LocaleChangeListener)item).localeChanged(oldLocale, newLocale);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
setText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getLabelId()));
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getTooltipId()));
}
}
private static class JToolBarWithMeta extends JToolBar implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = 366031204608808220L;
private final ContentNodeMetadata metadata;
private JToolBarWithMeta(final ContentNodeMetadata metadata) {
this.metadata = metadata;
this.setName(metadata.getName());
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
if (getNodeMetadata().getTooltipId() != null) {
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getTooltipId()));
}
}
}
private static class JButtonWithMeta extends JButton implements NodeMetadataOwner, LocaleChangeListener {
private static final long serialVersionUID = 366031204608808220L;
protected enum LAFType {
TEXT_ONLY, ICON_INLY, BOTH, ICON_THEN_TEXT
}
private final ContentNodeMetadata metadata;
private final LAFType type;
private JButtonWithMeta(final ContentNodeMetadata metadata) {
this(metadata,LAFType.BOTH);
}
private JButtonWithMeta(final ContentNodeMetadata metadata, final LAFType type) {
this.metadata = metadata;
this.type = type;
this.setName(metadata.getName());
this.setActionCommand(metadata.getApplicationPath() != null ? metadata.getApplicationPath().getSchemeSpecificPart() : "action:/"+metadata.getName());
try{fillLocalizedStrings();
} catch (IOException | LocalizationException e) {
e.printStackTrace();
}
}
@Override
public ContentNodeMetadata getNodeMetadata() {
return metadata;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
try{fillLocalizedStrings();
} catch (IOException e) {
e.printStackTrace();
}
}
private void fillLocalizedStrings() throws LocalizationException, IOException {
if (getNodeMetadata().getTooltipId() != null) {
setToolTipText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getTooltipId()));
}
switch (type) {
case BOTH :
if (getNodeMetadata().getIcon() != null) {
setIcon(new ImageIcon(getNodeMetadata().getIcon().toURL()));
}
setText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getLabelId()));
break;
case ICON_INLY :
if (getNodeMetadata().getIcon() != null) {
setIcon(new ImageIcon(getNodeMetadata().getIcon().toURL()));
}
break;
case ICON_THEN_TEXT :
if (getNodeMetadata().getIcon() != null) {
setIcon(new ImageIcon(getNodeMetadata().getIcon().toURL()));
break;
}
// break doesn't need!
case TEXT_ONLY :
setText(LocalizerFactory.getLocalizer(getNodeMetadata().getLocalizerAssociated()).getValue(getNodeMetadata().getLabelId()));
break;
default:
throw new UnsupportedOperationException("LAF type ["+type+"] is not supported yet");
}
}
}
private static class JButtonWithMetaAndActions extends JButtonWithMeta implements InnerActionNode {
private static final long serialVersionUID = 366031204608808220L;
private final JComponent[] actionable;
private JButtonWithMetaAndActions(final ContentNodeMetadata metadata, final JComponent... actionable) {
super(metadata);
this.actionable = actionable;
}
private JButtonWithMetaAndActions(final ContentNodeMetadata metadata, final LAFType type, final JComponent... actionable) {
super(metadata,type);
this.actionable = actionable;
}
@Override
public JComponent[] getActionNodes() {
return actionable;
}
@Override
public void localeChanged(final Locale oldLocale, final Locale newLocale) throws LocalizationException {
super.localeChanged(oldLocale, newLocale);
for (JComponent item : getActionNodes()) {
SwingUtils.refreshLocale(item,oldLocale, newLocale);
}
}
}
}
|
package eu.toolchain.async;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import eu.toolchain.async.caller.DirectAsyncCaller;
/**
* A high-level integration test for {@code TinyAsync#eventuallyCollect(java.util.Collection, StreamCollector, int)}.
*/
public class ThreadedEventuallyCollectTest {
private ExecutorService executor;
private ExecutorService otherExecutor;
private AsyncFramework async;
private AtomicLong internalErrors;
private static final long COUNT = 1000;
private static final long EXPECTED_SUM = COUNT;
private static final int PARALLELISM = 4;
private static final long TIMEOUT = 500;
@Before
public void setup() {
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 4);
otherExecutor = Executors.newFixedThreadPool(10);
internalErrors = new AtomicLong();
async = TinyAsync.builder().executor(executor).caller(new DirectAsyncCaller() {
@Override
protected void internalError(String what, Throwable e) {
internalErrors.incrementAndGet();
}
}).build();
}
@After
public void teardown() throws InterruptedException {
executor.shutdown();
executor.awaitTermination(100, TimeUnit.MILLISECONDS);
otherExecutor.shutdown();
otherExecutor.awaitTermination(100, TimeUnit.MILLISECONDS);
}
@Test(timeout = TIMEOUT)
public void testBasic() throws Exception {
int attempt = 0;
while (attempt++ < 10) {
final List<Callable<AsyncFuture<Long>>> callables = new ArrayList<>();
final AtomicInteger pending = new AtomicInteger();
final AtomicInteger called = new AtomicInteger();
for (long i = 0; i < COUNT; i++) {
callables.add(new Callable<AsyncFuture<Long>>() {
@Override
public AsyncFuture<Long> call() throws Exception {
pending.incrementAndGet();
return async.call(new Callable<Long>() {
@Override
public Long call() throws Exception {
if (pending.decrementAndGet() >= PARALLELISM)
throw new IllegalStateException("bad stuff");
called.incrementAndGet();
return 1l;
}
}, otherExecutor);
}
});
}
final AsyncFuture<Long> res = async.eventuallyCollect(callables, new StreamCollector<Long, Long>() {
final AtomicLong sum = new AtomicLong();
@Override
public void resolved(Long result) throws Exception {
sum.addAndGet(result);
}
@Override
public void failed(Throwable cause) throws Exception {
}
@Override
public void cancelled() throws Exception {
}
@Override
public Long end(int resolved, int failed, int cancelled) throws Exception {
return sum.get();
}
}, PARALLELISM);
assertEquals(EXPECTED_SUM, (long) res.get());
assertEquals(COUNT, called.get());
}
}
@Test(timeout = TIMEOUT)
public void testRandomFailuresAndCancel() throws InterruptedException, ExecutionException {
int attempt = 0;
final Random r = new Random(0xffaa0000);
final AtomicLong expectedInternalErrors = new AtomicLong();
while (attempt++ < 10) {
final List<Callable<AsyncFuture<Long>>> callables = new ArrayList<>();
final AtomicInteger pending = new AtomicInteger();
for (long i = 0; i < COUNT; i++) {
callables.add(new Callable<AsyncFuture<Long>>() {
@Override
public AsyncFuture<Long> call() throws Exception {
pending.incrementAndGet();
final AsyncFuture<Long> f = async.call(new Callable<Long>() {
@Override
public Long call() throws Exception {
if (r.nextInt(2) == 1)
throw new RuntimeException("failure");
return 1l;
}
}, otherExecutor);
if (r.nextInt(2) == 1)
f.cancel();
if (r.nextInt(2) == 1)
throw new RuntimeException("die");
return f;
}
});
}
final AsyncFuture<Long> res = async.eventuallyCollect(callables, new StreamCollector<Long, Long>() {
@Override
public void resolved(Long result) throws Exception {
if (r.nextInt(2) == 1) {
expectedInternalErrors.incrementAndGet();
throw new RuntimeException("die");
}
}
@Override
public void failed(Throwable cause) throws Exception {
if (r.nextInt(2) == 1) {
expectedInternalErrors.incrementAndGet();
throw new RuntimeException("die");
}
}
@Override
public void cancelled() throws Exception {
if (r.nextInt(2) == 1) {
expectedInternalErrors.incrementAndGet();
throw new RuntimeException("die");
}
}
@Override
public Long end(int resolved, int failed, int cancelled) throws Exception {
return (long) (resolved + failed + cancelled);
}
}, PARALLELISM);
assertEquals(COUNT, (long) res.get());
assertEquals(expectedInternalErrors.get(), internalErrors.get());
}
}
}
|
package org.scy.common.manager;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class SchedulerManager {
private Logger logger = LoggerFactory.getLogger(SchedulerManager.class);
private Scheduler scheduler;
private static SchedulerManager schedulerManager;
/**
* {@link #getInstance()}
*/
private SchedulerManager() {
try {
scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
}
catch (Exception e) {
e.printStackTrace();
logger.error("" + e.getMessage());
}
}
public static SchedulerManager getInstance() {
if (schedulerManager == null) {
synchronized (SchedulerManager.class) {
if (schedulerManager == null)
schedulerManager = new SchedulerManager();
}
}
return schedulerManager;
}
/**
* Cron
* @param cronExpression Cron
* @return Cron
*/
public static Trigger newCronTrigger(String cronExpression) {
return newCronTrigger(cronExpression, false);
}
/**
* Cron
* @param cronExpression Cron
* @param startNow
* @return Cron
*/
public static Trigger newCronTrigger(String cronExpression, boolean startNow) {
TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cronExpression));
if (startNow)
triggerBuilder.startNow();
return triggerBuilder.build();
}
/**
*
* @param jobCls
* @param trigger
* @return
*/
public String addScheduleJob(Class<? extends Job> jobCls, Trigger trigger) {
return addScheduleJob(jobCls, trigger, new HashMap<String, Object>());
}
/**
*
* @param jobCls
* @param data
* @return
*/
public String addScheduleJob(Class<? extends Job> jobCls, Trigger trigger, Map<String, Object> data) {
if (this.scheduler == null)
return null;
if (jobCls == null || trigger == null) {
logger.error("");
}
else {
String jobName = jobCls.getName() + "." + (new Date()).getTime();
JobBuilder jobBuilder = JobBuilder.newJob(jobCls);
jobBuilder.withIdentity(jobName, Scheduler.DEFAULT_GROUP);
jobBuilder.setJobData(new JobDataMap(data));
JobDetail jobDetail = jobBuilder.build();
try {
this.scheduler.scheduleJob(jobDetail, trigger);
}
catch (SchedulerException e) {
logger.error("" + e.getMessage());
}
return jobName;
}
return null;
}
public abstract static class MyJob implements Job {
/**
*
* @param jobExecutionContext
* @throws JobExecutionException
*/
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
this.executeJob(jobExecutionContext.getJobDetail().getJobDataMap());
}
/**
*
* @param data
* @throws JobExecutionException
*/
protected abstract void executeJob(JobDataMap data) throws JobExecutionException;
}
public abstract static class ThreadJob extends MyJob implements Runnable {
private Logger logger = LoggerFactory.getLogger(ThreadJob.class);
protected JobExecutionContext context;
private Thread currentThread;
/**
*
* @param jobExecutionContext
* @throws JobExecutionException
*/
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
this.context = jobExecutionContext;
if (!this.isRunning()) {
currentThread = new Thread(this);
currentThread.start();
}
}
public final void run() {
try {
this.executeJob(context.getJobDetail().getJobDataMap());
}
catch (JobExecutionException e) {
logger.error("", e);
}
currentThread = null;
}
private boolean isRunning() {
return currentThread != null && currentThread.isAlive();
}
}
}
|
package backtype.storm.coordination;
import backtype.storm.topology.FailedException;
import java.util.Map.Entry;
import backtype.storm.tuple.Values;
import backtype.storm.generated.GlobalStreamId;
import java.util.Collection;
import backtype.storm.Constants;
import backtype.storm.generated.Grouping;
import backtype.storm.task.IOutputCollector;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.utils.TimeCacheMap;
import backtype.storm.utils.Utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import static backtype.storm.utils.Utils.get;
/**
* Coordination requires the request ids to be globally unique for awhile. This is so it doesn't get confused
* in the case of retries.
*/
public class CoordinatedBolt implements IRichBolt {
public static Logger LOG = Logger.getLogger(CoordinatedBolt.class);
public static interface FinishedCallback {
void finishedId(Object id);
}
public static interface TimeoutCallback {
void timeoutId(Object id);
}
public static class SourceArgs implements Serializable {
public boolean singleCount;
protected SourceArgs(boolean singleCount) {
this.singleCount = singleCount;
}
public static SourceArgs single() {
return new SourceArgs(true);
}
public static SourceArgs all() {
return new SourceArgs(false);
}
@Override
public String toString() {
return "<Single: " + singleCount + ">";
}
}
public class CoordinatedOutputCollector implements IOutputCollector {
IOutputCollector _delegate;
public CoordinatedOutputCollector(IOutputCollector delegate) {
_delegate = delegate;
}
public List<Integer> emit(String stream, Collection<Tuple> anchors, List<Object> tuple) {
List<Integer> tasks = _delegate.emit(stream, anchors, tuple);
updateTaskCounts(tuple.get(0), tasks);
return tasks;
}
public void emitDirect(int task, String stream, Collection<Tuple> anchors, List<Object> tuple) {
updateTaskCounts(tuple.get(0), Arrays.asList(task));
_delegate.emitDirect(task, stream, anchors, tuple);
}
public void ack(Tuple tuple) {
Object id = tuple.getValue(0);
synchronized(_tracked) {
TrackingInfo track = _tracked.get(id);
if (track != null)
track.receivedTuples++;
}
boolean failed = checkFinishId(tuple, TupleType.REGULAR);
if(failed) {
_delegate.fail(tuple);
} else {
_delegate.ack(tuple);
}
}
public void fail(Tuple tuple) {
Object id = tuple.getValue(0);
synchronized(_tracked) {
TrackingInfo track = _tracked.get(id);
if (track != null)
track.failed = true;
}
checkFinishId(tuple, TupleType.REGULAR);
_delegate.fail(tuple);
}
public void reportError(Throwable error) {
_delegate.reportError(error);
}
private void updateTaskCounts(Object id, List<Integer> tasks) {
synchronized(_tracked) {
TrackingInfo track = _tracked.get(id);
if (track != null) {
Map<Integer, Integer> taskEmittedTuples = track.taskEmittedTuples;
for(Integer task: tasks) {
int newCount = get(taskEmittedTuples, task, 0) + 1;
taskEmittedTuples.put(task, newCount);
}
}
}
}
}
private Map<String, SourceArgs> _sourceArgs;
private IdStreamSpec _idStreamSpec;
private IRichBolt _delegate;
private Integer _numSourceReports;
private List<Integer> _countOutTasks = new ArrayList<Integer>();;
private OutputCollector _collector;
private TimeCacheMap<Object, TrackingInfo> _tracked;
public static class TrackingInfo {
int reportCount = 0;
int expectedTupleCount = 0;
int receivedTuples = 0;
boolean failed = false;
Map<Integer, Integer> taskEmittedTuples = new HashMap<Integer, Integer>();
boolean receivedId = false;
boolean finished = false;
List<Tuple> ackTuples = new ArrayList<Tuple>();
@Override
public String toString() {
return "reportCount: " + reportCount + "\n" +
"expectedTupleCount: " + expectedTupleCount + "\n" +
"receivedTuples: " + receivedTuples + "\n" +
"failed: " + failed + "\n" +
taskEmittedTuples.toString();
}
}
public static class IdStreamSpec implements Serializable {
GlobalStreamId _id;
public GlobalStreamId getGlobalStreamId() {
return _id;
}
public static IdStreamSpec makeDetectSpec(String component, String stream) {
return new IdStreamSpec(component, stream);
}
protected IdStreamSpec(String component, String stream) {
_id = new GlobalStreamId(component, stream);
}
}
public CoordinatedBolt(IRichBolt delegate) {
this(delegate, null, null);
}
public CoordinatedBolt(IRichBolt delegate, String sourceComponent, SourceArgs sourceArgs, IdStreamSpec idStreamSpec) {
this(delegate, singleSourceArgs(sourceComponent, sourceArgs), idStreamSpec);
}
public CoordinatedBolt(IRichBolt delegate, Map<String, SourceArgs> sourceArgs, IdStreamSpec idStreamSpec) {
_sourceArgs = sourceArgs;
if(_sourceArgs==null) _sourceArgs = new HashMap<String, SourceArgs>();
_delegate = delegate;
_idStreamSpec = idStreamSpec;
}
public void prepare(Map config, TopologyContext context, OutputCollector collector) {
TimeCacheMap.ExpiredCallback<Object, TrackingInfo> callback = null;
if(_delegate instanceof TimeoutCallback) {
callback = new TimeoutItems();
}
_tracked = new TimeCacheMap<Object, TrackingInfo>(context.maxTopologyMessageTimeout(), callback);
_collector = collector;
_delegate.prepare(config, context, new OutputCollector(new CoordinatedOutputCollector(collector)));
for(String component: Utils.get(context.getThisTargets(),
Constants.COORDINATED_STREAM_ID,
new HashMap<String, Grouping>())
.keySet()) {
for(Integer task: context.getComponentTasks(component)) {
_countOutTasks.add(task);
}
}
if(!_sourceArgs.isEmpty()) {
_numSourceReports = 0;
for(Entry<String, SourceArgs> entry: _sourceArgs.entrySet()) {
if(entry.getValue().singleCount) {
_numSourceReports+=1;
} else {
_numSourceReports+=context.getComponentTasks(entry.getKey()).size();
}
}
}
}
private boolean checkFinishId(Tuple tup, TupleType type) {
Object id = tup.getValue(0);
boolean failed = false;
synchronized(_tracked) {
TrackingInfo track = _tracked.get(id);
try {
if(track!=null) {
boolean delayed = false;
if(_idStreamSpec==null && type == TupleType.COORD || _idStreamSpec!=null && type==TupleType.ID) {
track.ackTuples.add(tup);
delayed = true;
}
if(track.failed) {
failed = true;
for(Tuple t: track.ackTuples) {
_collector.fail(t);
}
_tracked.remove(id);
} else if(track.receivedId
&& (_sourceArgs.isEmpty() ||
track.reportCount==_numSourceReports &&
track.expectedTupleCount == track.receivedTuples)){
if(_delegate instanceof FinishedCallback) {
((FinishedCallback)_delegate).finishedId(id);
}
if(!(_sourceArgs.isEmpty() || type!=TupleType.REGULAR)) {
throw new IllegalStateException("Coordination condition met on a non-coordinating tuple. Should be impossible");
}
Iterator<Integer> outTasks = _countOutTasks.iterator();
while(outTasks.hasNext()) {
int task = outTasks.next();
int numTuples = get(track.taskEmittedTuples, task, 0);
_collector.emitDirect(task, Constants.COORDINATED_STREAM_ID, tup, new Values(id, numTuples));
}
for(Tuple t: track.ackTuples) {
_collector.ack(t);
}
track.finished = true;
_tracked.remove(id);
}
if(!delayed && type!=TupleType.REGULAR) {
if(track.failed) {
_collector.fail(tup);
} else {
_collector.ack(tup);
}
}
} else {
if(type!=TupleType.REGULAR) _collector.fail(tup);
}
} catch(FailedException e) {
LOG.error("Failed to finish batch", e);
for(Tuple t: track.ackTuples) {
_collector.fail(t);
}
_tracked.remove(id);
failed = true;
}
}
return failed;
}
public void execute(Tuple tuple) {
Object id = tuple.getValue(0);
TrackingInfo track;
TupleType type = getTupleType(tuple);
synchronized(_tracked) {
track = _tracked.get(id);
if(track==null) {
track = new TrackingInfo();
if(_idStreamSpec==null) track.receivedId = true;
_tracked.put(id, track);
}
}
if(type==TupleType.ID) {
synchronized(_tracked) {
track.receivedId = true;
}
checkFinishId(tuple, type);
} else if(type==TupleType.COORD) {
int count = (Integer) tuple.getValue(1);
synchronized(_tracked) {
track.reportCount++;
track.expectedTupleCount+=count;
}
checkFinishId(tuple, type);
} else {
synchronized(_tracked) {
_delegate.execute(tuple);
}
}
}
public void cleanup() {
_delegate.cleanup();
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
_delegate.declareOutputFields(declarer);
declarer.declareStream(Constants.COORDINATED_STREAM_ID, true, new Fields("id", "count"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
return _delegate.getComponentConfiguration();
}
private static Map<String, SourceArgs> singleSourceArgs(String sourceComponent, SourceArgs sourceArgs) {
Map<String, SourceArgs> ret = new HashMap<String, SourceArgs>();
ret.put(sourceComponent, sourceArgs);
return ret;
}
private class TimeoutItems implements TimeCacheMap.ExpiredCallback<Object, TrackingInfo> {
@Override
public void expire(Object id, TrackingInfo val) {
synchronized(_tracked) {
// the combination of the lock and the finished flag ensure that
// an id is never timed out if it has been finished
val.failed = true;
if(!val.finished) {
((TimeoutCallback) _delegate).timeoutId(id);
}
}
}
}
private TupleType getTupleType(Tuple tuple) {
if(_idStreamSpec!=null
&& tuple.getSourceGlobalStreamid().equals(_idStreamSpec._id)) {
return TupleType.ID;
} else if(!_sourceArgs.isEmpty()
&& tuple.getSourceStreamId().equals(Constants.COORDINATED_STREAM_ID)) {
return TupleType.COORD;
} else {
return TupleType.REGULAR;
}
}
static enum TupleType {
REGULAR,
ID,
COORD
}
}
|
package org.support.project.web.logic;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.directory.api.ldap.model.cursor.Cursor;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.exception.InvalidConnectionException;
import org.support.project.common.config.INT_FLAG;
import org.support.project.common.log.Log;
import org.support.project.common.log.LogFactory;
import org.support.project.common.util.PasswordUtil;
import org.support.project.common.util.StringUtils;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.web.bean.LdapInfo;
import org.support.project.web.entity.LdapConfigsEntity;
@DI(instance = Instance.Singleton)
public class LdapLogic {
private static final Log LOG = LogFactory.getLog(LdapLogic.class);
/**
* Get instance
*
* @return instance
*/
public static LdapLogic get() {
return Container.getComp(LdapLogic.class);
}
/**
* Ldap
*
* @param entity entity
* @param id id
* @param password password
* @return LdapInfo
* @throws IOException IOException
* @throws LdapException LdapException
*/
public LdapInfo auth(LdapConfigsEntity entity, String id, String password) throws IOException, LdapException {
if (entity.getAuthType() == LdapConfigsEntity.AUTH_TYPE_LDAP || entity.getAuthType() == LdapConfigsEntity.AUTH_TYPE_BOTH) {
return ldapLogin1(entity, id, password);
} else if (entity.getAuthType() == LdapConfigsEntity.AUTH_TYPE_LDAP_2 || entity.getAuthType() == LdapConfigsEntity.AUTH_TYPE_BOTH_2) {
return ldapLogin2(entity, id, password);
}
return null;
}
public boolean check(LdapConfigsEntity entity) throws LdapException, IOException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost(entity.getHost()); // LDAP Host
config.setLdapPort(entity.getPort()); // LDAP Port
if (entity.getUseSsl() != null && entity.getUseSsl().intValue() == INT_FLAG.ON.getValue()) {
config.setUseSsl(true); // Use SSL
} else if (entity.getUseTls() != null && entity.getUseTls().intValue() == INT_FLAG.ON.getValue()) {
config.setUseTls(true); // USE TLS
}
LdapConnection conn = null;
Cursor<Entry> cursor = null;
try {
String pass = entity.getBindPassword();
if (StringUtils.isNotEmpty(entity.getSalt())) {
pass = PasswordUtil.decrypt(pass, entity.getSalt());
}
conn = new LdapNetworkConnection(config);
conn.bind(entity.getBindDn(), pass); // Bind DN //Bind Password (
return true;
} catch (LdapException e) {
return false;
} finally {
if (cursor != null) {
cursor.close();
}
if (conn != null) {
conn.unBind();
conn.close();
}
}
}
/**
* Ldap
*
* LdapDN ldapLogin1BASE DN
*
* @param entity entity
* @param id id
* @param password password
* @return LdapInfo
* @throws LdapException LdapException
* @throws IOException IOException
*/
private LdapInfo ldapLogin2(LdapConfigsEntity entity, String id, String password) throws LdapException, IOException {
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost(entity.getHost()); // LDAP Host
config.setLdapPort(entity.getPort()); // LDAP Port
if (entity.getUseSsl() != null && entity.getUseSsl().intValue() == INT_FLAG.ON.getValue()) {
config.setUseSsl(true); // Use SSL
} else if (entity.getUseTls() != null && entity.getUseTls().intValue() == INT_FLAG.ON.getValue()) {
config.setUseTls(true); // USE TLS
}
LdapConnection conn = null;
LdapConnection conn2 = null;
Cursor<Entry> cursor = null;
try {
conn = new LdapNetworkConnection(config);
String pass = entity.getBindPassword();
if (StringUtils.isNotEmpty(entity.getSalt())) {
pass = PasswordUtil.decrypt(pass, entity.getSalt());
}
try {
conn.bind(entity.getBindDn(), pass); // Bind DN //Bind Password (
} catch (InvalidConnectionException e) {
LOG.error(e);
// (LDAP
return null;
}
String base = entity.getBaseDn(); // Base DN
String filter = entity.getFilter(); // filter (user id)
filter = filter.replace(":userid", id);
SearchScope scope = SearchScope.SUBTREE;
cursor = conn.search(base, filter, scope);
String dn = null;
while (cursor.next()) {
Entry entry = cursor.get();
dn = entry.getDn().toString();
break;
}
if (StringUtils.isEmpty(dn)) {
return null;
}
conn2 = new LdapNetworkConnection(config);
conn2.bind(dn, password); // Bind DN //Bind Password (
cursor = conn2.search(base, filter, scope);
LdapInfo info = null;
while (cursor.next()) {
Entry entry = cursor.get();
info = loadLdapInfo(entity, entry);
break;
}
return info;
} catch (LdapException | CursorException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
| BadPaddingException e) {
return null;
} finally {
if (cursor != null) {
cursor.close();
}
if (conn != null && conn.isConnected()) {
conn.unBind();
conn.close();
}
if (conn2 != null && conn2.isConnected()) {
conn2.unBind();
conn2.close();
}
}
}
/*
* LdapLogin
* BASE DN Knowledge 0.5.3
* ldapLogin2
*/
@Deprecated
private LdapInfo ldapLogin1(LdapConfigsEntity entity, String id, String password) throws LdapException, IOException {
LdapConnectionConfig config = new LdapConnectionConfig();
config.setLdapHost(entity.getHost()); // LDAP Host
config.setLdapPort(entity.getPort()); // LDAP Port
if (entity.getUseSsl() != null && entity.getUseSsl().intValue() == INT_FLAG.ON.getValue()) {
config.setUseSsl(true); // Use SSL
} else if (entity.getUseTls() != null && entity.getUseTls().intValue() == INT_FLAG.ON.getValue()) {
config.setUseTls(true); // USE TLS
}
LdapConnection conn = null;
Cursor<Entry> cursor = null;
try {
conn = new LdapNetworkConnection(config);
StringBuilder bindDn = new StringBuilder();
bindDn.append(entity.getIdAttr()).append("=").append(id);
if (StringUtils.isNotEmpty(entity.getBaseDn())) {
bindDn.append(",").append(entity.getBaseDn());
}
try {
conn.bind(bindDn.toString(), password);
} catch (InvalidConnectionException e) {
LOG.error(e);
// (LDAP
return null;
}
String base = entity.getBaseDn(); // Base DN
StringBuilder filter = new StringBuilder();
filter.append("(").append(entity.getIdAttr()).append("=").append(id).append(")");
SearchScope scope = SearchScope.SUBTREE;
cursor = conn.search(base, filter.toString(), scope);
while (cursor.next()) {
Entry entry = cursor.get();
LdapInfo info = loadLdapInfo(entity, entry);
return info;
}
return null;
} catch (LdapException | CursorException e) {
return null;
} finally {
if (cursor != null) {
cursor.close();
}
if (conn != null && conn.isConnected()) {
conn.unBind();
conn.close();
}
}
}
private LdapInfo loadLdapInfo(LdapConfigsEntity entity, Entry entry) throws LdapInvalidAttributeValueException {
LdapInfo info = new LdapInfo();
info.setId(entry.get(entity.getIdAttr()).getString());
if (StringUtils.isNotEmpty(entity.getNameAttr())) {
if (entry.get(entity.getNameAttr()) != null) {
info.setName(entry.get(entity.getNameAttr()).getString());
}
}
if (StringUtils.isNotEmpty(entity.getMailAttr())) {
if (entry.get(entity.getMailAttr()) != null) {
info.setMail(entry.get(entity.getMailAttr()).getString());
}
}
if (StringUtils.isNotEmpty(entity.getAdminCheckFilter())) {
String[] adminids = entity.getAdminCheckFilter().split(",");
for (String string : adminids) {
if (info.getId().equals(string.trim())) {
info.setAdmin(true);
break;
}
}
}
return info;
}
}
|
package cn.edu.seu.kse.lpmln.util;
import cn.edu.seu.kse.lpmln.app.LPMLNApp;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author
* @date 2018/1/15
*/
public class FileHelper {
public static List<File> tempFiles = new ArrayList<>();
public static void cleanFiles(){
if(LPMLNApp.iskeeptranslation){
tempFiles.forEach(file -> {
if(file.getName().endsWith(".tmp")){
file.delete();
}
});
}else{
tempFiles.forEach(File::delete);
}
}
public static File randomFile(){
return new File(UUID.randomUUID()+".tmp");
}
/**
* .tmpcleanFilesiskeeptranslation
* @param file
* @param out
*/
public static void writeFile(File file, String out){
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"))){
tempFiles.add(file);
if(!file.exists()){
file.getParentFile().mkdirs();
}
bw.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* \r\n
* @param file
* @return
*/
public static String getFileContent(File file){
StringBuilder result = new StringBuilder();
String line;
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"))) {
while ((line = br.readLine())!=null){
result.append(line).append("\r\n");
}
}catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
|
package org.yidu.novel.action;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.BeanUtils;
import org.yidu.novel.action.base.AbstractPublicListBaseAction;
import org.yidu.novel.bean.ArticleSearchBean;
import org.yidu.novel.cache.ArticleCountManager;
import org.yidu.novel.cache.CacheManager;
import org.yidu.novel.constant.YiDuConfig;
import org.yidu.novel.constant.YiDuConstants;
import org.yidu.novel.entity.TArticle;
import org.yidu.novel.utils.Utils;
@Action(value = "articleList")
public class ArticleListAction extends AbstractPublicListBaseAction {
private static final long serialVersionUID = -4215796997609788238L;
public static final String NAME = "articleList";
/**
* URL
*/
public static final String URL = NAMESPACE + "/" + NAME;
private int category;
private int page;
private String author;
private Boolean fullflag;
private List<TArticle> articleList = new ArrayList<TArticle>();
/**
* category
*
* @return category
*/
public int getCategory() {
return category;
}
/**
*
* category
*
*
* @param category
* category
*/
public void setCategory(int category) {
this.category = category;
}
/**
* page
*
* @return page
*/
public int getPage() {
return page;
}
/**
*
* page
*
*
* @param page
* page
*/
public void setPage(int page) {
this.page = page;
}
/**
* author
*
* @return author
*/
public String getAuthor() {
return author;
}
/**
*
* author
*
*
* @param author
* author
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* fullflag
*
* @return fullflag
*/
public Boolean getFullflag() {
return fullflag;
}
/**
*
* fullflag
*
*
* @param fullflag
* fullflag
*/
public void setFullflag(Boolean fullflag) {
this.fullflag = fullflag;
}
/**
* articleList
*
* @return articleList
*/
public List<TArticle> getArticleList() {
return articleList;
}
/**
*
* articleList
*
*
* @param articleList
* articleList
*/
public void setArticleList(List<TArticle> articleList) {
this.articleList = articleList;
}
@Override
public String getTempName() {
return "articleList";
}
@Override
protected void loadData() {
logger.debug("loadData start.");
ArticleSearchBean searchBean = new ArticleSearchBean();
BeanUtils.copyProperties(this, searchBean);
searchBean.setPageType(ArticleSearchBean.PageType.publicPage);
pagination.setPageNumber(page == 0 ? 1 : page);
pagination.setSortColumn(TArticle.PROP_LASTUPDATE);
pagination.setSortOrder("DESC");
int count = 0;
if (YiDuConstants.yiduConf.getBoolean(YiDuConfig.ENABLE_CACHE_ARTICLE_COUNT, false)) {
if (category != 0) {
count = ArticleCountManager.getArticleCount(String.valueOf(category));
} else if (StringUtils.isNotEmpty(author)) {
count = ArticleCountManager.getArticleCount("author");
} else if (fullflag != null && fullflag) {
count = ArticleCountManager.getArticleCount("fullflag");
} else {
count = ArticleCountManager.getArticleCount("all");
}
} else {
Object countInfo = CacheManager.getObject(CacheManager.CacheKeyPrefix.CACHE_KEY_ARTICEL_LIST_COUNT_PREFIX,
searchBean);
if (countInfo == null) {
count = articleService.getCount(searchBean);
CacheManager.putObject(CacheManager.CacheKeyPrefix.CACHE_KEY_ARTICEL_LIST_COUNT_PREFIX, searchBean,
count);
} else {
count = Integer.parseInt(countInfo.toString());
}
}
pagination.setPreperties(count);
searchBean.setPagination(pagination);
articleList = CacheManager.getObject(CacheManager.CacheKeyPrefix.CACHE_KEY_ARTICEL_LIST_PREFIX, searchBean);
if (!Utils.isDefined(articleList)) {
articleList = articleService.find(searchBean);
CacheManager.putObject(CacheManager.CacheKeyPrefix.CACHE_KEY_ARTICEL_LIST_PREFIX, searchBean, articleList);
}
logger.debug("normally end.");
}
@Override
public int getPageType() {
return YiDuConstants.Pagetype.PAGE_ARTICLE_LIST;
}
@Override
protected String getBlockKey() {
return CacheManager.CacheKeyPrefix.CACHE_KEY_CATEGORY_LIST_BLOCK;
}
@Override
protected Short getBlockTarget() {
return YiDuConstants.BlockTarget.ARTICLE_LIST;
}
}
|
package pitt.search.semanticvectors;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod;
import pitt.search.semanticvectors.utils.VerbatimLogger;
import pitt.search.semanticvectors.vectors.Vector;
import pitt.search.semanticvectors.vectors.ZeroVectorException;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Logger;
/**
* Command line term vector search utility.
*/
public class SearchBatch {
private static final Logger logger = Logger.getLogger(SearchBatch.class.getCanonicalName());
/**
* Different types of searches that can be performed, set using {@link FlagConfig#searchtype()}.
*
* <p>Most involve processing combinations of vectors in different ways, in
* building a query expression, scoring candidates against these query
* expressions, or both. Most options here correspond directly to a particular
* subclass of {@link VectorSearcher}.
*
* <p>Names may be passed as command-line arguments, so underscores are avoided.
* */
public enum SearchType {
/**
* Build a query by adding together (weighted) vectors for each of the query
* terms, and search using cosine similarity.
* See {@link VectorSearcher.VectorSearcherCosine}.
* This is the default search option.
*/
SUM,
/**
* "Quantum disjunction" - get vectors for each query term, create a
* representation for the subspace spanned by these vectors, and score by
* measuring cosine similarity with this subspace.
* Uses {@link VectorSearcher.VectorSearcherSubspaceSim}.
*/
SUBSPACE,
/**
* "Closest disjunction" - get vectors for each query term, score by measuring
* distance to each term and taking the minimum.
* Uses {@link VectorSearcher.VectorSearcherMaxSim}.
*/
MAXSIM,
/**
* "Farthest conjunction" - get vectors for each query term, score by measuring
* distance to each term and taking the maximum.
* Uses {@link VectorSearcher.VectorSearcherMaxSim}.
*/
MINSIM,
/**
* Uses permutation of coordinates to model typed relationships, as
* introduced by Sahlgren at al. (2008).
*
* <p>Searches for the term that best matches the position of a "?" in a sequence of terms.
* For example <code>martin ? king</code> should retrieve <code>luther</code> as the top ranked match.
*
* <p>Requires {@link FlagConfig#queryvectorfile()} to contain
* unpermuted vectors, either random vectors or previously learned term vectors,
* and {@link FlagConfig#searchvectorfile()} must contain permuted learned vectors.
*
* <p>Uses {@link VectorSearcher.VectorSearcherPerm}.
*/
PERMUTATION,
/**
* This is a variant of the {@link SearchType#PERMUTATION} method which
* takes the mean of the two possible search directions (search
* with index vectors for permuted vectors, or vice versa).
* Uses {@link VectorSearcher.VectorSearcherPerm}.
*/
BALANCEDPERMUTATION,
/**
* Used for Predication Semantic Indexing, see {@link PSI}.
* Uses {@link VectorSearcher.VectorSearcherBoundProduct}.
*/
BOUNDPRODUCT,
/**
* Lucene document search, for comparison.
*
*/
LUCENE,
/**
* Used for Predication Semantic Indexing, see {@link PSI}.
* Finds minimum similarity across query terms to seek middle terms
*/
BOUNDMINIMUM,
/**
* Binds vectors to facilitate search across multiple relationship paths.
* Uses {@link VectorSearcher.VectorSearcherBoundProductSubSpace}
*/
BOUNDPRODUCTSUBSPACE,
/**
* Intended to support searches of the form A is to B as C is to ?, but
* hasn't worked well thus far. (dwiddows, 2013-02-03).
*/
ANALOGY,
/**
* Builds an additive query vector (as with {@link SearchType#SUM} and prints out the query
* vector for debugging).
*/
PRINTQUERY
}
private static LuceneUtils luceneUtils;
public static String usageMessage = "\nSearch class in package pitt.search.semanticvectors"
+ "\nUsage: java pitt.search.semanticvectors.Search [-queryvectorfile query_vector_file]"
+ "\n [-searchvectorfile search_vector_file]"
+ "\n [-luceneindexpath path_to_lucene_index]"
+ "\n [-searchtype TYPE]"
+ "\n <QUERYTERMS>"
+ "\nIf no query or search file is given, default will be"
+ "\n termvectors.bin in local directory."
+ "\n-luceneindexpath argument is needed if to get term weights from"
+ "\n term frequency, doc frequency, etc. in lucene index."
+ "\n-searchtype can be one of SUM, SUBSPACE, MAXSIM, MINSIM"
+ "\n BALANCEDPERMUTATION, PERMUTATION, PRINTQUERY"
+ "\n<QUERYTERMS> should be a list of words, separated by spaces."
+ "\n If the term NOT is used, terms after that will be negated.";
/**
* Takes a user's query, creates a query vector, and searches a vector store.
* @param flagConfig configuration object for controlling the search
* @return list containing search results.
*/
public static void runSearch(FlagConfig flagConfig)
throws IllegalArgumentException {
/**
* The runSearch function has four main stages:
* i. Check flagConfig for null (but so far fails to check other dependencies).
* ii. Open corresponding vector and lucene indexes.
* iii. Based on search type, build query vector and perform search.
* iv. Return LinkedList of results, usually for main() to print out.
*/
// Stage i. Check flagConfig for null, and there being at least some remaining query terms.
if (flagConfig == null) {
throw new NullPointerException("flagConfig cannot be null");
}
if (flagConfig.remainingArgs == null) {
throw new IllegalArgumentException("No query terms left after flag parsing!");
}
String[] queryArgs = flagConfig.remainingArgs;
/** Principal vector store for finding query vectors. */
VectorStore queryVecReader = null;
/** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */
VectorStore boundVecReader = null;
/** Auxiliary vector stores used when searching for boundproducts. Used only in some searchtypes. */
VectorStore elementalVecReader = null, semanticVecReader = null, predicateVecReader = null;
/**
* Vector store for searching. Defaults to being the same as queryVecReader.
* May be different from queryVecReader, e.g., when using terms to search for documents.
*/
VectorStore searchVecReader = null;
// Stage ii. Open vector stores, and Lucene utils.
try {
// Default VectorStore implementation is (Lucene) VectorStoreReader.
if (!flagConfig.elementalvectorfile().equals("elementalvectors") && !flagConfig.semanticvectorfile().equals("semanticvectors") && !flagConfig.elementalpredicatevectorfile().equals("predicatevectors")) {
//for PSI search
VerbatimLogger.info("Opening elemental query vector store from file: " + flagConfig.elementalvectorfile() + "\n");
VerbatimLogger.info("Opening semantic query vector store from file: " + flagConfig.semanticvectorfile() + "\n");
VerbatimLogger.info("Opening predicate query vector store from file: " + flagConfig.elementalpredicatevectorfile() + "\n");
if (flagConfig.elementalvectorfile().equals("deterministic")) {
if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.ORTHOGRAPHIC))
elementalVecReader = new VectorStoreOrthographical(flagConfig);
else if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH))
elementalVecReader = new VectorStoreDeterministic(flagConfig);
else
VerbatimLogger.info("Please select either -elementalmethod orthographic OR -elementalmethod contenthash depending upon the deterministic approach you would like used.");
} else {
elementalVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) elementalVecReader).initFromFile(flagConfig.elementalvectorfile());
}
semanticVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) semanticVecReader).initFromFile(flagConfig.semanticvectorfile());
predicateVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) predicateVecReader).initFromFile(flagConfig.elementalpredicatevectorfile());
} else {
VerbatimLogger.info("Opening query vector store from file: " + flagConfig.queryvectorfile() + "\n");
if (flagConfig.queryvectorfile().equals("deterministic")) {
if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.ORTHOGRAPHIC))
queryVecReader = new VectorStoreOrthographical(flagConfig);
else if (flagConfig.elementalmethod().equals(ElementalGenerationMethod.CONTENTHASH))
queryVecReader = new VectorStoreDeterministic(flagConfig);
else
VerbatimLogger.info("Please select either -elementalmethod orthographic OR -elementalmethod contenthash depending upon the deterministic approach you would like used.");
} else {
queryVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) queryVecReader).initFromFile(flagConfig.queryvectorfile());
}
}
if (flagConfig.boundvectorfile().length() > 0) {
VerbatimLogger.info("Opening second query vector store from file: " + flagConfig.boundvectorfile() + "\n");
boundVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) boundVecReader).initFromFile(flagConfig.boundvectorfile());
}
// Open second vector store if search vectors are different from query vectors.
if (flagConfig.queryvectorfile().equals(flagConfig.searchvectorfile())
|| flagConfig.searchvectorfile().isEmpty()) {
searchVecReader = queryVecReader;
} else {
VerbatimLogger.info("Opening search vector store from file: " + flagConfig.searchvectorfile() + "\n");
searchVecReader = new VectorStoreRAM(flagConfig);
((VectorStoreRAM) searchVecReader).initFromFile(flagConfig.searchvectorfile());
}
if (!flagConfig.luceneindexpath().isEmpty()) {
try {
luceneUtils = new LuceneUtils(flagConfig);
} catch (IOException e) {
logger.warning("Couldn't open Lucene index at " + flagConfig.luceneindexpath()
+ ". Will continue without term weighting.");
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader queryReader = new BufferedReader(new FileReader(new File(queryArgs[0])));
String queryString = queryReader.readLine();
int qcnt = 0;
while (queryString != null) {
ArrayList<String> queryTerms = new ArrayList<String>();
qcnt++;
if (!flagConfig.searchtype().equals(pitt.search.semanticvectors.Search.SearchType.ANALOGY))
{ //have Lucene parse the query string, for consistency
StandardAnalyzer analyzer = new StandardAnalyzer(new CharArraySet(new ArrayList<String>(), true));
TokenStream stream = analyzer.tokenStream(null, new StringReader(queryString));
CharTermAttribute cattr = stream.addAttribute(CharTermAttribute.class);
stream.reset();
//for each token in the query string
while (stream.incrementToken())
{
String term = cattr.toString();
if ((luceneUtils != null && !luceneUtils.stoplistContains(term)) || luceneUtils == null)
{
if (! flagConfig.matchcase()) term = term.toLowerCase();
queryTerms.add(term);
}
}
stream.end();
stream.close();
analyzer.close();
}
else
queryTerms.add(queryString);
//transform to String[] array
queryArgs = queryTerms.toArray(new String[0]);
// Stage iii. Perform search according to which searchType was selected.
// Most options have corresponding dedicated VectorSearcher subclasses.
VectorSearcher vecSearcher = null;
LinkedList<SearchResult> results;
String[] splitArgs = null;
boolean allTermsRepresented = true;
VerbatimLogger.info("Searching term vectors, searchtype " + flagConfig.searchtype() + "\n");
try {
switch (flagConfig.searchtype()) {
case SUM:
vecSearcher = new VectorSearcher.VectorSearcherCosine(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case SUBSPACE:
vecSearcher = new VectorSearcher.VectorSearcherSubspaceSim(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case MAXSIM:
vecSearcher = new VectorSearcher.VectorSearcherMaxSim(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case MINSIM:
vecSearcher = new VectorSearcher.VectorSearcherMinSim(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case BOUNDPRODUCT:
if (queryArgs.length == 2) {
vecSearcher = new VectorSearcher.VectorSearcherBoundProduct(
queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0], queryArgs[1]);
} else {
vecSearcher = new VectorSearcher.VectorSearcherBoundProduct(
elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]);
}
break;
case BOUNDPRODUCTSUBSPACE:
if (queryArgs.length == 2) {
vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace(
queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0], queryArgs[1]);
} else {
vecSearcher = new VectorSearcher.VectorSearcherBoundProductSubSpace(
elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]);
}
break;
case BOUNDMINIMUM:
if (queryArgs.length == 2) {
vecSearcher = new VectorSearcher.VectorSearcherBoundMinimum(
queryVecReader, boundVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0], queryArgs[1]);
} else {
vecSearcher = new VectorSearcher.VectorSearcherBoundMinimum(
elementalVecReader, semanticVecReader, predicateVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs[0]);
}
break;
case PERMUTATION:
vecSearcher = new VectorSearcher.VectorSearcherPerm(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case BALANCEDPERMUTATION:
vecSearcher = new VectorSearcher.BalancedVectorSearcherPerm(
queryVecReader, searchVecReader, luceneUtils, flagConfig, queryArgs);
break;
case ANALOGY:
splitArgs = queryArgs[0].split(" ");
for (String searchTerm : splitArgs)
if (!queryVecReader.containsVector(searchTerm)) allTermsRepresented = false;
vecSearcher = new VectorSearcher.AnalogySearcher(
queryVecReader, searchVecReader, luceneUtils, flagConfig, splitArgs);
break;
case LUCENE:
vecSearcher = new VectorSearcher.VectorSearcherLucene(
luceneUtils, flagConfig, queryArgs);
break;
case PRINTQUERY:
Vector queryVector = CompoundVectorBuilder.getQueryVector(
queryVecReader, luceneUtils, flagConfig, queryArgs);
System.out.println(queryVector.toString());
break;
default:
throw new IllegalArgumentException("Unknown search type: " + flagConfig.searchtype());
}
} catch (ZeroVectorException zve) {
logger.info(zve.getMessage());
}
results = new LinkedList<SearchResult>();
try {
if (!allTermsRepresented) System.out.println("0: Missing term(s)");
else results = vecSearcher.getNearestNeighbors(flagConfig.numsearchresults());
} catch (Exception e) {
//no search results returned
}
int cnt = 0;
// Print out results.
if (results.size() > 0) {
VerbatimLogger.info("Search output follows ...\n");
for (SearchResult result : results) {
boolean printResult = true;
if (flagConfig.searchtype() == Search.SearchType.ANALOGY) //don't output cue terms
{
for (String searchTerm : splitArgs) {
if (result.getObjectVector().getObject().toString().equals(searchTerm))
printResult = false;
}
}
if (printResult) {
if (flagConfig.treceval() != -1) //results in trec_eval format
{
System.out.println(
String.format("%s\t%s\t%s\t%s\t%f\t%s",
qcnt,
"Q0",
result.getObjectVector().getObject().toString(),
++cnt,
result.getScore(),
"DEFAULT")
);
} else System.out.println( //results in cosine:object format
String.format("%f:%s",
result.getScore(),
result.getObjectVector().getObject().toString()));
if (flagConfig.searchtype() == Search.SearchType.ANALOGY) {
break;
}
}
}
}
queryString = queryReader.readLine();
}
queryReader.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IllegalArgumentException, IOException {
FlagConfig flagConfig;
try {
flagConfig = FlagConfig.getFlagConfig(args);
runSearch(flagConfig);
} catch (IllegalArgumentException e) {
System.err.println(usageMessage);
throw e;
}
}
}
|
package utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import controllers.Application;
import models.Query;
import models.Shapefile;
import org.mapdb.*;
import org.opentripplanner.analyst.Histogram;
import org.opentripplanner.analyst.ResultSet;
import play.Play;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* A datastore optimized for storing query results.
* This is not a MapDB: it uses one flat file per variable (since you're only ever looking at one variable at a time),
* which is then encoded like this:
*
* Header: QUERYRESULT encoded as UTF
* Query ID encoded as UTF
* Variable name encoded as UTF
* Envelope parameter encoded as a UTF.
* Repeated:
* Feature ID encoded as string
* int number of counts (also number of sums)
* counts encoded as ints
* sums encoded as ints
*/
public class QueryResultStore {
public final boolean readOnly;
private List<String> attributes;
private File outDir;
private String queryId;
/** cache filewriters */
private Map<Fun.Tuple2<String, ResultEnvelope.Which>, FileWriter> writerCache = Maps.newHashMap();
/** we need to keep references to these because we need to close them */
private Collection<FileReader> readerCache = Lists.newArrayList();
public QueryResultStore (Query q) {
this.readOnly = q.completePoints == q.totalPoints;
this.queryId = q.id;
outDir = new File(Play.application().configuration().getString("application.data"), "flat_results");
outDir.mkdirs();
}
/** Save a result envelope in this store */
public void store(ResultEnvelope res) {
if (readOnly)
throw new UnsupportedOperationException("Attempt to write to read-only query result store!");
for (ResultEnvelope.Which which : ResultEnvelope.Which.values()) {
ResultSet rs = res.get(which);
if (rs != null) {
// parallelize across variables, which are stored in different files, so this is threadsafe
rs.histograms.entrySet().parallelStream().forEach(e -> {
getWriter(e.getKey(), which).write(res.id, e.getValue());
});
}
}
}
private FileWriter getWriter(String variable, ResultEnvelope.Which which) {
Fun.Tuple2<String, ResultEnvelope.Which> wkey = new Fun.Tuple2<>(variable, which);
if (!writerCache.containsKey(wkey)) {
synchronized (writerCache) {
if (!writerCache.containsKey(wkey)) {
String filename = String.format(Locale.US, "%s_%s_%s.results.gz", queryId, variable, which);
writerCache.put(wkey, new FileWriter(new File(outDir, filename), queryId, variable, which));
}
}
}
return writerCache.get(wkey);
}
/** close the underlying datastore, writing all changes to disk */
public void close () {
for (FileWriter w : writerCache.values()) {
w.close();
}
for (FileReader reader : readerCache) {
reader.close();
}
}
/** get all the resultsets for a particular variable and envelope parameter */
public Iterator<ResultSet> getAll(String attr, ResultEnvelope.Which which) {
String filename = String.format(Locale.US, "%s_%s_%s.results.gz", queryId, attr, which);
// cannot return a cached reader as each one has a pointer into the file
FileReader r = new FileReader(new File(outDir, filename));
readerCache.add(r);
return r;
}
/** Write resultsets to a flat file */
private static class FileWriter {
private final DataOutputStream out;
public FileWriter(File file, String queryId, String variable, ResultEnvelope.Which which) {
try {
OutputStream os = new FileOutputStream(file);
GZIPOutputStream gos = new GZIPOutputStream(os);
// buffer for performance
BufferedOutputStream bos = new BufferedOutputStream(gos);
out = new DataOutputStream(bos);
out.writeUTF("QUERYRESULT");
out.writeUTF(queryId);
out.writeUTF(variable);
out.writeUTF(which.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public synchronized void write (String id, Histogram histogram) {
if (id == null)
throw new NullPointerException("Feature ID is null!");
if (histogram.counts.length != histogram.sums.length)
throw new IllegalArgumentException("Invalid histogram, sum and count lengths differ");
try {
out.writeUTF(id);
out.writeInt(histogram.counts.length);
for (int i = 0; i < histogram.counts.length; i++) {
// TODO: zigzag encoding
// These are marginals so they are already effectively delta-coded
out.writeInt(histogram.counts[i]);
}
for (int i = 0; i < histogram.sums.length; i++) {
out.writeInt(histogram.sums[i]);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close () {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/** read resultsets from a flat file */
private static class FileReader implements Iterator<ResultSet> {
private DataInputStream in;
private String var;
public final String queryId;
public final ResultEnvelope.Which which;
public FileReader(File file) {
try {
InputStream is = new FileInputStream(file);
GZIPInputStream gis = new GZIPInputStream(is);
BufferedInputStream bis = new BufferedInputStream(gis);
in = new DataInputStream(bis);
// make sure we have a query result file, and record variable name
String header = in.readUTF();
if (!"QUERYRESULT".equals(header))
throw new IllegalArgumentException("Attempt to read non-query-result file");
queryId = in.readUTF();
var = in.readUTF();
which = ResultEnvelope.Which.valueOf(in.readUTF());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean hasNext() {
// this cannot be the easiest way to tell if we're at the end of the file
in.mark(8192);
try {
in.readUTF();
} catch (EOFException e) {
this.close();
return false;
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
in.reset();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
@Override
public ResultSet next() {
if (!hasNext())
throw new NoSuchElementException();
try {
ResultSet rs = new ResultSet();
// read the ID
rs.id = in.readUTF();
// number of bins in the histogram
int size = in.readInt();
int[] counts = new int[size];
for (int i = 0; i < size; i++) {
counts[i] = in.readInt();
}
int[] sums = new int[size];
for (int i = 0; i < size; i++) {
sums[i] = in.readInt();
}
Histogram h = new Histogram();
h.sums = sums;
h.counts = counts;
rs.histograms.put(var, h);
return rs;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void forEachRemaining(Consumer<? super ResultSet> consumer) {
while (hasNext())
consumer.accept(next());
}
public void close () {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
package gov.nih.nci.calab.ui.submit;
/**
* This class sets up input form for size characterization.
*
* @author pansu
*/
/* CVS $Id: NanoparticleSizeAction.java,v 1.24 2007-06-04 21:29:09 pansu Exp $ */
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.ui.core.BaseCharacterizationAction;
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 org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class NanoparticleSizeAction extends BaseCharacterizationAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName=theForm.getString("particleName");
String particleType=theForm.getString("particleType");
CharacterizationBean charBean = super.prepareCreate(request, theForm);
SubmitNanoparticleService service = new SubmitNanoparticleService();
service.addParticleSize(particleType, particleName, charBean);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addParticleSize");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
return forward;
}
protected void setLoadFileRequest(HttpServletRequest request) {
request.setAttribute("characterization", "size");
request.setAttribute("loadFileForward", "sizeInputForm");
}
@Override
//TODO delete this
protected void setFormCharacterizationBean(DynaValidatorForm theForm, Characterization aChar) throws Exception {
// TODO Auto-generated method stub
}
}
|
package mightypork.rogue;
/**
* Application constants
*
* @author MightyPork
*/
public final class Const {
// STRINGS
public static final int VERSION = 2;
public static final String APP_NAME = "Rogue";
public static final String TITLEBAR = APP_NAME + " v." + VERSION;
// AUDIO
public static final int FPS_RENDER = 120; // max
// INITIAL WINDOW SIZE
public static final int WINDOW_W = 1024;
public static final int WINDOW_H = 768;
}
|
package fs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.NotDirectoryException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Disk {
public final static char ZERO = '0';
/**
* The file where the disk is stored.
*/
private final File file;
/**
* List of available sectors.
*/
private final List<Sector> availableSectors;
/**
* The root node of the file system tree.
*/
private final Tree<Node> root;
/**
* The current directory node in the file system.
*/
private Tree<Node> current;
/**
* The size of a single sector. Amount of characters that a sector can hold.
*/
private final int sectorSize;
/**
* The amount of sectors in the disk.
*/
private final int sectorAmount;
/**
* Create a new disk.
*
* @param path The path where the disk will be write.
* @param sectorAmount The amount of sectors of the disk.
* @param sectorSize The size of a single sector.
*/
public Disk(String path, int sectorAmount, int sectorSize) {
SectorBuilder builder = new SectorBuilder();
this.file = new File(path);
this.sectorSize = sectorSize;
this.sectorAmount = sectorAmount;
this.root = new Tree<>(new Node(""));
this.availableSectors = builder.create(this.sectorAmount);
this.current = root;
if (file.exists()) {
file.delete();
}
writeZeros();
}
/**
* Change the current directory.
*
* @param path Path of the new directory
* @throws java.io.FileNotFoundException If the file doesn't exists.
* @throws java.nio.file.NotDirectoryException If the path isn't a
* directory.
*/
public void changeCurrentDirectory(String path) throws FileNotFoundException, NotDirectoryException {
Tree<Node> actual = searchTree(path);
if (actual == null) {
throw new FileNotFoundException("File not found");
}
if (!actual.getData().isDirectory()) {
throw new NotDirectoryException("The path is not a directory");
}
current = actual;
}
/**
* Check if a file or directory exists;
*
* @param path The file or directory path.
* @return true if a file or directory exists;
*/
public boolean exists(String path) {
return searchTree(path) != null;
}
/**
* Get the content of a file.
*
* @param path The path of the file.
* @return The file content.
* @throws java.io.IOException if an I/O error occurs reading the file.
*/
public String getFileContent(String path) throws IOException {
Node node = searchNode(path);
if(node == null)
{
throw new FileNotFoundException("File not found");
}
return node.getContent(file, sectorSize);
}
/**
* Change the content of a file.
*
* @param path The path of the file.
* @param content The new content.
* @throws java.io.IOException if an I/O error occurs writing to the file.
*/
public void changeFileContent(String path, String content) throws IOException {
Node node = searchNode(path);
if (node == null) {
throw new FileNotFoundException("File not found");
}
List<Sector> sectors = node.getSectors();
int required = requiredSectors(content);
int shortage = required - sectors.size();
if (shortage > availableSectors.size()) {
throw new IOException("Insufficient disk space");
}
if (shortage >= 0) {
sectors.addAll( getSectors(shortage) );
}
else {
Sector sector;
for (int i = shortage; i < 0; i++) {
sector = sectors.remove(0);
availableSectors.add(sector);
writeZeros(sector);
}
}
writeToSectors(sectors, content);
}
/**
* Create a new file.
*
* @param path The path where the file will be created.
* @param content The content to write in the file.
* @throws java.io.IOException if an I/O error occurs writing to or creating
* the file.
*/
public void createFile(String path, String content) throws IOException, Exception {
if (!FileUtils.isValidPath(path)) {
throw new MalformedURLException("Invalid file name");
}
if (exists(path)) {
throw new FileAlreadyExistsException("File already exists");
}
String fileName = FileUtils.getFileName(path);
String directory = FileUtils.getDirectory(path);
Tree<Node> parent = searchTree(directory);
if (parent == null || !parent.getData().isDirectory()) {
throw new FileNotFoundException("Directory '" + directory + "' doesn't exists");
}
int required = requiredSectors(content);
if (required > availableSectors.size()) {
throw new IOException("Insufficient disk space");
}
List<Sector> sectors = getSectors(required);
Node node = new Node(fileName, sectors);
writeToSectors(sectors, content);
parent.add(node);
}
/**
* Delete a file.
*
* @param path The path of the file.
* @throws java.io.IOException if an I/O error occurs deleting the file.
*/
public void deleteFile(String path) throws IOException {
Tree<Node> tree = searchTree(path);
if (tree == null)
{
throw new FileNotFoundException("File not found.");
}
if(tree.isLeaf())
{
deleteTree(tree);
}
}
/**
* Create a new directory.
*
* @param path The path where the directory will be created.
* @throws java.io.IOException if an I/O error occurs creating the
* directory.
*/
public void createDirectory(String path) throws IOException, Exception {
if (!FileUtils.isValidPath(path)) {
throw new MalformedURLException("Invalid directory name");
}
if (exists(path)) {
throw new FileAlreadyExistsException("Directory already exist");
}
String[] array = path.split("/");
String name = array[array.length - 1];
String directory = path.substring(0, path.lastIndexOf("/"));
Tree<Node> parent = searchTree(directory);
if (parent == null || !parent.getData().isDirectory()) {
throw new FileNotFoundException("Directory '" + directory + "' doesn't exist");
}
Node node = new Node(name);
parent.add(node);
}
/**
* Delete a directory.
*
* @param path The path of the directory.
* @throws java.io.FileNotFoundException If the file doesn't exists.
* @throws java.io.IOException if an I/O error occurs deleting the
* directory.
*/
public void deleteDirectory(String path) throws IOException {
Tree<Node> tree = searchTree(path);
if (tree == null) {
throw new FileNotFoundException("Directory doesn't exist");
}
if (tree.isRoot()) {
throw new AccessDeniedException("Root folder cannot be deleted");
}
deleteTree(tree);
}
/**
* Change a file location.
*
* @param oldPath The path of the file.
* @param newPath The new path of the file.
* @throws java.io.IOException if an I/O error occurs moving the file.
*/
public void moveFile(String oldPath, String newPath) throws IOException {
Tree<Node> node = searchTree(oldPath);
if (node == null) {
throw new FileNotFoundException("File doesn't exist");
}
String fileName = FileUtils.getFileName(newPath);
String directory = FileUtils.getDirectory(newPath);
Tree<Node> newDir = searchTree(directory);
if (newDir == null) {
throw new FileNotFoundException("Directory '" + directory + "' doesn't exist");
}
node.setParent(newDir);
if (!fileName.isEmpty()) {
node.getData().setName(fileName);
}
}
/**
* Get the files and directories in a directory.
*
* @param directory The path of the directory.
* @return The list of children of the directory. Null if the node is not a directory.
* @throws java.io.FileNotFoundException If the file doesn't exists.
* @throws java.io.IOException if an I/O error occurs reading the directory.
*/
public List<Node> getFiles(String directory) throws IOException
{
Tree treeNode = searchTree(directory);
List<Node> nodesList = new ArrayList();
if(treeNode == null)
{
throw new FileNotFoundException("Directory not found.");
}
if(((Node)treeNode.getData()).isDirectory())
{
for(Tree tree : (List<Tree<Node>>)treeNode.children())
{
nodesList.add((Node)tree.getData());
}
return nodesList;
}
return nodesList;
}
/**
* Get the files that satisfies certain regex in a directory.
*
* @param directory The path of the directory.
* @param regex The regular expression.
* @return The list of children of the directory.
* @throws java.io.IOException if an I/O error occurs reading the directory.
*/
public List<Node> getFiles(String directory, String regex) throws IOException
{
Tree<Node> treeNode = searchTree(directory);
List<Node> nodesList = new ArrayList();
if(treeNode == null)
{
throw new FileNotFoundException("Directory not found.");
}
if(treeNode.getData().isDirectory())
{
for(Tree<Node> tree : treeNode.children())
{
if(tree.getData().getName().contains(regex))
{
nodesList.add(tree.getData());
}
}
return nodesList;
}
return nodesList;
}
/**
* Get the file system tree.
*
* @return The file system tree.
*/
public Tree<Node> getTree() {
return root;
}
/**
* Search a subtree in the current directory or in the root. If the path
* starts with '/' the search will start in the root, otherwise if will
* start in the current directory.
*
* @param path The path to search.
* @return The subtree if found, otherwise null.
*/
private Tree<Node> searchTree(String path) {
String[] array = path.split("/");
Tree<Node> actual = current;
boolean changed;
Node node;
if (path.isEmpty()) {
return current;
}
if (path.startsWith("/")) {
actual = root;
}
for (String curr : array) {
changed = false;
for (Tree<Node> child : actual.children()) {
node = child.getData();
if (node.getName().equals(curr)) {
actual = child;
changed = true;
break;
}
}
if (!changed) {
return null;
}
}
return actual;
}
/**
* Search a node in the current directory or in the root. If the path starts
* with '/' the search will start in the root, otherwise if will start in
* the current directory.
*
* @param path The path to search.
* @return The node if found, otherwise null.
*/
private Node searchNode(String path) {
Tree<Node> actual = searchTree(path);
return actual != null ? actual.getData() : null;
}
/**
* Delete a tree in the file system from memory and disk
*
* @param tree The tree to delete.
*/
private void deleteTree(Tree<Node> tree) {
if(!tree.isRoot())
{
List<Sector> sectors = tree.getData().getSectors();
for(Sector sector : sectors)
{
writeZeros(sector);
}
root.remove(tree.getData());
}
}
/**
* Calculate the amount of sectors required to store a string in disk.
*
* @param content The string to store.
* @return The required sectors.
*/
private int requiredSectors(String content) {
if (content.isEmpty()) {
return 0;
} else {
return (int) Math.ceil((double) content.length() / (double) sectorSize);
}
}
/**
* Remove and return n sectors from the list of available sectors.
*
* @param count The number of sectors to remove.
* @return The sectors.
*/
private List<Sector> getSectors(int count) {
List<Sector> sectors = new ArrayList<>();
for (int i = 0; i < count; i++) {
sectors.add(availableSectors.remove(0));
}
return sectors;
}
/**
* Write a string to a file in the given sectors.
*
* @param sectors The sectors.
* @param content The content to write.
* @return true if no errors occurs.
*/
private boolean writeToSectors(List<Sector> sectors, String content) {
File temp = new File("disk.temp");
try (InputStream in = new FileInputStream(file)) {
try (OutputStream out = new FileOutputStream(temp)) {
Writer writer = new OutputStreamWriter(out);
Reader reader = new InputStreamReader(in);
String chunk = "";
int c; /* The current character */
int i = 0; /* The current sector */
int j = 0; /* The current chunk */
while ((c = reader.read()) != -1) {
chunk += (char) c;
if (chunk.length() == sectorSize) {
if (sectors.contains(new Sector(i))) {
chunk = StringUtils.substring(content, j * sectorSize, (j+1) * sectorSize);
chunk = StringUtils.fill(chunk, ZERO, sectorSize);
j++;
}
writer.write(chunk);
chunk = "";
i++;
}
}
writer.flush();
}
}
catch (IOException ex) {
return false;
}
file.delete();
temp.renameTo(file);
return true;
}
/**
* Delete the content of the entire disk.
*/
private boolean writeZeros() {
String text = StringUtils.repeat(Disk.ZERO, sectorSize * sectorAmount);
try (OutputStream out = new FileOutputStream(file)) {
Writer writer = new OutputStreamWriter(out);
writer.write(text);
writer.flush();
return true;
}
catch (IOException ex) {
return false;
}
}
/**
* Delete the content of a sector.
*
* @param sector The sector.
*/
private boolean writeZeros(Sector sector) {
List<Sector> list = new ArrayList<>();
list.add(sector);
String text = StringUtils.repeat(Disk.ZERO, sectorSize);
return writeToSectors(list, text);
}
/**
* Copies a file with real path to a virtual path.
*
* @param origin The real path.
* @param destination The virtual path.
*/
private void realToVirtual(String origin, String destination)
{
File originFile = new File(origin);
try
{
if(originFile.isDirectory())
{
Tree<Node> parent = searchTree(destination);
if(parent == null || !parent.getData().isDirectory())
{
throw new FileNotFoundException("Directory '" + destination + "' doesn't exist");
}
String[] nodesList = originFile.getPath().split(File.pathSeparator);
for(String nodeName : nodesList)
{
Node child = new Node(nodeName);
parent.add(child);
}
}
RandomAccessFile raf = new RandomAccessFile(originFile, "r");
byte[] bytes = null;
raf.readFully(bytes);
String content = new String(bytes);
createFile(destination, content);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Disk.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger(Disk.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex)
{
Logger.getLogger(Disk.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Copies a file with virtual path to a real path.
*
* @param origin The real path.
* @param destination The virtual path.
*/
private void virtualToReal(String origin, String destination) throws FileNotFoundException
{
Tree<Node> tree = searchTree(origin);
if(tree == null)
{
throw new FileNotFoundException("File '" + origin + "' doesn't exist");
}
byte[] content = null;
if(tree.getData().isDirectory())
{
List<Tree<Node>> nodesList = tree.children();
if(nodesList.isEmpty())
{
createRealFile(destination, null);
return;
}
for(Tree treeNode : nodesList)
{
Node node = (Node)treeNode.getData();
if(node.isDirectory())
{
origin += "/" + node.getName() + "/";
}
else
{
content = node.getContent(file, sectorSize).getBytes();
createRealFile(destination + node.getName(), content);
}
}
}
else
{
content = tree.getData().getContent(file, sectorSize).getBytes();
createRealFile(destination + tree.getData().getName(), content);
}
}
/**
* Creates a file (can be a directory also) in the real file system.
*
* @param destination The destination path,
* @param content The content of the file.
*/
private void createRealFile(String destination, byte[] content)
{
try
{
File fileOut = new File(destination);
if(!fileOut.exists())
{
fileOut.mkdir();
}
FileOutputStream out = new FileOutputStream(fileOut);
out.write(content);
out.close();
}
catch (IOException ex)
{
Logger.getLogger(Disk.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Copies a file from a virtual node to another virtual node.
*
* @param origin The real path.
* @param destination The virtual path.
*/
private void virtualToVirtual(String origin, String destination) throws FileNotFoundException, Exception
{
Tree<Node> originNode = searchTree(origin);
Tree<Node> destinationNode = searchTree(destination);
if(originNode == null)
{
throw new FileNotFoundException("File '" + origin + "' doesn't exist.");
}
if(destinationNode == null)
{
throw new FileNotFoundException("File '" + destination + "' doesn't exist.");
}
if(originNode.getData().isDirectory())
{
if(!destinationNode.getData().isDirectory())
{
throw new Exception("Can't copy a directory into a file.");
}
List<Tree<Node>> nodesList = originNode.children();
if(nodesList != null)
{
for(Tree<Node> treeNode : nodesList)
{
if(treeNode.getData().isDirectory())
{
String newPath = destination + "/" + originNode.getData().getName() + "/" + treeNode.getData().getName();
copyVirtualNode(newPath, originNode.getData());
if(treeNode.hasChildren())
{
virtualToVirtual(origin + "/" + treeNode.getData().getName(), newPath);
}
}
else
{
copyVirtualNode(destination + "/" + originNode.getData().getName() + "/" + treeNode.getData().getName(), treeNode.getData());
}
}
}
else
{
Node node = searchNode(destination);
if(node == null)
{
copyVirtualNode(destination + "/" + originNode.getData().getName(), originNode.getData());
}
}
}
else
{
copyVirtualNode(destination + "/" + originNode.getData().getName(), originNode.getData());
}
}
/**
* Copies a node into another node. If the node is a file also copies its content to disk.
*
* @param path The destination directory.
* @param originNode The node to copy.
* @return The new copied node, null otherwise.
* @throws Exception
*/
private Node copyVirtualNode(String path, Node originNode) throws Exception
{
Node insertedNode = null;
if(originNode.isDirectory())
{
createDirectory(path);
}
else
{
createFile(path, originNode.getContent(file, sectorSize));
}
insertedNode = searchNode(path);
if(insertedNode != null)
{
insertedNode.setCreationDate(originNode.getCreationDate());
insertedNode.setLastModificationDate(originNode.getLastModificationDate());
return insertedNode;
}
return null;
}
}
|
package com.phonegap;
import java.io.*;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.content.Intent;
import android.webkit.WebView;
/**
* This class provides SD card file and directory services to JavaScript.
* Only files on the SD card can be accessed.
*/
public class FileUtils implements Plugin {
public static int NOT_FOUND_ERR = 8;
public static int SECURITY_ERR = 18;
public static int ABORT_ERR = 20;
public static int NOT_READABLE_ERR = 24;
public static int ENCODING_ERR = 26;
WebView webView; // WebView object
DroidGap ctx; // DroidGap object
FileReader f_in;
FileWriter f_out;
/**
* Constructor.
*/
public FileUtils() {
System.out.println("FileUtils()");
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(DroidGap ctx) {
this.ctx = ctx;
}
/**
* Sets the main View of the application, this is the WebView within which
* a PhoneGap app runs.
*
* @param webView The PhoneGap WebView
*/
public void setView(WebView webView) {
this.webView = webView;
}
/**
* Executes the request and returns CommandResult.
*
* @param action The command to execute.
* @param args JSONArry of arguments for the command.
* @return A CommandResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
//System.out.println("FileUtils.execute("+action+")");
try {
if (action.equals("testSaveLocationExists")) {
boolean b = DirectoryManager.testSaveLocationExists();
return new PluginResult(status, b);
}
else if (action.equals("getFreeDiskSpace")) {
long l = DirectoryManager.getFreeDiskSpace();
return new PluginResult(status, l);
}
else if (action.equals("testFileExists")) {
boolean b = DirectoryManager.testFileExists(args.getString(0));
return new PluginResult(status, b);
}
else if (action.equals("testDirectoryExists")) {
boolean b = DirectoryManager.testFileExists(args.getString(0));
return new PluginResult(status, b);
}
else if (action.equals("deleteDirectory")) {
boolean b = DirectoryManager.deleteDirectory(args.getString(0));
return new PluginResult(status, b);
}
else if (action.equals("deleteFile")) {
boolean b = DirectoryManager.deleteFile(args.getString(0));
return new PluginResult(status, b);
}
else if (action.equals("createDirectory")) {
boolean b = DirectoryManager.createDirectory(args.getString(0));
return new PluginResult(status, b);
}
else if (action.equals("readAsText")) {
try {
String s = this.readAsText(args.getString(0), args.getString(1));
return new PluginResult(status, s);
} catch (FileNotFoundException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
} catch (IOException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
}
}
else if (action.equals("readAsDataURL")) {
try {
String s = this.readAsDataURL(args.getString(0));
return new PluginResult(status, s);
} catch (FileNotFoundException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
} catch (IOException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
}
}
else if (action.equals("writeAsText")) {
try {
this.writeAsText(args.getString(0), args.getString(1), args.getBoolean(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_FOUND_ERR);
} catch (IOException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.ERROR, FileUtils.NOT_READABLE_ERR);
}
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("readAsText")) {
return false;
}
else if (action.equals("readAsDataURL")) {
return false;
}
else if (action.equals("writeAsText")) {
return false;
}
return true;
}
/**
* Called when the system is about to start resuming a previous activity.
*/
public void onPause() {
}
/**
* Called when the activity will start interacting with the user.
*/
public void onResume() {
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
}
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
}
// LOCAL METHODS
public String readAsText(String filename, String encoding) throws FileNotFoundException, IOException {
System.out.println("FileUtils.readAsText("+filename+", "+encoding+")");
StringBuilder data = new StringBuilder();
FileInputStream fis = new FileInputStream(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, encoding), 1024);
String line;
while ((line = reader.readLine()) != null) {
data.append(line);
}
return data.toString();
}
/**
* Read content of text file and return as base64 encoded data url.
*
* @param filename The name of the file.
* @return Contents of file = data:<media type>;base64,<data>
* @throws FileNotFoundException, IOException
*/
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
byte[] bytes = new byte[1000];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename), 1024);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int numRead = 0;
while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
bos.write(bytes, 0, numRead);
}
// Determine content type from file name
// TODO
String contentType = "";
byte[] base64 = Base64.encodeBase64(bos.toByteArray());
String data = "data:" + contentType + ";base64," + new String(base64);
return data;
}
/**
* Write contents of file.
*
* @param filename The name of the file.
* @param data The contents of the file.
* @param append T=append, F=overwrite
* @throws FileNotFoundException, IOException
*/
public void writeAsText(String filename, String data, boolean append) throws FileNotFoundException, IOException {
String FilePath= filename;
byte [] rawData = data.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
FileOutputStream out= new FileOutputStream(FilePath, append);
byte buff[] = new byte[rawData.length];
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
out.close();
}
}
|
package de.lebk.madn.gui;
import de.lebk.madn.Coordinate;
import de.lebk.madn.Logger;
import de.lebk.madn.MADNControlInterface;
import de.lebk.madn.MapException;
import de.lebk.madn.MapNoSpaceForDiceException;
import de.lebk.madn.MapNotFoundException;
import de.lebk.madn.MapNotParsableException;
import de.lebk.madn.MenschAergereDichNichtException;
import de.lebk.madn.model.Figur;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.JFrame;
public class Board extends JFrame implements KeyListener {
public static final int DEFAULT_SIZE = 800;
public static final int DEFAULT_BORDER = 48;
public static final char DEFAULT_DICE_KEY = 'w';
protected char dice_key;
private ArrayList<BoardElementHome> homes;
private ArrayList<BoardElementGoal> goals;
private BoardElement[][] fields;
private BoardDice dice;
private MADNControlInterface game;
public Board(MADNControlInterface game, String mapfile) throws MenschAergereDichNichtException {
super("Mensch ärgere dich nicht");
this.game = game;
this.setSize(this.getScreenHeight() - DEFAULT_BORDER, this.getScreenHeight());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.initFields(mapfile);
this.setVisible(true);
this.dice_key = DEFAULT_DICE_KEY;
this.addKeyListener(this);
}
public int getScreenHeight() {
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
return gd.getDisplayMode().getHeight();
}
/**
* Sets the given number to the Board
* @param number Diced number
*/
public void setDice(int number, Color color) {
this.dice.setNumber(number);
this.dice.setColor(color);
}
public BoardElementHome[] getHomesOf(Color color) {
LinkedList<BoardElementHome> homes = new LinkedList<>();
for (BoardElementHome home: this.homes) {
if (home.isSameColor(color)) {
homes.add(home);
}
}
return homes.toArray(new BoardElementHome[homes.size()]);
}
public BoardElementGoal[] getGoalsOf(Color color) {
LinkedList<BoardElementGoal> goals = new LinkedList<>();
for (BoardElementGoal goal: this.goals) {
if (goal.isSameColor(color)) {
goals.add(goal);
}
}
return goals.toArray(new BoardElementGoal[goals.size()]);
}
public int getMapSize() {
return this.fields.length;
}
private void initFields(String mapfile) throws MapException {
MapLoader loader = new MapLoader(mapfile);
this.homes = new ArrayList<>();
this.goals = new ArrayList<>();
String[] lines = loader.readFile();
if (lines != null) {
int size = loader.getMapSize(lines);
this.fields = new BoardElement[size][size];
for (String line: lines) {
BoardElement.BOARD_ELEMENT_TYPES typ = loader.getTypeFromLine(line);
Coordinate objPos = loader.getCoordinateFromLine(line);
int y = objPos.getY();
int x = objPos.getX();
Coordinate next = loader.getCoordinateForNextElementFromLine(line);
Color color;
BoardElement element;
switch (typ) {
case HOME:
color = loader.getColorFromLine(line);
this.homes.add(new BoardElementHome(this, objPos, next, color));
element = (BoardElement) this.homes.get(this.homes.size()-1);
break;
case WAYPOINT:
element = new BoardElementWaypoint(this, objPos, next);
break;
case GOAL:
color = loader.getColorFromLine(line);
this.goals.add(new BoardElementGoal(this, objPos, next, color));
element = (BoardElement) this.goals.get(this.goals.size()-1);
break;
default:
throw new MapNotParsableException(String.format("BoardElement \"%s\" is not implemented yet / unknown!", typ.toString()));
}
this.fields[x][y] = element;
this.add(this.fields[x][y]);
}
// Add the dice
this.dice = new BoardDice(this);
this.add(this.dice);
repositioningElements();
} else {
// Error reading file
throw new MapNotFoundException("No lines found in mapfile");
}
}
private boolean isPositionAvailable(Coordinate c) {
return (this.fields[c.getX()][c.getY()] == null);
}
private Coordinate calcDicePos() {
Coordinate c = new Coordinate(Math.round(this.getMapSize()/2), Math.round(this.getMapSize()/2));
if (this.isPositionAvailable(c)) {
// The center of the board would be available for the dice
return c;
}
for (int y = (this.getMapSize() - 1); y >= 0; y
c.setY(y);
for (int x = (this.getMapSize() - 1); x >= 0; x
c.setX(x);
if (this.isPositionAvailable(c)) {
return c;
}
}
}
// There is no available place for the dice
return null;
}
private void repositioningElements() {
int x, y;
int elem_width = (Math.min(this.getWidth(), (this.getHeight() - DEFAULT_BORDER)) / this.getMapSize());
BoardElement.CIRCLE_PADDING = Math.round(elem_width / 8);
for (y = 0; y < this.getMapSize(); y++) {
for (x = 0; x < this.getMapSize(); x++) {
int elem_left = elem_width * x;
int elem_top = elem_width * y;
if (this.fields[x][y] != null) {
// Just for elements
this.fields[x][y].setBounds(elem_left, elem_top, elem_width, elem_width);
}
}
}
Coordinate dicePos = this.calcDicePos();
if (dicePos != null) {
this.dice.setBounds((elem_width * dicePos.getX()) + (elem_width/8), (elem_width * dicePos.getY()) + (elem_width/8), (elem_width/4)*3, (elem_width/4)*3);
} else {
// No diceposition
Logger.write(String.format("There is no space left to draw the dice! Try to use a better mapfile!"));
}
}
@Override
public void validate() {
super.validate();
this.repositioningElements();
}
public void moveFigur(Coordinate position, Figur figur) {
this.game.moveFigur(position, figur, this.dice.getNumber());
}
public void useDice() {
this.game.userDice();
}
/**
* Just calls getBoardElement(int x, int y)
* @param c Coordinates
* @return Null if the coordinates are invalid or there is no element or the BoardElement
*/
public BoardElement getBoardElement(Coordinate c) {
return this.getBoardElement(c.getX(), c.getY());
}
/**
* Returns the BoardElement which is placed at (x/y)
* @param x X-Coordinate
* @param y Y-Coordinate
* @return Null if the coordinates are invalid or there is no element or the BoardElement
*/
public BoardElement getBoardElement(int x, int y) {
if ((x < 0) || (y < 0) || (x >= this.fields.length) || (y >= this.fields[x].length)) {
// Coordinates are not valid
return null;
}
return this.fields[x][y];
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == this.dice_key)
{
this.game.userDice();
}
}
public void keyReleased(KeyEvent e)
{
}
}
|
package cn.momia.mapi.api.course;
import cn.momia.api.course.CourseServiceApi;
import cn.momia.api.course.SubjectServiceApi;
import cn.momia.api.course.dto.comment.UserCourseComment;
import cn.momia.api.course.dto.course.Course;
import cn.momia.api.course.dto.course.CourseDetail;
import cn.momia.api.course.dto.subject.SubjectSku;
import cn.momia.api.user.TeacherServiceApi;
import cn.momia.api.user.dto.Teacher;
import cn.momia.common.core.dto.PagedList;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/v3/course")
public class CourseV3Api extends AbstractApi {
private static final Logger LOGGER = LoggerFactory.getLogger(CourseV3Api.class);
@Autowired private CourseServiceApi courseServiceApi;
@Autowired private SubjectServiceApi subjectServiceApi;
@Autowired private TeacherServiceApi teacherServiceApi;
@RequestMapping(method = RequestMethod.GET)
public MomiaHttpResponse get(@RequestParam(required = false, defaultValue = "") String utoken,
@RequestParam long id,
@RequestParam(required = false, defaultValue = "") String pos) {
if (id <= 0) return MomiaHttpResponse.FAILED("ID");
Course course = completeLargeImg(courseServiceApi.get(id, pos));
JSONObject courseJson = (JSONObject) JSON.toJSON(course);
PagedList<Integer> pagedTeacherIds = courseServiceApi.teacherIds(id, 0, Configuration.getInt("PageSize.Teacher"));
List<Teacher> teachers = completeTeachersImgs(teacherServiceApi.list(pagedTeacherIds.getList()));
if (!teachers.isEmpty()) courseJson.put("teachers", teachers);
PagedList<UserCourseComment> pagedComments = courseServiceApi.queryCommentsByCourse(id, 0, Configuration.getInt("PageSize.CourseComment"));
completeCourseCommentsImgs(pagedComments.getList());
if (!pagedComments.getList().isEmpty()) courseJson.put("comments", pagedComments);
List<SubjectSku> subjectSkus = subjectServiceApi.querySkus(course.getSubjectId());
SubjectSku cheapestSubjectSku = null;
for (SubjectSku subjectSku : subjectSkus) {
if (subjectSku.getCourseId() > 0) continue;
if (cheapestSubjectSku == null || subjectSku.getPrice().compareTo(cheapestSubjectSku.getPrice()) < 0) cheapestSubjectSku = subjectSku;
}
if (cheapestSubjectSku != null) {
courseJson.put("cheapestSkuPrice", cheapestSubjectSku.getPrice());
courseJson.put("cheapestSkuTimeUnit", TimeUtil.toUnitString(cheapestSubjectSku.getTimeUnit()));
courseJson.put("cheapestSkuDesc", "" + cheapestSubjectSku.getCourseCount() + "");
}
try {
CourseDetail detail = courseServiceApi.detail(id);
JSONArray detailJson = JSON.parseArray(detail.getDetail());
for (int i = 0; i < detailJson.size(); i++) {
JSONObject detailBlockJson = detailJson.getJSONObject(i);
JSONArray contentJson = detailBlockJson.getJSONArray("content");
for (int j = 0; j < contentJson.size(); j++) {
JSONObject contentBlockJson = contentJson.getJSONObject(j);
if (contentBlockJson.containsKey("img")) contentBlockJson.put("img", completeLargeImg(contentBlockJson.getString("img")));
}
}
courseJson.put("goal", detail.getAbstracts());
courseJson.put("detail", detailJson);
} catch (Exception e) {
LOGGER.warn("invalid course detail: {}", id);
}
return MomiaHttpResponse.SUCCESS(courseJson);
}
}
|
package com.torodb.torod.mongodb;
import com.eightkdata.mongowp.mongoserver.protocol.MongoWP;
import com.google.common.collect.ImmutableList;
public final class MongoLayerConstants {
public static final int VERSION_MAJOR = 3;
public static final int VERSION_MINOR = 0;
public static final int VERSION_PATCH = 0;
public static final String VERSION_STRING =
VERSION_MAJOR + "." +
VERSION_MINOR + "." +
VERSION_PATCH;
public static final ImmutableList VERSION = ImmutableList.of(
MongoLayerConstants.VERSION_MAJOR,
MongoLayerConstants.VERSION_MINOR,
MongoLayerConstants.VERSION_PATCH
);
public static final int MAX_WIRE_VERSION = 3;
public static final int MIN_WIRE_VERSION = 0;
public static final int MAX_BSON_DOCUMENT_SIZE = 16 * 1024 * 1024;
public static final int MAX_WRITE_BATCH_SIZE = 1000;
public static final int MAX_MESSAGE_SIZE_BYTES = MongoWP.MAX_MESSAGE_SIZE_BYTES;
public static final int MONGO_CURSOR_LIMIT = 101;
private MongoLayerConstants() {
}
}
|
package pl.project13.janbanery.resources;
import com.google.gson.annotations.SerializedName;
import pl.project13.janbanery.resources.additions.On;
import pl.project13.janbanery.resources.additions.ReadOnly;
import pl.project13.janbanery.resources.additions.Required;
import pl.project13.janbanery.resources.additions.Settable;
import java.io.Serializable;
/**
* Describes an column in an Kanban board.
*
* @author Konrad Malawski
*/
public class Column extends KanbaneryResource implements Serializable {
@ReadOnly
private Long id;
@Required
@Settable(On.CreateOrUpdate)
private String name; // on create and update Name
@SerializedName("project_id")
@ReadOnly
private Integer projectId; // Project
@ReadOnly
private Boolean fixed; // If column can be moved
@Settable(On.CreateOrUpdate)
private Integer capacity; // Capacity (WIP limit)
@Settable(On.CreateOrUpdate)
private Integer position; // Position on the board, 1-based
public Column() {
}
@Override
public String getResourceId() {
return "column";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
public Boolean getFixed() {
return fixed;
}
public void setFixed(Boolean fixed) {
this.fixed = fixed;
}
public Integer getCapacity() {
return capacity;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
Column column = (Column) o;
if (capacity != null ? !capacity.equals(column.capacity) : column.capacity != null) {
return false;
}
if (fixed != null ? !fixed.equals(column.fixed) : column.fixed != null) {
return false;
}
if (id != null ? !id.equals(column.id) : column.id != null) {
return false;
}
if (name != null ? !name.equals(column.name) : column.name != null) {
return false;
}
if (position != null ? !position.equals(column.position) : column.position != null) {
return false;
}
if (projectId != null ? !projectId.equals(column.projectId) : column.projectId != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (projectId != null ? projectId.hashCode() : 0);
result = 31 * result + (fixed != null ? fixed.hashCode() : 0);
result = 31 * result + (capacity != null ? capacity.hashCode() : 0);
result = 31 * result + (position != null ? position.hashCode() : 0);
return result;
}
}
|
package gov.nih.nci.camod.service.impl;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.CellLine;
import gov.nih.nci.camod.domain.Organ;
import gov.nih.nci.camod.service.CellLineManager;
import gov.nih.nci.camod.webapp.form.CellLineData;
import java.util.List;
/**
* Impementation of CellLineManager. Used to persist CellLine objects.
*/
public class CellLineManagerImpl extends BaseManager implements CellLineManager {
/**
* Get all CellLine objects
*
* @return the matching CellLine objects
*
* @exception Exception
* when anything goes wrong.
*/
public List getAll() throws Exception {
log.trace("In CellLineManagerImpl.getAll");
return super.getAll(CellLine.class);
}
/**
* Get a specific CellLine by id
*
* @param id
* the unique id for a CellLine
*
* @return the matching CellLine object, or null if not found.
*
* @exception Exception
* when anything goes wrong.
*/
public CellLine get(String id) throws Exception {
log.trace("In CellLineManagerImpl.get");
return (CellLine) super.get(id, CellLine.class);
}
/**
* Save an CellLine object
*
* @param inCellLine
* the CellLine object to save
*
* @exception Exception
* if an error occurred
*/
public void save(CellLine inCellLine) throws Exception {
log.trace("In CellLineManagerImpl.save");
super.save(inCellLine);
}
/**
* Remove a CellLine object
*
* @param inId
* the ID of the CellLine to remove
* @param inAnimalModel
* the AnimalModel the CellLine is being deleted from.
*
* @exception Exception
* if an error occurred
*/
public void remove(String inId, AnimalModel inAnimalModel) throws Exception {
log.trace("In CellLineManagerImpl.remove");
inAnimalModel.getCellLineCollection().remove(get(inId));
super.save(inAnimalModel);
}
/**
* Create a CellLine object from the data being passed in
*
* @param inCellLineData
* the data used to ceate the CellLine
*
* @return the newly created CellLine object
* @exception Exception
* if an error occurred
*/
public CellLine create(CellLineData inCellLineData) throws Exception {
log.debug("Entering CellLineManagerImpl.create");
CellLine theCellLine = new CellLine();
// Populate w/ the new values and save
populateOrgan(inCellLineData,
theCellLine);
populateCellLine(inCellLineData, theCellLine);
log.debug("Exiting CellLineManagerImpl.create");
return theCellLine;
}
/**
* Update a CellLine object with the data being passed in
*
* @param inCellLineData
* the data used to ceate the CellLine
* @param inCellLine
* the CellLine object to update
*
* @exception Exception
* if an error occurred
*/
public void update(CellLineData inCellLineData, CellLine inCellLine)
throws Exception {
log.debug("Entering CellLineManagerImpl.update");
log.debug("Updating CellLineForm: " + inCellLine.getId());
// Populate w/ the new values and save
populateOrgan(inCellLineData,
inCellLine);
// Populate w/ the new values and save
populateCellLine(inCellLineData, inCellLine);
save(inCellLine);
log.debug("Exiting CellLineManagerImpl.update");
}
private void populateOrgan(CellLineData inCellLineData, CellLine inCellLine) throws Exception {
log.info("<CellLineManagerImpl> Entering populateOrgan");
// Update loop handeled separately for conceptCode = 00000
if (inCellLineData.getOrganTissueCode().equals(Constants.Dropdowns.CONCEPTCODEZEROS)){
log.info("Organ update loop for text: " + inCellLineData.getOrgan());
inCellLine.setOrgan(new Organ());
inCellLine.getOrgan().setName(inCellLineData.getOrgan());
inCellLine.getOrgan().setConceptCode(
Constants.Dropdowns.CONCEPTCODEZEROS);
} else {
// Using trees loop, new save loop and update loop
if (inCellLineData.getOrganTissueCode() != null && inCellLineData.getOrganTissueCode().length() > 0) {
log.info("OrganTissueCode: " + inCellLineData.getOrganTissueCode());
log.info("OrganTissueName: " + inCellLineData.getOrganTissueName());
log.info("OrganTissueCode() != null - getOrCreate method used");
// when using tree, organTissueName populates the organ name entry
Organ theNewOrgan = OrganManagerSingleton.instance().getOrCreate(
inCellLineData.getOrganTissueCode(),
inCellLineData.getOrganTissueName());
log.info("theNewOrgan: " + theNewOrgan);
inCellLine.setOrgan(theNewOrgan);
} else {
// text entry loop = new save
log.info("Organ (text): " + inCellLineData.getOrgan());
inCellLine.setOrgan(new Organ());
inCellLine.getOrgan().setName(inCellLineData.getOrgan());
inCellLine.getOrgan().setConceptCode(
Constants.Dropdowns.CONCEPTCODEZEROS);
log.info("Organ: " + inCellLine.getOrgan().toString());
}
}
}
// Common method used to populate a CellLine object
private void populateCellLine(CellLineData inCellLineData,
CellLine inCellLine) throws Exception {
log.debug("Entering populateCellLine");
inCellLine.setName(inCellLineData.getCellLineName());
inCellLine.setExperiment(inCellLineData.getExperiment());
inCellLine.setResults(inCellLineData.getResults());
inCellLine.setComments(inCellLineData.getComments());
log.debug("Exiting populateCellLine");
}
}
|
package org.codice.usng4j;
/**
* This interface models a point in the United States National Grid coordinate system. There are
* several valid formats for USNG coordinates. A fully specified coordinate is formatted like this:
*
* <p>{@code <zone number><latitude band letter><space><grid column><grid
* row><space><easting><space><northing>} e.g. 18T WL 85628 11322
*
* <p>Only {@code <zone number>} and {@code <latitude band letter>} are required. The grid letters
* are required if easting and northing values are supplied. The easting and northing values have a
* maximum length of 5 characters each (with an optional '-').
*
* <p>Default implementations of this class are immutable and therefore threadsafe.
*/
public interface UsngCoordinate {
/** RegEx expressions for USNG/MGRS Zone parsing */
public final String ZONE_REGEX_STRING = "([1-9]|[1-5][0-9]|60)";
/** RegEx expressions for USNG/MGRS Latitude Bands parsing, part one */
public final String LATITUDE_BAND_PART_ONE_REGEX_STRING = "([C-HJ-NP-X])";
/** RegEx expressions for USNG/MGRS Latitude Bands parsing, part two */
public final String LATITUDE_BAND_PART_TWO_REGEX_STRING = "([A-HJ-NP-Z][A-HJ-NP-V])?";
/** RegEx expressions for USNG/MGRS Latitude Bands parsing, combined */
public final String LATITUDE_BAND_REGEX_STRING =
LATITUDE_BAND_PART_ONE_REGEX_STRING + "\\W?" + LATITUDE_BAND_PART_TWO_REGEX_STRING;
/** RegEx expressions for USNG Northing and Easting parsing */
public final String USNG_COORDINATE_PART_REGEX_STRING = "(\\W\\d{0,5})?(\\W\\d{0,5})?";
/** RegEx expressions for MGRS Northing and Easting parsing */
public final String MGRS_COORDINATE_PART_REGEX_STRING = "(\\d{0,5})\\W*(\\d{0,5})\\W*";
/** @return the zone number of this USNG coordinate. */
int getZoneNumber();
/** @return the latitude band for this USNG coordinate or null if not specified. */
char getLatitudeBandLetter();
/** @return the grid column letter for this USNG coordinate or null if not specified. */
Character getColumnLetter();
/** @return the grid row letter for this USNG coordinate or null if not specified. */
Character getRowLetter();
/** @return the easting value for this USNG coordinate or null if not specified. */
Integer getEasting();
/** @return the northing for this USNG coordinate or null if not specified. */
Integer getNorthing();
/** @return the precision level of the supplied easting/northing values. */
CoordinatePrecision getPrecision();
/**
* @return an MGRS coordinate formatted representation of this coordinate. This is the same as the
* USNG formatted version with spaces removed.
*/
String toMgrsString();
}
|
package com.arckenver.mightyloot;
import java.util.Hashtable;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockTypes;
import com.arckenver.mightyloot.object.Loot;
public class DataHandler
{
private static Hashtable<String, Loot> loots;
public static void init()
{
loots = new Hashtable<String, Loot>();
}
// LOOT
public static void setLoot(String worldName, Loot loot)
{
loots.put(worldName, loot);
}
public static Loot removeLoot(String worldName)
{
Loot loot = unregisterLoot(worldName);
if (loot == null)
{
return null;
}
// TODO issue here : chest explodes and content stays
/*
((Chest) loot.getLoc().getTileEntity().get()).getInventory().clear();
*/
Sponge.getCommandManager().process(Sponge.getServer().getConsole(), "setblock " +
loot.getLoc().getBlockX() + " " +
loot.getLoc().getBlockY() + " " +
loot.getLoc().getBlockZ() + " minecraft:chest 0 replace {Items:[]}");
loot.getLoc().setBlockType(BlockTypes.AIR);
loot.getLoc().add(0, -1, 0).setBlockType(BlockTypes.AIR);
return loot;
}
public static Loot getLoot(String worldName)
{
return loots.get(worldName);
}
public static boolean hasLoot(String worldName)
{
return loots.get(worldName) != null;
}
public static Loot unregisterLoot(String worldName)
{
return loots.remove(worldName);
}
}
|
package refinedstorage.tile;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import refinedstorage.RS;
import refinedstorage.RSUtils;
import refinedstorage.api.util.IComparer;
import refinedstorage.apiimpl.storage.fluid.FluidStorageNBT;
import refinedstorage.apiimpl.storage.item.ItemStorageNBT;
import refinedstorage.block.EnumFluidStorageType;
import refinedstorage.block.EnumItemStorageType;
import refinedstorage.inventory.IItemValidator;
import refinedstorage.inventory.ItemHandlerBasic;
import refinedstorage.inventory.ItemHandlerFluid;
import refinedstorage.inventory.ItemHandlerUpgrade;
import refinedstorage.item.ItemUpgrade;
import refinedstorage.tile.config.IComparable;
import refinedstorage.tile.config.IFilterable;
import refinedstorage.tile.config.IType;
import refinedstorage.tile.data.ITileDataConsumer;
import refinedstorage.tile.data.ITileDataProducer;
import refinedstorage.tile.data.TileDataParameter;
import java.util.ArrayList;
public class TileDiskManipulator extends TileNode implements IComparable, IFilterable, IType {
public static final TileDataParameter<Integer> COMPARE = IComparable.createParameter();
public static final TileDataParameter<Integer> MODE = IFilterable.createParameter();
public static final TileDataParameter<Integer> TYPE = IType.createParameter();
public static final int IO_MODE_INSERT = 0;
public static final int IO_MODE_EXTRACT = 1;
public static final TileDataParameter<Integer> IO_MODE = new TileDataParameter<>(DataSerializers.VARINT, IO_MODE_INSERT, new ITileDataProducer<Integer, TileDiskManipulator>() {
@Override
public Integer getValue(TileDiskManipulator tile) {
return tile.ioMode;
}
}, new ITileDataConsumer<Integer, TileDiskManipulator>() {
@Override
public void setValue(TileDiskManipulator tile, Integer value) {
tile.ioMode = value;
tile.markDirty();
}
});
private static final String NBT_COMPARE = "Compare";
private static final String NBT_MODE = "Mode";
private static final String NBT_TYPE = "Type";
private static final String NBT_IO_MODE = "IOMode";
private int compare = IComparer.COMPARE_NBT | IComparer.COMPARE_DAMAGE;
private int mode = IFilterable.WHITELIST;
private int type = IType.ITEMS;
private int ioMode = IO_MODE_INSERT;
private ItemStorage[] itemStorages = new ItemStorage[6];
private FluidStorage[] fluidStorages = new FluidStorage[6];
public TileDiskManipulator() {
dataManager.addWatchedParameter(COMPARE);
dataManager.addWatchedParameter(MODE);
dataManager.addWatchedParameter(TYPE);
dataManager.addWatchedParameter(IO_MODE);
}
private ItemHandlerUpgrade upgrades = new ItemHandlerUpgrade(4, this, ItemUpgrade.TYPE_SPEED, ItemUpgrade.TYPE_STACK);
private ItemHandlerBasic disks = new ItemHandlerBasic(12, this, IItemValidator.STORAGE_DISK) {
@Override
protected void onContentsChanged(int slot) {
super.onContentsChanged(slot);
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && slot < 6) {
RSUtils.constructFromDrive(getStackInSlot(slot), slot, itemStorages, fluidStorages, s -> new ItemStorage(s), s -> new FluidStorage(s));
}
}
@Override
public ItemStack extractItem(int slot, int amount, boolean simulate) {
if (slot < 6) {
if (itemStorages[slot] != null) {
itemStorages[slot].writeToNBT();
}
if (fluidStorages[slot] != null) {
fluidStorages[slot].writeToNBT();
}
}
return super.extractItem(slot, amount, simulate);
}
};
public class ItemStorage extends ItemStorageNBT {
public ItemStorage(ItemStack disk) {
super(disk.getTagCompound(), EnumItemStorageType.getById(disk.getItemDamage()).getCapacity(), TileDiskManipulator.this);
}
@Override
public int getPriority() {
return 0;
}
@Override
public ItemStack insertItem(ItemStack stack, int size, boolean simulate) {
if (!IFilterable.canTake(itemFilters, mode, getCompare(), stack)) {
return ItemHandlerHelper.copyStackWithSize(stack, size);
}
return super.insertItem(stack, size, simulate);
}
@Override
public ItemStack extractItem(ItemStack stack, int size, int flags) {
if (!IFilterable.canTake(itemFilters, mode, getCompare(), stack)) {
return null;
}
return super.extractItem(stack, size, flags);
}
}
public class FluidStorage extends FluidStorageNBT {
public FluidStorage(ItemStack disk) {
super(disk.getTagCompound(), EnumFluidStorageType.getById(disk.getItemDamage()).getCapacity(), TileDiskManipulator.this);
}
@Override
public int getPriority() {
return 0;
}
@Override
public FluidStack insertFluid(FluidStack stack, int size, boolean simulate) {
if (!IFilterable.canTakeFluids(fluidFilters, mode, getCompare(), stack)) {
return RSUtils.copyStackWithSize(stack, size);
}
return super.insertFluid(stack, size, simulate);
}
@Override
public FluidStack extractFluid(FluidStack stack, int size, int flags) {
if (!IFilterable.canTakeFluids(fluidFilters, mode, getCompare(), stack)) {
return null;
}
return super.extractFluid(stack, size, flags);
}
}
private ItemHandlerBasic itemFilters = new ItemHandlerBasic(9, this);
private ItemHandlerFluid fluidFilters = new ItemHandlerFluid(9, this);
@Override
public int getEnergyUsage() {
return RS.INSTANCE.config.diskManipulatorUsage + upgrades.getEnergyUsage();
}
@Override
public boolean hasConnectivityState() {
return true;
}
@Override
public void updateNode() {
if (ticks % upgrades.getSpeed() != 0) {
return;
}
int slot = 0;
if (type == IType.ITEMS) {
while (slot < itemStorages.length && itemStorages[slot] == null) {
slot++;
}
if (slot == itemStorages.length) {
return;
}
ItemStorage storage = itemStorages[slot];
if (ioMode == IO_MODE_INSERT) {
insertIntoNetwork(storage, slot);
} else if (ioMode == IO_MODE_EXTRACT) {
extractFromNetwork(storage, slot);
}
} else if (type == IType.FLUIDS) {
while (slot < fluidStorages.length && fluidStorages[slot] == null) {
slot++;
}
if (slot == fluidStorages.length) {
return;
}
FluidStorage storage = fluidStorages[slot];
if (ioMode == IO_MODE_INSERT) {
insertIntoNetwork(storage, slot);
} else if (ioMode == IO_MODE_EXTRACT) {
extractFromNetwork(storage, slot);
}
}
}
private void insertIntoNetwork(ItemStorage storage, int slot) {
if (storage.getStored() == 0) {
moveDriveToOutput(slot);
return;
}
for (int i = 0; i < storage.getItems().size(); i++) {
ItemStack stack = storage.getItems().get(i);
if (stack == null) {
continue;
}
ItemStack extracted = storage.extractItem(stack, upgrades.getInteractStackSize(), compare);
if (extracted == null) {
continue;
}
ItemStack remainder = network.insertItem(extracted, extracted.stackSize, false);
if (remainder == null) {
break;
}
// We need to check if the stack was inserted
storage.insertItem(((extracted == remainder) ? remainder.copy() : remainder), remainder.stackSize, false);
}
if (storage.getItems().size() == 0) {
moveDriveToOutput(slot);
}
}
private void extractFromNetwork(ItemStorage storage, int slot) {
if (storage.getStored() == storage.getCapacity()) {
moveDriveToOutput(slot);
return;
}
ItemStack extracted = null;
int i = 0;
if (IFilterable.isEmpty(itemFilters)) {
ItemStack toExtract = null;
ArrayList<ItemStack> networkItems = new ArrayList<>(network.getItemStorageCache().getList().getStacks());
int j = 0;
while ((toExtract == null || toExtract.stackSize == 0) && j < networkItems.size()) {
toExtract = networkItems.get(j++);
}
if (toExtract != null) {
extracted = network.extractItem(toExtract, upgrades.getInteractStackSize(), compare);
}
} else {
while (itemFilters.getSlots() > i && extracted == null) {
ItemStack stack = null;
while (itemFilters.getSlots() > i && stack == null) {
stack = itemFilters.getStackInSlot(i++);
}
if (stack != null) {
extracted = network.extractItem(stack, upgrades.getInteractStackSize(), compare);
}
}
}
if (extracted == null) {
moveDriveToOutput(slot);
return;
}
ItemStack remainder = storage.insertItem(extracted, extracted.stackSize, false);
if (remainder != null) {
network.insertItem(remainder, remainder.stackSize, false);
}
}
private void insertIntoNetwork(FluidStorage storage, int slot) {
if (storage.getStored() == 0) {
moveDriveToOutput(slot);
return;
}
FluidStack extracted = null;
int i = 0;
do {
FluidStack stack = storage.getStacks().get(i);
while (stack == null && storage.getStacks().size() > i) {
i++;
}
if (stack != null) {
extracted = storage.extractFluid(stack, upgrades.getInteractStackSize(), compare);
}
} while (extracted == null && storage.getStacks().size() > i);
if (extracted == null) {
moveDriveToOutput(slot);
return;
}
FluidStack remainder = network.insertFluid(extracted, extracted.amount, false);
if (remainder != null) {
storage.insertFluid(remainder, remainder.amount, false);
}
}
private void extractFromNetwork(FluidStorage storage, int slot) {
if (storage.getStored() == storage.getCapacity()) {
moveDriveToOutput(slot);
return;
}
FluidStack extracted = null;
int i = 0;
if (IFilterable.isEmpty(itemFilters)) {
FluidStack toExtract = null;
ArrayList<FluidStack> networkFluids = new ArrayList<>(network.getFluidStorageCache().getList().getStacks());
int j = 0;
while ((toExtract == null || toExtract.amount == 0) && j < networkFluids.size()) {
toExtract = networkFluids.get(j++);
}
if (toExtract != null) {
extracted = network.extractFluid(toExtract, upgrades.getInteractStackSize(), compare);
}
} else {
while (fluidFilters.getSlots() > i && extracted == null) {
FluidStack stack = null;
while (fluidFilters.getSlots() > i && stack == null) {
stack = fluidFilters.getFluidStackInSlot(i++);
}
if (stack != null) {
extracted = network.extractFluid(stack, upgrades.getInteractStackSize(), compare);
}
}
}
if (extracted == null) {
moveDriveToOutput(slot);
return;
}
FluidStack remainder = storage.insertFluid(extracted, extracted.amount, false);
if (remainder != null) {
network.insertFluid(remainder, remainder.amount, false);
}
}
private void moveDriveToOutput(int slot) {
ItemStack disk = disks.getStackInSlot(slot);
if (disk != null) {
int i = 6;
while (i < 12 && disks.getStackInSlot(i) != null) {
i++;
}
if (i == 12) {
return;
}
if (slot < 6) {
if (itemStorages[slot] != null) {
itemStorages[slot].writeToNBT();
itemStorages[slot] = null;
}
if (fluidStorages[slot] != null) {
fluidStorages[slot].writeToNBT();
fluidStorages[slot] = null;
}
}
disks.extractItem(slot, 1, false);
disks.insertItem(i, disk, false);
}
}
@Override
public int getCompare() {
return compare;
}
@Override
public void setCompare(int compare) {
this.compare = compare;
}
@Override
public int getType() {
return this.type;
}
@Override
public void setType(int type) {
this.type = type;
}
@Override
public IItemHandler getFilterInventory() {
return getType() == IType.ITEMS ? itemFilters : fluidFilters;
}
@Override
public void setMode(int mode) {
this.mode = mode;
}
@Override
public int getMode() {
return this.mode;
}
public IItemHandler getDisks() {
return disks;
}
public IItemHandler getUpgrades() {
return upgrades;
}
@Override
public void read(NBTTagCompound tag) {
super.read(tag);
RSUtils.readItems(disks, 0, tag);
RSUtils.readItems(itemFilters, 1, tag);
RSUtils.readItems(fluidFilters, 2, tag);
RSUtils.readItems(upgrades, 3, tag);
if (tag.hasKey(NBT_COMPARE)) {
compare = tag.getInteger(NBT_COMPARE);
}
if (tag.hasKey(NBT_MODE)) {
mode = tag.getInteger(NBT_MODE);
}
if (tag.hasKey(NBT_TYPE)) {
type = tag.getInteger(NBT_TYPE);
}
if (tag.hasKey(NBT_IO_MODE)) {
ioMode = tag.getInteger(NBT_IO_MODE);
}
}
@Override
public NBTTagCompound write(NBTTagCompound tag) {
super.write(tag);
RSUtils.writeItems(disks, 0, tag);
RSUtils.writeItems(itemFilters, 1, tag);
RSUtils.writeItems(fluidFilters, 2, tag);
RSUtils.writeItems(upgrades, 3, tag);
tag.setInteger(NBT_COMPARE, compare);
tag.setInteger(NBT_MODE, mode);
tag.setInteger(NBT_TYPE, type);
tag.setInteger(NBT_IO_MODE, ioMode);
return tag;
}
@Override
public IItemHandler getDrops() {
return disks;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
return (T) disks;
}
return super.getCapability(capability, facing);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
}
public void onBreak() {
for (ItemStorage storage : itemStorages) {
if (storage != null) {
storage.writeToNBT();
}
}
for (FluidStorage storage : fluidStorages) {
if (storage != null) {
storage.writeToNBT();
}
}
}
}
|
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.domain.common.LabFile;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.dto.common.LabFileBean;
import gov.nih.nci.cananolab.dto.common.UserBean;
import gov.nih.nci.cananolab.dto.particle.ParticleBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.exception.FileException;
import gov.nih.nci.cananolab.service.common.FileService;
import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl;
import gov.nih.nci.cananolab.service.common.impl.FileServiceRemoteImpl;
import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService;
import gov.nih.nci.cananolab.service.particle.impl.NanoparticleSampleServiceLocalImpl;
import gov.nih.nci.cananolab.service.particle.impl.NanoparticleSampleServiceRemoteImpl;
import gov.nih.nci.cananolab.service.security.AuthorizationService;
import gov.nih.nci.cananolab.ui.particle.InitNanoparticleSetup;
import gov.nih.nci.cananolab.ui.security.InitSecuritySetup;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.DataLinkBean;
import gov.nih.nci.cananolab.util.PropertyReader;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* Base action for all annotation actions
*
* @author pansu
*
*/
public abstract class BaseAnnotationAction extends AbstractDispatchAction {
public ParticleBean setupParticle(DynaValidatorForm theForm,
HttpServletRequest request, String location) throws Exception {
String particleId = request.getParameter("particleId");
if (particleId == null) {
particleId = theForm.getString("particleId");
}
HttpSession session = request.getSession();
UserBean user = (UserBean) session.getAttribute("user");
NanoparticleSampleService service = null;
if (location.equals("local")) {
service = new NanoparticleSampleServiceLocalImpl();
} else {
String serviceUrl = InitSetup.getInstance().getGridServiceUrl(
request, location);
service = new NanoparticleSampleServiceRemoteImpl(serviceUrl);
}
ParticleBean particleBean = service
.findNanoparticleSampleById(particleId);
particleBean.setLocation(location);
request.setAttribute("theParticle", particleBean);
if (location.equals("local")) {
InitNanoparticleSetup.getInstance().getOtherParticleNames(
request,
particleBean.getDomainParticleSample().getName(),
particleBean.getDomainParticleSample().getSource()
.getOrganizationName(), user);
}
return particleBean;
}
protected void saveFilesToFileSystem(List<LabFileBean> files)
throws Exception {
// save file data to file system and set visibility
AuthorizationService authService = new AuthorizationService(
CaNanoLabConstants.CSM_APP_NAME);
FileService fileService = new FileServiceLocalImpl();
for (LabFileBean fileBean : files) {
fileService.writeFile(fileBean.getDomainFile(), fileBean
.getNewFileData());
authService.assignVisibility(fileBean.getDomainFile().getId()
.toString(), fileBean.getVisibilityGroups());
}
}
public boolean loginRequired() {
return false;
}
public boolean canUserExecute(UserBean user)
throws CaNanoLabSecurityException {
return InitSecuritySetup.getInstance().userHasCreatePrivilege(user,
CaNanoLabConstants.CSM_PG_PARTICLE);
}
public Map<String, SortedSet<DataLinkBean>> setupDataTree(
ParticleBean particleBean, HttpServletRequest request)
throws Exception {
request.setAttribute("updateDataTree", "true");
InitSetup.getInstance()
.getDefaultAndOtherLookupTypes(request, "reportCategories",
"Report", "category", "otherCategory", true);
return InitNanoparticleSetup.getInstance().getDataTree(particleBean,
request);
}
public ActionForward setupDeleteAll(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String submitType = request.getParameter("submitType");
DynaValidatorForm theForm = (DynaValidatorForm) form;
ParticleBean particleBean = setupParticle(theForm, request, "local");
Map<String, SortedSet<DataLinkBean>> dataTree = setupDataTree(
particleBean, request);
SortedSet<DataLinkBean> dataToDelete = dataTree.get(submitType);
request.getSession().setAttribute("actionName",
dataToDelete.first().getDataLink());
request.getSession().setAttribute("dataToDelete", dataToDelete);
return mapping.findForward("annotationDeleteView");
}
// check for cases where delete can't happen
protected boolean checkDelete(HttpServletRequest request,
ActionMessages msgs, String id) throws Exception {
return true;
}
public ActionForward deleteAll(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String submitType = request.getParameter("submitType");
String className = InitSetup.getInstance().getObjectName(submitType,
request.getSession().getServletContext());
String fullClassName = ClassUtils.getFullClass(className)
.getCanonicalName();
String[] dataIds = (String[]) theForm.get("idsToDelete");
NanoparticleSampleService sampleService = new NanoparticleSampleServiceLocalImpl();
ActionMessages msgs = new ActionMessages();
for (String id : dataIds) {
if (!checkDelete(request, msgs, id)) {
return mapping.findForward("annotationDeleteView");
}
sampleService.deleteAnnotationById(fullClassName, new Long(id));
}
ParticleBean particleBean = setupParticle(theForm, request, "local");
setupDataTree(particleBean, request);
ActionMessage msg = new ActionMessage("message.deleteAnnotations",
submitType);
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
saveMessages(request, msgs);
return mapping.findForward("success");
}
/**
* Download action to handle file downloading and viewing
*
* @param
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileId = request.getParameter("fileId");
UserBean user = (UserBean) request.getSession().getAttribute("user");
String location = request.getParameter("location");
FileService fileService = null;
String remoteServerHostUrl = "";
LabFileBean fileBean = null;
String serviceUrl = null;
if (location.equals("local")) {
fileService = new FileServiceLocalImpl();
}
// CQL2HQL filters out subclasses, disabled the filter
else {
serviceUrl = InitSetup.getInstance().getGridServiceUrl(request,
location);
fileService = new FileServiceRemoteImpl(serviceUrl);
}
fileBean = fileService.findFileById(fileId, user);
if (fileBean != null) {
if (fileBean.getDomainFile().getUriExternal()) {
response.sendRedirect(fileBean.getDomainFile().getUri());
return null;
}
}
if (!location.equals("local")) {
// assume grid service is located on the same server and port as
// webapp
URL localURL = new URL(request.getRequestURL().toString());
String actionPath = localURL.getPath();
URL remoteUrl = new URL(serviceUrl);
remoteServerHostUrl = remoteUrl.getProtocol() + ":
+ remoteUrl.getHost() + ":" + remoteUrl.getPort();
String remoteDownloadUrl = remoteServerHostUrl + "/" + actionPath
+ "?dispatch=download" + "&fileId=" + fileId
+ "&location=local";
// remote URL
response.sendRedirect(remoteDownloadUrl);
return null;
}
String fileRoot = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
File dFile = new File(fileRoot + File.separator
+ fileBean.getDomainFile().getUri());
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileBean.getDomainFile().getName());
response.setHeader("cache-control", "Private");
java.io.InputStream in = new FileInputStream(dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("error.noFile");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
throw new FileException("File " + fileBean.getDomainFile().getUri()
+ " doesn't exist on the server");
}
return null;
}
protected NanoparticleSample[] prepareCopy(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
String[] otherParticles = (String[]) theForm.get("otherParticles");
if (otherParticles.length == 0) {
return null;
}
NanoparticleSample[] particleSamples = new NanoparticleSample[otherParticles.length];
NanoparticleSampleService sampleService = new NanoparticleSampleServiceLocalImpl();
int i = 0;
for (String other : otherParticles) {
NanoparticleSample particleSample = sampleService
.findNanoparticleSampleByName(other);
particleSamples[i] = particleSample;
i++;
}
return particleSamples;
}
protected boolean validateFileBean(HttpServletRequest request,
ActionMessages msgs, LabFileBean fileBean) {
boolean noErrors = true;
LabFile labfile = fileBean.getDomainFile();
if (labfile.getTitle().length() == 0) {
ActionMessage msg = new ActionMessage("errors.required",
"file title");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
noErrors = false;
}
if (labfile.getType().length() == 0) {
ActionMessage msg = new ActionMessage("errors.required",
"file type");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
noErrors = false;
}
if (labfile.getUriExternal()) {
if (fileBean.getExternalUrl() == null
|| fileBean.getExternalUrl().trim().length() == 0) {
ActionMessage msg = new ActionMessage("errors.required",
"external url");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
noErrors = false;
}
} else{
//all empty
if ((fileBean.getUploadedFile()==null || fileBean.getUploadedFile().toString().trim().length()==0) &&
(fileBean.getExternalUrl()==null || fileBean.getExternalUrl().trim().length()==0)
){
ActionMessage msg = new ActionMessage("errors.required",
"uploaded file");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
noErrors = false;
//the case that user switch from url to upload file, but no file is selected
}else if ((fileBean.getUploadedFile() == null
|| fileBean.getUploadedFile().getFileName().length() == 0) &&
fileBean.getExternalUrl()!=null && fileBean.getExternalUrl().trim().length()>0) {
ActionMessage msg = new ActionMessage("errors.required",
"uploaded file");
msgs.add(ActionMessages.GLOBAL_MESSAGE, msg);
this.saveErrors(request, msgs);
noErrors = false;
}
}
return noErrors;
}
}
|
package at.fhtw.mcs.controller;
import static at.fhtw.mcs.util.NullSafety.emptyListIfNull;
import static java.util.Comparator.comparing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.Mixer;
import javax.xml.bind.JAXBException;
import at.fhtw.mcs.model.Format;
import at.fhtw.mcs.model.Project;
import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.ui.LocalizedAlertBuilder;
import at.fhtw.mcs.util.AudioOuput;
import at.fhtw.mcs.util.TrackFactory;
import at.fhtw.mcs.util.TrackFactory.UnsupportedFormatException;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.RadioButton;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
* Controller class for Root.fxml
*/
public class RootController implements Initializable {
/*
* Where to move those? ResourceBundles?
*/
private static final String ICON_PAUSE = "||";
private static final String ICON_PLAY = "\u25B6";
private static final String URL_MANUAL = "https://github.com/flpa/mcs/wiki";
@FXML
private VBox vboxTracks;
@FXML
private CheckMenuItem checkMenuItemSyncronizeStartPoints;
@FXML
private Menu menuOutputDevices;
@FXML
private MenuItem menuItemQuit;
@FXML
private MenuItem menuItemNewProject;
@FXML
private MenuItem menuItemOpenProject;
@FXML
private MenuItem menuItemSaveProject;
@FXML
private MenuItem menuItemSaveProjectAs;
@FXML
private MenuItem menuItemCloseProject;
@FXML
private MenuItem menuItemAddTracks;
@FXML
private MenuItem menuItemManual;
@FXML
private MenuItem menuItemAbout;
@FXML
private Button buttonPlayPause;
@FXML
private Button buttonStop;
@FXML
private Button buttonAddTracks;
@FXML
private Text textCurrentTime;
@FXML
private Text textTotalTime;
@FXML
private ProgressBar progressBarTime;
@FXML
private Slider sliderProgressBarTime;
@FXML
private ScrollPane scrollPaneTracks;
@FXML
private Rectangle rectangleSpacer;
@FXML
private Slider sliderMasterVolume;
private ToggleGroup toggleGroupActiveTrack = new ToggleGroup();
private ResourceBundle bundle;
private Stage stage;
private List<TrackController> trackControllers = new ArrayList<>();
private List<List<Button>> moveButtonList = new ArrayList<>();
private List<Button> deleteButtonList = new ArrayList<>();
private List<LineChart<Number, Number>> lineChartList = new ArrayList<>();
// TODO: could be a configuration parameter?
private long updateFrequencyMs = 100;
private int longestTrackFrameLength;
private long longestTrackMicrosecondsLength;
private Project project;
// debug variables
Boolean trackChanged = false;
int trackChangedChecker = 0;
public RootController(Stage stage) {
this.stage = stage;
stage.setOnCloseRequest(event -> {
if (handleUnsavedChanges() == false) {
event.consume();
}
});
}
@Override
public void initialize(URL viewSource, ResourceBundle translations) {
this.bundle = translations;
newProject();
menuItemQuit.setOnAction(e -> afterUnsavedChangesAreHandledDo(Platform::exit));
menuItemNewProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::newProject));
menuItemOpenProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::openProject));
menuItemSaveProject.setOnAction(e -> this.save());
menuItemSaveProject.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN));
menuItemSaveProjectAs.setOnAction(e -> this.saveAs());
menuItemCloseProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::closeProject));
menuItemAddTracks.setOnAction(this::handleAddTracks);
menuItemAbout.setOnAction(this::handleAbout);
menuItemManual.setOnAction(this::handleManual);
// TODO: inline lambdas vs methods?
buttonPlayPause.setOnAction(e -> {
getSelectedTrack().ifPresent(Track::togglePlayPause);
buttonPlayPause.setText(ICON_PLAY.equals(buttonPlayPause.getText()) ? ICON_PAUSE : ICON_PLAY);
});
buttonStop.setOnAction(this::handleStop);
buttonAddTracks.setOnAction(this::handleAddTracks);
sliderMasterVolume.setMax(1);
sliderMasterVolume.setMin(0);
// TODO: check if Volume changes if you alter the value with clicking
// instead of dragging
sliderMasterVolume.valueProperty()
.addListener((observable, oldValue, newValue) -> project.setMasterLevel((double) newValue));
checkMenuItemSyncronizeStartPoints.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
project.setSynchronizeStartPoints(newValue);
for (TrackController trackController : trackControllers) {
trackController.drawTrack();
}
}
});
ToggleGroup toggleGroupOutputDevice = new ToggleGroup();
// @formatter:off
Arrays.stream(AudioSystem.getMixerInfo()).filter(RootController::isOutputMixerInfo).forEach(info -> {
RadioMenuItem radio = new RadioMenuItem();
radio.setText(String.format("%s (%s)", info.getName(), info.getDescription()));
radio.setUserData(info);
radio.setToggleGroup(toggleGroupOutputDevice);
radio.setSelected(info.equals(AudioOuput.getSelectedMixerInfo()));
menuOutputDevices.getItems().add(radio);
});
// @formatter:on
toggleGroupOutputDevice.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> value, Toggle previousSelection,
Toggle newSelection) {
/*
* When modifying grouped RadioMenuItems, this is invoked twice:
* 1) oldValue and null 2) null and newValue
*/
if (newSelection != null) {
AudioOuput.setSelectedMixerInfo((Mixer.Info) newSelection.getUserData());
project.getTracks().forEach(Track::reload);
}
}
});
toggleGroupActiveTrack.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> value, Toggle previousSelection,
Toggle newSelection) {
long currentMs = 0;
boolean wasPlaying = false;
trackChanged = true;
if (previousSelection != null) {
Track prevTrack = (Track) previousSelection.getUserData();
wasPlaying = prevTrack.isPlaying();
prevTrack.pause();
currentMs = prevTrack.getCurrentMicroseconds();
}
if (newSelection != null) {
Track newTrack = (Track) newSelection.getUserData();
newTrack.setCurrentMicroseconds(currentMs);
if (wasPlaying) {
newTrack.play();
}
}
setStylesheetsForTracks();
}
});
/*
* Start the update thread here to prevent multiple threads when adding
* a track, deleting it, adding a track [...]
*/
startTimeUpdateThread();
// Eventlistener to change the Playbackpoint
// TODO fix bug, where timeline is set back when switching between
// tracks
sliderProgressBarTime.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if ((double) newValue - (double) oldValue > 2_500_000 || (double) newValue - (double) oldValue < 0) {
if (!trackChanged) {
for (Track track : project.getTracks()) {
long temp = Math.round((double) newValue);
track.setCurrentMicroseconds(temp + 250000);
// System.out.println("valuechange: " + newValue +
// ":" + oldValue);
}
}
}
}
});
}
private void afterUnsavedChangesAreHandledDo(Runnable callback) {
if (handleUnsavedChanges()) {
callback.run();
}
}
private boolean handleUnsavedChanges() {
return project.hasUnsavedChanges() == false || letUserHandleUnsavedChanges();
}
private boolean letUserHandleUnsavedChanges() {
// ButtonData.YES means this is our default button
ButtonType save = new ButtonType(bundle.getString("alert.unsavedChanges.button.save"), ButtonData.YES);
ButtonType proceedWithoutSaving = new ButtonType(
bundle.getString("alert.unsavedChanges.button.proceedWithoutSaving"));
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.unsavedChanges.",
AlertType.CONFIRMATION);
builder.setButtons(proceedWithoutSaving, ButtonType.CANCEL, save);
builder.setHeaderFormatParameters(getProjectName());
Optional<ButtonType> result = builder.build().showAndWait();
return result.isPresent() && (result.get() == proceedWithoutSaving || (result.get() == save && save()));
}
private String getProjectName() {
String name = project.getName();
return name == null ? bundle.getString("project.unnamed") : name;
}
private boolean save() {
if (project.getDirectory() == null) {
return saveAs();
}
return saveAndCatchErrors();
}
private boolean saveAs() {
Optional<File> directory = letUserChooseProjectDirectory();
if (directory.isPresent()) {
project.setDirectory(directory.get());
return saveAndCatchErrors();
}
return false;
}
private Optional<File> letUserChooseProjectDirectory() {
DirectoryChooser directoryChooser = new DirectoryChooser();
return Optional.ofNullable(directoryChooser.showDialog(stage));
}
private boolean saveAndCatchErrors() {
boolean success = false;
try {
project.save();
updateApplicationTitle();
success = true;
} catch (IOException e) {
handleSaveError(e);
}
return success;
}
private void handleSaveError(IOException e) {
e.printStackTrace();
new LocalizedAlertBuilder(bundle, "alert.saveFailed.", AlertType.ERROR).build().showAndWait();
}
private void newProject() {
setProject(new Project());
}
private void setProject(Project project) {
removeAllTracks();
this.project = project;
updateApplicationTitle();
loadTrackUis(project.getTracks());
sliderMasterVolume.setValue(project.getMasterLevel());
checkMenuItemSyncronizeStartPoints.setSelected(project.isSynchronizeStartPoints());
project.unsavedChangesProperty().addListener((observable, oldValue, newValue) -> this.updateApplicationTitle());
}
private void removeAllTracks() {
if (this.project != null) {
int trackCount = this.project.getTracks().size();
for (int i = 0; i < trackCount; i++) {
// removing first track until all have been removed
removeTrack(0);
}
}
}
private void openProject() {
Optional<File> chosenDirectory = letUserChooseProjectDirectory();
if (chosenDirectory.isPresent()) {
try {
setProject(Project.load(chosenDirectory.get()));
} catch (FileNotFoundException | JAXBException e) {
handleOpenError(e);
}
}
}
private void handleOpenError(Exception e) {
e.printStackTrace();
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.loadFailed.", AlertType.ERROR);
builder.setContentKey(e instanceof FileNotFoundException ? "content.loadError" : "content.parseError");
builder.build().showAndWait();
}
private void closeProject() {
newProject();
}
private void updateApplicationTitle() {
String format = MessageFormat.format(bundle.getString("app.title"), getProjectName());
if (project.hasUnsavedChanges()) {
format += "*";
}
stage.setTitle(format);
}
private static boolean isOutputMixerInfo(Mixer.Info info) {
return AudioSystem.getMixer(info).isLineSupported(new Line.Info(Clip.class));
}
private Optional<Track> getSelectedTrack() {
Toggle selectedToggle = toggleGroupActiveTrack.getSelectedToggle();
if (selectedToggle == null) {
return Optional.empty();
}
return Optional.of((Track) selectedToggle.getUserData());
}
private void updateTime() {
Optional<Track> selectedTrack = getSelectedTrack();
if (selectedTrack.isPresent() == false) {
return;
}
if (trackChanged && trackChangedChecker > 10) {
trackChanged = false;
trackChangedChecker = 0;
} else if (trackChanged) {
trackChangedChecker++;
}
Track currentTrack = selectedTrack.get();
long currentMicroseconds = currentTrack.getCurrentMicroseconds();
double progress = (double) currentMicroseconds / longestTrackMicrosecondsLength;
boolean currentTrackHasEnded = currentTrack.getTotalMicroseconds() == currentMicroseconds;
/*
* Disable tracks with a length shorter than the current position. Also
* enables them again after resetting via stop.
*/
for (Toggle toggle : toggleGroupActiveTrack.getToggles()) {
RadioButton radio = (RadioButton) toggle;
Track track = (Track) radio.getUserData();
radio.setDisable(track != currentTrack && currentMicroseconds > track.getTotalMicroseconds());
}
Platform.runLater(() -> {
progressBarTime.setProgress(progress);
sliderProgressBarTime.setValue(currentMicroseconds - 250000);
textCurrentTime.setText(formatTimeString(currentMicroseconds));
if (currentTrackHasEnded) {
buttonPlayPause.setText(ICON_PLAY);
}
});
}
private void handleAddTracks(ActionEvent event) {
FileChooser chooser = new FileChooser();
/*
* TODO: change filter from hardcoded to a responsible class
*/
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(
bundle.getString("fileChooser.addTrack.filterText"), "*.mp3", "*.wav", "*.wave", "*.aif", "*.aiff");
chooser.getExtensionFilters().add(filter);
List<File> files = emptyListIfNull(chooser.showOpenMultipleDialog(stage));
for (File file : files) {
addFile(file);
}
}
public void addFile(File file) {
Track track;
try {
track = TrackFactory.loadTrack(file.getAbsolutePath());
} catch (UnsupportedFormatException e) {
this.showErrorUnsupportedFormat(e.getFormat(), e.getAudioFormat());
return;
} catch (OutOfMemoryError e) {
this.showErrorOutOfMemory();
return;
}
if (checkMenuItemSyncronizeStartPoints.isSelected()) {
track.applyStartPointOffset();
}
/*
* Needs to be added before drawing so that the longest track can be
* determined.
*/
project.addTrack(track);
loadTrackUis(Arrays.asList(track));
}
private void loadTrackUis(List<Track> tracks) {
determineLongestTrackLengths();
for (Track track : tracks) {
loadTrackUi(track);
}
setPlaybackControlsDisable(tracks.isEmpty());
addButtonsAndChart();
project.setLoudnessLevel();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
}
public void setPlaybackControlsDisable(boolean disable) {
buttonPlayPause.setDisable(disable);
buttonStop.setDisable(disable);
}
public void determineLongestTrackLengths() {
if (project.getTracks().isEmpty()) {
return;
}
Track longestTrack = project.getTracks().stream().max(comparing(Track::getTotalMicroseconds)).get();
longestTrackFrameLength = longestTrack.getLengthWeighted();
longestTrackMicrosecondsLength = longestTrack.getTotalMicroseconds();
trackControllers.forEach(controller -> controller.setLongestTrackFrameLength(longestTrackFrameLength));
String timeString = formatTimeString(longestTrackMicrosecondsLength);
textTotalTime.setText(timeString);
// Set the Slider to the same length as the Progressbar
sliderProgressBarTime.setMin(0);
sliderProgressBarTime.setMax(longestTrackMicrosecondsLength - 250000);
}
private void loadTrackUi(Track track) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setController(new TrackController(track, toggleGroupActiveTrack, longestTrackFrameLength));
loader.setLocation(getClass().getClassLoader().getResource("views/Track.fxml"));
loader.setResources(bundle);
trackControllers.add(loader.getController());
vboxTracks.getChildren().add(loader.load());
} catch (IOException e) {
throw new RuntimeException("Error while loading track UI.", e);
}
}
private void startTimeUpdateThread() {
Timer timer = new Timer(true);
/*
* Reading the documentation of timer.schedule(...), it seems like
* there's no danger of timer-execution-congestion when a time
* invocation blocks: "[...]each execution is scheduled relative to the
* actual execution time of the previous execution."
*/
timer.schedule(new TimerTask() {
@Override
public void run() {
long prevMillis = System.currentTimeMillis();
updateTime();
long elapsedMs = System.currentTimeMillis() - prevMillis;
if (elapsedMs >= updateFrequencyMs) {
System.err.println(
String.format("Warning: Time update (%dms) took longer than the update frequency (%dms).",
elapsedMs, updateFrequencyMs));
}
}
}, 0, updateFrequencyMs);
}
private String formatTimeString(long totalMicroseconds) {
long minutes = TimeUnit.MICROSECONDS.toMinutes(totalMicroseconds);
long seconds = TimeUnit.MICROSECONDS.toSeconds(totalMicroseconds) % 60;
return String.format("%d:%02d", minutes, seconds);
}
private void handleStop(ActionEvent event) {
getSelectedTrack().ifPresent(Track::stop);
buttonPlayPause.setText(ICON_PLAY);
}
private void handleAbout(ActionEvent event) {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "about.", AlertType.INFORMATION);
Alert alertAbout = builder.build();
alertAbout.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
// TODO: auto-resize to content
alertAbout.getDialogPane().setPrefWidth(700);
alertAbout.showAndWait();
}
private void handleManual(ActionEvent event) {
if (java.awt.Desktop.isDesktopSupported()) {
new Thread(() -> {
try {
java.awt.Desktop.getDesktop().browse(new java.net.URI(URL_MANUAL));
} catch (IOException | URISyntaxException e) {
System.err.println("Error while opening manual webpage.");
e.printStackTrace();
}
}).start();
} else {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "manual.", AlertType.INFORMATION);
String contentText = bundle.getString("manual.content");
contentText += URL_MANUAL;
builder.setContentText(contentText);
Alert alertManual = builder.build();
alertManual.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertManual.getDialogPane().setPrefWidth(700);
alertManual.showAndWait();
}
}
private void showErrorUnsupportedFormat(Format format, AudioFormat audioFormat) {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "errorUnsupportedFormat.", AlertType.ERROR);
builder.setHeaderText(null);
String errorText = bundle.getString(determineErrorDescriptionForFormat(format, audioFormat));
errorText += bundle.getString("errorUnsupportedFormat.supportedFormats");
builder.setContentText(errorText);
Alert alertError = builder.build();
alertError.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertError.getDialogPane().setPrefWidth(700);
alertError.showAndWait();
}
private String determineErrorDescriptionForFormat(Format format, AudioFormat audioFormat) {
if (audioFormat == null) {
return "errorUnsupportedFormat.contentDefault";
}
switch (format) {
case AIFF:
case WAV:
if (audioFormat.getSampleSizeInBits() == 24) {
return "errorUnsupportedFormat.content24bit";
} else {
return "errorUnsupportedFormat.contentDefault";
}
case MP3:
return "errorUnsupportedFormat.contentMp3";
default:
return "errorUnsupportedFormat.contentDefault";
}
}
private void showErrorOutOfMemory() {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "errorOutOfMemory.", AlertType.ERROR);
builder.setHeaderText(null);
Alert alertError = builder.build();
alertError.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertError.getDialogPane().setPrefWidth(700);
alertError.showAndWait();
}
private void addButtonsAndChart() {
moveButtonList.clear();
deleteButtonList.clear();
lineChartList.clear();
for (int i = 0; i < trackControllers.size(); i++) {
// deleteButton
deleteButtonList.add(trackControllers.get(i).getButtonDelete());
// moveButtons
List<Button> tempList = new ArrayList<>();
tempList.add(trackControllers.get(i).getButtonMoveUp());
tempList.add(trackControllers.get(i).getButtonMoveDown());
moveButtonList.add(tempList);
// Linechart Waveform
lineChartList.add(trackControllers.get(i).getChart());
}
}
private void setMoveButtons() {
List<Track> tracks = project.getTracks();
for (int i = 0; i < tracks.size(); i++) {
if (i == 0) {
moveButtonList.get(i).get(0).setDisable(true);
moveButtonList.get(i).get(1).setDisable(false);
} else if (i < tracks.size() - 1) {
moveButtonList.get(i).get(0).setDisable(false);
moveButtonList.get(i).get(1).setDisable(false);
}
if (i == tracks.size() - 1) {
moveButtonList.get(i).get(1).setDisable(true);
}
}
}
private void setButtonsEventHandler() {
for (int i = 0; i < moveButtonList.size(); i++) {
final int trackNumber = i;
deleteButtonList.get(i).setOnAction(e -> {
deleteTrack(trackNumber);
});
for (int j = 0; j < moveButtonList.get(i).size(); j++) {
final int buttonNumber = j;
moveButtonList.get(i).get(j).setOnAction(e -> {
if (buttonNumber != 1) {
moveUp(trackNumber);
} else {
moveDown(trackNumber);
}
});
}
}
}
private void setLineChartEventHandler() {
for (int i = 0; i < lineChartList.size(); i++) {
final int trackNumber = i;
lineChartList.get(i).setOnMouseClicked(e -> {
trackControllers.get(trackNumber).setRadioButtonActive();
if (trackControllers.get(trackNumber).getRadioButtonActiveTrack().isSelected()) {
trackControllers.get(trackNumber).getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/ActiveTrack.css").toExternalForm());
}
});
}
}
private void deleteTrack(int number) {
List<Track> tracks = project.getTracks();
String trackName = tracks.get(number).getName();
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.deleteTrack.", AlertType.CONFIRMATION);
builder.setHeaderFormatParameters(trackName);
Optional<ButtonType> result = builder.build().showAndWait();
if (result.get() == ButtonType.OK) {
removeTrack(number);
determineLongestTrackLengths();
}
}
private void removeTrack(int number) {
List<Track> tracks = project.getTracks();
handleStop(null);
vboxTracks.getChildren().remove(number);
Track removed = tracks.remove(number);
toggleGroupActiveTrack.getToggles().removeIf(toggle -> toggle.getUserData().equals(removed));
trackControllers.remove(number);
moveButtonList.remove(number);
deleteButtonList.remove(number);
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
project.setLoudnessLevel();
if (tracks.size() > 0) {
trackControllers.get(0).getRadioButtonActiveTrack().fire();
} else {
setPlaybackControlsDisable(true);
}
}
private void moveUp(int number) {
if (number != 0) {
List<Node> tempVboxTracks = new ArrayList<>();
List<TrackController> tempTrackController = new ArrayList<>();
List<Track> tempTracks = new ArrayList<>();
List<Track> tracks = project.getTracks();
for (int i = 0; i < vboxTracks.getChildren().size(); i++) {
if (i == number - 1) {
tempVboxTracks.add(vboxTracks.getChildren().get(i + 1));
tempTrackController.add(trackControllers.get(i + 1));
tempTracks.add(tracks.get(i + 1));
} else if (i == number) {
tempVboxTracks.add(vboxTracks.getChildren().get(i - 1));
tempTrackController.add(trackControllers.get(i - 1));
tempTracks.add(tracks.get(i - 1));
} else {
tempVboxTracks.add(vboxTracks.getChildren().get(i));
tempTrackController.add(trackControllers.get(i));
tempTracks.add(tracks.get(i));
}
}
vboxTracks.getChildren().clear();
trackControllers.clear();
tracks.clear();
for (int i = 0; i < tempVboxTracks.size(); i++) {
vboxTracks.getChildren().add(tempVboxTracks.get(i));
trackControllers.add(tempTrackController.get(i));
tracks.add(tempTracks.get(i));
}
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
}
}
private void moveDown(int number) {
List<Track> tracks = project.getTracks();
if (number != tracks.size() - 1) {
List<Node> tempVboxTracks = new ArrayList<>();
List<TrackController> tempTrackController = new ArrayList<>();
List<Track> tempTracks = new ArrayList<>();
for (int i = 0; i < vboxTracks.getChildren().size(); i++) {
if (i == number + 1) {
tempVboxTracks.add(vboxTracks.getChildren().get(i - 1));
tempTrackController.add(trackControllers.get(i - 1));
tempTracks.add(tracks.get(i - 1));
} else if (i == number) {
tempVboxTracks.add(vboxTracks.getChildren().get(i + 1));
tempTrackController.add(trackControllers.get(i + 1));
tempTracks.add(tracks.get(i + 1));
} else {
tempVboxTracks.add(vboxTracks.getChildren().get(i));
tempTrackController.add(trackControllers.get(i));
tempTracks.add(tracks.get(i));
}
}
vboxTracks.getChildren().clear();
trackControllers.clear();
tracks.clear();
for (int i = 0; i < tempVboxTracks.size(); i++) {
vboxTracks.getChildren().add(tempVboxTracks.get(i));
trackControllers.add(tempTrackController.get(i));
tracks.add(tempTracks.get(i));
}
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
}
}
private void setStylesheetsForTracks() {
for (TrackController trackController : trackControllers) {
trackController.getChart().getStylesheets().clear();
if (trackController.getRadioButtonActiveTrack().isSelected()) {
trackController.getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/ActiveTrack.css").toExternalForm());
} else {
trackController.getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/NotActiveTrack.css").toExternalForm());
}
}
}
public void sceneInitialization(Scene scene) {
scene.getAccelerators().put(new KeyCodeCombination(KeyCode.SPACE), buttonPlayPause::fire);
// To unfocus the comment text field
scene.setOnMouseClicked(event -> scene.getRoot().requestFocus());
}
}
|
package de.gurkenlabs.utiliti.components;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.IUpdateable;
import de.gurkenlabs.litiengine.Resources;
import de.gurkenlabs.litiengine.SpriteSheetInfo;
import de.gurkenlabs.litiengine.Valign;
import de.gurkenlabs.litiengine.entities.CollisionEntity;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.entities.LightSource;
import de.gurkenlabs.litiengine.environment.Environment;
import de.gurkenlabs.litiengine.environment.IEnvironment;
import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer;
import de.gurkenlabs.litiengine.environment.tilemap.IMap;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObject;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.ITileset;
import de.gurkenlabs.litiengine.environment.tilemap.MapLoader;
import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty;
import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType;
import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Map;
import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject;
import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset;
import de.gurkenlabs.litiengine.graphics.ImageCache;
import de.gurkenlabs.litiengine.graphics.ImageFormat;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.graphics.TextRenderer;
import de.gurkenlabs.litiengine.gui.ComponentMouseEvent;
import de.gurkenlabs.litiengine.gui.ComponentMouseWheelEvent;
import de.gurkenlabs.litiengine.gui.GuiComponent;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.util.ColorHelper;
import de.gurkenlabs.litiengine.util.MathUtilities;
import de.gurkenlabs.litiengine.util.geom.GeometricUtilities;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
import de.gurkenlabs.litiengine.util.io.ImageSerializer;
import de.gurkenlabs.litiengine.util.io.XmlUtilities;
import de.gurkenlabs.utiliti.EditorScreen;
import de.gurkenlabs.utiliti.Program;
import de.gurkenlabs.utiliti.UndoManager;
import de.gurkenlabs.utiliti.swing.XmlImportDialog;
public class MapComponent extends EditorComponent implements IUpdateable {
public enum TransformType {
UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, NONE
}
public static final int EDITMODE_CREATE = 0;
public static final int EDITMODE_EDIT = 1;
public static final int EDITMODE_MOVE = 2;
private static final Logger log = Logger.getLogger(MapComponent.class.getName());
private static final float[] zooms = new float[] { 0.1f, 0.25f, 0.5f, 1, 1.5f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 16f, 32f, 50f, 80f, 100f };
private static final String DEFAULT_MAPOBJECTLAYER_NAME = "default";
private static final int TRANSFORM_RECT_SIZE = 6;
private static final int BASE_SCROLL_SPEED = 50;
private static final Color DEFAULT_COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35);
private static final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15);
private static final Color COLOR_COLLISION_BORDER = Color.RED;
private static final Color COLOR_NOCOLLISION_BORDER = new Color(255, 0, 0, 150);
private static final Color COLOR_TRIGGER_BORDER = Color.YELLOW;
private static final Color COLOR_TRIGGER_FILL = new Color(255, 255, 0, 15);
private static final Color COLOR_SPAWNPOINT = Color.GREEN;
private static final Color COLOR_LANE = Color.YELLOW;
private static final Color COLOR_NEWOBJECT_FILL = new Color(0, 255, 0, 50);
private static final Color COLOR_NEWOBJECT_BORDER = Color.GREEN.darker();
private static final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100);
private static final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15);
private static final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170);
private static final Color COLOR_MOUSE_SELECTION_AREA_FILL = new Color(0, 130, 152, 80);
private static final Color COLOR_MOUSE_SELECTION_AREA_BORDER = new Color(0, 130, 152, 150);
private double currentTransformRectSize = TRANSFORM_RECT_SIZE;
private final java.util.Map<TransformType, Rectangle2D> transformRects;
private final List<Consumer<Integer>> editModeChangedConsumer;
private final List<Consumer<IMapObject>> focusChangedConsumer;
private final List<Consumer<List<IMapObject>>> selectionChangedConsumer;
private final List<Consumer<Map>> mapLoadedConsumer;
private final java.util.Map<String, Integer> selectedLayers;
private final java.util.Map<String, Point2D> cameraFocus;
private final java.util.Map<String, IMapObject> focusedObjects;
private final java.util.Map<String, List<IMapObject>> selectedObjects;
private final java.util.Map<String, IEnvironment> environments;
private final java.util.Map<IMapObject, Point2D> dragLocationMapObjects;
private int currentEditMode = EDITMODE_EDIT;
private TransformType currentTransform;
private int currentZoomIndex = 7;
private final List<Map> maps;
private float scrollSpeed = BASE_SCROLL_SPEED;
private Point2D startPoint;
private Point2D dragPoint;
private boolean isMoving;
private boolean isMovingWithKeyboard;
private boolean isTransforming;
private boolean isFocussing;
private float dragSizeHeight;
private float dragSizeWidth;
private Rectangle2D newObjectArea;
private Blueprint copiedBlueprint;
private int gridSize;
private Color colorSelectionBorder;
private float focusBorderBrightness = 0;
private boolean focusBorderBrightnessIncreasing = true;
private final EditorScreen screen;
private boolean loading;
private boolean initialized;
public MapComponent(final EditorScreen screen) {
super(ComponentType.MAP);
this.editModeChangedConsumer = new CopyOnWriteArrayList<>();
this.focusChangedConsumer = new CopyOnWriteArrayList<>();
this.selectionChangedConsumer = new CopyOnWriteArrayList<>();
this.mapLoadedConsumer = new CopyOnWriteArrayList<>();
this.focusedObjects = new ConcurrentHashMap<>();
this.selectedObjects = new ConcurrentHashMap<>();
this.environments = new ConcurrentHashMap<>();
this.maps = new ArrayList<>();
this.selectedLayers = new ConcurrentHashMap<>();
this.cameraFocus = new ConcurrentHashMap<>();
this.transformRects = new ConcurrentHashMap<>();
this.dragLocationMapObjects = new ConcurrentHashMap<>();
this.screen = screen;
Game.getCamera().onZoomChanged(zoom -> {
this.currentTransformRectSize = TRANSFORM_RECT_SIZE / zoom;
this.updateTransformControls();
});
this.gridSize = Program.getUserPreferences().getGridSize();
}
public void onEditModeChanged(Consumer<Integer> cons) {
this.editModeChangedConsumer.add(cons);
}
public void onFocusChanged(Consumer<IMapObject> cons) {
this.focusChangedConsumer.add(cons);
}
public void onSelectionChanged(Consumer<List<IMapObject>> cons) {
this.selectionChangedConsumer.add(cons);
}
public void onMapLoaded(Consumer<Map> cons) {
this.mapLoadedConsumer.add(cons);
}
@Override
public void render(Graphics2D g) {
if (Game.getEnvironment() == null) {
return;
}
this.renderGrid(g);
final BasicStroke shapeStroke = new BasicStroke(1 / Game.getCamera().getRenderScale());
if (Program.getUserPreferences().isRenderBoundingBoxes()) {
this.renderMapObjectBounds(g);
}
switch (this.currentEditMode) {
case EDITMODE_CREATE:
this.renderNewObjectArea(g, shapeStroke);
break;
case EDITMODE_EDIT:
this.renderMouseSelectionArea(g, shapeStroke);
break;
default:
break;
}
this.renderSelection(g);
this.renderFocus(g);
super.render(g);
}
public void loadMaps(String projectPath) {
final List<String> files = FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "tmx");
log.log(Level.INFO, "{0} maps found in folder {1}", new Object[] { files.size(), projectPath });
final List<Map> loadedMaps = new ArrayList<>();
for (final String mapFile : files) {
Map map = (Map) MapLoader.load(mapFile);
loadedMaps.add(map);
log.log(Level.INFO, "map found: {0}", new Object[] { map.getName() });
}
this.loadMaps(loadedMaps);
}
public void loadMaps(List<Map> maps) {
if (maps == null) {
return;
}
EditorScreen.instance().getMapObjectPanel().bind(null);
this.setFocus(null, true);
this.getMaps().clear();
Collections.sort(maps);
this.getMaps().addAll(maps);
EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps(), true);
}
public List<Map> getMaps() {
return this.maps;
}
public int getGridSize() {
return this.gridSize;
}
public IMapObject getFocusedMapObject() {
if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) {
return this.focusedObjects.get(Game.getEnvironment().getMap().getName());
}
return null;
}
public List<IMapObject> getSelectedMapObjects() {
final String map = Game.getEnvironment().getMap().getName();
if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null && this.selectedObjects.containsKey(map)) {
return this.selectedObjects.get(map);
}
return new ArrayList<>();
}
public Blueprint getCopiedBlueprint() {
return this.copiedBlueprint;
}
public boolean isLoading() {
return this.loading;
}
@Override
public void prepare() {
Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0);
if (!this.initialized) {
Game.getScreenManager().getRenderComponent().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
startPoint = null;
}
});
this.setupKeyboardControls();
this.setupMouseControls();
this.initialized = true;
Game.getLoop().attach(this);
}
super.prepare();
}
public void loadEnvironment(Map map) {
if(map == null) {
return;
}
this.loading = true;
try {
if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) {
final String mapName = Game.getEnvironment().getMap().getName();
double x = Game.getCamera().getFocus().getX();
double y = Game.getCamera().getFocus().getY();
Point2D newPoint = new Point2D.Double(x, y);
this.cameraFocus.put(mapName, newPoint);
this.selectedLayers.put(mapName, EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex());
}
Point2D newFocus = null;
if (this.cameraFocus.containsKey(map.getName())) {
newFocus = this.cameraFocus.get(map.getName());
} else {
newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2);
this.cameraFocus.put(map.getName(), newFocus);
}
Game.getCamera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY()));
this.ensureUniqueIds(map);
if (!this.environments.containsKey(map.getName())) {
Environment env = new Environment(map);
env.init();
this.environments.put(map.getName(), env);
}
Game.loadEnvironment(this.environments.get(map.getName()));
Program.updateScrollBars();
EditorScreen.instance().getMapSelectionPanel().setSelection(map.getName());
if (this.selectedLayers.containsKey(map.getName())) {
EditorScreen.instance().getMapSelectionPanel().selectLayer(this.selectedLayers.get(map.getName()));
}
EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject());
for (Consumer<Map> cons : this.mapLoadedConsumer) {
cons.accept(map);
}
} finally {
this.loading = false;
}
}
public void reloadEnvironment() {
if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) {
return;
}
this.loadEnvironment((Map) Game.getEnvironment().getMap());
}
public void add(IMapObject mapObject) {
this.add(mapObject, getCurrentLayer());
UndoManager.instance().mapObjectAdded(mapObject);
}
public void add(IMapObjectLayer layer) {
if (layer == null) {
return;
}
this.getSelectedMapObjects().clear();
this.setFocus(null, true);
for (IMapObject mapObject : layer.getMapObjects()) {
Game.getEnvironment().loadFromMap(mapObject.getId());
if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) {
Game.getEnvironment().getAmbientLight().updateSection(mapObject.getBoundingBox());
}
this.setSelection(mapObject, false);
this.setFocus(mapObject, false);
}
this.updateTransformControls();
this.setEditMode(EDITMODE_MOVE);
}
public void delete(IMapObjectLayer layer) {
if (layer == null) {
return;
}
for (IMapObject mapObject : layer.getMapObjects()) {
if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) {
Game.getEnvironment().getAmbientLight().updateSection(mapObject.getBoundingBox());
}
Game.getEnvironment().remove(mapObject.getId());
if (mapObject.equals(this.getFocusedMapObject())) {
this.setFocus(null, true);
}
this.getSelectedMapObjects().remove(mapObject);
}
}
public void add(IMapObject mapObject, IMapObjectLayer layer) {
if (layer == null || mapObject == null) {
return;
}
layer.addMapObject(mapObject);
Game.getEnvironment().loadFromMap(mapObject.getId());
if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) {
Game.getEnvironment().getAmbientLight().updateSection(mapObject.getBoundingBox());
}
Game.getScreenManager().getRenderComponent().requestFocus();
this.setFocus(mapObject, false);
this.setEditMode(EDITMODE_EDIT);
}
public void copy() {
this.copiedBlueprint = new Blueprint("", this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()]));
}
public void paste() {
if (this.copiedBlueprint == null) {
return;
}
int x = (int) Input.mouse().getMapLocation().getX();
int y = (int) Input.mouse().getMapLocation().getY();
this.paste(x, y);
}
public void paste(int x, int y) {
if (this.copiedBlueprint == null) {
return;
}
UndoManager.instance().beginOperation();
try {
this.setFocus(null, true);
for (IMapObject mapObject : this.copiedBlueprint.build(x, y)) {
this.add(mapObject);
this.setSelection(mapObject, false);
}
// clean up copied blueprints in case, we cut the objects and kept the IDs
if (this.copiedBlueprint.keepIds()) {
this.copiedBlueprint = null;
}
} finally {
UndoManager.instance().endOperation();
}
}
public void cut() {
this.copiedBlueprint = new Blueprint("", true, this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()]));
UndoManager.instance().beginOperation();
try {
for (IMapObject mapObject : this.getSelectedMapObjects()) {
this.delete(mapObject);
UndoManager.instance().mapObjectDeleted(mapObject);
}
} finally {
UndoManager.instance().endOperation();
}
}
public void clearAll() {
this.focusedObjects.clear();
this.selectedLayers.clear();
this.selectedObjects.clear();
this.cameraFocus.clear();
this.environments.clear();
}
public void delete() {
UndoManager.instance().beginOperation();
try {
for (IMapObject deleteObject : this.getSelectedMapObjects()) {
if (deleteObject == null) {
continue;
}
UndoManager.instance().mapObjectDeleted(deleteObject);
this.delete(deleteObject);
}
} finally {
UndoManager.instance().endOperation();
}
}
public void delete(final IMapObject mapObject) {
if (mapObject == null) {
return;
}
MapObjectType type = MapObjectType.get(mapObject.getType());
Game.getEnvironment().getMap().removeMapObject(mapObject.getId());
Game.getEnvironment().remove(mapObject.getId());
if (type == MapObjectType.STATICSHADOW || type == MapObjectType.LIGHTSOURCE) {
Game.getEnvironment().getAmbientLight().updateSection(mapObject.getBoundingBox());
}
if (mapObject.equals(this.getFocusedMapObject())) {
this.setFocus(null, true);
}
}
public void defineBlueprint() {
if (this.getFocusedMapObject() == null) {
return;
}
Object name = JOptionPane.showInputDialog(Game.getScreenManager().getRenderComponent(), Resources.get("input_prompt_name"), Resources.get("input_prompt_name_title"), JOptionPane.PLAIN_MESSAGE, null, null, this.getFocusedMapObject().getName());
if (name == null) {
return;
}
Blueprint blueprint = new Blueprint(name.toString(), this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()]));
EditorScreen.instance().getGameFile().getBluePrints().add(blueprint);
Program.getAssetTree().forceUpdate();
}
public void centerCameraOnFocus() {
if (this.getFocusedMapObject() != null) {
final Rectangle2D focus = this.getFocus();
if (focus == null) {
return;
}
Game.getCamera().setFocus(new Point2D.Double(focus.getCenterX(), focus.getCenterY()));
}
}
public void setEditMode(int editMode) {
if (editMode == this.currentEditMode) {
return;
}
switch (editMode) {
case EDITMODE_CREATE:
this.setFocus(null, true);
EditorScreen.instance().getMapObjectPanel().bind(null);
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_ADD, 0, 0);
break;
case EDITMODE_EDIT:
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
break;
case EDITMODE_MOVE:
EditorScreen.instance().getMapObjectPanel().bind(null);
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_MOVE, 0, 0);
break;
default:
break;
}
this.currentEditMode = editMode;
for (Consumer<Integer> cons : this.editModeChangedConsumer) {
cons.accept(this.currentEditMode);
}
}
public void setFocus(IMapObject mapObject, boolean clearSelection) {
if (this.isFocussing) {
return;
}
this.isFocussing = true;
try {
final IMapObject currentFocus = this.getFocusedMapObject();
if (mapObject != null && currentFocus != null && mapObject.equals(currentFocus) || mapObject == null && currentFocus == null) {
return;
}
if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) {
return;
}
if (this.isMoving || this.isTransforming) {
return;
}
EditorScreen.instance().getMapObjectPanel().bind(mapObject);
EditorScreen.instance().getMapSelectionPanel().focus(mapObject);
if (mapObject == null) {
this.focusedObjects.remove(Game.getEnvironment().getMap().getName());
} else {
this.focusedObjects.put(Game.getEnvironment().getMap().getName(), mapObject);
}
for (Consumer<IMapObject> cons : this.focusChangedConsumer) {
cons.accept(mapObject);
}
this.updateTransformControls();
this.setSelection(mapObject, clearSelection);
} finally {
this.isFocussing = false;
}
}
public void setSelection(IMapObject mapObject, boolean clearSelection) {
if (mapObject == null) {
this.getSelectedMapObjects().clear();
for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) {
cons.accept(this.getSelectedMapObjects());
}
return;
}
final String map = Game.getEnvironment().getMap().getName();
if (!this.selectedObjects.containsKey(map)) {
this.selectedObjects.put(map, new CopyOnWriteArrayList<>());
}
if (clearSelection) {
this.getSelectedMapObjects().clear();
}
if (!this.getSelectedMapObjects().contains(mapObject)) {
this.getSelectedMapObjects().add((MapObject) mapObject);
}
for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) {
cons.accept(this.getSelectedMapObjects());
}
}
public void setSelection(List<IMapObject> mapObjects, boolean clearSelection) {
if (mapObjects == null || mapObjects.isEmpty()) {
this.getSelectedMapObjects().clear();
for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) {
cons.accept(this.getSelectedMapObjects());
}
return;
}
final String map = Game.getEnvironment().getMap().getName();
if (!this.selectedObjects.containsKey(map)) {
this.selectedObjects.put(map, new CopyOnWriteArrayList<>());
}
if (clearSelection) {
this.getSelectedMapObjects().clear();
}
for (IMapObject mapObject : mapObjects) {
if (!this.getSelectedMapObjects().contains(mapObject)) {
this.getSelectedMapObjects().add((MapObject) mapObject);
}
}
for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) {
cons.accept(this.getSelectedMapObjects());
}
}
public void setGridSize(int gridSize) {
Program.getUserPreferences().setGridSize(gridSize);
this.gridSize = gridSize;
}
public void updateTransformControls() {
final Rectangle2D focus = this.getFocus();
if (focus == null) {
this.transformRects.clear();
return;
}
for (TransformType trans : TransformType.values()) {
if (trans == TransformType.NONE) {
continue;
}
Rectangle2D transRect = new Rectangle2D.Double(this.getTransX(trans, focus), this.getTransY(trans, focus), this.currentTransformRectSize, this.currentTransformRectSize);
this.transformRects.put(trans, transRect);
}
}
public void deleteMap() {
if (this.getMaps() == null || this.getMaps().isEmpty()) {
return;
}
if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) {
return;
}
int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("hud_deleteMapMessage") + "\n" + Game.getEnvironment().getMap().getName(), Resources.get("hud_deleteMap"), JOptionPane.YES_NO_OPTION);
if (n != JOptionPane.YES_OPTION) {
return;
}
this.getMaps().removeIf(x -> x.getName().equals(Game.getEnvironment().getMap().getName()));
// TODO: remove all tile sets from the game file that are no longer needed
// by any other map.
EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps());
if (!this.maps.isEmpty()) {
this.loadEnvironment(this.maps.get(0));
} else {
this.loadEnvironment(null);
}
EditorScreen.instance().updateGameFileMaps();
}
public void importMap() {
if (this.getMaps() == null) {
return;
}
XmlImportDialog.importXml("Tilemap", Map.FILE_EXTENSION, file -> {
String mapPath = file.toString();
Map map = (Map) MapLoader.load(mapPath);
if (map == null) {
log.log(Level.WARNING, "could not load map from file {0}", new Object[] { mapPath });
return;
}
if (map.getMapObjectLayers().isEmpty()) {
// make sure there's a map object layer on the map because we need one
// to add any kind of entities
MapObjectLayer layer = new MapObjectLayer();
layer.setName(DEFAULT_MAPOBJECTLAYER_NAME);
map.addMapObjectLayer(layer);
}
Optional<Map> current = this.maps.stream().filter(x -> x.getName().equals(map.getName())).findFirst();
if (current.isPresent()) {
int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("input_replace_map", map.getName()), Resources.get("input_replace_map_title"), JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
this.getMaps().remove(current.get());
} else {
return;
}
}
this.getMaps().add(map);
Collections.sort(this.getMaps());
for (IImageLayer imageLayer : map.getImageLayers()) {
BufferedImage img = Resources.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true);
if (img == null) {
continue;
}
Spritesheet sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight());
this.screen.getGameFile().getSpriteSheets().add(new SpriteSheetInfo(sprite));
}
// remove old spritesheets
for (ITileset tileSet : map.getTilesets()) {
this.loadTileset(tileSet, true);
}
// remove old tilesets
for (ITileset tileset : map.getExternalTilesets()) {
this.loadTileset(tileset, false);
}
EditorScreen.instance().updateGameFileMaps();
ImageCache.clearAll();
if (this.environments.containsKey(map.getName())) {
this.environments.remove(map.getName());
}
EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps(), true);
this.loadEnvironment(map);
log.log(Level.INFO, "imported map {0}", new Object[] { map.getName() });
});
}
public void loadTileset(ITileset tileset, boolean embedded) {
Spritesheet sprite = Spritesheet.find(tileset.getImage().getSource());
if (sprite != null) {
Spritesheet.remove(sprite.getName());
this.screen.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(sprite.getName()));
}
Spritesheet newSprite = Spritesheet.load(tileset);
SpriteSheetInfo info = new SpriteSheetInfo(newSprite);
EditorScreen.instance().getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(info.getName()));
EditorScreen.instance().getGameFile().getSpriteSheets().add(info);
EditorScreen.instance().loadSpriteSheets(Arrays.asList(info), true);
if (!embedded) {
this.screen.getGameFile().getTilesets().removeIf(x -> x.getName().equals(tileset.getName()));
this.screen.getGameFile().getTilesets().add((Tileset) tileset);
}
}
public void exportMap() {
if (this.getMaps() == null || this.getMaps().isEmpty()) {
return;
}
Map map = (Map) Game.getEnvironment().getMap();
if (map == null) {
return;
}
this.exportMap(map);
}
public void exportMap(Map map) {
// TODO: replace by XmlExportDialog call
JFileChooser chooser;
try {
String source = EditorScreen.instance().getProjectPath();
chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath());
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setDialogTitle("Export Map");
FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
chooser.setSelectedFile(new File(map.getName() + "." + Map.FILE_EXTENSION));
int result = chooser.showSaveDialog(Game.getScreenManager().getRenderComponent());
if (result == JFileChooser.APPROVE_OPTION) {
String newFile = XmlUtilities.save(map, chooser.getSelectedFile().toString(), Map.FILE_EXTENSION);
// save all tilesets manually because a map has a relative reference to
// the tilesets
String dir = FileUtilities.getParentDirPath(newFile);
for (ITileset tileSet : map.getTilesets()) {
ImageFormat format = ImageFormat.get(FileUtilities.getExtension(tileSet.getImage().getSource()));
ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Spritesheet.find(tileSet.getImage().getSource()).getImage(), format);
Tileset tile = (Tileset) tileSet;
if (tile.isExternal()) {
tile.saveSource(dir);
}
}
log.log(Level.INFO, "exported {0} to {1}", new Object[] { map.getName(), newFile });
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
public void zoomIn() {
if (this.currentZoomIndex < zooms.length - 1) {
this.currentZoomIndex++;
}
this.setCurrentZoom();
this.updateScrollSpeed();
}
public void zoomOut() {
if (this.currentZoomIndex > 0) {
this.currentZoomIndex
}
this.setCurrentZoom();
this.updateScrollSpeed();
}
private void updateScrollSpeed() {
this.scrollSpeed = BASE_SCROLL_SPEED / zooms[this.currentZoomIndex];
}
private void ensureUniqueIds(IMap map) {
int maxMapId = MapUtilities.getMaxMapId(map);
List<Integer> usedIds = new ArrayList<>();
for (IMapObject obj : map.getMapObjects()) {
if (usedIds.contains(obj.getId())) {
obj.setId(++maxMapId);
}
usedIds.add(obj.getId());
}
}
private static IMapObjectLayer getCurrentLayer() {
int layerIndex = EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex();
if (layerIndex < 0 || layerIndex >= Game.getEnvironment().getMap().getMapObjectLayers().size()) {
layerIndex = 0;
}
return Game.getEnvironment().getMap().getMapObjectLayers().get(layerIndex);
}
private IMapObject createNewMapObject(MapObjectType type) {
IMapObject mo = new MapObject();
mo.setType(type.toString());
mo.setX((float) this.newObjectArea.getX());
mo.setY((float) this.newObjectArea.getY());
// ensure a minimum size for the new object
float width = (float) this.newObjectArea.getWidth();
float height = (float) this.newObjectArea.getHeight();
mo.setWidth(width == 0 ? 16 : width);
mo.setHeight(height == 0 ? 16 : height);
mo.setId(Game.getEnvironment().getNextMapId());
mo.setName("");
switch (type) {
case PROP:
mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObjectArea.getWidth() * 0.4) + "");
mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObjectArea.getHeight() * 0.4) + "");
mo.setCustomProperty(MapObjectProperty.COLLISION, "true");
mo.setCustomProperty(MapObjectProperty.COMBAT_INDESTRUCTIBLE, "false");
mo.setCustomProperty(MapObjectProperty.PROP_ADDSHADOW, "true");
break;
case LIGHTSOURCE:
mo.setCustomProperty(MapObjectProperty.LIGHT_ALPHA, "180");
mo.setCustomProperty(MapObjectProperty.LIGHT_COLOR, "#ffffff");
mo.setCustomProperty(MapObjectProperty.LIGHT_SHAPE, LightSource.ELLIPSE);
mo.setCustomProperty(MapObjectProperty.LIGHT_ACTIVE, "true");
break;
case SPAWNPOINT:
default:
break;
}
this.add(mo);
return mo;
}
private Rectangle2D getCurrentMouseSelectionArea(boolean snap) {
final Point2D start = this.startPoint;
if (start == null) {
return null;
}
final Point2D endPoint = Input.mouse().getMapLocation();
double minX = Math.min(start.getX(), endPoint.getX());
double maxX = Math.max(start.getX(), endPoint.getX());
double minY = Math.min(start.getY(), endPoint.getY());
double maxY = Math.max(start.getY(), endPoint.getY());
if (snap) {
minX = this.snapX(minX);
maxX = this.snapX(maxX);
minY = this.snapY(minY);
maxY = this.snapY(maxY);
}
double width = Math.abs(minX - maxX);
double height = Math.abs(minY - maxY);
return new Rectangle2D.Double(minX, minY, width, height);
}
private Rectangle2D getFocus() {
final IMapObject focusedObject = this.getFocusedMapObject();
if (focusedObject == null) {
return null;
}
return focusedObject.getBoundingBox();
}
private double getTransX(TransformType type, Rectangle2D focus) {
switch (type) {
case DOWN:
case UP:
return focus.getCenterX() - this.currentTransformRectSize / 2;
case LEFT:
case DOWNLEFT:
case UPLEFT:
return focus.getX() - this.currentTransformRectSize;
case RIGHT:
case DOWNRIGHT:
case UPRIGHT:
return focus.getMaxX();
default:
return 0;
}
}
private double getTransY(TransformType type, Rectangle2D focus) {
switch (type) {
case DOWN:
case DOWNLEFT:
case DOWNRIGHT:
return focus.getMaxY();
case UP:
case UPLEFT:
case UPRIGHT:
return focus.getY() - this.currentTransformRectSize;
case LEFT:
case RIGHT:
return focus.getCenterY() - this.currentTransformRectSize / 2;
default:
return 0;
}
}
private void handleTransform() {
final IMapObject transformObject = this.getFocusedMapObject();
if (transformObject == null || this.currentEditMode != EDITMODE_EDIT || currentTransform == TransformType.NONE) {
return;
}
if (this.dragPoint == null) {
this.dragPoint = Input.mouse().getMapLocation();
this.dragLocationMapObjects.put(this.getFocusedMapObject(), new Point2D.Double(transformObject.getX(), transformObject.getY()));
this.dragSizeHeight = transformObject.getHeight();
this.dragSizeWidth = transformObject.getWidth();
return;
}
Point2D dragLocationMapObject = this.dragLocationMapObjects.get(this.getFocusedMapObject());
double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX();
double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY();
double newWidth = this.dragSizeWidth;
double newHeight = this.dragSizeHeight;
double newX = this.snapX(dragLocationMapObject.getX());
double newY = this.snapY(dragLocationMapObject.getY());
switch (this.currentTransform) {
case DOWN:
newHeight += deltaY;
break;
case DOWNRIGHT:
newHeight += deltaY;
newWidth += deltaX;
break;
case DOWNLEFT:
newHeight += deltaY;
newWidth -= deltaX;
newX += deltaX;
newX = MathUtilities.clamp(newX, 0, dragLocationMapObject.getX() + this.dragSizeWidth);
break;
case LEFT:
newWidth -= deltaX;
newX += deltaX;
newX = MathUtilities.clamp(newX, 0, dragLocationMapObject.getX() + this.dragSizeWidth);
break;
case RIGHT:
newWidth += deltaX;
break;
case UP:
newHeight -= deltaY;
newY += deltaY;
newY = MathUtilities.clamp(newY, 0, dragLocationMapObject.getY() + this.dragSizeHeight);
break;
case UPLEFT:
newHeight -= deltaY;
newY += deltaY;
newY = MathUtilities.clamp(newY, 0, dragLocationMapObject.getY() + this.dragSizeHeight);
newWidth -= deltaX;
newX += deltaX;
newX = MathUtilities.clamp(newX, 0, dragLocationMapObject.getX() + this.dragSizeWidth);
break;
case UPRIGHT:
newHeight -= deltaY;
newY += deltaY;
newY = MathUtilities.clamp(newY, 0, dragLocationMapObject.getY() + this.dragSizeHeight);
newWidth += deltaX;
break;
default:
return;
}
transformObject.setWidth(this.snapX(newWidth));
transformObject.setHeight(this.snapY(newHeight));
transformObject.setX(this.snapX(newX));
transformObject.setY(this.snapY(newY));
Game.getEnvironment().reloadFromMap(transformObject.getId());
if (MapObjectType.get(transformObject.getType()) == MapObjectType.LIGHTSOURCE) {
Game.getEnvironment().getAmbientLight().updateSection(transformObject.getBoundingBox());
}
EditorScreen.instance().getMapObjectPanel().bind(transformObject);
this.updateTransformControls();
}
private void handleSelectedEntitiesDrag() {
if (!this.isMoving) {
this.isMoving = true;
UndoManager.instance().beginOperation();
for (IMapObject selected : this.getSelectedMapObjects()) {
UndoManager.instance().mapObjectChanging(selected);
}
}
IMapObject minX = null;
IMapObject minY = null;
for (IMapObject selected : this.getSelectedMapObjects()) {
if (minX == null || selected.getX() < minX.getX()) {
minX = selected;
}
if (minY == null || selected.getY() < minY.getY()) {
minY = selected;
}
}
if (minX == null || minY == null || (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.currentEditMode != EDITMODE_MOVE)) {
return;
}
if (this.dragPoint == null) {
this.dragPoint = Input.mouse().getMapLocation();
return;
}
if (!this.dragLocationMapObjects.containsKey(minX)) {
this.dragLocationMapObjects.put(minX, new Point2D.Double(minX.getX(), minX.getY()));
}
if (!this.dragLocationMapObjects.containsKey(minY)) {
this.dragLocationMapObjects.put(minY, new Point2D.Double(minY.getX(), minY.getY()));
}
Point2D dragLocationMapObjectMinX = this.dragLocationMapObjects.get(minX);
Point2D dragLocationMapObjectMinY = this.dragLocationMapObjects.get(minY);
double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX();
float newX = this.snapX(dragLocationMapObjectMinX.getX() + deltaX);
float snappedDeltaX = newX - minX.getX();
double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY();
float newY = this.snapY(dragLocationMapObjectMinY.getY() + deltaY);
float snappedDeltaY = newY - minY.getY();
if (snappedDeltaX == 0 && snappedDeltaY == 0) {
return;
}
final Rectangle2D beforeBounds = MapObject.getBounds2D(this.getSelectedMapObjects());
this.handleEntityDrag(snappedDeltaX, snappedDeltaY);
if (this.getSelectedMapObjects().stream().anyMatch(x -> MapObjectType.get(x.getType()) == MapObjectType.STATICSHADOW || MapObjectType.get(x.getType()) == MapObjectType.LIGHTSOURCE)) {
final Rectangle2D afterBounds = MapObject.getBounds2D(this.getSelectedMapObjects());
double x = Math.min(beforeBounds.getX(), afterBounds.getX());
double y = Math.min(beforeBounds.getY(), afterBounds.getY());
double width = Math.max(beforeBounds.getMaxX(), afterBounds.getMaxX()) - x;
double height = Math.max(beforeBounds.getMaxY(), afterBounds.getMaxY()) - y;
Game.getEnvironment().getAmbientLight().updateSection(new Rectangle2D.Double(x, y, width, height));
}
}
private void handleEntityDrag(float snappedDeltaX, float snappedDeltaY) {
for (IMapObject selected : this.getSelectedMapObjects()) {
selected.setX(selected.getX() + snappedDeltaX);
selected.setY(selected.getY() + snappedDeltaY);
IEntity entity = Game.getEnvironment().get(selected.getId());
if (entity != null) {
entity.setX(selected.getLocation().getX());
entity.setY(selected.getLocation().getY());
} else {
Game.getEnvironment().reloadFromMap(selected.getId());
}
if (selected.equals(this.getFocusedMapObject())) {
EditorScreen.instance().getMapObjectPanel().bind(selected);
this.updateTransformControls();
}
}
}
private void setCurrentZoom() {
Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0);
}
private void setupKeyboardControls() {
Input.keyboard().onKeyReleased(KeyEvent.VK_ADD, e -> {
if (this.isSuspended() || !this.isVisible()) {
return;
}
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
this.zoomIn();
}
});
Input.keyboard().onKeyReleased(KeyEvent.VK_SUBTRACT, e -> {
if (this.isSuspended() || !this.isVisible()) {
return;
}
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
this.zoomOut();
}
});
Input.keyboard().onKeyPressed(KeyEvent.VK_SPACE, e -> this.centerCameraOnFocus());
Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> {
if (this.currentEditMode == EDITMODE_EDIT) {
this.setEditMode(EDITMODE_MOVE);
}
});
Input.keyboard().onKeyPressed(KeyEvent.VK_ESCAPE, e -> {
if (this.currentEditMode == EDITMODE_CREATE) {
this.setEditMode(EDITMODE_EDIT);
}
});
Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> this.setEditMode(EDITMODE_EDIT));
Input.keyboard().onKeyReleased(KeyEvent.VK_Z, e -> {
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
UndoManager.instance().undo();
}
});
Input.keyboard().onKeyReleased(KeyEvent.VK_Y, e -> {
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
UndoManager.instance().redo();
}
});
Input.keyboard().onKeyPressed(KeyEvent.VK_DELETE, e -> {
if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) {
return;
}
if (Game.getScreenManager().getRenderComponent().hasFocus() && this.currentEditMode == EDITMODE_EDIT) {
this.delete();
}
});
Input.keyboard().onKeyReleased(e -> {
if (e.getKeyCode() != KeyEvent.VK_RIGHT && e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) {
return;
}
// if one of the move buttons is still pressed, don't end the operation
if (Input.keyboard().isPressed(KeyEvent.VK_RIGHT) || Input.keyboard().isPressed(KeyEvent.VK_LEFT) || Input.keyboard().isPressed(KeyEvent.VK_UP) || Input.keyboard().isPressed(KeyEvent.VK_DOWN)) {
return;
}
if (this.isMovingWithKeyboard) {
for (IMapObject selected : this.getSelectedMapObjects()) {
UndoManager.instance().mapObjectChanged(selected);
}
UndoManager.instance().endOperation();
this.isMovingWithKeyboard = false;
}
});
Input.keyboard().onKeyPressed(KeyEvent.VK_RIGHT, e -> {
if (!Game.getScreenManager().getRenderComponent().hasFocus()) {
return;
}
this.beforeKeyPressed();
this.handleEntityDrag(1, 0);
this.afterKeyPressed();
});
Input.keyboard().onKeyPressed(KeyEvent.VK_LEFT, e -> {
if (!Game.getScreenManager().getRenderComponent().hasFocus()) {
return;
}
this.beforeKeyPressed();
this.handleEntityDrag(-1, 0);
this.afterKeyPressed();
});
Input.keyboard().onKeyPressed(KeyEvent.VK_UP, e -> {
if (!Game.getScreenManager().getRenderComponent().hasFocus()) {
return;
}
this.beforeKeyPressed();
this.handleEntityDrag(0, -1);
this.afterKeyPressed();
});
Input.keyboard().onKeyPressed(KeyEvent.VK_DOWN, e -> {
if (!Game.getScreenManager().getRenderComponent().hasFocus()) {
return;
}
this.beforeKeyPressed();
this.handleEntityDrag(0, 1);
this.afterKeyPressed();
});
}
private void beforeKeyPressed() {
if (!this.isMovingWithKeyboard) {
UndoManager.instance().beginOperation();
for (IMapObject selected : this.getSelectedMapObjects()) {
UndoManager.instance().mapObjectChanging(selected);
}
this.isMovingWithKeyboard = true;
}
}
private void afterKeyPressed() {
EditorScreen.instance().getMapComponent().updateTransformControls();
}
private void setupMouseControls() {
this.onMouseWheelScrolled(this::handleMouseWheelScrolled);
this.onMouseMoved(this::handleMouseMoved);
this.onMousePressed(this::handleMousePressed);
this.onMouseDragged(this::handleMouseDragged);
this.onMouseReleased(this::handleMouseReleased);
}
private void handleMouseWheelScrolled(ComponentMouseWheelEvent e) {
if (!this.hasFocus()) {
return;
}
final Point2D currentFocus = Game.getCamera().getFocus();
// horizontal scrolling
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.dragPoint == null) {
if (e.getEvent().getWheelRotation() < 0) {
Point2D newFocus = new Point2D.Double(currentFocus.getX() - this.scrollSpeed, currentFocus.getY());
Game.getCamera().setFocus(newFocus);
} else {
Point2D newFocus = new Point2D.Double(currentFocus.getX() + this.scrollSpeed, currentFocus.getY());
Game.getCamera().setFocus(newFocus);
}
Program.getHorizontalScrollBar().setValue((int) Game.getCamera().getViewPort().getCenterX());
return;
}
if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) {
if (e.getEvent().getWheelRotation() < 0) {
this.zoomIn();
} else {
this.zoomOut();
}
return;
}
if (e.getEvent().getWheelRotation() < 0) {
Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() - this.scrollSpeed);
Game.getCamera().setFocus(newFocus);
} else {
Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() + this.scrollSpeed);
Game.getCamera().setFocus(newFocus);
}
Program.getVerticalcrollBar().setValue((int) Game.getCamera().getViewPort().getCenterY());
}
/***
* Handles the mouse moved event and executes the following:
* <ol>
* <li>Set cursor image depending on the hovered transform control</li>
* <li>Update the currently active transform field.</li>
* </ol>
*
* @param e
* The mouse event of the calling {@link GuiComponent}
*/
private void handleMouseMoved(ComponentMouseEvent e) {
if (this.getFocus() == null) {
if (this.currentEditMode != EDITMODE_CREATE) {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
}
this.currentTransform = TransformType.NONE;
return;
}
boolean hovered = false;
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
return;
}
for (Entry<TransformType, Rectangle2D> entry : this.transformRects.entrySet()) {
Rectangle2D rect = entry.getValue();
Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 3, rect.getY() - rect.getHeight() * 3, rect.getWidth() * 5, rect.getHeight() * 5);
if (hoverrect.contains(Input.mouse().getMapLocation())) {
hovered = true;
if (entry.getKey() == TransformType.DOWN || entry.getKey() == TransformType.UP) {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0);
} else if (entry.getKey() == TransformType.UPLEFT || entry.getKey() == TransformType.DOWNRIGHT) {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0);
} else if (entry.getKey() == TransformType.UPRIGHT || entry.getKey() == TransformType.DOWNLEFT) {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0);
} else {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0);
}
this.currentTransform = entry.getKey();
break;
}
}
if (!hovered) {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
this.currentTransform = TransformType.NONE;
}
}
private void handleMousePressed(ComponentMouseEvent e) {
if (!this.hasFocus()) {
return;
}
switch (this.currentEditMode) {
case EDITMODE_CREATE:
if (SwingUtilities.isLeftMouseButton(e.getEvent())) {
this.startPoint = Input.mouse().getMapLocation();
}
break;
case EDITMODE_MOVE:
break;
case EDITMODE_EDIT:
if (this.isMoving || this.currentTransform != TransformType.NONE || SwingUtilities.isRightMouseButton(e.getEvent())) {
return;
}
final Point2D mouse = Input.mouse().getMapLocation();
this.startPoint = mouse;
break;
default:
break;
}
}
private void handleMouseDragged(ComponentMouseEvent e) {
if (!this.hasFocus()) {
return;
}
switch (this.currentEditMode) {
case EDITMODE_CREATE:
if (startPoint == null) {
return;
}
if (SwingUtilities.isLeftMouseButton(e.getEvent())) {
newObjectArea = this.getCurrentMouseSelectionArea(true);
}
break;
case EDITMODE_EDIT:
if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
this.handleSelectedEntitiesDrag();
return;
} else if (this.currentTransform != TransformType.NONE) {
if (!this.isTransforming) {
this.isTransforming = true;
UndoManager.instance().mapObjectChanging(this.getFocusedMapObject());
}
this.handleTransform();
return;
}
break;
case EDITMODE_MOVE:
this.handleSelectedEntitiesDrag();
break;
default:
break;
}
}
private void handleMouseReleased(ComponentMouseEvent e) {
if (!this.hasFocus()) {
return;
}
this.dragPoint = null;
this.dragLocationMapObjects.clear();
this.dragSizeHeight = 0;
this.dragSizeWidth = 0;
switch (this.currentEditMode) {
case EDITMODE_CREATE:
if (SwingUtilities.isRightMouseButton(e.getEvent())) {
this.newObjectArea = null;
this.setEditMode(EDITMODE_EDIT);
break;
}
if (this.newObjectArea == null) {
break;
}
IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType());
this.newObjectArea = null;
this.setFocus(mo, !Input.keyboard().isPressed(KeyEvent.VK_SHIFT));
EditorScreen.instance().getMapObjectPanel().bind(mo);
this.setEditMode(EDITMODE_EDIT);
break;
case EDITMODE_MOVE:
if (this.isMoving) {
this.isMoving = false;
for (IMapObject selected : this.getSelectedMapObjects()) {
UndoManager.instance().mapObjectChanged(selected);
}
UndoManager.instance().endOperation();
}
break;
case EDITMODE_EDIT:
if (this.isMoving || this.isTransforming) {
this.isMoving = false;
this.isTransforming = false;
UndoManager.instance().mapObjectChanged(this.getFocusedMapObject());
}
if (this.startPoint == null) {
return;
}
Rectangle2D rect = this.getCurrentMouseSelectionArea(false);
boolean somethingIsFocused = false;
boolean currentObjectFocused = false;
for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) {
if (layer == null || !EditorScreen.instance().getMapSelectionPanel().isVisibleMapObjectLayer(layer.getName())) {
continue;
}
for (IMapObject mapObject : layer.getMapObjects()) {
if (mapObject == null) {
continue;
}
MapObjectType type = MapObjectType.get(mapObject.getType());
if (type == MapObjectType.PATH) {
continue;
}
if (!GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) {
continue;
}
if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) {
currentObjectFocused = true;
continue;
}
if (somethingIsFocused) {
if (rect.getWidth() == 0 && rect.getHeight() == 0) {
break;
}
this.setSelection(mapObject, false);
continue;
}
if (this.getSelectedMapObjects().contains((MapObject) mapObject)) {
this.getSelectedMapObjects().remove((MapObject) mapObject);
} else {
this.setFocus(mapObject, !Input.keyboard().isPressed(KeyEvent.VK_SHIFT));
EditorScreen.instance().getMapObjectPanel().bind(mapObject);
}
somethingIsFocused = true;
}
}
if (!somethingIsFocused && !currentObjectFocused) {
this.setFocus(null, true);
EditorScreen.instance().getMapObjectPanel().bind(null);
}
break;
default:
break;
}
this.startPoint = null;
}
private float snapX(double x) {
if (Program.getUserPreferences().isSnapGrid()) {
double snapped = ((int) (x / this.gridSize) * this.gridSize);
return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getWidth()));
}
if (Program.getUserPreferences().isSnapPixels()) {
return MathUtilities.clamp((int) Math.round(x), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getWidth());
}
return MathUtilities.round((float) x, 2);
}
private float snapY(double y) {
if (Program.getUserPreferences().isSnapGrid()) {
int snapped = (int) (y / this.gridSize) * this.gridSize;
return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getHeight()));
}
if (Program.getUserPreferences().isSnapPixels()) {
return MathUtilities.clamp((int) Math.round(y), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getHeight());
}
return MathUtilities.round((float) y, 2);
}
private boolean hasFocus() {
if (this.isSuspended() || !this.isVisible()) {
return false;
}
for (GuiComponent comp : this.getComponents()) {
if (comp.isHovered() && !comp.isSuspended()) {
return false;
}
}
return true;
}
private void renderMapObjectBounds(Graphics2D g) {
// render all entities
for (final IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) {
if (layer == null) {
continue;
}
if (!EditorScreen.instance().getMapSelectionPanel().isVisibleMapObjectLayer(layer.getName())) {
continue;
}
Color colorBoundingBoxFill;
if (layer.getColor() != null) {
colorBoundingBoxFill = new Color(layer.getColor().getRed(), layer.getColor().getGreen(), layer.getColor().getBlue(), 15);
} else {
colorBoundingBoxFill = DEFAULT_COLOR_BOUNDING_BOX_FILL;
}
for (final IMapObject mapObject : layer.getMapObjects()) {
if (mapObject == null) {
continue;
}
MapObjectType type = MapObjectType.get(mapObject.getType());
final BasicStroke shapeStroke = new BasicStroke(1f / Game.getCamera().getRenderScale());
// render spawn points
if (type == MapObjectType.SPAWNPOINT) {
g.setColor(COLOR_SPAWNPOINT);
Game.getRenderEngine().renderShape(g, new Rectangle2D.Double(mapObject.getBoundingBox().getCenterX() - 1, mapObject.getBoundingBox().getCenterY() - 1, 2, 2));
} else if (type == MapObjectType.PATH) {
// render lane
if (mapObject.getPolyline() == null || mapObject.getPolyline().getPoints().isEmpty()) {
continue;
}
// found the path for the rat
final Path2D path = MapUtilities.convertPolylineToPath(mapObject);
if (path == null) {
continue;
}
g.setColor(COLOR_LANE);
Game.getRenderEngine().renderOutline(g, path, shapeStroke);
Point2D start = new Point2D.Double(mapObject.getLocation().getX(), mapObject.getLocation().getY());
Game.getRenderEngine().renderShape(g, new Ellipse2D.Double(start.getX() - 1, start.getY() - 1, 3, 3));
Game.getRenderEngine().renderText(g, "#" + mapObject.getId() + "(" + mapObject.getName() + ")", start.getX(), start.getY() - 5);
}
if (type != MapObjectType.COLLISIONBOX) {
this.renderBoundingBox(g, mapObject, colorBoundingBoxFill, shapeStroke);
}
this.renderCollisionBox(g, mapObject, shapeStroke);
}
}
}
private void renderName(Graphics2D g, Color nameColor, IMapObject mapObject) {
final int MAX_TAGS_RENDER_CHARS = 30;
g.setColor(nameColor.getAlpha() > 100 ? nameColor : Color.WHITE);
float textSize = 2.5f * zooms[this.currentZoomIndex];
g.setFont(Program.TEXT_FONT.deriveFont(textSize).deriveFont(Font.PLAIN));
String objectName = mapObject.getName();
if (objectName != null && !objectName.isEmpty()) {
Game.getRenderEngine().renderText(g, mapObject.getName(), mapObject.getX() + 1, mapObject.getBoundingBox().getMaxY() - 1);
}
// render tags
String tags = mapObject.getCustomProperty(MapObjectProperty.TAGS);
if (tags == null || tags.isEmpty()) {
return;
}
FontMetrics fm = g.getFontMetrics();
double y = objectName != null && !objectName.isEmpty() ? mapObject.getBoundingBox().getMaxY() - 2 - fm.getMaxDescent() : mapObject.getBoundingBox().getMaxY() - 1;
if (tags.length() > MAX_TAGS_RENDER_CHARS) {
tags = tags.substring(0, MAX_TAGS_RENDER_CHARS - 1);
tags += "...";
}
Game.getRenderEngine().renderText(g, "[" + tags + "]", mapObject.getX() + 1, y);
}
private void renderGrid(Graphics2D g) {
// render the grid
if (Program.getUserPreferences().isShowGrid() && Game.getCamera().getRenderScale() >= 1) {
g.setColor(new Color(255, 255, 255, 70));
final Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale());
final double viewPortX = Math.max(0, Game.getCamera().getViewPort().getX());
final double viewPortMaxX = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getWidth(), Game.getCamera().getViewPort().getMaxX());
final double viewPortY = Math.max(0, Game.getCamera().getViewPort().getY());
final double viewPortMaxY = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getHeight(), Game.getCamera().getViewPort().getMaxY());
final int startX = Math.max(0, (int) (viewPortX / gridSize) * gridSize);
final int startY = Math.max(0, (int) (viewPortY / gridSize) * gridSize);
for (int x = startX; x <= viewPortMaxX; x += gridSize) {
Game.getRenderEngine().renderOutline(g, new Line2D.Double(x, viewPortY, x, viewPortMaxY), stroke);
}
for (int y = startY; y <= viewPortMaxY; y += gridSize) {
Game.getRenderEngine().renderOutline(g, new Line2D.Double(viewPortX, y, viewPortMaxX, y), stroke);
}
}
}
private void renderNewObjectArea(Graphics2D g, Stroke shapeStroke) {
if (this.newObjectArea == null) {
return;
}
g.setColor(COLOR_NEWOBJECT_FILL);
Game.getRenderEngine().renderShape(g, newObjectArea);
g.setColor(COLOR_NEWOBJECT_BORDER);
Game.getRenderEngine().renderOutline(g, newObjectArea, shapeStroke);
g.setFont(g.getFont().deriveFont(Font.BOLD));
Game.getRenderEngine().renderText(g, newObjectArea.getWidth() + "", newObjectArea.getX() + newObjectArea.getWidth() / 2 - 3, newObjectArea.getY() - 5);
Game.getRenderEngine().renderText(g, newObjectArea.getHeight() + "", newObjectArea.getX() - 10, newObjectArea.getY() + newObjectArea.getHeight() / 2);
}
private void renderMouseSelectionArea(Graphics2D g, Stroke shapeStroke) {
// draw mouse selection area
final Point2D start = this.startPoint;
if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
final Rectangle2D rect = this.getCurrentMouseSelectionArea(false);
if (rect == null) {
return;
}
g.setColor(COLOR_MOUSE_SELECTION_AREA_FILL);
Game.getRenderEngine().renderShape(g, rect);
g.setColor(COLOR_MOUSE_SELECTION_AREA_BORDER);
Game.getRenderEngine().renderOutline(g, rect, shapeStroke);
}
}
private void renderFocus(Graphics2D g) {
// render the focus and the transform rects
final Rectangle2D focus = this.getFocus();
final IMapObject focusedMapObject = this.getFocusedMapObject();
if (focus != null && focusedMapObject != null) {
Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15);
g.setColor(Color.BLACK);
Game.getRenderEngine().renderOutline(g, focus, stroke);
Stroke whiteStroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15 - 1f);
g.setColor(Color.WHITE);
Game.getRenderEngine().renderOutline(g, focus, whiteStroke);
// render transform rects
if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
Stroke transStroke = new BasicStroke(1 / Game.getCamera().getRenderScale());
for (Rectangle2D trans : this.transformRects.values()) {
g.setColor(COLOR_TRANSFORM_RECT_FILL);
Game.getRenderEngine().renderShape(g, trans);
g.setColor(Color.BLACK);
Game.getRenderEngine().renderOutline(g, trans, transStroke);
}
}
// render transform rects
if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) {
Stroke transStroke = new BasicStroke(1 / Game.getCamera().getRenderScale());
for (Rectangle2D trans : this.transformRects.values()) {
g.setColor(COLOR_TRANSFORM_RECT_FILL);
Game.getRenderEngine().renderShape(g, trans);
g.setColor(Color.BLACK);
Game.getRenderEngine().renderOutline(g, trans, transStroke);
}
}
}
if (focusedMapObject != null) {
Point2D loc = Game.getCamera().getViewPortLocation(new Point2D.Double(focusedMapObject.getX() + focusedMapObject.getWidth() / 2, focusedMapObject.getY()));
g.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD, 15f));
g.setColor(Color.WHITE);
String id = "#" + focusedMapObject.getId();
TextRenderer.render(g, id, loc.getX() * Game.getCamera().getRenderScale() - g.getFontMetrics().stringWidth(id) / 2.0, loc.getY() * Game.getCamera().getRenderScale() - (5 * this.currentTransformRectSize));
}
}
private void renderSelection(Graphics2D g) {
for (IMapObject mapObject : this.getSelectedMapObjects()) {
if (mapObject.equals(this.getFocusedMapObject())) {
continue;
}
Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale());
g.setColor(colorSelectionBorder);
Game.getRenderEngine().renderOutline(g, mapObject.getBoundingBox(), stroke);
}
}
private void renderBoundingBox(Graphics2D g, IMapObject mapObject, Color colorBoundingBoxFill, BasicStroke shapeStroke) {
MapObjectType type = MapObjectType.get(mapObject.getType());
Color fillColor = colorBoundingBoxFill;
if (type == MapObjectType.TRIGGER) {
fillColor = COLOR_TRIGGER_FILL;
} else if (type == MapObjectType.STATICSHADOW) {
fillColor = COLOR_SHADOW_FILL;
}
// render bounding boxes
g.setColor(fillColor);
// don't fill rect for lightsource because it is important to judge
// the color
if (type != MapObjectType.LIGHTSOURCE) {
Game.getRenderEngine().renderShape(g, mapObject.getBoundingBox());
}
Color borderColor = colorBoundingBoxFill;
if (type == MapObjectType.TRIGGER) {
borderColor = COLOR_TRIGGER_BORDER;
} else if (type == MapObjectType.LIGHTSOURCE) {
final String mapObjectColor = mapObject.getCustomProperty(MapObjectProperty.LIGHT_COLOR);
if (mapObjectColor != null && !mapObjectColor.isEmpty()) {
Color lightColor = ColorHelper.decode(mapObjectColor);
borderColor = new Color(lightColor.getRed(), lightColor.getGreen(), lightColor.getBlue(), 180);
}
} else if (type == MapObjectType.STATICSHADOW) {
borderColor = COLOR_SHADOW_BORDER;
} else if (type == MapObjectType.SPAWNPOINT) {
borderColor = COLOR_SPAWNPOINT;
}
g.setColor(borderColor);
Game.getRenderEngine().renderOutline(g, mapObject.getBoundingBox(), shapeStroke);
this.renderName(g, borderColor, mapObject);
}
private void renderCollisionBox(Graphics2D g, IMapObject mapObject, BasicStroke shapeStroke) {
// render collision boxes
boolean collision = mapObject.getCustomPropertyBool(MapObjectProperty.COLLISION, false);
float collisionBoxWidth = mapObject.getCustomPropertyFloat(MapObjectProperty.COLLISIONBOX_WIDTH, -1);
float collisionBoxHeight = mapObject.getCustomPropertyFloat(MapObjectProperty.COLLISIONBOX_HEIGHT, -1);
final Align align = Align.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_ALIGN));
final Valign valign = Valign.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_VALIGN));
if (MapObjectType.get(mapObject.getType()) == MapObjectType.COLLISIONBOX) {
collisionBoxWidth = mapObject.getWidth();
collisionBoxHeight = mapObject.getHeight();
collision = true;
}
if (collisionBoxWidth != -1 && collisionBoxHeight != -1) {
g.setColor(COLOR_COLLISION_FILL);
Rectangle2D collisionBox = CollisionEntity.getCollisionBox(mapObject.getLocation(), mapObject.getWidth(), mapObject.getHeight(), collisionBoxWidth, collisionBoxHeight, align, valign);
Game.getRenderEngine().renderShape(g, collisionBox);
g.setColor(collision ? COLOR_COLLISION_BORDER : COLOR_NOCOLLISION_BORDER);
Stroke collisionStroke = collision ? shapeStroke : new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 0, new float[] { 1f }, 0);
Game.getRenderEngine().renderOutline(g, collisionBox, collisionStroke);
}
}
@Override
public void update() {
if (this.focusBorderBrightness <= 0.4) {
this.focusBorderBrightnessIncreasing = true;
} else if (this.focusBorderBrightness >= 0.9) {
this.focusBorderBrightnessIncreasing = false;
}
if (this.focusBorderBrightnessIncreasing && this.focusBorderBrightness < 0.9) {
this.focusBorderBrightness += 0.005;
} else if (!focusBorderBrightnessIncreasing && this.focusBorderBrightness >= 0.4) {
this.focusBorderBrightness -= 0.005;
}
this.colorSelectionBorder = Color.getHSBColor(0, 0, this.focusBorderBrightness);
}
}
|
package com.areen.jlib.test;
import com.areen.jlib.api.RemoteFile;
import com.areen.jlib.gui.GuiTools;
import com.areen.jlib.util.MIMEUtil;
import com.areen.jlib.util.MIMEUtil.MIMEType;
import com.areen.jlib.util.StringUtility;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Window;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* JComponent made for the sole purpose of maintaining various remote files.
*
* What it does:
* 1) It indicates clearly whether remote document is uploaded or not.
* 2) It is capable of triggering upload of file either by drag&drop, or by clicking on the button and
* invoking the file select dialog so user can pick file to upload.
* 3) It has a button to delete the remote file in the case wrong file has been uploaded.
*
* TODO: This class was made long before the ADM and ReqDocPanel, therefore it was designed with different
* things in mind. After we designed ADM model it was obvious that we have to either refactor
* RemoteFileButton, or write a completely new, similar set of classes.
*
* @author Dejan
*/
public class RemoteFileButton
extends JComponent
implements PropertyChangeListener, DropTargetListener {
// :::::: PRIVATE/PROTECTED :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
private RemoteFileButtonModel model;
private BorderLayout layout;
private JLabel iconLabel;
private JLabel textLabel;
private JPopupMenu popupMenu;
private static ImageIcon fileUploadedImageIcon;
private static ImageIcon fileNotUploadedImageIcon;
private RemoteFile remoteFile;
static {
URL iconUrl = GuiTools.getResource(RemoteFileButton.class,
"/com/areen/jlib/res/icons/file_not_available.png");
fileNotUploadedImageIcon = new ImageIcon(iconUrl);
iconUrl = GuiTools.getResource(RemoteFileButton.class,
"/com/areen/jlib/res/icons/yes.png");
fileUploadedImageIcon = new ImageIcon(iconUrl);
} // static constructor
public RemoteFileButton(RemoteFile argRemoteFile) {
super();
remoteFile = argRemoteFile;
setBorder(BorderFactory.createRaisedBevelBorder());
model = new RemoteFileButtonModel(remoteFile);
model.setCaption(remoteFile.getDescription());
model.addPropertyChangeListener(this);
layout = new BorderLayout();
layout.setHgap(3);
layout.setVgap(3);
setLayout(layout);
// ::::: ICON :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
iconLabel = new JLabel();
iconLabel.setIcon(fileNotUploadedImageIcon);
add(iconLabel, BorderLayout.WEST);
/*
if (uploadEnabled) {
iconLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e); //To change body of generated methods, choose Tools | Templates.
iconLabelMouseClick();
}
});
}
*/
// ::::: TITLE ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
textLabel = new JLabel(model.getCaption());
add(textLabel, BorderLayout.CENTER);
// ::::: Popup Menu :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
popupMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("New Version");
menuItem.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
handleNewVersion();
}
});
popupMenu.add(menuItem);
menuItem = new JMenuItem("Delete");
menuItem.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
handleDelete();
}
});
popupMenu.add(menuItem);
menuItem = new JMenuItem("Properties");
menuItem.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
remoteFile.showProperties();
}
});
popupMenu.add(menuItem);
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(textLabel, e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(textLabel, e.getX(), e.getY());
}
}
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e); //To change body of generated methods, choose Tools | Templates.
if (SwingUtilities.isLeftMouseButton(e)) {
handleOpen();
}
}
});
} // RemoteFileButton constructor (default)
// ::::: PropertyChangeListener :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@Override
public void propertyChange(PropertyChangeEvent evt) {
// Model has been changed, let's update the view
if (model.isUploaded()) {
// handle property change for a document
refreshIcon();
refreshToolTip();
}
}
// ::::: DropTargetListener :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@Override
public void dragEnter(DropTargetDragEvent dtde) {
setBorder(BorderFactory.createLineBorder(Color.BLUE));
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
@Override
public void dragOver(DropTargetDragEvent dtde) {
System.out.println("D&D");
}
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("D&D");
}
@Override
public void dragExit(DropTargetEvent dte) {
resetDropIndicator();
setCursor(Cursor.getDefaultCursor());
}
@Override
public void drop(DropTargetDropEvent dtde) {
Transferable t = dtde.getTransferable();
System.out.println(Arrays.toString(t.getTransferDataFlavors()));
DataFlavor fileListDataFlavor = DataFlavor.javaFileListFlavor;
if (t.isDataFlavorSupported(fileListDataFlavor)) {
try {
int ret = JOptionPane.showConfirmDialog(GuiTools.getWindow(this),
"Are you sure to create a new version of " + remoteFile.getDescription() + "?",
"New version confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ret == JOptionPane.NO_OPTION) {
resetDropIndicator();
return;
}
dtde.acceptDrop(DnDConstants.ACTION_COPY);
System.out.println("drop accepted");
List fileList = (List) t.getTransferData(fileListDataFlavor);
File[] tempFiles = new File[fileList.size()];
fileList.toArray(tempFiles);
final File[] files = tempFiles;
remoteFile.newVersion(files[0]);
dtde.getDropTargetContext().dropComplete(true);
System.out.println("drop complete");
} catch (UnsupportedFlavorException ex) {
Logger.getLogger(RemoteFileButton.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RemoteFileButton.class.getName()).log(Level.SEVERE, null, ex);
}
}
resetDropIndicator();
}
public void refreshToolTip() {
System.out.println("Refresh tool top : " + getToolTipText() + " -> " + remoteFile.getToolTip());
setToolTipText(remoteFile.getToolTip());
repaint();
}
public void refreshIcon() {
MIMEType mTy = MIMEUtil.getMIMEType(remoteFile.getMimeType());
ImageIcon icon = MIMEUtil.getIcon(mTy, remoteFile.getExtension());
iconLabel.setIcon(icon);
repaint();
if (getParent() != null) {
getParent().validate();
}
}
public RemoteFile getRemoteFile() {
return remoteFile;
}
public String getText() {
return textLabel.getText();
}
public void setText(String argText) {
textLabel.setText(argText);
}
public RemoteFileButtonModel getModel() {
return model;
}
public void setModel(RemoteFileButtonModel argModel) {
model = argModel;
}
private void resetDropIndicator() {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
setBorder(BorderFactory.createRaisedBevelBorder());
}
private void handleDelete() {
// show confirmation message
int answer = JOptionPane.showConfirmDialog(GuiTools.getWindow(this),
"Are you sure you want to delete "
+ getToolTipText() + " (" + remoteFile.getDescription() + ") file?",
"Confirm to delete the file",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
// if confirmed delete the file and remove the button from the parent component
if (answer == JOptionPane.OK_OPTION) {
if (remoteFile.delete()) {
// remove this component from the parent
Container parent = getParent();
Window w = GuiTools.getWindow(this);
parent.remove(this);
// sometimes it doesn't refresh so force validation of the window
parent.repaint();
parent.validate();
}
}
}
private void handleNewVersion() {
String fileToUpload;
JFileChooser fc = new JFileChooser();
String[] fExtns = remoteFile.getAllowedExtensions();
fc.setFileFilter(
new FileNameExtensionFilter("Doc Files, ("
+ StringUtility.generateExtensionList(fExtns)
+ ")"
, fExtns)
);
fc.setMultiSelectionEnabled(false);
int returnVal = fc.showDialog(this, "Select");
// if user makes a selection record that and update the selectedFile box
if (returnVal == JFileChooser.APPROVE_OPTION) {
String fileString = fc.getSelectedFile().getPath();
fileToUpload = fileString;
} else {
fileToUpload = null;
}
// if user has clicked ok
if (fileToUpload != null && !fileToUpload.contains("*")) {
model.setLocalPath(fileToUpload);
remoteFile.newVersion(new File(fileToUpload));
}
}
private void handleOpen() {
remoteFile.open();
}
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
TestFile tf = new TestFile();
tf.setDescription("Test");
frame.add(new RemoteFileButton(tf), BorderLayout.NORTH);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}
});
} // main() method
} // RemoteFileButton class
|
package gr.uoi.cs.daintiness.hecate.transitions;
import gr.uoi.cs.daintiness.hecate.sql.Attribute;
import gr.uoi.cs.daintiness.hecate.sql.Table;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
/**
* @author iskoulis
*
*/
public abstract class Transition {
@XmlElement(name="table")
Table affectedTable;
@XmlElement(name="attribute")
Collection<Attribute> affectedAtributes;
@XmlAttribute(name="type")
String type;
public Transition() {
affectedTable = null;
type = null;
affectedAtributes = new ArrayList<Attribute>();
}
public void attribute(Attribute newAttribute) throws Exception {
if (type == null) {
type = "UpdateTable";
}
if (affectedTable == null) {
this.affectedTable = newAttribute.getTable();
} else if (affectedTable != newAttribute.getTable()){
throw new Exception("ta ekanes salata!");
}
this.affectedAtributes.add(newAttribute);
}
public void table(Table newTable) {
this.affectedTable = newTable;
this.affectedAtributes = newTable.getAttrs().values();
}
public Table getAffTable(){
return affectedTable;
}
public String getType(){
return this.type;
}
public int getNumOfAffAttributes() {
return affectedAtributes.size();
}
public Collection<Attribute> getAffAttributes() {
return affectedAtributes;
}
}
|
package org.wso2.carbon.uuf.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.uuf.model.MapModel;
import org.wso2.carbon.uuf.model.Model;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
public class Component {
public static final String ROOT_COMPONENT_NAME = "root";
public static final String ROOT_COMPONENT_CONTEXT = "/root";
private static final Logger log = LoggerFactory.getLogger(Component.class);
private final String name;
private final String version;
private final SortedSet<Page> pages;
private final ComponentLookup lookup;
public Component(String name, String version, SortedSet<Page> pages, ComponentLookup lookup) {
if (!name.equals(lookup.getComponentName())) {
throw new IllegalArgumentException("Specified 'lookup' does not belong to this component.");
}
this.name = name;
this.version = version;
this.pages = pages;
this.lookup = lookup;
}
String getName() {
return name;
}
String getContext() {
return lookup.getComponentContext();
}
public Map<String, Fragment> getFragments() {
return lookup.getFragments();
}
ComponentLookup getLookup() {
return lookup;
}
@Deprecated
public Component(String name,
String context,
String version,
SortedSet<Page> pages,
Lookup lookup) {
this.name = name;
this.version = version;
this.pages = pages;
this.lookup = null;
}
public Optional<String> renderPage(String pageUri, RequestLookup requestLookup, API api) {
Optional<Page> servingPage = getPage(pageUri);
if (!servingPage.isPresent()) {
return Optional.<String>empty();
}
Page page = servingPage.get();
if (log.isDebugEnabled()) {
log.debug("Component '" + lookup.getComponentName() + "' is serving Page '" + page + "' for URI '" +
pageUri + "'.");
}
Model model = new MapModel(Collections.emptyMap());
return Optional.of(page.render(model, lookup, requestLookup, api));
}
private Optional<Page> getPage(String pageUri) {
return pages.stream().filter(page -> page.getUriPatten().match(pageUri)).findFirst();
}
@Deprecated
public boolean hasPage(String uri) {
return getPage(uri).isPresent();
}
@Deprecated
public Set<Page> getPages() {
return new HashSet<>(pages);
}
@Override
public String toString() {
return "{\"name\":\"" + name + "\", \"version\": \"" + version + "\", \"context\": \"" + getContext() + "\"}";
}
}
|
package ru.r2cloud.jradio.tubix20;
import java.io.DataInputStream;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.r2cloud.jradio.fec.Hamming;
import ru.r2cloud.jradio.fec.ccsds.UncorrectableException;
public class CMX909bHeader {
private static final Logger LOG = LoggerFactory.getLogger(CMX909bHeader.class);
private Control1 control1;
private Control2 control2;
public CMX909bHeader() {
//do nothing
}
public CMX909bHeader(DataInputStream dis) throws UncorrectableException, IOException {
int control1Byte = dis.readUnsignedByte();
int control2Byte = dis.readUnsignedByte();
int fec = dis.readUnsignedByte();
control1Byte = Hamming.decode12b8((control1Byte << 4) | (fec >> 4));
control1 = new Control1();
MessageType type = MessageType.valueOfCode(control1Byte >> 5);
if (type != null) {
control1.setType(type);
} else {
LOG.info("unknown message type: ", (control1Byte >> 5));
}
control1.setNumberOfBlocks((control1Byte & 0x1F) + 1);
control1.setNumberOfErrors((control1Byte & 0x1F));
control2Byte = Hamming.decode12b8((control2Byte << 4) | (fec & 0xF));
control2 = new Control2();
control2.setBaud9600((control2Byte & 0x1) > 0);
control2.setAck((control2Byte & 0x2) > 0);
control2.setSubaddress((byte) ((control2Byte >> 2) & 0x3));
control2.setAddress((byte) (control2Byte >> 4));
}
public Control1 getControl1() {
return control1;
}
public void setControl1(Control1 control1) {
this.control1 = control1;
}
public Control2 getControl2() {
return control2;
}
public void setControl2(Control2 control2) {
this.control2 = control2;
}
}
|
package ca.mjdsystems.jmatio.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.zip.InflaterInputStream;
import ca.mjdsystems.jmatio.common.MatDataTypes;
import ca.mjdsystems.jmatio.io.MatFileWriter.ByteArrayOutputStream2;
import ca.mjdsystems.jmatio.types.ByteStorageSupport;
import ca.mjdsystems.jmatio.types.MLArray;
import ca.mjdsystems.jmatio.types.MLCell;
import ca.mjdsystems.jmatio.types.MLChar;
import ca.mjdsystems.jmatio.types.MLDouble;
import ca.mjdsystems.jmatio.types.MLEmptyArray;
import ca.mjdsystems.jmatio.types.MLInt16;
import ca.mjdsystems.jmatio.types.MLInt32;
import ca.mjdsystems.jmatio.types.MLInt64;
import ca.mjdsystems.jmatio.types.MLInt8;
import ca.mjdsystems.jmatio.types.MLJavaObject;
import ca.mjdsystems.jmatio.types.MLNumericArray;
import ca.mjdsystems.jmatio.types.MLObject;
import ca.mjdsystems.jmatio.types.MLSingle;
import ca.mjdsystems.jmatio.types.MLSparse;
import ca.mjdsystems.jmatio.types.MLStructure;
import ca.mjdsystems.jmatio.types.MLUInt32;
import ca.mjdsystems.jmatio.types.MLUInt64;
import ca.mjdsystems.jmatio.types.MLUInt8;
/**
* MAT-file reader. Reads MAT-file into <code>MLArray</code> objects.
*
* Usage:
* <pre><code>
* //read in the file
* MatFileReader mfr = new MatFileReader( "mat_file.mat" );
*
* //get array of a name "my_array" from file
* MLArray mlArrayRetrived = mfr.getMLArray( "my_array" );
*
* //or get the collection of all arrays that were stored in the file
* Map content = mfr.getContent();
* </pre></code>
*
* @see ca.mjdsystems.jmatio.io.MatFileFilter
* @author Wojciech Gradkowski (<a href="mailto:wgradkowski@gmail.com">wgradkowski@gmail.com</a>)
*/
/**
* @author Wojciech Gradkowski (<a
* href="mailto:wgradkowski@gmail.com">wgradkowski@gmail.com</a>)
*
*/
public class MatFileReader
{
public static final int MEMORY_MAPPED_FILE = 1;
public static final int DIRECT_BYTE_BUFFER = 2;
public static final int HEAP_BYTE_BUFFER = 4;
/**
* Type of matlab mat file.
*/
private final MatFileType matType;
/**
* MAT-file header
*/
private MatFileHeader matFileHeader;
/**
* Container for red <code>MLArray</code>s
*/
private Map<String, MLArray> data;
/**
* Tells how bytes are organized in the buffer.
*/
private ByteOrder byteOrder;
/**
* Array name filter
*/
private MatFileFilter filter;
/**
* Whether or not we have found an MCOS type variable. Needed to know if further processing is needed.
*/
private boolean haveMCOS = false;
/**
* Holds the likely candidate for the MCOS extra data at the end of a MAT file.
*/
private MLUInt8 mcosData;
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file
* from location given as <code>fileName</code>.
*
* This method reads MAT-file without filtering.
*
* @param fileName the MAT-file path <code>String</code>
* @throws IOException when error occurred while processing the file.
*/
public MatFileReader(String fileName) throws FileNotFoundException, IOException
{
this ( new File(fileName), new MatFileFilter(), MatFileType.Regular);
}
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file
* from location given as <code>fileName</code>.
*
* Results are filtered by <code>MatFileFilter</code>. Arrays that do not meet
* filter match condition will not be available in results.
*
* @param fileName the MAT-file path <code>String</code>
* @param MatFileFilter array name filter.
* @throws IOException when error occurred while processing the file.
*/
public MatFileReader(String fileName, MatFileFilter filter ) throws IOException
{
this( new File(fileName), filter, MatFileType.Regular);
}
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file
* from <code>file</code>.
*
* This method reads MAT-file without filtering.
*
* @param file the MAT-file
* @throws IOException when error occurred while processing the file.
*/
public MatFileReader(File file) throws IOException
{
this ( file, new MatFileFilter(), MatFileType.Regular);
}
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file from
* <code>file</code>.
* <p>
* Results are filtered by <code>MatFileFilter</code>. Arrays that do not
* meet filter match condition will not be available in results.
* <p>
* <i>Note: this method reads file using the memory mapped file policy, see
* notes to </code>{@link #read(File, MatFileFilter, ca.mjdsystems.jmatio.io.MatFileReader.MallocPolicy)}</code>
*
* @param file
* the MAT-file
* @param MatFileFilter
* array name filter.
* @throws IOException
* when error occurred while processing the file.
*/
public MatFileReader(File file, MatFileFilter filter, MatFileType matType) throws IOException
{
this(matType);
read(file, filter, MEMORY_MAPPED_FILE);
}
public MatFileReader(MatFileType matType)
{
this.matType = matType;
filter = new MatFileFilter();
data = new LinkedHashMap<String, MLArray>();
}
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file from
* <code>file</code>.
*
* This method reads MAT-file without filtering.
*
* @param stream
* the MAT-file stream
* @throws IOException
* when error occurred while processing the file.
*/
public MatFileReader(InputStream stream, MatFileType type) throws IOException
{
this(stream, new MatFileFilter(), type);
}
/**
* Creates instance of <code>MatFileReader</code> and reads MAT-file from
* <code>file</code>.
* <p>
* Results are filtered by <code>MatFileFilter</code>. Arrays that do not
* meet filter match condition will not be available in results.
* <p>
* <i>Note: this method reads file using the memory mapped file policy, see
* notes to </code>
* {@link #read(File, MatFileFilter, ca.mjdsystems.jmatio.io.MatFileReader.MallocPolicy)}
* </code>
*
* @param stream
* the MAT-file stream
* @param MatFileFilter
* array name filter.
* @throws IOException
* when error occurred while processing the file.
*/
public MatFileReader(InputStream stream, MatFileFilter filter, MatFileType type) throws IOException
{
this(type);
read(stream, filter);
}
/**
* Reads the content of a MAT-file and returns the mapped content.
* <p>
* This method calls
* <code>read(file, new MatFileFilter(), MallocPolicy.MEMORY_MAPPED_FILE)</code>.
*
* @param file
* a valid MAT-file file to be read
* @return the same as <code>{@link #getContent()}</code>
* @throws IOException
* if error occurs during file processing
*/
public synchronized Map<String, MLArray> read(File file) throws IOException
{
return read(file, new MatFileFilter(), MEMORY_MAPPED_FILE);
}
/**
* Reads the content of a MAT-file and returns the mapped content.
* <p>
* This method calls <code>read(stream, new MatFileFilter())</code>.
*
* @param stream
* a valid MAT-file stream to be read
* @return the same as <code>{@link #getContent()}</code>
* @throws IOException
* if error occurs during file processing
*/
public synchronized Map<String, MLArray> read(InputStream stream) throws IOException
{
return read(stream, new MatFileFilter());
}
/**
* Reads the content of a MAT-file and returns the mapped content.
* <p>
* This method calls
* <code>read(file, new MatFileFilter(), policy)</code>.
*
* @param file
* a valid MAT-file file to be read
* @param policy
* the file memory allocation policy
* @return the same as <code>{@link #getContent()}</code>
* @throws IOException
* if error occurs during file processing
*/
public synchronized Map<String, MLArray> read(File file, int policy) throws IOException
{
return read(file, new MatFileFilter(), policy);
}
private static final int DIRECT_BUFFER_LIMIT = 1 << 25;
public synchronized Map<String, MLArray> read(File file, MatFileFilter filter,
int policy) throws IOException
{
this.filter = filter;
//clear the results
for ( String key : data.keySet() )
{
data.remove(key);
}
FileChannel roChannel = null;
RandomAccessFile raFile = null;
ByteBuffer buf = null;
WeakReference<MappedByteBuffer> bufferWeakRef = null;
try
{
//Create a read-only memory-mapped file
raFile = new RandomAccessFile(file, "r");
roChannel = raFile.getChannel();
// until java bug #4715154 is fixed I am not using memory mapped files
// The bug disables re-opening the memory mapped files for writing
// or deleting until the VM stops working. In real life I need to open
// and update files
switch ( policy )
{
case DIRECT_BYTE_BUFFER:
buf = ByteBuffer.allocateDirect( (int)roChannel.size() );
roChannel.read(buf, 0);
buf.rewind();
break;
case HEAP_BYTE_BUFFER:
int filesize = (int)roChannel.size();
System.gc();
buf = ByteBuffer.allocate( filesize );
// The following two methods couldn't be used (at least under MS Windows)
// since they are implemented in a suboptimal way. Each of them
// allocates its own _direct_ buffer of exactly the same size,
// the buffer passed as parameter has, reads data into it and
// only afterwards moves data into the buffer passed as parameter.
// roChannel.read(buf, 0); // ends up in outOfMemory
// raFile.readFully(buf.array()); // ends up in outOfMemory
int numberOfBlocks = filesize / DIRECT_BUFFER_LIMIT + ((filesize % DIRECT_BUFFER_LIMIT) > 0 ? 1 : 0);
if (numberOfBlocks > 1) {
ByteBuffer tempByteBuffer = ByteBuffer.allocateDirect(DIRECT_BUFFER_LIMIT);
for (int block=0; block<numberOfBlocks; block++) {
tempByteBuffer.clear();
roChannel.read(tempByteBuffer, block*DIRECT_BUFFER_LIMIT);
tempByteBuffer.flip();
buf.put(tempByteBuffer);
}
tempByteBuffer = null;
} else
roChannel.read(buf, 0);
buf.rewind();
break;
case MEMORY_MAPPED_FILE:
buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
bufferWeakRef = new WeakReference<MappedByteBuffer>((MappedByteBuffer)buf);
break;
default:
throw new IllegalArgumentException("Unknown file allocation policy");
}
//read in file header
readHeader(buf);
while ( buf.remaining() > 0 ) {
readData( buf );
}
if ( haveMCOS ) {
parseMCOS(mcosData);
if ( data.get("@") == mcosData ) {
data.remove("@");
}
for ( Map.Entry<String, MLArray> it : data.entrySet() ) {
if ( it.getValue() == mcosData ) {
data.remove(it.getKey());
break;
}
}
}
mcosData = null;
return getContent();
}
catch ( IOException e )
{
throw e;
}
finally
{
if ( roChannel != null )
{
roChannel.close();
}
if ( raFile != null )
{
raFile.close();
}
if ( buf != null && bufferWeakRef != null && policy == MEMORY_MAPPED_FILE )
{
try
{
clean(buf);
}
catch ( Exception e )
{
int GC_TIMEOUT_MS = 1000;
buf = null;
long start = System.currentTimeMillis();
while (bufferWeakRef.get() != null)
{
if (System.currentTimeMillis() - start > GC_TIMEOUT_MS)
{
break; //a hell cannot be unmapped - hopefully GC will
//do it's job later
}
System.gc();
Thread.yield();
}
}
}
}
}
private void parseMCOS(MLUInt8 mcosData) throws IOException
{
// First, parse back out the mcosData.
ByteBuffer buffer = mcosData.getRealByteBuffer();
ByteBufferInputStream dataStream = new ByteBufferInputStream(buffer, buffer.limit());
Map<String, MLArray> mcosContent;
MatFileReader matFile = new MatFileReader(dataStream, MatFileType.ReducedHeader);
mcosContent = matFile.getContent();
MLCell mcosInfo = (MLCell) ((MLStructure) mcosContent.get("@0")).getField("MCOS");
ByteBuffer mcosDataBuf = ((MLUInt8) mcosInfo.get(0)).getRealByteBuffer();
// This bytebuffer needs to be read in the byte order of the MAT file order. Thus fix.
mcosDataBuf.order(matFile.getMatFileHeader().getByteOrder());
// Parse out the data buffer. First get version information. Should always equal 2.
int version = mcosDataBuf.getInt();
if (version != 2) {
throw new IllegalStateException("MAT file's MCOS data has a different version(?). Got: " + version + ", wanted 2.");
}
// Get the string count + define the string array.
int strCount = mcosDataBuf.getInt();
String[] strs = new String[strCount];
// Get the segment indexes.
int segmentIndexes[] = new int[6];
for (int i = 0; i < segmentIndexes.length; ++i) {
segmentIndexes[i] = mcosDataBuf.getInt();
}
// There should now be 8 0 bytes. Make sure this is true to avoid object format changes.
if (mcosDataBuf.getLong() != 0) {
throw new IllegalStateException("MAT file's MCOS data has different byte values for unknown fields! Aborting!");
}
// Finally, read in each string. Java doesn't provide an easy way to do this in bulk, so just use a stupid formula for now.
for (int i = 0; i < strCount; ++i) {
StringBuilder sb = new StringBuilder();
for (char next = (char)mcosDataBuf.get(); next != '\0'; next = (char)mcosDataBuf.get()) {
sb.append(next);
}
strs[i] = sb.toString();
}
// Sanity check, next 8 byte aligned position in the buffer should equal the start of the first segment!
if (((mcosDataBuf.position() + 0x07) & ~0x07) != segmentIndexes[0]) {
throw new IllegalStateException("Data from the strings section was not all read!");
}
// First segment, class information. Really just need the class names.
List<String> classNamesList = new ArrayList<String>();
mcosDataBuf.position(segmentIndexes[0]);
// There are 16 unknown bytes. Ensure they are 0.
if (mcosDataBuf.getLong() != 0 || mcosDataBuf.getLong() != 0) {
throw new IllegalStateException("MAT file's MCOS data has different byte values for unknown fields! Aborting!");
}
while (mcosDataBuf.position() < segmentIndexes[1]) {
int packageNameIndex = mcosDataBuf.getInt(); // Unused for now.
int classNameIndex = mcosDataBuf.getInt(); // Unused for now.
String className = strs[classNameIndex - 1];
classNamesList.add(className);
if (mcosDataBuf.getLong() != 0) {
throw new IllegalStateException("MAT file's MCOS data has different byte values for unknown fields! Aborting!");
}
}
// Sanity check, position in the buffer should equal the start of the second segment!
if (mcosDataBuf.position() != segmentIndexes[1]) {
throw new IllegalStateException("Data from the class section was not all read!");
}
// @todo: Second segment, Object properties containing other properties. Not used yet, thus ignored.
mcosDataBuf.position(segmentIndexes[2]);
// Third segment. Contains all the useful per-object information.
Map<Integer, MatMCOSObjectInformation> objectInfoList = new HashMap<Integer, MatMCOSObjectInformation>();
// There are 24 unknown bytes. Ensure they are 0.
if (mcosDataBuf.getLong() != 0 || mcosDataBuf.getLong() != 0 || mcosDataBuf.getLong() != 0) {
throw new IllegalStateException("MAT file's MCOS data has different byte values for unknown fields! Aborting!");
}
while (mcosDataBuf.position() < segmentIndexes[3]) {
// First fetch the data.
int classIndex = mcosDataBuf.getInt();
if (mcosDataBuf.getLong() != 0) {
throw new IllegalStateException("MAT file's MCOS data has different byte values for unknown fields! Aborting!");
}
int segment2Index = mcosDataBuf.getInt();
int segment4Index = mcosDataBuf.getInt();
int objectId = mcosDataBuf.getInt();
// Then parse it into the form needed for the object.
MatMCOSObjectInformation objHolder = objectInfoList.get(objectId - 1);
if (objHolder == null) {
objHolder = new MatMCOSObjectInformation(classNamesList.get(classIndex - 1), classIndex, objectId);
objectInfoList.put(objectId - 1, objHolder);
}
}
// Sanity check, position in the buffer should equal the start of the fourth segment!
if (mcosDataBuf.position() != segmentIndexes[3]) {
throw new IllegalStateException("Data from the object section was not all read! At: " + mcosDataBuf.position() + ", wanted: " + segmentIndexes[3]);
}
// Finally, merge in attributes from the global grab bag.
MLCell attribBag = (MLCell) mcosInfo.get(mcosInfo.getSize() -1); // Get the grab bag.
for (MatMCOSObjectInformation it : objectInfoList.values()) {
Collection<MLArray> attributes = ((MLStructure) attribBag.get(it.classId)).getAllFields();
MLStructure objAttributes = it.structure;
for (MLArray attribute : attributes) {
if (objAttributes.getField(attribute.getName()) == null) {
objAttributes.setField(attribute.getName(), attribute);
}
}
}
for (Map.Entry<String, MLArray> it : data.entrySet()) {
if ( it.getValue() instanceof MLObjectPlaceholder ) {
MLObjectPlaceholder obj = (MLObjectPlaceholder) it.getValue();
it.setValue(new MLObject(obj.name, classNamesList.get(obj.classId - 1), objectInfoList.get(obj.objectId - 1).structure));
}
}
}
/**
* Read a mat file from a stream. Internally this will read the stream fully
* into memory before parsing it.
*
* @param stream
* a valid MAT-file stream to be read
* @param filter
* the array filter applied during reading
*
* @return the same as <code>{@link #getContent()}</code>
* @see MatFileFilter
* @throws IOException
* if error occurs during file processing
*/
public synchronized Map<String, MLArray> read(InputStream stream, MatFileFilter filter) throws IOException
{
this.filter = filter;
data.clear();
ByteBuffer buf = null;
final ByteArrayOutputStream2 baos = new ByteArrayOutputStream2();
copy(stream, baos);
buf = ByteBuffer.wrap(baos.getBuf(), 0, baos.getCount());
// read in file header
readHeader(buf);
while (buf.remaining() > 0)
{
readData(buf);
}
return getContent();
}
private void copy(InputStream stream, ByteArrayOutputStream2 output) throws IOException {
final byte[] buffer = new byte[1024 * 4];
int n = 0;
while (-1 != (n = stream.read(buffer))) {
output.write(buffer, 0, n);
}
}
private void clean(final Object buffer) throws Exception
{
AccessController.doPrivileged(new PrivilegedAction<Object>()
{
public Object run()
{
try
{
Method getCleanerMethod = buffer.getClass().getMethod(
"cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
.invoke(buffer, new Object[0]);
cleaner.clean();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
});
}
/**
* Gets MAT-file header
*
* @return - a <code>MatFileHeader</code> object
*/
public MatFileHeader getMatFileHeader()
{
return matFileHeader;
}
/**
* Returns list of <code>MLArray</code> objects that were inside MAT-file
*
* @return - a <code>ArrayList</code>
* @deprecated use <code>getContent</code> which returns a Map to provide
* easier access to <code>MLArray</code>s contained in MAT-file
*/
public ArrayList<MLArray> getData()
{
return new ArrayList<MLArray>( data.values() );
}
/**
* Returns the value to which the red file maps the specified array name.
*
* Returns <code>null</code> if the file contains no content for this name.
*
* @param - array name
* @return - the <code>MLArray</code> to which this file maps the specified name,
* or null if the file contains no content for this name.
*/
public MLArray getMLArray( String name )
{
return data.get( name );
}
/**
* Returns a map of <code>MLArray</code> objects that were inside MAT-file.
*
* MLArrays are mapped with MLArrays' names
*
* @return - a <code>Map</code> of MLArrays mapped with their names.
*/
public Map<String, MLArray> getContent()
{
return data;
}
/**
* Reads data form byte buffer. Searches for either
* <code>miCOMPRESSED</code> data or <code>miMATRIX</code> data.
*
* Compressed data are inflated and the product is recursively passed back
* to this same method.
*
* Modifies <code>buf</code> position.
*
* @param buf -
* input byte buffer
* @throws IOException when error occurs while reading the buffer.
*/
private void readData( ByteBuffer buf ) throws IOException
{
//read data
ISMatTag tag = new ISMatTag(buf);
switch ( tag.type )
{
case MatDataTypes.miCOMPRESSED:
int numOfBytes = tag.size;
//inflate and recur
if ( buf.remaining() < numOfBytes )
{
throw new MatlabIOException("Compressed buffer length miscalculated!");
}
//instead of standard Inlater class instance I use an inflater input
//stream... gives a great boost to the performance
InflaterInputStream iis = new InflaterInputStream(new ByteBufferInputStream(buf, numOfBytes));
//process data decompression
byte[] result = new byte[1024];
HeapBufferDataOutputStream dos = new HeapBufferDataOutputStream();
int i;
try
{
do
{
i = iis.read(result, 0, result.length);
int len = Math.max(0, i);
dos.write(result, 0, len);
}
while ( i > 0 );
}
catch ( IOException e )
{
throw new MatlabIOException("Could not decompress data: " + e );
}
finally
{
iis.close();
dos.flush();
}
//create a ByteBuffer from the deflated data
ByteBuffer out = dos.getByteBuffer();
//with proper byte ordering
out.order( byteOrder );
try
{
readData( out );
}
catch ( IOException e )
{
throw e;
}
finally
{
dos.close();
}
break;
case MatDataTypes.miMATRIX:
//read in the matrix
int pos = buf.position();
MLArray element = readMatrix( buf, true );
if ( element != null ) {
if ( !data.containsKey( element.getName() ) ) {
data.put(element.getName(), element);
}
if ( element.getName() == "@" ) {
int nextIndex = 0;
for( ; data.containsKey("@" + nextIndex); nextIndex++ ) { }
data.put( "@" + nextIndex, element );
}
} else {
int red = buf.position() - pos;
int toread = tag.size - red;
buf.position( buf.position() + toread );
}
int red = buf.position() - pos;
int toread = tag.size - red;
if ( toread != 0 )
{
throw new MatlabIOException("Matrix was not red fully! " + toread + " remaining in the buffer.");
}
break;
default:
throw new MatlabIOException("Incorrect data tag: " + tag);
}
}
private MLArray readMatrix(ByteBuffer buf, boolean isRoot ) throws IOException
{
//result
MLArray mlArray;
ISMatTag tag;
//read flags
int[] flags = readFlags(buf);
int attributes = ( flags.length != 0 ) ? flags[0] : 0;
int nzmax = ( flags.length != 0 ) ? flags[1] : 0;
int type = attributes & 0xff;
//read Array dimension
int[] dims = readDimension(buf);
//read array Name
String name = readName(buf);
//if this array is filtered out return immediately
if ( isRoot && !filter.matches(name) )
{
return null;
}
//read data >> consider changing it to stategy pattern
switch ( type )
{
case MLArray.mxSTRUCT_CLASS:
MLStructure struct = new MLStructure(name, dims, type, attributes);
// field name length - this subelement always uses the compressed data element format
tag = new ISMatTag(buf);
int maxlen = buf.getInt(); //maximum field length
////// read fields data as Int8
tag = new ISMatTag(buf);
//calculate number of fields
int numOfFields = tag.size/maxlen;
String[] fieldNames = new String[numOfFields];
for ( int i = 0; i < numOfFields; i++ )
{
byte[] names = new byte[maxlen];
buf.get(names);
fieldNames[i] = zeroEndByteArrayToString(names);
}
buf.position( buf.position() + tag.padding );
//read fields
for ( int index = 0; index < struct.getM()*struct.getN(); index++ )
{
for ( int i = 0; i < numOfFields; i++ )
{
//read matrix recursively
tag = new ISMatTag(buf);
if ( tag.size > 0 )
{
MLArray fieldValue = readMatrix( buf, false);
struct.setField(fieldNames[i], fieldValue, index);
}
else
{
struct.setField(fieldNames[i], new MLEmptyArray(), index);
}
}
}
mlArray = struct;
break;
case MLArray.mxCELL_CLASS:
MLCell cell = new MLCell(name, dims, type, attributes);
for ( int i = 0; i < cell.getM()*cell.getN(); i++ )
{
tag = new ISMatTag(buf);
if ( tag.size > 0 )
{
//read matrix recursively
MLArray cellmatrix = readMatrix( buf, false);
cell.set(cellmatrix, i);
}
else
{
cell.set(new MLEmptyArray(), i);
}
}
mlArray = cell;
break;
case MLArray.mxDOUBLE_CLASS:
mlArray = new MLDouble(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxSINGLE_CLASS:
mlArray = new MLSingle(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxUINT8_CLASS:
mlArray = new MLUInt8(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
// This might be the MCOS extra data. If there is no name, set it as the current set of data.
if ( name.equals("") ) {
mcosData = (MLUInt8) mlArray;
}
break;
case MLArray.mxINT8_CLASS:
mlArray = new MLInt8(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxINT16_CLASS:
mlArray = new MLInt16(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxINT32_CLASS:
mlArray = new MLInt32(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxUINT32_CLASS:
mlArray = new MLUInt32(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxINT64_CLASS:
mlArray = new MLInt64(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxUINT64_CLASS:
mlArray = new MLUInt64(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getRealByteBuffer(),
(MLNumericArray<?>) mlArray );
//read complex
if ( mlArray.isComplex() )
{
tag = new ISMatTag(buf);
tag.readToByteBuffer( ((MLNumericArray<?>) mlArray).getImaginaryByteBuffer(),
(MLNumericArray<?>) mlArray );
}
break;
case MLArray.mxCHAR_CLASS:
MLChar mlchar = new MLChar(name, dims, type, attributes);
//read real
tag = new ISMatTag(buf);
// char[] ac = tag.readToCharArray();
String str = tag.readToString();
for ( int i = 0; i < str.length(); i++ )
{
mlchar.setChar( str.charAt(i), i );
}
mlArray = mlchar;
break;
case MLArray.mxSPARSE_CLASS:
MLSparse sparse = new MLSparse(name, dims, attributes, nzmax);
//read ir (row indices)
tag = new ISMatTag(buf);
int[] ir = tag.readToIntArray();
//read jc (column count)
tag = new ISMatTag(buf);
int[] jc = tag.readToIntArray();
//read pr (real part)
tag = new ISMatTag(buf);
double[] ad1 = tag.readToDoubleArray();
int count = 0;
for (int column = 0; column < sparse.getN(); column++) {
while(count < jc[column+1]) {
sparse.setReal(ad1[count], ir[count], column);
count++;
}
}
//read pi (imaginary part)
if ( sparse.isComplex() )
{
tag = new ISMatTag(buf);
double[] ad2 = tag.readToDoubleArray();
count = 0;
for (int column = 0; column < sparse.getN(); column++) {
while(count < jc[column+1]) {
sparse.setImaginary(ad2[count], ir[count], column);
count++;
}
}
}
mlArray = sparse;
break;
case MLArray.mxOPAQUE_CLASS:
//read class name
tag = new ISMatTag(buf);
// class name
String className = tag.readToString();
// System.out.println( "Class name: " + className );
// should be "java"
// System.out.println( "Array name: " + name );
// the stored array name
// read array name stored in dims (!)
byte[] nn = new byte[dims.length];
for ( int i = 0; i < dims.length; i++ )
{
nn[i] = (byte)dims[i];
}
String arrName = new String(nn);
// System.out.println( "Array name: " + arrName );
// next tag should be miMatrix
ISMatTag contentTag = new ISMatTag(buf);
if ( contentTag.type == MatDataTypes.miMATRIX ) {
if ( name.equals("java") ) {
// should return UInt8
MLUInt8 content = (MLUInt8) readMatrix(buf, false);
// de-serialize object
ObjectInputStream ois = new ObjectInputStream(
new ByteBufferInputStream(content.getRealByteBuffer(),
content.getRealByteBuffer().limit())
);
try {
Object o = ois.readObject();
mlArray = new MLJavaObject(arrName, className, o);
} catch (Exception e) {
throw new IOException(e);
} finally {
ois.close();
}
} else if ( name.equals("MCOS") ) {
// FileWrapper__ is a special MATLAB internal name. Should never appear from users.
if ( !className.equals("FileWrapper__") ) {
MLUInt32 content = (MLUInt32) readMatrix(buf, false);
int[][] t = content.getArray();
// Check that the first four numbers are the same, as expected.
if (t[0][0] != 0xdd000000 || t[1][0] != 2 || t[2][0] != 1 || t[3][0] != 1) {
throw new IOException("MCOS per-object header was different then expected! Got: " + content.contentToString());
}
mlArray = new MLObjectPlaceholder(arrName, className, t);
haveMCOS = true;
} else { // This is where we get the useful MCOS data. Only used on FileWrapper__ classes.
mlArray = readMatrix(buf, false);
}
} else {
throw new IOException("Unknown object type (" + name + ") found.");
}
}
else
{
throw new IOException("Unexpected object content");
}
break;
case MLArray.mxOBJECT_CLASS:
//read class name
tag = new ISMatTag(buf);
// class name
className = tag.readToString();
// TODO: currently copy pasted from structure
struct = new MLStructure(name, dims, type, attributes);
//field name lenght - this subelement always uses the compressed data element format
tag = new ISMatTag(buf);
maxlen = buf.getInt(); //maximum field length
////// read fields data as Int8
tag = new ISMatTag(buf);
//calculate number of fields
numOfFields = tag.size/maxlen;
fieldNames = new String[numOfFields];
for ( int i = 0; i < numOfFields; i++ )
{
byte[] names = new byte[maxlen];
buf.get(names);
fieldNames[i] = zeroEndByteArrayToString(names);
}
buf.position( buf.position() + tag.padding );
//read fields
for ( int index = 0; index < 1; index++ )
{
for ( int i = 0; i < numOfFields; i++ )
{
//read matrix recursively
tag = new ISMatTag(buf);
if ( tag.size > 0 )
{
MLArray fieldValue = readMatrix( buf, false);
struct.setField( fieldNames[i], fieldValue, index );
}
else
{
struct.setField(fieldNames[i], new MLEmptyArray(), index);
}
}
}
mlArray = new MLObject( name, className, struct );
break;
default:
throw new MatlabIOException("Incorrect matlab array class: " + MLArray.typeToString(type) );
}
return mlArray;
}
/**
* Converts byte array to <code>String</code>.
*
* It assumes that String ends with \0 value.
*
* @param bytes byte array containing the string.
* @return String retrieved from byte array.
* @throws IOException if reading error occurred.
*/
private String zeroEndByteArrayToString(byte[] bytes) throws IOException
{
int i = 0;
for ( i = 0; i < bytes.length && bytes[i] != 0; i++ );
return new String( bytes, 0, i );
}
/**
* Reads Matrix flags.
*
* Modifies <code>buf</code> position.
*
* @param buf <code>ByteBuffer</code>
* @return flags int array
* @throws IOException if reading from buffer fails
*/
private int[] readFlags(ByteBuffer buf) throws IOException
{
ISMatTag tag = new ISMatTag(buf);
int[] flags = tag.readToIntArray();
return flags;
}
/**
* Reads Matrix dimensions.
*
* Modifies <code>buf</code> position.
*
* @param buf <code>ByteBuffer</code>
* @return dimensions int array
* @throws IOException if reading from buffer fails
*/
private int[] readDimension(ByteBuffer buf ) throws IOException
{
ISMatTag tag = new ISMatTag(buf);
int[] dims = tag.readToIntArray();
return dims;
}
/**
* Reads Matrix name.
*
* Modifies <code>buf</code> position.
*
* @param buf <code>ByteBuffer</code>
* @return name <code>String</code>
* @throws IOException if reading from buffer fails
*/
private String readName(ByteBuffer buf) throws IOException
{
ISMatTag tag = new ISMatTag(buf);
return tag.readToString();
}
/**
* Reads MAT-file header.
*
* Modifies <code>buf</code> position.
*
* @param buf
* <code>ByteBuffer</code>
* @throws IOException
* if reading from buffer fails or if this is not a valid
* MAT-file
*/
private void readHeader(ByteBuffer buf) throws IOException
{
//header values
String description;
int version;
byte[] endianIndicator = new byte[2];
// This part of the header is missing if the file isn't a regular mat file. So ignore.
if (matType == MatFileType.Regular) {
//descriptive text 116 bytes
byte[] descriptionBuffer = new byte[116];
buf.get(descriptionBuffer);
description = zeroEndByteArrayToString(descriptionBuffer);
if (!description.matches("MATLAB 5.0 MAT-file.*")) {
throw new MatlabIOException("This is not a valid MATLAB 5.0 MAT-file.");
}
//subsyst data offset 8 bytes
buf.position(buf.position() + 8);
} else {
description = "Simulink generated MATLAB 5.0 MAT-file"; // Default simulink description.
}
byte[] bversion = new byte[2];
//version 2 bytes
buf.get(bversion);
//endian indicator 2 bytes
buf.get(endianIndicator);
//program reading the MAT-file must perform byte swapping to interpret the data
//in the MAT-file correctly
if ( (char)endianIndicator[0] == 'I' && (char)endianIndicator[1] == 'M')
{
byteOrder = ByteOrder.LITTLE_ENDIAN;
version = bversion[1] & 0xff | bversion[0] << 8;
}
else
{
byteOrder = ByteOrder.BIG_ENDIAN;
version = bversion[0] & 0xff | bversion[1] << 8;
}
buf.order( byteOrder );
matFileHeader = new MatFileHeader(description, version, endianIndicator, byteOrder);
// After the header, the next read must be aligned. Thus force the alignment. Only matters with reduced header data,
// but apply it regardless for safety.
buf.position((buf.position() + 7) & 0xfffffff8);
}
/**
* TAG operator. Facilitates reading operations.
*
* <i>Note: reading from buffer modifies it's position</i>
*
* @author Wojciech Gradkowski (<a href="mailto:wgradkowski@gmail.com">wgradkowski@gmail.com</a>)
*/
private static class ISMatTag extends MatTag
{
private final MatFileInputStream mfis;
private final int padding;
private final boolean compressed;
public ISMatTag(ByteBuffer buf) throws IOException
{
//must call parent constructor
super(0,0);
int tmp = buf.getInt();
//data not packed in the tag
if ( tmp >> 16 == 0 )
{
type = tmp;
size = buf.getInt();
compressed = false;
}
else //data _packed_ in the tag (compressed)
{
size = tmp >> 16; // 2 more significant bytes
type = tmp & 0xffff; // 2 less significant bytes;
compressed = true;
}
padding = getPadding(size, compressed);
mfis = new MatFileInputStream(buf, type);
}
public void readToByteBuffer( ByteBuffer buff, ByteStorageSupport<?> storage ) throws IOException
{
int elements = size/sizeOf();
mfis.readToByteBuffer( buff, elements, storage );
mfis.skip( padding );
}
public byte[] readToByteArray() throws IOException
{
//allocate memory for array elements
int elements = size/sizeOf();
byte[] ab = new byte[elements];
for ( int i = 0; i < elements; i++ )
{
ab[i] = mfis.readByte();
}
//skip padding
mfis.skip( padding );
return ab;
}
public double[] readToDoubleArray() throws IOException
{
//allocate memory for array elements
int elements = size/sizeOf();
double[] ad = new double[elements];
for ( int i = 0; i < elements; i++ )
{
ad[i] = mfis.readDouble();
}
//skip padding
mfis.skip( padding );
return ad;
}
public int[] readToIntArray() throws IOException
{
//allocate memory for array elements
int elements = size/sizeOf();
int[] ai = new int[elements];
for ( int i = 0; i < elements; i++ )
{
ai[i] = mfis.readInt();
}
//skip padding
mfis.skip( padding );
return ai;
}
public String readToString() throws IOException
{
byte[] bytes = readToByteArray();
return new String( bytes, "UTF-8" );
}
public char[] readToCharArray() throws IOException
{
//allocate memory for array elements
int elements = size/sizeOf();
char[] ac = new char[elements];
for ( int i = 0; i < elements; i++ )
{
ac[i] = mfis.readChar();
}
//skip padding
mfis.skip( padding );
return ac;
}
}
}
|
package scrum.client.sprint;
import scrum.client.collaboration.CommentsWidget;
import scrum.client.common.AScrumWidget;
import scrum.client.common.BlockListWidget;
import scrum.client.project.Requirement;
import scrum.client.workspace.PagePanel;
import com.google.gwt.user.client.ui.Widget;
public class SprintBacklogWidget extends AScrumWidget {
private BlockListWidget<Requirement> requirementList;
@Override
protected Widget onInitialization() {
Sprint sprint = getSprint();
requirementList = new BlockListWidget<Requirement>(RequirementInSprintBlock.FACTORY);
requirementList.setAutoSorter(getCurrentProject().getRequirementsOrderComparator());
PagePanel page = new PagePanel();
page.addHeader("Requirements in this Sprint");
page.addSection(requirementList);
page.addHeader("Sprint Properties");
page.addSection(new SprintWidget(sprint));
page.addHeader("Sprint Comments");
page.addSection(new CommentsWidget(sprint));
return page;
}
@Override
protected void onUpdate() {
requirementList.setObjects(getSprint().getRequirements());
super.onUpdate();
}
public void selectRequirement(Requirement r) {
requirementList.extendObject(r);
requirementList.scrollToObject(r);
}
public void selectTask(Task task) {
RequirementInSprintBlock rBlock = (RequirementInSprintBlock) requirementList.getBlock(task.getRequirement());
requirementList.extendBlock(rBlock, true);
rBlock.selectTask(task);
}
private Sprint getSprint() {
return getCurrentProject().getCurrentSprint();
}
}
|
package org.xins.common.http;
import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnection;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpRecoverableException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.NDC;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.ProgrammingError;
import org.xins.common.TimeOutException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.collections.PropertyReaderUtils;
import org.xins.common.text.URLEncoding;
import org.xins.common.service.CallConfig;
import org.xins.common.service.CallException;
import org.xins.common.service.CallExceptionList;
import org.xins.common.service.CallRequest;
import org.xins.common.service.CallResult;
import org.xins.common.service.ConnectionRefusedCallException;
import org.xins.common.service.ConnectionTimeOutCallException;
import org.xins.common.service.Descriptor;
import org.xins.common.service.GenericCallException;
import org.xins.common.service.IOCallException;
import org.xins.common.service.ServiceCaller;
import org.xins.common.service.SocketTimeOutCallException;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.service.TotalTimeOutCallException;
import org.xins.common.service.UnexpectedExceptionCallException;
import org.xins.common.service.UnknownHostCallException;
import org.xins.common.service.UnsupportedProtocolException;
import org.xins.common.text.FastStringBuffer;
import org.xins.common.text.TextUtils;
import org.xins.logdoc.LogdocSerializable;
public final class HTTPServiceCaller extends ServiceCaller {
// Class fields
/**
* Fully-qualified name of this class.
*/
private static final String CLASSNAME = HTTPServiceCaller.class.getName();
// Class functions
/**
* Logs the fact that the constructor was entered. The descriptor passed
* to the constructor is both the input and the output for this class
* function.
*
* @param descriptor
* the descriptor, could be <code>null</code>.
*
* @return
* <code>descriptor</code>.
*/
private static final Descriptor trace(Descriptor descriptor) {
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
return descriptor;
}
private static HttpMethod createMethod(String url,
HTTPCallRequest request,
HTTPCallConfig callConfig)
throws IllegalArgumentException {
final String THIS_METHOD = "createMethod(String,HTTPCallRequest,HTTPCallConfig)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// Check preconditions
MandatoryArgumentChecker.check("url", url, "request", request);
// Get the HTTP method (like GET and POST) and parameters
HTTPMethod method = callConfig.getMethod();
PropertyReader parameters = request.getParameters();
// HTTP POST request
if (method == HTTPMethod.POST) {
PostMethod postMethod = new PostMethod(url);
// Loop through the parameters
if (parameters != null) {
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
String value = parameters.get(key);
if (value == null) {
value = "";
}
// Add this parameter key/value combination.
if (key != null) {
postMethod.addParameter(key, value);
}
}
}
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return postMethod;
// HTTP GET request
} else if (method == HTTPMethod.GET) {
GetMethod getMethod = new GetMethod(url);
// Loop through the parameters
if (parameters != null) {
FastStringBuffer query = new FastStringBuffer(255);
Iterator keys = parameters.getNames();
while (keys.hasNext()) {
// Get the parameter key
String key = (String) keys.next();
// Get the value
String value = parameters.get(key);
if (value == null) {
value = "";
}
// Add this parameter key/value combination.
if (key != null) {
if (query.getLength() > 0) {
query.append("&");
}
query.append(URLEncoding.encode(key));
query.append("=");
query.append(URLEncoding.encode(value));
}
}
if (query.getLength() > 0) {
getMethod.setQueryString(query.toString());
}
}
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return getMethod;
// Unrecognized HTTP method (only GET and POST are supported)
} else {
String message = "Unrecognized HTTP method \"" + method + "\".";
Log.log_1050(CLASSNAME, THIS_METHOD, message);
throw new ProgrammingError(message);
}
}
// Constructors
public HTTPServiceCaller(Descriptor descriptor,
HTTPCallConfig callConfig)
throws IllegalArgumentException, UnsupportedProtocolException {
// Trace first and then call superclass constructor
super(trace(descriptor), callConfig);
// Check that all targets have a supported protocol
Iterator iterator = descriptor.iterateTargets();
while (iterator.hasNext()) {
TargetDescriptor target = (TargetDescriptor) iterator.next();
String url = target.getURL().toLowerCase();
if (! url.startsWith("http:
throw new UnsupportedProtocolException(target);
}
}
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
public HTTPServiceCaller(Descriptor descriptor)
throws IllegalArgumentException, UnsupportedProtocolException {
this(descriptor, null);
}
// Fields
// Methods
/**
* Returns a default <code>CallConfig</code> object. This method is called
* by the <code>ServiceCaller</code> constructor if no
* <code>CallConfig</code> object was given.
*
* <p>The implementation of this method in class {@link HTTPServiceCaller}
* returns a standard {@link HTTPCallConfig} object which has unconditional
* fail-over disabled and the HTTP method set to
* {@link HTTPMethod#POST POST}.
*
* @return
* a new {@link HTTPCallConfig} instance, never <code>null</code>.
*/
protected CallConfig getDefaultCallConfig() {
return new HTTPCallConfig();
}
protected Object doCallImpl(CallRequest request,
CallConfig callConfig,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
final String THIS_METHOD = "doCallImpl(CallRequest,CallConfig,TargetDescriptor)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// Delegate to method with more specialized interface
Object ret = call((HTTPCallRequest) request,
(HTTPCallConfig) callConfig,
target);
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return ret;
}
public HTTPCallResult call(HTTPCallRequest request,
HTTPCallConfig callConfig)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
final String THIS_METHOD = "call(HTTPCallRequest,HTTPCallConfig)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Perform the call
CallResult callResult;
try {
callResult = doCall(request, callConfig);
// Allow GenericCallException, HTTPCallException and Error to proceed,
// but block other kinds of exceptions and throw an Error instead.
} catch (GenericCallException exception) {
throw exception;
} catch (HTTPCallException exception) {
throw exception;
} catch (Exception exception) {
final String METHOD = "doCall(CallRequest,CallConfig)";
FastStringBuffer message = new FastStringBuffer(190, CLASSNAME);
message.append('.');
message.append(METHOD);
message.append(" threw ");
message.append(exception.getClass().getName());
message.append(". Message: ");
message.append(TextUtils.quote(exception.getMessage()));
message.append('.');
Log.log_1052(exception, CLASSNAME, METHOD);
throw new ProgrammingError(message.toString(), exception);
}
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return (HTTPCallResult) callResult;
}
public HTTPCallResult call(HTTPCallRequest request)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
return call(request, (HTTPCallConfig) null);
}
public HTTPCallResult call(HTTPCallRequest request,
HTTPCallConfig callConfig,
TargetDescriptor target)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
// TRACE: Enter method
Log.log_1003(CLASSNAME, "call(HTTPCallRequest,TargetDescriptor)", null);
// Get the parameters for logging
PropertyReader p = request.getParameters();
LogdocSerializable params = PropertyReaderUtils.serialize(p, "-");
// Prepare a thread for execution of the call
// NOTE: Preconditions are checked by the CallExecutor constructor
CallExecutor executor = new CallExecutor(request, callConfig, target, NDC.peek());
// Get URL and time-out values
String url = target.getURL();
int totalTimeOut = target.getTotalTimeOut();
int connectionTimeOut = target.getConnectionTimeOut();
int socketTimeOut = target.getSocketTimeOut();
// About to make an HTTP call
Log.log_1100(url, params, totalTimeOut, connectionTimeOut, socketTimeOut);
// Perform the HTTP call
long start = System.currentTimeMillis();
long duration;
try {
controlTimeOut(executor, target);
// Total time-out exceeded
} catch (TimeOutException exception) {
duration = System.currentTimeMillis() - start;
Log.log_1106(url, params, duration, totalTimeOut);
throw new TotalTimeOutCallException(request, target, duration);
} finally {
// Determine the call duration
duration = System.currentTimeMillis() - start;
}
// Log the HTTP call done.
Log.log_1101(url, params, duration);
// Check for exceptions
Throwable exception = executor.getException();
if (exception != null) {
// Unknown host
if (exception instanceof UnknownHostException) {
Log.log_1102(url, params, duration);
throw new UnknownHostCallException(request, target, duration);
// Connection refusal
} else if (exception instanceof ConnectException) {
Log.log_1103(url, params, duration);
throw new ConnectionRefusedCallException(request, target, duration);
// Connection time-out
} else if (exception instanceof HttpConnection.ConnectionTimeoutException) {
Log.log_1104(url, params, duration, connectionTimeOut);
throw new ConnectionTimeOutCallException(request, target, duration);
// Socket time-out
} else if (exception instanceof HttpRecoverableException) {
// XXX: This is an ugly way to detect a socket time-out, but there
// does not seem to be a better way in HttpClient 2.0. This
// will, however, be fixed in HttpClient 3.0. See:
String exMessage = exception.getMessage();
if (exMessage != null && exMessage.startsWith("java.net.SocketTimeoutException")) {
Log.log_1105(url, params, duration, socketTimeOut);
throw new SocketTimeOutCallException(request, target, duration);
// Unspecific I/O error
} else {
Log.log_1109(exception, url, params, duration);
throw new IOCallException(request, target, duration, (IOException) exception);
}
// Unspecific I/O error
} else if (exception instanceof IOException) {
Log.log_1109(exception, url, params, duration);
throw new IOCallException(request, target, duration, (IOException) exception);
// Unrecognized kind of exception caught
} else {
Log.log_1052(exception, executor.getThrowingClass(), executor.getThrowingMethod());
throw new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
}
// Retrieve the data returned from the HTTP call
HTTPCallResultData data = executor.getData();
// Determine the HTTP status code
int code = data.getStatusCode();
HTTPStatusCodeVerifier verifier = request.getStatusCodeVerifier();
// Status code is considered acceptable
if (verifier == null || verifier.isAcceptable(code)) {
Log.log_1107(url, params, duration, code);
// Status code is considered unacceptable
} else {
Log.log_1108(url, params, duration, code);
// TODO: Pass down body as well. Perhaps just pass down complete
// HTTPCallResult object and add getter for the body to the
// StatusCodeHTTPCallException class.
throw new StatusCodeHTTPCallException(request, target, duration, code);
}
// TRACE: Leave method
Log.log_1005(CLASSNAME, "call(HTTPCallRequest,TargetDescriptor)", null);
return new HTTPCallResult(request, target, duration, null, data);
}
public HTTPCallResult call(HTTPCallRequest request,
TargetDescriptor target)
throws IllegalArgumentException,
GenericCallException,
HTTPCallException {
return call(request, (HTTPCallConfig) null, target);
}
/**
* Constructs an appropriate <code>CallResult</code> object for a
* successful call attempt. This method is called from
* {@link #doCall(CallRequest)}.
*
* <p>The implementation of this method in class
* {@link HTTPServiceCaller} expects an {@link HTTPCallRequest} and
* returns an {@link HTTPCallResult}.
*
* @param request
* the {@link CallRequest} that was to be executed, never
* <code>null</code> when called from {@link #doCall(CallRequest)};
* should be an instance of class {@link HTTPCallRequest}.
*
* @param succeededTarget
* the {@link TargetDescriptor} for the service that was successfully
* called, never <code>null</code> when called from
* {@link #doCall(CallRequest)}.
*
* @param duration
* the call duration in milliseconds, must be a non-negative number.
*
* @param exceptions
* the list of {@link CallException} instances, or <code>null</code> if
* there were no call failures.
*
* @param result
* the result from the call, which is the object returned by
* {@link #doCallImpl(CallRequest,TargetDescriptor)}, always an instance
* of class {@link HTTPCallResult}, never <code>null</code>; .
*
* @return
* an {@link HTTPCallResult} instance, never <code>null</code>.
*
* @throws ClassCastException
* if either <code>request</code> or <code>result</code> is not of the
* correct class.
*/
protected CallResult createCallResult(CallRequest request,
TargetDescriptor succeededTarget,
long duration,
CallExceptionList exceptions,
Object result)
throws ClassCastException {
return new HTTPCallResult((HTTPCallRequest) request,
succeededTarget,
duration,
exceptions,
(HTTPCallResultData) result);
}
/**
* Determines whether a call should fail-over to the next selected target
* based on a request, call configuration and exception list.
* This method should only be called from
* {@link #doCall(CallRequest,CallConfig)}.
*
* <p>The implementation of this method in class {@link HTTPServiceCaller}
* returns <code>true</code> if and only if one of the following conditions
* holds true:
*
* <ul>
* <li><code>super.shouldFailOver(request, callConfig, exceptions)</code>
* <li><code>exceptions.{@link CallExceptionList#last() last()}
* instanceof {@link StatusCodeHTTPCallException}</code> and for
* that exception
* {@link StatusCodeHTTPCallException#getStatusCode() getStatusCode()} is not in the
* range 200-299.
* </ul>
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param callConfig
* the call config that is currently in use, never <code>null</code>.
*
* @param exceptions
* the current list of {@link CallException}s; never
* <code>null</code>; get the most recent one by calling
* <code>exceptions.</code>{@link CallExceptionList#last() last()}.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*/
protected boolean shouldFailOver(CallRequest request,
CallConfig callConfig,
CallExceptionList exceptions) {
CallException last = exceptions.last();
// Let the superclass do it's job
if (super.shouldFailOver(request, callConfig, exceptions)) {
return true;
// A non-2xx HTTP status code indicates the request was not handled
} else if (last instanceof StatusCodeHTTPCallException) {
int code = ((StatusCodeHTTPCallException) last).getStatusCode();
return (code < 200 || code > 299);
// Otherwise do not fail over
} else {
return false;
}
}
// Inner classes
/**
* Executor of calls to an API.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
private static final class CallExecutor extends Thread {
// Class fields
/**
* The number of constructed call executors.
*/
private static int CALL_EXECUTOR_COUNT;
// Constructors
private CallExecutor(HTTPCallRequest request,
HTTPCallConfig callConfig,
TargetDescriptor target,
String context)
throws IllegalArgumentException {
// Create textual representation of this object
_asString = "HTTP call executor #" + (++CALL_EXECUTOR_COUNT);
// Check preconditions
MandatoryArgumentChecker.check("request", request,
"callConfig", callConfig,
"target", target);
// Store data for later use in the run() method
_request = request;
_callConfig = callConfig;
_target = target;
_context = context;
}
// Fields
/**
* Textual representation of this object. Never <code>null</code>.
*/
private final String _asString;
/**
* The call request to execute. Never <code>null</code>.
*/
private final HTTPCallRequest _request;
/**
* The call configuration. Never <code>null</code>.
*/
private final HTTPCallConfig _callConfig;
/**
* The service target on which to execute the request. Never
* <code>null</code>.
*/
private final TargetDescriptor _target;
/**
* The <em>Nested Diagnostic Context identifier</em> (NDC). Is set to
* <code>null</code> if it should be left unchanged.
*/
private final String _context;
/**
* The exception caught while executing the call. If there was no
* exception, then this field is <code>null</code>.
*/
private Throwable _exception;
/**
* The name of the class that threw the exception. This field is
* <code>null</code> if the call was performed successfully.
*/
private String _throwingClass;
/**
* The name of the method that threw the exception. This field is
* <code>null</code> if the call was performed successfully.
*/
private String _throwingMethod;
/**
* The result from the call. The value of this field is
* <code>null</code> if the call was unsuccessful or if it was not
* executed yet.
*/
private HTTPCallResultData _result;
// Methods
/**
* Runs this thread (wrapper method). It will call the HTTP service. If that call was
* successful, then the result is stored in this object. Otherwise
* there is an exception, in which case that exception is stored in this
* object instead.
*/
public void run() {
// TODO: Check if this request was already executed, since this is a
// stateful object. If not, mark it as executing within a
// synchronized section, so it may no 2 threads may execute
// this request at the same time.
// XXX: Note that performance could be improved by using local
// variables for _target and _request
// Activate the diagnostic context ID
if (_context != null) {
NDC.push(_context);
try {
runImpl();
} finally {
NDC.pop();
}
} else {
runImpl();
}
// TODO: Mark this CallExecutor object as executed, so it may not be
// run again
}
/**
* Runs this thread (implementation method). This method is called from
* {@link #run()}.
*/
private void runImpl() {
// Construct new HttpClient object
HttpClient client = new HttpClient();
// Determine URL and time-outs
String url = _target.getURL();
int totalTimeOut = _target.getTotalTimeOut();
int connectionTimeOut = _target.getConnectionTimeOut();
int socketTimeOut = _target.getSocketTimeOut();
// Configure connection time-out and socket time-out
client.setConnectionTimeout(connectionTimeOut);
client.setTimeout (socketTimeOut);
// Construct the method object
HttpMethod method = createMethod(url, _request, _callConfig);
// Perform the HTTP call
try {
// Execute call
_throwingClass = client.getClass().getName();
_throwingMethod = "executeMethod(" + method.getClass().getName() + ')';
int statusCode = client.executeMethod(method);
// Get response body
_throwingClass = method.getClass().getName();
_throwingMethod = "getResponseBody()";
byte[] body = method.getResponseBody();
// Store the result
_throwingClass = HTTPCallResultDataHandler.class.getName();
_throwingMethod = "<init>(int,byte[])";
_result = new HTTPCallResultDataHandler(statusCode, body);
// No exception thrown, reset _throwingXXXX fields
_throwingClass = null;
_throwingMethod = null;
// If an exception is thrown, store it for processing at later stage
} catch (Throwable exception) {
_exception = exception;
// Release the HTTP connection immediately
} finally {
try {
method.releaseConnection();
} catch (Throwable exception) {
Log.log_1052(exception, method.getClass().getName(), "releaseConnection()");
}
}
}
/**
* Gets the exception if any generated when calling the method.
*
* @return
* the invocation exception or <code>null</code> if the call was
* performed successfully.
*/
private Throwable getException() {
return _exception;
}
/**
* Gets the name of the class that threw the exception.
*
* @return
* the name of the class that threw the exception or
* <code>null</code> if the call was performed successfully.
*/
private String getThrowingClass() {
return _throwingClass;
}
/**
* Gets the name of the method that threw the exception.
*
* @return
* the name of the method that threw the exception or
* <code>null</code> if the call was performed successfully.
*/
private String getThrowingMethod() {
return _throwingMethod;
}
/**
* Returns the result if the call was successful. If the call was
* unsuccessful, then <code>null</code> is returned.
*
* @return
* the result from the call, or <code>null</code> if it was
* unsuccessful.
*/
private HTTPCallResultData getData() {
return _result;
}
}
/**
* Container of the data part of an HTTP call result.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
private final static class HTTPCallResultDataHandler
implements HTTPCallResultData {
// Constructor
/**
* Constructs a new <code>HTTPCallResultDataHandler</code> object.
*
* @param code
* the HTTP status code.
*
* @param data
* the data returned from the call, as a set of bytes.
*/
HTTPCallResultDataHandler(int code, byte[] data) {
_code = code;
_data = data;
}
// Fields
/**
* The HTTP status code.
*/
private final int _code;
/**
* The data returned.
*/
private final byte[] _data;
// Methods
/**
* Returns the HTTP status code.
*
* @return
* the HTTP status code.
*/
public int getStatusCode() {
return _code;
}
/**
* Returns the result data as a byte array. Note that this is not a copy or
* clone of the internal data structure, but it is a link to the actual
* data structure itself.
*
* @return
* a byte array of the result data, never <code>null</code>.
*/
public byte[] getData() {
return _data;
}
}
}
|
package simcity.gui;
import housing.Housing;
import housing.ResidentAgent.State;
import housing.gui.HousingAnimationPanel;
import housing.test.mock.LoggedEvent;
import bank.gui.Bank;
import bank.gui.BankAnimationPanel;
import javax.swing.*;
import market.Market;
import market.gui.MarketAnimationPanel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import restaurant_bayou.gui.BayouAnimationPanel;
import restaurant_bayou.gui.RestaurantBayou;
import restaurant_rancho.gui.RanchoAnimationPanel;
import restaurant_rancho.gui.RestaurantRancho;
import restaurant_rancho.gui.RestaurantRanchoGui;
import restaurant_rancho.gui.RestaurantRancho;
import restaurant_pizza.gui.RestaurantPizza;
import restaurant_pizza.gui.PizzaAnimationPanel;
import restaurant_haus.gui.HausAnimationPanel;
import restaurant_haus.gui.RestaurantHaus;
import simcity.PersonAgent;
import transportation.TransportationPanel;
import restaurant_cafe.gui.CafeAnimationPanel;
import restaurant_cafe.gui.RestaurantCafe;
public class SimCityGui extends JFrame {
public static final int WINDOWX = 800;
public static final int WINDOWY = 600;
String name;
SimCityPanel simCityPanel;
JPanel cards;
public static RestaurantRancho restRancho;
public RanchoAnimationPanel ranchoAniPanel = new RanchoAnimationPanel();
public static RestaurantBayou restBayou;
public BayouAnimationPanel bayouAniPanel = new BayouAnimationPanel();
public static RestaurantPizza restPizza;
public PizzaAnimationPanel pizzaAniPanel = new PizzaAnimationPanel();
public static Housing mainStApts1;
public HousingAnimationPanel housAniPanel1 = new HousingAnimationPanel();
public static Housing mainStApts2;
public HousingAnimationPanel housAniPanel2 = new HousingAnimationPanel();
public static Housing mainStApts3;
public HousingAnimationPanel housAniPanel3 = new HousingAnimationPanel();
public static Housing mainStApts4;
public HousingAnimationPanel housAniPanel4 = new HousingAnimationPanel();
public static Housing mainStApts5;
public HousingAnimationPanel housAniPanel5 = new HousingAnimationPanel();
public static Housing mainStApts6;
public HousingAnimationPanel housAniPanel6 = new HousingAnimationPanel();
public static Housing hauntedMansion;
public HousingAnimationPanel housAniPanel7 = new HousingAnimationPanel();
public static Market mickeysMarket;
public MarketAnimationPanel markAniPanel = new MarketAnimationPanel();
public static Bank pirateBank;
public BankAnimationPanel bankAniPanel = new BankAnimationPanel();
public static RestaurantCafe restCafe;
public CafeAnimationPanel cafeAniPanel = new CafeAnimationPanel();
public static RestaurantHaus restHaus;
public HausAnimationPanel hausAniPanel = new HausAnimationPanel();
TransportationPanel cityAniPanel = new TransportationPanel(this);
private JPanel cityBanner = new JPanel();
private JPanel zoomBanner = new JPanel();
private JPanel cityAnimation = new JPanel();
private JPanel zoomAnimation = new JPanel();
private JPanel cityPanel = new JPanel();
private JPanel zoomPanel = new JPanel();
private JLabel cityLabel = new JLabel("Disney City View ");
private JLabel zoomLabel = new JLabel("Click on a Building to see Animation Inside");
public static ArrayList<JPanel> animationPanelsList = new ArrayList<JPanel>();
public SimCityGui(String name) {
cards = new JPanel(new CardLayout());
cards.add(cafeAniPanel, "Cafe");
cards.add(housAniPanel7, "Mansion");
cards.add(housAniPanel1, "Apt1");
cards.add(housAniPanel2, "Apt2");
cards.add(housAniPanel3, "Apt3");
cards.add(housAniPanel4, "Apt4");
cards.add(housAniPanel5, "Apt5");
cards.add(housAniPanel6, "Apt6");
cards.add(markAniPanel, "Market");
cards.add(bankAniPanel, "Bank");
cards.add(ranchoAniPanel, "Rancho");
cards.add(bayouAniPanel, "Bayou");
cards.add(pizzaAniPanel, "Pizza");
cards.add(cafeAniPanel, "Cafe");
cards.add(hausAniPanel, "Haus");
animationPanelsList.add(cafeAniPanel);
animationPanelsList.add(housAniPanel7);
animationPanelsList.add(housAniPanel1);
animationPanelsList.add(housAniPanel2);
animationPanelsList.add(housAniPanel3);
animationPanelsList.add(housAniPanel4);
animationPanelsList.add(housAniPanel5);
animationPanelsList.add(housAniPanel6);
animationPanelsList.add(markAniPanel);
animationPanelsList.add(bankAniPanel);
animationPanelsList.add(ranchoAniPanel);
animationPanelsList.add(bayouAniPanel);
animationPanelsList.add(pizzaAniPanel);
animationPanelsList.add(cafeAniPanel);
animationPanelsList.add(hausAniPanel);
// Restaurants etc. must be created before simCityPanel is constructed, as demonstrated below
restRancho = new RestaurantRancho(this, "Rancho Del Zocalo");
restBayou = new RestaurantBayou(this, "Blue Bayou");
restPizza = new RestaurantPizza(this, "Pizza Port");
restHaus = new RestaurantHaus(this, "Village Haus");
restCafe = new RestaurantCafe(this, "Carnation Cafe");
hauntedMansion = new Housing(housAniPanel7, "Haunted Mansion");
mainStApts1 = new Housing(housAniPanel1, "Main St Apartments
mainStApts2 = new Housing(housAniPanel2, "Main St Apartments
mainStApts3 = new Housing(housAniPanel3, "Main St Apartments
mainStApts4 = new Housing(housAniPanel4, "Main St Apartments
mainStApts5 = new Housing(housAniPanel5, "Main St Apartments
mainStApts6 = new Housing(housAniPanel6, "Main St Apartments
mickeysMarket = new Market(this, "Mickey's Market");
pirateBank = new Bank(this, "Pirate Bank");
simCityPanel = new SimCityPanel(this);
setLayout(new GridBagLayout());
setBounds(WINDOWX/20, WINDOWX/20, WINDOWX, WINDOWY);
GridBagConstraints c = new GridBagConstraints();
//c.fill = GridBagConstraints.BOTH;
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.BOTH;
c1.weightx = .5;
c1.gridx = 0;
c1.gridy = 0;
c1.gridwidth = 3;
cityBanner.setBorder(BorderFactory.createTitledBorder("City Banner"));
cityBanner.add(cityLabel);
add(cityBanner, c1);
GridBagConstraints c3 = new GridBagConstraints();
c3.fill = GridBagConstraints.BOTH;
c3.weightx = .5;
c3.gridx = 5;
c3.gridy = 0;
c3.gridwidth = 5;
zoomBanner.setBorder(BorderFactory.createTitledBorder("Zoom Banner"));
zoomBanner.add(zoomLabel);
add(zoomBanner, c3);
GridBagConstraints c2 = new GridBagConstraints();
c2.fill = GridBagConstraints.BOTH;
c2.weightx = .5;
c2.weighty = .32;
c2.gridx = 0;
c2.gridy = 1;
c2.gridwidth = 3;
c2.gridheight = 3;
cityAnimation.setLayout(new BoxLayout(cityAnimation, BoxLayout.Y_AXIS));
cityAnimation.add(cityAniPanel);
//cityAnimation.setBorder(BorderFactory.createTitledBorder("City Animation"));
add(cityAnimation, c2);
GridBagConstraints c4 = new GridBagConstraints();
c4.fill = GridBagConstraints.BOTH;
c4.weightx = .5;
c4.weighty=.32;
c4.gridx = 3;
c4.gridy=1;
c4.gridwidth = GridBagConstraints.REMAINDER;
c4.gridheight = 3;
zoomAnimation.setLayout(new BoxLayout(zoomAnimation, BoxLayout.Y_AXIS));
zoomAnimation.add(cards);
// ranchoAniPanel.setVisible(false);
// zoomAnimation.add(housAniPanel);
//zoomAnimation.setBorder(BorderFactory.createTitledBorder("Zoom Animation"));
add(zoomAnimation, c4);
GridBagConstraints c5 = new GridBagConstraints();
c5.fill = GridBagConstraints.BOTH;
c5.weightx= .5;
c5.weighty = .18;
c5.gridx=0;
c5.gridy=5;
c5.gridwidth = 3;
c5.gridheight = 2;
cityPanel.setBorder(BorderFactory.createTitledBorder("City Panel"));
add(cityPanel, c5);
GridBagConstraints c6 = new GridBagConstraints();
c6.fill = GridBagConstraints.BOTH;
c6.weightx= 0;
c6.weighty = .18;
c6.gridx=3;
c6.gridy=5;
c6.gridwidth = GridBagConstraints.REMAINDER;
c6.gridheight =2;
zoomPanel.setBorder(BorderFactory.createTitledBorder("Zoom Panel"));
add(zoomPanel, c6);
}
public static void main(String[] args) {
SimCityGui gui = new SimCityGui("Sim City Disneyland");
gui.setTitle("SimCity Disneyland");
gui.setVisible(true);
gui.setResizable(false);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
restRancho.setMarket(mickeysMarket);
restRancho.addPerson(null, "Cook", "cook", 50);
restRancho.addPerson(null, "Waiter", "w", 50);
restRancho.addPerson(null, "Cashier", "cash", 50);
restRancho.addPerson(null, "Market", "Trader Joes", 50);
restRancho.addPerson(null, "Host", "Host", 50);
restRancho.addPerson(null, "Customer", "Sally", 50);
//restPizza.addPerson(null, "Cook", "cook", 50);
//restPizza.addPerson(null, "Waiter", "w", 50);
//restPizza.addPerson(null, "Cashier", "cash", 50);
//restPizza.addPerson(null, "Host", "Host", 50);
//restPizza.addPerson(null, "Customer", "Sally", 50);
//restBayou.addPerson(null, "Cook", "cook", 50);
//restBayou.addPerson(null, "Waiter", "w", 50);
//restBayou.addPerson(null, "Cashier", "cash", 50);
//restBayou.addPerson(null, "Market", "Trader Joes", 50);
//restBayou.addPerson(null, "Host", "Host", 50);
//restBayou.addPerson(null, "Customer", "Sally", 50);
restHaus.addPerson(null, "Cook", "cook", 50);
restHaus.addPerson(null, "Waiter", "w", 50);
restHaus.addPerson(null, "Cashier", "cash", 50);
restHaus.addPerson(null, "Host", "Host", 50);
//restHaus.addPerson(null, "Customer", "Sally", 50);
mickeysMarket.addPerson(null, "Manager", "MRAWP");
mickeysMarket.addPerson(null, "Cashier", "Kapow");
mickeysMarket.addPerson(null, "Worker", "Bleep");
}
public void showPanel(String panel) {
System.out.println("showing " + panel);
((CardLayout)(cards.getLayout())).show(cards, panel);
}
}
|
package com.cloudbees.breizhcamp.domain;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import com.google.common.base.Objects;
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Talk {
@Id
@GeneratedValue
private long id;
private String title;
@Column(name = "abstract")
@JsonProperty("abstract")
private String abstract_;
private Date start;
private Date end;
private String room;
private Theme theme;
@ManyToMany(mappedBy = "talks")
private final Set<Speaker> speakers = new HashSet<Speaker>();
public long getId() {
return id;
}
public Set<Speaker> getSpeakers() {
return speakers;
}
public String getAbstract() {
return abstract_;
}
public void setAbstract(String abstract_) {
this.abstract_ = abstract_;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o instanceof Talk) {
Talk other=(Talk)o;
return Objects.equal(other.id, id);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("id", id).add("title", title).add("theme", theme).add("room", room).add("start", start).add("end", end).toString();
}
}
|
package co.zpdev.bots.jitters.cmd;
import co.zpdev.bots.jitters.Jitters;
import co.zpdev.bots.jitters.lstnr.JoinLeaveLog;
import co.zpdev.core.discord.command.Command;
import co.zpdev.core.discord.exception.ExceptionHandler;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.PrivateChannel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author ZP4RKER
*/
public class TestCommand {
@Command(
aliases = "test",
autodelete = true
)
public void onCommand(Message message) {
PrivateChannel pc = message.getAuthor().openPrivateChannel().complete();
String intro;
pc.sendMessage("start").complete();
new InputStreamReader(Jitters.class.getResourceAsStream("intros.txt"));
pc.sendMessage("end").complete();
BufferedReader rd = new BufferedReader(new InputStreamReader(Jitters.class.getResourceAsStream("intros.txt")));
pc.sendMessage("end").complete();
String line; List<String> intros = new ArrayList<>();
try {
while ((line = rd.readLine()) != null) {
if (line.startsWith("//")) continue;
intros.add(line);
}
rd.close();
int rand = ThreadLocalRandom.current().nextInt(0, intros.size());
intro = intros.get(rand).replace("%user%", message.getAuthor().getAsMention());
} catch (IOException e) {
ExceptionHandler.handleException("reading file (intros.txt)", e);
intro = null;
}
}
}
|
package org.mwc.cmap.plotViewer.actions;
import java.text.DecimalFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.plotViewer.editors.chart.CoreTracker;
import org.mwc.cmap.plotViewer.editors.chart.SWTCanvas;
import org.mwc.cmap.plotViewer.editors.chart.SWTChart;
import org.mwc.cmap.plotViewer.editors.chart.SWTChart.PlotMouseDragger;
import MWC.Algorithms.Conversions;
import MWC.GUI.Layers;
import MWC.GUI.PlainChart;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldVector;
/**
* @author ian.mayo
*/
final public class RangeBearing extends CoreDragAction
{
/**
* embedded class that handles the range/bearing measurement
*
* @author Ian
*/
final public static class RangeBearingMode extends SWTChart.PlotMouseDragger
{
/**
* the start point, in world coordinates (so we don't have to calculate it
* as often)
*/
WorldLocation _startLocation;
/**
* the start point, in screen coordinates - where we started our drag
*/
Point _startPoint;
/**
* the last rectangle drawn, so we can erase it on the next update
*/
Rectangle _lastRect;
/**
* the canvas we're updating..
*/
SWTCanvas _myCanvas;
@SuppressWarnings("deprecation")
final public void doMouseDrag(final Point pt, final int JITTER, final Layers theLayers,
final SWTCanvas theCanvas)
{
if (_startPoint != null)
{
final GC gc = new GC(_myCanvas.getCanvas());
// This is the same as a !XOR
//gc.setXORMode(true);
//gc.setForeground(gc.getBackground());
// Erase existing rectangle
if (_lastRect != null) {
//plotUpdate(gc);
_myCanvas.getCanvas().redraw();
Display.getCurrent().update();
}
final int dx = pt.x - _startPoint.x;
final int dy = pt.y - _startPoint.y;
// Draw selection rectangle
_lastRect = new Rectangle(_startPoint.x, _startPoint.y, dx, dy);
try
{
// update the range/bearing text
plotUpdate(gc);
}
catch(final Exception e)
{
e.printStackTrace();
}
gc.dispose();
} else
{
// System.out.println("no point.");
}
}
@SuppressWarnings("deprecation")
final public void doMouseUp(final Point point, final int keyState)
{
//final GC gc = new GC(_myCanvas.getCanvas());
// This is the same as a !XOR
//gc.setXORMode(true);
//gc.setForeground(gc.getBackground());
// Erase existing rectangle
if (_lastRect != null)
{
// hmm, we've finished plotting. see if the ctrl button is
// down
if ((keyState & SWT.CTRL) == 0)
try
{
//plotUpdate(gc);
_myCanvas.getCanvas().redraw();
Display.getCurrent().update();
}
catch(final Exception e)
{
e.printStackTrace();
}
//gc.dispose();
}
_startPoint = null;
_lastRect = null;
_myCanvas = null;
_startLocation = null;
}
final public void mouseDown(final Point point, final SWTCanvas canvas,
final PlainChart theChart)
{
_startPoint = point;
_myCanvas = canvas;
_startLocation = new WorldLocation(_myCanvas.getProjection().toWorld(
new java.awt.Point(point.x, point.y)));
}
final private void plotUpdate(final GC dest)
{
final java.awt.Point endPoint = new java.awt.Point(_lastRect.x
+ _lastRect.width, _lastRect.y + _lastRect.height);
// this color leaks
//dest.setForeground(new Color(Display.getDefault(), 111, 111, 111));
Color oldForeground = dest.getForeground();
Color c = dest.getBackground();
int r = c.getRed() ^ 111;
int g = c.getGreen() ^ 111;
int b = c.getBlue() ^ 111;
Color f = new Color(Display.getDefault(), r, g, b);
dest.setForeground(f);
dest.setLineWidth(2);
dest.drawLine(_lastRect.x, _lastRect.y, _lastRect.x + _lastRect.width,
_lastRect.y + _lastRect.height);
// also put in a text-label
final WorldLocation endLocation = _myCanvas.getProjection().toWorld(endPoint);
final WorldVector sep = endLocation.subtract(_startLocation);
final String myUnits = CorePlugin.getToolParent().getProperty(
MWC.GUI.Properties.UnitsPropertyEditor.UNITS_PROPERTY);
final double rng = Conversions.convertRange(sep.getRange(), myUnits);
double brg = sep.getBearing();
brg = brg * 180 / Math.PI;
if (brg < 0)
brg += 360;
final DecimalFormat df = new DecimalFormat("0.00");
final String numComponent = df.format(rng);
final String txt = "[" + numComponent + myUnits + " " + (int) brg + "\u00b0" + "]";
// decide the mid-point
final java.awt.Point loc = new java.awt.Point(
_lastRect.x + _lastRect.width / 2, _lastRect.y + _lastRect.height / 2);
// find out how big the text is
final FontMetrics fm = dest.getFontMetrics();
loc.translate(0, fm.getHeight() / 2);
loc.translate(-txt.length() / 2 * fm.getAverageCharWidth(), 0);
// ok, do the write operation
// this color leaks
//dest.setForeground(new Color(Display.getDefault(), 200, 200, 200));
c = dest.getBackground();
r = c.getRed() ^ 200;
g = c.getGreen() ^ 200;
b = c.getBlue() ^ 200;
Color f2 = new Color(Display.getDefault(), r, g, b);
dest.setForeground(f2);
dest.drawText(txt, loc.x, loc.y, SWT.DRAW_TRANSPARENT);
// also get the RangeTracker to display the range/bearing
CoreTracker.write(txt);
// revert old foregoround color
dest.setForeground(oldForeground);
// dispose created colors
f.dispose();
f2.dispose();
}
}
public PlotMouseDragger getDragMode()
{
return new RangeBearingMode();
}
}
|
package seedu.bulletjournal.logic.parser;
import static seedu.bulletjournal.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.bulletjournal.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.bulletjournal.logic.commands.AddCommand;
import seedu.bulletjournal.logic.commands.ChangeDirectoryCommand;
import seedu.bulletjournal.logic.commands.ClearCommand;
import seedu.bulletjournal.logic.commands.Command;
import seedu.bulletjournal.logic.commands.DeleteCommand;
import seedu.bulletjournal.logic.commands.EditCommand;
import seedu.bulletjournal.logic.commands.ExitCommand;
import seedu.bulletjournal.logic.commands.FindCommand;
import seedu.bulletjournal.logic.commands.HelpCommand;
import seedu.bulletjournal.logic.commands.IncorrectCommand;
import seedu.bulletjournal.logic.commands.ListCommand;
import seedu.bulletjournal.logic.commands.SelectCommand;
import seedu.bulletjournal.logic.commands.ShowCommand;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
/**
* Parses user input into command for execution.
*
* @param userInput
* full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandFromUser = matcher.group("commandWord");
FlexibleCommand flexibleCmd = new FlexibleCommand(commandFromUser);
final String commandWord = flexibleCmd.getCommandWord();
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return new AddCommandParser().parse(arguments);
/*
case AddCommandFloating.COMMAND_WORD:
return new AddCommandParserFloating().parse(arguments);
case AddCommandDeadline.COMMAND_WORD:
return new AddCommandParserDeadline().parse(arguments);
*/
case EditCommand.COMMAND_WORD:
return new EditCommandParser().parse(arguments);
case SelectCommand.COMMAND_WORD:
return new SelectCommandParser().parse(arguments);
case DeleteCommand.COMMAND_WORD:
return new DeleteCommandParser().parse(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case ChangeDirectoryCommand.COMMAND_WORD:
return new ChangeDirectoryCommand(arguments.trim());
case FindCommand.COMMAND_WORD:
return new FindCommandParser().parse(arguments);
case ShowCommand.COMMAND_WORD:
return new ShowCommandParser().parse(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
}
|
package org.xins.util.text;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Pattern;
import org.xins.util.MandatoryArgumentChecker;
/**
* Simple pattern parser.
*
* <h3>Format</h3>
*
* <p>A simple pattern is a text string that may contain letters, digits,
* underscores, hyphens, dots and the wildcard characters <code>'*'</code>
* (asterisk) and <code>'?'</code> (question mark).
*
* <p>The location of an asterisk indicates any number of characters is
* allowed. The location of a question mark indicates exactly one character is
* expected.
*
* <p>To allow matching of simple patterns, a simple pattern is first compiled
* into a Perl 5 regular expression. Every asterisk is converted to
* <code>".*"</code>, while every question mark is converted to
* <code>"."</code>.
*
* <h3>Examples</h3>
*
* <p>Examples of conversions from a simple pattern to a Perl 4 regular
* expression:
*
* <table>
* <tr><th>Simple pattern</th><th>Perl 5 regex equivalent</th></tr>
* <tr><td></td> <td>^$</td> </tr>
* <tr><td>*</td> <td>^.*$</td> </tr>
* <tr><td>?</td> <td>^.$</td> </tr>
* <tr><td>_Get*</td> <td>^_Get.*$</td> </tr>
* <tr><td>_Get*i?n</td> <td>^_Get.*i.n$</td> </tr>
* <tr><td>*on</td> <td>^.*on$</td> </tr>
* </table>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
* @author Peter Troon (<a href="mailto:peter.troon@nl.wanadoo.com">peter.troon@nl.wanadoo.com</a>)
*
* @since XINS 0.152
*/
public class SimplePatternParser extends Object {
// Class fields
/**
* The dot character.
*/
private static final char DOT = '.';
/**
* The asterisk character.
*/
private static final char ASTERISK = '*';
/**
* The question mark character.
*/
private static final char QUESTION_MARK = '?';
/**
* The accent circunflex character.
*/
private static final char CIRCUNFLEX = '^';
/**
* The dollar sign character.
*/
private static final char DOLLAR_SIGN = '$';
/**
* The regular expression that is used to replace all occurrences of an
* asterisk within the pattern by a dot and an asterisk.
*/
private static final String ASTERISK_REGEXP = "\\*";
/**
* The wilcard (dot and asterisk) to which each asterisk that appears
* within the pattern is converted.
*/
private static final String PERL5_ASTERISK_WILDCARD = ".*";
// Class functions
// Constructors
/**
* Creates a new <code>SimplePatternParser</code> object.
*/
public SimplePatternParser() {
// empty
}
// Fields
// Methods
public Perl5Pattern parseSimplePattern(String simplePattern)
throws IllegalArgumentException, ParseException {
MandatoryArgumentChecker.check("simplePattern", simplePattern);
if (isValidPattern(simplePattern) == false) {
throw new ParseException("The pattern '" + simplePattern + "' is invalid.");
}
simplePattern = convertToPerl5RegularExpression(simplePattern);
Perl5Pattern perl5pattern = null;
Perl5Compiler perl5compiler = new Perl5Compiler();
boolean parseError = false;
try {
Pattern pattern = perl5compiler.compile(simplePattern);
if (pattern instanceof Perl5Pattern) {
perl5pattern = (Perl5Pattern) pattern;
} else {
parseError = true;
}
} catch (
MalformedPatternException mpe) {
parseError = true;
}
if (parseError == true) {
throw new ParseException("An error occurred while parsing the pattern '" + simplePattern + "'.");
}
return perl5pattern;
}
/**
* Converts the pattern to a Perl 5 Regular Expression. This means that
* every asterisk is replaced by a dot and an asterisk, every question mark
* is replaced by a dot, an accent circunflex is prepended to the pattern
* and a dollar sign is appended to the pattern.
*
* @param pattern
* the pattern to be converted, may not be <code>null</code>.
*
* @return
* the converted pattern, not <code>null</code>.
*
* @throws NullPointerException
* if <code>pattern == null</code>.
*/
private String convertToPerl5RegularExpression(String pattern)
throws NullPointerException {
pattern = pattern.replaceAll(ASTERISK_REGEXP, PERL5_ASTERISK_WILDCARD);
pattern = pattern.replace(QUESTION_MARK, DOT);
pattern = CIRCUNFLEX + pattern + DOLLAR_SIGN;
return pattern;
}
/**
* Determines whether the provided pattern is valid.
*
* @param pattern
* the pattern to be validated, not <code>null</code>.
*
* @return
* boolean with the value <code>true</code> if the pattern is valid,
* otherwise <code>false</code>.
*
* @throws NullPointerException
* if <code>pattern == null</code>.
*/
private boolean isValidPattern(String pattern)
throws NullPointerException {
char[] patternContents = pattern.toCharArray();
int patternContentsLength = patternContents.length;
boolean valid = true;
for (int i= 0;i < patternContentsLength && valid == true; i++) {
char currChar = patternContents[i];
if (i < patternContentsLength - 1) {
if (currChar == ASTERISK || currChar == QUESTION_MARK || currChar == CIRCUNFLEX || currChar == DOLLAR_SIGN) {
char nextChar = patternContents[i + 1];
if (nextChar == ASTERISK || nextChar == QUESTION_MARK || nextChar == CIRCUNFLEX || nextChar == DOLLAR_SIGN) {
valid = false;
}
}
}
}
return valid;
}
}
|
package com.codeborne.selenide;
import java.util.logging.Logger;
import org.openqa.selenium.remote.DesiredCapabilities;
import static com.codeborne.selenide.Configuration.AssertionMode.STRICT;
import static com.codeborne.selenide.Configuration.FileDownloadMode.HTTPGET;
import static com.codeborne.selenide.Configuration.SelectorMode.CSS;
import static com.codeborne.selenide.WebDriverRunner.FIREFOX;
public class Configuration {
private static final Logger LOG = Logger.getLogger(Configuration.class.getName());
public static String baseUrl = System.getProperty("selenide.baseUrl", "http://localhost:8080");
/**
* Timeout in milliseconds for a collection to get completely loaded
* Conditions will be checked at this point at latest, even if they are still loading
* Can be configured either programmatically or by system property "-Dselenide.collectionsTimeout=10000"
* Default value: 6000 (milliseconds)
*/
public static long collectionsTimeout = Long.parseLong(System.getProperty("selenide.collectionsTimeout", "6000"));
/**
* Timeout in milliseconds to fail the test, if conditions still not met
* Can be configured either programmatically or by system property "-Dselenide.timeout=10000"
* Default value: 4000 (milliseconds)
*/
public static long timeout = Long.parseLong(System.getProperty("selenide.timeout", "4000"));
/**
* Interval in milliseconds, when checking if a single element is appeared
* Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50"
* Default value: 100 (milliseconds)
*/
public static long pollingInterval = Long.parseLong(System.getProperty("selenide.pollingInterval", "100"));
/**
* Interval in milliseconds, when checking if a new collection elements appeared
* Can be configured either programmatically or by system property "-Dselenide.collectionsPollingInterval=150"
* Default value: 200 (milliseconds)
*/
public static long collectionsPollingInterval = Long.parseLong(
System.getProperty("selenide.collectionsPollingInterval", "200"));
/**
* If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging.
* Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true".
* <br>
* Default value: false.
*/
public static boolean holdBrowserOpen = Boolean.getBoolean("selenide.holdBrowserOpen");
/**
* Should Selenide re-spawn browser if it's disappeared (hangs, broken, unexpectedly closed).
* <br>
* Can be configured either programmatically or by system property "-Dselenide.reopenBrowserOnFail=false".
* <br>
* Default value: true
* Set this property to false if you want to disable automatic re-spawning the browser.
*/
public static boolean reopenBrowserOnFail = Boolean.parseBoolean(
System.getProperty("selenide.reopenBrowserOnFail", "true"));
/**
* Timeout (in milliseconds) for closing/killing browser.
* <br>
* Sometimes we have problems with calling driver.close() or driver.quit() method, and test always is suspended too long.
* <br>
* Can be configured either programmatically or by system property "-Dselenide.closeBrowserTimeout=10000"
* Default value: 5000 (milliseconds)
*/
public static long closeBrowserTimeoutMs = Long.parseLong(System.getProperty("selenide.closeBrowserTimeout", "5000"));
/**
* Which browser to use.
* Can be configured either programmatically or by system property "-Dselenide.browser=ie" or "-Dbrowser=ie".
* Supported values: "chrome", "firefox", "legacy_firefox", "ie", "htmlunit", "phantomjs", "opera", "safari", "edge", "jbrowser"
* <br>
* Default value: "firefox"
*/
public static String browser = System.getProperty("selenide.browser", System.getProperty("browser", FIREFOX));
/**
* Which browser version to use (for Internet Explorer).
* Can be configured either programmatically or by system property "-Dselenide.browserVersion=8" or "-Dbrowser.version=8".
* <br>
* Default value: none
*/
public static String browserVersion = System.getProperty("selenide.browserVersion",
System.getProperty("selenide.browser.version", System.getProperty("browser.version")));
public static String remote = System.getProperty("remote");
/**
* The browser window size.
* Can be configured either programmatically or by system property "-Dselenide.browserSize=1024x768".
*
* Default value: none (browser size will not be set explicitly)
*/
public static String browserSize = System.getProperty("selenide.browserSize",
System.getProperty("selenide.browser-size"));
/**
* The browser window position on screen.
* Can be configured either programmatically or by system property "-Dselenide.browserPosition=10x10".
*
* Default value: none (browser window position will not be set explicitly)
*/
public static String browserPosition = System.getProperty("selenide.browserPosition");
/**
* The browser window is maximized when started.
* Can be configured either programmatically or by system property "-Dselenide.startMaximized=true".
* <p>
* Default value: true
*/
public static boolean startMaximized = Boolean.parseBoolean(System.getProperty("selenide.startMaximized",
System.getProperty("selenide.start-maximized", "true")));
/**
* @deprecated this options allowed only a single switch.
* Please use instead more generic -Dchromeoptions.args=<comma-separated list of switches>
* <p>
* or use -Dchromeoptions.prefs=<comma-separated dictionary of key=value>
* <p>
*
* Value of "chrome.switches" parameter (in case of using Chrome driver).
* Can be configured either programmatically or by system property,
* i.e. "-Dselenide.chrome.switches=--disable-popup-blocking".
*
* Default value: none
*/
@Deprecated
public static String chromeSwitches = System.getProperty("selenide.chrome.switches", System.getProperty("chrome.switches"));
/**
* Browser capabilities.
* Warning: this capabilities will override capabilities were set by system properties.
* <br>
* Default value: null
*/
public static DesiredCapabilities browserCapabilities;
public static String pageLoadStrategy = System.getProperty("selenide.pageLoadStrategy",
System.getProperty("selenide.page-load-strategy", "normal"));
/**
* ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature.
* Use clicking via JavaScript instead common element clicking.
* This solution may be helpful for testing in Internet Explorer.
* Can be configured either programmatically or by system property "-Dselenide.clickViaJs=true".
* Default value: false
*/
public static boolean clickViaJs = Boolean.parseBoolean(System.getProperty("selenide.clickViaJs",
System.getProperty("selenide.click-via-js", "false")));
/**
* Defines if Selenide tries to capture JS errors
* Can be configured either programmatically or by system property "-Dselenide.captureJavascriptErrors=false".
*
* Default value: true
*/
public static boolean captureJavascriptErrors = Boolean.parseBoolean(System.getProperty("selenide.captureJavascriptErrors", "true"));
/**
* Defines if Selenide takes screenshots on failing tests.
* Can be configured either programmatically or by system property "-Dselenide.screenshots=false".
*
* Default value: true
*/
public static boolean screenshots = Boolean.parseBoolean(System.getProperty("selenide.screenshots", "true"));
/**
* Defines if Selenide saves page source on failing tests.
* Can be configured either programmatically or by system property "-Dselenide.savePageSource=false".
* Default value: true
*/
public static boolean savePageSource = Boolean.parseBoolean(System.getProperty("selenide.savePageSource", "true"));
/**
* Folder to store screenshots to.
* Can be configured either programmatically or by system property "-Dselenide.reportsFolder=test-result/reports".
*
* Default value: "build/reports/tests" (this is default for Gradle projects)
*/
public static String reportsFolder = System.getProperty("selenide.reportsFolder",
System.getProperty("selenide.reports", "build/reports/tests"));
public static String reportsUrl = getReportsUrl();
static String getReportsUrl() {
String reportsUrl = System.getProperty("selenide.reportsUrl");
if (isEmpty(reportsUrl)) {
reportsUrl = getJenkinsReportsUrl();
if (isEmpty(reportsUrl)) {
LOG.config("Variable selenide.reportsUrl not found");
}
} else {
LOG.config("Using variable selenide.reportsUrl=" + reportsUrl);
}
return reportsUrl;
}
private static boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
private static String getJenkinsReportsUrl() {
String build_url = System.getProperty("BUILD_URL");
if (!isEmpty(build_url)) {
LOG.config("Using Jenkins BUILD_URL: " + build_url);
return build_url + "artifact/";
}
else {
LOG.config("No BUILD_URL variable found. It's not Jenkins.");
return null;
}
}
public static boolean fastSetValue = Boolean.parseBoolean(System.getProperty("selenide.fastSetValue", "false"));
public static boolean versatileSetValue = Boolean.parseBoolean(System.getProperty("selenide.versatileSetValue", "false"));
/**
* If set to true, 'setValue' and 'val' methods of SelenideElement trigger changeEvent after main manipulations.
*
* Firing change event is not natural and could lead to unpredictable results. Browser fires this event automatically
* according to web driver actions. Recommended behaviour is to disable this option.
* Make its true by default for backward compatibility.
*
* Can be configured either programmatically or by system property "-Dselenide.setValueChangeEvent=true".
* Default value: true
*/
public static boolean setValueChangeEvent = Boolean.parseBoolean(System.getProperty("selenide.setValueChangeEvent", "true"));
/**
* Choose how Selenide should retrieve web elements: using default CSS or Sizzle (CSS3)
*/
public static SelectorMode selectorMode = CSS;
public enum SelectorMode {
/**
* Default Selenium behavior
*/
CSS,
/**
* Use Sizzle for CSS selectors.
* It allows powerful CSS3 selectors - ":input", ":not", ":nth", ":first", ":last", ":contains('text')"
*
* For other selectors (XPath, ID etc.) uses default Selenium mechanism.
*/
Sizzle
}
/**
* Assertion modes available
*/
public enum AssertionMode {
/**
* Default mode - tests are failing immediately
*/
STRICT,
/**
* Test are failing only at the end of the methods.
*/
SOFT
}
/**
* Assertion mode - STRICT or SOFT Asserts
* Default value: STRICT
*
* @see AssertionMode
*/
public static AssertionMode assertionMode = STRICT;
public enum FileDownloadMode {
/**
* Download files via direct http request.
* Works only for <a href></a> elements.
* Sends GET request to "href" with all cookies from current browser session.
*/
HTTPGET,
/**
* Download files via selenide embedded proxy server.
* Works for any elements (e.g. form submission).
* Doesn't work if you are using custom webdriver without selenide proxy server.
*/
PROXY
}
/**
* Defines if files are downloaded via direct HTTP or vie selenide emebedded proxy server
* Can be configured either programmatically or by system property "-Dselenide.fileDownload=PROXY"
* Default: HTTPGET
*/
public static FileDownloadMode fileDownload = FileDownloadMode.valueOf(
System.getProperty("selenide.fileDownload", HTTPGET.name()));
/**
* If Selenide should run browser through its own proxy server.
* It allows some additional features which are not possible with plain Selenium.
* But it's not enabled by default because sometimes it would not work (more exactly, if tests and browser and
* executed on different machines, and "test machine" is not accessible from "browser machine"). If it's not your
* case, I recommend to enable proxy.
*
* Default: false
*/
public static boolean proxyEnabled = Boolean.parseBoolean(System.getProperty("selenide.proxyEnabled", "false"));
/**
* Host of Selenide proxy server.
* Used only if proxyEnabled == true.
*
* Default: empty (meaning that Selenide will detect current machine's ip/hostname automatically)
*
* @see net.lightbody.bmp.client.ClientUtil#getConnectableAddress()
*/
public static String proxyHost = System.getProperty("selenide.proxyHost", "");
/**
* Port of Selenide proxy server.
* Used only if proxyEnabled == true.
*
* Default: 0 (meaning that Selenide will choose a random free port on current machine)
*/
public static int proxyPort = Integer.parseInt(System.getProperty("selenide.proxyPort", "0"));
public static boolean driverManagerEnabled = Boolean.parseBoolean(System.getProperty("selenide.driverManagerEnabled", "true"));
/**
* Enables the ability to run the browser in headless mode.
* Works only for Chrome(59+) and Firefox(56+).
*
* Default: false
*/
public static boolean headless = Boolean.parseBoolean(System.getProperty("selenide.headless", "false"));
/**
* Sets the path to browser executable.
* Works only for Chrome, Firefox and Opera.
*/
public static String browserBinary = System.getProperty("selenide.browserBinary", "");
}
|
package com.axelor.script;
import java.lang.reflect.Method;
import java.util.Map;
import com.axelor.common.ClassUtils;
import com.axelor.db.JpaRepository;
import com.axelor.db.JpaScanner;
import com.axelor.db.Model;
import com.axelor.internal.javax.el.BeanELResolver;
import com.axelor.internal.javax.el.ELClass;
import com.axelor.internal.javax.el.ELContext;
import com.axelor.internal.javax.el.ELException;
import com.axelor.internal.javax.el.ELProcessor;
import com.axelor.internal.javax.el.ImportHandler;
import com.axelor.internal.javax.el.MapELResolver;
import com.axelor.internal.javax.el.MethodNotFoundException;
import com.axelor.rpc.Context;
import com.google.common.primitives.Ints;
public class ELScriptHelper extends AbstractScriptHelper {
private ELProcessor processor;
class ClassResolver extends MapELResolver {
private static final String FIELD_CLASS = "class";
public ClassResolver() {
super(true);
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (base instanceof ELClass && FIELD_CLASS.equals(property)) {
context.setPropertyResolved(true);
return ((ELClass) base).getKlass();
}
if (base != null) {
return null;
}
// try resolving model/repository classes
Class<?> cls = JpaScanner.findModel(property.toString());
if (cls == null) {
cls = JpaScanner.findRepository(property.toString());
}
if (cls == null) {
return null;
}
context.setPropertyResolved(true);
return cls;
}
}
class ContextResolver extends MapELResolver {
@Override
public Object getValue(ELContext context, Object base, Object property) {
final ScriptBindings bindings = getBindings();
if (bindings == null || base != null) {
return null;
}
final String name = (String) property;
if (bindings.containsKey(name)) {
context.setPropertyResolved(true);
return bindings.get(name);
}
final ImportHandler handler = context.getImportHandler();
Object value = handler.resolveClass(name);
if (value == null) {
value = handler.resolveStatic(name);
}
context.setPropertyResolved(true);
return value;
}
}
class BeanResolver extends BeanELResolver {
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (base instanceof Map<?, ?> && ((Map<?, ?>) base).containsKey(property)) {
context.setPropertyResolved(true);
return ((Map<?, ?>) base).get(property);
}
return super.getValue(context, base, property);
}
@Override
public Object invoke(ELContext context, final Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (base instanceof Class) {
final Class<?> klass = (Class<?>) base;
try {
final Method staticMethod = klass.getMethod(method.toString(), paramTypes);
context.setPropertyResolved(true);
return staticMethod.invoke(klass, params);
} catch (NoSuchMethodException | SecurityException e) {
throw new MethodNotFoundException(klass.getName() + "." + method.toString());
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new ELException(e);
}
}
return super.invoke(context, base, method, paramTypes, params);
}
}
public static final class Helpers {
private static Class<?> typeClass(Object type) {
if (type instanceof Class<?>) return (Class<?>) type;
if (type instanceof String) return ClassUtils.findClass(type.toString());
if (type instanceof ELClass) return ((ELClass) type).getKlass();
throw new IllegalArgumentException("Invalid type: " + type);
}
public static Object as(Object base, Object type) {
final Class<?> klass = typeClass(type);
if (base instanceof Context) {
return ((Context) base).asType(klass);
}
return klass.cast(base);
}
public static Object is(Object base, Object type) {
final Class<?> klass = typeClass(type);
if (base instanceof Context) {
return klass.isAssignableFrom(((Context) base).getContextClass());
}
return klass.isInstance(base);
}
public static Class<?> importClass(String name) {
return ClassUtils.findClass(name);
}
public static <T extends Model> JpaRepository<T> repo(Class<T> model) {
return JpaRepository.of(model);
}
public static Integer toInt(Object value) {
if (value == null) {
return null;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Long) {
return Ints.checkedCast((Long) value);
}
return Integer.valueOf(value.toString());
}
public static String text(Object value) {
if (value == null) return "";
return value.toString();
}
public static String formatText(String format, Object... args) {
if (args == null) {
return String.format(format, args);
}
return String.format(format, args);
}
}
public ELScriptHelper(ScriptBindings bindings) {
this.processor = new ELProcessor();
this.processor.getELManager().addELResolver(new ClassResolver());
this.processor.getELManager().addELResolver(new ContextResolver());
this.processor.getELManager().addELResolver(new BeanResolver());
final String className = Helpers.class.getName();
try {
this.processor.defineFunction("", "as", className, "as");
this.processor.defineFunction("", "is", className, "is");
this.processor.defineFunction("", "int", className, "toInt");
this.processor.defineFunction("", "str", className, "text");
this.processor.defineFunction("", "imp", className, "importClass");
this.processor.defineFunction("", "T", className, "importClass");
this.processor.defineFunction("", "__repo__", className, "repo");
this.processor.defineFunction("fmt", "text", className, "formatText");
} catch (Exception e) {
}
final String[] packages = {
"java.util",
"org.joda.time",
"com.axelor.common",
"com.axelor.script.util",
"com.axelor.apps.tool"
};
for (String pkg : packages) {
try {
this.processor.getELManager().importPackage(pkg);
} catch (Exception e) {
}
}
this.processor.getELManager().importClass("com.axelor.db.Model");
this.processor.getELManager().importClass("com.axelor.db.Query");
this.processor.getELManager().importClass("com.axelor.db.Repository");
this.setBindings(bindings);
}
public ELScriptHelper(Context context) {
this(new ScriptBindings(context));
}
@Override
public Object eval(String expr) {
return processor.eval(expr);
}
@Override
protected Object doCall(Object obj, String methodCall) {
ScriptBindings bindings = new ScriptBindings(getBindings());
ELScriptHelper sh = new ELScriptHelper(bindings);
bindings.put("__obj__", obj);
return sh.eval("__obj__." + methodCall);
}
}
|
package seedu.taskell.logic.commands;
import java.util.HashSet;
import java.util.Set;
import seedu.taskell.commons.exceptions.IllegalValueException;
import seedu.taskell.model.tag.Tag;
import seedu.taskell.model.tag.UniqueTagList;
import seedu.taskell.model.task.*;
/**
* Adds a task to the task manager.
*/
public class AddCommand extends Command {
public static final String COMMAND_WORD = "add";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to the task manager. "
+ "Parameters: DESCRIPTION by/on[DATE] from[START_TIME] to[END_TIME] [p/PRIORITY] [#TAG]...\n"
+ "Example: " + COMMAND_WORD
+ " go for meeting on 1-1-2100 from 12.30AM to 12.45AM p/3 #work";
public static final String MESSAGE_SUCCESS = "New task added: %1$s";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager";
private final Task toAdd;
public AddCommand(String description, String taskType, String startDate, String endDate, String startTime, String endTime, String taskPriority, Set<String> tags)
throws IllegalValueException {
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
switch (taskType) {
case Task.FLOATING_TASK:
this.toAdd = new FloatingTask(description, taskPriority, new UniqueTagList(tagSet));
break;
case Task.EVENT_TASK:
this.toAdd = new EventTask(description, startDate, endDate, startTime, endTime, taskPriority, new UniqueTagList(tagSet));
break;
default:
toAdd = null;
}
}
@Override
public CommandResult execute() {
assert model != null;
try {
model.addTask(toAdd);
UndoCommand.addTaskToCommandHistory(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
} catch (UniqueTaskList.DuplicateTaskException e) {
return new CommandResult(MESSAGE_DUPLICATE_TASK);
}
}
}
|
package com.puppetlabs.puppetserver.pool;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public interface LockablePool<E> {
/**
* Introduce a new instance to the pool in a way that allows us to keep track
* of the list of all existing instances, even if some of them are
* borrowed.
*/
void register(E e) throws InterruptedException;
/**
* Borrow an instance. This and <tt>borrowItemWithTimeout</tt> are the
* only entry points for accessing instances.
*/
E borrowItem() throws InterruptedException;
/**
* Borrow an instance, waiting up to the specified timeout if necessary
* for an instance to become available. Returns `null` if the wait time
* elapses before an instance is available.
*
* This and <tt>borrowItemWithTimeout</tt> are the only entry points for
* accessing instances.
*/
E borrowItemWithTimeout(long timout, TimeUnit unit) throws InterruptedException;
/**
* Return an instance to the pool.
*/
void returnItem(E e) throws InterruptedException;
/**
* Insert a poison pill to the pool. This is different from returning an
* instance to the pool because there are different locking semantics
* around inserting a pill.
*/
void insertPill(E e) throws InterruptedException;
/**
* Clear the pool.
*/
void clear();
/**
* Returns the number of additional items that the pool can accept without
* blocking. Equal to the initial capacity of the pool minus the current
* <tt>size</tt> of the pool.
*/
int remainingCapacity();
/**
* Returns the number of elements in the pool.
*/
int size();
/**
* Lock the pool. This method should make the following guarantees:
*
* a) blocks until all registered instances are returned to the pool
* b) once this method is called (even before it returns), any new threads
* that attempt a <tt>borrow</tt> should block until <tt>unlock()</tt>
* is called
* c) if there are other threads that were already blocking in a
* <tt>borrow</tt> before this method was called, they should continue
* to block until <tt>unlock()</tt> is called
* d) instances may be returned by other threads while this method is
* being executied
* e) when the method returns, the caller holds an exclusive lock on the
* pool; the lock should be re-entrant in the sense that this thread
* should still be able to perform borrows while it's holding the lock
*/
void lock() throws InterruptedException;
/**
* Release the exclusive lock so that other threads may begin to perform
* borrow operations again.
*/
void unlock() throws InterruptedException;
/**
* Returns a set of all of the known elements that have been registered with
* this pool, regardless of whether they are
* currently available in the pool or not.
*/
Set<E> getRegisteredElements();
}
|
package com.areen.jlib.gui.fcb;
import com.areen.jlib.gui.ColorArrowUI;
import com.areen.jlib.util.Sise;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
public class ComboBoxFilter extends PlainDocument {
private JComboBox comboBox;
private JTextComponent comboBoxEditor;
private FilteredComboBoxModel comboBoxModel;
/**
* Every call to setSelectedItem() in the combo-box will provoke another
* call to the insertString, with the newly selected item. We prevent this
* by seting "selecting" to true before we call setPattern(). Subsequent
* calls to remove/insertString should be ignored.
*/
boolean selecting = false;
boolean hidePopupOnFocusLoss;
private boolean arrowKeyPressed = false;
private boolean keyPressed = false;
private boolean finish = false;
private boolean inPreparation;
private int selectedIndex;
private Object pickedItem;
private Object pickedKey;
/**
* This value is set by cell-editors to inform ComboBoxFilter whether to
* execute pick value or not during the preparation phase (prepare()
* method).
*/
private boolean triggeredByKeyPress = false;
private int previousItemCount;
/**
* We have to store the popup menu's dimension so we can fix incorrect popup
* size during the filtering process.
*/
private int popupMenuWidth;
private int popupMenuHeight;
static final Logger LOGGER = Logger.getLogger(ComboBoxFilter.class.getCanonicalName());
/**
* This constructor adds filtering capability to the given JComboBox object
* argComboBox. It will also assign appropriate model to the combo-box, one
* that has setPattern() method. It will also set the argComboBox to be
* editable.
*
* @param argComboBox
* @param argComboBoxModel
*/
public ComboBoxFilter(final JComboBox argComboBox, FilteredComboBoxModel argComboBoxModel) {
comboBox = argComboBox;
comboBox.setEditable(true);
fixComboBoxArrowUI();
comboBoxModel = argComboBoxModel;
comboBox.setModel(comboBoxModel);
// If initially an item is selected, we will assume that item is a picked item.
comboBox.putClientProperty("item-picked", Boolean.TRUE);
/*
if (comboBox.getSelectedItem() == null) {
comboBox.putClientProperty("item-picked", Boolean.TRUE);
} else {
comboBox.putClientProperty("item-picked", Boolean.TRUE);
}
*
*/
comboBoxEditor = (JTextComponent) comboBox.getEditor().getEditorComponent();
comboBoxEditor.setDocument(this);
// let's add a key listener to the editor
comboBoxEditor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
LOGGER.info("keyPressed()");
int keyCode = e.getKeyCode();
System.out.println(keyCode);
/*
* In the case user presses SHIFT, CTRL, ALT keys, or <ANY>+TAB,
* we return imediately.
*/
//int modifiers = e.getModifiersEx();
if (keyCode == KeyEvent.VK_SHIFT
|| (keyCode == KeyEvent.VK_ALT)
|| (keyCode == KeyEvent.VK_CONTROL)
|| (keyCode == KeyEvent.VK_WINDOWS)
|| (keyCode == KeyEvent.VK_CONTEXT_MENU)
|| (keyCode == KeyEvent.VK_TAB && e.isShiftDown())) {
keyPressed = false;
return;
}
keyPressed = true;
boolean isTableCellEditor = false;
Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor");
if (tmp != null) {
isTableCellEditor = tmp.equals(Boolean.TRUE);
}
if (comboBox.isDisplayable()) {
comboBox.setPopupVisible(true);
}
arrowKeyPressed = false;
finish = false;
int currentIndex = comboBox.getSelectedIndex();
switch (keyCode) {
case KeyEvent.VK_TAB:
LOGGER.info("TAB!");
finish = true;
comboBoxModel.setReadyToFinish(false);
if (!isTableCellEditor()) {
String txt = updateFcbEditor();
}
if ((comboBox.getSelectedItem() == null)) {
/*
* if TAB is pressed, but nothing is selected, and
* the picked item is not null * that means the user
* pressed tab when there was an empty list of
* items. * (Typically when user typed something
* that does not exist in the list of * items). In
* this case we cancel the editing.
*/
comboBoxModel.setCancelled(true);
}
if (comboBox.getSelectedItem() != null) {
if (pickedItem == comboBox.getSelectedItem()) {
/*
* We cancel the editing when the picked item is
* the same as the item that * is currently
* selected in the combo-box, because we do not
* want to * trigger database change (there is
* no need to update to the same value).
*/
comboBoxModel.setCancelled(true);
} else {
pickedItem = comboBox.getSelectedItem();
pickedKey = comboBoxModel.getKeyOfTheSelectedItem().toString();
} // else
}
break;
case KeyEvent.VK_ESCAPE:
if (isTableCellEditor()) {
comboBoxModel.setCancelled(true);
comboBox.setSelectedItem(pickedItem);
} else {
ComboBoxFilter.this.setText(pickedKey.toString());
}
break;
case KeyEvent.VK_ENTER:
finish = true;
comboBoxModel.setReadyToFinish(false); // we expect cell editor
String txt = updateFcbEditor();
if ((txt == null) && !comboBoxModel.isAnyPatternAllowed()) {
// if user types a string that has no match, we select the last picked item.
comboBox.setSelectedItem(pickedItem);
// After all events are processed, alert the user
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String eol = System.getProperty("line.separator");
JOptionPane.showMessageDialog(comboBox,
"Invalid option.");
} // run() method
}); // Runnable (anonymous) implementation
} else {
pickedItem = comboBox.getSelectedItem();
pickedKey = txt;
comboBoxModel.setPickedItem(pickedItem);
} // else
break;
case KeyEvent.VK_UP:
arrowKeyPressed = true;
if (isTableCellEditor) {
/*
* For some reason, the JTable is stealing keyboard
* events and preventing us * from moving up/down,
* so we have to select proper values manually. * *
* If selection did not move, we will manually
* select appropriate item.
*/
if ((selectedIndex == currentIndex) && (currentIndex > 0)) {
comboBox.setSelectedIndex(currentIndex - 1);
selectedIndex = currentIndex - 1;
} else {
selectedIndex = currentIndex;
}
// we set this to false ONLY if the combo box is a cell editor!
arrowKeyPressed = false;
}
break;
case KeyEvent.VK_DOWN:
arrowKeyPressed = true;
if (isTableCellEditor && comboBox.isPopupVisible()) {
/*
* For some reason, the JTable is stealing keyboard
* events and preventing us * from moving up/down,
* so we have to select proper values manually. * *
* If selection did not move, we will manually
* select appropriate item.
*/
if ((selectedIndex == currentIndex)
&& (currentIndex < comboBox.getItemCount() - 1)) {
comboBox.setSelectedIndex(currentIndex + 1);
selectedIndex = currentIndex + 1;
} else {
selectedIndex = currentIndex;
} // else
// we set this to false ONLY if the combo box is a cell editor!
arrowKeyPressed = false;
}
break;
default:
selectedIndex = currentIndex;
} // switch
keyPressed = false;
} // keyPressed() method
});
// Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
// Highlight whole text when focus gets lost
comboBoxEditor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
boolean pa = comboBoxModel.isAnyPatternAllowed();
boolean ma = comboBoxModel.isMultiSelectionAllowed();
LOGGER.info("focusLost()");
if (pickedKey != null && !(pa || ma)) {
// When combo-box loses focus, we need to set the text to the selected
setText(pickedKey.toString());
}
// Workaround for Bug 5100422 - Hide Popup on focus loss
if (hidePopupOnFocusLoss) {
ComboBoxFilter.this.comboBox.setPopupVisible(false);
}
comboBoxModel.setReadyToFinish(false);
}
@Override
public void focusGained(FocusEvent fe) {
if (!isTableCellEditor()) {
super.focusGained(fe);
comboBoxEditor.selectAll();
}
} // focusGained() method
});
/*
* The following PopupMenuListener is needed to store the inidial
* Dimension of the combobox popup.
*/
comboBox.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
/*
* NOTE: Dimension returned by getSize() method is actually the
* dimension of the combo-box popup menu! It is not the size of
* the JTextComponent object! :)
*/
JComboBox box = (JComboBox) pme.getSource();
popupMenuWidth = box.getSize().width;
popupMenuHeight = box.getSize().height;
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
LOGGER.info("hiding popup...");
comboBox.putClientProperty("item-picked", Boolean.FALSE);
}
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
// do nothing
}
});
if (!isTableCellEditor()) {
comboBoxEditor.setFocusTraversalKeysEnabled(false);
Action myAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Nothing is needed here - all we want is to skip focusLost() call when user presses TAB
comboBoxEditor.transferFocus();
} // actionPerformed() method
};
comboBoxEditor.getActionMap().put("tab-action", myAction);
comboBoxEditor.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("TAB"), "tab-action");
}
Object selected = comboBox.getSelectedItem();
pickedItem = selected;
Object tmp = comboBoxModel.getKeyOfTheSelectedItem();
if (tmp instanceof String) {
pickedKey = tmp.toString();
} else {
pickedKey = tmp;
} // else
selectedIndex = comboBox.getSelectedIndex();
if (selected != null) {
setText(comboBoxModel.getKeyOfTheSelectedItem().toString());
}
}
/**
* User typically will call this method from a table cell editor when we
* want to "inform" filtered combo-box that we want to re-filter before we
* actually start editing. The reason for this is when user goes to another
* cell, the filtered set of entries from the previous cell will not apply.
*
* @param argPattern
*/
public void prepare(Object argPattern) {
LOGGER.info("prepare(" + argPattern + ")");
if (argPattern == null) {
// If the previous value is null, we simply exit this method.
pickedItem = null;
pickedKey = null;
comboBox.setSelectedItem(null);
return;
}
inPreparation = true;
selecting = true;
comboBoxModel.setCancelled(false);
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(false);
}
String pat = (String) argPattern.toString();
/*
* If the editing is triggered by a key-press in a JTable, then the
* argPattern contains a string in SISE format, so we have to extract
* they key pressed and the previous value.
*/
String key = "";
if (isTriggeredByKeyPress()) {
String[] strs = Sise.units(pat);
/*
* In the case the cell's value was a NULL, then strs will have only
* one element. In that case we set pat to be a null, and do not set
* the pickedItem.
*/
if (strs.length == 2) {
pat = strs[1];
} else {
pat = null;
} // else
key = strs[0];
}
try {
if (argPattern == null) {
setText("");
} else {
if (pat != null) {
setText(pat.trim());
}
} // else
if (pat == null) {
pickedItem = null;
pickedKey = null;
} else {
// Cell's value was not a null, so we can execute filter so the combo-box updates the
// selected item to be what was previously selected.
filterTheModel();
pickedItem = comboBox.getSelectedItem();
pickedKey = comboBoxModel.getKeyOfTheSelectedItem();
} // else
// Finally, when we have selected the item that was previously selected, now we can insert
// the character user typed inside a JTable
if (isTriggeredByKeyPress()) {
setText(key);
filterTheModel();
}
} catch (BadLocationException ex) {
Logger.getLogger(ComboBoxFilter.class.getName()).log(Level.SEVERE, null, ex);
}
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(false);
}
inPreparation = false;
LOGGER.info("prepare done.");
} // prepare() method
private void clearTextSelection() {
if (comboBoxEditor.getSelectedText() != null) {
// we have a selected text, removing the selection. On Windows text may become selected by default
LOGGER.info("SELECTED TEXT: " + comboBoxEditor.getSelectedText());
int pos = comboBoxEditor.getCaretPosition();
comboBoxEditor.select(0, 0);
// return caret position to the original place
comboBoxEditor.setCaretPosition(pos);
}
}
private void setText(String text) {
try {
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, text, null);
} catch (BadLocationException e) {
throw new RuntimeException(e.toString());
}
}
/**
* This method is a leftover from the previous version of the
* ComboBoxFilter. Should be removed after the testing phase.
*/
private void highlightCompletedText(int start) {
comboBoxEditor.setCaretPosition(getLength());
comboBoxEditor.moveCaretPosition(start);
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
LOGGER.info("insertString(" + offs + ", " + str + ")");
//LOGGER.info("insertString(" + selecting + ", " + arrowKeyPressed + ")");
// return immediately when selecting an item
if (selecting) {
return;
}
if (arrowKeyPressed) {
arrowKeyPressed = false;
comboBox.putClientProperty("item-picked", Boolean.FALSE);
return;
}
boolean itemPicked = false; // we need this value because item-picked may change due to chain
// of events
// inform action-performed listeners that the item has been picked so they may update
// some other components
if (keyPressed) {
itemPicked = false;
} else {
itemPicked = true;
}
boolean isPicked = (Boolean) comboBox.getClientProperty("item-picked");
comboBox.putClientProperty("item-picked", itemPicked || isPicked);
// insert the string into the document
if (str.contains(Sise.UNIT_SEPARATOR_STRING)) {
LOGGER.info("%%%%%%%%%%%%%");
System.out.println(str);
// we got a string in the Sise format, that must be because user picked an item with a mouse
// in that case, we will take the key component (SISE unit) and put that instead.
String[] strs = Sise.units(str);
int idx = comboBoxModel.getKeyIndex();
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(true);
}
// This is an ArrayOutOfBounds exception "fix". When user presses SPACE + ENTER sometimes we get
// an error, because strs is an empty array!
if (strs.length > 0) {
super.insertString(offs, strs[idx], a);
} else {
super.insertString(offs, "", a);
}
// We have to filter after the user selects an item with the mouse.
// WARNING: here we rely on the FilteredComboBoxModel's setPattern() method to select the
// exact match - ie the item that user picked with the mouse.
filterTheModel();
if (itemPicked) {
pickedItem = comboBox.getSelectedItem();
Object tmp = comboBoxModel.getKeyOfTheSelectedItem();
if (tmp instanceof String) {
pickedKey = tmp.toString();
} else {
pickedKey = tmp;
} // else
}
comboBox.putClientProperty("item-picked", Boolean.TRUE);
return;
} else {
// otherwise, insert the whole string
super.insertString(offs, str, a);
} // else
if (finish) {
return;
}
filterTheModel();
} // insertString() method
@Override
public void remove(int offs, int len) throws BadLocationException {
LOGGER.info("remove(" + offs + ", " + len + ")");
LOGGER.info("remove(" + selecting + ", " + arrowKeyPressed + ")");
// return immediately when selecting an item
if (selecting) {
// remove() is called whenever setSelectedItem() or setSelectedIndex() are called. They may be
// called during the filtering process, so we do not want to remove while in the middle.
return;
}
if (arrowKeyPressed) {
if (isTableCellEditor()) {
// if the remove() has been called while user navigates through the combobox list, we do not
// filter. when user navigates via arrow keys, remove() is always called first, followed by
// the insertString. However, sometimes table steals the event, and causes trouble.
// As remove() is called first, here we check if correct value has been selected after user
// presses UP/DOWN
int currentIndex = comboBox.getSelectedIndex();
if (selectedIndex != currentIndex) {
// they are not equal, fix it
comboBox.setSelectedIndex(selectedIndex);
}
}
return;
}
// remove the string from the document
super.remove(offs, len);
if (finish) {
// user pressed ENTER so in the case remove is called we do not filter the model.
return;
}
// finally, do the filter
filterTheModel();
} // remove() method
/**
* Use this method when you need to programmatically pick an item.
* @param argItem
*/
public void pickItem(Object argItem) {
Object obj = comboBoxModel.getKeyOfAnItem(argItem);
if ((argItem == null) && (obj == null)) {
return;
}
pickedItem = argItem;
pickedKey = obj.toString();
} // pickItem() method
/**
* This method calls the setPatter() method, and starts the filtering.
*
* It also sets the previousItemCount variable to hold the previous number
* of filtered items.
*/
private void filterTheModel() throws BadLocationException {
// we have to "guard" the call to comboBoxModel.setPattern() with selecting set to true, then false
selecting = true;
boolean oldValue = comboBoxModel.isReadyToFinish();
comboBoxModel.setReadyToFinish(false); // we must set this to false during the filtering
previousItemCount = comboBox.getItemCount(); /// store the number of items before filtering
String pattern = getText(0, getLength());
//LOGGER.info("filterTheModel(): " + pattern);
comboBoxModel.setPattern(pattern);
clearTextSelection();
fixPopupSize();
comboBoxModel.setReadyToFinish(oldValue); // restore the value
selecting = false;
selectedIndex = comboBox.getSelectedIndex();
//LOGGER.info("SELECTED AFTER:" + comboBox.getSelectedItem());
}
/**
* Use this method whenever you need to determine if the comboBox is used as
* a cell editor or not.
*
* @return boolean Value indicating whether comboBox is a cell editor (TRUE)
* or not (FALSE).
*/
private boolean isTableCellEditor() {
boolean isTableCellEditor = false;
Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor");
if (tmp != null) {
isTableCellEditor = tmp.equals(Boolean.TRUE);
}
return isTableCellEditor;
} // isTableCellEditor method
/**
* This method is used internally to fix the popup-menu size. Apparently
* JComboBox has a bug and does not calculate the proper height of the
* popup.
*
* The first time popup menu is shown, ComboBoxFilter stores the dimension,
* and re-adjusts the width to the original value all the time. Reason for
* this is that we do not want to have different widths while user types
* something.
*/
private void fixPopupSize() {
if (inPreparation) {
return;
}
LOGGER.info("fixPopupSize()");
int maxRows = comboBox.getMaximumRowCount();
if ((previousItemCount < maxRows) || (comboBox.getItemCount() < maxRows)) {
// do this only when we have less than maxRows items, to prevent the flickering.
// this is a hack and is actually the easiest solution to the JComboBox's popup resizing problem.
if (comboBox.isPopupVisible()) {
comboBox.setPopupVisible(false);
comboBox.setPopupVisible(true);
}
}
} // fixPopupSize() method
/**
* If the l&f is system, and OS is Windows, we have to fix the arrow UI of
* the combo box, when editing is enabled. This method is responsible for
* doing that.
*/
private void fixComboBoxArrowUI() {
String scn = UIManager.getSystemLookAndFeelClassName();
if (System.getProperty("os.name").startsWith("Windows")
&& UIManager.getLookAndFeel().getClass().getCanonicalName().equals(scn)) {
System.err.println("DEBUG: fixing the combo-box's arrow");
comboBox.setUI(ColorArrowUI.createUI(comboBox));
}
} // fixComboBoxArrowUI() method
private String updateFcbEditor() {
Object obj = comboBoxModel.getKeyOfTheSelectedItem();
String txt = null;
if (obj != null) {
txt = obj.toString();
}
System.out.println("))))))))))))) " + txt);
if (txt != null) {
if (!comboBoxModel.isAnyPatternAllowed() || !comboBoxModel.isMultiSelectionAllowed()) {
/* In the case when *any* pattern is allowed, or all we want is to get a *
* listof items that match, then we do not update the comboBox editor *
* component with the newly selected item's key. */
if (!isTableCellEditor()) {
setText(txt);
}
}
}
return txt;
} // updateFcbEditor() method
public boolean isTriggeredByKeyPress() {
return triggeredByKeyPress;
}
public void setTriggeredByKeyPress(boolean argTriggeredByKeyPress) {
triggeredByKeyPress = argTriggeredByKeyPress;
}
public Object getPickedItem() {
return pickedItem;
}
public Object getPickedKey() {
return pickedKey;
}
} // ComboBoxFilter class
|
// $Id: ChatProvider.java,v 1.29 2004/06/17 18:28:58 ray Exp $
package com.threerings.crowd.chat.server;
import java.util.Iterator;
import com.samskivert.util.StringUtil;
import com.threerings.util.MessageBundle;
import com.threerings.util.Name;
import com.threerings.util.TimeUtil;
import com.threerings.presents.client.InvocationService.InvocationListener;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.server.InvocationException;
import com.threerings.presents.server.InvocationManager;
import com.threerings.presents.server.InvocationProvider;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.OccupantInfo;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.server.AccessControl;
import com.threerings.crowd.server.CrowdServer;
import com.threerings.crowd.chat.client.ChatService.TellListener;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.UserMessage;
/**
* The chat provider handles the server side of the chat-related
* invocation services.
*/
public class ChatProvider
implements ChatCodes, InvocationProvider
{
/** The access control identifier for broadcast chat privileges. */
public static final String BROADCAST_TOKEN = "crowd.chat.broadcast";
/** Interface to allow an auto response to a tell message. */
public static interface TellAutoResponder
{
/**
* Called following the delivery of <code>message</code> from
* <code>teller</code> to <code>tellee</code>.
*/
public void sentTell (BodyObject teller, BodyObject tellee,
String message);
}
/**
* Set the auto tell responder for the chat provider. Only one auto
* responder is allowed.
*/
public static void setTellAutoResponder (TellAutoResponder autoRespond)
{
_autoRespond = autoRespond;
}
/**
* Set the authorizer we will use to see if the user is allowed to
* perform various chatting actions.
*/
public static void setCommunicationAuthorizer (
CommunicationAuthorizer comAuth)
{
_comAuth = comAuth;
}
/**
* Initializes the chat services and registers a chat provider with
* the invocation manager.
*/
public static void init (InvocationManager invmgr, DObjectManager omgr)
{
_omgr = omgr;
// register a chat provider with the invocation manager
invmgr.registerDispatcher(new ChatDispatcher(
new ChatProvider()), true);
}
/**
* Processes a request from a client to deliver a tell message to
* another client.
*/
public void tell (ClientObject caller, Name target, String message,
TellListener listener)
throws InvocationException
{
// make sure the caller is authorized to perform this action
if ((_comAuth != null) && (!_comAuth.authorized(caller))) {
return;
}
// make sure the target user is online
BodyObject tobj = CrowdServer.lookupBody(target);
if (tobj == null) {
throw new InvocationException(USER_NOT_ONLINE);
}
if (tobj.status == OccupantInfo.DISCONNECTED) {
throw new InvocationException(MessageBundle.compose(
USER_DISCONNECTED, TimeUtil.getTimeOrderString(
System.currentTimeMillis() - tobj.statusTime,
TimeUtil.SECOND)));
}
// deliver a tell notification to the target player
BodyObject source = (BodyObject)caller;
sendTellMessage(tobj, source.username, null, message);
// let the teller know it went ok
long idle = 0L;
if (tobj.status == OccupantInfo.IDLE) {
idle = System.currentTimeMillis() - tobj.statusTime;
}
String awayMessage = null;
if (!StringUtil.blank(tobj.awayMessage)) {
awayMessage = tobj.awayMessage;
}
listener.tellSucceeded(idle, awayMessage);
// do the autoresponse if needed
if (_autoRespond != null) {
_autoRespond.sentTell(source, tobj, message);
}
}
/**
* Processes a {@link ClientService#broadcast} request.
*/
public void broadcast (ClientObject caller, String message,
InvocationListener listener)
throws InvocationException
{
BodyObject body = (BodyObject)caller;
// make sure the requesting user has broadcast privileges
if (!CrowdServer.actrl.checkAccess(body, BROADCAST_TOKEN)) {
throw new InvocationException(AccessControl.LACK_ACCESS);
}
broadcast(body.username, null, message, false);
}
/**
* Broadcast the specified message to all places in the game.
*
* @param from the user the broadcast is from, or null to send the message
* as a system message.
* @param bundle the bundle, or null if the message needs no translation.
* @param msg the content of the message to broadcast.
* @param attention if true, the message is sent as ATTENTION level,
* otherwise as INFO. Ignored if from is non-null.
*/
public static void broadcast (Name from, String bundle, String msg,
boolean attention)
{
Iterator iter = CrowdServer.plreg.enumeratePlaces();
while (iter.hasNext()) {
PlaceObject plobj = (PlaceObject)iter.next();
if (plobj.shouldBroadcast()) {
if (from == null) {
if (attention) {
SpeakProvider.sendAttention(plobj, bundle, msg);
} else {
SpeakProvider.sendInfo(plobj, bundle, msg);
}
} else {
SpeakProvider.sendSpeak(plobj, from, bundle, msg,
BROADCAST_MODE);
}
}
}
}
/**
* Processes a {@link ClientService#away} request.
*/
public void away (ClientObject caller, String message)
{
BodyObject body = (BodyObject)caller;
// we modify this field via an invocation service request because
// a body object is not modifiable by the client
body.setAwayMessage(message);
}
/**
* Delivers a tell notification to the specified target player,
* originating with the specified speaker.
*
* @param target the body object of the user that will receive the
* tell message.
* @param speaker the username of the user that generated the message
* (or some special speaker name for server messages).
* @param bundle the bundle identifier that will be used by the client
* to translate the message text (this would be null in all cases
* except where the message originated from some server entity that
* was "faking" a tell to a real player).
* @param message the text of the chat message.
*/
public static void sendTellMessage (
BodyObject target, Name speaker, String bundle, String message)
{
UserMessage msg =
new UserMessage(message, bundle, speaker, DEFAULT_MODE);
SpeakProvider.sendMessage(target, msg);
// note that the teller "heard" what they said
SpeakProvider.noteMessage(speaker, msg);
}
/** The distributed object manager used by the chat services. */
protected static DObjectManager _omgr;
/** Reference to our auto responder object. */
protected static TellAutoResponder _autoRespond;
/** The entity that will authorize our chatters. */
protected static CommunicationAuthorizer _comAuth;
}
|
package com.google.rolecall.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final Environment env;
@Override
public void addCorsMappings(CorsRegistry registry) {
|
package com.couchbase.lite.replicator;
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.BlobStore;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.support.RemoteRequestCompletionBlock;
import com.couchbase.lite.support.HttpClientFactory;
import com.couchbase.lite.util.Log;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
/**
* @exclude
*/
@InterfaceAudience.Private
public class Pusher extends Replication implements Database.ChangeListener {
private boolean shouldCreateTarget;
private boolean observing;
private ReplicationFilter filter;
/**
* Constructor
*/
@InterfaceAudience.Private
/* package */ public Pusher(Database db, URL remote, boolean continuous, ScheduledExecutorService workExecutor) {
this(db, remote, continuous, null, workExecutor);
}
/**
* Constructor
*/
@InterfaceAudience.Private
/* package */ public Pusher(Database db, URL remote, boolean continuous, HttpClientFactory clientFactory, ScheduledExecutorService workExecutor) {
super(db, remote, continuous, clientFactory, workExecutor);
shouldCreateTarget = false;
observing = false;
}
@Override
@InterfaceAudience.Public
public boolean isPull() {
return false;
}
@Override
@InterfaceAudience.Public
public boolean shouldCreateTarget() {
return shouldCreateTarget;
}
@Override
@InterfaceAudience.Public
public void setCreateTarget(boolean createTarget) {
this.shouldCreateTarget = createTarget;
}
@Override
@InterfaceAudience.Public
public void stop() {
stopObserving();
super.stop();
}
@Override
@InterfaceAudience.Private
void maybeCreateRemoteDB() {
if(!shouldCreateTarget) {
return;
}
Log.v(Database.TAG, "Remote db might not exist; creating it...");
sendAsyncRequest("PUT", "", null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
if(e != null && e instanceof HttpResponseException && ((HttpResponseException)e).getStatusCode() != 412) {
Log.v(Database.TAG, "Unable to create remote db (normal if using sync gateway)");
} else {
Log.v(Database.TAG, "Created remote db");
}
shouldCreateTarget = false;
beginReplicating();
}
});
}
@Override
@InterfaceAudience.Private
public void beginReplicating() {
// If we're still waiting to create the remote db, do nothing now. (This method will be
// re-invoked after that request finishes; see maybeCreateRemoteDB() above.)
if(shouldCreateTarget) {
return;
}
if(filterName != null) {
filter = db.getFilter(filterName);
}
if(filterName != null && filter == null) {
Log.w(Database.TAG, String.format("%s: No ReplicationFilter registered for filter '%s'; ignoring", this, filterName));;
}
// Process existing changes since the last push:
long lastSequenceLong = 0;
if(lastSequence != null) {
lastSequenceLong = Long.parseLong(lastSequence);
}
ChangesOptions options = new ChangesOptions();
options.setIncludeConflicts(true);
RevisionList changes = db.changesSince(lastSequenceLong, options, filter);
if(changes.size() > 0) {
processInbox(changes);
}
// Now listen for future changes (in continuous mode):
if(continuous) {
observing = true;
db.addChangeListener(this);
asyncTaskStarted(); // prevents stopped() from being called when other tasks finish
}
}
@InterfaceAudience.Private
private void stopObserving() {
if(observing) {
observing = false;
db.removeChangeListener(this);
asyncTaskFinished(1);
}
}
@Override
@InterfaceAudience.Private
public void changed(Database.ChangeEvent event) {
List<DocumentChange> changes = event.getChanges();
for (DocumentChange change : changes) {
// Skip revisions that originally came from the database I'm syncing to:
URL source = change.getSourceUrl();
if(source != null && source.equals(remote)) {
return;
}
RevisionInternal rev = change.getAddedRevision();
Map<String, Object> paramsFixMe = null; // TODO: these should not be null
if (getLocalDatabase().runFilter(filter, paramsFixMe, rev)) {
addToInbox(rev);
}
}
}
@Override
@InterfaceAudience.Private
protected void processInbox(final RevisionList inbox) {
final long lastInboxSequence = inbox.get(inbox.size()-1).getSequence();
// Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
Map<String,List<String>> diffs = new HashMap<String,List<String>>();
for (RevisionInternal rev : inbox) {
String docID = rev.getDocId();
List<String> revs = diffs.get(docID);
if(revs == null) {
revs = new ArrayList<String>();
diffs.put(docID, revs);
}
revs.add(rev.getRevId());
}
// Call _revs_diff on the target db:
asyncTaskStarted();
sendAsyncRequest("POST", "/_revs_diff", diffs, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object response, Throwable e) {
Map<String,Object> results = (Map<String,Object>)response;
if(e != null) {
error = e;
stop();
} else if(results.size() != 0) {
// Go through the list of local changes again, selecting the ones the destination server
// said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
List<Object> docsToSend = new ArrayList<Object>();
for(RevisionInternal rev : inbox) {
Map<String,Object> properties = null;
Map<String,Object> resultDoc = (Map<String,Object>)results.get(rev.getDocId());
if(resultDoc != null) {
List<String> revs = (List<String>)resultDoc.get("missing");
if(revs != null && revs.contains(rev.getRevId())) {
//remote server needs this revision
// Get the revision's properties
if(rev.isDeleted()) {
properties = new HashMap<String,Object>();
properties.put("_id", rev.getDocId());
properties.put("_rev", rev.getRevId());
properties.put("_deleted", true);
} else {
// OPT: Shouldn't include all attachment bodies, just ones that have changed
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.of(
Database.TDContentOptions.TDIncludeAttachments,
Database.TDContentOptions.TDBigAttachmentsFollow
);
try {
db.loadRevisionBody(rev, contentOptions);
} catch (CouchbaseLiteException e1) {
String msg = String.format("%s Couldn't get local contents of %s", rev, this);
Log.w(Database.TAG, msg);
continue;
}
properties = new HashMap<String,Object>(rev.getProperties());
}
if (properties.containsKey("_attachments")) {
if (uploadMultipartRevision(rev)) {
continue;
}
}
if(properties != null) {
// Add the _revisions list:
properties.put("_revisions", db.getRevisionHistoryDict(rev));
//now add it to the docs to send
docsToSend.add(properties);
}
}
}
}
// Post the revisions to the destination. "new_edits":false means that the server should
// use the given _rev IDs instead of making up new ones.
final int numDocsToSend = docsToSend.size();
if (numDocsToSend > 0 ) {
Map<String,Object> bulkDocsBody = new HashMap<String,Object>();
bulkDocsBody.put("docs", docsToSend);
bulkDocsBody.put("new_edits", false);
Log.i(Database.TAG, String.format("%s: Sending %d revisions", this, numDocsToSend));
Log.v(Database.TAG, String.format("%s: Sending %s", this, inbox));
setChangesCount(getChangesCount() + numDocsToSend);
asyncTaskStarted();
sendAsyncRequest("POST", "/_bulk_docs", bulkDocsBody, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
if(e != null) {
error = e;
} else {
Log.v(Database.TAG, String.format("%s: Sent %s", this, inbox));
setLastSequence(String.format("%d", lastInboxSequence));
}
setCompletedChangesCount(getCompletedChangesCount() + numDocsToSend);
asyncTaskFinished(1);
}
});
}
} else {
// If none of the revisions are new to the remote, just bump the lastSequence:
setLastSequence(String.format("%d", lastInboxSequence));
}
asyncTaskFinished(1);
}
});
}
@InterfaceAudience.Private
private boolean uploadMultipartRevision(RevisionInternal revision) {
MultipartEntity multiPart = null;
Map<String, Object> revProps = revision.getProperties();
revProps.put("_revisions", db.getRevisionHistoryDict(revision));
Map<String, Object> attachments = (Map<String, Object>) revProps.get("_attachments");
for (String attachmentKey : attachments.keySet()) {
Map<String, Object> attachment = (Map<String, Object>) attachments.get(attachmentKey);
if (attachment.containsKey("follows")) {
if (multiPart == null) {
multiPart = new MultipartEntity();
try {
String json = Manager.getObjectMapper().writeValueAsString(revProps);
Charset utf8charset = Charset.forName("UTF-8");
multiPart.addPart("param1", new StringBody(json, "application/json", utf8charset));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
BlobStore blobStore = this.db.getAttachments();
String base64Digest = (String) attachment.get("digest");
BlobKey blobKey = new BlobKey(base64Digest);
InputStream inputStream = blobStore.blobStreamForKey(blobKey);
if (inputStream == null) {
Log.w(Database.TAG, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision.");
multiPart = null;
}
else {
String contentType = null;
if (attachment.containsKey("content_type")) {
contentType = (String) attachment.get("content_type");
}
else if (attachment.containsKey("content-type")) {
String message = String.format("Found attachment that uses content-type" +
" field name instead of content_type (see couchbase-lite-android" +
" issue #80): " + attachment);
Log.w(Database.TAG, message);
}
multiPart.addPart(attachmentKey, new InputStreamBody(inputStream, contentType, attachmentKey));
}
}
}
if (multiPart == null) {
return false;
}
String path = String.format("/%s?new_edits=false", revision.getDocId());
// TODO: need to throttle these requests
Log.d(Database.TAG, "Uploadeding multipart request. Revision: " + revision);
asyncTaskStarted();
sendAsyncMultipartRequest("PUT", path, multiPart, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
if(e != null) {
Log.e(Database.TAG, "Exception uploading multipart request", e);
error = e;
} else {
Log.d(Database.TAG, "Uploaded multipart request. Result: " + result);
}
asyncTaskFinished(1);
}
});
return true;
}
}
|
package soot.dexpler;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jf.dexlib2.iface.Annotation;
import org.jf.dexlib2.iface.AnnotationElement;
import org.jf.dexlib2.iface.Method;
import org.jf.dexlib2.iface.value.ArrayEncodedValue;
import org.jf.dexlib2.iface.value.EncodedValue;
import org.jf.dexlib2.iface.value.TypeEncodedValue;
import soot.Body;
import soot.G;
import soot.MethodSource;
import soot.Modifier;
import soot.RefType;
import soot.SootClass;
import soot.SootMethod;
import soot.SootResolver;
import soot.Type;
import soot.jimple.Jimple;
import soot.jimple.toolkits.typing.TypeAssigner;
import soot.options.Options;
/**
* DexMethod is a container for all methods that are declared in a class.
* It holds information about its name, the class it belongs to, its access flags, thrown exceptions, the return type and parameter types as well as the encoded method itself.
*
*/
public class DexMethod {
private DexMethod() {}
/**
* Retrieve the SootMethod equivalent of this method
* @return the SootMethod of this method
*/
public static SootMethod makeSootMethod(String dexFile, Method method, SootClass declaringClass) {
Set<Type> types = new HashSet<Type>();
int accessFlags = method.getAccessFlags();
List<Type> parameterTypes = new ArrayList<Type>();
// get the name of the method
String name = method.getName();
Debug.printDbg("processing method '", method.getDefiningClass() ,": ", method.getReturnType(), " ", method.getName(), " p: ", method.getParameters(), "'");
// the following snippet retrieves all exceptions that this method throws by analyzing its annotations
List<SootClass> thrownExceptions = new ArrayList<SootClass>();
for (Annotation a : method.getAnnotations()) {
Type atype = DexType.toSoot(a.getType());
String atypes = atype.toString();
if (!(atypes.equals("dalvik.annotation.Throws")))
continue;
for (AnnotationElement ae : a.getElements()) {
EncodedValue ev = ae.getValue();
if(ev instanceof ArrayEncodedValue) {
for(EncodedValue evSub : ((ArrayEncodedValue) ev).getValue()) {
if(evSub instanceof TypeEncodedValue) {
TypeEncodedValue valueType = (TypeEncodedValue) evSub;
String exceptionName = valueType.getValue();
String dottedName = Util.dottedClassName(exceptionName);
thrownExceptions.add(SootResolver.v().makeClassRef(dottedName));
}
}
}
}
}
// retrieve all parameter types
if (method.getParameters() != null) {
List<? extends CharSequence> parameters = method.getParameterTypes();
for(CharSequence t : parameters) {
Type type = DexType.toSoot(t.toString());
parameterTypes.add(type);
types.add(type);
}
}
// retrieve the return type of this method
Type returnType = DexType.toSoot(method.getReturnType());
types.add(returnType);
//Build soot method by all available parameters
SootMethod sm = declaringClass.getMethodUnsafe(name, parameterTypes, returnType);
if (sm == null) {
sm = new SootMethod(name, parameterTypes, returnType, accessFlags, thrownExceptions);
}
// if the method is abstract or native, no code needs to be transformed
int flags = method.getAccessFlags();
if (Modifier.isAbstract(flags)|| Modifier.isNative(flags))
return sm;
if (Options.v().oaat() && declaringClass.resolvingLevel() <= SootClass.SIGNATURES)
return sm;
// // retrieve all local types of the method
// DebugInfoItem debugInfo = method.g.codeItem.getDebugInfo();
// if(debugInfo!=null) {
// for(Item<?> item : debugInfo.getReferencedItems()) {
// if (item instanceof TypeIdItem) {
// Type type = DexType.toSoot((TypeIdItem) item);
// dexClass.types.add(type);
//add the body of this code item
final DexBody dexBody = new DexBody(dexFile, method, (RefType) declaringClass.getType());
for (Type t : dexBody.usedTypes())
types.add(t);
// sets the method source by adding its body as the active body
sm.setSource(new MethodSource() {
public Body getBody(SootMethod m, String phaseName) {
Body b = Jimple.v().newBody(m);
try {
dexBody.jimplify(b, m);
} catch (InvalidDalvikBytecodeException e) {
String msg = "Warning: Invalid bytecode in method "+ m +": "+ e;
G.v().out.println(msg);
Util.emptyBody(b);
Util.addExceptionAfterUnit(b, "java.lang.RuntimeException", b.getUnits().getLast(), "Soot has detected that this method contains invalid Dalvik bytecode which would have throw an exception at runtime. ["+ msg +"]");
TypeAssigner.v().transform(b);
}
m.setActiveBody(b);
return m.getActiveBody();
}
});
return sm;
}
}
|
package com.areen.jlib.gui.fcb;
import com.areen.jlib.gui.ColorArrowUI;
import com.areen.jlib.util.Sise;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
public class ComboBoxFilter extends PlainDocument {
private JComboBox comboBox;
private JTextComponent comboBoxEditor;
private FilteredComboBoxModel comboBoxModel;
/**
* Every call to setSelectedItem() in the combo-box will provoke another
* call to the insertString, with the newly selected item. We prevent this
* by seting "selecting" to true before we call setPattern(). Subsequent
* calls to remove/insertString should be ignored.
*/
boolean selecting = false;
boolean hidePopupOnFocusLoss;
// TODO: these two are not important, remove after debug
private boolean hitBackspaceOnSelection;
private boolean hitBackspace;
private boolean arrowKeyPressed = false;
private boolean keyPressed = false;
private boolean finish = false;
private boolean inPreparation;
private int selectedIndex;
private Object pickedItem;
private Object pickedKey;
/**
* This value is set by cell-editors to inform ComboBoxFilter whether to
* execute pick value or not during the preparation phase (prepare()
* method).
*/
private boolean triggeredByKeyPress = false;
private int previousItemCount;
/**
* We have to store the popup menu's dimension so we can fix incorrect popup
* size during the filtering process.
*/
private int popupMenuWidth;
private int popupMenuHeight;
static final Logger LOGGER = Logger.getLogger(ComboBoxFilter.class.getCanonicalName());
/**
* This constructor adds filtering capability to the given JComboBox object
* argComboBox. It will also assign appropriate model to the combo-box, one
* that has setPattern() method. It will also set the argComboBox to be
* editable.
*
* @param argComboBox
* @param argComboBoxModel
*/
public ComboBoxFilter(final JComboBox argComboBox, FilteredComboBoxModel argComboBoxModel) {
comboBox = argComboBox;
comboBox.setEditable(true);
fixComboBoxArrowUI();
comboBoxModel = argComboBoxModel;
comboBox.setModel(comboBoxModel);
comboBox.putClientProperty("item-picked", Boolean.FALSE);
comboBoxEditor = (JTextComponent) comboBox.getEditor().getEditorComponent();
comboBoxEditor.setDocument(this);
// let's add a key listener to the editor
comboBoxEditor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
LOGGER.info("keyPressed()");
int keyCode = e.getKeyCode();
System.out.println(keyCode);
/*
* In the case user presses SHIFT, CTRL, ALT keys, or <ANY>+TAB,
* we return imediately.
*/
//int modifiers = e.getModifiersEx();
if (keyCode == KeyEvent.VK_SHIFT
|| (keyCode == KeyEvent.VK_ALT)
|| (keyCode == KeyEvent.VK_CONTROL)
|| (keyCode == KeyEvent.VK_WINDOWS)
|| (keyCode == KeyEvent.VK_CONTEXT_MENU)
|| (keyCode == KeyEvent.VK_TAB && e.isShiftDown())) {
keyPressed = false;
return;
}
keyPressed = true;
boolean isTableCellEditor = false;
Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor");
if (tmp != null) {
isTableCellEditor = tmp.equals(Boolean.TRUE);
}
if (comboBox.isDisplayable()) {
comboBox.setPopupVisible(true);
}
arrowKeyPressed = false;
finish = false;
int currentIndex = comboBox.getSelectedIndex();
switch (keyCode) {
case KeyEvent.VK_TAB:
LOGGER.info("TAB!");
finish = true;
comboBoxModel.setReadyToFinish(false);
if (!isTableCellEditor()) {
Object obj = comboBoxModel.getKeyOfTheSelectedItem();
if (obj == null) {
setText("");
} else {
setText(comboBoxModel.getKeyOfTheSelectedItem().toString());
}
}
if ((comboBox.getSelectedItem() == null)) {
/*
* if TAB is pressed, but nothing is selected, and
* the picked item is not null * that means the user
* pressed tab when there was an empty list of
* items. * (Typically when user typed something
* that does not exist in the list of * items). In
* this case we cancel the editing.
*/
comboBoxModel.setCancelled(true);
}
if (comboBox.getSelectedItem() != null) {
if (pickedItem == comboBox.getSelectedItem()) {
/*
* We cancel the editing when the picked item is
* the same as the item that * is currently
* selected in the combo-box, because we do not
* want to * trigger database change (there is
* no need to update to the same value).
*/
comboBoxModel.setCancelled(true);
} else {
pickedItem = comboBox.getSelectedItem();
pickedKey = comboBoxModel.getKeyOfTheSelectedItem().toString();
} // else
}
break;
case KeyEvent.VK_ESCAPE:
if (isTableCellEditor()) {
comboBoxModel.setCancelled(true);
comboBox.setSelectedItem(pickedItem);
} else {
ComboBoxFilter.this.setText(pickedKey.toString());
}
break;
case KeyEvent.VK_ENTER:
finish = true;
comboBoxModel.setReadyToFinish(false); // we expect cell editor
Object obj = comboBoxModel.getKeyOfTheSelectedItem();
String txt = "";
if (obj != null) {
txt = obj.toString();
}
if (!isTableCellEditor()) {
setText(txt);
}
pickedItem = comboBox.getSelectedItem();
pickedKey = txt;
break;
case KeyEvent.VK_UP:
arrowKeyPressed = true;
if (isTableCellEditor) {
/*
* For some reason, the JTable is stealing keyboard
* events and preventing us * from moving up/down,
* so we have to select proper values manually. * *
* If selection did not move, we will manually
* select appropriate item.
*/
if ((selectedIndex == currentIndex) && (currentIndex > 0)) {
comboBox.setSelectedIndex(currentIndex - 1);
selectedIndex = currentIndex - 1;
} else {
selectedIndex = currentIndex;
}
// we set this to false ONLY if the combo box is a cell editor!
arrowKeyPressed = false;
}
break;
case KeyEvent.VK_DOWN:
arrowKeyPressed = true;
if (isTableCellEditor && comboBox.isPopupVisible()) {
/*
* For some reason, the JTable is stealing keyboard
* events and preventing us * from moving up/down,
* so we have to select proper values manually. * *
* If selection did not move, we will manually
* select appropriate item.
*/
if ((selectedIndex == currentIndex)
&& (currentIndex < comboBox.getItemCount() - 1)) {
comboBox.setSelectedIndex(currentIndex + 1);
selectedIndex = currentIndex + 1;
} else {
selectedIndex = currentIndex;
} // else
// we set this to false ONLY if the combo box is a cell editor!
arrowKeyPressed = false;
}
break;
default:
selectedIndex = currentIndex;
} // switch
keyPressed = false;
} // keyPressed() method
});
// Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out
hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5");
// Highlight whole text when focus gets lost
comboBoxEditor.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
LOGGER.info("focusLost()");
if (pickedKey != null) {
// When combo-box loses focus, we need to set the text to the selected
setText(pickedKey.toString());
}
// Workaround for Bug 5100422 - Hide Popup on focus loss
if (hidePopupOnFocusLoss) {
ComboBoxFilter.this.comboBox.setPopupVisible(false);
}
comboBoxModel.setReadyToFinish(false);
}
@Override
public void focusGained(FocusEvent fe) {
if (!isTableCellEditor()) {
super.focusGained(fe);
comboBoxEditor.selectAll();
}
} // focusGained() method
});
/*
* The following PopupMenuListener is needed to store the inidial
* Dimension of the combobox popup.
*/
comboBox.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
/*
* NOTE: Dimension returned by getSize() method is actually the
* dimension of the combo-box popup menu! It is not the size of
* the JTextComponent object! :)
*/
JComboBox box = (JComboBox) pme.getSource();
popupMenuWidth = box.getSize().width;
popupMenuHeight = box.getSize().height;
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
LOGGER.info("hiding popup...");
comboBox.putClientProperty("item-picked", Boolean.FALSE);
}
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
// do nothing
}
});
if (!isTableCellEditor()) {
comboBoxEditor.setFocusTraversalKeysEnabled(false);
Action myAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Nothing is needed here - all we want is to skip focusLost() call when user presses TAB
comboBoxEditor.transferFocus();
} // actionPerformed() method
};
comboBoxEditor.getActionMap().put("tab-action", myAction);
comboBoxEditor.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(KeyStroke.getKeyStroke("TAB"), "tab-action");
}
Object selected = comboBox.getSelectedItem();
pickedItem = selected;
Object tmp = comboBoxModel.getKeyOfTheSelectedItem();
if (tmp instanceof String) {
pickedKey = tmp.toString();
} else {
pickedKey = tmp;
} // else
selectedIndex = comboBox.getSelectedIndex();
if (selected != null) {
setText(comboBoxModel.getKeyOfTheSelectedItem().toString());
}
}
/**
* User typically will call this method from a table cell editor when we
* want to "inform" filtered combo-box that we want to re-filter before we
* actually start editing. The reason for this is when user goes to another
* cell, the filtered set of entries from the previous cell will not apply.
*
* @param argPattern
*/
public void prepare(Object argPattern) {
LOGGER.info("prepare(" + argPattern + ")");
if (argPattern == null) {
// If the previous value is null, we simply exit this method.
pickedItem = null;
pickedKey = null;
comboBox.setSelectedItem(null);
return;
}
inPreparation = true;
selecting = true;
comboBoxModel.setCancelled(false);
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(false);
}
String pat = (String) argPattern.toString();
/*
* If the editing is triggered by a key-press in a JTable, then the
* argPattern contains a string in SISE format, so we have to extract
* they key pressed and the previous value.
*/
String key = "";
if (isTriggeredByKeyPress()) {
String[] strs = Sise.units(pat);
/*
* In the case the cell's value was a NULL, then strs will have only
* one element. In that case we set pat to be a null, and do not set
* the pickedItem.
*/
if (strs.length == 2) {
pat = strs[1];
} else {
pat = null;
} // else
key = strs[0];
}
try {
if (argPattern == null) {
setText("");
} else {
if (pat != null) {
setText(pat.trim());
}
} // else
if (pat == null) {
pickedItem = null;
pickedKey = null;
} else {
// Cell's value was not a null, so we can execute filter so the combo-box updates the
// selected item to be what was previously selected.
filterTheModel();
pickedItem = comboBox.getSelectedItem();
pickedKey = comboBoxModel.getKeyOfTheSelectedItem();
} // else
// Finally, when we have selected the item that was previously selected, now we can insert
// the character user typed inside a JTable
if (isTriggeredByKeyPress()) {
setText(key);
filterTheModel();
}
} catch (BadLocationException ex) {
Logger.getLogger(ComboBoxFilter.class.getName()).log(Level.SEVERE, null, ex);
}
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(false);
}
inPreparation = false;
LOGGER.info("prepare done.");
} // prepare() method
private void clearTextSelection() {
if (comboBoxEditor.getSelectedText() != null) {
// we have a selected text, removing the selection. On Windows text may become selected by default
LOGGER.info("SELECTED TEXT: " + comboBoxEditor.getSelectedText());
int pos = comboBoxEditor.getCaretPosition();
comboBoxEditor.select(0, 0);
// return caret position to the original place
comboBoxEditor.setCaretPosition(pos);
}
}
private void setText(String text) {
try {
// remove all text and insert the completed string
super.remove(0, getLength());
super.insertString(0, text, null);
} catch (BadLocationException e) {
throw new RuntimeException(e.toString());
}
}
/**
* This method is a leftover from the previous version of the
* ComboBoxFilter. Should be removed after the testing phase.
*/
private void highlightCompletedText(int start) {
comboBoxEditor.setCaretPosition(getLength());
comboBoxEditor.moveCaretPosition(start);
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
LOGGER.info("insertString(" + offs + ", " + str + ")");
//LOGGER.info("insertString(" + selecting + ", " + arrowKeyPressed + ")");
// return immediately when selecting an item
if (selecting) {
return;
}
if (arrowKeyPressed) {
arrowKeyPressed = false;
comboBox.putClientProperty("item-picked", Boolean.FALSE);
return;
}
// insert the string into the document
if (str.contains(Sise.UNIT_SEPARATOR_STRING)) {
LOGGER.info("%%%%%%%%%%%%%");
System.out.println(str);
// we got a string in the Sise format, that must be because user picked an item with a mouse
// in that case, we will take the key component (SISE unit) and put that instead.
String[] strs = Sise.units(str);
int idx = comboBoxModel.getKeyIndex();
if (isTableCellEditor()) {
comboBoxModel.setReadyToFinish(true);
}
boolean itemPicked = false; // we need this value because item-packed may change due to chain
// of events
// inform action-performed listeners that the item has been picked so they may update
// some other components
if (keyPressed) {
itemPicked = false;
} else {
itemPicked = true;
}
comboBox.putClientProperty("item-picked", itemPicked);
System.out.println(strs[idx]);
System.out.println(itemPicked);
super.insertString(offs, strs[idx], a);
// we have to filter after the user selects an item with the mouse.
// WARNING: here we rely on the FilteredComboBoxModel's setPattern() method to select the
// exact match - ie the item that user picked with the mouse.
filterTheModel();
if (itemPicked) {
pickedItem = comboBox.getSelectedItem();
Object tmp = comboBoxModel.getKeyOfTheSelectedItem();
if (tmp instanceof String) {
pickedKey = tmp.toString();
} else {
pickedKey = tmp;
} // else
}
comboBox.putClientProperty("item-picked", Boolean.FALSE);
return;
} else {
comboBox.putClientProperty("item-picked", Boolean.FALSE);
// otherwise, insert the whole string
super.insertString(offs, str, a);
} // else
if (finish) {
return;
}
filterTheModel();
} // insertString() method
@Override
public void remove(int offs, int len) throws BadLocationException {
LOGGER.info("remove(" + offs + ", " + len + ")");
LOGGER.info("remove(" + selecting + ", " + arrowKeyPressed + ")");
// return immediately when selecting an item
if (selecting) {
// remove() is called whenever setSelectedItem() or setSelectedIndex() are called. They may be
// called during the filtering process, so we do not want to remove while in the middle.
return;
}
if (arrowKeyPressed) {
if (isTableCellEditor()) {
// if the remove() has been called while user navigates through the combobox list, we do not
// filter. when user navigates via arrow keys, remove() is always called first, followed by
// the insertString. However, sometimes table steals the event, and causes trouble.
// As remove() is called first, here we check if correct value has been selected after user
// presses UP/DOWN
int currentIndex = comboBox.getSelectedIndex();
if (selectedIndex != currentIndex) {
// they are not equal, fix it
comboBox.setSelectedIndex(selectedIndex);
}
}
return;
}
// remove the string from the document
super.remove(offs, len);
if (finish) {
// user pressed ENTER so in the case remove is called we do not filter the model.
return;
}
// finally, do the filter
filterTheModel();
} // remove() method
/**
* This method calls the setPatter() method, and starts the filtering.
*
* It also sets the previousItemCount variable to hold the previous number
* of filtered items.
*/
private void filterTheModel() throws BadLocationException {
// we have to "guard" the call to comboBoxModel.setPattern() with selecting set to true, then false
selecting = true;
boolean oldValue = comboBoxModel.isReadyToFinish();
comboBoxModel.setReadyToFinish(false); // we must set this to false during the filtering
previousItemCount = comboBox.getItemCount(); /// store the number of items before filtering
String pattern = getText(0, getLength());
//LOGGER.info("filterTheModel(): " + pattern);
comboBoxModel.setPattern(pattern);
clearTextSelection();
fixPopupSize();
comboBoxModel.setReadyToFinish(oldValue); // restore the value
selecting = false;
selectedIndex = comboBox.getSelectedIndex();
//LOGGER.info("SELECTED AFTER:" + comboBox.getSelectedItem());
}
/**
* Use this method whenever you need to determine if the comboBox is used as
* a cell editor or not.
*
* @return boolean Value indicating whether comboBox is a cell editor (TRUE)
* or not (FALSE).
*/
private boolean isTableCellEditor() {
boolean isTableCellEditor = false;
Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor");
if (tmp != null) {
isTableCellEditor = tmp.equals(Boolean.TRUE);
}
return isTableCellEditor;
} // isTableCellEditor method
/**
* This method is used internally to fix the popup-menu size. Apparently
* JComboBox has a bug and does not calculate the proper height of the
* popup.
*
* The first time popup menu is shown, ComboBoxFilter stores the dimension,
* and re-adjusts the width to the original value all the time. Reason for
* this is that we do not want to have different widths while user types
* something.
*/
private void fixPopupSize() {
if (inPreparation) {
return;
}
LOGGER.info("fixPopupSize()");
int maxRows = comboBox.getMaximumRowCount();
if ((previousItemCount < maxRows) || (comboBox.getItemCount() < maxRows)) {
// do this only when we have less than maxRows items, to prevent the flickering.
// this is a hack and is actually the easiest solution to the JComboBox's popup resizing problem.
if (comboBox.isPopupVisible()) {
comboBox.setPopupVisible(false);
comboBox.setPopupVisible(true);
}
}
} // fixPopupSize() method
/**
* If the l&f is system, and OS is Windows, we have to fix the arrow UI of
* the combo box, when editing is enabled. This method is responsible for
* doing that.
*/
private void fixComboBoxArrowUI() {
String scn = UIManager.getSystemLookAndFeelClassName();
if (System.getProperty("os.name").startsWith("Windows")
&& UIManager.getLookAndFeel().getClass().getCanonicalName().equals(scn)) {
System.err.println("DEBUG: fixing the combo-box's arrow");
comboBox.setUI(ColorArrowUI.createUI(comboBox));
}
} // fixComboBoxArrowUI() method
public boolean isTriggeredByKeyPress() {
return triggeredByKeyPress;
}
public void setTriggeredByKeyPress(boolean argTriggeredByKeyPress) {
triggeredByKeyPress = argTriggeredByKeyPress;
}
public Object getPickedItem() {
return pickedItem;
}
public Object getPickedKey() {
return pickedKey;
}
} // ComboBoxFilter class
|
package xyz.openmodloader.event.impl;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.*;
import xyz.openmodloader.OpenModLoader;
import xyz.openmodloader.event.Event;
/**
* Parent class for world related events. All events that fall within this scope
* should extend this class. They should usually also be added as inner classes,
* although this is not an absolute requirement.
*/
public abstract class WorldEvent extends Event {
/**
* The world that this event was fired from.
*/
private final World world;
/**
* Creates a new world event.
* Only for use by subclasses.
*
* @param world the world this event was fired from
*/
public WorldEvent(World world) {
this.world = world;
}
/**
* Gets the world that this event was fired from.
*
* @return the world
*/
public World getWorld() {
return world;
}
/**
* Fired when the world has loaded. Fired from {@link WorldServer#init()}
* and the {@link WorldClient} constructor.
*
* This event is not cancelable.
*/
public static class Load extends WorldEvent {
/**
* Creates a new Load event. For internal use only!
*
* @param world the world this event was fired from
*/
public Load(World world) {
super(world);
}
/**
* Internal method for handling Load events.
*/
public static Load handle(World world) {
Load event = new Load(world);
OpenModLoader.getEventBus().post(event);
return event;
}
}
/**
* Fired when the world has unloaded. Fired from
* {@link Minecraft#loadWorld(WorldClient,String)} and
* {@link MinecraftServer#stopServer()}.
*
* This event is not cancelable.
*/
public static class Unload extends WorldEvent {
/**
* Creates a new Unload event. For internal use only!
*
* @param world the world this event was fired from
*/
public Unload(World world) {
super(world);
}
/**
* Internal method for handling Unload events.
*/
public static Unload handle(World world) {
Unload event = new Unload(world);
OpenModLoader.getEventBus().post(event);
return event;
}
}
/**
* Fired when the spawn point is determined. Fired from
* {@link WorldServer#createSpawnPosition(WorldSettings)}.
*
* This event is cancelable.
*/
public static class SetSpawn extends WorldEvent {
/**
* The position that will be used as spawn point.
*/
private BlockPos spawnPoint;
/**
* Creates a new SetSpawn event. For internal use only!
*
* @param world the world this event was fired from
* @param spawnPoint the spawn point generated by Vanilla
*/
public SetSpawn(World world, BlockPos spawnPoint) {
super(world);
this.spawnPoint = spawnPoint;
}
/**
* Gets the position that will be used as spawn point.
*
* @return the position
*/
public BlockPos getSpawnPoint() {
return spawnPoint;
}
/**
* Sets the position that will be used as spawn point
*
* @param spawnPoint the new spawn point
*/
public void setSpawnPoint(BlockPos spawnPoint) {
this.spawnPoint = spawnPoint;
}
@Override
public boolean isCancelable() {
return true;
}
/**
* Internal method for handling SetSpawn events.
*/
public static SetSpawn handle(World world, BlockPos spawnPoint) {
SetSpawn event = new SetSpawn(world, spawnPoint);
OpenModLoader.getEventBus().post(event);
return event;
}
}
}
|
// 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.presents.server;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Iterator;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.Throttle;
import com.samskivert.util.ResultListener;
import com.threerings.util.Name;
import com.threerings.presents.Log;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.ObjectAccessException;
import com.threerings.presents.dobj.ProxySubscriber;
import com.threerings.presents.net.BootstrapData;
import com.threerings.presents.net.BootstrapNotification;
import com.threerings.presents.net.Credentials;
import com.threerings.presents.net.EventNotification;
import com.threerings.presents.net.UpstreamMessage;
import com.threerings.presents.net.ForwardEventRequest;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.PingRequest;
import com.threerings.presents.net.SubscribeRequest;
import com.threerings.presents.net.UnsubscribeRequest;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.FailureResponse;
import com.threerings.presents.net.ObjectResponse;
import com.threerings.presents.net.PongResponse;
import com.threerings.presents.net.UnsubscribeResponse;
import com.threerings.presents.server.net.Connection;
import com.threerings.presents.server.net.MessageHandler;
/**
* A client object represents a client session in the server. It is
* associated with a connection instance (while the client is connected)
* and acts as the intermediary for the remote client in terms of passing
* along events forwarded by the client, ensuring that subscriptions are
* maintained on behalf of the client and that events are forwarded to the
* client.
*
* <p><em>A note on synchronization:</em> the client object is structured
* so that its <code>Subscriber</code> implementation (which is called
* from the dobjmgr thread) can proceed without synchronization. This does
* not overlap with its other client duties which are called from the
* conmgr thread and therefore also need not be synchronized.
*/
public class PresentsClient
implements ProxySubscriber, MessageHandler, ClientResolutionListener
{
/** Used by {@link #setUsername} to report success or failure. */
public static interface UserChangeListener
{
/** Called when the new client object has been resolved and the
* new client object reported to the client, but the old one has
* not yet been destroyed. Any events delivered on this callback
* to the old client object will be delivered.
*
* @param rl when this method is finished with its business and
* the old client object can be destroyed, the result listener
* should be called.
* */
public void changeReported (ClientObject newObji, ResultListener rl);
/** Called when the user change is completed, the old client
* object is destroyed and all updates are committed. */
public void changeCompleted (ClientObject newObj);
/** Called if some failure occurs during the user change
* process. */
public void changeFailed (Exception cause);
}
/**
* Returns the credentials used to authenticate this client.
*/
public Credentials getCredentials ()
{
return _creds;
}
/**
* Returns true if this client has been disconnected for sufficiently
* long that its session should be forcibly ended.
*/
public boolean checkExpired (long now)
{
return (getConnection() == null && (now - _networkStamp > FLUSH_TIME));
}
/**
* Returns the time at which this client started their network
* session.
*/
public long getSessionStamp ()
{
return _sessionStamp;
}
/**
* Returns the time at which this client most recently connected or
* disconnected.
*/
public long getNetworkStamp ()
{
return _networkStamp;
}
/**
* Returns the username with which this client instance is associated.
*/
public Name getUsername ()
{
return _username;
}
/**
* Returns the address of the connected client or null if this client
* is not connected.
*/
public InetAddress getInetAddress ()
{
Connection conn = getConnection();
return (conn == null) ? null : conn.getInetAddress();
}
/**
* Configures this client with a custom class loader that will be used
* when unserializing classes from the network.
*/
public void setClassLoader (ClassLoader loader)
{
_loader = loader;
Connection conn = getConnection();
if (conn != null) {
conn.setClassLoader(loader);
}
}
/**
* <em>Danger:</em> this method is not for general consumption. This
* changes the username of the client, but should only be done very
* early in a user's session, when you know that no one has mapped the
* user based on their username or has in any other way made use of
* their username in a way that will break. However, it should not be
* done <em>too</em> early in the session. The client must be fully
* resolved.
*
* <p> It exists to support systems wherein a user logs in with an
* account username and then chooses a "screen name" by which they
* will play (often from a small set of available "characters"
* available per account). This will take care of remapping the
* username to client object mappings that were made by the Presents
* services when the user logs on, but anything else that has had its
* grubby mits on the username will be left to its own devices, hence
* the care that must be exercised when using this method.
*
* @param ucl an entity that will (optionally) be notified when the
* username conversion process is complete.
*/
public void setUsername (Name username, final UserChangeListener ucl)
{
ClientResolutionListener clr = new ClientResolutionListener() {
public void clientResolved (final Name username,
final ClientObject clobj)
{
// if they old client object is gone by now, they ended
// their session while we were switching, so freak out
if (_clobj == null) {
Log.warning("Client disappeared before we could " +
"complete the switch to a new client " +
"object [ousername=" + _username +
", nusername=" + username + "].");
_cmgr.releaseClientObject(username);
Exception error = new Exception("Early withdrawal");
resolutionFailed(username, error);
return;
}
// let the client know that the rug has been yanked out
// from under their ass
Object[] args = new Object[] { Integer.valueOf(clobj.getOid()) };
_clobj.postMessage(ClientObject.CLOBJ_CHANGED, args);
// call down to any derived classes
clientObjectWillChange(_clobj, clobj);
// let the caller know that we've got some new business
if (ucl != null) {
ucl.changeReported(clobj, new ResultListener() {
public void requestCompleted (Object result) {
finishResolved(username, clobj);
}
public void requestFailed (Exception cause) {
finishResolved(username, clobj);
}
});
} else {
finishResolved(username, clobj);
}
}
/**
* Finish the final phase of the switch.
*/
protected void finishResolved (Name username, ClientObject clobj)
{
// release our old client object; this will destroy it
_cmgr.releaseClientObject(_username);
// update our internal fields
_username = username;
_clobj = clobj;
// call down to any derived classes
clientObjectDidChange(_clobj);
// let our listener know we're groovy
if (ucl != null) {
ucl.changeCompleted(_clobj);
}
}
public void resolutionFailed (Name username, Exception reason) {
Log.warning("Unable to resolve new client object " +
"[oldname=" + _username + ", newname=" + username +
", reason=" + reason + "].");
Log.logStackTrace(reason);
// let our listener know we're hosed
if (ucl != null) {
ucl.changeFailed(reason);
}
}
};
// resolve the new client object
_cmgr.resolveClientObject(username, clr);
}
/**
* Called when {@link #setUsername} has been called and the new client
* object is about to be applied to this client. The old client object
* will not yet have been destroyed, so any final events can be sent
* along prior to the new object being put into effect.
*/
protected void clientObjectWillChange (
ClientObject oldClobj, ClientObject newClobj)
{
}
/**
* Called after the new client object has been committed to this
* client due to a call to {@link #setUsername}.
*/
protected void clientObjectDidChange (ClientObject newClobj)
{
}
/**
* Returns the client object that is associated with this client.
*/
public ClientObject getClientObject ()
{
return _clobj;
}
/**
* Initializes this client instance with the specified username,
* connection instance and client object and begins a client session.
*/
protected void startSession (
ClientManager cmgr, Credentials creds, Connection conn, Object authdata)
{
_cmgr = cmgr;
_creds = creds;
_authdata = authdata;
setConnection(conn);
// obtain our starting username
assignStartingUsername();
// resolve our client object before we get fully underway
cmgr.resolveClientObject(_username, this);
// make a note of our session start time
_sessionStamp = System.currentTimeMillis();
}
/**
* This is factored out to allow derived classes to use a different
* starting username than the one supplied in the user's credentials.
* Generally one only wants to munge the starting username if the user
* will subsequently choose a "screen name" and it is desirable to
* avoid collision between the authentication user namespace and the
* screen namespace.
*/
protected void assignStartingUsername ()
{
_username = _creds.getUsername();
}
// documentation inherited from interface
public void clientResolved (Name username, ClientObject clobj)
{
// we'll be keeping this bad boy
_clobj = clobj;
// finish up our regular business
sessionWillStart();
sendBootstrap();
}
// documentation inherited from interface
public void resolutionFailed (Name username, Exception reason)
{
// urk; nothing to do but complain and get the f**k out of dodge
Log.warning("Unable to resolve client [username=" + username + "].");
Log.logStackTrace(reason);
// end the session now to prevent danglage
endSession();
}
/**
* Called by the client manager when a new connection arrives that
* authenticates as this already established client. This must only be
* called from the congmr thread.
*/
protected void resumeSession (Connection conn)
{
// check to see if we've already got a connection object, in which
// case it's probably stale
Connection oldconn = getConnection();
if (oldconn != null && !oldconn.isClosed()) {
Log.info("Closing stale connection [old=" + oldconn +
", new=" + conn + "].");
// close the old connection (which results in everything being
// properly unregistered)
oldconn.close();
}
// start using the new connection
setConnection(conn);
// if a client connects, drops the connection and reconnects
// within the span of a very short period of time, we'll find
// ourselves in resumeSession() before their client object was
// resolved from the initial connection; in such a case, we can
// simply bail out here and let the original session establishment
// code take care of initializing this resumed session
if (_clobj == null) {
Log.warning("Rapid-fire reconnect caused us to arrive in " +
"resumeSession() before the original session " +
"resolved its client object? " + this + ".");
return;
}
// we need to get onto the distributed object thread so that we
// can finalize the resumption of the session.
PresentsServer.omgr.postRunnable(new Runnable() {
public void run () {
// now that we're on the dobjmgr thread we can resume our
// session resumption
finishResumeSession();
}
});
}
/**
* This is called from the dobjmgr thread to complete the session
* resumption. We call some call backs and send the bootstrap info to
* the client.
*/
protected void finishResumeSession ()
{
// let derived classes do any session resuming
sessionWillResume();
// send off a bootstrap notification immediately because we've
// already got our client object
sendBootstrap();
Log.info("Session resumed " + this + ".");
}
/**
* Forcibly terminates a client's session. This must be called from
* the dobjmgr thread.
*/
public void endSession ()
{
// queue up a request for our connection to be closed (if we have
// a connection, that is)
Connection conn = getConnection();
if (conn != null) {
// go ahead and clear out our connection now to prevent
// funniness
setConnection(null);
// have the connection manager close our connection when it is
// next convenient
PresentsServer.conmgr.closeConnection(conn);
}
// if we don't have a client object, we failed to resolve in the
// first place, in which case we have to cope as best we can
if (_clobj != null) {
// and clean up after ourselves
try {
sessionDidEnd();
} catch (Exception e) {
Log.warning("Choked in sessionDidEnd [client=" + this + "].");
Log.logStackTrace(e);
}
// release (and destroy) our client object
_cmgr.releaseClientObject(_username);
}
// let the client manager know that we're audi 5000
_cmgr.clientDidEndSession(this);
// clear out the client object so that we know the session is over
_clobj = null;
}
/**
* Queues up a runnable on the object manager thread where we can
* safely end the session.
*/
protected void safeEndSession ()
{
PresentsServer.omgr.postRunnable(new Runnable() {
public void run () {
if (getClientObject() == null) {
// refuse to end the session unless the client is
// fully resolved
Log.warning("Refusing logoff request from " +
"still-resolving client " + this + ".");
} else {
// end the session in a civilized manner
endSession();
}
}
});
}
/**
* This is called when the server is shut down in the middle of a
* client session. In this circumstance, {@link #endSession} will
* <em>not</em> be called and so any persistent data that might
* normally be flushed at the end of a client's session should likely
* be flushed here.
*/
public void shutdown ()
{
// if the client is connected, we need to fake the computation of
// their final connect time because we won't be closing their
// socket normally
if (getConnection() != null) {
long now = System.currentTimeMillis();
_connectTime += ((now - _networkStamp) / 1000);
}
}
/**
* Makes a note that this client is subscribed to this object so that
* we can clean up after ourselves if and when the client goes
* away. This is called by the client internals and needn't be called
* by code outside the client.
*/
public synchronized void mapSubscrip (DObject object)
{
_subscrips.put(object.getOid(), object);
}
/**
* Makes a note that this client is no longer subscribed to this
* object. The subscription map is used to clean up after the client
* when it goes away. This is called by the client internals and
* needn't be called by code outside the client.
*/
public synchronized void unmapSubscrip (int oid)
{
DObject object = (DObject)_subscrips.remove(oid);
if (object != null) {
object.removeSubscriber(this);
} else {
Log.warning("Requested to unmap non-existent subscription " +
"[oid=" + oid + "].");
}
}
/**
* Clears out the tracked client subscriptions. Called when the client
* goes away and shouldn't be called otherwise.
*/
protected void clearSubscrips (boolean verbose)
{
for (Iterator itr = _subscrips.elements(); itr.hasNext(); ) {
DObject object = (DObject)itr.next();
if (verbose) {
Log.info("Clearing subscription [client=" + this +
", obj=" + object.getOid() + "].");
}
object.removeSubscriber(this);
}
_subscrips.clear();
}
/**
* Called when the client session is first started. The client object
* has been created at this point and after this method is executed,
* the bootstrap information will be sent to the client which will
* trigger the start of the session. Derived classes that override
* this method should be sure to call
* <code>super.sessionWillStart</code>.
*
* <p><em>Note:</em> This function will be called on the dobjmgr
* thread which means that object manipulations are OK, but client
* instance manipulations must done carefully.
*/
protected void sessionWillStart ()
{
}
/**
* Called when the client resumes a session (after having disconnected
* and reconnected). After this method is executed, the bootstrap
* information will be sent to the client which will trigger the
* resumption of the session. Derived classes that override this
* method should be sure to call <code>super.sessionWillResume</code>.
*
* <p><em>Note:</em> This function will be called on the dobjmgr
* thread which means that object manipulations are OK, but client
* instance manipulations must done carefully.
*/
protected void sessionWillResume ()
{
}
/**
* Called when the client session ends (either because the client
* logged off or because the server forcibly terminated the session).
* Derived classes that override this method should be sure to call
* <code>super.sessionDidEnd</code>.
*
* <p><em>Note:</em> This function will be called on the dobjmgr
* thread which means that object manipulations are OK, but client
* instance manipulations must done carefully.
*/
protected void sessionDidEnd ()
{
// clear out our subscriptions so that we don't get a complaint
// about inability to forward the object destroyed event we're
// about to generate
clearSubscrips(false);
}
/**
* This is called once we have a handle on the client distributed
* object. It sends a bootstrap notification to the client with all
* the information it will need to interact with the server.
*/
protected void sendBootstrap ()
{
// Log.info("Sending bootstrap " + this + ".");
// create and populate our bootstrap data
BootstrapData data = createBootstrapData();
populateBootstrapData(data);
// create a send bootstrap notification
postMessage(new BootstrapNotification(data));
}
/**
* Derived client classes can override this member to create derived
* bootstrap data classes that contain extra bootstrap information, if
* desired.
*/
protected BootstrapData createBootstrapData ()
{
return new BootstrapData();
}
/**
* Derived client classes can override this member to populate the
* bootstrap data with additional information. They should be sure to
* call <code>super.populateBootstrapData</code> before doing their
* own populating, however.
*
* <p><em>Note:</em> This function will be called on the dobjmgr
* thread which means that object manipulations are OK, but client
* instance manipulations must be done carefully.
*/
protected void populateBootstrapData (BootstrapData data)
{
// give them the client object id
data.clientOid = _clobj.getOid();
// fill in the list of bootstrap services
data.services = PresentsServer.invmgr.bootlist;
}
/**
* Called by the connection manager when this client's connection is
* unmapped. That may be because of a connection failure (in which
* case this call will be followed up by a call to
* <code>connectionFailed</code>) or it may be because of an orderly
* closing of the connection. In either case, the client can deal with
* its lack of a connection in this method. This is invoked by the
* conmgr thread and should behave accordingly.
*/
protected void wasUnmapped ()
{
// clear out our connection reference
setConnection(null);
// clear out our subscriptions. we need to do this on the dobjmgr
// thread. it is important that we do this *after* we clear out
// our connection reference. once the connection ref is null, no
// more subscriptions will be processed (even those that were
// queued up before the connection went away)
PresentsServer.omgr.postRunnable(new Runnable() {
public void run () {
sessionConnectionClosed();
}
});
}
/**
* Called on the dobjmgr thread when the connection associated with
* this session has been closed and unmapped. If the user logged off
* before closing their connection, this will be preceded by a call to
* {@link #sessionDidEnd}.
*/
protected void sessionConnectionClosed ()
{
// clear out our dobj subscriptions in case they weren't cleared
// by a call to sessionDidEnd
clearSubscrips(false);
}
/**
* Called by the connection manager when this client's connection
* fails. This is invoked on the conmgr thread and should behave
* accordingly.
*/
protected void connectionFailed (IOException fault)
{
// nothing to do here presently. the client manager already
// complained about the failed connection
}
/**
* Sets our connection reference in a thread safe way. Also
* establishes the back reference to us as the connection's message
* handler.
*/
protected synchronized void setConnection (Connection conn)
{
// if our connection is being cleared out, record the amount of
// time we were connected to our total connected time
long now = System.currentTimeMillis();
if (_conn != null && conn == null) {
_connectTime += ((now - _networkStamp) / 1000);
}
// keep a handle to the new connection
_conn = conn;
// tell the connection to pass messages on to us (if we're setting
// a connection rather than clearing one out)
if (_conn != null) {
_conn.setMessageHandler(this);
// configure any active custom class loader
if (_loader != null) {
_conn.setClassLoader(_loader);
}
}
// make a note that our network status changed
_networkStamp = now;
}
protected synchronized Connection getConnection ()
{
return _conn;
}
// documentation inherited from interface
public void handleMessage (UpstreamMessage message)
{
_messagesIn++; // count 'em up!
// if the client has been getting crazy with the cheeze whiz,
// stick a fork in them; the first time through we end our
// session, subsequently _throttle is null and we just drop any
// messages that come in until we've fully shutdown
if (_throttle == null) {
// Log.info("Dropping message from force-quit client " +
// "[conn=" + _conn +
// ", msg=" + message + "].");
return;
} else if (_throttle.throttleOp(message.received)) {
Log.warning("Client sent more than 100 messages in 10 seconds, " +
"forcing disconnect " + this + ".");
safeEndSession();
_throttle = null;
}
// we dispatch to a message dispatcher that is specialized for the
// particular class of message that we received
MessageDispatcher disp = (MessageDispatcher)
_disps.get(message.getClass());
if (disp == null) {
Log.warning("No dispatcher for message [msg=" + message + "].");
return;
}
// otherwise pass the message on to the dispatcher
disp.dispatch(this, message);
}
// documentation inherited from interface
public void objectAvailable (DObject object)
{
if (postMessage(new ObjectResponse(object))) {
// make a note of this new subscription
mapSubscrip(object);
} else {
// if we failed to send the object response, unsubscribe
object.removeSubscriber(this);
}
}
// documentation inherited from interface
public void requestFailed (int oid, ObjectAccessException cause)
{
postMessage(new FailureResponse(oid));
}
// documentation inherited from interface
public void eventReceived (DEvent event)
{
if (event instanceof PresentsDObjectMgr.AccessObjectEvent) {
Log.warning("Ignoring event that shouldn't be forwarded " +
event + ".");
Thread.dumpStack();
} else {
postMessage(new EventNotification(event));
}
}
/** Callable from non-dobjmgr thread, this queues up a runnable on the
* dobjmgr thread to post the supplied message to this client. */
protected final void safePostMessage (final DownstreamMessage msg)
{
PresentsServer.omgr.postRunnable(new Runnable() {
public void run () {
postMessage(msg);
}
});
}
/** Queues a message for delivery to the client. */
protected final boolean postMessage (DownstreamMessage msg)
{
Connection conn = getConnection();
if (conn != null) {
conn.postMessage(msg);
_messagesOut++; // count 'em up!
return true;
}
// don't log dropped messages unless we're dropping a lot of them
// (meaning something is still queueing messages up for this dead
// client even though it shouldn't be)
if (++_messagesDropped % 50 == 0) {
Log.warning("Dropping many messages? [client=" + this +
", count=" + _messagesDropped + "].");
}
// make darned sure we don't have any remaining subscriptions
if (_subscrips.size() > 0) {
// Log.warning("Clearing stale subscriptions [client=" + this +
// ", subscrips=" + _subscrips.size() + "].");
clearSubscrips(_messagesDropped > 10);
}
return false;
}
/**
* Generates a string representation of this instance.
*/
public String toString ()
{
StringBuffer buf = new StringBuffer("[");
toString(buf);
return buf.append("]").toString();
}
/**
* Derived classes override this to augment stringification.
*/
protected void toString (StringBuffer buf)
{
buf.append("username=").append(_username);
buf.append(", conn=").append(_conn);
buf.append(", cloid=").append(
(_clobj == null) ? -1 : _clobj.getOid());
buf.append(", in=").append(_messagesIn);
buf.append(", out=").append(_messagesOut);
}
/**
* Message dispatchers are used to dispatch each different type of
* upstream message. We can look the dispatcher up in a table and
* invoke it through an overloaded member which is faster (so we
* think) than doing a bunch of instanceofs.
*/
protected static interface MessageDispatcher
{
/**
* Dispatch the supplied message for the specified client.
*/
public void dispatch (PresentsClient client, UpstreamMessage mge);
}
/**
* Processes subscribe requests.
*/
protected static class SubscribeDispatcher implements MessageDispatcher
{
public void dispatch (PresentsClient client, UpstreamMessage msg)
{
SubscribeRequest req = (SubscribeRequest)msg;
// Log.info("Subscribing [client=" + client +
// ", oid=" + req.getOid() + "].");
// forward the subscribe request to the omgr for processing
PresentsServer.omgr.subscribeToObject(req.getOid(), client);
}
}
/**
* Processes unsubscribe requests.
*/
protected static class UnsubscribeDispatcher implements MessageDispatcher
{
public void dispatch (PresentsClient client, UpstreamMessage msg)
{
UnsubscribeRequest req = (UnsubscribeRequest)msg;
int oid = req.getOid();
// Log.info("Unsubscribing " + client + " [oid=" + oid + "].");
// forward the unsubscribe request to the omgr for processing
PresentsServer.omgr.unsubscribeFromObject(oid, client);
// update our subscription tracking table
client.unmapSubscrip(oid);
// post a response to the client letting them know that we
// will no longer send them events regarding this object
client.safePostMessage(new UnsubscribeResponse(oid));
}
}
/**
* Processes forward event requests.
*/
protected static class ForwardEventDispatcher implements MessageDispatcher
{
public void dispatch (PresentsClient client, UpstreamMessage msg)
{
ForwardEventRequest req = (ForwardEventRequest)msg;
DEvent fevt = req.getEvent();
// fill in the proper source oid
fevt.setSourceOid(client.getClientObject().getOid());
// Log.info("Forwarding event [client=" + client +
// ", event=" + fevt + "].");
// forward the event to the omgr for processing
PresentsServer.omgr.postEvent(fevt);
}
}
/**
* Processes ping requests.
*/
protected static class PingDispatcher implements MessageDispatcher
{
public void dispatch (PresentsClient client, UpstreamMessage msg)
{
// send a pong response
PingRequest req = (PingRequest)msg;
client.safePostMessage(new PongResponse(req.getUnpackStamp()));
}
}
/**
* Processes logoff requests.
*/
protected static class LogoffDispatcher implements MessageDispatcher
{
public void dispatch (final PresentsClient client, UpstreamMessage msg)
{
Log.debug("Client requested logoff " + client + ".");
client.safeEndSession();
}
}
protected ClientManager _cmgr;
protected Credentials _creds;
protected Object _authdata;
protected Name _username;
protected Connection _conn;
protected ClientObject _clobj;
protected HashIntMap _subscrips = new HashIntMap();
protected ClassLoader _loader;
/** The time at which this client started their session. */
protected long _sessionStamp;
/** The time at which this client most recently connected or
* disconnected. */
protected long _networkStamp;
/** The total number of seconds for which the user was connected to
* the server in this session. */
protected int _connectTime;
/** Prevent the client from sending too many messages too frequently.
* 100 messages in 10 seconds and you're audi. */
protected Throttle _throttle = new Throttle(100, 10 * 1000L);
// keep these for kicks and giggles
protected int _messagesIn;
protected int _messagesOut;
protected int _messagesDropped;
/** A mapping of message dispatchers. */
protected static HashMap _disps = new HashMap();
/** The amount of time after disconnection a user is allowed before
* their session is forcibly ended. */
protected static final long FLUSH_TIME = 7 * 60 * 1000L;
// register our message dispatchers
static {
_disps.put(SubscribeRequest.class, new SubscribeDispatcher());
_disps.put(UnsubscribeRequest.class, new UnsubscribeDispatcher());
_disps.put(ForwardEventRequest.class, new ForwardEventDispatcher());
_disps.put(PingRequest.class, new PingDispatcher());
_disps.put(LogoffRequest.class, new LogoffDispatcher());
}
}
|
// SQLiteStore.java
package com.couchbase.lite.store;
import com.couchbase.lite.BlobKey;
import com.couchbase.lite.ChangesOptions;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.DocumentChange;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Misc;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryOptions;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.ReplicationFilter;
import com.couchbase.lite.Revision;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.TransactionalTask;
import com.couchbase.lite.View;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.storage.ContentValues;
import com.couchbase.lite.storage.Cursor;
import com.couchbase.lite.storage.SQLException;
import com.couchbase.lite.storage.SQLiteStorageEngine;
import com.couchbase.lite.storage.SQLiteStorageEngineFactory;
import com.couchbase.lite.support.RevisionUtils;
import com.couchbase.lite.support.security.SymmetricKey;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.SQLiteUtils;
import com.couchbase.lite.util.TextUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class SQLiteStore implements Store {
public String TAG = Log.TAG_DATABASE;
public static String kDBFilename = "db.sqlite3";
// Default value for maxRevTreeDepth, the max rev depth to preserve in a prune operation
private static final int DEFAULT_MAX_REVS = Integer.MAX_VALUE;
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
public static final String SCHEMA = "" +
// docs
"CREATE TABLE docs ( " +
" doc_id INTEGER PRIMARY KEY, " +
" docid TEXT UNIQUE NOT NULL); " +
" CREATE INDEX docs_docid ON docs(docid); " +
// revs
" CREATE TABLE revs ( " +
" sequence INTEGER PRIMARY KEY AUTOINCREMENT, " +
" doc_id INTEGER NOT NULL REFERENCES docs(doc_id) ON DELETE CASCADE, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" parent INTEGER REFERENCES revs(sequence) ON DELETE SET NULL, " +
" current BOOLEAN, " +
" deleted BOOLEAN DEFAULT 0, " +
" json BLOB, " +
" no_attachments BOOLEAN, " +
" UNIQUE (doc_id, revid)); " +
" CREATE INDEX revs_parent ON revs(parent); " +
" CREATE INDEX revs_by_docid_revid ON revs(doc_id, revid desc, current, deleted); " +
" CREATE INDEX revs_current ON revs(doc_id, current desc, deleted, revid desc); " +
// localdocs
" CREATE TABLE localdocs ( " +
" docid TEXT UNIQUE NOT NULL, " +
" revid TEXT NOT NULL COLLATE REVID, " +
" json BLOB); " +
" CREATE INDEX localdocs_by_docid ON localdocs(docid); " +
// views
" CREATE TABLE views ( " +
" view_id INTEGER PRIMARY KEY, " +
" name TEXT UNIQUE NOT NULL," +
" version TEXT, " +
" lastsequence INTEGER DEFAULT 0," +
" total_docs INTEGER DEFAULT -1); " +
" CREATE INDEX views_by_name ON views(name); " +
// info
" CREATE TABLE info (" +
" key TEXT PRIMARY KEY," +
" value TEXT);" +
// version
" PRAGMA user_version = 17"; // at the end, update user_version
//OPT: Would be nice to use partial indexes but that requires SQLite 3.8 and makes the
// db file only readable by SQLite 3.8+, i.e. the file would not be portable to iOS 8
// which only has SQLite 3.7 :(
// On the revs_parent _index we could add "WHERE parent not null".
// transactionLevel is per thread
static class TransactionLevel extends ThreadLocal<Integer> {
@Override
protected Integer initialValue() {
return 0;
}
}
private String directory;
private String path;
private Manager manager;
private SQLiteStorageEngine storageEngine;
private TransactionLevel transactionLevel;
private StoreDelegate delegate;
private int maxRevTreeDepth;
// Constructor
public SQLiteStore(String directory, Manager manager, StoreDelegate delegate) {
assert (new File(directory).isAbsolute()); // path must be absolute
this.directory = directory;
File dir = new File(directory);
if (!dir.exists() || !dir.isDirectory()) {
throw new IllegalArgumentException("directory '" + directory + "' does not exist or not directory");
}
this.path = new File(directory, kDBFilename).getPath();
this.manager = manager;
this.storageEngine = null;
this.transactionLevel = new TransactionLevel();
this.delegate = delegate;
this.maxRevTreeDepth = DEFAULT_MAX_REVS;
}
// Implementation of Storage
// INITIALIZATION AND CONFIGURATION:
@Override
public boolean databaseExists(String directory) {
return new File(directory, kDBFilename).exists();
}
@Override
public synchronized boolean open() throws CouchbaseLiteException {
// Create the storage engine.
SQLiteStorageEngineFactory factory =
manager.getContext().getSQLiteStorageEngineFactory();
storageEngine = factory.createStorageEngine(manager.isEnableStorageEncryption());
// Try to open the storage engine and stop if we fail.
if (storageEngine == null) {
String msg = "Unable to create a storage engine, fatal error";
Log.e(TAG, msg);
throw new IllegalStateException(msg);
}
boolean isOpenSuccess = false;
try {
// Open database:
storageEngine.open(path);
// Try to decrypt or access the database:
SymmetricKey encryptionKey = delegate.getEncryptionKey();
decrypt(encryptionKey);
isOpenSuccess = true;
} catch (SQLException e) {
String message = "Unable to create a storage engine";
Log.e(TAG, message, e);
throw new CouchbaseLiteException(message, e, Status.DB_ERROR);
} finally {
if (!isOpenSuccess) {
// As an exception will be thrown, no return false is needed here:
storageEngine.close();
}
}
// Stuff we need to initialize every time the sqliteDb opens:
if (!initialize("PRAGMA foreign_keys = ON;")) {
Log.e(TAG, "Error turning on foreign keys");
return false;
}
// Check the user_version number we last stored in the sqliteDb:
int dbVersion = storageEngine.getVersion();
// Incompatible version changes increment the hundreds' place:
if (dbVersion >= 200) {
Log.e(TAG, "Database: Database version (%d) is newer than I know how to work with",
dbVersion);
storageEngine.close();
return false;
}
boolean isNew = (dbVersion == 0);
boolean isSuccessful = false;
// BEGIN TRANSACTION
if (!beginTransaction()) {
storageEngine.close();
return false;
}
try {
if (dbVersion < 17) {
// First-time initialization:
// (Note: Declaring revs.sequence as AUTOINCREMENT means the values will always be
if (!isNew) {
Log.w(TAG, "Database version (%d) is older than I know how to work with",
dbVersion);
storageEngine.close();
return false;
}
if (!initialize(SCHEMA)) {
return false;
}
dbVersion = 17;
}
if (dbVersion < 21) {
// Version 18:
String upgradeSql = "ALTER TABLE revs ADD COLUMN doc_type TEXT; " +
"PRAGMA user_version = 21";
if (!initialize(upgradeSql)) {
return false;
}
dbVersion = 21;
}
if (dbVersion < 101) {
String upgradeSql = "PRAGMA user_version = 101";
if (!initialize(upgradeSql)) {
return false;
}
dbVersion = 101;
}
if (isNew) {
optimizeSQLIndexes(); // runs ANALYZE query
}
// successfully updated storageEngine schema
isSuccessful = true;
} finally {
// END TRANSACTION WITH COMMIT OR ROLLBACK
endTransaction(isSuccessful);
// if failed, close storageEngine before return
if (!isSuccessful) {
storageEngine.close();
}
}
return true;
}
@Override
public void close() {
if (storageEngine != null && storageEngine.isOpen())
storageEngine.close();
storageEngine = null;
}
@Override
public void setDelegate(StoreDelegate delegate) {
this.delegate = delegate;
}
@Override
public StoreDelegate getDelegate() {
return delegate;
}
/**
* Set the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public void setMaxRevTreeDepth(int maxRevTreeDepth) {
this.maxRevTreeDepth = maxRevTreeDepth;
}
/**
* Get the maximum depth of a document's revision tree (or, max length of its revision history.)
* Revisions older than this limit will be deleted during a -compact: operation.
* Smaller values save space, at the expense of making document conflicts somewhat more likely.
*/
@Override
public int getMaxRevTreeDepth() {
return maxRevTreeDepth;
}
// Database Encryption
private void decrypt(SymmetricKey encryptionKey) throws CouchbaseLiteException {
if (encryptionKey != null) {
if (!storageEngine.supportEncryption()) {
Log.w(TAG, "SQLiteStore: encryption not available (app not built with SQLCipher)");
throw new CouchbaseLiteException("Encryption not available",
Status.NOT_IMPLEMENTED);
} else {
try {
storageEngine.execSQL("PRAGMA key = \"x'" + encryptionKey.getHexData() + "'\"");
} catch (SQLException e) {
Log.w(TAG, "SQLiteStore: 'pragma key' failed", e);
throw e;
}
}
}
// Verify that encryption key is correct (or db is unencrypted, if no key given)
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery("SELECT count(*) FROM sqlite_master", null);
if (cursor == null || !cursor.moveToNext()) {
// Backup error:
Log.w(TAG, "SQLiteStore: database is unreadable, unknown error");
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.DB_ERROR);
}
} catch (Exception e) {
Log.w(TAG, "SQLiteStore: database is unreadable", e);
if (e.getMessage() != null &&
e.getMessage().contains("file is encrypted or is not a database (code 26)")) {
throw new CouchbaseLiteException("Cannot decrypt or access the database",
Status.UNAUTHORIZED);
} else {
throw new CouchbaseLiteException(e, Status.DB_ERROR);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
// DATABASE ATTRIBUTES & OPERATIONS:
@Override
public long setInfo(String key, String info) {
ContentValues args = new ContentValues();
args.put("key", key);
args.put("value", info);
return storageEngine.insertWithOnConflict("info", null, args,
SQLiteStorageEngine.CONFLICT_REPLACE);
}
@Override
public String getInfo(String key) {
String result = null;
Cursor cursor = null;
try {
String[] args = {key};
cursor = storageEngine.rawQuery("SELECT value FROM info WHERE key=?", args);
if (cursor.moveToNext()) {
result = cursor.getString(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error querying " + key, e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public int getDocumentCount() {
String sql = "SELECT COUNT(DISTINCT doc_id) FROM revs WHERE current=1 AND deleted=0";
Cursor cursor = null;
int result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getInt(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document count", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* The latest sequence number used. Every new revision is assigned a new sequence number,
* so this property increases monotonically as changes are made to the storageEngine. It can be
* used to check whether the storageEngine has changed between two points in time.
*/
public long getLastSequence() {
String sql = "SELECT MAX(sequence) FROM revs";
Cursor cursor = null;
long result = 0;
try {
cursor = storageEngine.rawQuery(sql, null);
if (cursor.moveToNext()) {
result = cursor.getLong(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting last sequence", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
/**
* Is a transaction active?
*/
@Override
public boolean inTransaction() {
return transactionLevel.get() > 0;
}
@Override
public void compact() throws CouchbaseLiteException {
// Start off by pruning each revision tree's depth:
pruneRevsToMaxDepth(maxRevTreeDepth);
// Remove the JSON of non-current revisions, which is most of the space.
try {
Log.v(TAG, "Deleting JSON of old revisions...");
ContentValues args = new ContentValues();
args.put("json", (String) null);
args.put("doc_type", (String) null);
args.put("no_attachments", 1);
int changes = storageEngine.update("revs", args, "current=0", null);
Log.v(TAG, "... deleted %d revisions", changes);
} catch (SQLException e) {
Log.e(TAG, "Error compacting", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.v(TAG, "Vacuuming SQLite database...");
try {
storageEngine.execSQL("VACUUM");
} catch (SQLException e) {
Log.e(TAG, "Error vacuuming sqliteDb", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
Log.v(TAG, "...Finished database compaction.");
}
@Override
public boolean runInTransaction(TransactionalTask transactionalTask) {
boolean shouldCommit = true;
beginTransaction();
try {
shouldCommit = transactionalTask.run();
} catch (Exception e) {
shouldCommit = false;
Log.e(TAG, e.toString(), e);
throw new RuntimeException(e);
} finally {
endTransaction(shouldCommit);
}
return shouldCommit;
}
// DOCUMENTS:
@Override
public RevisionInternal getDocument(String docID, String revID, boolean withBody) {
long docNumericID = getDocNumericID(docID);
if (docNumericID < 0) {
return null;
}
RevisionInternal result = null;
String sql;
Cursor cursor = null;
try {
cursor = null;
String cols = "revid, deleted, sequence";
if (withBody) {
cols += ", json";
}
if (revID != null) {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? AND revid=? AND json notnull LIMIT 1";
String[] args = {Long.toString(docNumericID), revID};
cursor = storageEngine.rawQuery(sql, args);
} else {
sql = "SELECT " + cols + " FROM revs WHERE revs.doc_id=? and current=1 and deleted=0 ORDER BY revid DESC LIMIT 1";
String[] args = {Long.toString(docNumericID)};
cursor = storageEngine.rawQuery(sql, args);
}
if (cursor.moveToNext()) {
if (revID == null) {
revID = cursor.getString(0);
}
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(docID, revID, deleted);
result.setSequence(cursor.getLong(2));
if (withBody) {
byte[] json = cursor.getBlob(3);
result.setJSON(json);
}
} else {
// revID != null?Status.NOT_FOUND:Status.DELTED
}
} catch (SQLException e) {
Log.e(TAG, "Error getting document with id and rev", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public RevisionInternal loadRevisionBody(RevisionInternal rev)
throws CouchbaseLiteException {
if (rev.getBody() != null && rev.getSequence() != 0) // no-op
return rev;
assert (rev.getDocID() != null && rev.getRevID() != null);
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.NOT_FOUND);
Cursor cursor = null;
Status result = new Status(Status.NOT_FOUND);
try {
String sql = "SELECT sequence, json FROM revs WHERE doc_id=? AND revid=? LIMIT 1";
String[] args = {String.valueOf(docNumericID), rev.getRevID()};
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
byte[] json = cursor.getBlob(1);
if (json != null) {
result.setCode(Status.OK);
rev.setSequence(cursor.getLong(0));
rev.setJSON(json);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error loading revision body", e);
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null) {
cursor.close();
}
}
if (result.getCode() == Status.NOT_FOUND) {
throw new CouchbaseLiteException(result);
}
return rev;
}
@Override
public RevisionInternal getParentRevision(RevisionInternal rev) {
// First get the parent's sequence:
long seq = rev.getSequence();
if (seq > 0) {
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE sequence=?",
new String[]{Long.toString(seq)});
} else {
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0) {
return null;
}
String[] args = new String[]{Long.toString(docNumericID), rev.getRevID()};
seq = SQLiteUtils.longForQuery(storageEngine,
"SELECT parent FROM revs WHERE doc_id=? and revid=?", args);
}
if (seq == 0) {
return null;
}
// Now get its revID and deletion status:
RevisionInternal result = null;
String[] args = {Long.toString(seq)};
String queryString = "SELECT revid, deleted FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revId = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
result = new RevisionInternal(rev.getDocID(), revId, deleted/*, this*/);
result.setSequence(seq);
}
} finally {
cursor.close();
}
return result;
}
/**
* Returns an array of TDRevs in reverse chronological order, starting with the given revision.
*/
@Override
public List<RevisionInternal> getRevisionHistory(RevisionInternal rev) {
String docId = rev.getDocID();
String revId = rev.getRevID();
assert ((docId != null) && (revId != null));
long docNumericId = getDocNumericID(docId);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new ArrayList<RevisionInternal>();
}
String sql = "SELECT sequence, parent, revid, deleted, json isnull FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericId)};
Cursor cursor = null;
List<RevisionInternal> result;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
long lastSequence = 0;
result = new ArrayList<RevisionInternal>();
while (!cursor.isAfterLast()) {
long sequence = cursor.getLong(0);
boolean matches = false;
if (lastSequence == 0) {
matches = revId.equals(cursor.getString(2));
} else {
matches = (sequence == lastSequence);
}
if (matches) {
revId = cursor.getString(2);
boolean deleted = (cursor.getInt(3) > 0);
boolean missing = (cursor.getInt(4) > 0);
RevisionInternal aRev = new RevisionInternal(docId, revId, deleted);
aRev.setMissing(missing);
aRev.setSequence(cursor.getLong(0));
result.add(aRev);
lastSequence = cursor.getLong(1);
if (lastSequence == 0) {
break;
}
}
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting revision history", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
private RevisionList getAllRevisions(String docId, long docNumericID, boolean onlyCurrent) {
String sql = null;
if (onlyCurrent)
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? AND current ORDER BY sequence DESC";
else
sql = "SELECT sequence, revid, deleted FROM revs " +
"WHERE doc_id=? ORDER BY sequence DESC";
String[] args = {Long.toString(docNumericID)};
Cursor cursor = storageEngine.rawQuery(sql, args);
RevisionList result = null;
try {
cursor.moveToNext();
result = new RevisionList();
while (!cursor.isAfterLast()) {
RevisionInternal rev = new RevisionInternal(docId,
cursor.getString(1),
(cursor.getInt(2) > 0));
rev.setSequence(cursor.getLong(0));
result.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
return null;
} finally {
if (cursor != null)
cursor.close();
}
return result;
}
@Override
public List<String> getPossibleAncestorRevisionIDs(RevisionInternal rev, int limit,
AtomicBoolean onlyAttachments) {
int generation = rev.getGeneration();
if (generation <= 1)
return null;
long docNumericID = getDocNumericID(rev.getDocID());
if (docNumericID <= 0)
return null;
List<String> revIDs = new ArrayList<String>();
int sqlLimit = limit > 0 ? (int) limit : -1; // SQL uses -1, not 0, to denote 'no limit'
String sql = "SELECT revid, sequence FROM revs WHERE doc_id=? and revid < ?" +
" and deleted=0 and json not null" +
" ORDER BY sequence DESC LIMIT ?";
String[] args = {Long.toString(docNumericID), generation + "-", Integer.toString(sqlLimit)};
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
if (onlyAttachments != null && revIDs.size() == 0) {
onlyAttachments.set(sequenceHasAttachments(cursor.getLong(1)));
}
revIDs.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all revisions of document", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return revIDs;
}
@Override
public String findCommonAncestor(RevisionInternal rev, List<String> revIDs) {
String result = null;
if (revIDs.size() == 0)
return null;
String docId = rev.getDocID();
long docNumericID = getDocNumericID(docId);
if (docNumericID <= 0)
return null;
String quotedRevIds = TextUtils.joinQuoted(revIDs);
String sql = "SELECT revid FROM revs " +
"WHERE doc_id=? and revid in (" + quotedRevIds + ") and revid <= ? " +
"ORDER BY revid DESC LIMIT 1";
String[] args = {Long.toString(docNumericID)};
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
if (!cursor.isAfterLast()) {
result = cursor.getString(0);
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all revisions of document", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
@Override
public int findMissingRevisions(RevisionList touchRevs) throws SQLException {
int numRevisionsRemoved = 0;
if (touchRevs.size() == 0) {
return numRevisionsRemoved;
}
String quotedDocIds = TextUtils.joinQuoted(touchRevs.getAllDocIds());
String quotedRevIds = TextUtils.joinQuoted(touchRevs.getAllRevIds());
String sql = "SELECT docid, revid FROM revs, docs " +
"WHERE docid IN (" +
quotedDocIds +
") AND revid in (" +
quotedRevIds + ")" +
" AND revs.doc_id == docs.doc_id";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
RevisionInternal rev = touchRevs.revWithDocIdAndRevId(cursor.getString(0),
cursor.getString(1));
if (rev != null) {
touchRevs.remove(rev);
numRevisionsRemoved += 1;
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return numRevisionsRemoved;
}
/**
* - (NSSet*) findAllAttachmentKeys: (NSError**)outError
*/
@Override
public Set<BlobKey> findAllAttachmentKeys() throws CouchbaseLiteException {
Set<BlobKey> allKeys = new HashSet<BlobKey>();
String sql = "SELECT json FROM revs WHERE no_attachments != 1";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(sql, null);
cursor.moveToNext();
while (!cursor.isAfterLast()) {
byte[] json = cursor.getBlob(0);
if (json != null && json.length > 0) {
try {
Map<String, Object> docProperties = Manager.getObjectMapper().readValue(json, Map.class);
if (docProperties.containsKey("_attachments")) {
Map<String, Object> attachments = (Map<String, Object>) docProperties.get("_attachments");
Iterator<String> itr = attachments.keySet().iterator();
while (itr.hasNext()) {
String name = itr.next();
Map<String, Object> attachment = (Map<String, Object>) attachments.get(name);
String digest = (String) attachment.get("digest");
BlobKey key = new BlobKey(digest);
allKeys.add(key);
}
}
} catch (IOException e) {
Log.e(TAG, e.toString(), e);
}
}
cursor.moveToNext();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return allKeys;
}
/**
* - (CBLQueryIteratorBlock) getAllDocs: (CBLQueryOptions*)options
* status: (CBLStatus*)outStatus
*/
@Override
public Map<String, Object> getAllDocs(QueryOptions options) throws CouchbaseLiteException {
Map<String, Object> result = new HashMap<String, Object>();
List<QueryRow> rows = new ArrayList<QueryRow>();
if (options == null) {
options = new QueryOptions();
}
boolean includeDeletedDocs = (options.getAllDocsMode() == Query.AllDocsMode.INCLUDE_DELETED);
long updateSeq = 0;
if (options.isUpdateSeq()) {
updateSeq = getLastSequence(); // TODO: needs to be atomic with the following SELECT
}
// Generate the SELECT statement, based on the options:
StringBuffer sql = new StringBuffer("SELECT revs.doc_id, docid, revid, sequence");
if (options.isIncludeDocs()) {
sql.append(", json, no_attachments");
}
if (includeDeletedDocs) {
sql.append(", deleted");
}
sql.append(" FROM revs, docs WHERE");
if (options.getKeys() != null) {
if (options.getKeys().size() == 0) {
return result;
}
String commaSeperatedIds = TextUtils.joinQuotedObjects(options.getKeys());
sql.append(String.format(" revs.doc_id IN (SELECT doc_id FROM docs WHERE docid IN (%s)) AND",
commaSeperatedIds));
}
sql.append(" docs.doc_id = revs.doc_id AND current=1");
if (!includeDeletedDocs) {
sql.append(" AND deleted=0");
}
List<String> args = new ArrayList<String>();
Object minKey = options.getStartKey();
Object maxKey = options.getEndKey();
boolean inclusiveMin = true;
boolean inclusiveMax = options.isInclusiveEnd();
if (options.isDescending()) {
minKey = maxKey;
maxKey = options.getStartKey();
inclusiveMin = inclusiveMax;
inclusiveMax = true;
}
if (minKey != null) {
assert (minKey instanceof String);
sql.append((inclusiveMin ? " AND docid >= ?" : " AND docid > ?"));
args.add((String) minKey);
}
if (maxKey != null) {
assert (maxKey instanceof String);
maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
sql.append((inclusiveMax ? " AND docid <= ?" : " AND docid < ?"));
args.add((String) maxKey);
}
sql.append(
String.format(
" ORDER BY docid %s, %s revid DESC LIMIT ? OFFSET ?",
(options.isDescending() ? "DESC" : "ASC"),
(includeDeletedDocs ? "deleted ASC," : "")
)
);
args.add(Integer.toString(options.getLimit()));
args.add(Integer.toString(options.getSkip()));
// Now run the database query:
Cursor cursor = null;
Map<String, QueryRow> docs = new HashMap<String, QueryRow>();
try {
// Get row values now, before the code below advances 'cursor':
cursor = storageEngine.rawQuery(sql.toString(), args.toArray(new String[args.size()]));
boolean keepGoing = cursor.moveToNext(); // Go to first result row
while (keepGoing) {
long docNumericID = cursor.getLong(0);
String docID = cursor.getString(1);
String revID = cursor.getString(2);
long sequence = cursor.getLong(3);
boolean deleted = includeDeletedDocs && cursor.getInt(getDeletedColumnIndex(options)) > 0;
RevisionInternal docRevision = null;
if (options.isIncludeDocs()) {
//docRevision = revision(docID, revID, deleted, sequence, cursor.getBlob(4));
byte[] json = cursor.getBlob(4);
Map<String, Object> properties = documentPropertiesFromJSON(json, docID, revID,
false, sequence);
docRevision = revision(
docID, // docID
revID, // revID
false, // deleted
sequence, // sequence
properties// properties
);
}
// Iterate over following rows with the same doc_id -- these are conflicts.
// Skip them, but collect their revIDs if the 'conflicts' option is set:
List<String> conflicts = new ArrayList<String>();
while (((keepGoing = cursor.moveToNext()) == true) && cursor.getLong(0) == docNumericID) {
if (options.getAllDocsMode() == Query.AllDocsMode.SHOW_CONFLICTS ||
options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS) {
if (conflicts.isEmpty()) {
conflicts.add(revID);
}
conflicts.add(cursor.getString(2));
}
}
if (options.getAllDocsMode() == Query.AllDocsMode.ONLY_CONFLICTS && conflicts.isEmpty())
continue;
Map<String, Object> value = new HashMap<String, Object>();
value.put("rev", revID);
value.put("_conflicts", conflicts);
if (includeDeletedDocs) {
value.put("deleted", (deleted ? true : null));
}
QueryRow change = new QueryRow(docID,
sequence,
docID,
value,
docRevision,
null);
if (options.getKeys() != null)
docs.put(docID, change);
// TODO: In the future, we need to implement CBLRowPassesFilter() in CBLView+Querying.m
else if (options.getPostFilter() == null || options.getPostFilter().apply(change))
rows.add(change);
}
// If given doc IDs, sort the output into that order, and add entries for missing docs:
if (options.getKeys() != null) {
for (Object docIdObject : options.getKeys()) {
if (docIdObject instanceof String) {
String docID = (String) docIdObject;
QueryRow change = docs.get(docID);
if (change == null) {
Map<String, Object> value = new HashMap<String, Object>();
long docNumericID = getDocNumericID(docID);
if (docNumericID > 0) {
boolean deleted;
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String revID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (revID != null) {
value.put("rev", revID);
value.put("deleted", true);
}
}
change = new QueryRow((value != null ? docID : null), 0, docID, value, null, null);
}
// TODO add options.filter
rows.add(change);
}
}
}
} catch (SQLException e) {
Log.e(TAG, "Error getting all docs", e);
throw new CouchbaseLiteException("Error getting all docs", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
result.put("rows", rows);
result.put("total_rows", rows.size());
result.put("offset", options.getSkip());
if (updateSeq != 0) {
result.put("update_seq", updateSeq);
}
return result;
}
@Override
public RevisionList changesSince(long lastSequence,
ChangesOptions options,
ReplicationFilter filter,
Map<String, Object> filterParams) {
// http://wiki.apache.org/couchdb/HTTP_database_API#Changes
if (options == null) {
options = new ChangesOptions();
}
boolean includeDocs = options.isIncludeDocs() || (filter != null);
String additionalSelectColumns = "";
if (includeDocs) {
additionalSelectColumns = ", json";
}
String sql = "SELECT sequence, revs.doc_id, docid, revid, deleted" + additionalSelectColumns + " FROM revs, docs "
+ "WHERE sequence > ? AND current=1 "
+ "AND revs.doc_id = docs.doc_id "
+ "ORDER BY revs.doc_id, revid DESC";
String[] args = {Long.toString(lastSequence)};
Cursor cursor = null;
RevisionList changes = null;
try {
cursor = storageEngine.rawQuery(sql, args);
cursor.moveToNext();
changes = new RevisionList();
long lastDocId = 0;
while (!cursor.isAfterLast()) {
if (!options.isIncludeConflicts()) {
// Only count the first rev for a given doc (the rest will be losing conflicts):
long docNumericId = cursor.getLong(1);
if (docNumericId == lastDocId) {
cursor.moveToNext();
continue;
}
lastDocId = docNumericId;
}
RevisionInternal rev = new RevisionInternal(cursor.getString(2), cursor.getString(3), (cursor.getInt(4) > 0));
rev.setSequence(cursor.getLong(0));
if (includeDocs)
rev.setJSON(cursor.getBlob(5));
if (delegate.runFilter(filter, filterParams, rev))
changes.add(rev);
cursor.moveToNext();
}
} catch (SQLException e) {
Log.e(TAG, "Error looking for changes", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
if (options.isSortBySequence()) {
changes.sortBySequence();
}
changes.limit(options.getLimit());
return changes;
}
// INSERTION / DELETION:
/**
* Creates a new revision of a document.
* On success, before returning the new CBL_Revision, the implementation will also call the
* delegate's -databaseStorageChanged: method to give it more details about the change.
*
* @param docID The document ID, or nil if an ID should be generated at random.
* @param prevRevID The parent revision ID, or nil if creating a new document.
* @param properties The new revision's properties. (Metadata other than "_attachments" ignored.)
* @param deleting YES if this revision is a deletion.
* @param allowConflict YES if this operation is allowed to create a conflict; otherwise a 409,
* status will be returned if the parent revision is not a leaf.
* @param validationBlock If non-nil, this block will be called before the revision is added.
* It's given the parent revision, with its properties if available, and can reject
* the operation by returning an error status.
* @param outStatus On return a status will be stored here. Note that on success, the
* status should be 201 for a created revision but 200 for a deletion.
* @return The new revision, with its revID and sequence filled in, or nil on error.
*/
@Override
@InterfaceAudience.Private
public RevisionInternal add(
String docID,
String prevRevID,
Map<String, Object> properties,
boolean deleting,
boolean allowConflict,
StorageValidation validationBlock,
Status outStatus)
throws CouchbaseLiteException {
byte[] json;
if (properties != null && properties.size() > 0) {
json = RevisionUtils.asCanonicalJSON(properties);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
} else {
json = "{}".getBytes();
}
RevisionInternal newRev = null;
String winningRevID = null;
boolean inConflict = false;
beginTransaction();
// try - finally for beginTransaction() and endTransaction()
try {
//// PART I: In which are performed lookups and validations prior to the insert...
// Get the doc's numeric ID (doc_id) and its current winning revision:
AtomicBoolean isNewDoc = new AtomicBoolean(prevRevID == null);
long docNumericID = -1;
if (docID != null) {
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
// TODO: error
throw new CouchbaseLiteException(Status.UNKNOWN);
} else {
docNumericID = 0;
isNewDoc.set(true);
}
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean wasConflicted = new AtomicBoolean(false);
String oldWinningRevID = null;
if (!isNewDoc.get()) {
// Look up which rev is the winner, before this insertion
//OPT: This rev ID could be cached in the 'docs' row
oldWinningRevID = winningRevIDOfDocNumericID(docNumericID, oldWinnerWasDeletion, wasConflicted);
}
long parentSequence = 0;
if (prevRevID != null) {
// Replacing: make sure given prevRevID is current & find its sequence number:
if (isNewDoc.get())
throw new CouchbaseLiteException(Status.NOT_FOUND);
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, !allowConflict);
if (parentSequence <= 0) { // -1 if not found
// Not found: either a 404 or a 409, depending on whether there is any current revision
if (!allowConflict && existsDocument(docID, null)) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} else {
// Inserting first revision.
if (deleting && docID != null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (existsDocument(docID, null))
throw new CouchbaseLiteException(Status.CONFLICT);
else
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
if (docID != null) {
// Inserting first revision, with docID given (PUT):
// Doc ID exists; check whether current winning revision is deleted:
if (oldWinnerWasDeletion.get() == true) {
prevRevID = oldWinningRevID;
parentSequence = getSequenceOfDocument(docNumericID, prevRevID, false);
} else if (oldWinningRevID != null) {
// The current winning revision is not deleted, so this is a conflict
throw new CouchbaseLiteException(Status.CONFLICT);
}
} else {
// Inserting first revision, with no docID given (POST): generate a unique docID:
docID = Misc.CreateUUID();
docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
return null;
}
}
// There may be a conflict if (a) the document was already in conflict, or
inConflict = wasConflicted.get() ||
(!deleting &&
prevRevID != null &&
oldWinningRevID != null &&
!prevRevID.equals(oldWinningRevID));
//// PART II: In which we prepare for insertion...
// Bump the revID and update the JSON:
String newRevId = delegate.generateRevID(json, deleting, prevRevID);
if (newRevId == null)
throw new CouchbaseLiteException(Status.BAD_ID); // invalid previous revID (no numeric prefix)
assert (docID != null);
newRev = new RevisionInternal(docID, newRevId, deleting);
if (properties != null) {
properties.put("_id", docID);
properties.put("_rev", newRevId);
newRev.setProperties(properties);
}
if (validationBlock != null) {
// Fetch the previous revision and validate the new one against it:
RevisionInternal prevRev = null;
if (prevRevID != null)
prevRev = new RevisionInternal(docID, prevRevID, false);
Status status = validationBlock.validate(newRev, prevRev, prevRevID);
if (status.isError()) {
outStatus.setCode(status.getCode());
throw new CouchbaseLiteException(status);
}
}
// Don't store a SQL null in the 'json' column -- I reserve it to mean that the revision data
// is missing due to compaction or replication.
// Instead, store an empty zero-length blob.
if (json == null)
json = new byte[0];
//// PART III: In which the actual insertion finally takes place:
boolean hasAttachments = properties == null ? false : properties.get("_attachments") != null;
String docType = properties == null ? null : (String) properties.get("type");
long sequence = insertRevision(newRev,
docNumericID,
parentSequence,
true,
hasAttachments,
json,
docType);
if (sequence <= 0) {
// The insert failed. If it was due to a constraint violation, that means a revision
// already exists with identical contents and the same parent rev. We can ignore this
// insert call, then.
// TODO - figure out storageEngine error code
// NOTE - In AndroidSQLiteStorageEngine.java, CBL Android uses insert() method of SQLiteDatabase
// which return -1 for error case. Instead of insert(), should use insertOrThrow method()
// which throws detailed error code. Need to check with SQLiteDatabase.CONFLICT_FAIL.
// However, returning after updating parentSequence might not cause any problem.
//if (_fmdb.lastErrorCode != SQLITE_CONSTRAINT)
// return null;
Log.w(TAG, "Duplicate rev insertion: " + docID + " / " + newRevId);
newRev.setBody(null);
// don't return yet; update the parent's current just to be sure (see #316 (iOS #509))
}
// Make replaced rev non-current:
if (parentSequence > 0) {
try {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
storageEngine.update("revs", args, "sequence=?", new String[]{String.valueOf(parentSequence)});
} catch (SQLException e) {
Log.e(TAG, "Error setting parent rev non-current", e);
storageEngine.delete("revs", "sequence=?", new String[]{String.valueOf(sequence)});
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
if (sequence <= 0) {
// duplicate rev; see above
outStatus.setCode(Status.OK);
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), newRev);
// Success!
if (deleting) {
outStatus.setCode(Status.OK);
} else {
outStatus.setCode(Status.CREATED);
}
} finally {
endTransaction(outStatus.isSuccessful());
}
//// EPILOGUE: A change notification is sent...
if (newRev.getSequence() != 0)
delegate.databaseStorageChanged(new DocumentChange(newRev, winningRevID, inConflict, null));
return newRev;
}
/**
* Inserts an already-existing revision replicated from a remote sqliteDb.
* <p/>
* It must already have a revision ID. This may create a conflict! The revision's history must be given; ancestor revision IDs that don't already exist locally will create phantom revisions with no content.
*
* @exclude in CBLDatabase+Insertion.m
* - (CBLStatus) forceInsert: (CBL_Revision*)inRev
* revisionHistory: (NSArray*)history // in *reverse* order, starting with rev's revID
* source: (NSURL*)source
*/
@Override
@InterfaceAudience.Private
public void forceInsert(RevisionInternal inRev,
List<String> history,
StorageValidation validationBlock,
URL source)
throws CouchbaseLiteException {
Status status = new Status(Status.UNKNOWN);
RevisionInternal rev = inRev.copy();
rev.setSequence(0);
String docID = rev.getDocID();
String winningRevID = null;
AtomicBoolean inConflict = new AtomicBoolean(false);
boolean success = false;
beginTransaction();
try {
// First look up the document's row-id and all locally-known revisions of it:
Map<String, RevisionInternal> localRevs = null;
String oldWinningRevID = null;
AtomicBoolean oldWinnerWasDeletion = new AtomicBoolean(false);
AtomicBoolean isNewDoc = new AtomicBoolean(history.size() == 1);
long docNumericID = createOrGetDocNumericID(docID, isNewDoc);
if (docNumericID <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
if (!isNewDoc.get()) {
RevisionList localRevsList = getAllRevisions(docID, docNumericID, false);
if (localRevsList == null)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
localRevs = new HashMap<String, RevisionInternal>();
for (RevisionInternal r : localRevsList)
localRevs.put(r.getRevID(), r);
// Look up which rev is the winner, before this insertion
oldWinningRevID = winningRevIDOfDocNumericID(
docNumericID,
oldWinnerWasDeletion,
inConflict);
}
// Validate against the latest common ancestor:
if (validationBlock != null) {
RevisionInternal oldRev = null;
for (int i = 1; i < history.size(); i++) {
oldRev = (localRevs != null) ? localRevs.get(history.get(i)) : null;
if (oldRev != null) {
break;
}
}
String parentRevId = (history.size() > 1) ? history.get(1) : null;
Status tmpStatus = validationBlock.validate(rev, oldRev, parentRevId);
if (tmpStatus.isError()) {
throw new CouchbaseLiteException(tmpStatus);
}
}
// Walk through the remote history in chronological order, matching each revision ID to
// a local revision. When the list diverges, start creating blank local revisions to
// fill in the local history:
long sequence = 0;
long localParentSequence = 0;
for (int i = history.size() - 1; i >= 0; --i) {
String revID = history.get(i);
RevisionInternal localRev = (localRevs != null) ? localRevs.get(revID) : null;
if (localRev != null) {
// This revision is known locally. Remember its sequence as the parent of
// the next one:
sequence = localRev.getSequence();
assert (sequence > 0);
localParentSequence = sequence;
} else {
// This revision isn't known, so add it:
RevisionInternal newRev = null;
byte[] json = null;
String docType = null;
boolean current = false;
if (i == 0) {
// Hey, this is the leaf revision we're inserting:
newRev = rev;
json = RevisionUtils.asCanonicalJSON(inRev);
if (json == null)
throw new CouchbaseLiteException(Status.BAD_JSON);
docType = (String) rev.getObject("type");
current = true;
} else {
// It's an intermediate parent, so insert a stub:
newRev = new RevisionInternal(docID, revID, false);
}
// Insert it:
sequence = insertRevision(
newRev,
docNumericID,
sequence,
current,
(newRev.getAttachments() != null && newRev.getAttachments().size() > 0),
json,
docType);
if (sequence <= 0)
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
if (localParentSequence == sequence) {
success = true; // No-op: No new revisions were inserted.
status.setCode(Status.OK);
}
// Mark the latest local rev as no longer current:
else if (localParentSequence > 0) {
ContentValues args = new ContentValues();
args.put("current", 0);
args.put("doc_type", (String) null);
String[] whereArgs = {Long.toString(localParentSequence)};
int numRowsChanged = 0;
try {
numRowsChanged = storageEngine.update("revs", args, "sequence=? AND current!=0", whereArgs);
if (numRowsChanged == 0)
inConflict.set(true); // local parent wasn't a leaf, ergo we just created a branch
} catch (SQLException e) {
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
}
}
if (!success) {
// Figure out what the new winning rev ID is:
winningRevID = winner(docNumericID, oldWinningRevID, oldWinnerWasDeletion.get(), rev);
success = true;
status.setCode(Status.CREATED);
}
} catch (SQLException e) {
throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(success);
}
// Notify and return:
if (status.getCode() == Status.CREATED)
delegate.databaseStorageChanged(new DocumentChange(rev, winningRevID, inConflict.get(), source));
else if (status.isError())
throw new CouchbaseLiteException(status);
}
@Override
@InterfaceAudience.Private
public Map<String, Object> purgeRevisions(final Map<String, List<String>> docsToRevs) {
final Map<String, Object> result = new HashMap<String, Object>();
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
for (String docID : docsToRevs.keySet()) {
long docNumericID = getDocNumericID(docID);
if (docNumericID == -1) {
continue; // no such document, skip it
}
List<String> revsPurged = new ArrayList<String>();
List<String> revIDs = (List<String>) docsToRevs.get(docID);
if (revIDs == null) {
return false;
} else if (revIDs.size() == 0) {
revsPurged = new ArrayList<String>();
} else if (revIDs.contains("*")) {
// Delete all revisions if magic "*" revision ID is given:
try {
String[] args = {Long.toString(docNumericID)};
storageEngine.execSQL("DELETE FROM revs WHERE doc_id=?", args);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions", e);
return false;
}
revsPurged = new ArrayList<String>();
revsPurged.add("*");
} else {
// Iterate over all the revisions of the doc, in reverse sequence order.
// Keep track of all the sequences to delete, i.e. the given revs and ancestors,
// but not any non-given leaf revs or their ancestors.
Cursor cursor = null;
try {
String[] args = {Long.toString(docNumericID)};
String queryString = "SELECT revid, sequence, parent FROM revs WHERE doc_id=? ORDER BY sequence DESC";
cursor = storageEngine.rawQuery(queryString, args);
if (!cursor.moveToNext()) {
Log.w(TAG, "No results for query: %s", queryString);
return false;
}
Set<Long> seqsToPurge = new HashSet<Long>();
Set<Long> seqsToKeep = new HashSet<Long>();
Set<String> revsToPurge = new HashSet<String>();
while (!cursor.isAfterLast()) {
String revID = cursor.getString(0);
long sequence = cursor.getLong(1);
long parent = cursor.getLong(2);
if (seqsToPurge.contains(sequence) || revIDs.contains(revID) && !seqsToKeep.contains(sequence)) {
// Purge it and maybe its parent:
seqsToPurge.add(sequence);
revsToPurge.add(revID);
if (parent > 0) {
seqsToPurge.add(parent);
}
} else {
// Keep it and its parent:
seqsToPurge.remove(sequence);
revsToPurge.remove(revID);
seqsToKeep.add(parent);
}
cursor.moveToNext();
}
seqsToPurge.removeAll(seqsToKeep);
Log.i(TAG, "Purging doc '%s' revs (%s); asked for (%s)", docID, revsToPurge, revIDs);
if (seqsToPurge.size() > 0) {
// Now delete the sequences to be purged.
String seqsToPurgeList = TextUtils.join(",", seqsToPurge);
String sql = String.format("DELETE FROM revs WHERE sequence in (%s)", seqsToPurgeList);
try {
storageEngine.execSQL(sql);
} catch (SQLException e) {
Log.e(TAG, "Error deleting revisions via: " + sql, e);
return false;
}
}
revsPurged.addAll(revsToPurge);
} catch (SQLException e) {
Log.e(TAG, "Error getting revisions", e);
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
result.put(docID, revsPurged);
}
return true;
}
});
return result;
}
// VIEWS:
/**
* Instantiates storage for a view.
*
* @param name The name of the view
* @param create If YES, the view should be created; otherwise it must already exist
* @return Storage for the view, or nil if create=NO and it doesn't exist.
*/
public ViewStore getViewStorage(String name, boolean create) {
try {
return new SQLiteViewStore(this, name, create);
}catch(CouchbaseLiteException ex){
return null;
}
}
@Override
public List<String> getAllViewNames() {
Cursor cursor = null;
List<String> result = null;
try {
cursor = storageEngine.rawQuery("SELECT name FROM views", null);
cursor.moveToNext();
result = new ArrayList<String>();
while (!cursor.isAfterLast()) {
//result.add(delegate.getView(cursor.getString(0)));
result.add(cursor.getString(0));
cursor.moveToNext();
}
} catch (Exception e) {
Log.e(TAG, "Error getting all views", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return result;
}
// LOCAL DOCS:
@Override
public RevisionInternal getLocalDocument(String docID, String revID) {
// docID already should contain "_local/" prefix
RevisionInternal result = null;
Cursor cursor = null;
try {
String[] args = {docID};
cursor = storageEngine.rawQuery("SELECT revid, json FROM localdocs WHERE docid=?", args);
if (cursor.moveToNext()) {
String gotRevID = cursor.getString(0);
if (revID != null && (!revID.equals(gotRevID))) {
return null;
}
byte[] json = cursor.getBlob(1);
Map<String, Object> properties = null;
try {
properties = Manager.getObjectMapper().readValue(json, Map.class);
properties.put("_id", docID);
properties.put("_rev", gotRevID);
result = new RevisionInternal(docID, gotRevID, false);
result.setProperties(properties);
} catch (Exception e) {
Log.w(TAG, "Error parsing local doc JSON", e);
return null;
}
}
return result;
} catch (SQLException e) {
Log.e(TAG, "Error getting local document", e);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@Override
public RevisionInternal putLocalRevision(RevisionInternal revision, String prevRevID, boolean obeyMVCC)
throws CouchbaseLiteException {
String docID = revision.getDocID();
if (!docID.startsWith("_local/")) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (!revision.isDeleted()) {
// PUT:
byte[] json = RevisionUtils.asCanonicalJSON(revision);
String newRevID;
if (prevRevID != null) {
int generation = RevisionInternal.generationFromRevID(prevRevID);
if (generation == 0) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
newRevID = Integer.toString(++generation) + "-local";
ContentValues values = new ContentValues();
values.put("revid", newRevID);
values.put("json", json);
String[] whereArgs = {docID, prevRevID};
try {
int rowsUpdated = storageEngine.update("localdocs", values, "docid=? AND revid=?", whereArgs);
if (rowsUpdated == 0) {
throw new CouchbaseLiteException(Status.CONFLICT);
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
} else {
newRevID = "1-local";
ContentValues values = new ContentValues();
values.put("docid", docID);
values.put("revid", newRevID);
values.put("json", json);
try {
storageEngine.insertWithOnConflict("localdocs", null, values, SQLiteStorageEngine.CONFLICT_IGNORE);
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
return revision.copyWithDocID(docID, newRevID);
} else {
// DELETE:
deleteLocalDocument(docID, prevRevID);
return revision;
}
}
@Override
public RevisionList getAllRevisions(String docID, boolean onlyCurrent) {
long docNumericId = getDocNumericID(docID);
if (docNumericId < 0) {
return null;
} else if (docNumericId == 0) {
return new RevisionList();
} else {
return getAllRevisions(docID, docNumericId, onlyCurrent);
}
}
// Internal (PROTECTED & PRIVATE) METHODS
protected SQLiteStorageEngine getStorageEngine() {
return storageEngine;
}
private boolean existsDocument(String docID, String revID) {
return getDocument(docID, revID, false) != null;
}
private void deleteLocalDocument(String docID, String revID) throws CouchbaseLiteException {
if (docID == null) {
throw new CouchbaseLiteException(Status.BAD_REQUEST);
}
if (revID == null) {
// Didn't specify a revision to delete: 404 or a 409, depending
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
String[] whereArgs = {docID, revID};
try {
int rowsDeleted = storageEngine.delete("localdocs", "docid=? AND revid=?", whereArgs);
if (rowsDeleted == 0) {
if (getLocalDocument(docID, null) != null) {
throw new CouchbaseLiteException(Status.CONFLICT);
} else {
throw new CouchbaseLiteException(Status.NOT_FOUND);
}
}
} catch (SQLException e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Returns the rev ID of the 'winning' revision of this document, and whether it's deleted.
* <p/>
* in CBLDatabase+Internal.m
* - (NSString*) winningRevIDOfDocNumericID: (SInt64)docNumericID
* isDeleted: (BOOL*)outIsDeleted
* isConflict: (BOOL*)outIsConflict // optional
* status: (CBLStatus*)outStatus
*/
protected String winningRevIDOfDocNumericID(long docNumericId,
AtomicBoolean outIsDeleted,
AtomicBoolean outIsConflict) // optional
throws CouchbaseLiteException {
assert (docNumericId > 0);
Cursor cursor = null;
String sql = "SELECT revid, deleted FROM revs" +
" WHERE doc_id=? and current=1" +
" ORDER BY deleted asc, revid desc LIMIT ?";
long limit = (outIsConflict != null && outIsConflict.get()) ? 2 : 1;
String[] args = {Long.toString(docNumericId), Long.toString(limit)};
String revID = null;
try {
cursor = storageEngine.rawQuery(sql, args);
if (cursor.moveToNext()) {
revID = cursor.getString(0);
outIsDeleted.set(cursor.getInt(1) > 0);
// The document is in conflict if there are two+ result rows that are not deletions.
if (outIsConflict != null) {
outIsConflict.set(!outIsDeleted.get() && cursor.moveToNext() && !(cursor.getInt(1) > 0));
}
} else {
outIsDeleted.set(false);
if (outIsConflict != null) {
outIsConflict.set(false);
}
}
} catch (SQLException e) {
Log.e(TAG, "Error", e);
throw new CouchbaseLiteException("Error", e, new Status(Status.INTERNAL_SERVER_ERROR));
} finally {
if (cursor != null) {
cursor.close();
}
}
return revID;
}
protected void optimizeSQLIndexes() {
Log.v(Log.TAG_DATABASE, "calls optimizeSQLIndexes()");
final long currentSequence = getLastSequence();
if (currentSequence > 0) {
final long lastOptimized = getLastOptimized();
if (lastOptimized <= currentSequence / 10) {
runInTransaction(new TransactionalTask() {
@Override
public boolean run() {
Log.i(Log.TAG_DATABASE, "%s: Optimizing SQL indexes (curSeq=%d, last run at %d)",
this, currentSequence, lastOptimized);
storageEngine.execSQL("ANALYZE");
storageEngine.execSQL("ANALYZE sqlite_master");
setInfo("last_optimized", String.valueOf(currentSequence));
return true;
}
});
}
}
}
/**
* Begins a storageEngine transaction. Transactions can nest.
* Every beginTransaction() must be balanced by a later endTransaction()
* <p/>
* Notes: 1. SQLiteDatabase.beginTransaction() supported nested transaction. But, in case
* nested transaction rollbacked, it also rollbacks outer transaction too.
* This is not ideal behavior for CBL
* 2. SAVEPOINT...RELEASE supports nested transaction. But Android API 14 and 15,
* it throws Exception. I assume it is Android bug. As CBL need to support from API 10
* . So it does not work for CBL.
* 3. Using Transaction for outer/1st level of transaction and inner/2nd level of transaction
* works with CBL requirement.
* 4. CBL Android and Java uses Thread, So it is better to use SQLiteDatabase.beginTransaction()
* for outer/1st level transaction. if we use BEGIN...COMMIT and SAVEPOINT...RELEASE,
* we need to implement wrapper of BEGIN...COMMIT and SAVEPOINT...RELEASE to be
* Thread-safe.
*/
protected boolean beginTransaction() {
int tLevel = transactionLevel.get();
try {
// Outer (level 0) transaction. Use SQLiteDatabase.beginTransaction()
if (tLevel == 0) {
storageEngine.beginTransaction();
}
// Inner (level 1 or higher) transaction. Use SQLite's SAVEPOINT
else {
storageEngine.execSQL("SAVEPOINT cbl_" + Integer.toString(tLevel));
}
Log.v(Log.TAG_DATABASE, "%s Begin transaction (level %d)", Thread.currentThread().getName(), tLevel);
transactionLevel.set(++tLevel);
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling beginTransaction()", e);
return false;
}
return true;
}
/**
* Commits or aborts (rolls back) a transaction.
*
* @param commit If true, commits; if false, aborts and rolls back, undoing all changes made
* since the matching -beginTransaction call, *including* any committed nested
* transactions.
* @exclude
*/
protected boolean endTransaction(boolean commit) {
int tLevel = transactionLevel.get();
assert (tLevel > 0);
transactionLevel.set(--tLevel);
// Outer (level 0) transaction. Use SQLiteDatabase.setTransactionSuccessful() and SQLiteDatabase.endTransaction()
if (tLevel == 0) {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
storageEngine.setTransactionSuccessful();
storageEngine.endTransaction();
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.endTransaction();
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
}
// Inner (level 1 or higher) transaction: Use SQLite's ROLLBACK and RELEASE
else {
if (commit) {
Log.v(Log.TAG_DATABASE, "%s Committing transaction (level %d)", Thread.currentThread().getName(), tLevel);
} else {
Log.v(Log.TAG_DATABASE, "%s CANCEL transaction (level %d)", Thread.currentThread().getName(), tLevel);
try {
storageEngine.execSQL(";ROLLBACK TO cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
try {
storageEngine.execSQL("RELEASE cbl_" + Integer.toString(tLevel));
} catch (SQLException e) {
Log.e(Log.TAG_DATABASE, Thread.currentThread().getName() + " Error calling endTransaction()", e);
return false;
}
}
if (delegate != null)
delegate.storageExitedTransaction(commit);
return true;
}
protected Map<String, Object> documentPropertiesFromJSON(byte[] json, String docID,
String revID, boolean deleted,
long sequence) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setMissing(json == null);
Map<String, Object> docProperties = null;
if (json == null || json.length == 0 || (json.length == 2 && json.equals("{}"))) {
docProperties = new HashMap<String, Object>();
} else {
try {
docProperties = Manager.getObjectMapper().readValue(json, Map.class);
} catch (IOException e) {
Log.e(TAG, String.format("Unparseable JSON for doc=%s, rev=%s: %s", docID, revID, new String(json)), e);
docProperties = new HashMap<String, Object>();
}
}
docProperties.put("_id", docID);
docProperties.put("_rev", revID);
if (deleted)
docProperties.put("_deleted", true);
return docProperties;
}
/**
* Prune revisions to the given max depth. Eg, remove revisions older than that max depth,
* which will reduce storage requirements.
* <p/>
* TODO: This implementation is a bit simplistic. It won't do quite the right thing in
* histories with branches, if one branch stops much earlier than another. The shorter branch
* will be deleted entirely except for its leaf revision. A more accurate pruning
* would require an expensive full tree traversal. Hopefully this way is good enough.
*/
protected int pruneRevsToMaxDepth(int maxDepth) throws CouchbaseLiteException {
if (maxDepth == 0) {
maxDepth = getMaxRevTreeDepth();
}
// First find which docs need pruning, and by how much:
long docNumericID = -1;
int minGen = 0;
int maxGen = 0;
Map<Long, Integer> toPrune = new HashMap<Long, Integer>();
Cursor cursor = null;
try {
String[] args = {};
cursor = storageEngine.rawQuery(
"SELECT doc_id, MIN(revid), MAX(revid) FROM revs GROUP BY doc_id", args);
while (cursor.moveToNext()) {
docNumericID = cursor.getLong(0);
String minGenRevId = cursor.getString(1);
String maxGenRevId = cursor.getString(2);
minGen = Revision.generationFromRevID(minGenRevId);
maxGen = Revision.generationFromRevID(maxGenRevId);
if ((maxGen - minGen + 1) > maxDepth) {
toPrune.put(docNumericID, (maxGen - minGen));
}
}
} catch (Exception e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
if (cursor != null) {
cursor.close();
}
}
int outPruned = 0;
boolean shouldCommit = false;
try {
beginTransaction();
if (toPrune.size() == 0) {
return 0;
}
for (Long docNumericIDLong : toPrune.keySet()) {
String minIDToKeep = String.format("%d-", toPrune.get(docNumericIDLong).intValue() + 1);
String[] deleteArgs = {Long.toString(docNumericID), minIDToKeep};
int rowsDeleted = storageEngine.delete(
"revs", "doc_id=? AND revid < ? AND current=0", deleteArgs);
outPruned += rowsDeleted;
}
shouldCommit = true;
} catch (Throwable e) {
throw new CouchbaseLiteException(e, Status.INTERNAL_SERVER_ERROR);
} finally {
endTransaction(shouldCommit);
}
return outPruned;
}
protected boolean runStatements(String statements) {
for (String statement : statements.split(";")) {
try {
storageEngine.execSQL(statement);
} catch (SQLException e) {
Log.e(TAG, "Failed to execSQL: " + statement, e);
return false;
}
}
return true;
}
private boolean initialize(String statements) {
if (!runStatements(statements)) {
close();
return false;
}
return true;
}
private long getLastOptimized() {
String info = getInfo("last_optimized");
if (info != null) {
return Long.parseLong(info);
}
return 0;
}
private boolean sequenceHasAttachments(long sequence) {
String args[] = {Long.toString(sequence)};
return SQLiteUtils.booleanForQuery(storageEngine, "SELECT no_attachments=0 FROM revs WHERE sequence=?", args);
}
protected long getDocNumericID(String docID) {
return SQLiteUtils.longForQuery(storageEngine,
"SELECT doc_id FROM docs WHERE docid=?",
new String[]{docID});
}
// Registers a docID and returns its numeric row ID in the 'docs' table.
// On input, *ioIsNew should be YES if the docID is probably not known, NO if it's probably known.
// On return, *ioIsNew will be YES iff the docID is newly-created (was not known before.)
// Return value is the positive row ID of this doc, or <= 0 on error.
private long createOrGetDocNumericID(String docID, AtomicBoolean isNew) {
// TODO: cache
long row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
if (row < 0)
return row;
if (row == 0) {
isNew.set(!isNew.get());
row = isNew.get() ? createDocNumericID(docID, isNew) : getDocNumericID(docID);
}
// TODO: cache
return row;
}
//private long getOrInsertDocNumericID(String docID) {
private long createDocNumericID(String docID, AtomicBoolean isNew) {
long docNumericId = getDocNumericID(docID);
if (docNumericId == 0) {
docNumericId = insertDocumentID(docID);
isNew.set(true);
} else {
isNew.set(false);
}
return docNumericId;
}
private long insertDocumentID(String docID) {
long rowId = -1;
try {
ContentValues args = new ContentValues();
args.put("docid", docID);
rowId = storageEngine.insert("docs", null, args);
} catch (Exception e) {
Log.e(TAG, "Error inserting document id", e);
}
return rowId;
}
// Raw row insertion. Returns new sequence, or 0 on error
private long insertRevision(RevisionInternal rev,
long docNumericID,
long parentSequence,
boolean current,
boolean hasAttachments,
byte[] json,
String docType) {
long rowId = 0;
try {
ContentValues args = new ContentValues();
args.put("doc_id", docNumericID);
args.put("revid", rev.getRevID());
if (parentSequence != 0) {
args.put("parent", parentSequence);
}
args.put("current", current);
args.put("deleted", rev.isDeleted());
args.put("no_attachments", !hasAttachments);
args.put("json", json);
args.put("doc_type", docType);
rowId = storageEngine.insert("revs", null, args);
rev.setSequence(rowId);
} catch (Exception e) {
Log.e(TAG, "Error inserting revision", e);
}
return rowId;
}
private long getSequenceOfDocument(long docNumericID, String revID, boolean onlyCurrent) {
String sql = String.format(
"SELECT sequence FROM revs WHERE doc_id=? AND revid=? %s LIMIT 1",
(onlyCurrent ? "AND current=1" : ""));
String[] args = {Long.toString(docNumericID), revID};
return SQLiteUtils.longForQuery(storageEngine, sql, args);
}
/**
* Hack because cursor interface does not support cursor.getColumnIndex("deleted") yet.
*/
private int getDeletedColumnIndex(QueryOptions options) {
if (options.isIncludeDocs()) {
return 6; // + json and no_attachments
} else {
return 4; // revs.doc_id, docid, revid, sequence
}
}
/**
* Loads revision given its sequence. Assumes the given docID is valid.
*/
protected RevisionInternal getDocument(String docID, long sequence) {
// Now get its revID and deletion status:
RevisionInternal rev = null;
String[] args = {Long.toString(sequence)};
String queryString = "SELECT revid, deleted, json FROM revs WHERE sequence=?";
Cursor cursor = null;
try {
cursor = storageEngine.rawQuery(queryString, args);
if (cursor.moveToNext()) {
String revID = cursor.getString(0);
boolean deleted = (cursor.getInt(1) > 0);
byte[] json = cursor.getBlob(2);
rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
rev.setJSON(json);
}
} finally {
cursor.close();
}
return rev;
}
protected RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence, byte[] json) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (json != null)
rev.setJSON(json);
return rev;
}
protected RevisionInternal revision(String docID, String revID,
boolean deleted, long sequence,
Map<String, Object> properties) {
RevisionInternal rev = new RevisionInternal(docID, revID, deleted);
rev.setSequence(sequence);
if (properties != null)
rev.setProperties(properties);
return rev;
}
private String winner(long docNumericID,
String oldWinningRevID,
boolean oldWinnerWasDeletion,
RevisionInternal newRev)
throws CouchbaseLiteException {
String newRevID = newRev.getRevID();
if (oldWinningRevID == null) {
return newRevID;
}
if (!newRev.isDeleted()) {
if (oldWinnerWasDeletion || RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // this is now the winning live revision
} else if (oldWinnerWasDeletion) {
if (RevisionInternal.CBLCompareRevIDs(newRevID, oldWinningRevID) > 0)
return newRevID; // doc still deleted, but this beats previous deletion rev
} else {
// Doc was alive. How does this deletion affect the winning rev ID?
AtomicBoolean outIsDeleted = new AtomicBoolean(false);
String winningRevID = winningRevIDOfDocNumericID(docNumericID, outIsDeleted, null);
if (!winningRevID.equals(oldWinningRevID))
return winningRevID;
}
return null; // no change
}
}
|
package com.boundary.sdk;
import java.util.Date;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.boundary.sdk.RawEvent;
import com.boundary.sdk.Severity;
/**
* @author davidg
*
*/
public class SNMPToEventProcessor implements Processor {
private static final Logger LOG = LoggerFactory.getLogger(SNMPToEventProcessor.class);
public SNMPToEventProcessor() {
}
@Override
public void process(Exchange exchange) throws Exception {
Message message = exchange.getIn();
LOG.debug("class: {}",message.getBody().getClass().toString());
// Create our event so that we can populate with the Syslog data
RawEvent event = new RawEvent();
Date dt = new java.util.Date();
event.setTitle("SNMP TRAP " + dt);
event.setStatus(Status.OPEN);
event.setSeverity(Severity.WARN);
event.getSource().setRef("localhost");
event.getSource().setType("host");
// event.setMessage(message.getBody().toString());
// event.putProperty("message",message.getBody().toString());
event.putFingerprintField("@title");
message.setBody(event, RawEvent.class);
}
}
|
// 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.presents.server;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.samskivert.util.Invoker;
import com.samskivert.util.Lifecycle;
import com.samskivert.util.RunQueue;
import com.samskivert.util.SystemInfo;
import com.threerings.presents.annotation.AuthInvoker;
import com.threerings.presents.annotation.EventQueue;
import com.threerings.presents.annotation.MainInvoker;
import com.threerings.presents.client.Client;
import com.threerings.presents.dobj.AccessController;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.RootDObjectManager;
import com.threerings.presents.server.PresentsDObjectMgr.LongRunnable;
import com.threerings.presents.server.net.ConnectionManager;
import com.threerings.crowd.server.PlaceManager;
import static com.threerings.presents.Log.log;
/**
* The presents server provides a central point of access to the various facilities that make up
* the presents framework. To facilitate extension and customization, a single instance of the
* presents server should be created and initialized in a process. To facilitate easy access to the
* services provided by the presents server, static references to the various managers are made
* available in the <code>PresentsServer</code> class. These will be configured when the singleton
* instance is initialized.
*/
@Singleton
public class PresentsServer
{
/** Configures dependencies needed by the Presents services. */
public static class Module extends AbstractModule
{
@Override protected void configure () {
bindInvokers();
bind(RunQueue.class).annotatedWith(EventQueue.class).to(PresentsDObjectMgr.class);
bind(DObjectManager.class).to(PresentsDObjectMgr.class);
bind(RootDObjectManager.class).to(PresentsDObjectMgr.class);
bind(Lifecycle.class).toInstance(new Lifecycle());
}
/**
* Binds just the invokers so this can be overridden if desired.
*/
protected void bindInvokers() {
bind(Invoker.class).annotatedWith(MainInvoker.class).to(PresentsInvoker.class);
bind(Invoker.class).annotatedWith(AuthInvoker.class).to(PresentsAuthInvoker.class);
}
}
/**
* The default entry point for the server.
*/
public static void main (String[] args)
{
Injector injector = Guice.createInjector(new Module());
PresentsServer server = injector.getInstance(PresentsServer.class);
try {
// initialize the server
server.init(injector);
// check to see if we should load and invoke a test module before running the server
String testmod = System.getProperty("test_module");
if (testmod != null) {
try {
log.info("Invoking test module", "mod", testmod);
Class<?> tmclass = Class.forName(testmod);
Runnable trun = (Runnable)tmclass.newInstance();
trun.run();
} catch (Exception e) {
log.warning("Unable to invoke test module '" + testmod + "'.", e);
}
}
// start the server to running (this method call won't return until the server is shut
// down)
server.run();
} catch (Exception e) {
log.warning("Unable to initialize server.", e);
System.exit(-1);
}
}
/** Legacy static reference to the main distributed object manager. Don't use this. If you're
* writing a game, use {@link PlaceManager#_omgr}. */
@Deprecated public static PresentsDObjectMgr omgr;
/** Legacy static reference to the invocation manager. Don't use this. If you're
* writing a game, use {@link PlaceManager#_invmgr}. */
@Deprecated public static InvocationManager invmgr;
/**
* Initializes all of the server services and prepares for operation.
*/
public void init (Injector injector)
throws Exception
{
// output general system information
SystemInfo si = new SystemInfo();
log.info("Starting up server", "os", si.osToString(), "jvm", si.jvmToString());
// register SIGTERM, SIGINT (ctrl-c) and a SIGHUP handlers
boolean registered = false;
try {
registered = injector.getInstance(SunSignalHandler.class).init();
} catch (Throwable t) {
log.warning("Unable to register Sun signal handlers", "error", t);
}
if (!registered) {
injector.getInstance(NativeSignalHandler.class).init();
}
// initialize our deprecated legacy static references
omgr = _omgr;
invmgr = _invmgr;
// configure the dobject manager with our access controller
_omgr.setDefaultAccessController(createDefaultObjectAccessController());
// start the main and auth invoker threads
_invoker.start();
_authInvoker.start();
((PresentsInvoker)_invoker).addInterdependentInvoker(_authInvoker);
// provide our client manager with the injector it needs
_clmgr.setInjector(injector);
// configure our connection manager
_conmgr.init(getBindHostname(), getListenPorts(), getDatagramPorts());
// initialize the time base services
TimeBaseProvider.init(_invmgr, _omgr);
// make the client manager shut down before the invoker and dobj threads; this helps
// application code to avoid long chains of shutdown constraints
_lifecycle.addShutdownConstraint(
_clmgr, Lifecycle.Constraint.RUNS_BEFORE, (PresentsInvoker)_invoker);
// initialize all of our registered components
_lifecycle.init();
}
/**
* Starts up all of the server services and enters the main server event loop.
*/
public void run ()
{
// wait till everything in the dobjmgr queue and invokers are processed and then start the
// connection manager
((PresentsInvoker)_invoker).postRunnableWhenEmpty(new Runnable() {
public void run () {
// Take as long as you like opening to the public
_omgr.postRunnable(new LongRunnable() {
public void run () {
openToThePublic();
}
});
}
});
// invoke the dobjmgr event loop
_omgr.run();
}
/**
* Opens the server for connections after the event thread is running and all the invokers are
* clear after starting up.
*/
protected void openToThePublic ()
{
_conmgr.start();
}
/**
* Queues up a request to shutdown on the event thread. This method may be safely called from
* any thread.
*/
public void queueShutdown ()
{
_omgr.postRunnable(new PresentsDObjectMgr.LongRunnable() {
public void run () {
_lifecycle.shutdown();
}
});
}
/**
* Defines the default object access policy for all {@link DObject} instances. The default
* default policy is to allow all subscribers but reject all modifications by the client.
*/
protected AccessController createDefaultObjectAccessController ()
{
return PresentsObjectAccess.DEFAULT;
}
/**
* Returns the hostname on which the connection manager will listen for TCP and datagram
* traffic, or <code>null</code> to bind to the wildcard address.
*/
protected String getBindHostname ()
{
return null;
}
/**
* Returns the port on which the connection manager will listen for client connections.
*/
protected int[] getListenPorts ()
{
return Client.DEFAULT_SERVER_PORTS;
}
/**
* Returns the ports on which the connection manager will listen for datagrams.
*/
protected int[] getDatagramPorts ()
{
return Client.DEFAULT_DATAGRAM_PORTS;
}
/**
* Called once the invoker and distributed object manager have both completed processing all
* remaining events and are fully shutdown. <em>Note:</em> this is called as the last act of
* the invoker <em>on the invoker thread</em>. In theory no other (important) threads are
* running, so thread safety should not be an issue, but be careful!
*/
protected void invokerDidShutdown ()
{
}
/** The manager of distributed objects. */
@Inject protected PresentsDObjectMgr _omgr;
/** The manager of network connections. */
@Inject protected ConnectionManager _conmgr;
/** The manager of clients. */
@Inject protected ClientManager _clmgr;
/** The manager of invocation services. */
@Inject protected InvocationManager _invmgr;
/** Handles orderly initialization and shutdown of our managers, etc. */
@Inject protected Lifecycle _lifecycle;
/** Used to invoke background tasks that should not be allowed to tie up the distributed object
* manager thread (generally talking to databases and other relatively slow entities). */
@Inject @MainInvoker protected Invoker _invoker;
/** Used to invoke authentication tasks. */
@Inject @AuthInvoker protected Invoker _authInvoker;
}
|
package com.sdl.dxa.core;
import com.sdl.webapp.common.api.WebRequestContext;
import com.sdl.webapp.common.api.content.ContentProvider;
import com.sdl.webapp.common.api.formats.DataFormatter;
import com.sdl.webapp.common.api.localization.LocalizationResolver;
import com.sdl.webapp.common.impl.interceptor.LocalizationResolverInterceptor;
import com.sdl.webapp.common.impl.interceptor.StaticContentInterceptor;
import com.sdl.webapp.common.impl.interceptor.ThreadLocalInterceptor;
import com.sdl.webapp.common.views.AtomView;
import com.sdl.webapp.common.views.JsonView;
import com.sdl.webapp.common.views.RssView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.sdl.dxa.core", "com.sdl.webapp"})
public class SpringConfiguration extends WebMvcConfigurerAdapter {
private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/Views/";
private static final String VIEW_RESOLVER_SUFFIX = ".jsp";
@Autowired
private LocalizationResolver localizationResolver;
@Autowired
private ContentProvider contentProvider;
@Autowired
private WebRequestContext webRequestContext;
@Autowired
private DataFormatter dataFormatter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localizationResolverInterceptor());
registry.addInterceptor(staticContentInterceptor());
registry.addInterceptor(threadLocalInterceptor());
}
@Bean
public HandlerInterceptor localizationResolverInterceptor() {
return new LocalizationResolverInterceptor(localizationResolver, webRequestContext);
}
@Bean
public HandlerInterceptor staticContentInterceptor() {
return new StaticContentInterceptor(contentProvider, webRequestContext);
}
@Bean
public HandlerInterceptor threadLocalInterceptor() {
return new ThreadLocalInterceptor();
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);
return viewResolver;
}
@Bean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
@Bean(name = "rssFeedView")
public RssView rssFeedView() {
return new RssView(webRequestContext);
}
@Bean(name = "atomFeedView")
public AtomView atomFeedView() {
return new AtomView(webRequestContext);
}
@Bean(name = "jsonFeedView")
public JsonView jsonFeedView() {
return new JsonView(webRequestContext);
}
}
|
package com.demonwav.mcdev.util;
import org.jetbrains.annotations.NotNull;
import java.awt.Color;
import java.util.Map;
public final class CommonColors {
private static final Color DARK_RED = new Color(0xAA0000);
private static final Color RED = new Color(0xFF5555);
private static final Color GOLD = new Color(0xFFAA00);
private static final Color YELLOW = new Color(0xFFFF55);
private static final Color DARK_GREEN = new Color(0x00AA00);
private static final Color GREEN = new Color(0x55FF55);
private static final Color AQUA = new Color(0x55FFFF);
private static final Color DARK_AQUA = new Color(0x00AAAA);
private static final Color DARK_BLUE = new Color(0x0000AA);
private static final Color BLUE = new Color(0x5555FF);
private static final Color LIGHT_PURPLE = new Color(0xFF55FF);
private static final Color DARK_PURPLE = new Color(0xAA00AA);
private static final Color WHITE = new Color(0xFFFFFF);
private static final Color GRAY = new Color(0xAAAAAA);
private static final Color DARK_GRAY = new Color(0x555555);
private static final Color BLACK = new Color(0x000000);
private CommonColors() {
}
public static void applyStandardColors(@NotNull Map<String, Color> map, @NotNull String prefix) {
map.put(prefix + ".DARK_RED", DARK_RED);
map.put(prefix + ".RED", RED);
map.put(prefix + ".GOLD", GOLD);
map.put(prefix + ".YELLOW", YELLOW);
map.put(prefix + ".DARK_GREEN", DARK_GREEN);
map.put(prefix + ".GREEN", GREEN);
map.put(prefix + ".AQUA", AQUA);
map.put(prefix + ".DARK_AQUA", DARK_AQUA);
map.put(prefix + ".DARK_BLUE", DARK_BLUE);
map.put(prefix + ".BLUE", BLUE);
map.put(prefix + ".LIGHT_PURPLE", LIGHT_PURPLE);
map.put(prefix + ".DARK_PURPLE", DARK_PURPLE);
map.put(prefix + ".WHITE", WHITE);
map.put(prefix + ".GRAY", GRAY);
map.put(prefix + ".DARK_GRAY", DARK_GRAY);
map.put(prefix + ".BLACK", BLACK);
}
}
|
package com.byoutline.mockserver;
import java.io.IOException;
import java.io.InputStream;
public interface ConfigReader {
/**
* Provide input stream which includes port and custom responses.
* If null is returned default port and no responses will be used.
* @return stream with json string or null
*/
InputStream getMainConfigFile();
/**
* Provide input stream for file that contains response for single HTTP
* call.
*
* @param fileName name of file that was in main config.
* @throws java.io.IOException if there is no such a file and 404 should be
* returned.
*/
InputStream getResponseConfigFromFile(String fileName) throws IOException;
/**
* Provide a static file that should be served for GET call.
* If no file should be returned return null or throw {@link IOException}
*
* @param fileName name of file that was requested.
* @throws java.io.IOException if there is no such a file and 404 should be
* returned.
*/
InputStream getStaticFile(String fileName) throws IOException;
}
|
// $Id: PresentsServer.java,v 1.33 2003/03/31 02:10:37 mdb Exp $
package com.threerings.presents.server;
import java.util.ArrayList;
import com.samskivert.util.IntervalManager;
import com.samskivert.util.ObserverList;
import com.samskivert.util.StringUtil;
import com.samskivert.util.SystemInfo;
import com.threerings.util.signal.SignalManager;
import com.threerings.presents.Log;
import com.threerings.presents.client.Client;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.server.net.ConnectionManager;
import com.threerings.presents.server.util.SafeInterval;
import com.threerings.presents.util.Invoker;
/**
* The presents server provides a central point of access to the various
* facilities that make up the presents framework. To facilitate extension
* and customization, a single instance of the presents server should be
* created and initialized in a process. To facilitate easy access to the
* services provided by the presents server, static references to the
* various managers are made available in the <code>PresentsServer</code>
* class. These will be configured when the singleton instance is
* initialized.
*/
public class PresentsServer
implements SignalManager.SignalHandler
{
/** Used to generate "state of the server" reports. See {@link
* #registerReporter}. */
public static interface Reporter
{
/**
* Requests that this reporter append its report to the supplied
* string buffer.
*
* @param buffer the string buffer to which the report text should
* be appended.
* @param now the time at which the report generation began, in
* epoch millis.
* @param sinceLast number of milliseconds since the last time we
* generated a report.
*/
public void appendReport (
StringBuffer buffer, long now, long sinceLast);
}
/** Implementers of this interface will be notified when the server is
* shutting down. */
public static interface Shutdowner
{
/**
* Called when the server is shutting down.
*/
public void shutdown ();
}
/** The manager of network connections. */
public static ConnectionManager conmgr;
/** The manager of clients. */
public static ClientManager clmgr;
/** The distributed object manager. */
public static PresentsDObjectMgr omgr;
/** The invocation manager. */
public static InvocationManager invmgr;
/** This is used to invoke background tasks that should not be allowed
* to tie up the distributed object manager thread. This is generally
* used to talk to databases and other (relatively) slow entities. */
public static Invoker invoker;
/**
* Initializes all of the server services and prepares for operation.
*/
public void init ()
throws Exception
{
// output general system information
SystemInfo si = new SystemInfo();
Log.info("Starting up server [os=" + si.osToString() +
", jvm=" + si.jvmToString() +
", mem=" + si.memoryToString() + "].");
// register a ctrl-c handler
SignalManager.registerSignalHandler(SignalManager.SIGINT, this);
// create our distributed object manager
omgr = new PresentsDObjectMgr();
// create and start up our invoker
invoker = new Invoker(omgr);
invoker.start();
// create our connection manager
conmgr = new ConnectionManager(getListenPort());
conmgr.setAuthenticator(new DummyAuthenticator());
// create our client manager
clmgr = new ClientManager(conmgr);
// create our invocation manager
invmgr = new InvocationManager(omgr);
// initialize the time base services
TimeBaseProvider.init(invmgr, omgr);
// queue up an interval which will generate reports
IntervalManager.register(new SafeInterval(omgr) {
public void run () {
generateReport(System.currentTimeMillis());
}
}, REPORT_INTERVAL, null, true);
}
/**
* Returns the port on which the connection manager will listen for
* client connections.
*/
protected int getListenPort ()
{
return Client.DEFAULT_SERVER_PORT;
}
/**
* Starts up all of the server services and enters the main server
* event loop.
*/
public void run ()
{
// post a unit that will start up the connection manager when
// everything else in the dobjmgr queue is processed
omgr.postUnit(new Runnable() {
public void run () {
// start up the connection manager
conmgr.start();
}
});
// invoke the dobjmgr event loop
omgr.run();
}
// documentation inherited from interface
public boolean signalReceived (int signo)
{
// this is called when we receive a ctrl-c
omgr.postUnit(new Runnable() {
public void run () {
shutdown();
}
});
return true;
}
/**
* A report is generated by the presents server periodically in which
* server entities can participate by registering a {@link Reporter}
* with this method.
*/
public static void registerReporter (Reporter reporter)
{
_reporters.add(reporter);
}
/**
* Generates and logs a "state of server" report.
*/
protected void generateReport (long now)
{
long sinceLast = now - _lastReportStamp;
long uptime = now - _serverStartTime;
StringBuffer report = new StringBuffer("State of server report:\n");
report.append("- Uptime: ");
report.append(StringUtil.intervalToString(uptime)).append(", ");
report.append(StringUtil.intervalToString(sinceLast));
report.append(" since last report\n");
// report on the state of memory
Runtime rt = Runtime.getRuntime();
long total = rt.totalMemory(), max = rt.maxMemory();
long used = (total - rt.freeMemory());
report.append("- Memory: ").append(used/1024).append("k used, ");
report.append(total/1024).append("k total, ");
report.append(max/1024).append("k max\n");
for (int ii = 0; ii < _reporters.size(); ii++) {
Reporter rptr = (Reporter)_reporters.get(ii);
try {
rptr.appendReport(report, now, sinceLast);
} catch (Throwable t) {
Log.warning("Reporter choked [rptr=" + rptr + "].");
Log.logStackTrace(t);
}
}
// strip off the final newline
int blen = report.length();
if (report.charAt(blen-1) == '\n') {
report.delete(blen-1, blen);
}
_lastReportStamp = now;
logReport(report.toString());
}
/**
* Logs the state of the server report via the default logging
* mechanism. Derived classes may wish to log the state of the server
* report via a different means.
*/
protected void logReport (String report)
{
Log.info(report);
}
/**
* Requests that the server shut down. All registered shutdown
* participants will be shut down, following which the server process
* will be terminated.
*/
public void shutdown ()
{
// shut down the connection manager (this will cease all network
// activity but not actually close the connections)
conmgr.shutdown();
// shut down all shutdown participants
_downers.apply(new ObserverList.ObserverOp() {
public boolean apply (Object observer) {
((Shutdowner)observer).shutdown();
return true;
}
});
// finally shut down the invoker and distributed object manager
invoker.shutdown();
omgr.shutdown();
}
/**
* Registers an entity that will be notified when the server is
* shutting down.
*/
public static void registerShutdowner (Shutdowner downer)
{
_downers.add(downer);
}
public static void main (String[] args)
{
Log.info("Presents server starting...");
PresentsServer server = new PresentsServer();
try {
// initialize the server
server.init();
// check to see if we should load and invoke a test module
// before running the server
String testmod = System.getProperty("test_module");
if (testmod != null) {
try {
Log.info("Invoking test module [mod=" + testmod + "].");
Class tmclass = Class.forName(testmod);
Runnable trun = (Runnable)tmclass.newInstance();
trun.run();
} catch (Exception e) {
Log.warning("Unable to invoke test module " +
"[mod=" + testmod + "].");
Log.logStackTrace(e);
}
}
// start the server to running (this method call won't return
// until the server is shut down)
server.run();
} catch (Exception e) {
Log.warning("Unable to initialize server.");
Log.logStackTrace(e);
System.exit(-1);
}
}
/** The time at which the server was started. */
protected long _serverStartTime = System.currentTimeMillis();
/** The last time at which {@link #generateReport} was run. */
protected long _lastReportStamp = _serverStartTime;
/** Used to generate "state of server" reports. */
protected static ArrayList _reporters = new ArrayList();
/** A list of shutdown participants. */
protected static ObserverList _downers =
new ObserverList(ObserverList.SAFE_IN_ORDER_NOTIFY);
/** The frequency with which we generate "state of server" reports. */
protected static final long REPORT_INTERVAL = 15 * 60 * 1000L;
}
|
package com.e16din.alertmanager;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.afollestad.materialdialogs.MaterialDialog;
import org.joda.time.DateTime;
import java.util.ArrayList;
public class AlertManager {
private AlertManager() {
}
private static final int INVALID_VALUE = -100500;
public static final int MILLISECONDS_IN_THE_DAY = 86400;
private static class Holder {
public static final AlertManager HOLDER_INSTANCE = new AlertManager();
}
public static AlertManager manager(Context context) {
Holder.HOLDER_INSTANCE.setContext(context);
return Holder.HOLDER_INSTANCE;
}
private static int customAlertTitle = R.string.title_alert;
private static int customErrorTitle = R.string.title_error;
private Context context = null;
private ArrayList<String> displayedAlerts = new ArrayList<>();
private void setContext(Context context) {
this.context = context;
}
private AlertDialogWrapper.Builder createAlertBuilder() {
return new AlertDialogWrapper.Builder(context);
}
public static int getCustomAlertTitle() {
return customAlertTitle;
}
public static void setCustomAlertTitle(int customAlertTitle) {
AlertManager.customAlertTitle = customAlertTitle;
}
public static int getCustomErrorTitle() {
return customErrorTitle;
}
public static void setCustomErrorTitle(int customErrorTitle) {
AlertManager.customErrorTitle = customErrorTitle;
}
public boolean isAlertDisplayed(String message) {
return displayedAlerts.contains(message);
}
public void showAlert(String message, boolean isCancelable) {
showAlert(message, customAlertTitle, isCancelable, null);
}
public void showErrorAlert(String message, boolean isCancelable) {
showAlert(message, customErrorTitle, isCancelable, null);
}
public void showErrorAlert(String message, boolean isCancelable,
DialogInterface.OnClickListener listener) {
showAlert(message, customErrorTitle, isCancelable, listener);
}
public void showAlert(String message) {
showAlert(message, customAlertTitle, false, null);
}
public void showAlert(int message) {
showAlert(message, customAlertTitle, false, null);
}
public void showAlert(String message, DialogInterface.OnClickListener listener) {
showAlert(message, customAlertTitle, false, listener);
}
public void showAlert(int message, DialogInterface.OnClickListener listener) {
showAlert(message, customAlertTitle, false, listener);
}
public void showErrorAlert(String message) {
showAlert(message, customErrorTitle, false, null);
}
public void showErrorAlert(String message, DialogInterface.OnClickListener listener) {
showAlert(message, customErrorTitle, false, listener);
}
public void showAlert(final String message, final int title, final boolean isCancelable,
final DialogInterface.OnClickListener listener) {
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
try {
AlertDialogWrapper.Builder builder = createAlertBuilder();
String updatedTitle = context.getString(title);
if (!TextUtils.isEmpty(context.getString(title)))
builder.setTitle(updatedTitle);
builder.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null)
listener.onClick(dialog, which);
displayedAlerts.remove(message);
}
}).setCancelable(isCancelable).setOnKeyListener(
new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ||
event.getAction() == KeyEvent.ACTION_UP) {
if (listener != null)
listener.onClick(dialog, INVALID_VALUE);
}
displayedAlerts.remove(message);
return false;
}
}).show();
displayedAlerts.add(message);
} catch (WindowManager.BadTokenException e) {
Log.e("debug", "error: ", e);
}
}
}, 500);
}
public void showAlert(final int message, int title, boolean isCancelable,
final DialogInterface.OnClickListener listener) {
showAlert(context.getString(message), title, isCancelable, listener);
}
public void showAlert(final String message, boolean isCancelable,
final DialogInterface.OnClickListener listener) {
try {
AlertDialogWrapper.Builder builder = createAlertBuilder();
final String customAlertTitle = context.getString(AlertManager.customAlertTitle);
if (!TextUtils.isEmpty(customAlertTitle))
builder.setTitle(customAlertTitle);
builder.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null)
listener.onClick(dialog, which);
displayedAlerts.remove(message);
}
}).setCancelable(isCancelable).setOnKeyListener(
new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ||
event.getAction() == KeyEvent.ACTION_UP) {
if (listener != null)
listener.onClick(dialog, INVALID_VALUE);
displayedAlerts.remove(message);
}
return false;
}
}).show();
displayedAlerts.add(message);
} catch (WindowManager.BadTokenException e) {
Log.e("debug", "error: ", e);
}
}
public void showAlertYesNo(final String message,
final DialogInterface.OnClickListener yesListener) {
try {
AlertDialogWrapper.Builder builder = createAlertBuilder();
final String customAlertTitle = context.getString(AlertManager.customAlertTitle);
if (!TextUtils.isEmpty(customAlertTitle))
builder.setTitle(customAlertTitle);
builder.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (yesListener != null)
yesListener.onClick(dialog, which);
displayedAlerts.remove(message);
}
}).setNegativeButton(android.R.string.no, null).show();
displayedAlerts.add(message);
} catch (WindowManager.BadTokenException e) {
Log.e("debug", "error: ", e);
}
}
public void showDialogList(final String title, final CharSequence[] items, final TextView tv,
final DialogInterface.OnClickListener listener) {
try {
AlertDialogWrapper.Builder builder = createAlertBuilder();
if (!TextUtils.isEmpty(title))
builder.setTitle(title);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (tv != null && which >= 0)
tv.setText(items[which]);
if (listener != null)
listener.onClick(dialog, which);
displayedAlerts.remove(title);
}
}).show();
displayedAlerts.add(title);
} catch (WindowManager.BadTokenException e) {
Log.e("debug", "error: ", e);
}
}
public void showRadioList(final String title, final CharSequence[] items,
final DialogInterface.OnClickListener listener) {
showRadioList(title, items, null, listener);
}
public void showRadioList(final CharSequence[] items,
final DialogInterface.OnClickListener listener) {
showRadioList(null, items, null, listener);
}
public void showRadioList(final CharSequence[] items, final TextView tv,
final DialogInterface.OnClickListener listener) {
showRadioList(null, items, tv, listener);
}
public void showRadioList(final String title, final CharSequence[] items, final TextView tv,
final DialogInterface.OnClickListener listener) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
if (!TextUtils.isEmpty(title))
builder.title(title);
builder.items(items)
.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which,
CharSequence text) {
/**
* If you use alwaysCallSingleChoiceCallback(), which is discussed below,
* returning false here won't allow the newly selected radio button to actually be selected.
**/
if (tv != null && which >= 0)
tv.setText(items[which]);
if (listener != null)
listener.onClick(dialog, which);
dialog.dismiss();
dialog.cancel();
return true;
}
})
.alwaysCallSingleChoiceCallback()
.positiveText(android.R.string.cancel)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
dialog.dismiss();
}
})
.show();
}
public void showDialogList(final CharSequence[] items,
DialogInterface.OnClickListener listener) {
showDialogList(context.getString(customAlertTitle), items, null, listener);
}
public void showDialogList(final CharSequence[] items, final TextView tv,
DialogInterface.OnClickListener listener) {
showDialogList(context.getString(customAlertTitle), items, tv, listener);
}
public void showTimePicker(int hours, int minutes,
final TimePickerDialog.OnTimeSetListener onTimeSetListener) {
final TimePicker timePicker = new TimePicker(context);
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(hours);
timePicker.setCurrentMinute(minutes);
AlertDialogWrapper.Builder builder = createAlertBuilder();
final String title = context.getString(R.string.set_time);
if (!TextUtils.isEmpty(title))
builder.setTitle(title);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onTimeSetListener.onTimeSet(timePicker, timePicker.getCurrentHour(),
timePicker.getCurrentMinute());
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setView(timePicker).show();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void showDatePicker(final String title, final int year, final int month, final int day,
long maxDate,
final DatePickerDialog.OnDateSetListener onDateSetListener) {
final DatePicker datePicker = new DatePicker(context);
datePicker.updateDate(year, month - 1, day);
datePicker.setCalendarViewShown(false);
if (maxDate > 0)
datePicker.setMaxDate(maxDate);
AlertDialogWrapper.Builder builder = createAlertBuilder();
if (!TextUtils.isEmpty(title))
builder.setTitle(title);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertManager", "year: " + datePicker.getYear() + " month: " +
datePicker.getMonth() + 1 + " day: " + datePicker.getDayOfMonth());
onDateSetListener.onDateSet(datePicker,
datePicker.getYear(),
datePicker.getMonth() + 1,
datePicker.getDayOfMonth());
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setView(datePicker).show();
}
public void showDatePicker(final String title, final int year, final int month, final int day,
final DatePickerDialog.OnDateSetListener onDateSetListener) {
showDatePicker(title, year, month, day, DateTime.now().plusYears(1).getMillis(),
onDateSetListener);
}
public void showBirthDatePicker(final String title, final int year, final int month,
final int day,
final DatePickerDialog.OnDateSetListener onDateSetListener) {
showDatePicker(title, year, month, day, DateTime.now().getMillis(), onDateSetListener);
}
public void showDatePicker(final int year, final int month, final int day,
final DatePickerDialog.OnDateSetListener onDateSetListener) {
showDatePicker(context.getString(R.string.check_date), year, month, day,
DateTime.now().plusYears(1).getMillis(), onDateSetListener);
}
public void showBirthDatePicker(final int year, final int month, final int day,
final DatePickerDialog.OnDateSetListener onDateSetListener) {
showDatePicker(context.getString(R.string.check_date), year, month, day,
DateTime.now().getMillis(), onDateSetListener);
}
public void showCalendarPicker(final AlertDialogCallback<DateTime> callback) {
new MaterialDialog.Builder(context)
.customView(R.layout.dialog_calendar, false)
.positiveText("Ok")
.negativeText("Отмена")
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onNegative(MaterialDialog dialog) {
if (callback != null) {
callback.onNegative();//todo return date
}
}
@Override
public void onNeutral(MaterialDialog dialog) {
if (callback != null) {
callback.onNeutral();//todo return date
}
}
@Override
public void onPositive(MaterialDialog dialog) {
if (callback != null) {
callback.onPositive();//todo return date
}
}
}).show();
}
public void showMessageEditor(String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), null, message, -1, false, callback);
}
public void showMessageEditor(String message, int inputType, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), null, message, inputType, false, callback);
}
public void showMessageEditor(String hint, String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), hint, message, -1, false, callback);
}
public void showSingleLineMessageEditor(String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), null, message, -1, true, callback);
}
public void showSingleLineMessageEditor(String message, int inputType, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), null, message, inputType, true, callback);
}
public void showSingleLineMessageEditor(String hint, String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), hint, message, -1, true, callback);
}
public void showTextPasswordEditor(String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), context.getString(R.string.enter_password), message,
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, callback);
}
public void showTextPasswordEditor(String message, String hint, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), hint, message,
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, callback);
}
public void showNumberPasswordEditor(String message, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), context.getString(R.string.enter_password), message,
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, callback);
}
public void showNumberPasswordEditor(String message, String hint, final AlertDialogCallback<String> callback) {
showMessageEditor(context.getString(customAlertTitle), hint, message,
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD, true, callback);
}
//TODO: create Builder: setTitle, setMessage, setListener
public void showMessageEditor(String title, String hint, String message, int inputType, boolean singleLine,
final AlertDialogCallback<String> callback) {
final View customView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_message,
null);
final TextInputLayout tilMessage = (TextInputLayout) customView.findViewById(R.id.tilMessage);
final EditText etMessage = (EditText) customView.findViewById(R.id.etMessage);
etMessage.setHint(hint);
etMessage.setText(message);
etMessage.setSelection(etMessage.length());
tilMessage.setHint(hint);
if (inputType >= 0)
etMessage.setInputType(inputType);
if (singleLine)
etMessage.setSingleLine();
new MaterialDialog.Builder(context)
.title(title)
.customView(customView, false)
.positiveText("Готово")
.negativeText("Отмена")
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
String text = etMessage.getText().toString();
if (callback != null)
callback.onPositive(text);
}
}).show();
}
}
|
package com.codeborne.selenide.impl;
import com.codeborne.selenide.Selenide;
import com.codeborne.selenide.logevents.SelenideLog;
import com.codeborne.selenide.logevents.SelenideLogger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.security.UserAndPassword;
import java.net.URL;
import java.util.logging.Logger;
import static com.codeborne.selenide.Configuration.baseUrl;
import static com.codeborne.selenide.WebDriverRunner.*;
import static com.codeborne.selenide.logevents.LogEvent.EventStatus.PASS;
public class Navigator {
private static final Logger log = Logger.getLogger(Navigator.class.getName());
public void open(String relativeOrAbsoluteUrl) {
open(relativeOrAbsoluteUrl, "", "" , "");
}
public void open(URL url) {
open(url, "", "" , "");
}
public void open(String relativeOrAbsoluteUrl, String domain, String login, String password) {
if (relativeOrAbsoluteUrl.startsWith("http:") ||
relativeOrAbsoluteUrl.startsWith("https:") ||
isLocalFile(relativeOrAbsoluteUrl)) {
navigateToAbsoluteUrl(relativeOrAbsoluteUrl, domain, login, password);
} else {
navigateToAbsoluteUrl(absoluteUrl(relativeOrAbsoluteUrl), domain, login, password);
}
}
public void open(URL url, String domain, String login, String password) {
navigateToAbsoluteUrl(url.toExternalForm());
}
protected String absoluteUrl(String relativeUrl) {
return baseUrl + relativeUrl;
}
protected void navigateToAbsoluteUrl(String url) {
navigateToAbsoluteUrl(url, "", "", "");
}
protected void navigateToAbsoluteUrl(String url, String domain, String login, String password) {
if (isIE() && !isLocalFile(url)) {
url = makeUniqueUrlToAvoidIECaching(url, System.nanoTime());
if (!domain.isEmpty()) domain += "\\";
}
else {
if (!domain.isEmpty()) domain += "%5C";
if (!login.isEmpty()) login += ":";
if (!password.isEmpty()) password += "@";
int idx1 = url.indexOf(":
url = (idx1 < 3 ? "" : (url.substring(0, idx1 - 3) + ":
+ domain
+ login
+ password
+ (idx1 < 3 ? url : url.substring(idx1));
}
SelenideLog log = SelenideLogger.beginStep("open", url);
try {
WebDriver webdriver = getAndCheckWebDriver();
webdriver.navigate().to(url);
if (isIE() && !"".equals(login)) Selenide.switchTo().alert().authenticateUsing(new UserAndPassword(domain + login, password));
collectJavascriptErrors((JavascriptExecutor) webdriver);
SelenideLogger.commitStep(log, PASS);
} catch (WebDriverException e) {
SelenideLogger.commitStep(log, e);
e.addInfo("selenide.url", url);
e.addInfo("selenide.baseUrl", baseUrl);
throw e;
}
catch (RuntimeException e) {
SelenideLogger.commitStep(log, e);
throw e;
}
catch (Error e) {
SelenideLogger.commitStep(log, e);
throw e;
}
}
protected void collectJavascriptErrors(JavascriptExecutor webdriver) {
try {
webdriver.executeScript(
"if (!window._selenide_jsErrors) {\n" +
" window._selenide_jsErrors = [];\n" +
"}\n" +
"if (!window.onerror) {\n" +
" window.onerror = function (errorMessage, url, lineNumber) {\n" +
" var message = errorMessage + ' at ' + url + ':' + lineNumber;\n" +
" window._selenide_jsErrors.push(message);\n" +
" return false;\n" +
" };\n" +
"}\n"
);
} catch (UnsupportedOperationException cannotExecuteJsAgainstPlainTextPage) {
log.warning(cannotExecuteJsAgainstPlainTextPage.toString());
} catch (WebDriverException cannotExecuteJs) {
log.severe(cannotExecuteJs.toString());
}
}
protected String makeUniqueUrlToAvoidIECaching(String url, long unique) {
if (url.contains("timestamp=")) {
return url.replaceFirst("(.*)(timestamp=)(.*)([&#].*)", "$1$2" + unique + "$4")
.replaceFirst("(.*)(timestamp=)(.*)$", "$1$2" + unique);
} else {
return url.contains("?") ?
url + "×tamp=" + unique :
url + "?timestamp=" + unique;
}
}
protected boolean isLocalFile(String url) {
return url.startsWith("file:");
}
public void back() {
getWebDriver().navigate().back();
}
public void forward() {
getWebDriver().navigate().forward();
}
}
|
// 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.puzzle.client;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import com.samskivert.swing.util.MouseHijacker;
import com.samskivert.util.CollectionUtil;
import com.samskivert.util.ObserverList;
import com.samskivert.util.StringUtil;
import com.threerings.media.FrameParticipant;
import com.threerings.presents.dobj.AttributeChangeListener;
import com.threerings.presents.dobj.AttributeChangedEvent;
import com.threerings.presents.dobj.ElementUpdateListener;
import com.threerings.presents.dobj.ElementUpdatedEvent;
import com.threerings.crowd.client.PlaceControllerDelegate;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.parlor.game.client.GameController;
import com.threerings.parlor.game.data.GameObject;
import com.threerings.puzzle.Log;
import com.threerings.puzzle.data.Board;
import com.threerings.puzzle.data.PuzzleCodes;
import com.threerings.puzzle.data.PuzzleConfig;
import com.threerings.puzzle.data.PuzzleObject;
import com.threerings.puzzle.util.PuzzleContext;
/**
* The puzzle game controller handles logical actions for a puzzle game.
*/
public abstract class PuzzleController extends GameController
implements PuzzleCodes
{
/** The action command to toggle chatting mode. */
public static final String TOGGLE_CHATTING = "toggle_chat";
/** Used by {@link PuzzleController#fireWhenActionCleared}. */
public static interface ClearPender
{
/** {@link #actionCleared} return code. */
public static final int RESTART_ACTION = -1;
/** {@link #actionCleared} return code. */
public static final int CARE_NOT = 0;
/** {@link #actionCleared} return code. */
public static final int NO_RESTART_ACTION = 1;
/**
* Called when the action is fully cleared.
*
* @return One of {@link #RESTART_ACTION}, {@link #CARE_NOT} or
* {@link #NO_RESTART_ACTION}.
*/
public int actionCleared ();
}
// documentation inherited
protected void didInit ()
{
super.didInit();
_panel = (PuzzlePanel)_view;
_pctx = (PuzzleContext)_ctx;
// initialize the puzzle panel
_puzconfig = (PuzzleConfig)_config;
_panel.init(_puzconfig);
// initialize the board view
_pview = _panel.getBoardView();
_pview.setController(this);
}
/**
* Creates and returns a new board model.
*/
protected abstract Board newBoard ();
/**
* Returns the board associated with the puzzle.
*/
public Board getBoard ()
{
return _pboard;
}
/**
* Returns the player's index in the list of players for the game.
*/
public int getPlayerIndex ()
{
return _pidx;
}
// documentation inherited
public void setGameOver (boolean gameOver)
{
super.setGameOver(gameOver);
// clear the action if we're informed that the game is over early
// by the client
if (gameOver) {
clearAction();
}
}
/**
* Returns true if the puzzle has action, false if the action is
* cleared or it is suspended.
*/
public boolean hasAction ()
{
return (_astate == ACTION_GOING);
}
/**
* Sets whether we're focusing on the chat window rather than the puzzle.
*/
public void setChatting (boolean chatting)
{
// ignore the request if we're already there
if ((isChatting() == chatting) ||
// ..or if we want to initiate chatting and..
// we either can't right now or we don't have action
(chatting && (!canStartChatting() || !hasAction()))) {
return;
}
// update the panel
_panel.setPuzzleGrabsKeys(!chatting);
// if we're moving focus to chat..
if (chatting) {
if (_unpauser != null) {
Log.warning("Huh? Already have a mouse unpauser?");
_unpauser.release();
}
_unpauser = new Unpauser(_panel);
} else {
if (_unpauser != null) {
_unpauser.release();
_unpauser = null;
}
}
// update the chatting state
_chatting = chatting;
// dispatch the change to our delegates
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
((PuzzleControllerDelegate)delegate).setChatting(_chatting);
}
});
// and check if we should be suspending the action during this pause
if (supportsActionPause()) {
// clear the action if we're pausing, resume it if we're
// unpausing
if (chatting) {
clearAction();
} else {
safeStartAction();
}
_pview.setPaused(chatting);
}
}
/**
* Get the (untranslated) string to display when the puzzle is paused.
*/
public String getPauseString ()
{
return "m.paused";
}
/**
* Derived classes should override this and return false if their
* action should not be paused when the user switches control to the
* chat area.
*/
protected boolean supportsActionPause ()
{
return true;
}
/**
* Can we start chatting at this juncture?
*/
protected boolean canStartChatting ()
{
// check with the delegates
final boolean[] canChatNow = new boolean[] { true };
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
canChatNow[0] =
((PuzzleControllerDelegate)delegate).canStartChatting() &&
canChatNow[0];
}
});
return canChatNow[0];
}
/**
* Returns true if the puzzle has been defocused because the player
* is doing some chatting.
*/
public boolean isChatting ()
{
return _chatting;
}
// documentation inherited
public void willEnterPlace (PlaceObject plobj)
{
super.willEnterPlace(plobj);
// get a casted reference to our puzzle object
_puzobj = (PuzzleObject)plobj;
_puzobj.addListener(_kolist);
_puzobj.addListener(_mlist);
// listen to key events..
_pctx.getKeyDispatcher().addGlobalKeyListener(_globalKeyListener);
// save off our player index
_pidx = _puzobj.getPlayerIndex(_pctx.getUsername());
// generate the starting board
generateNewBoard();
// if the game is already in play, start up the action
if (_puzobj.isInPlay() && _puzobj.isActivePlayer(_pidx)) {
startAction();
}
}
// documentation inherited
public void mayLeavePlace (PlaceObject plobj)
{
super.mayLeavePlace(plobj);
// flush any pending progress events
sendProgressUpdate();
}
// documentation inherited
public void didLeavePlace (PlaceObject plobj)
{
super.didLeavePlace(plobj);
// clean up and clear out
clearAction();
// stop listening to key events..
_pctx.getKeyDispatcher().removeGlobalKeyListener(_globalKeyListener);
// clear out the puzzle object
if (_puzobj != null) {
_puzobj.removeListener(_mlist);
_puzobj.removeListener(_kolist);
_puzobj = null;
}
}
/**
* Puzzles that do not have "action" that starts and stops (via {@link
* #startAction} and {@link #clearAction}) when the puzzle starts and
* stops can override this method and return false.
*/
protected boolean isActionPuzzle ()
{
return true;
}
/**
* Indicates whether the action should start immediately as a result
* of {@link #gameDidStart} being called. If a puzzle wishes to do
* some beginning of the game fun stuff, like display a tutorial
* screen, they can veto the action start and then start it themselves
* later.
*/
protected boolean startActionImmediately ()
{
return true;
}
// documentation inherited
public void attributeChanged (AttributeChangedEvent event)
{
String name = event.getName();
// deal with game state changes
if (name.equals(PuzzleObject.STATE)) {
switch (event.getIntValue()) {
case PuzzleObject.IN_PLAY:
// we have to postpone all game starting activity until the
// current action has ended; only after all the animations have
// been completed will everything be in a state fit for
// starting back up again
fireWhenActionCleared(new ClearPender() {
public int actionCleared () {
// do the standard game did start business
gameDidStart();
// we don't always start the action immediately
return startActionImmediately() ?
RESTART_ACTION : NO_RESTART_ACTION;
}
});
break;
case PuzzleObject.GAME_OVER:
// similarly we haev to postpone game ending activity until
// the current action has ended
// clean up and clear out
clearAction();
// wait until the action is cleared before we roll down to our
// delegates and do all that business
fireWhenActionCleared(new ClearPender() {
public int actionCleared () {
gameDidEnd();
return CARE_NOT;
}
});
break;
default:
super.attributeChanged(event);
break;
}
} else if (name.equals(PuzzleObject.ROUND_ID)) {
// Need to clear out stale events. If we don't, we could send
// events that claim to be from the new round that are actually
// from the old round.
_events.clear();
}
}
// documentation inherited
protected void gameWillReset ()
{
super.gameWillReset();
// stop the old action
clearAction();
// when the server gets around to resetting the game, we'll get a
// 'state => IN_PLAY' message which will result in gameDidStart()
// being called and starting the action back up
}
/**
* Called when a new board is set.
*/
public void setBoard (Board board)
{
// we don't need to do anything by default
}
/**
* Derived classes should override this method and do whatever is
* necessary to start up the action for their puzzle. This could be
* called when the user is already in the "room" and the game starts,
* or immediately upon entering the room if the game is already
* started (for example if they disconnected and reconnected to a game
* already in progress).
*/
protected void startAction ()
{
// do nothing if we're not an action puzzle
if (!isActionPuzzle()) {
return;
}
// refuse to start the action if our puzzle view is hidden
if (_pidx != -1 && !_panel.getBoardView().isShowing()) {
Log.warning("Refusing to start action on hidden puzzle.");
Thread.dumpStack();
return;
}
// refuse to start the action if it's already going
if (_astate != ACTION_CLEARED) {
Log.warning("Action state inappropriate for startAction() " +
"[astate=" + _astate + "].");
Thread.dumpStack();
return;
}
if (isChatting() && supportsActionPause()) {
Log.info("Not starting action, player is chatting in a puzzle " +
"that supports pausing the action.");
return;
}
Log.debug("Starting puzzle action.");
// register the game progress updater; it may already be updated
// because we can cycle through clearing the action and starting
// it again before the updater gets a chance to unregister itself
if (!_pctx.getFrameManager().isRegisteredFrameParticipant(_updater)) {
_pctx.getFrameManager().registerFrameParticipant(_updater);
}
// make a note that we've started the action
_astate = ACTION_GOING;
// let our panel know what's up
_panel.startAction();
// and if we're not currently chatting, set the puzzle to grab
// keys and for the chatbox to look disabled
if (!isChatting()) {
_panel.setPuzzleGrabsKeys(true);
}
// let our delegates do their business
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
((PuzzleControllerDelegate)delegate).startAction();
}
});
}
/**
* If it is not known whether the puzzle board view has finished
* animating its final bits after a previous call to {@link
* #clearAction}, this method should be used instead of {@link
* #startAction} as it will wait until the action is confirmedly over
* before starting it anew.
*/
protected void safeStartAction ()
{
// do nothing if we're not an action puzzle
if (!isActionPuzzle()) {
return;
}
fireWhenActionCleared(new ClearPender() {
public int actionCleared () {
return RESTART_ACTION;
}
});
}
/**
* Called when the game has ended or when it is going to reset and
* when the client leaves the game "room". This method does not always
* immediately clear the action, but may mark the clear as pending if
* the action cannot yet be cleared (as indicated by {@link
* #canClearAction}). The action will eventually be cleared which will
* result in a call to {@link #actuallyClearAction} which is what
* derived classes should override to do their action clearing
* business.
*/
protected void clearAction ()
{
// do nothing if we're not an action puzzle
if (!isActionPuzzle()) {
return;
}
// no need to clear if we're already cleared or clearing
if (_astate == CLEAR_PENDING || _astate == ACTION_CLEARED) {
return;
}
Log.debug("Attempting to clear puzzle action.");
// put ourselves into a pending clear state and attempt to clear
// the action
_astate = CLEAR_PENDING;
maybeClearAction();
}
/**
* This method is called by the {@link PuzzleBoardView} when all
* action on the board has finished.
*/
protected void boardActionCleared ()
{
// if we have a clear pending, this could be the trigger that
// allows us to clear our action
maybeClearAction();
}
/**
* Queues up code to be invoked when the action is completely cleared
* (including all remaining interesting sprites and animations on the
* puzzle board).
*/
protected void fireWhenActionCleared (ClearPender pender)
{
// if the action is already ended, fire this pender immediately
if (_astate == ACTION_CLEARED) {
if (pender.actionCleared() == ClearPender.RESTART_ACTION) {
Log.debug("Restarting action at behest of pender " +
pender + ".");
startAction();
}
} else {
Log.debug("Queueing action pender " + pender + ".");
_clearPenders.add(pender);
}
}
/**
* Returns whether or not it is safe to clear the action. The default
* behavior is to not allow the action to be cleared until all
* interesting sprites and animations in the board view have finished.
* If derived classes or delegates wish to postpone the clearing of
* the action, they can return false from this method, but they must
* then be sure to call {@link #maybeClearAction} when whatever
* condition that caused them to desire to postpone action clearing
* has finally been satisfied.
*/
protected boolean canClearAction ()
{
final boolean[] canClear = new boolean[1];
canClear[0] = (_pview.getActionCount() == 0);
// if (!canClear[0]) {
// _pview.dumpActors();
// PuzzleBoardView.DEBUG_ACTION = true;
// let our delegates do their business
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
canClear[0] = canClear[0] &&
((PuzzleControllerDelegate)delegate).canClearAction();
}
});
return canClear[0];
}
/**
* Called to effect the actual clearing of our action if we've
* received some asynchronous trigger that indicates that it may well
* be safe now to clear the action.
*/
protected void maybeClearAction ()
{
if (_astate == CLEAR_PENDING && canClearAction()) {
actuallyClearAction();
// } else {
// Log.info("Not clearing action [astate=" + _astate +
// ", canClear=" + canClearAction() + "].");
}
}
/**
* Performs the actual process of clearing the action for this puzzle.
* This is only called after it is known to be safe to clear the
* action. Derived classes can override this method and clear out
* anything that is not needed while the puzzle's "action" is not
* going (timers, etc.). Anything that is cleared out here should be
* recreated in {@link #startAction}.
*/
protected void actuallyClearAction ()
{
Log.debug("Actually clearing action.");
// make a note that we've cleared the action
_astate = ACTION_CLEARED;
// PuzzleBoardView.DEBUG_ACTION = false;
// let our delegates do their business
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
((PuzzleControllerDelegate)delegate).clearAction();
}
});
// let our panel know what's up
_panel.clearAction();
_panel.setPuzzleGrabsKeys(false); // let the user chat
// deliver one final update to the server
sendProgressUpdate();
// let derived classes do things
try {
actionWasCleared();
} catch (Exception e) {
Log.warning("Choked in actionWasCleared");
Log.logStackTrace(e);
}
// notify any penders that the action has cleared
final int[] results = new int[2];
_clearPenders.apply(new ObserverList.ObserverOp() {
public boolean apply (Object observer) {
switch (((ClearPender)observer).actionCleared()) {
case ClearPender.RESTART_ACTION: results[0]++; break;
case ClearPender.NO_RESTART_ACTION: results[1]++; break;
}
return true;
}
});
_clearPenders.clear();
// if there are no refusals and at least one restart request, go
// ahead and restart the action now
if (results[1] == 0 && results[0] > 0) {
startAction();
}
}
/**
* Called when the action was actually cleared, but before the action
* obsevers are notified.
*/
protected void actionWasCleared ()
{
}
// documentation inherited
public boolean handleAction (ActionEvent action)
{
String cmd = action.getActionCommand();
if (cmd.equals(TOGGLE_CHATTING)) {
setChatting(!isChatting());
} else {
return super.handleAction(action);
}
return true;
}
/**
* Returns the delay in milliseconds between sending each progress
* update event to the server. Derived classes may wish to override
* this to send their progress updates more or less frequently than
* the default.
*/
protected long getProgressInterval ()
{
return DEFAULT_PROGRESS_INTERVAL;
}
/**
* Signal the game to generate and distribute a new board.
*/
protected void generateNewBoard ()
{
// wait for any animations or sprites in the board to finish their
// business before setting the board into place
fireWhenActionCleared(new ClearPender() {
public int actionCleared () {
// update the player board
_pboard = newBoard();
if (_puzobj.seed != 0) {
_pboard.initializeSeed(_puzobj.seed);
}
setBoard(_pboard);
_pview.setBoard(_pboard);
// and repaint things
_pview.repaint();
// let our delegates do their business
DelegateOp dop = new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
((PuzzleControllerDelegate)delegate).setBoard(_pboard);
}
};
applyToDelegates(PuzzleControllerDelegate.class, dop);
return CARE_NOT;
}
});
}
/**
* Returns the number of progress events currently queued up for
* sending to the server with the next progress update.
*/
public int getEventCount ()
{
return _events.size();
}
/**
* Are we syncing boards for this puzzle?
* By default, we defer to the PuzzlePanel and its runtime config.
*/
protected boolean isSyncingBoards ()
{
return PuzzlePanel.isSyncingBoards();
}
/**
* Adds the given progress event and a snapshot of the supplied board
* state to the set of progress events and associated board states for
* later transmission to the server.
*/
public void addProgressEvent (int event, Board board)
{
// make sure they don't queue things up at strange times
if (_puzobj.state != PuzzleObject.IN_PLAY) {
Log.warning("Rejecting progress event; game not in play " +
"[puzobj=" + _puzobj.which() +
", event=" + event + "].");
return;
}
_events.add(new Integer(event));
if (isSyncingBoards()) {
_states.add((board == null) ? null : board.clone());
if (board == null) {
Log.warning("Added progress event with no associated board " +
"state, server will not be able to ensure " +
"board state synchronization.");
}
}
}
/**
* Sends the server a game progress update with the list of events, as
* well as board states if {@link PuzzlePanel#isSyncingBoards} is true.
*/
public void sendProgressUpdate ()
{
// make sure we have our puzzle object and events to send
int size = _events.size();
if (size == 0 || _puzobj == null) {
return;
}
// create an array of the events we're sending to the server
int[] events = CollectionUtil.toIntArray(_events);
_events.clear();
// Log.info("Sending progress [round=" + _puzobj.roundId +
// ", events=" + StringUtil.toString(events) + "].");
// create an array of the board states that correspond with those
// events (if state syncing is enabled)
int numStates = _states.size();
if (numStates == size) { // ie, if we have a board to match every event
Board[] states = new Board[numStates];
_states.toArray(states);
_states.clear();
// send the update progress request
_puzobj.puzzleGameService.updateProgressSync(
_ctx.getClient(), _puzobj.roundId, events, states);
} else {
// send the update progress request
_puzobj.puzzleGameService.updateProgress(
_ctx.getClient(), _puzobj.roundId, events);
}
}
/**
* Called when a player is knocked out of the game to give the puzzle
* a chance to perform any post-knockout actions that may be desired.
* Derived classes may wish to override this method but should be sure
* to call <code>super.playerKnockedOut()</code>.
*/
protected void playerKnockedOut (final int pidx)
{
// dispatch this to our delegates
applyToDelegates(PuzzleControllerDelegate.class, new DelegateOp() {
public void apply (PlaceControllerDelegate delegate) {
((PuzzleControllerDelegate)delegate).playerKnockedOut(pidx);
}
});
}
/**
* Catches clicks an unpauses, without passing the click through
* to the puzzle.
*/
class Unpauser extends MouseHijacker
{
public Unpauser (PuzzlePanel panel)
{
super(panel.getBoardView());
_panel = panel;
panel.addMouseListener(_clicker);
panel.getBoardView().addMouseListener(_clicker);
}
public Component release ()
{
_panel.removeMouseListener(_clicker);
_panel.getBoardView().removeMouseListener(_clicker);
return super.release();
}
protected MouseAdapter _clicker = new MouseAdapter() {
public void mousePressed (MouseEvent event) {
setChatting(false); // this will call release
}
};
protected PuzzlePanel _panel;
}
/** A special frame participant that handles the sending of puzzle
* progress updates. We can't just
* register an interval for this because sometimes the clock goes
* backwards in time in windows and our intervals don't get called for
* a long period of time which causes the server to think the client
* is disconnected or cheating and resign them from the puzzle. God
* bless you, Microsoft. */
protected class Updater implements FrameParticipant
{
public void tick (long tickStamp) {
if (_astate == ACTION_CLEARED) {
// remove ourselves as the action is now cleared; we can't
// do this in actuallyClearAction() because that might get
// called during the PuzzlePanel's frame tick and it's
// only safe to remove yourself during a tick(), not
// another frame participant
_pctx.getFrameManager().removeFrameParticipant(_updater);
} else if (tickStamp - _lastProgressTick > getProgressInterval()) {
_lastProgressTick = tickStamp;
sendProgressUpdate();
}
}
public boolean needsPaint () {
return false;
}
public Component getComponent () {
return null;
}
public long _lastProgressTick;
}
/**
* Create the updater to be used in this puzzle.
*/
protected Updater createUpdater ()
{
return new Updater();
}
/** The mouse jockey for unpausing our puzzles. */
protected Unpauser _unpauser;
/** Handles the sending of puzzle progress updates. */
protected Updater _updater = createUpdater();
/** Listens for players being knocked out. */
protected ElementUpdateListener _kolist = new ElementUpdateListener() {
public void elementUpdated (ElementUpdatedEvent event) {
String name = event.getName();
if (name.equals(PuzzleObject.PLAYER_STATUS)) {
if (event.getIntValue() == GameObject.PLAYER_LEFT_GAME) {
playerKnockedOut(event.getIndex());
}
}
}
};
/** Listens for various attribute changes. */
protected AttributeChangeListener _mlist = new AttributeChangeListener() {
public void attributeChanged (AttributeChangedEvent event) {
String name = event.getName();
if (name.equals(PuzzleObject.SEED)) {
generateNewBoard();
}
}
};
/** A casted reference to the client context. */
protected PuzzleContext _pctx;
/** Our player index in the game. */
protected int _pidx;
/** The puzzle panel. */
protected PuzzlePanel _panel;
/** The puzzle config. */
protected PuzzleConfig _puzconfig;
/** A reference to our puzzle game object. */
protected PuzzleObject _puzobj;
/** The puzzle board view. */
protected PuzzleBoardView _pview;
/** The puzzle board data. */
protected Board _pboard;
/** The list of relevant game events since the last progress update. */
protected ArrayList _events = new ArrayList();
/** Board snapshots that correspond to our board state after each of
* our events has been applied. */
protected ArrayList _states = new ArrayList();
/** A flag indicating that we're in chatting mode. */
protected boolean _chatting = false;
/** The current action state of the puzzle. */
protected int _astate = ACTION_CLEARED;
/** The action cleared penders. */
protected ObserverList _clearPenders = new ObserverList(
ObserverList.SAFE_IN_ORDER_NOTIFY);
/** A key listener that currently just toggles pause in the puzzle. */
protected KeyListener _globalKeyListener = new KeyAdapter() {
public void keyReleased (KeyEvent e)
{
int keycode = e.getKeyCode();
// toggle chatting (pause)
if (keycode == KeyEvent.VK_ESCAPE || keycode == KeyEvent.VK_PAUSE) {
setChatting(!isChatting());
// pressing P also to pause (but not unpause),
// and only if it has not been reassigned
} else if (keycode == KeyEvent.VK_P && !isChatting() &&
!_panel._xlate.hasCommand(KeyEvent.VK_P)) {
setChatting(true);
}
}
};
/** The delay in milliseconds between progress update intervals. */
protected static final long DEFAULT_PROGRESS_INTERVAL = 6000L;
/** A {@link #_astate} constant. */
protected static final int ACTION_CLEARED = 0;
/** A {@link #_astate} constant. */
protected static final int CLEAR_PENDING = 1;
/** A {@link #_astate} constant. */
protected static final int ACTION_GOING = 2;
}
|
package com.e16din.intentmaster;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import com.e16din.intentmaster.model.Data;
import java.io.Serializable;
public final class IntentMaster {
private IntentMaster() {
super();
}
//new fragment
public static Fragment newFragment(Fragment fragment, Data... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static Fragment newFragment(Fragment fragment, Serializable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static Fragment newFragment(Fragment fragment, Parcelable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static DialogFragment newDialogFragment(DialogFragment fragment, Data... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static DialogFragment newDialogFragment(DialogFragment fragment, Serializable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static DialogFragment newDialogFragment(DialogFragment fragment, Parcelable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static android.app.DialogFragment newDialogFragment(android.app.DialogFragment fragment, Data... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static android.app.DialogFragment newDialogFragment(android.app.DialogFragment fragment, Serializable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static android.app.DialogFragment newDialogFragment(android.app.DialogFragment fragment, Parcelable... data) {
Bundle bundle = Create.bundle(data);
fragment.setArguments(bundle);
return fragment;
}
public static Serializable getArgument(@NonNull Fragment fragment, @NonNull String key) {
return Extra.get(fragment, key);
}
public static Serializable getArgument(@NonNull Fragment fragment) {
return Extra.get(fragment);
}
public static Serializable getArgument(@NonNull Fragment fragment, int position) {
return Extra.get(fragment, position);
}
public static Parcelable getArgumentP(@NonNull Fragment fragment, @NonNull String key) {
return Extra.getP(fragment, key);
}
public static Parcelable getArgumentP(@NonNull Fragment fragment) {
return Extra.getP(fragment);
}
public static Parcelable getArgumentP(@NonNull Fragment fragment, int position) {
return Extra.getP(fragment, position);
}
//start activity
public static void start(Context context, @NonNull Class cls) {
Intent intent = Create.intent(context, cls);
context.startActivity(intent);
}
public static void start(Context context, @NonNull Class cls, Data... data) {
Intent intent = Create.intent(context, cls, data);
context.startActivity(intent);
}
public static void start(Context context, @NonNull Class cls, Serializable... data) {
Intent intent = Create.intent(context, cls, data);
context.startActivity(intent);
}
public static void start(Context context, @NonNull Class cls, Parcelable... data) {
Intent intent = Create.intent(context, cls, data);
context.startActivity(intent);
}
public static void startForResult(@NonNull Activity activity, @NonNull Class cls, int requestCode) {
Intent intent = Create.intent(activity, cls);
activity.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Activity activity, @NonNull Class cls, int requestCode,
Data... data) {
Intent intent = Create.intent(activity, cls, data);
activity.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Activity activity, @NonNull Class cls, int requestCode,
Serializable... data) {
Intent intent = Create.intent(activity, cls, data);
activity.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Activity activity, @NonNull Class cls, int requestCode,
Parcelable... data) {
Intent intent = Create.intent(activity, cls, data);
activity.startActivityForResult(intent, requestCode);
}
public static void startForResult0(@NonNull Activity activity, @NonNull Class cls) {
startForResult(activity, cls, 0);
}
public static void startForResult0(@NonNull Activity activity, @NonNull Class cls, Data... data) {
startForResult(activity, cls, 0, data);
}
public static void startForResult0(@NonNull Activity activity, @NonNull Class cls,
Serializable... data) {
startForResult(activity, cls, 0, data);
}
public static void startForResult0(@NonNull Activity activity, @NonNull Class cls,
Parcelable... data) {
startForResult(activity, cls, 0, data);
}
//start activity for result
public static void startForResult(@NonNull Fragment fragment, @NonNull Class cls, int requestCode) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls);
fragment.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Fragment fragment, @NonNull Class cls, int requestCode,
Data... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Fragment fragment, @NonNull Class cls, int requestCode,
Serializable... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
public static void startForResult(@NonNull Fragment fragment, @NonNull Class cls, int requestCode,
Parcelable... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
public static void startForResult0(@NonNull Fragment fragment, @NonNull Class cls) {
startForResult(fragment, cls, 0);
}
public static void startActivityForResult0(@NonNull Fragment fragment, @NonNull Class cls, Data... data) {
startForResult(fragment, cls, 0, data);
}
public static void startForResult0(@NonNull Fragment fragment, @NonNull Class cls,
Serializable... data) {
startForResult(fragment, cls, 0, data);
}
public static void startForResult0(@NonNull Fragment fragment, @NonNull Class cls,
Parcelable... data) {
startForResult(fragment, cls, 0, data);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void startForResult(@NonNull android.app.Fragment fragment, @NonNull Class cls, int requestCode) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls);
fragment.startActivityForResult(intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void startForResult(@NonNull android.app.Fragment fragment, @NonNull Class cls, int requestCode,
Data... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void startForResult(@NonNull android.app.Fragment fragment, @NonNull Class cls, int requestCode,
Serializable... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void startForResult(@NonNull android.app.Fragment fragment, @NonNull Class cls, int requestCode,
Parcelable... data) {
Activity activity = fragment.getActivity();
Intent intent = Create.intent(activity, cls, data);
fragment.startActivityForResult(intent, requestCode);
}
public static void startForResult0(@NonNull android.app.Fragment fragment, @NonNull Class cls) {
startForResult(fragment, cls, 0);
}
public static void startForResult0(@NonNull android.app.Fragment fragment, @NonNull Class cls, Data... data) {
startForResult(fragment, cls, 0, data);
}
public static void startForResult0(@NonNull android.app.Fragment fragment, @NonNull Class cls,
Serializable... data) {
startForResult(fragment, cls, 0, data);
}
public static void startForResult0(@NonNull android.app.Fragment fragment, @NonNull Class cls,
Parcelable... data) {
startForResult(fragment, cls, 0, data);
}
// get extra
public static Serializable getExtra(@NonNull Intent intent, @NonNull String key) {
return Extra.get(intent, key);
}
public static Serializable getExtra(@NonNull Intent intent) {
return Extra.get(intent);
}
public static Serializable getExtra(@NonNull Intent intent, int position) {
return Extra.get(intent, position);
}
public static Serializable getExtra(@NonNull Activity activity) {
return Extra.get(activity);
}
public static Serializable getExtra(@NonNull Activity activity, @NonNull String key) {
return Extra.get(activity, key);
}
public static Serializable getExtra(@NonNull Activity activity, int position) {
return Extra.get(activity, position);
}
public static Parcelable getExtraP(@NonNull Intent intent, @NonNull String key) {
return Extra.getP(intent, key);
}
public static Parcelable getExtraP(@NonNull Intent intent) {
return Extra.getP(intent);
}
public static Parcelable getExtraP(@NonNull Intent intent, int position) {
return Extra.getP(intent, position);
}
public static Parcelable getExtraP(@NonNull Activity activity) {
return Extra.getP(activity);
}
public static Parcelable getExtraP(@NonNull Activity activity, @NonNull String key) {
return Extra.getP(activity, key);
}
public static Parcelable getExtraP(@NonNull Activity activity, int position) {
return Extra.getP(activity, position);
}
public static boolean containsKey(@NonNull Intent intent, @NonNull String key) {
return Extra.containsKey(intent, key);
}
public static int getExtrasCount(@NonNull Intent intent) {
return Extra.getExtrasCount(intent);
}
public static int getExtrasCount(@NonNull Activity activity) {
return Extra.getExtrasCount(activity);
}
public static boolean hasExtra(@NonNull Intent intent) {
return Extra.has(intent);
}
public static boolean hasExtra(@NonNull Activity activity) {
return Extra.has(activity);
}
//broadcast
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void sendBroadcast(@NonNull android.app.Fragment fragment, @NonNull String action) {
Intent intent = Create.intent(action);
fragment.getActivity().sendBroadcast(intent);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void sendBroadcast(@NonNull android.app.Fragment fragment, @NonNull String action, Data... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void sendBroadcast(@NonNull android.app.Fragment fragment, @NonNull String action, Serializable... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void sendBroadcast(@NonNull android.app.Fragment fragment, @NonNull String action, Parcelable... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Fragment fragment, @NonNull String action) {
Intent intent = Create.intent(action);
fragment.getActivity().sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Fragment fragment, @NonNull String action, Data... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Fragment fragment, @NonNull String action, Serializable... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Fragment fragment, @NonNull String action, Parcelable... data) {
Intent intent = Create.intent(action, data);
fragment.getActivity().sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Activity activity, @NonNull String action) {
Intent intent = Create.intent(action);
activity.sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Activity activity, @NonNull String action, Data... data) {
Intent intent = Create.intent(action, data);
activity.sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Activity activity, @NonNull String action, Serializable... data) {
Intent intent = Create.intent(action, data);
activity.sendBroadcast(intent);
}
public static void sendBroadcast(@NonNull Activity activity, @NonNull String action, Parcelable... data) {
Intent intent = Create.intent(action, data);
activity.sendBroadcast(intent);
}
//todo: show view by url
}
|
package com.conveyal.r5.analyst.broker;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;
import com.conveyal.r5.analyst.cluster.GenericClusterRequest;
import com.conveyal.r5.common.JsonUtilities;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectLongMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.HttpStatus;
import com.conveyal.r5.analyst.cluster.AnalystWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* This class tracks incoming requests from workers to consume Analyst tasks, and attempts to match those
* requests to enqueued tasks. It aims to draw tasks fairly from all users, and fairly from all jobs within each user,
* while attempting to respect the graph affinity of each worker (give it tasks that require the same graph it has been
* working on recently).
*
* When no work is available or no workers are available, the polling functions return immediately, avoiding spin-wait.
* When they are receiving no work, workers are expected to disconnect and re-poll occasionally, on the order of 30
* seconds. This serves as a signal to the broker that they are still alive and waiting.
*
* TODO if there is a backlog of work (the usual case when jobs are lined up) workers will constantly change graphs.
* Because (at least currently) two users never share the same graph, we can get by with pulling tasks cyclically or
* randomly from all the jobs, and just actively shaping the number of workers with affinity for each graph by forcing
* some of them to accept tasks on graphs other than the one they have declared affinity for.
*
* This could be thought of as "affinity homeostasis". We will constantly keep track of the ideal proportion of workers
* by graph (based on active queues), and the true proportion of consumers by graph (based on incoming requests) then
* we can decide when a worker's graph affinity should be ignored and what it should be forced to.
*
* It may also be helpful to mark jobs every time they are skipped in the LRU queue. Each time a job is serviced,
* it is taken out of the queue and put at its end. Jobs that have not been serviced float to the top.
*
* TODO: occasionally purge closed connections from workersByCategory
* TODO: worker catalog and graph affinity homeostasis
* TODO: catalog of recently seen consumers by affinity with IP: response.getRequest().getRemoteAddr();
*/
public class Broker implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Broker.class);
public final CircularList<Job> jobs = new CircularList<>();
/** The most tasks to deliver to a worker at a time. */
public final int MAX_TASKS_PER_WORKER = 8;
/**
* How long to give workers to start up (in ms) before assuming that they have started (and starting more
* on a given graph if they haven't.
*/
public static final long WORKER_STARTUP_TIME = 60 * 60 * 1000;
private int nUndeliveredTasks = 0; // Including normal priority jobs and high-priority tasks. TODO check that this total is really properly maintained
private int nWaitingConsumers = 0; // including some that might be closed
private int nextTaskId = 0;
/** Maximum number of workers allowed */
private int maxWorkers;
private static final ObjectMapper mapper = JsonUtilities.objectMapper;
private long nextRedeliveryCheckTime = System.currentTimeMillis();
/*static {
mapper.registerModule(AgencyAndIdSerializer.makeModule());
mapper.registerModule(QualifiedModeSetSerializer.makeModule());
mapper.registerModule(JavaLocalDateSerializer.makeModule());
mapper.registerModule(TraverseModeSetSerializer.makeModule());
}*/
/** The configuration for this broker. */
private final Properties brokerConfig;
/** The configuration that will be applied to workers launched by this broker. */
private final Properties workerConfig;
/** Keeps track of all the workers that have contacted this broker recently asking for work. */
protected WorkerCatalog workerCatalog = new WorkerCatalog();
/**
* Requests that are not part of a job and can "cut in line" in front of jobs for immediate execution.
* When a high priority task is first received, we attempt to send it to a worker right away via
* the side channels. If that doesn't work, we put them here to be picked up the next time a worker
* is available via normal task distribution channels.
*/
private ArrayListMultimap<WorkerCategory, GenericClusterRequest> stalledHighPriorityTasks = ArrayListMultimap.create();
/**
* High priority requests that have just come and are about to be sent down a single point channel.
* They put here for just 100 ms so that any that arrive together are batched to the same worker.
* If we didn't do this, two requests arriving at basically the same time could get fanned out to
* two different workers because the second came in in between closing the side channel and the worker
* reopening it.
*/
private Multimap<WorkerCategory, GenericClusterRequest> newHighPriorityTasks = ArrayListMultimap.create();
/** Priority requests that have already been farmed out to workers, and are awaiting a response. */
private TIntObjectMap<Response> highPriorityResponses = new TIntObjectHashMap<>();
/** Outstanding requests from workers for tasks, grouped by worker graph affinity. */
Map<WorkerCategory, Deque<Response>> workersByCategory = new HashMap<>();
/**
* Side channels used to send single point requests to workers, cutting in front of any other work on said workers.
* We use a TreeMultimap because it is ordered, and the wrapped response defines an order based on
* machine ID. This way, the same machine will tend to get all single point work for a graph,
* so multiple machines won't stay alive to do single point work.
*/
private Multimap<WorkerCategory, WrappedResponse> singlePointChannels = TreeMultimap.create();
/** should we work offline */
private boolean workOffline;
private AmazonEC2 ec2;
private Timer timer = new Timer();
private String workerName, project;
/**
* keep track of which graphs we have launched workers on and how long ago we launched them,
* so that we don't re-request workers which have been requested.
*/
private TObjectLongMap<WorkerCategory> recentlyRequestedWorkers = new TObjectLongHashMap<>();
// Queue of tasks to complete Delete, Enqueue etc. to avoid synchronizing all the functions ?
public Broker (Properties brokerConfig, String addr, int port) {
// print out date on startup so that CloudWatch logs has a unique fingerprint
LOG.info("Analyst broker starting at {}", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
this.brokerConfig = brokerConfig;
// create a config for the AWS workers
workerConfig = new Properties();
// load the base worker configuration if specified
if (this.brokerConfig.getProperty("worker-config") != null) {
try {
File f = new File(this.brokerConfig.getProperty("worker-config"));
FileInputStream fis = new FileInputStream(f);
workerConfig.load(fis);
fis.close();
} catch (IOException e) {
LOG.error("Error loading base worker configuration", e);
}
}
workerConfig.setProperty("broker-address", addr);
workerConfig.setProperty("broker-port", "" + port);
if (brokerConfig.getProperty("statistics-queue") != null)
workerConfig.setProperty("statistics-queue", brokerConfig.getProperty("statistics-queue"));
workerConfig.setProperty("graphs-bucket", brokerConfig.getProperty("graphs-bucket"));
workerConfig.setProperty("pointsets-bucket", brokerConfig.getProperty("pointsets-bucket"));
// Tell the workers to shut themselves down automatically
workerConfig.setProperty("auto-shutdown", "true");
Boolean workOffline = Boolean.parseBoolean(brokerConfig.getProperty("work-offline"));
if (workOffline == null) workOffline = true;
this.workOffline = workOffline;
workerName = brokerConfig.getProperty("worker-name") != null ? brokerConfig.getProperty("worker-name") : "analyst-worker";
project = brokerConfig.getProperty("project") != null ? brokerConfig.getProperty("project") : "analyst";
this.maxWorkers = brokerConfig.getProperty("max-workers") != null ? Integer.parseInt(brokerConfig.getProperty("max-workers")) : 4;
ec2 = new AmazonEC2Client();
// default to current region when running in EC2
com.amazonaws.regions.Region r = Regions.getCurrentRegion();
if (r != null)
ec2.setRegion(r);
}
/**
* Enqueue a task for execution ASAP, planning to return the response over the same HTTP connection.
* Low-reliability, no re-delivery.
*/
public synchronized void enqueuePriorityTask (GenericClusterRequest task, Response response) {
boolean workersAvailable = workersAvailable(task.getWorkerCategory());
if (!workersAvailable) {
createWorkersInCategory(task.getWorkerCategory());
// chances are it won't be done in 30 seconds, but we want to poll frequently to avoid issues with phasing
try {
response.setHeader("Retry-After", "30");
response.sendError(503,
"No workers available in this category, please retry shortly.");
} catch (IOException e) {
LOG.error("Could not finish high-priority 503 response", e);
}
}
// if we're in offline mode, enqueue anyhow to kick the cluster to build the graph
// note that this will mean that requests get delivered multiple times in offline mode,
// so some unnecessary computation takes place
if (workersAvailable || workOffline) {
task.taskId = nextTaskId++;
newHighPriorityTasks.put(task.getWorkerCategory(), task);
highPriorityResponses.put(task.taskId, response);
// wait 100ms to deliver to workers in case another request comes in almost simultaneously
timer.schedule(new TimerTask() {
@Override
public void run() {
deliverHighPriorityTasks(task.getWorkerCategory());
}
}, 100);
}
// do not notify task delivery thread just yet as we haven't put anything in the task delivery queue yet.
}
/** Attempt to deliver high priority tasks via side channels, or move them into normal channels if need be. */
public synchronized void deliverHighPriorityTasks (WorkerCategory category) {
Collection<GenericClusterRequest> tasks = newHighPriorityTasks.get(category);
if (tasks.isEmpty())
// someone got here first
return;
// try to deliver via side channels
Collection<WrappedResponse> wrs = singlePointChannels.get(category);
if (!wrs.isEmpty()) {
// there is (probably) a single point machine waiting to receive this
WrappedResponse wr = wrs.iterator().next();
try {
wr.response.setContentType("application/json");
OutputStream os = wr.response.getOutputStream();
mapper.writeValue(os, tasks);
os.close();
wr.response.resume();
newHighPriorityTasks.removeAll(category);
return;
} catch (Exception e) {
LOG.info("Failed to deliver single point job via side channel, reverting to normal channel", e);
} finally {
// remove responses whether they are dead or alive
removeSinglePointChannel(category, wr);
}
}
// if we got here we didn't manage to send it via side channel, put it in the rotation for normal channels
// not using putAll as it retains a link to the original collection and then we get a concurrent modification exception later.
tasks.forEach(t -> stalledHighPriorityTasks.put(category, t));
LOG.info("No side channel available for graph {}, delivering {} tasks via normal channel",
category, tasks.size());
nUndeliveredTasks += tasks.size();
newHighPriorityTasks.removeAll(category);
// wake up delivery thread
notify();
}
/** Enqueue some tasks for queued execution possibly much later. Results will be saved to S3. */
public synchronized void enqueueTasks (List<GenericClusterRequest> tasks) {
Job job = findJob(tasks.get(0)); // creates one if it doesn't exist
if (!workersAvailable(job.getWorkerCategory())) {
createWorkersInCategory(job.getWorkerCategory());
}
for (GenericClusterRequest task : tasks) {
task.taskId = nextTaskId++;
job.addTask(task);
nUndeliveredTasks += 1;
LOG.debug("Enqueued task id {} in job {}", task.taskId, job.jobId);
if (!task.graphId.equals(job.workerCategory.graphId)) {
LOG.error("Task graph ID {} does not match job: {}.", task.graphId, job.workerCategory);
}
if (!task.workerVersion.equals(job.workerCategory.workerVersion)) {
LOG.error("Task R5 commit {} does not match job: {}.", task.workerVersion, job.workerCategory);
}
}
// Wake up the delivery thread if it's waiting on input.
// This wakes whatever thread called wait() while holding the monitor for this Broker object.
notify();
}
public boolean workersAvailable (WorkerCategory category) {
// Ensure we don't assign work to dead workers.
workerCatalog.purgeDeadWorkers();
return !workerCatalog.workersByCategory.get(category).isEmpty();
}
/** Create workers for a given job, if need be */
public void createWorkersInCategory (WorkerCategory category) {
String clientToken = UUID.randomUUID().toString().replaceAll("-", "");
if (workOffline) {
LOG.info("Work offline enabled, not creating workers for {}", category);
return;
}
if (workerCatalog.observationsByWorkerId.size() >= maxWorkers) {
LOG.warn("{} workers already started, not starting more; jobs will not complete on {}", maxWorkers, category);
return;
}
// If workers have already been started up, don't repeat the operation.
if (recentlyRequestedWorkers.containsKey(category)
&& recentlyRequestedWorkers.get(category) >= System.currentTimeMillis() - WORKER_STARTUP_TIME){
LOG.info("Workers still starting on {}, not starting more", category);
return;
}
// TODO: compute
int nWorkers = 1;
// There are no workers on this graph with the right worker commit, start some.
LOG.info("Starting {} workers as there are none on {}", nWorkers, category);
RunInstancesRequest req = new RunInstancesRequest();
req.setImageId(brokerConfig.getProperty("ami-id"));
req.setInstanceType(InstanceType.valueOf(brokerConfig.getProperty("worker-type")));
req.setSubnetId(brokerConfig.getProperty("subnet-id"));
// even if we can't get all the workers we want at least get some
req.setMinCount(1);
req.setMaxCount(nWorkers);
// It's fine to just modify the worker config without a protective copy because this method is synchronized.
workerConfig.setProperty("initial-graph-id", category.graphId);
workerConfig.setProperty("worker-version", category.workerVersion);
String workerDownloadUrl = String.format("http://maven.conveyal.com/com/conveyal/r5/%s/r5-%s-shaded.jar",
category.workerVersion, category.workerVersion);
workerConfig.setProperty("download-url", workerDownloadUrl);
// This is the R5 broker, so always start R5 workers (rather than OTP workers)
workerConfig.setProperty("use-transport-networks", "true");
ByteArrayOutputStream cfg = new ByteArrayOutputStream();
try {
workerConfig.store(cfg, "Worker config");
cfg.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
// Send the config to the new workers as EC2 "user data"
String userData = new String(Base64.getEncoder().encode(cfg.toByteArray()));
req.setUserData(userData);
if (brokerConfig.getProperty("worker-iam-role") != null)
req.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(brokerConfig.getProperty("worker-iam-role")));
// launch into a VPC if desired
if (brokerConfig.getProperty("subnet") != null)
req.setSubnetId(brokerConfig.getProperty("subnet"));
// allow us to retry request at will
req.setClientToken(clientToken);
// allow machine to shut itself completely off
req.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate);
RunInstancesResult res = ec2.runInstances(req);
res.getReservation().getInstances().forEach(i -> {
Collection<Tag> tags = Arrays.asList(
new Tag("name", workerName),
new Tag("project", project)
);
i.setTags(tags);
});
recentlyRequestedWorkers.put(category, System.currentTimeMillis());
LOG.info("Requesting {} workers", nWorkers);
}
/** Consumer long-poll operations are enqueued here. */
public synchronized void registerSuspendedResponse(WorkerCategory category, Response response) {
// Add this worker to our catalog, tracking its graph affinity and the last time it was seen.
String workerId = response.getRequest().getHeader(AnalystWorker.WORKER_ID_HEADER);
if (workerId != null && !workerId.isEmpty()) {
workerCatalog.catalog(workerId, category);
} else {
LOG.error("Worker did not supply a unique ID for itself . Ignoring it.");
return;
}
// Shelf this suspended response in a queue grouped by graph affinity.
Deque<Response> deque = workersByCategory.get(category);
if (deque == null) {
deque = new ArrayDeque<>();
workersByCategory.put(category, deque);
}
deque.addLast(response);
nWaitingConsumers += 1;
// Wake up the delivery thread if it's waiting on consumers.
// This is whatever thread called wait() while holding the monitor for this Broker object.
notify();
}
/** When we notice that a long poll connection has closed, we remove it here. */
public synchronized boolean removeSuspendedResponse(WorkerCategory category, Response response) {
Deque<Response> deque = workersByCategory.get(category);
if (deque == null) {
return false;
}
if (deque.remove(response)) {
nWaitingConsumers -= 1;
LOG.debug("Removed closed connection from queue.");
return true;
}
return false;
}
/**
* Register an HTTP connection that can be used to send single point requests directly to
* workers, bypassing normal task distribution channels.
*/
public synchronized void registerSinglePointChannel (WorkerCategory category, WrappedResponse response) {
singlePointChannels.put(category, response);
// No need to notify as the side channels are not used by the normal task delivery loop.
}
/**
* Remove a single point channel because the connection was closed.
*/
public synchronized boolean removeSinglePointChannel (WorkerCategory category, WrappedResponse response) {
return singlePointChannels.remove(category, response);
}
/**
* This method checks whether there are any high-priority tasks or normal job tasks and attempts to match them with
* waiting workers.
*
* It blocks by calling wait() whenever it has nothing to do (when no tasks or workers available). It is awakened
* whenever new tasks come in or when a worker (re-)connects.
*/
public synchronized void deliverTasks() throws InterruptedException {
// Wait until there are some undelivered tasks.
while (nUndeliveredTasks == 0) {
LOG.debug("Task delivery thread is going to sleep, there are no tasks waiting for delivery.");
// Thread will be notified when tasks are added or there are new incoming consumer connections.
wait();
// If a worker connected while there were no tasks queued for delivery,
// we need to check if any should be re-delivered.
for (Job job : jobs) {
nUndeliveredTasks += job.redeliver();
}
}
LOG.debug("Task delivery thread is awake and there are some undelivered tasks.");
while (nWaitingConsumers == 0) {
LOG.debug("Task delivery thread is going to sleep, there are no consumers waiting.");
// Thread will be notified when tasks are added or there are new incoming consumer connections.
wait();
}
LOG.debug("Task delivery thread awake; consumers are waiting and tasks are available");
// Loop over all jobs and send them to consumers
// This makes for an as-fair-as-possible allocation: jobs are fairly allocated between
// workers on their graph.
// start with high-priority tasks
HIGHPRIORITY: for (Map.Entry<WorkerCategory, Collection<GenericClusterRequest>> e : stalledHighPriorityTasks
.asMap().entrySet()) {
// the collection is an arraylist with the most recently added at the end
WorkerCategory workerCategory = e.getKey();
Collection<GenericClusterRequest> tasks = e.getValue();
// See if there are any workers that requested tasks in this category.
// Don't respect graph affinity when working offline; we can't arbitrarily start more workers.
Deque<Response> consumers;
if (!workOffline) {
consumers = workersByCategory.get(workerCategory);
} else {
Optional<Deque<Response>> opt = workersByCategory.values().stream().filter(c -> !c.isEmpty()).findFirst();
if (opt.isPresent()) consumers = opt.get();
else consumers = null;
}
if (consumers == null || consumers.isEmpty()) {
LOG.warn("No worker found for {}, needed for {} high-priority tasks", workerCategory, tasks.size());
continue HIGHPRIORITY;
}
Iterator<GenericClusterRequest> taskIt = tasks.iterator();
while (taskIt.hasNext() && !consumers.isEmpty()) {
Response consumer = consumers.pop();
// package tasks into a job
Job job = new Job("HIGH PRIORITY");
job.workerCategory = workerCategory;
for (int i = 0; i < MAX_TASKS_PER_WORKER && taskIt.hasNext(); i++) {
job.addTask(taskIt.next());
taskIt.remove();
}
// TODO inefficiency here: we should mix single point and multipoint in the same response
deliver(job, consumer);
nWaitingConsumers
}
}
// deliver low priority tasks
while (nWaitingConsumers > 0) {
// ensure we advance at least one; advanceToElement will not advance if the predicate passes
// for the first element.
jobs.advance();
// find a job that both has visible tasks and has available workers
// We don't respect graph affinity when working offline, because we can't start more workers
Job current;
if (!workOffline) {
current = jobs.advanceToElement(job -> !job.tasksAwaitingDelivery.isEmpty() &&
workersByCategory.containsKey(job.workerCategory) &&
!workersByCategory.get(job.workerCategory).isEmpty());
}
else {
current = jobs.advanceToElement(e -> !e.tasksAwaitingDelivery.isEmpty());
}
// nothing to see here
if (current == null) break;
Deque<Response> consumers;
if (!workOffline)
consumers = workersByCategory.get(current.workerCategory);
else {
Optional<Deque<Response>> opt = workersByCategory.values().stream().filter(c -> !c.isEmpty()).findFirst();
if (opt.isPresent()) consumers = opt.get();
else consumers = null;
}
// deliver this job to only one consumer
// This way if there are multiple workers and multiple jobs the jobs will be fairly distributed, more or less
deliver(current, consumers.pop());
nWaitingConsumers
}
// TODO: graph switching
// we've delivered everything we can, prevent anything else from happening until something changes
wait();
}
/**
* This uses a linear search through jobs, which should not be problematic unless there are thousands of
* simultaneous jobs. TODO task IDs should really not be sequential integers should they?
* @return a Job object that contains the given task ID.
*/
public Job getJobForTask (int taskId) {
for (Job job : jobs) {
if (job.containsTask(taskId)) {
return job;
}
}
return null;
}
/**
* Attempt to hand some tasks from the given job to a waiting consumer connection.
* The write will fail if the consumer has closed the connection but it hasn't been removed from the connection
* queue yet. This can happen because the Broker methods are synchronized, and the removal action may be waiting
* to get the monitor while we are trying to distribute tasks here.
* @return whether the handoff succeeded.
*/
public synchronized boolean deliver (Job job, Response response) {
// Check up-front whether the connection is still open.
if (!response.getRequest().getRequest().getConnection().isOpen()) {
LOG.debug("Consumer connection was closed. It will be removed.");
return false;
}
// Get up to N tasks from the tasksAwaitingDelivery deque
List<GenericClusterRequest> tasks = new ArrayList<>();
while (tasks.size() < MAX_TASKS_PER_WORKER && !job.tasksAwaitingDelivery.isEmpty()) {
tasks.add(job.tasksAwaitingDelivery.poll());
}
// Attempt to deliver the tasks to the given consumer.
try {
response.setStatus(HttpStatus.OK_200);
OutputStream out = response.getOutputStream();
mapper.writeValue(out, tasks);
response.resume();
} catch (IOException e) {
// The connection was probably closed by the consumer, but treat it as a server error.
LOG.debug("Consumer connection caused IO error, it will be removed.");
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
response.resume();
// Delivery failed, put tasks back on (the end of) the queue.
job.tasksAwaitingDelivery.addAll(tasks);
return false;
}
LOG.debug("Delivery of {} tasks succeeded.", tasks.size());
nUndeliveredTasks -= tasks.size(); // FIXME keeping a separate counter for this seems redundant, why not compute it?
job.lastDeliveryTime = System.currentTimeMillis();
return true;
}
/**
* Take a normal (non-priority) task out of a job queue, marking it as completed so it will not be re-delivered.
* TODO maybe use unique delivery receipts instead of task IDs to handle redelivered tasks independently
* @return whether the task was found and removed.
*/
public synchronized boolean markTaskCompleted (int taskId) {
Job job = getJobForTask(taskId);
if (job == null) {
LOG.error("Could not find a job containing task {}, and therefore could not mark the task as completed.", taskId);
return false;
}
job.completedTasks.add(taskId);
return true;
}
/**
* Marks the specified priority request as completed, and returns the suspended Response object for the connection
* that submitted the priority request (the UI), which probably still waiting to receive a result back over the
* same connection. A HttpHandler thread can then pump data from the DELETE body back to the origin of the request,
* without blocking the broker thread.
* TODO rename to "deregisterSuspendedProducer" and "deregisterSuspendedConsumer" ?
*/
public synchronized Response deletePriorityTask (int taskId) {
return highPriorityResponses.remove(taskId);
}
/** This is the broker's main event loop. */
@Override
public void run() {
while (true) {
try {
deliverTasks();
} catch (InterruptedException e) {
LOG.info("Task pump thread was interrupted.");
return;
}
}
}
/** Find the job that should contain a given task, creating that job if it does not exist. */
public Job findJob (GenericClusterRequest task) {
Job job = findJob(task.jobId);
if (job != null) {
return job;
}
job = new Job(task.jobId);
job.workerCategory = new WorkerCategory(task.graphId, task.workerVersion);
jobs.insertAtTail(job);
return job;
}
/** Find the job for the given jobId, returning null if that job does not exist. */
public Job findJob (String jobId) {
for (Job job : jobs) {
if (job.jobId.equals(jobId)) {
return job;
}
}
return null;
}
/** Delete the job with the given ID. */
public synchronized boolean deleteJob (String jobId) {
Job job = findJob(jobId);
if (job == null) return false;
nUndeliveredTasks -= job.tasksAwaitingDelivery.size();
return jobs.remove(job);
}
/** Returns whether this broker is tracking and jobs that have unfinished tasks. */
public synchronized boolean anyJobsActive() {
for (Job job : jobs) {
if (!job.isComplete()) return true;
}
return false;
}
/**
* We wrap responses in a class that has a machine ID, and then put them in a TreeSet so that
* the machine with the lowest ID on a given graph always gets single-point work. The reason
* for this is so that a single machine will tend to get single-point work and thus we don't
* unnecessarily keep multiple multipoint machines alive.
*/
public static class WrappedResponse implements Comparable<WrappedResponse> {
public final Response response;
public final String machineId;
public WrappedResponse(Request request, Response response) {
this.response = response;
this.machineId = request.getHeader(AnalystWorker.WORKER_ID_HEADER);
}
@Override public int compareTo(WrappedResponse wrappedResponse) {
return this.machineId.compareTo(wrappedResponse.machineId);
}
}
}
|
package net.hillsdon.reviki.wiki.renderer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.common.base.Supplier;
import net.hillsdon.reviki.vc.PageInfo;
import net.hillsdon.reviki.vc.PageStore;
import net.hillsdon.reviki.web.urls.URLOutputFilter;
import net.hillsdon.reviki.wiki.MarkupRenderer;
import net.hillsdon.reviki.wiki.renderer.creole.CreoleRenderer;
import net.hillsdon.reviki.wiki.renderer.creole.LinkPartsHandler;
import net.hillsdon.reviki.wiki.renderer.creole.ast.*;
import net.hillsdon.reviki.wiki.renderer.macro.Macro;
/**
* A renderer for Docbook. Rather than an XML document, this renders to an input
* stream for easy integration with the http output. The document (and string
* serialisation) can be accessed with the
* {@link #buildString(ASTNode, URLOutputFilter)} and
* {@link #buildDocument(ASTNode, URLOutputFilter)} methods.
*
* @author msw
*/
public class DocbookRenderer extends MarkupRenderer<InputStream> {
private final PageStore _pageStore;
private final LinkPartsHandler _linkHandler;
private final LinkPartsHandler _imageHandler;
private final Supplier<List<Macro>> _macros;
public DocbookRenderer(final PageStore pageStore, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler, final Supplier<List<Macro>> macros) {
_pageStore = pageStore;
_linkHandler = linkHandler;
_imageHandler = imageHandler;
_macros = macros;
}
@Override
public ASTNode render(final PageInfo page) {
return CreoleRenderer.render(_pageStore, page, _linkHandler, _imageHandler, _macros);
}
@Override
public InputStream build(final ASTNode ast, final URLOutputFilter urlOutputFilter) {
String out = buildString(ast, urlOutputFilter);
return new ByteArrayInputStream(out.getBytes(StandardCharsets.UTF_8));
}
@Override
public String getContentType() {
return "text/xml; charset=utf-8";
}
public String buildString(final ASTNode ast, final URLOutputFilter urlOutputFilter) {
String out;
try {
Document doc = buildDocument(ast, urlOutputFilter);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
out = writer.getBuffer().toString();
}
catch (Exception e) {
out = "error: " + e;
}
return out;
}
public Document buildDocument(final ASTNode ast, final URLOutputFilter urlOutputFilter) {
Document document;
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.setXmlVersion("1.0");
}
catch (ParserConfigurationException e) {
// Not nice, but what can we do?
throw new RuntimeException(e);
}
DocbookVisitor renderer = new DocbookVisitor(document);
renderer.setUrlOutputFilter(urlOutputFilter);
// The renderer builds the root element, in this case.
document.appendChild(renderer.visit(ast).get(0));
return document;
}
private final class DocbookVisitor extends ASTRenderer<List<Node>> {
private final Document _document;
public DocbookVisitor(final Document document) {
super(new ArrayList<Node>());
_document = document;
}
@Override
protected List<Node> combine(final List<Node> x1, final List<Node> x2) {
List<Node> combined = new ArrayList<Node>();
combined.addAll(x1);
combined.addAll(x2);
return combined;
}
@Override
public List<Node> visitPage(final Page node) {
Element article = _document.createElement("article");
article.setAttribute("xmlns", "http://docbook.org/ns/docbook");
article.setAttribute("xmlns:xl", "http:
article.setAttribute("version", "5.0");
article.setAttribute("xml:lang", "en");
// Stack of sections and subsections. Head of stack is what we're
// currently rendering to.
Stack<Element> sections = new Stack<Element>();
// Stack of heading levels. Head of stack is the last heading we saw.
// Seeing a smaller heading results in a new subsection being created,
// seeing a larger heading results in sections being popped and saved to
// the document/parent sections.
// Invariant: sections.size() == levels.size()
// There may be one more section than heading because the document might
// not start off with a heading.
Stack<Integer> levels = new Stack<Integer>();
for (ASTNode child : node.getChildren()) {
// Upon hitting a heading, we need to start a new section.
if (child instanceof Heading) {
// If there are sections around at the moment, we may need to
// rearrange the document: we compare with the current heading:
// popping things off the stack and merging them into their parent
// sections if it's bigger.
Integer hdr = new Integer(((Heading) child).getLevel());
while (!levels.isEmpty() && levels.peek() >= hdr) {
Element sect = sections.pop();
levels.pop();
Element parent = sections.isEmpty() ? article : sections.peek();
parent.appendChild(sect);
}
// Then we finally make a new section.
sections.push(_document.createElement("section"));
levels.push(hdr);
}
// The document might not start off with a heading, in which case we
// pretend there was a level 1 heading.
if (sections.empty()) {
sections.push(_document.createElement("section"));
levels.push(new Integer(1));
}
// Add everything to the current section.
for (Node sibling : visit(child)) {
sections.peek().appendChild(sibling);
}
}
// Save the last subsection stack.
while (!sections.isEmpty()) {
Element sect = sections.pop();
Element parent = sections.isEmpty() ? article : sections.peek();
parent.appendChild(sect);
}
// And we're done.
return singleton(article);
}
/**
* Helper function: build a node from an element type name and an ASTNode
* containing children.
*/
public Element wraps(final String element, final ASTNode node) {
return (Element) build(_document.createElement(element), visitASTNode(node)).get(0);
}
/**
* Helper function: build a node list from an element and some children.
*/
public List<Node> build(final Element container, final List<Node> siblings) {
for (Node sibling : siblings) {
container.appendChild(sibling);
}
return singleton(container);
}
/**
* Helper function: build a singleton list.
*/
public List<Node> singleton(final Node n) {
List<Node> out = new ArrayList<Node>();
out.add(n);
return out;
}
@Override
public List<Node> visitBold(final Bold node) {
Element strong = _document.createElement("emphasis");
strong.setAttribute("role", "bold");
return build(strong, visitASTNode(node));
}
@Override
public List<Node> visitCode(final Code node) {
Element out = _document.createElement("programlisting");
if (node.getLanguage().isPresent()) {
out.setAttribute("language", node.getLanguage().get().toString());
}
out.appendChild(_document.createCDATASection(node.getText()));
return singleton(out);
}
@Override
public List<Node> visitHeading(final Heading node) {
Element out = _document.createElement("info");
Element title = wraps("title", node);
out.appendChild(title);
return singleton(out);
}
@Override
public List<Node> visitHorizontalRule(final HorizontalRule node) {
Element out = _document.createElement("bridgehead");
out.setAttribute("role", "separator");
return singleton(out);
}
@Override
public List<Node> renderImage(final String target, final String title, final Image node) {
Element out = _document.createElement("imageobject");
// Header
Element info = _document.createElement("info");
Element etitle = _document.createElement("title");
etitle.appendChild(_document.createTextNode(title));
info.appendChild(etitle);
// Image data
Element imagedata = _document.createElement("imagedata");
imagedata.setAttribute("fileref", target);
out.appendChild(info);
out.appendChild(imagedata);
return singleton(out);
}
@Override
public List<Node> visitInlineCode(final InlineCode node) {
Element out = _document.createElement("code");
if (node.getLanguage().isPresent()) {
out.setAttribute("language", node.getLanguage().get().toString());
}
out.appendChild(_document.createTextNode(node.getText()));
return singleton(out);
}
@Override
public List<Node> visitItalic(final Italic node) {
return singleton(wraps("emphasis", node));
}
@Override
public List<Node> visitLinebreak(final Linebreak node) {
return singleton(_document.createElement("sbr"));
}
@Override
public List<Node> renderLink(final String target, final String title, final Link node) {
Element out = _document.createElement("link");
out.setAttribute("xl:href", target);
out.appendChild(_document.createTextNode(title));
return singleton(out);
}
@Override
public List<Node> visitListItem(final ListItem node) {
return singleton(wraps("listitem", node));
}
@Override
public List<Node> visitMacroNode(final MacroNode node) {
return singleton(wraps(node.isBlock() ? "pre" : "code", node));
}
@Override
public List<Node> visitOrderedList(final OrderedList node) {
return singleton(wraps("orderedlist", node));
}
@Override
public List<Node> visitParagraph(final Paragraph node) {
return singleton(wraps("para", node));
}
@Override
public List<Node> visitStrikethrough(final Strikethrough node) {
Element strong = _document.createElement("emphasis");
strong.setAttribute("role", "strike");
return build(strong, visitASTNode(node));
}
@Override
public List<Node> visitTable(final Table node) {
return singleton(wraps("table", node));
}
@Override
public List<Node> visitTableCell(final TableCell node) {
Element out = (Element) wraps("td", node);
if (isEnabled(TABLE_ALIGNMENT_DIRECTIVE)) {
try {
out.setAttribute("valign", unsafeGetArgs(TABLE_ALIGNMENT_DIRECTIVE).get(0));
}
catch (Exception e) {
System.err.println("Error when handling directive " + TABLE_ALIGNMENT_DIRECTIVE);
}
}
return singleton(out);
}
@Override
public List<Node> visitTableHeaderCell(final TableHeaderCell node) {
Element out = (Element) wraps("th", node);
if (isEnabled(TABLE_ALIGNMENT_DIRECTIVE)) {
try {
out.setAttribute("valign", unsafeGetArgs(TABLE_ALIGNMENT_DIRECTIVE).get(0));
}
catch (Exception e) {
System.err.println("Error when handling directive " + TABLE_ALIGNMENT_DIRECTIVE);
}
}
return singleton(out);
}
@Override
public List<Node> visitTableRow(final TableRow node) {
return singleton(wraps("tr", node));
}
@Override
public List<Node> visitTextNode(final TextNode node) {
String text = node.getText();
return singleton(node.isEscaped() ? _document.createTextNode(text) : _document.createCDATASection(text));
}
@Override
public List<Node> visitUnorderedList(final UnorderedList node) {
return singleton(wraps("itemizedlist", node));
}
}
}
|
package gui;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* @author linneasahlberg
* @author jasonfortunato
* Started 9/18/16
*/
public class GUI extends JPanel {
static final int TEXT_LEN_LONG = 8;
final static int TEXT_LEN_SHORT = 3;
// we'll dump our input into this guy/object
shared.SessionParameters parms;
// eventually delete this for real time inputs
JButton submit;
GridBagConstraints c = new GridBagConstraints();
JLabel seedLabel; // Seed
JTextField seedField;
JLabel popSizeLabel; // Population size
JTextField popSizeField;
JLabel popConstLabel; // Population constant
ButtonGroup popConstGroup;
JRadioButton popConstTrue;
JRadioButton popConstFalse;
JLabel initPopLabel; // Initial population
JTextField initPop;
JLabel carryCapLabel; // Carrying Capacity
JTextField carryCap;
JLabel numGensLabel; // Number of Gens
JTextField numGens;
JLabel postCrashLabel; // Crash
JTextField postCrash;
JLabel initFreqALabel; // Initial frequencies
JTextField initFreqA;
JLabel calcFreqAA, calcFreqAB,
calcFreqBB;
JLabel selectLabel; // Selection
ButtonGroup selectGroup;
JRadioButton selectRandS,
selectAbs;
JLabel reproRateLabel, // Reproduction Rates (0 to 10, decimal allowed)
reproAALabel, reproABLabel, reproBBLabel;
JTextField reproAA, reproAB, reproBB;
JLabel survRateLabel, // Survival Rates (0 to 1)
survAALabel, survABLabel, survBBLabel;
JTextField survAA, survAB, survBB;
JLabel absFitLabel, // Absolute fitness (any num)
absFitAALabel, absFitABLabel, absFitBBLabel;
JTextField absFitAA, absFitAB, absFitBB;
JLabel relFitLabel, // Relative fitness (0 to 1)
relFitAALabel, relFitABLabel, relFitBBLabel;
JLabel mutLabel, // Mutation (0 to 1)
mutAtoBLabel, mutBtoALabel;
JTextField mutAtoB, mutBtoA;
JLabel migLabel; // Migration
ButtonGroup migGroup;
JRadioButton fixedMig, varMig;
JLabel fixedMigRateLabel;
JTextField fixedMigRate;
JLabel varMigRateLabel;
JLabel varMigRateAALabel, varMigRateABLabel, varMigRateBBLabel;
JTextField varMigRateAA, varMigRateAB, varMigRateBB;
/**
* This is the panel that will be added to the window (the frame)
*/
public GUI() {
// our input will go in this guy/object <-- lowkey offensive
parms = new shared.SessionParameters();
setLayout(new GridBagLayout());
// left align
c.anchor = GridBagConstraints.WEST;
// add spacing
c.insets = new Insets(1, 10, 0, 0);
// Problems were comming from non-uniformed column widths
// This will standardize them
for(int i = 0; i < 6; i++) {
c.gridx = i; c.gridy = 1;
add(new JLabel("_______________________________"), c);
}
// seed stuff
seedLabel = new JLabel("Seed: ");
seedField = new JTextField(TEXT_LEN_LONG);
c.gridx = 999998; c.gridy = 0;
c.anchor = GridBagConstraints.EAST;
add(seedLabel, c);
c.gridx = 999999; c.gridy = 0;
add(seedField, c);
// population size stuff
popSizeLabel = new JLabel("Population Size: ");
popSizeField = new JTextField(TEXT_LEN_LONG);
c.gridx = 0; c.gridy = 10;
c.anchor = GridBagConstraints.WEST;
add(popSizeLabel, c);
c.gridx = 1; c.gridy = 10;
add(popSizeField, c);
// population constant radio button stuff
popConstLabel = new JLabel("Population Size is: ");
popConstGroup = new ButtonGroup();
popConstTrue = new JRadioButton("Constant");
popConstFalse = new JRadioButton("Varying");
popConstGroup.add(popConstTrue);
popConstGroup.add(popConstFalse);
c.gridx = 0; c.gridy = 20;
add(popConstLabel, c);
c.gridx = 1; c.gridy = 20;
add(popConstTrue, c);
c.gridx = 2; c.gridy = 20;
add(popConstFalse, c);
/*// initial population stuff - appears when popSize varying
initPopLabel = new JLabel("Initial Population Size: ");
initPop = new JTextField(TEXT_LEN_LONG);
c.gridx = 1; c.gridy = 30;
c.gridwidth = 2;
add(initPopLabel, c);
c.gridx = 3; c.gridy = 30;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
//c.ipadx = -55;
add(initPop, c);
c.ipadx = 0;*/
// carrying capacity stuff - appears when popSize varying
carryCapLabel = new JLabel("Carrying Capacity: ");
carryCap = new JTextField(TEXT_LEN_LONG);
c.gridx = 1; c.gridy = 40;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(carryCapLabel, c);
c.gridx = 2; c.gridy = 40;
c.gridwidth = 1;
c.anchor = GridBagConstraints.EAST;
//c.ipadx = -55;
add(carryCap, c);
c.ipadx = 0;
// post crash population size stuff - appears when popSize varying
postCrashLabel = new JLabel("Post Crash Population Size: ");
postCrash = new JTextField(TEXT_LEN_LONG);
c.gridx = 1; c.gridy = 50;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(postCrashLabel, c);
c.gridx = 2; c.gridy = 50;
c.gridwidth = 1;
c.anchor = GridBagConstraints.EAST;
//c.ipadx = -55;
add(postCrash, c);
c.ipadx = 0;
// num generations stuff
numGensLabel = new JLabel("Number of Generations: ");
numGens = new JTextField(TEXT_LEN_LONG);
c.gridx = 0; c.gridy = 60;
c.anchor = GridBagConstraints.EAST;
add(numGensLabel, c);
c.gridx = 1; c.gridy = 60;
add(numGens, c);
// initial frequencies stuff
initFreqALabel = new JLabel("Initial Frequency of Allele A: ");
initFreqA = new JTextField(TEXT_LEN_SHORT);
// add spacing
c.insets = new Insets(5, 10, 5, 0);
c.gridx = 0; c.gridy = 70;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(initFreqALabel, c);
c.gridx = 1; c.gridy = 70;
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
add(initFreqA, c);
calcFreqAA = new JLabel("AA: ___");
calcFreqAB = new JLabel("AB: ___");
calcFreqBB = new JLabel("BB: ___");
c.gridwidth = 2;
c.gridx = 1; c.gridy = 80;
c.anchor = GridBagConstraints.WEST;
add(calcFreqAA, c);
c.gridx = 1; c.gridy = 80;
c.anchor = GridBagConstraints.CENTER;
add(calcFreqAB, c);
c.gridx = 1; c.gridy = 80;
c.anchor = GridBagConstraints.EAST;
add(calcFreqBB, c);
JLabel evoForces = new JLabel("Select active evolutionary forces:");
JCheckBox popSizeCheck = new JCheckBox("Population Size", true);
// popSizeCheck.setSelected(true);
popSizeCheck.setEnabled(false);
JCheckBox selectCheck = new JCheckBox("Natural Selection");
JCheckBox mutationCheck = new JCheckBox("Mutation");
JCheckBox migrationCheck = new JCheckBox("Migration");
JCheckBox sexualSelectCheck = new JCheckBox("Non-Random Mating");
c.gridx = 0; c.gridy = 84;
c.gridwidth = 3;
c.anchor = GridBagConstraints.WEST;
add(evoForces, c);
c.gridx = 0; c.gridy = 86;
c.gridwidth = 1;
add(popSizeCheck, c);
c.gridx = 1; c.gridy = 86;
add(selectCheck, c);
c.gridx = 2; c.gridy = 86;
add(mutationCheck, c);
c.gridx = 3; c.gridy = 86;
add(migrationCheck, c);
c.gridx = 4; c.gridy = 86;
add(sexualSelectCheck, c);
// Selection radio buttons
selectLabel = new JLabel("Selection: ");
selectGroup = new ButtonGroup();
selectRandS = new JRadioButton("Reproduction and Survival");
selectAbs = new JRadioButton("Absolute Fitness");
selectGroup.add(selectRandS);
selectGroup.add(selectAbs);
c.gridwidth = 1;
c.gridx = 0; c.gridy = 90;
c.anchor = GridBagConstraints.WEST;
add(selectLabel, c);
c.gridx = 1; c.gridy = 90;
c.gridwidth = 2;
add(selectRandS, c);
c.gridx = 3; c.gridy = 90;
c.gridwidth = 1;
add(selectAbs, c);
// Reproduction Rates (visible if Repro and Surv is selected)
reproRateLabel = new JLabel("Reproduction Rates (0 to 10, decimals allowed): ");
reproAALabel = new JLabel("AA: ");
reproABLabel = new JLabel("AB: ");
reproBBLabel = new JLabel("BB: ");
reproAA = new JTextField(TEXT_LEN_LONG);
reproAB = new JTextField(TEXT_LEN_LONG);
reproBB = new JTextField(TEXT_LEN_LONG);
c.gridx = 1; c.gridy = 100;
c.gridwidth = 3;
add(reproRateLabel, c);
// add label then field x3
c.gridwidth = 1;
c.gridx = 1; c.gridy = 110;
c.anchor = GridBagConstraints.WEST;
add(reproAALabel, c);
c.gridx = 1; //c.gridy = 110;
c.anchor = GridBagConstraints.CENTER;
add(reproAA, c);
c.gridx = 2; c.gridy = 110;
c.anchor = GridBagConstraints.WEST;
add(reproABLabel, c);
c.anchor = GridBagConstraints.CENTER;
c.gridx = 2; c.gridy = 110;
add(reproAB, c);
c.gridx = 3; c.gridy = 110;
c.anchor = GridBagConstraints.WEST;
add(reproBBLabel, c);
c.gridx = 3; c.gridy = 110;
c.anchor = GridBagConstraints.CENTER;
add(reproBB, c);
// Survival Rates (visible if Repro and Surv is selected)
survRateLabel = new JLabel("Survival Rates (0 to 1): ");
survAALabel = new JLabel("AA: ");
survABLabel = new JLabel("AB: ");
survBBLabel = new JLabel("BB: ");
survAA = new JTextField(TEXT_LEN_SHORT);
survAB = new JTextField(TEXT_LEN_SHORT);
survBB = new JTextField(TEXT_LEN_SHORT);
c.gridx = 1; c.gridy = 120;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(survRateLabel, c);
// add label then field x3
c.gridx = 1; c.gridy = 130;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
add(survAALabel, c);
c.gridx = 1; c.gridy = 130;
c.anchor = GridBagConstraints.CENTER;
add(survAA, c);
c.gridx = 2; c.gridy = 130;
c.anchor = GridBagConstraints.WEST;
add(survABLabel, c);
c.gridx = 2; c.gridy = 130;
c.anchor = GridBagConstraints.CENTER;
add(survAB, c);
c.gridx = 3; c.gridy = 130;
c.anchor = GridBagConstraints.WEST;
add(survBBLabel, c);
c.gridx = 3; c.gridy = 130;
c.anchor = GridBagConstraints.CENTER;
add(survBB, c);
// Absolute Fitness Rates (any number)
absFitLabel = new JLabel("Absolute Fitness (any number): ");
absFitAALabel = new JLabel("AA: ");
absFitABLabel = new JLabel("AB: ");
absFitBBLabel = new JLabel("BB: ");
absFitAA = new JTextField(TEXT_LEN_LONG);
absFitAB = new JTextField(TEXT_LEN_LONG);
absFitBB = new JTextField(TEXT_LEN_LONG);
c.gridx = 1; c.gridy = 140;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(absFitLabel, c);
// add label then field x3
c.gridx = 1; c.gridy = 150;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
add(absFitAALabel, c);
c.gridx = 1; c.gridy = 150;
c.anchor = GridBagConstraints.CENTER;
add(absFitAA, c);
c.gridx = 2; c.gridy = 150;
c.anchor = GridBagConstraints.WEST;
add(absFitABLabel, c);
c.gridx = 2; c.gridy = 150;
c.anchor = GridBagConstraints.CENTER;
add(absFitAB, c);
c.gridx = 3; c.gridy = 150;
c.anchor = GridBagConstraints.WEST;
add(absFitBBLabel, c);
c.gridx = 3; c.gridy = 150;
c.anchor = GridBagConstraints.CENTER;
add(absFitBB, c);
// Relative Fitness Rates (display only, 0 to 1)
relFitLabel = new JLabel("Relative Fitness: ");
relFitAALabel = new JLabel("AA: ___");
relFitABLabel = new JLabel("AB: ___");
relFitBBLabel = new JLabel("BB: ___");
c.gridx = 1; c.gridy = 160;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(relFitLabel, c);
// add label then field x3
c.gridx = 1; c.gridy = 170;
c.gridwidth = 2;
c.anchor = GridBagConstraints.WEST;
add(relFitAALabel, c);
// c.gridx = 2; c.gridy = 170;
c.anchor = GridBagConstraints.CENTER;
add(relFitABLabel, c);
// c.gridx = 3; c.gridy = 170;
c.anchor = GridBagConstraints.EAST;
add(relFitBBLabel, c);
// Mutation (0 to 1)
mutLabel = new JLabel("Mutation (0 to 1): ");
mutAtoBLabel = new JLabel("A to B: ");
mutBtoALabel = new JLabel("B to A: ");
mutAtoB = new JTextField(TEXT_LEN_SHORT);
mutBtoA = new JTextField(TEXT_LEN_SHORT);
c.gridx = 0; c.gridy = 180;
c.anchor = GridBagConstraints.WEST;
add(mutLabel, c);
// add label then field x3
c.gridx = 0; c.gridy = 190;
c.gridwidth = 1;
c.anchor = GridBagConstraints.EAST;
add(mutAtoBLabel, c);
c.gridx = 1; c.gridy = 190;
c.anchor = GridBagConstraints.WEST;
add(mutAtoB, c);
c.gridx = 2; c.gridy = 190;
//c.anchor = GridBagConstraints.EAST;
add(mutBtoALabel, c);
c.gridx = 2; c.gridy = 190;
c.anchor = GridBagConstraints.EAST;
add(mutBtoA, c);
// Migration radio buttons
migLabel = new JLabel("Migration: ");
migGroup = new ButtonGroup();
fixedMig = new JRadioButton("Fixed");
varMig = new JRadioButton("Varies by Genotype");
migGroup.add(fixedMig);
migGroup.add(varMig);
c.gridx = 0; c.gridy = 200;
c.anchor = GridBagConstraints.WEST;
add(migLabel, c);
c.gridx = 0; c.gridy = 200;
c.anchor = GridBagConstraints.EAST;
add(fixedMig, c);
c.gridx = 1; c.gridy = 200;
c.anchor = GridBagConstraints.WEST;
add(varMig, c);
// Migration rate - if fixed
fixedMigRateLabel = new JLabel("Migration Rate: ");
fixedMigRate = new JTextField(TEXT_LEN_SHORT);
c.gridx = 1; c.gridy = 210;
c.anchor = GridBagConstraints.WEST;
add(fixedMigRateLabel, c);
c.gridx = 1; c.gridy = 210;
c.anchor = GridBagConstraints.EAST;
add(fixedMigRate, c);
// Migration Rates by genotype - if varies
varMigRateLabel = new JLabel("Migration Rate (by genotype): ");
varMigRateAALabel = new JLabel("AA: ");
varMigRateABLabel = new JLabel("AB: ");
varMigRateBBLabel = new JLabel("BB: ");
varMigRateAA = new JTextField(TEXT_LEN_SHORT);
varMigRateAB = new JTextField(TEXT_LEN_SHORT);
varMigRateBB = new JTextField(TEXT_LEN_SHORT);
c.gridwidth = 3;
c.gridx = 1; c.gridy = 220;
c.anchor = GridBagConstraints.WEST;
add(varMigRateLabel, c);
// add label then field x3
c.gridx = 1; c.gridy = 230;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
add(varMigRateAALabel, c);
c.gridx = 1; c.gridy = 230;
c.anchor = GridBagConstraints.CENTER;
add(varMigRateAA, c);
c.gridx = 2; c.gridy = 230;
c.anchor = GridBagConstraints.WEST;
add(varMigRateABLabel, c);
c.gridx = 2; c.gridy = 230;
c.anchor = GridBagConstraints.CENTER;
add(varMigRateAB, c);
c.gridx = 3; c.gridy = 230;
c.anchor = GridBagConstraints.WEST;
add(varMigRateBBLabel, c);
c.gridx = 3; c.gridy = 230;
c.anchor = GridBagConstraints.CENTER;
add(varMigRateBB, c);
submit = new JButton(">> Submit <<");
c.gridx = 999999; c.gridy = 999999;
add(submit, c);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
parms.setSeed(Integer.parseInt(seedField.getText()));
parms.setPopSize(Integer.parseInt(popSizeField.getText()));
System.out.println(parms.getSeed());
System.out.println(parms.getPopSize());
System.out.println(selectCheck.isSelected());
System.out.println(popSizeCheck.isSelected());
}
});
}
public static void createAndShowGUI() {
//make the panel
GUI g = new GUI();
//g.setLayout(new GridBagLayout());
//make the window
JFrame frame = new JFrame();
frame.setTitle("EVOLVE - v0.0");
//frame.setSize(800, 640);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the panel to the window
frame.add(g);
frame.pack();
frame.setVisible(true);
//System.out.println("done");
}
public static void main(String[] args) {
createAndShowGUI();
}
}
|
package com.facebook.litho;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.Rect;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import com.facebook.R;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.reference.ColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.litho.reference.ResourceDrawableReference;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaBaselineFunction;
import com.facebook.yoga.YogaFlexDirection;
import com.facebook.yoga.YogaJustify;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaNodeAPI;
import com.facebook.yoga.YogaOverflow;
import com.facebook.yoga.Spacing;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.support.annotation.Dimension.DP;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.yoga.YogaEdge.ALL;
import static com.facebook.yoga.YogaEdge.BOTTOM;
import static com.facebook.yoga.YogaEdge.END;
import static com.facebook.yoga.YogaEdge.HORIZONTAL;
import static com.facebook.yoga.YogaEdge.LEFT;
import static com.facebook.yoga.YogaEdge.RIGHT;
import static com.facebook.yoga.YogaEdge.START;
import static com.facebook.yoga.YogaEdge.TOP;
import static com.facebook.yoga.YogaEdge.VERTICAL;
/**
* Internal class representing both a {@link ComponentLayout} and a
* {@link com.facebook.litho.ComponentLayout.ContainerBuilder}.
*/
@ThreadConfined(ThreadConfined.ANY)
class InternalNode implements ComponentLayout, ComponentLayout.ContainerBuilder {
// Used to check whether or not the framework can use style IDs for
// paddingStart/paddingEnd due to a bug in some Android devices.
private static final boolean SUPPORTS_RTL = (SDK_INT >= JELLY_BEAN_MR1);
// When this flag is set, layoutDirection style was explicitly set on this node.
private static final long PFLAG_LAYOUT_DIRECTION_IS_SET = 1L << 0;
// When this flag is set, alignSelf was explicitly set on this node.
private static final long PFLAG_ALIGN_SELF_IS_SET = 1L << 1;
// When this flag is set, position type was explicitly set on this node.
private static final long PFLAG_POSITION_TYPE_IS_SET = 1L << 2;
// When this flag is set, flex was explicitly set on this node.
private static final long PFLAG_FLEX_IS_SET = 1L << 3;
// When this flag is set, flex grow was explicitly set on this node.
private static final long PFLAG_FLEX_GROW_IS_SET = 1L << 4;
// When this flag is set, flex shrink was explicitly set on this node.
private static final long PFLAG_FLEX_SHRINK_IS_SET = 1L << 5;
// When this flag is set, flex basis was explicitly set on this node.
private static final long PFLAG_FLEX_BASIS_IS_SET = 1L << 6;
// When this flag is set, importantForAccessibility was explicitly set on this node.
private static final long PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET = 1L << 7;
// When this flag is set, duplicateParentState was explicitly set on this node.
private static final long PFLAG_DUPLICATE_PARENT_STATE_IS_SET = 1L << 8;
// When this flag is set, margin was explicitly set on this node.
private static final long PFLAG_MARGIN_IS_SET = 1L << 9;
// When this flag is set, padding was explicitly set on this node.
private static final long PFLAG_PADDING_IS_SET = 1L << 10;
// When this flag is set, position was explicitly set on this node.
private static final long PFLAG_POSITION_IS_SET = 1L << 11;
// When this flag is set, width was explicitly set on this node.
private static final long PFLAG_WIDTH_IS_SET = 1L << 12;
// When this flag is set, minWidth was explicitly set on this node.
private static final long PFLAG_MIN_WIDTH_IS_SET = 1L << 13;
// When this flag is set, maxWidth was explicitly set on this node.
private static final long PFLAG_MAX_WIDTH_IS_SET = 1L << 14;
// When this flag is set, height was explicitly set on this node.
private static final long PFLAG_HEIGHT_IS_SET = 1L << 15;
// When this flag is set, minHeight was explicitly set on this node.
private static final long PFLAG_MIN_HEIGHT_IS_SET = 1L << 16;
// When this flag is set, maxHeight was explicitly set on this node.
private static final long PFLAG_MAX_HEIGHT_IS_SET = 1L << 17;
// When this flag is set, background was explicitly set on this node.
private static final long PFLAG_BACKGROUND_IS_SET = 1L << 18;
// When this flag is set, foreground was explicitly set on this node.
private static final long PFLAG_FOREGROUND_IS_SET = 1L << 19;
// When this flag is set, visibleHandler was explicitly set on this node.
private static final long PFLAG_VISIBLE_HANDLER_IS_SET = 1L << 20;
// When this flag is set, focusedHandler was explicitly set on this node.
private static final long PFLAG_FOCUSED_HANDLER_IS_SET = 1L << 21;
// When this flag is set, fullImpressionHandler was explicitly set on this node.
private static final long PFLAG_FULL_IMPRESSION_HANDLER_IS_SET = 1L << 22;
// When this flag is set, invisibleHandler was explicitly set on this node.
private static final long PFLAG_INVISIBLE_HANDLER_IS_SET = 1L << 23;
// When this flag is set, touch expansion was explicitly set on this node.
private static final long PFLAG_TOUCH_EXPANSION_IS_SET = 1L << 24;
// When this flag is set, border width was explicitly set on this node.
private static final long PFLAG_BORDER_WIDTH_IS_SET = 1L << 25;
// When this flag is set, aspectRatio was explicitly set on this node.
private static final long PFLAG_ASPECT_RATIO_IS_SET = 1L << 26;
// When this flag is set, transitionKey was explicitly set on this node.
private static final long PFLAG_TRANSITION_KEY_IS_SET = 1L << 27;
// When this flag is set, border color was explicitly set on this node.
private static final long PFLAG_BORDER_COLOR_IS_SET = 1L << 28;
private final ResourceResolver mResourceResolver = new ResourceResolver();
YogaNodeAPI mYogaNode;
private ComponentContext mComponentContext;
private Resources mResources;
private Component mComponent;
private int mImportantForAccessibility = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
private boolean mDuplicateParentState;
private boolean mIsNestedTreeHolder;
private InternalNode mNestedTree;
private InternalNode mNestedTreeHolder;
private long mPrivateFlags;
private Reference<? extends Drawable> mBackground;
private Reference<? extends Drawable> mForeground;
private int mBorderColor = Color.TRANSPARENT;
private NodeInfo mNodeInfo;
private boolean mForceViewWrapping;
private String mTransitionKey;
private EventHandler mVisibleHandler;
private EventHandler mFocusedHandler;
private EventHandler mFullImpressionHandler;
private EventHandler mInvisibleHandler;
private String mTestKey;
private Spacing mTouchExpansion;
private Spacing mNestedTreePadding;
private Spacing mNestedTreeBorderWidth;
private boolean[] mIsPaddingPercent;
private float mResolvedTouchExpansionLeft = YogaConstants.UNDEFINED;
private float mResolvedTouchExpansionRight = YogaConstants.UNDEFINED;
private float mResolvedX = YogaConstants.UNDEFINED;
private float mResolvedY = YogaConstants.UNDEFINED;
private float mResolvedWidth = YogaConstants.UNDEFINED;
private float mResolvedHeight = YogaConstants.UNDEFINED;
private int mLastWidthSpec = DiffNode.UNSPECIFIED;
private int mLastHeightSpec = DiffNode.UNSPECIFIED;
private float mLastMeasuredWidth = DiffNode.UNSPECIFIED;
private float mLastMeasuredHeight = DiffNode.UNSPECIFIED;
private DiffNode mDiffNode;
private boolean mCachedMeasuresValid;
private TreeProps mPendingTreeProps;
void init(YogaNodeAPI yogaNode, ComponentContext componentContext, Resources resources) {
yogaNode.setData(this);
yogaNode.setOverflow(YogaOverflow.HIDDEN);
yogaNode.setMeasureFunction(null);
// YogaNode is the only version of YogaNodeAPI with this support;
if (yogaNode instanceof YogaNode) {
yogaNode.setBaselineFunction(null);
}
mYogaNode = yogaNode;
mComponentContext = componentContext;
mResources = resources;
mResourceResolver.init(
mComponentContext,
componentContext.getResourceCache());
}
@Px
@Override
public int getX() {
if (YogaConstants.isUndefined(mResolvedX)) {
mResolvedX = mYogaNode.getLayoutX();
}
return (int) mResolvedX;
}
@Px
@Override
public int getY() {
if (YogaConstants.isUndefined(mResolvedY)) {
mResolvedY = mYogaNode.getLayoutY();
}
return (int) mResolvedY;
}
@Px
@Override
public int getWidth() {
if (YogaConstants.isUndefined(mResolvedWidth)) {
mResolvedWidth = mYogaNode.getLayoutWidth();
}
return (int) mResolvedWidth;
}
@Px
@Override
public int getHeight() {
if (YogaConstants.isUndefined(mResolvedHeight)) {
mResolvedHeight = mYogaNode.getLayoutHeight();
}
return (int) mResolvedHeight;
}
@Px
@Override
public int getPaddingLeft() {
return FastMath.round(mYogaNode.getLayoutPadding(LEFT));
}
@Px
@Override
public int getPaddingTop() {
return FastMath.round(mYogaNode.getLayoutPadding(TOP));
}
@Px
@Override
public int getPaddingRight() {
return FastMath.round(mYogaNode.getLayoutPadding(RIGHT));
}
@Px
@Override
public int getPaddingBottom() {
return FastMath.round(mYogaNode.getLayoutPadding(BOTTOM));
}
public Reference<? extends Drawable> getBackground() {
return mBackground;
}
public Reference<? extends Drawable> getForeground() {
return mForeground;
}
public void setCachedMeasuresValid(boolean valid) {
mCachedMeasuresValid = valid;
}
public int getLastWidthSpec() {
return mLastWidthSpec;
}
public void setLastWidthSpec(int widthSpec) {
mLastWidthSpec = widthSpec;
}
public int getLastHeightSpec() {
return mLastHeightSpec;
}
public void setLastHeightSpec(int heightSpec) {
mLastHeightSpec = heightSpec;
}
public boolean hasVisibilityHandlers() {
return mVisibleHandler != null
|| mFocusedHandler != null
|| mFullImpressionHandler != null
|| mInvisibleHandler != null;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the width. This is used together with {@link InternalNode#getLastWidthSpec()}
* to implement measure caching.
*/
float getLastMeasuredWidth() {
return mLastMeasuredWidth;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the width.
*/
void setLastMeasuredWidth(float lastMeasuredWidth) {
mLastMeasuredWidth = lastMeasuredWidth;
}
/**
* The last value the measure funcion associated with this node {@link Component} returned
* for the height. This is used together with {@link InternalNode#getLastHeightSpec()}
* to implement measure caching.
*/
float getLastMeasuredHeight() {
return mLastMeasuredHeight;
}
/**
* Sets the last value the measure funcion associated with this node {@link Component} returned
* for the height.
*/
void setLastMeasuredHeight(float lastMeasuredHeight) {
mLastMeasuredHeight = lastMeasuredHeight;
}
DiffNode getDiffNode() {
return mDiffNode;
}
boolean areCachedMeasuresValid() {
return mCachedMeasuresValid;
}
void setDiffNode(DiffNode diffNode) {
mDiffNode = diffNode;
}
/**
* Mark this node as a nested tree root holder.
*/
void markIsNestedTreeHolder(TreeProps currentTreeProps) {
mIsNestedTreeHolder = true;
mPendingTreeProps = TreeProps.copy(currentTreeProps);
}
/**
* @return Whether this node is holding a nested tree or not. The decision was made during
* tree creation {@link ComponentLifecycle#createLayout(ComponentContext, Component, boolean)}.
*/
boolean isNestedTreeHolder() {
return mIsNestedTreeHolder;
}
@Override
public YogaDirection getResolvedLayoutDirection() {
return mYogaNode.getLayoutDirection();
}
@Override
public InternalNode layoutDirection(YogaDirection direction) {
mPrivateFlags |= PFLAG_LAYOUT_DIRECTION_IS_SET;
mYogaNode.setDirection(direction);
return this;
}
@Override
public InternalNode flexDirection(YogaFlexDirection direction) {
mYogaNode.setFlexDirection(direction);
return this;
}
@Override
public InternalNode wrap(YogaWrap wrap) {
mYogaNode.setWrap(wrap);
return this;
}
@Override
public InternalNode justifyContent(YogaJustify justifyContent) {
mYogaNode.setJustifyContent(justifyContent);
return this;
}
@Override
public InternalNode alignItems(YogaAlign alignItems) {
mYogaNode.setAlignItems(alignItems);
return this;
}
@Override
public InternalNode alignContent(YogaAlign alignContent) {
mYogaNode.setAlignContent(alignContent);
return this;
}
@Override
public InternalNode alignSelf(YogaAlign alignSelf) {
mPrivateFlags |= PFLAG_ALIGN_SELF_IS_SET;
mYogaNode.setAlignSelf(alignSelf);
return this;
}
@Override
public InternalNode positionType(YogaPositionType positionType) {
mPrivateFlags |= PFLAG_POSITION_TYPE_IS_SET;
mYogaNode.setPositionType(positionType);
return this;
}
@Override
public InternalNode flex(float flex) {
mPrivateFlags |= PFLAG_FLEX_IS_SET;
mYogaNode.setFlex(flex);
return this;
}
@Override
public InternalNode flexGrow(float flexGrow) {
mPrivateFlags |= PFLAG_FLEX_GROW_IS_SET;
mYogaNode.setFlexGrow(flexGrow);
return this;
}
@Override
public InternalNode flexShrink(float flexShrink) {
mPrivateFlags |= PFLAG_FLEX_SHRINK_IS_SET;
mYogaNode.setFlexShrink(flexShrink);
return this;
}
@Override
public InternalNode flexBasisPx(@Px int flexBasis) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasis(flexBasis);
return this;
}
@Override
public InternalNode flexBasisPercent(float percent) {
mPrivateFlags |= PFLAG_FLEX_BASIS_IS_SET;
mYogaNode.setFlexBasisPercent(percent);
return this;
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode flexBasisAttr(@AttrRes int resId) {
return flexBasisAttr(resId, 0);
}
@Override
public InternalNode flexBasisRes(@DimenRes int resId) {
return flexBasisPx(mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode flexBasisDip(@Dimension(unit = DP) int flexBasis) {
return flexBasisPx(mResourceResolver.dipsToPixels(flexBasis));
}
@Override
public InternalNode importantForAccessibility(int importantForAccessibility) {
mPrivateFlags |= PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET;
mImportantForAccessibility = importantForAccessibility;
return this;
}
@Override
public InternalNode duplicateParentState(boolean duplicateParentState) {
mPrivateFlags |= PFLAG_DUPLICATE_PARENT_STATE_IS_SET;
mDuplicateParentState = duplicateParentState;
return this;
}
@Override
public InternalNode marginPx(YogaEdge edge, @Px int margin) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMargin(edge, margin);
return this;
}
@Override
public InternalNode marginPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginPercent(edge, percent);
return this;
}
@Override
public InternalNode marginAuto(YogaEdge edge) {
mPrivateFlags |= PFLAG_MARGIN_IS_SET;
mYogaNode.setMarginAuto(edge);
return this;
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode marginAttr(
YogaEdge edge,
@AttrRes int resId) {
return marginAttr(edge, resId, 0);
}
@Override
public InternalNode marginRes(YogaEdge edge, @DimenRes int resId) {
return marginPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode marginDip(YogaEdge edge, @Dimension(unit = DP) int margin) {
return marginPx(edge, mResourceResolver.dipsToPixels(margin));
}
@Override
public InternalNode paddingPx(YogaEdge edge, @Px int padding) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), padding);
setIsPaddingPercent(edge, false);
} else {
mYogaNode.setPadding(edge, padding);
}
return this;
}
@Override
public InternalNode paddingPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreePadding == null) {
mNestedTreePadding = ComponentsPools.acquireSpacing();
}
mNestedTreePadding.set(edge.intValue(), percent);
setIsPaddingPercent(edge, true);
} else {
mYogaNode.setPaddingPercent(edge, percent);
}
return this;
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode paddingAttr(
YogaEdge edge,
@AttrRes int resId) {
return paddingAttr(edge, resId, 0);
}
@Override
public InternalNode paddingRes(YogaEdge edge, @DimenRes int resId) {
return paddingPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode paddingDip(YogaEdge edge, @Dimension(unit = DP) int padding) {
return paddingPx(edge, mResourceResolver.dipsToPixels(padding));
}
@Override
public InternalNode borderWidthPx(YogaEdge edge, @Px int borderWidth) {
mPrivateFlags |= PFLAG_BORDER_WIDTH_IS_SET;
if (mIsNestedTreeHolder) {
if (mNestedTreeBorderWidth == null) {
mNestedTreeBorderWidth = ComponentsPools.acquireSpacing();
}
mNestedTreeBorderWidth.set(edge.intValue(), borderWidth);
} else {
mYogaNode.setBorder(edge, borderWidth);
}
return this;
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode borderWidthAttr(
YogaEdge edge,
@AttrRes int resId) {
return borderWidthAttr(edge, resId, 0);
}
@Override
public InternalNode borderWidthRes(YogaEdge edge, @DimenRes int resId) {
return borderWidthPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode borderWidthDip(
YogaEdge edge,
@Dimension(unit = DP) int borderWidth) {
return borderWidthPx(edge, mResourceResolver.dipsToPixels(borderWidth));
}
@Override
public Builder borderColor(@ColorInt int borderColor) {
mPrivateFlags |= PFLAG_BORDER_COLOR_IS_SET;
mBorderColor = borderColor;
return this;
}
@Override
public InternalNode positionPx(YogaEdge edge, @Px int position) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPosition(edge, position);
return this;
}
@Override
public InternalNode positionPercent(YogaEdge edge, float percent) {
mPrivateFlags |= PFLAG_POSITION_IS_SET;
mYogaNode.setPositionPercent(edge, percent);
return this;
}
@Override
public InternalNode positionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode positionAttr(YogaEdge edge, @AttrRes int resId) {
return positionAttr(edge, resId, 0);
}
@Override
public InternalNode positionRes(YogaEdge edge, @DimenRes int resId) {
return positionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode positionDip(
YogaEdge edge,
@Dimension(unit = DP) int position) {
return positionPx(edge, mResourceResolver.dipsToPixels(position));
}
@Override
public InternalNode widthPx(@Px int width) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidth(width);
return this;
}
@Override
public InternalNode widthPercent(float percent) {
mPrivateFlags |= PFLAG_WIDTH_IS_SET;
mYogaNode.setWidthPercent(percent);
return this;
}
@Override
public InternalNode widthRes(@DimenRes int resId) {
return widthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return widthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode widthAttr(@AttrRes int resId) {
return widthAttr(resId, 0);
}
@Override
public InternalNode widthDip(@Dimension(unit = DP) int width) {
return widthPx(mResourceResolver.dipsToPixels(width));
}
@Override
public InternalNode minWidthPx(@Px int minWidth) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidth(minWidth);
return this;
}
@Override
public InternalNode minWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_WIDTH_IS_SET;
mYogaNode.setMinWidthPercent(percent);
return this;
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minWidthAttr(@AttrRes int resId) {
return minWidthAttr(resId, 0);
}
@Override
public InternalNode minWidthRes(@DimenRes int resId) {
return minWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minWidthDip(@Dimension(unit = DP) int minWidth) {
return minWidthPx(mResourceResolver.dipsToPixels(minWidth));
}
@Override
public InternalNode maxWidthPx(@Px int maxWidth) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidth(maxWidth);
return this;
}
@Override
public InternalNode maxWidthPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_WIDTH_IS_SET;
mYogaNode.setMaxWidthPercent(percent);
return this;
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxWidthAttr(@AttrRes int resId) {
return maxWidthAttr(resId, 0);
}
@Override
public InternalNode maxWidthRes(@DimenRes int resId) {
return maxWidthPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxWidthDip(@Dimension(unit = DP) int maxWidth) {
return maxWidthPx(mResourceResolver.dipsToPixels(maxWidth));
}
@Override
public InternalNode heightPx(@Px int height) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeight(height);
return this;
}
@Override
public InternalNode heightPercent(float percent) {
mPrivateFlags |= PFLAG_HEIGHT_IS_SET;
mYogaNode.setHeightPercent(percent);
return this;
}
@Override
public InternalNode heightRes(@DimenRes int resId) {
return heightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return heightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode heightAttr(@AttrRes int resId) {
return heightAttr(resId, 0);
}
@Override
public InternalNode heightDip(@Dimension(unit = DP) int height) {
return heightPx(mResourceResolver.dipsToPixels(height));
}
@Override
public InternalNode minHeightPx(@Px int minHeight) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeight(minHeight);
return this;
}
@Override
public InternalNode minHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MIN_HEIGHT_IS_SET;
mYogaNode.setMinHeightPercent(percent);
return this;
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode minHeightAttr(@AttrRes int resId) {
return minHeightAttr(resId, 0);
}
@Override
public InternalNode minHeightRes(@DimenRes int resId) {
return minHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode minHeightDip(@Dimension(unit = DP) int minHeight) {
return minHeightPx(mResourceResolver.dipsToPixels(minHeight));
}
@Override
public InternalNode maxHeightPx(@Px int maxHeight) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeight(maxHeight);
return this;
}
@Override
public InternalNode maxHeightPercent(float percent) {
mPrivateFlags |= PFLAG_MAX_HEIGHT_IS_SET;
mYogaNode.setMaxHeightPercent(percent);
return this;
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeAttr(resId, defaultResId));
}
@Override
public InternalNode maxHeightAttr(@AttrRes int resId) {
return maxHeightAttr(resId, 0);
}
@Override
public InternalNode maxHeightRes(@DimenRes int resId) {
return maxHeightPx(mResourceResolver.resolveDimenSizeRes(resId));
}
@Override
public InternalNode maxHeightDip(@Dimension(unit = DP) int maxHeight) {
return maxHeightPx(mResourceResolver.dipsToPixels(maxHeight));
}
@Override
public InternalNode aspectRatio(float aspectRatio) {
mPrivateFlags |= PFLAG_ASPECT_RATIO_IS_SET;
if (mYogaNode instanceof YogaNode) {
((YogaNode) mYogaNode).setAspectRatio(aspectRatio);
return this;
} else {
throw new IllegalStateException("Aspect ration requires using YogaNode not YogaNodeDEPRECATED");
}
}
private boolean shouldApplyTouchExpansion() {
return mTouchExpansion != null && mNodeInfo != null && mNodeInfo.hasTouchEventHandlers();
}
boolean hasTouchExpansion() {
return ((mPrivateFlags & PFLAG_TOUCH_EXPANSION_IS_SET) != 0L);
}
Spacing getTouchExpansion() {
return mTouchExpansion;
}
int getTouchExpansionLeft() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionLeft)) {
mResolvedTouchExpansionLeft = resolveHorizontalSpacing(mTouchExpansion, Spacing.LEFT);
}
return FastMath.round(mResolvedTouchExpansionLeft);
}
int getTouchExpansionTop() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.TOP));
}
int getTouchExpansionRight() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
if (YogaConstants.isUndefined(mResolvedTouchExpansionRight)) {
mResolvedTouchExpansionRight = resolveHorizontalSpacing(mTouchExpansion, Spacing.RIGHT);
}
return FastMath.round(mResolvedTouchExpansionRight);
}
int getTouchExpansionBottom() {
if (!shouldApplyTouchExpansion()) {
return 0;
}
return FastMath.round(mTouchExpansion.get(Spacing.BOTTOM));
}
@Override
public InternalNode touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
if (mTouchExpansion == null) {
mTouchExpansion = ComponentsPools.acquireSpacing();
}
mPrivateFlags |= PFLAG_TOUCH_EXPANSION_IS_SET;
mTouchExpansion.set(edge.intValue(), touchExpansion);
return this;
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId,
@DimenRes int defaultResId) {
return touchExpansionPx(
edge,
mResourceResolver.resolveDimenOffsetAttr(resId, defaultResId));
}
@Override
public InternalNode touchExpansionAttr(
YogaEdge edge,
@AttrRes int resId) {
return touchExpansionAttr(edge, resId, 0);
}
@Override
public InternalNode touchExpansionRes(YogaEdge edge, @DimenRes int resId) {
return touchExpansionPx(edge, mResourceResolver.resolveDimenOffsetRes(resId));
}
@Override
public InternalNode touchExpansionDip(
YogaEdge edge,
@Dimension(unit = DP) int touchExpansion) {
return touchExpansionPx(edge, mResourceResolver.dipsToPixels(touchExpansion));
}
@Override
public InternalNode child(ComponentLayout child) {
if (child != null && child != NULL_LAYOUT) {
addChildAt((InternalNode) child, mYogaNode.getChildCount());
}
return this;
}
@Override
public InternalNode child(ComponentLayout.Builder child) {
if (child != null && child != NULL_LAYOUT) {
child(child.build());
}
return this;
}
@Override
public InternalNode child(Component<?> child) {
if (child != null) {
child(Layout.create(mComponentContext, child).flexShrink(0).flexShrink(0).flexShrink(0));
}
return this;
}
@Override
public InternalNode child(Component.Builder<?> child) {
if (child != null) {
child(child.build());
}
return this;
}
@Override
public InternalNode background(Reference<? extends Drawable> background) {
mPrivateFlags |= PFLAG_BACKGROUND_IS_SET;
mBackground = background;
setPaddingFromDrawableReference(background);
return this;
}
@Override
public InternalNode background(Reference.Builder<? extends Drawable> builder) {
return background(builder.build());
}
@Override
public InternalNode backgroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return backgroundRes(mResourceResolver.resolveResIdAttr(resId, defaultResId));
}
@Override
public InternalNode backgroundAttr(@AttrRes int resId) {
return backgroundAttr(resId, 0);
}
@Override
public InternalNode backgroundRes(@DrawableRes int resId) {
if (resId == 0) {
return background((Reference<Drawable>) null);
}
return background(
ResourceDrawableReference.create(mComponentContext)
.resId(resId)
.build());
}
@Override
public InternalNode backgroundColor(@ColorInt int backgroundColor) {
return background(
ColorDrawableReference.create(mComponentContext)
.color(backgroundColor)
.build());
}
@Override
public InternalNode foreground(Reference<? extends Drawable> foreground) {
mPrivateFlags |= PFLAG_FOREGROUND_IS_SET;
mForeground = foreground;
return this;
}
@Override
public InternalNode foreground(Reference.Builder<? extends Drawable> builder) {
return foreground(builder.build());
}
@Override
public InternalNode foregroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return foregroundRes(mResourceResolver.resolveResIdAttr(resId, defaultResId));
}
@Override
public InternalNode foregroundAttr(@AttrRes int resId) {
return foregroundAttr(resId, 0);
}
@Override
public InternalNode foregroundRes(@DrawableRes int resId) {
if (resId == 0) {
return foreground((Reference<Drawable>) null);
}
return foreground(
ResourceDrawableReference.create(mComponentContext)
.resId(resId)
.build());
}
@Override
public InternalNode foregroundColor(@ColorInt int foregroundColor) {
return foreground(
ColorDrawableReference.create(mComponentContext)
.color(foregroundColor)
.build());
}
@Override
public InternalNode wrapInView() {
mForceViewWrapping = true;
return this;
}
boolean isForceViewWrapping() {
return mForceViewWrapping;
}
@Override
public InternalNode clickHandler(EventHandler clickHandler) {
getOrCreateNodeInfo().setClickHandler(clickHandler);
return this;
}
@Override
public InternalNode longClickHandler(EventHandler longClickHandler) {
getOrCreateNodeInfo().setLongClickHandler(longClickHandler);
return this;
}
@Override
public InternalNode touchHandler(EventHandler touchHandler) {
getOrCreateNodeInfo().setTouchHandler(touchHandler);
return this;
}
@Override
public ContainerBuilder focusable(boolean isFocusable) {
getOrCreateNodeInfo().setFocusable(isFocusable);
return this;
}
@Override
public InternalNode visibleHandler(EventHandler visibleHandler) {
mPrivateFlags |= PFLAG_VISIBLE_HANDLER_IS_SET;
mVisibleHandler = visibleHandler;
return this;
}
EventHandler getVisibleHandler() {
return mVisibleHandler;
}
@Override
public InternalNode focusedHandler(EventHandler focusedHandler) {
mPrivateFlags |= PFLAG_FOCUSED_HANDLER_IS_SET;
mFocusedHandler = focusedHandler;
return this;
}
EventHandler getFocusedHandler() {
return mFocusedHandler;
}
@Override
public InternalNode fullImpressionHandler(EventHandler fullImpressionHandler) {
mPrivateFlags |= PFLAG_FULL_IMPRESSION_HANDLER_IS_SET;
mFullImpressionHandler = fullImpressionHandler;
return this;
}
EventHandler getFullImpressionHandler() {
return mFullImpressionHandler;
}
@Override
public InternalNode invisibleHandler(EventHandler invisibleHandler) {
mPrivateFlags |= PFLAG_INVISIBLE_HANDLER_IS_SET;
mInvisibleHandler = invisibleHandler;
return this;
}
EventHandler getInvisibleHandler() {
return mInvisibleHandler;
}
@Override
public InternalNode contentDescription(CharSequence contentDescription) {
getOrCreateNodeInfo().setContentDescription(contentDescription);
return this;
}
@Override
public InternalNode contentDescription(@StringRes int stringId) {
return contentDescription(mResources.getString(stringId));
}
@Override
public InternalNode contentDescription(@StringRes int stringId, Object... formatArgs) {
return contentDescription(mResources.getString(stringId, formatArgs));
}
@Override
public InternalNode viewTag(Object viewTag) {
getOrCreateNodeInfo().setViewTag(viewTag);
return this;
}
@Override
public InternalNode viewTags(SparseArray<Object> viewTags) {
getOrCreateNodeInfo().setViewTags(viewTags);
return this;
}
@Override
public InternalNode testKey(String testKey) {
mTestKey = testKey;
return this;
}
@Override
public InternalNode dispatchPopulateAccessibilityEventHandler(
EventHandler<DispatchPopulateAccessibilityEventEvent>
dispatchPopulateAccessibilityEventHandler) {
getOrCreateNodeInfo().setDispatchPopulateAccessibilityEventHandler(
dispatchPopulateAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onInitializeAccessibilityEventHandler(
EventHandler<OnInitializeAccessibilityEventEvent> onInitializeAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnInitializeAccessibilityEventHandler(
onInitializeAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onInitializeAccessibilityNodeInfoHandler(
EventHandler<OnInitializeAccessibilityNodeInfoEvent>
onInitializeAccessibilityNodeInfoHandler) {
getOrCreateNodeInfo().setOnInitializeAccessibilityNodeInfoHandler(
onInitializeAccessibilityNodeInfoHandler);
return this;
}
@Override
public InternalNode onPopulateAccessibilityEventHandler(
EventHandler<OnPopulateAccessibilityEventEvent> onPopulateAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnPopulateAccessibilityEventHandler(
onPopulateAccessibilityEventHandler);
return this;
}
@Override
public InternalNode onRequestSendAccessibilityEventHandler(
EventHandler<OnRequestSendAccessibilityEventEvent> onRequestSendAccessibilityEventHandler) {
getOrCreateNodeInfo().setOnRequestSendAccessibilityEventHandler(
onRequestSendAccessibilityEventHandler);
return this;
}
@Override
public InternalNode performAccessibilityActionHandler(
EventHandler<PerformAccessibilityActionEvent> performAccessibilityActionHandler) {
getOrCreateNodeInfo().setPerformAccessibilityActionHandler(performAccessibilityActionHandler);
return this;
}
@Override
public InternalNode sendAccessibilityEventHandler(
EventHandler<SendAccessibilityEventEvent> sendAccessibilityEventHandler) {
getOrCreateNodeInfo().setSendAccessibilityEventHandler(sendAccessibilityEventHandler);
return this;
}
@Override
public InternalNode sendAccessibilityEventUncheckedHandler(
EventHandler<SendAccessibilityEventUncheckedEvent> sendAccessibilityEventUncheckedHandler) {
getOrCreateNodeInfo().setSendAccessibilityEventUncheckedHandler(
sendAccessibilityEventUncheckedHandler);
return this;
}
@Override
public ContainerBuilder transitionKey(String key) {
if (SDK_INT >= ICE_CREAM_SANDWICH) {
mPrivateFlags |= PFLAG_TRANSITION_KEY_IS_SET;
mTransitionKey = key;
wrapInView();
}
return this;
}
String getTransitionKey() {
return mTransitionKey;
}
/**
* A unique identifier which may be set for retrieving a component and its bounds when testing.
*/
String getTestKey() {
return mTestKey;
}
void setMeasureFunction(YogaMeasureFunction measureFunction) {
mYogaNode.setMeasureFunction(measureFunction);
}
void setBaselineFunction(YogaBaselineFunction baselineFunction) {
// YogaNode is the only version of YogaNodeAPI with this support;
if (mYogaNode instanceof YogaNode) {
mYogaNode.setBaselineFunction(baselineFunction);
}
}
boolean hasNewLayout() {
return mYogaNode.hasNewLayout();
}
void markLayoutSeen() {
mYogaNode.markLayoutSeen();
}
float getStyleWidth() {
return mYogaNode.getWidth().value;
}
float getMinWidth() {
return mYogaNode.getMinWidth().value;
}
float getMaxWidth() {
return mYogaNode.getMaxWidth().value;
}
float getStyleHeight() {
return mYogaNode.getHeight().value;
}
float getMinHeight() {
return mYogaNode.getMinHeight().value;
}
float getMaxHeight() {
return mYogaNode.getMaxHeight().value;
}
void calculateLayout(float width, float height) {
final ComponentTree tree = mComponentContext == null
? null
: mComponentContext.getComponentTree();
final ComponentsStethoManager stethoManager = tree == null ? null : tree.getStethoManager();
if (stethoManager != null) {
applyOverridesRecursive(stethoManager, this);
}
mYogaNode.calculateLayout(width, height);
}
private static void applyOverridesRecursive(
ComponentsStethoManager stethoManager,
InternalNode node) {
stethoManager.applyOverrides(node);
for (int i = 0, count = node.getChildCount(); i < count; i++) {
applyOverridesRecursive(stethoManager, node.getChildAt(i));
}
if (node.hasNestedTree()) {
applyOverridesRecursive(stethoManager, node.getNestedTree());
}
}
void calculateLayout() {
calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
}
int getChildCount() {
return mYogaNode.getChildCount();
}
com.facebook.yoga.YogaDirection getStyleDirection() {
return mYogaNode.getStyleDirection();
}
InternalNode getChildAt(int index) {
if (mYogaNode.getChildAt(index) == null) {
return null;
}
return (InternalNode) mYogaNode.getChildAt(index).getData();
}
int getChildIndex(InternalNode child) {
for (int i = 0, count = mYogaNode.getChildCount(); i < count; i++) {
if (mYogaNode.getChildAt(i) == child.mYogaNode) {
return i;
}
}
return -1;
}
InternalNode getParent() {
if (mYogaNode == null || mYogaNode.getParent() == null) {
return null;
}
return (InternalNode) mYogaNode.getParent().getData();
}
void addChildAt(InternalNode child, int index) {
mYogaNode.addChildAt(child.mYogaNode, index);
}
InternalNode removeChildAt(int index) {
return (InternalNode) mYogaNode.removeChildAt(index).getData();
}
@Override
public ComponentLayout build() {
return this;
}
private float resolveHorizontalSpacing(Spacing spacing, int index) {
final boolean isRtl =
(mYogaNode.getLayoutDirection() == YogaDirection.RTL);
final int resolvedIndex;
switch (index) {
case Spacing.LEFT:
resolvedIndex = (isRtl ? Spacing.END : Spacing.START);
break;
case Spacing.RIGHT:
resolvedIndex = (isRtl ? Spacing.START : Spacing.END);
break;
default:
throw new IllegalArgumentException("Not an horizontal padding index: " + index);
}
float result = spacing.getRaw(resolvedIndex);
if (YogaConstants.isUndefined(result)) {
result = spacing.get(index);
}
return result;
}
ComponentContext getContext() {
return mComponentContext;
}
Component getComponent() {
return mComponent;
}
int getBorderColor() {
return mBorderColor;
}
boolean shouldDrawBorders() {
return mBorderColor != Color.TRANSPARENT
&& (mYogaNode.getLayoutBorder(LEFT) != 0
|| mYogaNode.getLayoutBorder(TOP) != 0
|| mYogaNode.getLayoutBorder(RIGHT) != 0
|| mYogaNode.getLayoutBorder(BOTTOM) != 0);
}
void setComponent(Component component) {
mComponent = component;
}
boolean hasNestedTree() {
return mNestedTree != null;
}
@Nullable InternalNode getNestedTree() {
return mNestedTree;
}
InternalNode getNestedTreeHolder() {
return mNestedTreeHolder;
}
/**
* Set the nested tree before measuring it in order to transfer over important information
* such as layout direction needed during measurement.
*/
void setNestedTree(InternalNode nestedTree) {
nestedTree.mNestedTreeHolder = this;
mNestedTree = nestedTree;
}
NodeInfo getNodeInfo() {
return mNodeInfo;
}
void copyInto(InternalNode node) {
if (mNodeInfo != null) {
if (node.mNodeInfo == null) {
node.mNodeInfo = mNodeInfo.acquireRef();
} else {
node.mNodeInfo.updateWith(mNodeInfo);
}
}
if ((node.mPrivateFlags & PFLAG_LAYOUT_DIRECTION_IS_SET) == 0L
|| node.getResolvedLayoutDirection() == YogaDirection.INHERIT) {
node.layoutDirection(getResolvedLayoutDirection());
}
if ((node.mPrivateFlags & PFLAG_IMPORTANT_FOR_ACCESSIBILITY_IS_SET) == 0L
|| node.mImportantForAccessibility == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
node.mImportantForAccessibility = mImportantForAccessibility;
}
if ((mPrivateFlags & PFLAG_DUPLICATE_PARENT_STATE_IS_SET) != 0L) {
node.mDuplicateParentState = mDuplicateParentState;
}
if ((mPrivateFlags & PFLAG_BACKGROUND_IS_SET) != 0L) {
node.mBackground = mBackground;
}
if ((mPrivateFlags & PFLAG_FOREGROUND_IS_SET) != 0L) {
node.mForeground = mForeground;
}
if (mForceViewWrapping) {
node.mForceViewWrapping = true;
}
if ((mPrivateFlags & PFLAG_VISIBLE_HANDLER_IS_SET) != 0L) {
node.mVisibleHandler = mVisibleHandler;
}
if ((mPrivateFlags & PFLAG_FOCUSED_HANDLER_IS_SET) != 0L) {
node.mFocusedHandler = mFocusedHandler;
}
if ((mPrivateFlags & PFLAG_FULL_IMPRESSION_HANDLER_IS_SET) != 0L) {
node.mFullImpressionHandler = mFullImpressionHandler;
}
if ((mPrivateFlags & PFLAG_INVISIBLE_HANDLER_IS_SET) != 0L) {
node.mInvisibleHandler = mInvisibleHandler;
}
if (mTestKey != null) {
node.mTestKey = mTestKey;
}
if ((mPrivateFlags & PFLAG_PADDING_IS_SET) != 0L) {
if (mNestedTreePadding == null) {
throw new IllegalStateException("copyInto() must be used when resolving a nestedTree. " +
"If padding was set on the holder node, we must have a mNestedTreePadding instance");
}
final YogaNodeAPI yogaNode = node.mYogaNode;
node.mPrivateFlags |= PFLAG_PADDING_IS_SET;
if (isPaddingPercent(LEFT)) {
yogaNode.setPaddingPercent(LEFT, mNestedTreePadding.getRaw(Spacing.LEFT));
} else {
yogaNode.setPadding(LEFT, mNestedTreePadding.getRaw(Spacing.LEFT));
}
if (isPaddingPercent(TOP)) {
yogaNode.setPaddingPercent(TOP, mNestedTreePadding.getRaw(Spacing.TOP));
} else {
yogaNode.setPadding(TOP, mNestedTreePadding.getRaw(Spacing.TOP));
}
if (isPaddingPercent(RIGHT)) {
yogaNode.setPaddingPercent(RIGHT, mNestedTreePadding.getRaw(Spacing.RIGHT));
} else {
yogaNode.setPadding(RIGHT, mNestedTreePadding.getRaw(Spacing.RIGHT));
}
if (isPaddingPercent(BOTTOM)) {
yogaNode.setPaddingPercent(BOTTOM, mNestedTreePadding.getRaw(Spacing.BOTTOM));
} else {
yogaNode.setPadding(BOTTOM, mNestedTreePadding.getRaw(Spacing.BOTTOM));
}
if (isPaddingPercent(VERTICAL)) {
yogaNode.setPaddingPercent(VERTICAL, mNestedTreePadding.getRaw(Spacing.VERTICAL));
} else {
yogaNode.setPadding(VERTICAL, mNestedTreePadding.getRaw(Spacing.VERTICAL));
}
if (isPaddingPercent(HORIZONTAL)) {
yogaNode.setPaddingPercent(HORIZONTAL, mNestedTreePadding.getRaw(Spacing.HORIZONTAL));
} else {
yogaNode.setPadding(HORIZONTAL, mNestedTreePadding.getRaw(Spacing.HORIZONTAL));
}
if (isPaddingPercent(START)) {
yogaNode.setPaddingPercent(START, mNestedTreePadding.getRaw(Spacing.START));
} else {
yogaNode.setPadding(START, mNestedTreePadding.getRaw(Spacing.START));
}
if (isPaddingPercent(END)) {
yogaNode.setPaddingPercent(END, mNestedTreePadding.getRaw(Spacing.END));
} else {
yogaNode.setPadding(END, mNestedTreePadding.getRaw(Spacing.END));
}
if (isPaddingPercent(ALL)) {
yogaNode.setPaddingPercent(ALL, mNestedTreePadding.getRaw(Spacing.ALL));
} else {
yogaNode.setPadding(ALL, mNestedTreePadding.getRaw(Spacing.ALL));
}
}
if ((mPrivateFlags & PFLAG_BORDER_WIDTH_IS_SET) != 0L) {
if (mNestedTreeBorderWidth == null) {
throw new IllegalStateException("copyInto() must be used when resolving a nestedTree. " +
"If border width was set on the holder node, we must have a mNestedTreeBorderWidth " +
"instance");
}
final YogaNodeAPI yogaNode = node.mYogaNode;
node.mPrivateFlags |= PFLAG_BORDER_WIDTH_IS_SET;
yogaNode.setBorder(LEFT, mNestedTreeBorderWidth.getRaw(Spacing.LEFT));
yogaNode.setBorder(TOP, mNestedTreeBorderWidth.getRaw(Spacing.TOP));
yogaNode.setBorder(RIGHT, mNestedTreeBorderWidth.getRaw(Spacing.RIGHT));
yogaNode.setBorder(BOTTOM, mNestedTreeBorderWidth.getRaw(Spacing.BOTTOM));
yogaNode.setBorder(VERTICAL, mNestedTreeBorderWidth.getRaw(Spacing.VERTICAL));
yogaNode.setBorder(HORIZONTAL, mNestedTreeBorderWidth.getRaw(Spacing.HORIZONTAL));
yogaNode.setBorder(START, mNestedTreeBorderWidth.getRaw(Spacing.START));
yogaNode.setBorder(END, mNestedTreeBorderWidth.getRaw(Spacing.END));
yogaNode.setBorder(ALL, mNestedTreeBorderWidth.getRaw(Spacing.ALL));
}
if ((mPrivateFlags & PFLAG_TRANSITION_KEY_IS_SET) != 0L) {
node.mTransitionKey = mTransitionKey;
}
if ((mPrivateFlags & PFLAG_BORDER_COLOR_IS_SET) != 0L) {
node.mBorderColor = mBorderColor;
}
}
void setStyleWidthFromSpec(int widthSpec) {
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setWidth(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxWidth(SizeSpec.getSize(widthSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setWidth(SizeSpec.getSize(widthSpec));
break;
}
}
void setStyleHeightFromSpec(int heightSpec) {
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.UNSPECIFIED:
mYogaNode.setHeight(YogaConstants.UNDEFINED);
break;
case SizeSpec.AT_MOST:
mYogaNode.setMaxHeight(SizeSpec.getSize(heightSpec));
break;
case SizeSpec.EXACTLY:
mYogaNode.setHeight(SizeSpec.getSize(heightSpec));
break;
}
}
int getImportantForAccessibility() {
return mImportantForAccessibility;
}
boolean isDuplicateParentStateEnabled() {
return mDuplicateParentState;
}
void applyAttributes(TypedArray a) {
for (int i = 0, size = a.getIndexCount(); i < size; i++) {
final int attr = a.getIndex(i);
if (attr == R.styleable.ComponentLayout_android_layout_width) {
int width = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (width >= 0) {
widthPx(width);
}
} else if (attr == R.styleable.ComponentLayout_android_layout_height) {
int height = a.getLayoutDimension(attr, -1);
// We don't support WRAP_CONTENT or MATCH_PARENT so no-op for them
if (height >= 0) {
heightPx(height);
}
} else if (attr == R.styleable.ComponentLayout_android_paddingLeft) {
paddingPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingTop) {
paddingPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingRight) {
paddingPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingBottom) {
paddingPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingStart && SUPPORTS_RTL) {
paddingPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_paddingEnd && SUPPORTS_RTL) {
paddingPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_padding) {
paddingPx(ALL, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginLeft) {
marginPx(LEFT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginTop) {
marginPx(TOP, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginRight) {
marginPx(RIGHT, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginBottom) {
marginPx(BOTTOM, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginStart && SUPPORTS_RTL) {
marginPx(START, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_marginEnd && SUPPORTS_RTL) {
marginPx(END, a.getDimensionPixelOffset(attr, 0));
} else if (attr == R.styleable.ComponentLayout_android_layout_margin) {
marginPx(ALL, a.getDimensionPixelOffset(attr, 0));
|
package com.crawljax.browser;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.internal.FileHandler;
import com.crawljax.core.configuration.ProxyConfiguration;
/**
* The class representing a Firefox webbrowser extending the AbstractWebDriver.
*
* @author Stefan Lenselink <S.R.Lenselink@student.tudelft.nl>
* @author mesbah
* @version $Id$
*/
public class WebDriverFirefox extends AbstractWebDriver {
private ProxyConfiguration proxyConfiguration = null;
private String firefoxLocation = null;
private static final Logger LOGGER = Logger.getLogger(WebDriverFirefox.class.getName());
private final FirefoxDriver driver;
/**
* Creates a new FirefoxDriver object based on a given driver as WebDriver.
*/
private WebDriverFirefox(FirefoxDriver driver, List<String> filterAttributes,
long crawlWaitReload, long crawlWaitEvent) {
super(driver, LOGGER, filterAttributes, crawlWaitReload, crawlWaitEvent);
this.driver = driver;
}
/**
* Creates a new FirefoxDriver object, use the default FirefoxDriver as WebDriver.
*
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
*/
public WebDriverFirefox(List<String> filterAttributes, long crawlWaitReload,
long crawlWaitEvent) {
this(new FirefoxDriver(), filterAttributes, crawlWaitReload, crawlWaitEvent);
}
/**
* Creates a webdriver firefox instance with a proxy set.
*
* @param config
* Proxy configuration options.
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
*/
public WebDriverFirefox(ProxyConfiguration config, List<String> filterAttributes,
long crawlWaitReload, long crawlWaitEvent) {
this(makeProfile(config), filterAttributes, crawlWaitReload, crawlWaitEvent);
proxyConfiguration = config;
}
/**
* Creates a webdriver firefox instance for a given firefox location.
*
* @param location
* the location where to find the Firefox version to use
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
*/
public WebDriverFirefox(String location, List<String> filterAttributes, long crawlWaitReload,
long crawlWaitEvent) {
this(new FirefoxDriver(new FirefoxBinary(new File(location)), null), filterAttributes,
crawlWaitReload, crawlWaitEvent);
firefoxLocation = location;
}
/**
* Creates a webdriver firefox instance for a given profile configuration.
*
* @param profile
* the profile configuration to read the config from
* @param filterAttributes
* the attributes to be filtered from DOM.
* @param crawlWaitReload
* the period to wait after a reload.
* @param crawlWaitEvent
* the period to wait after an event is fired.
*/
public WebDriverFirefox(FirefoxProfile profile, List<String> filterAttributes,
long crawlWaitReload, long crawlWaitEvent) {
this(new FirefoxDriver(profile), filterAttributes, crawlWaitReload, crawlWaitReload);
}
private static FirefoxProfile makeProfile(ProxyConfiguration config) {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", config.getHostname());
profile.setPreference("network.proxy.http_port", config.getPort());
/* 1 means HTTP proxy */
profile.setPreference("network.proxy.type", 1);
/* use proxy for everything, including localhost */
profile.setPreference("network.proxy.no_proxies_on", "");
return profile;
}
@Override
public EmbeddedBrowser clone() {
FirefoxBinary binary = null;
FirefoxProfile profile = null;
// If there is a proxyConfiguration; create a new Profile
if (proxyConfiguration != null) {
profile = makeProfile(proxyConfiguration);
}
// If the firefox location was specified, reuse the location
if (firefoxLocation != null) {
binary = new FirefoxBinary(new File(firefoxLocation));
} else {
binary = new FirefoxBinary();
}
return new WebDriverFirefox(new FirefoxDriver(binary, profile), getFilterAttributes(),
getCrawlWaitReload(), getCrawlWaitEvent());
}
/**
* @param file
* the file to write to the filename to save the screenshot in.
*/
public void saveScreenShot(File file) {
File tmpfile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileHandler.copy(tmpfile, file);
} catch (IOException e) {
throw new WebDriverException(e);
}
removeCanvasGeneratedByFirefoxDriverForScreenshots();
}
private void removeCanvasGeneratedByFirefoxDriverForScreenshots() {
String js = "";
js += "var canvas = document.getElementById('fxdriver-screenshot-canvas');";
js += "if(canvas != null){";
js += "canvas.parentNode.removeChild(canvas);";
js += "}";
try {
executeJavaScript(js);
} catch (Exception e) {
LOGGER.warn("Could not remove the screenshot canvas from the DOM.");
}
}
}
|
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.beans.PropertyChangeEvent;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.customcontrols.*;
import net.java.sip.communicator.impl.gui.event.*;
import net.java.sip.communicator.impl.gui.lookandfeel.*;
import net.java.sip.communicator.impl.gui.main.call.*;
import net.java.sip.communicator.impl.gui.main.chat.conference.*;
import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.impl.gui.main.menus.*;
import net.java.sip.communicator.impl.gui.main.presence.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.contacteventhandler.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.gui.Container;
import net.java.sip.communicator.service.keybindings.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.swing.*;
import org.osgi.framework.*;
/**
* The main application window. This class is the core of this ui
* implementation. It stores all available protocol providers and their
* operation sets, as well as all registered accounts, the
* <tt>MetaContactListService</tt> and all sent messages that aren't
* delivered yet.
*
* @author Yana Stamcheva
* @author Lubomir Marinov
*/
public class MainFrame
extends SIPCommFrame
implements ExportedWindow,
PluginComponentListener
{
private final Logger logger = Logger.getLogger(MainFrame.class);
private final TransparentPanel mainPanel
= new TransparentPanel(new BorderLayout(0, 8));
private final TransparentPanel statusBarPanel
= new TransparentPanel(new BorderLayout());
private final ImageIcon moreActionsIcon = new ImageIcon(ImageLoader
.getImage(ImageLoader.MORE_ACTIONS_BUTTON));
private final ImageIcon moreActionsRolloverIcon = new ImageIcon(ImageLoader
.getImage(ImageLoader.MORE_ACTIONS_ROLLOVER_BUTTON));
private MainMenu menu;
private MainCallPanel mainCallPanel;
private final HashMap<ProtocolProviderService, Integer> protocolProviders =
new LinkedHashMap<ProtocolProviderService, Integer>();
private AccountStatusPanel accountStatusPanel;
private MetaContactListService contactList;
private final Map<ProtocolProviderService, ContactEventHandler>
providerContactHandlers =
new Hashtable<ProtocolProviderService, ContactEventHandler>();
private final Map<PluginComponent, Component> nativePluginsTable =
new Hashtable<PluginComponent, Component>();
private final JPanel pluginPanelNorth = new JPanel();
private final JPanel pluginPanelSouth = new JPanel();
private final JPanel pluginPanelWest = new JPanel();
private final JPanel pluginPanelEast = new JPanel();
private ContactListPane contactListPanel;
private ActionMenuGlassPane glassPane = null;
/**
* Creates an instance of <tt>MainFrame</tt>.
*/
public MainFrame()
{
if (!ConfigurationManager.isWindowDecorated())
{
this.setUndecorated(true);
}
this.mainCallPanel = new MainCallPanel(this);
this.contactListPanel = new ContactListPane(this);
this.accountStatusPanel = new AccountStatusPanel(this);
menu = new MainMenu(this);
/*
* Before closing the application window saves the current size and
* position through the ConfigurationService.
*/
this.addWindowListener(new WindowAdapter()
{
public void windowClosed(WindowEvent event)
{
MainFrame.this.windowClosed(event);
}
public void windowClosing(WindowEvent event)
{
MainFrame.this.windowClosing(event);
}
});
addComponentListener(new ComponentAdapter()
{
@Override
public void componentResized(ComponentEvent e)
{
if ((glassPane != null) && glassPane.isVisible())
glassPane.revalidate();
}
});
this.initTitleFont();
ResourceManagementService resources = GuiActivator.getResources();
String applicationName
= resources.getSettingsString("service.gui.APPLICATION_NAME");
this.setTitle(applicationName);
this.mainPanel.setBackground(new Color(
GuiActivator.getResources()
.getColor("service.gui.MAIN_WINDOW_BACKGROUND")));
this.init();
this.initPluginComponents();
}
/**
* Initiates the content of this frame.
*/
private void init()
{
if (GuiActivator.getUIService().getExitOnMainWindowClose())
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
else
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setKeybindingInput(KeybindingSet.Category.MAIN);
this.addKeybindingAction("plugin.keybindings.MAIN_RENAME",
new RenameAction());
TransparentPanel northPanel = new TransparentPanel(new BorderLayout());
TransparentPanel centerPanel
= new TransparentPanel(new BorderLayout(0, 0));
String isToolbarExtendedString
= GuiActivator.getResources().
getSettingsString("impl.gui.IS_TOOLBAR_EXTENDED");
boolean isToolBarExtended
= new Boolean(isToolbarExtendedString).booleanValue();
JPanel menusPanel = new JPanel(new BorderLayout());
if (isToolBarExtended)
{
menusPanel.add(new ExtendedQuickMenu(this), BorderLayout.SOUTH);
}
this.setJMenuBar(menu);
menusPanel.setUI(new SIPCommOpaquePanelUI());
northPanel.add(new LogoBar(), BorderLayout.NORTH);
northPanel.add(menusPanel, BorderLayout.CENTER);
northPanel.add(accountStatusPanel, BorderLayout.SOUTH);
JLabel moreActionsLabel = new JLabel(moreActionsIcon);
moreActionsLabel.setToolTipText(GuiActivator.getResources()
.getI18NString("service.gui.OPEN_TOOLS"));
moreActionsLabel.addMouseListener(new ActionMenuMouseListener());
TransparentPanel moreActionsPanel
= new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
moreActionsPanel.add(moreActionsLabel);
centerPanel.add(moreActionsPanel, BorderLayout.NORTH);
centerPanel.add(contactListPanel, BorderLayout.CENTER);
centerPanel.add(mainCallPanel, BorderLayout.SOUTH);
this.mainPanel.add(northPanel, BorderLayout.NORTH);
this.mainPanel.add(centerPanel, BorderLayout.CENTER);
java.awt.Container contentPane = getContentPane();
contentPane.add(mainPanel, BorderLayout.CENTER);
contentPane.add(statusBarPanel, BorderLayout.SOUTH);
}
/**
* Sets frame size and position.
*/
public void initBounds()
{
int width = GuiActivator.getResources()
.getSettingsInt("impl.gui.MAIN_WINDOW_WIDTH");
int height = GuiActivator.getResources()
.getSettingsInt("impl.gui.MAIN_WINDOW_HEIGHT");
int minWidth = GuiActivator.getResources()
.getSettingsInt("impl.gui.MAIN_WINDOW_MIN_WIDTH");
int minHeight = GuiActivator.getResources()
.getSettingsInt("impl.gui.MAIN_WINDOW_MIN_HEIGHT");
this.getContentPane().setMinimumSize(new Dimension(minWidth, minHeight));
this.setSize(width, height);
this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width
- this.getWidth(), 50);
}
/**
* Initialize main window font.
*/
private void initTitleFont()
{
JComponent layeredPane = this.getLayeredPane();
ResourceManagementService resources = GuiActivator.getResources();
String fontName
= resources.getSettingsString("service.gui.FONT_NAME");
String titleFontSize
= resources.getSettingsString("service.gui.FONT_SIZE");
Font font = new Font( fontName,
Font.BOLD,
new Integer(titleFontSize).intValue());
final int componentCount = layeredPane.getComponentCount();
for (int i = 0; i < componentCount; i++)
{
layeredPane.getComponent(i).setFont(font);
}
}
/**
* Returns the <tt>MetaContactListService</tt>.
*
* @return <tt>MetaContactListService</tt> The current meta contact list.
*/
public MetaContactListService getContactList()
{
return this.contactList;
}
/**
* Initializes the contact list panel.
*
* @param contactList The <tt>MetaContactListService</tt> containing
* the contact list data.
*/
public void setContactList(MetaContactListService contactList)
{
this.contactList = contactList;
contactListPanel.initList(contactList);
contactListPanel.getContactList()
.addListSelectionListener(mainCallPanel);
}
/**
* Adds all protocol supported operation sets.
*
* @param protocolProvider The protocol provider.
*/
public void addProtocolSupportedOperationSets(
ProtocolProviderService protocolProvider)
{
Map<String, OperationSet> supportedOperationSets
= protocolProvider.getSupportedOperationSets();
String ppOpSetClassName = OperationSetPersistentPresence
.class.getName();
String pOpSetClassName = OperationSetPresence.class.getName();
// Obtain the presence operation set.
if (supportedOperationSets.containsKey(ppOpSetClassName)
|| supportedOperationSets.containsKey(pOpSetClassName)) {
OperationSetPresence presence = (OperationSetPresence)
supportedOperationSets.get(ppOpSetClassName);
if(presence == null) {
presence = (OperationSetPresence)
supportedOperationSets.get(pOpSetClassName);
}
presence.addProviderPresenceStatusListener(
new GUIProviderPresenceStatusListener());
presence.addContactPresenceStatusListener(
new GUIContactPresenceStatusListener());
}
// Obtain the basic instant messaging operation set.
String imOpSetClassName = OperationSetBasicInstantMessaging
.class.getName();
if (supportedOperationSets.containsKey(imOpSetClassName)) {
OperationSetBasicInstantMessaging im
= (OperationSetBasicInstantMessaging)
supportedOperationSets.get(imOpSetClassName);
//Add to all instant messaging operation sets the Message
//listener implemented in the ContactListPanel, which handles
//all received messages.
im.addMessageListener(getContactListPanel());
}
// Obtain the typing notifications operation set.
String tnOpSetClassName = OperationSetTypingNotifications
.class.getName();
if (supportedOperationSets.containsKey(tnOpSetClassName)) {
OperationSetTypingNotifications tn
= (OperationSetTypingNotifications)
supportedOperationSets.get(tnOpSetClassName);
//Add to all typing notification operation sets the Message
//listener implemented in the ContactListPanel, which handles
//all received messages.
tn.addTypingNotificationsListener(this.getContactListPanel());
}
// Obtain the basic telephony operation set.
String telOpSetClassName = OperationSetBasicTelephony.class.getName();
if (supportedOperationSets.containsKey(telOpSetClassName)) {
OperationSetBasicTelephony telephony
= (OperationSetBasicTelephony)
supportedOperationSets.get(telOpSetClassName);
telephony.addCallListener(new CallManager.GuiCallListener());
}
// Obtain the multi user chat operation set.
String multiChatClassName = OperationSetMultiUserChat.class.getName();
if (supportedOperationSets.containsKey(multiChatClassName))
{
OperationSetMultiUserChat multiUserChat
= (OperationSetMultiUserChat)
supportedOperationSets.get(multiChatClassName);
ConferenceChatManager conferenceManager
= GuiActivator.getUIService().getConferenceChatManager();
multiUserChat.addInvitationListener(conferenceManager);
multiUserChat.addInvitationRejectionListener(conferenceManager);
multiUserChat.addPresenceListener(conferenceManager);
}
}
/**
* Returns a set of all protocol providers.
*
* @return a set of all protocol providers.
*/
public Iterator<ProtocolProviderService> getProtocolProviders()
{
return ((Map<ProtocolProviderService, Integer>)protocolProviders.clone()).keySet().iterator();
}
/**
* Returns the protocol provider associated to the account given
* by the account user identifier.
*
* @param accountName The account user identifier.
* @return The protocol provider associated to the given account.
*/
public ProtocolProviderService getProtocolProviderForAccount(
String accountName)
{
for (ProtocolProviderService pps : protocolProviders.keySet()) {
if (pps.getAccountID().getUserID().equals(accountName)) {
return pps;
}
}
return null;
}
/**
* Adds a protocol provider.
* @param protocolProvider The protocol provider to add.
*/
public void addProtocolProvider(ProtocolProviderService protocolProvider)
{
logger.trace("Add the following protocol provider to the gui: "
+ protocolProvider.getAccountID().getAccountAddress());
this.protocolProviders.put(protocolProvider,
new Integer(initiateProviderIndex(protocolProvider)));
this.addProtocolSupportedOperationSets(protocolProvider);
this.addAccount(protocolProvider);
ContactEventHandler contactHandler
= this.getContactHandlerForProvider(protocolProvider);
if (contactHandler == null)
contactHandler = new DefaultContactEventHandler(this);
this.addProviderContactHandler(protocolProvider, contactHandler);
}
/**
* Returns the index of the given protocol provider.
* @param protocolProvider the protocol provider to search for
* @return the index of the given protocol provider
*/
public int getProviderIndex(ProtocolProviderService protocolProvider)
{
Integer o = protocolProviders.get(protocolProvider);
return (o != null) ? o.intValue() : 0;
}
/**
* Adds an account to the application.
*
* @param protocolProvider The protocol provider of the account.
*/
public void addAccount(ProtocolProviderService protocolProvider)
{
if (!accountStatusPanel.containsAccount(protocolProvider))
{
logger.trace("Add the following account to the status bar: "
+ protocolProvider.getAccountID().getAccountAddress());
accountStatusPanel.addAccount(protocolProvider);
//request the focus in the contact list panel, which
//permits to search in the contact list
this.contactListPanel.getContactList()
.requestFocus();
}
if(!mainCallPanel.containsCallAccount(protocolProvider)
&& getTelephonyOpSet(protocolProvider) != null)
{
mainCallPanel.addCallAccount(protocolProvider);
}
}
/**
* Adds an account to the application.
*
* @param protocolProvider The protocol provider of the account.
*/
public void removeProtocolProvider(ProtocolProviderService protocolProvider)
{
this.protocolProviders.remove(protocolProvider);
this.updateProvidersIndexes(protocolProvider);
if (accountStatusPanel.containsAccount(protocolProvider))
{
accountStatusPanel.removeAccount(protocolProvider);
}
if(mainCallPanel.containsCallAccount(protocolProvider))
{
mainCallPanel.removeCallAccount(protocolProvider);
}
}
/**
* Returns the account user id for the given protocol provider.
* @return The account user id for the given protocol provider.
*/
public String getAccount(ProtocolProviderService protocolProvider)
{
return protocolProvider.getAccountID().getUserID();
}
/**
* Returns the presence operation set for the given protocol provider.
*
* @param protocolProvider The protocol provider for which the
* presence operation set is searched.
* @return the presence operation set for the given protocol provider.
*/
public OperationSetPresence getProtocolPresenceOpSet(
ProtocolProviderService protocolProvider)
{
OperationSet opSet
= protocolProvider.getOperationSet(OperationSetPresence.class);
return (opSet instanceof OperationSetPresence) ? (OperationSetPresence) opSet
: null;
}
/**
* Returns the Web Contact Info operation set for the given
* protocol provider.
*
* @param protocolProvider The protocol provider for which the TN
* is searched.
* @return OperationSetWebContactInfo The Web Contact Info operation
* set for the given protocol provider.
*/
public OperationSetWebContactInfo getWebContactInfoOpSet(
ProtocolProviderService protocolProvider)
{
OperationSet opSet
= protocolProvider.getOperationSet(OperationSetWebContactInfo.class);
return (opSet instanceof OperationSetWebContactInfo) ? (OperationSetWebContactInfo) opSet
: null;
}
/**
* Returns the telephony operation set for the given protocol provider.
*
* @param protocolProvider The protocol provider for which the telephony
* operation set is about.
* @return OperationSetBasicTelephony The telephony operation
* set for the given protocol provider.
*/
public OperationSetBasicTelephony getTelephonyOpSet(
ProtocolProviderService protocolProvider)
{
OperationSet opSet
= protocolProvider.getOperationSet(OperationSetBasicTelephony.class);
return (opSet instanceof OperationSetBasicTelephony) ? (OperationSetBasicTelephony) opSet
: null;
}
/**
* Returns the multi user chat operation set for the given protocol provider.
*
* @param protocolProvider The protocol provider for which the multi user
* chat operation set is about.
* @return OperationSetMultiUserChat The telephony operation
* set for the given protocol provider.
*/
public OperationSetMultiUserChat getMultiUserChatOpSet(
ProtocolProviderService protocolProvider)
{
OperationSet opSet
= protocolProvider.getOperationSet(OperationSetMultiUserChat.class);
return (opSet instanceof OperationSetMultiUserChat) ? (OperationSetMultiUserChat) opSet
: null;
}
/**
* Listens for all contactPresenceStatusChanged events in order
* to refresh the contact list, when a status is changed.
*/
private class GUIContactPresenceStatusListener implements
ContactPresenceStatusListener
{
/**
* Indicates that a contact has changed its status.
*
* @param evt the presence event containing information about the
* contact status change
*/
public void contactPresenceStatusChanged(
ContactPresenceStatusChangeEvent evt)
{
Contact sourceContact = evt.getSourceContact();
MetaContact metaContact = contactList
.findMetaContactByContact(sourceContact);
if (metaContact != null
&& (evt.getOldStatus() != evt.getNewStatus()))
{
// Update the status in the contact list.
contactListPanel.getContactList().refreshContact(metaContact);
}
}
}
/**
* Listens for all providerStatusChanged and providerStatusMessageChanged
* events in order to refresh the account status panel, when a status is
* changed.
*/
private class GUIProviderPresenceStatusListener implements
ProviderPresenceStatusListener
{
public void providerStatusChanged(ProviderPresenceStatusChangeEvent evt)
{
ProtocolProviderService pps = evt.getProvider();
accountStatusPanel.updateStatus(pps, evt.getNewStatus());
if(mainCallPanel.containsCallAccount(pps))
{
mainCallPanel.updateCallAccountStatus(pps);
}
}
public void providerStatusMessageChanged(PropertyChangeEvent evt) {
}
}
/**
* Returns the list of all groups.
* @return The list of all groups.
*/
public Iterator<MetaContactGroup> getAllGroups()
{
return getContactListPanel().getContactList().getAllGroups();
}
/**
* Returns the Meta Contact Group corresponding to the given MetaUID.
*
* @param metaUID An identifier of a group.
* @return The Meta Contact Group corresponding to the given MetaUID.
*/
public MetaContactGroup getGroupByID(String metaUID)
{
return getContactListPanel()
.getContactList().getGroupByID(metaUID);
}
/**
* Returns the panel containing the ContactList.
* @return ContactListPanel the panel containing the ContactList
*/
public ContactListPane getContactListPanel()
{
return this.contactListPanel;
}
/**
* Checks in the configuration xml if there is already stored index for
* this provider and if yes, returns it, otherwise creates a new account
* index and stores it.
*
* @param protocolProvider the protocol provider
* @return the protocol provider index
*/
private int initiateProviderIndex(
ProtocolProviderService protocolProvider)
{
ConfigurationService configService
= GuiActivator.getConfigurationService();
String prefix = "net.java.sip.communicator.impl.gui.accounts";
List<String> accounts = configService
.getPropertyNamesByPrefix(prefix, true);
boolean savedAccount = false;
for (String accountRootPropName : accounts) {
String accountUID
= configService.getString(accountRootPropName);
if(accountUID.equals(protocolProvider
.getAccountID().getAccountUniqueID())) {
savedAccount = true;
String index = configService.getString(
accountRootPropName + ".accountIndex");
if(index != null) {
//if we have found the accountIndex for this protocol provider
//return this index
return Integer.parseInt(index);
}
else {
//if there's no stored accountIndex for this protocol
//provider, calculate the index, set it in the configuration
//service and return it.
int accountIndex = createAccountIndex(protocolProvider,
accountRootPropName);
return accountIndex;
}
}
}
if(!savedAccount) {
String accNodeName
= "acc" + Long.toString(System.currentTimeMillis());
String accountPackage
= "net.java.sip.communicator.impl.gui.accounts."
+ accNodeName;
configService.setProperty(accountPackage,
protocolProvider.getAccountID().getAccountUniqueID());
int accountIndex = createAccountIndex(protocolProvider,
accountPackage);
return accountIndex;
}
return -1;
}
/**
* Creates and calculates the account index for the given protocol
* provider.
* @param protocolProvider the protocol provider
* @param accountRootPropName the path to where the index should be saved
* in the configuration xml
* @return the created index
*/
private int createAccountIndex(ProtocolProviderService protocolProvider,
String accountRootPropName)
{
ConfigurationService configService
= GuiActivator.getConfigurationService();
int accountIndex = -1;
for (ProtocolProviderService pps : protocolProviders.keySet())
{
if (pps.getProtocolDisplayName().equals(
protocolProvider.getProtocolDisplayName())
&& !pps.equals(protocolProvider))
{
int index = protocolProviders.get(pps).intValue();
if (accountIndex < index)
accountIndex = index;
}
}
accountIndex++;
configService.setProperty(
accountRootPropName + ".accountIndex",
new Integer(accountIndex));
return accountIndex;
}
/**
* Updates the indexes in the configuration xml, when a provider has been
* removed.
* @param removedProvider the removed protocol provider
*/
private void updateProvidersIndexes(ProtocolProviderService removedProvider)
{
ConfigurationService configService
= GuiActivator.getConfigurationService();
String prefix = "net.java.sip.communicator.impl.gui.accounts";
ProtocolProviderService currentProvider = null;
int sameProtocolProvidersCount = 0;
for (ProtocolProviderService pps : protocolProviders.keySet()) {
if(pps.getProtocolDisplayName().equals(
removedProvider.getProtocolDisplayName())) {
sameProtocolProvidersCount++;
if(sameProtocolProvidersCount > 1) {
break;
}
currentProvider = pps;
}
}
if(sameProtocolProvidersCount < 2 && currentProvider != null) {
protocolProviders.put(currentProvider, new Integer(0));
List<String> accounts = configService
.getPropertyNamesByPrefix(prefix, true);
for (String rootPropName : accounts) {
String accountUID
= configService.getString(rootPropName);
if(accountUID.equals(currentProvider
.getAccountID().getAccountUniqueID())) {
configService.setProperty(
rootPropName + ".accountIndex",
new Integer(0));
}
}
}
}
/**
* If the protocol provider supports presence operation set searches the
* last status which was selected, otherwise returns null.
*
* @param protocolProvider the protocol provider we're interested in.
* @return the last protocol provider presence status, or null if this
* provider doesn't support presence operation set
*/
public Object getProtocolProviderLastStatus(
ProtocolProviderService protocolProvider)
{
if(getProtocolPresenceOpSet(protocolProvider) != null)
return accountStatusPanel
.getLastPresenceStatus(protocolProvider);
else
return accountStatusPanel.getLastStatusString(protocolProvider);
}
/**
* <tt>RenameAction</tt> is invoked when user presses the F2 key. Depending
* on the selection opens the appropriate form for renaming.
*/
private class RenameAction extends AbstractAction
{
private static final long serialVersionUID = 0L;
public void actionPerformed(ActionEvent e)
{
Object selectedObject
= getContactListPanel().getContactList().getSelectedValue();
if(selectedObject instanceof MetaContact) {
RenameContactDialog dialog = new RenameContactDialog(
MainFrame.this, (MetaContact)selectedObject);
dialog.setLocation(
Toolkit.getDefaultToolkit().getScreenSize().width/2
- 200,
Toolkit.getDefaultToolkit().getScreenSize().height/2
- 50
);
dialog.setVisible(true);
dialog.requestFocusInFiled();
}
else if(selectedObject instanceof MetaContactGroup) {
RenameGroupDialog dialog = new RenameGroupDialog(
MainFrame.this, (MetaContactGroup)selectedObject);
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(screenSize.width / 2 - 200,
screenSize.height / 2 - 50);
dialog.setVisible(true);
dialog.requestFocusInFiled();
}
}
}
/**
* Overwrites the <tt>SIPCommFrame</tt> close method. This method is
* invoked when user presses the Escape key.
*/
protected void close(boolean isEscaped)
{
ContactList contactList = getContactListPanel().getContactList();
ContactRightButtonMenu contactPopupMenu
= contactList.getContactRightButtonMenu();
GroupRightButtonMenu groupPopupMenu
= contactList.getGroupRightButtonMenu();
CommonRightButtonMenu commonPopupMenu
= getContactListPanel().getCommonRightButtonMenu();
if(contactPopupMenu != null && contactPopupMenu.isVisible())
{
contactPopupMenu.setVisible(false);
}
else if(groupPopupMenu != null && groupPopupMenu.isVisible())
{
groupPopupMenu.setVisible(false);
}
else if(commonPopupMenu != null && commonPopupMenu.isVisible())
{
commonPopupMenu.setVisible(false);
}
else if(accountStatusPanel.hasSelectedMenus()
|| menu.hasSelectedMenus())
{
MenuSelectionManager selectionManager
= MenuSelectionManager.defaultManager();
selectionManager.clearSelectedPath();
}
}
/**
* Returns the main menu in the application window.
* @return the main menu in the application window
*/
public MainMenu getMainMenu()
{
return menu;
}
/**
*
* @param protocolProvider
* @param contactHandler
*/
public void addProviderContactHandler(
ProtocolProviderService protocolProvider,
ContactEventHandler contactHandler)
{
providerContactHandlers.put(protocolProvider, contactHandler);
}
/**
* Returns the <tt>ContactEventHandler</tt> registered for this protocol
* provider.
*
* @param protocolProvider the <tt>ProtocolProviderService</tt> for which
* we are searching a <tt>ContactEventHandler</tt>.
* @return the <tt>ContactEventHandler</tt> registered for this protocol
* provider
*/
public ContactEventHandler getContactHandler(
ProtocolProviderService protocolProvider)
{
return providerContactHandlers.get(protocolProvider);
}
/**
*
* @param protocolProvider
* @return
*/
private ContactEventHandler getContactHandlerForProvider(
ProtocolProviderService protocolProvider)
{
ServiceReference[] serRefs = null;
String osgiFilter = "("
+ ProtocolProviderFactory.PROTOCOL
+ "=" + protocolProvider.getProtocolName()+")";
try
{
serRefs = GuiActivator.bundleContext.getServiceReferences(
ContactEventHandler.class.getName(), osgiFilter);
}
catch (InvalidSyntaxException ex){
logger.error("GuiActivator : " + ex);
}
if(serRefs == null)
return null;
return (ContactEventHandler) GuiActivator.bundleContext
.getService(serRefs[0]);
}
/**
* Initialize plugin components already registered for this container.
*/
private void initPluginComponents()
{
pluginPanelSouth.setLayout(
new BoxLayout(pluginPanelSouth, BoxLayout.Y_AXIS));
pluginPanelNorth.setLayout(
new BoxLayout(pluginPanelNorth, BoxLayout.Y_AXIS));
pluginPanelEast.setLayout(
new BoxLayout(pluginPanelEast, BoxLayout.Y_AXIS));
pluginPanelWest.setLayout(
new BoxLayout(pluginPanelWest, BoxLayout.Y_AXIS));
java.awt.Container contentPane = getContentPane();
contentPane.add(pluginPanelNorth, BorderLayout.NORTH);
contentPane.add(pluginPanelEast, BorderLayout.EAST);
contentPane.add(pluginPanelWest, BorderLayout.WEST);
this.mainPanel.add(pluginPanelSouth, BorderLayout.SOUTH);
// Search for plugin components registered through the OSGI bundle
// context.
ServiceReference[] serRefs = null;
String osgiFilter = "(|("
+ Container.CONTAINER_ID
+ "="+Container.CONTAINER_MAIN_WINDOW.getID()+")"
+ "(" + Container.CONTAINER_ID
+ "="+Container.CONTAINER_STATUS_BAR.getID()+"))";
try
{
serRefs = GuiActivator.bundleContext.getServiceReferences(
PluginComponent.class.getName(),
osgiFilter);
}
catch (InvalidSyntaxException exc)
{
logger.error("Could not obtain plugin reference.", exc);
}
if (serRefs != null)
{
for (int i = 0; i < serRefs.length; i++)
{
PluginComponent c =
(PluginComponent) GuiActivator.bundleContext
.getService(serRefs[i]);
if (c.isNativeComponent())
nativePluginsTable.put(c, new JPanel());
else
{
String pluginConstraints = c.getConstraints();
Object constraints = null;
if (pluginConstraints != null)
constraints =
UIServiceImpl
.getBorderLayoutConstraintsFromContainer(pluginConstraints);
else
constraints = BorderLayout.SOUTH;
this.addPluginComponent((Component) c.getComponent(), c
.getContainer(), constraints);
}
}
}
GuiActivator.getUIService().addPluginComponentListener(this);
}
/**
* Adds the associated with this <tt>PluginComponentEvent</tt> component to
* the appropriate container.
*/
public void pluginComponentAdded(PluginComponentEvent event)
{
PluginComponent pluginComponent = event.getPluginComponent();
Container pluginContainer = pluginComponent.getContainer();
if (pluginContainer.equals(Container.CONTAINER_MAIN_WINDOW)
|| pluginContainer.equals(Container.CONTAINER_STATUS_BAR))
{
String pluginConstraints = pluginComponent.getConstraints();
Object constraints = null;
if (pluginConstraints != null)
constraints =
UIServiceImpl
.getBorderLayoutConstraintsFromContainer(pluginConstraints);
else
constraints = BorderLayout.SOUTH;
if (pluginComponent.isNativeComponent())
{
this.nativePluginsTable.put(pluginComponent, new JPanel());
if (isVisible())
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
addNativePlugins();
}
});
}
}
else
{
this.addPluginComponent((Component) pluginComponent
.getComponent(), pluginContainer, constraints);
}
}
}
/**
* Removes the associated with this <tt>PluginComponentEvent</tt> component
* from this container.
*/
public void pluginComponentRemoved(PluginComponentEvent event)
{
final PluginComponent pluginComponent = event.getPluginComponent();
final Container containerID = pluginComponent.getContainer();
if (containerID.equals(Container.CONTAINER_MAIN_WINDOW))
{
Object constraints = UIServiceImpl
.getBorderLayoutConstraintsFromContainer(
pluginComponent.getConstraints());
if (constraints == null)
constraints = BorderLayout.SOUTH;
if (pluginComponent.isNativeComponent())
{
if (nativePluginsTable.containsKey(pluginComponent))
{
final Component c = nativePluginsTable.get(pluginComponent);
final Object finalConstraints = constraints;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
removePluginComponent(c, containerID,
finalConstraints);
getContentPane().repaint();
}
});
}
}
else
{
this.removePluginComponent((Component) pluginComponent
.getComponent(), containerID, constraints);
}
nativePluginsTable.remove(pluginComponent);
}
}
/**
* The logo bar is positioned on the top of the window and is meant to
* contain the application logo.
*/
private static class LogoBar
extends JPanel
{
private final TexturePaint texture;
/**
* Creates the logo bar and specify the size.
*/
public LogoBar()
{
int width = GuiActivator.getResources()
.getSettingsInt("impl.gui.LOGO_BAR_WIDTH");
int height = GuiActivator.getResources()
.getSettingsInt("impl.gui.LOGO_BAR_HEIGHT");
Dimension size = new Dimension(width, height);
this.setMinimumSize(size);
this.setPreferredSize(size);
BufferedImage bgImage =
ImageLoader.getImage(ImageLoader.WINDOW_TITLE_BAR_BG);
Rectangle rect =
new Rectangle(0, 0, bgImage.getWidth(null), bgImage
.getHeight(null));
texture = new TexturePaint(bgImage, rect);
}
/**
* Paints the logo bar.
*
* @param g the <tt>Graphics</tt> object used to paint the background
* image of this logo bar.
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Image logoImage
= ImageLoader.getImage(ImageLoader.WINDOW_TITLE_BAR);
g.drawImage(logoImage, 0, 0, null);
g.setColor(new Color(
GuiActivator.getResources().getColor("logoBarBackground")));
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(texture);
g2.fillRect(logoImage.getWidth(null), 0,
this.getWidth(), this.getHeight());
}
}
/**
* Removes all native plugins from this container.
*/
private void removeNativePlugins()
{
Object constraints;
for (Map.Entry<PluginComponent, Component> entry : nativePluginsTable
.entrySet())
{
PluginComponent pluginComponent = entry.getKey();
Component c = entry.getValue();
constraints =
UIServiceImpl
.getBorderLayoutConstraintsFromContainer(pluginComponent
.getConstraints());
if (constraints == null)
constraints = BorderLayout.SOUTH;
this.removePluginComponent(c, pluginComponent.getContainer(),
constraints);
this.getContentPane().repaint();
}
}
/**
* Adds all native plugins to this container.
*/
public void addNativePlugins()
{
this.removeNativePlugins();
for (Map.Entry<PluginComponent, Component> pluginEntry : nativePluginsTable
.entrySet())
{
PluginComponent plugin = pluginEntry.getKey();
Object constraints =
UIServiceImpl.getBorderLayoutConstraintsFromContainer(plugin
.getConstraints());
Component c = (Component) plugin.getComponent();
this.addPluginComponent(c, plugin.getContainer(), constraints);
this.nativePluginsTable.put(plugin, c);
}
}
public void bringToFront()
{
this.toFront();
}
public WindowID getIdentifier()
{
return ExportedWindow.MAIN_WINDOW;
}
public Object getSource()
{
return this;
}
public void maximize()
{
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void minimize()
{
this.setExtendedState(JFrame.ICONIFIED);
}
/**
* Implements <code>isVisible</code> in the UIService interface. Checks if
* the main application window is visible.
*
* @return <code>true</code> if main application window is visible,
* <code>false</code> otherwise
* @see UIService#isVisible()
*/
public boolean isVisible()
{
return super.isVisible()
&& (super.getExtendedState() != JFrame.ICONIFIED);
}
/**
* Implements <code>setVisible</code> in the UIService interface. Shows or
* hides the main application window depending on the parameter
* <code>visible</code>.
*
* @param isVisible true if we are to show the main application frame and
* false otherwise.
*
* @see UIService#setVisible(boolean)
*/
public void setVisible(final boolean isVisible)
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
if(isVisible)
{
MainFrame.this.addNativePlugins();
MainFrame.super.setVisible(isVisible);
MainFrame.super.setExtendedState(MainFrame.NORMAL);
MainFrame.super.toFront();
}
else
{
MainFrame.super.setVisible(isVisible);
}
}
});
}
/**
* Adds the given component with to the container corresponding to the
* given constraints.
*
* @param c the component to add
* @param constraints the constraints determining the container
*/
private void addPluginComponent(Component c,
Container container,
Object constraints)
{
if (container.equals(Container.CONTAINER_MAIN_WINDOW))
{
if (constraints.equals(BorderLayout.NORTH))
{
pluginPanelNorth.add(c);
pluginPanelNorth.repaint();
}
else if (constraints.equals(BorderLayout.SOUTH))
{
pluginPanelSouth.add(c);
pluginPanelSouth.repaint();
}
else if (constraints.equals(BorderLayout.WEST))
{
pluginPanelWest.add(c);
pluginPanelWest.repaint();
}
else if (constraints.equals(BorderLayout.EAST))
{
pluginPanelEast.add(c);
pluginPanelEast.repaint();
}
}
else if (container.equals(Container.CONTAINER_STATUS_BAR))
{
statusBarPanel.add(c);
}
this.getContentPane().repaint();
}
/**
* Removes the given component from the container corresponding to the given
* constraints.
*
* @param c the component to remove
* @param constraints the constraints determining the container
*/
private void removePluginComponent( Component c,
Container container,
Object constraints)
{
if (container.equals(Container.CONTAINER_MAIN_WINDOW))
{
if (constraints.equals(BorderLayout.NORTH))
pluginPanelNorth.remove(c);
else if (constraints.equals(BorderLayout.SOUTH))
pluginPanelSouth.remove(c);
else if (constraints.equals(BorderLayout.WEST))
pluginPanelWest.remove(c);
else if (constraints.equals(BorderLayout.EAST))
pluginPanelEast.remove(c);
}
else if (container.equals(Container.CONTAINER_STATUS_BAR))
{
this.statusBarPanel.remove(c);
}
}
/**
* Returns the account status panel.
* @return the account status panel.
*/
public AccountStatusPanel getAccountStatusPanel()
{
return accountStatusPanel;
}
/**
* Returns the phone number currently entered in the phone number field.
*
* @return the phone number currently entered in the phone number field.
*/
public String getCurrentPhoneNumber()
{
return mainCallPanel.getPhoneNumberComboText();
}
/**
* Implementation of {@link ExportedWindow#setParams(Object[])}.
*/
public void setParams(Object[] windowParams) {}
protected void windowClosed(WindowEvent event)
{
if(GuiActivator.getUIService().getExitOnMainWindowClose())
{
try
{
GuiActivator.bundleContext.getBundle(0).stop();
}
catch (BundleException ex)
{
logger.error("Failed to gently shutdown Felix", ex);
System.exit(0);
}
//stopping a bundle doesn't leave the time to the felix thread to
//properly end all bundles and call their Activator.stop() methods.
//if this causes problems don't uncomment the following line but
//try and see why felix isn't exiting (suggesting: is it running
//in embedded mode?)
//System.exit(0);
}
}
protected void windowClosing(WindowEvent event)
{
if (!GuiActivator.getUIService().getExitOnMainWindowClose())
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (ConfigurationManager.isQuitWarningShown())
{
MessageDialog dialog =
new MessageDialog(null,
GuiActivator.getResources().getI18NString(
"service.gui.CLOSE"),
GuiActivator.getResources().getI18NString(
"service.gui.HIDE_MAIN_WINDOW"), false);
if (dialog.showDialog() == MessageDialog.OK_DONT_ASK_CODE)
ConfigurationManager.setQuitWarningShown(false);
}
}
});
ConfigurationManager.setApplicationVisible(false);
}
}
/**
* Initializes the more actions panel.
*/
private class ActionMenuMouseListener extends MouseAdapter
{
public void mouseEntered(MouseEvent e)
{
JLabel moreActionsLabel = (JLabel) e.getComponent();
moreActionsLabel.setIcon(moreActionsRolloverIcon);
moreActionsLabel.revalidate();
moreActionsLabel.repaint();
}
public void mouseExited(MouseEvent e)
{
JLabel moreActionsLabel = (JLabel) e.getComponent();
moreActionsLabel.setIcon(moreActionsIcon);
moreActionsLabel.revalidate();
moreActionsLabel.repaint();
}
public void mousePressed(MouseEvent e)
{
if ((glassPane == null) && (rootPane != null))
{
glassPane = new ActionMenuGlassPane();
glassPane.add(new ActionMenuPanel());
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener(
new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent e)
{
String prop = e.getPropertyName();
if ("focusOwner".equals(prop))
{
if (!glassPane.isVisible())
return;
Object newValue = e.getNewValue();
// we dont want the glasspane staying on top
// ot certains components
if (newValue == rootPane)
{
glassPane.setVisible(false);
}
}
}
});
rootPane.setGlassPane(glassPane);
glassPane.setVisible(true);
}
else
{
glassPane.setVisible(!glassPane.isVisible());
}
}
}
}
|
package com.feeyo.redis.engine.manage;
import com.feeyo.kafka.config.KafkaPoolCfg;
import com.feeyo.kafka.config.TopicCfg;
import com.feeyo.kafka.net.backend.KafkaBackendConnection;
import com.feeyo.kafka.net.backend.broker.BrokerPartition;
import com.feeyo.kafka.net.backend.broker.BrokerPartition.ConsumerOffset;
import com.feeyo.kafka.net.backend.broker.offset.BrokerOffsetService;
import com.feeyo.kafka.net.backend.pool.KafkaPool;
import com.feeyo.net.codec.redis.RedisRequest;
import com.feeyo.net.nio.ClosableConnection;
import com.feeyo.net.nio.NetSystem;
import com.feeyo.net.nio.buffer.BufferPool;
import com.feeyo.net.nio.buffer.bucket.AbstractBucket;
import com.feeyo.net.nio.buffer.bucket.BucketBufferPool;
import com.feeyo.net.nio.buffer.page.PageBufferPool;
import com.feeyo.net.nio.util.ProtoUtils;
import com.feeyo.redis.config.PoolCfg;
import com.feeyo.redis.config.UserCfg;
import com.feeyo.redis.engine.RedisEngineCtx;
import com.feeyo.redis.engine.manage.stat.BigKeyCollector;
import com.feeyo.redis.engine.manage.stat.BigKeyCollector.BigKey;
import com.feeyo.redis.engine.manage.stat.BigLengthCollector.BigLength;
import com.feeyo.redis.engine.manage.stat.CmdAccessCollector;
import com.feeyo.redis.engine.manage.stat.CmdAccessCollector.Command;
import com.feeyo.redis.engine.manage.stat.CmdAccessCollector.UserCommand;
import com.feeyo.redis.engine.manage.stat.SlowKeyColletor.SlowKey;
import com.feeyo.redis.engine.manage.stat.StatUtil;
import com.feeyo.redis.engine.manage.stat.StatUtil.AccessStatInfoResult;
import com.feeyo.redis.engine.manage.stat.UserFlowCollector.UserFlow;
import com.feeyo.redis.net.backend.RedisBackendConnection;
import com.feeyo.redis.net.backend.callback.DirectTransTofrontCallBack;
import com.feeyo.redis.net.backend.pool.AbstractPool;
import com.feeyo.redis.net.backend.pool.PhysicalNode;
import com.feeyo.redis.net.backend.pool.RedisStandalonePool;
import com.feeyo.redis.net.backend.pool.cluster.ClusterNode;
import com.feeyo.redis.net.backend.pool.cluster.RedisClusterPool;
import com.feeyo.redis.net.front.NetFlowGuard;
import com.feeyo.redis.net.front.NetFlowGuard.Guard;
import com.feeyo.redis.net.front.RedisFrontConnection;
import com.feeyo.redis.net.front.bypass.BypassService;
import com.feeyo.redis.net.front.bypass.BypassThreadExecutor;
import com.feeyo.util.JavaUtils;
import com.feeyo.util.ShellUtils;
import com.feeyo.util.Versions;
import com.feeyo.util.jedis.JedisConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
*
*
* @author zhuam
*
*/
public class Manage {
private static Logger LOGGER = LoggerFactory.getLogger( Manage.class );
private static String JAVA_BIN_PATH = "/usr/local/software/jdk1.7.0_72/bin/";
private static List<String> getOS_JVM_INFO(String cmd) {
List<String> lines = new ArrayList<String>();
try {
String output = JavaUtils.launchProcess(cmd, new HashMap<String, String>(), false);
lines.add(output);
} catch (IOException e) {
LOGGER.error("Failed to execute " + cmd, e);
lines.add("Failed to execute " + cmd);
} catch (Exception e) {
LOGGER.error("", e);
lines.add("Failed to execute " + cmd + ", " + e.getCause());
}
return lines;
}
public static byte[] execute(final RedisRequest request, RedisFrontConnection frontCon) {
int numArgs = request.getNumArgs();
if ( numArgs < 2 ) {
return "-ERR Parameter error \r\n".getBytes();
}
byte[] arg1 = request.getArgs()[0];
String arg2 = new String( request.getArgs()[1] );
if ( arg1 == null || arg2 == null) {
return "-ERR Parameter error \r\n".getBytes();
}
// JVM
if ( arg1.length == 3 ) {
if ( (arg1[0] == 'J' || arg1[0] == 'j' ) &&
(arg1[1] == 'V' || arg1[1] == 'v' ) &&
(arg1[2] == 'M' || arg1[2] == 'm' ) ) {
// fake xx
// /usr/local/software/jdk1.7.0_71/bin/jstack
StringBuffer cmdBuffer = new StringBuffer();
if ( JavaUtils.isLinux() )
cmdBuffer.append( JAVA_BIN_PATH );
// JVM JSTACK
if ( arg2.equalsIgnoreCase("JSTACK") ) {
cmdBuffer.append("jstack ").append( JavaUtils.process_pid() );
return encode( getOS_JVM_INFO( cmdBuffer.toString() ) );
// JVM JSTAT
} else if ( arg2.equalsIgnoreCase("JSTAT") ) {
cmdBuffer.append("jstat -gc ").append( JavaUtils.process_pid() );
return encode( getOS_JVM_INFO( cmdBuffer.toString() ) );
// JVM JMAP_HISTO
} else if ( arg2.equalsIgnoreCase("JMAP_HISTO") ) {
cmdBuffer.append("jmap -histo ").append( JavaUtils.process_pid() );
return encode( getOS_JVM_INFO( cmdBuffer.toString() ) );
// JVM JMAP_HEAP
} else if ( arg2.equalsIgnoreCase("JMAP_HEAP") ) {
cmdBuffer.append("jmap -heap ").append( JavaUtils.process_pid() );
return encode( getOS_JVM_INFO( cmdBuffer.toString() ) );
// JVM PS
} else if ( arg2.equalsIgnoreCase("PS") ) {
String cmd = "ps -mp " + JavaUtils.process_pid() + " -o THREAD,tid,time";
List<String> line = new ArrayList<String>();
try {
line.add( ShellUtils.execCommand( "bash", "-c", cmd ) );
} catch (IOException e) {
line.add( e.getMessage() );
}
return encode( line );
}
// USE use poolId
} else if ( (arg1[0] == 'U' || arg1[0] == 'u' ) &&
(arg1[1] == 'S' || arg1[1] == 's' ) &&
(arg1[2] == 'E' || arg1[2] == 'e' ) ) {
try {
int poolId = Integer.parseInt(arg2);
AbstractPool pool = RedisEngineCtx.INSTANCE().getPoolMap().get(poolId);
if (pool == null) {
return "-ERR No such pool. \r\n".getBytes();
} else {
int poolType = pool.getType();
frontCon.getUserCfg().setUsePool(poolId, poolType);
return "+OK\r\n".getBytes();
}
} catch (NumberFormatException e) {
return "-ERR PoolId is a number. \r\n".getBytes();
}
}
// SHOW
} else if ( arg1.length == 4 ) {
if ( (arg1[0] == 'S' || arg1[0] == 's' ) &&
(arg1[1] == 'H' || arg1[1] == 'h' ) &&
(arg1[2] == 'O' || arg1[2] == 'o' ) &&
(arg1[3] == 'W' || arg1[3] == 'w' ) ) {
// SHOW QPS
if ( arg2.equalsIgnoreCase("QPS") ) {
List<String> lines = new ArrayList<String>();
AccessStatInfoResult result = StatUtil.getTotalAccessStatInfo().get( StatUtil.STAT_KEY );
if ( result != null ) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("total=").append( result.totalCount ).append(", ");
sBuffer.append("slow=").append( result.slowCount ).append(", ");
sBuffer.append("max=").append( result.maxCount ).append(", ");
sBuffer.append("min=").append( result.minCount ).append(", ");
sBuffer.append("avg=").append( result.avgCount ).append(", ");
sBuffer.append("waitSlow=").append( result.waitSlowCount ).append(", ");
sBuffer.append("procTime=").append( result.procTime ).append(", ");
sBuffer.append("waitTime=").append( result.waitTime ).append(", ");
sBuffer.append("created=").append( result.created );
lines.add( sBuffer.toString() );
}
return encode( lines );
// SHOW CMD
} else if ( arg2.equalsIgnoreCase("CMD") ) {
List<Object> lines = new ArrayList<Object>();
long sum = 0;
Set<Entry<String, Command>> entrys = StatUtil.getCommandCountMap().entrySet();
for (Entry<String, Command> entry : entrys) {
Command parent = entry.getValue();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append( parent.cmd ).append(" ").append( parent.count.get() );
if ( parent.childs != null) {
List<String> list = new ArrayList<String>();
list.add( sBuffer.toString() );
for (Entry<String, Command> childEntry : parent.childs.entrySet()) {
Command child = childEntry.getValue();
StringBuffer sb = new StringBuffer();
sb.append(" ").append( child.cmd ).append(" ").append( child.count.get() );
list.add( sb.toString() );
}
lines.add( list );
} else {
lines.add( sBuffer.toString() );
}
sum += parent.count.get();
}
// sum
StringBuffer sBuffer = new StringBuffer();
sBuffer.append( "
lines.add( sBuffer.toString() );
return encodeObject( lines );
// SHOW USER_CMD
} else if (arg2.equalsIgnoreCase("USER_CMD")) {
List<String> lines = new ArrayList<String>();
StringBuffer titleSB = new StringBuffer();
titleSB.append("USER").append(" ");
titleSB.append("READ").append(" ");
titleSB.append("WRITE").append(" ");
titleSB.append("TOTAL");
lines.add(titleSB.toString());
Set<Entry<String, UserCommand>> entrys = StatUtil.getUserCommandCountMap().entrySet();
for (Entry<String, UserCommand> entry : entrys) {
UserCommand userCommand = entry.getValue();
StringBuffer bodySB = new StringBuffer();
bodySB.append(userCommand.user).append(" ");
bodySB.append(userCommand.readComandCount.get()).append(" ");
bodySB.append(userCommand.writeCommandCount.get()).append(" ");
bodySB.append( userCommand.readComandCount.get() + userCommand.writeCommandCount.get() );
lines.add( bodySB.toString() );
}
return encode(lines);
// SHOW USER_CMD_DETAIL USER
} else if ( arg2.equalsIgnoreCase("USER_CMD_DETAIL") && numArgs == 3 ) {
String user = new String( request.getArgs()[2] );
List<String> lines = new ArrayList<String>();
StringBuffer titleSB = new StringBuffer();
titleSB.append("CMD").append(" ");
titleSB.append("COUNT");
lines.add( titleSB.toString() );
int sum = 0;
ConcurrentHashMap<String, UserCommand> userCommandMap = StatUtil.getUserCommandCountMap();
UserCommand userCommand = userCommandMap.get(user);
if (userCommand != null) {
for (Entry<String, AtomicLong> entry : userCommand.commandCount.entrySet()) {
StringBuffer bodySB = new StringBuffer();
bodySB.append(entry.getKey()).append(" ");
bodySB.append(entry.getValue().get());
lines.add( bodySB.toString() );
}
}
StringBuffer end = new StringBuffer();
end.append( "
lines.add( end.toString() );
return encode( lines );
// SHOW IP_CMD
} else if (arg2.equalsIgnoreCase("IP_CMD")) {
List<String> lines = new ArrayList<String>();
StringBuffer titleSB = new StringBuffer();
titleSB.append("IP").append(" ");
titleSB.append("READ").append(" ");
titleSB.append("WRITE").append(" ");
titleSB.append("TOTAL");
lines.add(titleSB.toString());
Set<Entry<String, CmdAccessCollector.IPCommand>> entrys = StatUtil.getIPCommandCountMap().entrySet();
for (Entry<String, CmdAccessCollector.IPCommand> entry : entrys) {
CmdAccessCollector.IPCommand ipCommand = entry.getValue();
StringBuffer bodySB = new StringBuffer();
bodySB.append(ipCommand.ip).append(" ");
bodySB.append(ipCommand.readComandCount.get()).append(" ");
bodySB.append(ipCommand.writeCommandCount.get()).append(" ");
bodySB.append( ipCommand.readComandCount.get() + ipCommand.writeCommandCount.get() );
lines.add( bodySB.toString() );
}
return encode(lines);
// SHOW IP_CMD
} else if (arg2.equalsIgnoreCase("HOT_KEY")) {
List<String> lines = new ArrayList<String>();
StringBuffer titleSB = new StringBuffer();
titleSB.append("KEY").append(" ");
titleSB.append("COUNT").append(" ");
lines.add(titleSB.toString());
Set<Entry<String, Integer>> entrys = StatUtil.getHotKeyCountMap().entrySet();
for (Entry<String, Integer> entry : entrys) {
StringBuffer bodySB = new StringBuffer();
bodySB.append(entry.getKey()).append(" ");
bodySB.append(entry.getValue()).append(" ");
lines.add( bodySB.toString() );
}
return encode(lines);
// SHOW JEDIS
} else if ( arg2.equalsIgnoreCase("JEDIS") ) {
List<String> lines = new ArrayList<String>();
lines.add( "connect=" + JedisConnection.getConnectSize() );
lines.add( "disconnect=" + JedisConnection.getDisConnectSize() );
return encode( lines );
// SHOW VER
} else if ( arg2.equalsIgnoreCase("VER") ) {
List<String> lines = new ArrayList<String>();
lines.add( Versions.SERVER_VERSION );
return encode( lines );
// SHOW CPU
} else if ( arg2.equalsIgnoreCase("CPU") ) {
List<String> lines = new ArrayList<String>();
if ( JavaUtils.isLinux() ) {
StringBuffer cmdBuffer = new StringBuffer();
cmdBuffer.append( "ps -p ").append( JavaUtils.process_pid() ).append(" -o %cpu,%mem" );
String response;
try {
response = ShellUtils.execCommand( "bash", "-c", cmdBuffer.toString() );
lines.add( response );
} catch (IOException e) {
LOGGER.error("get cpu err:", e );
lines.add( "%CPU %MEM 0 0 " );
}
} else {
// %CPU %MEM 231 13.3
lines.add( "%CPU %MEM 0 0 " );
}
return encode( lines );
// SHOW MEM
} else if ( arg2.equalsIgnoreCase("MEM") ) {
List<String> lines = new ArrayList<String>();
lines.add( "mem:"+ JavaUtils.bytesToString2( Math.round( JavaUtils.getMemUsage() ) ) );
return encode( lines );
// SHOW CONN
} else if ( arg2.equalsIgnoreCase("CONN") ) {
int frontSize = 0;
int backendSize = 0;
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if ( c instanceof RedisFrontConnection ) {
frontSize++;
} else {
backendSize++;
}
}
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("+");
sBuffer.append("Connection:");
sBuffer.append(" front=").append( frontSize ).append(", ");
sBuffer.append(" backend=").append( backendSize ).append("\r\n");
return sBuffer.toString().getBytes();
// SHOW USER_CONN
} else if ( arg2.equalsIgnoreCase("USER_CONN") ) {
Map<String, Integer> userMap = new HashMap<String, Integer>();
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if (c instanceof RedisFrontConnection) {
userMap.put(((RedisFrontConnection) c).getPassword(),
1 + (userMap.get(((RedisFrontConnection) c).getPassword()) == null ? 0
: userMap.get(((RedisFrontConnection) c).getPassword())));
}
}
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("+");
sBuffer.append("user front");
Iterator<Entry<String, Integer>> users = userMap.entrySet().iterator();
while (users.hasNext()) {
sBuffer.append("\n");
Entry<String, Integer> en = users.next();
sBuffer.append(en.getKey());
sBuffer.append(" ");
sBuffer.append(en.getValue());
}
sBuffer.append("\r\n");
return sBuffer.toString().getBytes();
} else if ( arg2.equalsIgnoreCase("BY_CONN") ) {
BypassThreadExecutor threadPoolExecutor=BypassService.INSTANCE().getThreadPoolExecutor();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("+");
sBuffer.append("active=").append( threadPoolExecutor.getActiveCount()).append(", ");
sBuffer.append("poolSize=").append( threadPoolExecutor.getPoolSize()).append(", ");
sBuffer.append("corePoolSize=").append( threadPoolExecutor.getCorePoolSize()).append(", ");
sBuffer.append("maxSubmittedTaskCount=").append( threadPoolExecutor.getMaxSubmittedTaskCount()).append(", ");
sBuffer.append("submittedTasksCount=").append( threadPoolExecutor.getSubmittedTasksCount()).append(", ");
sBuffer.append("completedTaskCount=").append( threadPoolExecutor.getCompletedTaskCount()).append(", ");
sBuffer.append("\r\n");
return sBuffer.toString().getBytes();
// SHOW USER
} else if ( arg2.equalsIgnoreCase("USER") ) {
List<String> lines = new ArrayList<String>();
ConcurrentHashMap<String, AccessStatInfoResult> results = StatUtil.getTotalAccessStatInfo();
for (Map.Entry<String, AccessStatInfoResult> entry : results.entrySet()) {
AccessStatInfoResult result = entry.getValue();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("key=").append( result.key ).append(", ");
sBuffer.append("total=").append( result.totalCount ).append(", ");
sBuffer.append("slow=").append( result.slowCount ).append(", ");
sBuffer.append("max=").append( result.maxCount ).append(", ");
sBuffer.append("min=").append( result.minCount ).append(", ");
sBuffer.append("avg=").append( result.avgCount ).append(", ");
sBuffer.append("procTime=").append( result.procTime ).append(", ");
sBuffer.append("netIn (");
sBuffer.append("max=").append( result.netInBytes[1] ).append(", ");
sBuffer.append("min=").append( result.netInBytes[2] ).append(", ");
sBuffer.append("avg=").append( result.netInBytes[3] ).append(") ").append(", ");
sBuffer.append("netOut (");
sBuffer.append("max=").append( result.netOutBytes[1] ).append(", ");
sBuffer.append("min=").append( result.netOutBytes[2] ).append(", ");
sBuffer.append("avg=").append( result.netOutBytes[3] ).append(") ").append(", ");
sBuffer.append("created=").append( result.created );
lines.add( sBuffer.toString() );
}
return encode( lines );
// SHOW FRONT
} else if ( arg2.equalsIgnoreCase("FRONT") ) {
List<String> lines = new ArrayList<String>();
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if ( c instanceof RedisFrontConnection ) {
lines.add( c.toString() );
}
}
return encode( lines );
// SHOW BUFFER
} else if ( arg2.equalsIgnoreCase("BUFFER") ) {
BufferPool bufferPool = NetSystem.getInstance().getBufferPool();
long usedBufferSize = bufferPool.getUsedBufferSize().get();
long maxBufferSize = bufferPool.getMaxBufferSize();
long minBufferSize = bufferPool.getMinBufferSize();
long sharedOptsCount = bufferPool.getSharedOptsCount();
int capacity = 0;
if ( bufferPool instanceof BucketBufferPool ) {
BucketBufferPool p = (BucketBufferPool) bufferPool;
AbstractBucket[] buckets = p.buckets();
for (AbstractBucket b : buckets) {
capacity += b.getCount();
}
int bucketLen = buckets.length;
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("+");
sBuffer.append("Buffer:");
sBuffer.append(" capacity=").append( capacity ).append(",");
sBuffer.append(" minBufferSize=").append( minBufferSize ).append(",");
sBuffer.append(" maxBufferSize=").append( maxBufferSize ).append(",");
sBuffer.append(" usedBufferSize=").append( usedBufferSize ).append(",");
sBuffer.append(" buckets=").append( bucketLen ).append(",");
sBuffer.append(" shared=").append( sharedOptsCount ).append("\r\n");
return sBuffer.toString().getBytes();
} else if ( bufferPool instanceof PageBufferPool ) {
List<String> lines = new ArrayList<String>();
ConcurrentHashMap<Long, Long> bufferpoolUsageMap = bufferPool.getNetDirectMemoryUsage();
// packetbuffer pool DirectMemory
long usedforNetwork = 0;
for (Map.Entry<Long, Long> entry : bufferpoolUsageMap.entrySet()) {
long value = entry.getValue() ;
lines.add("threadId=" + entry.getKey() + ", value=" + ( value > 0 ? JavaUtils.bytesToString2(value) : "0") );
usedforNetwork = usedforNetwork + value;
}
lines.add( "minBufferSize=" + JavaUtils.bytesToString2( minBufferSize ) );
lines.add( "maxBufferSize=" + JavaUtils.bytesToString2( maxBufferSize ) );
lines.add( "usedBufferSize=" + JavaUtils.bytesToString2( usedforNetwork ) );
return encode( lines );
}
// SHOW BUCKET
} else if ( arg2.equalsIgnoreCase("BUCKET") ) {
List<String> lines = new ArrayList<String>();
BufferPool bufferPool = NetSystem.getInstance().getBufferPool();
if ( bufferPool instanceof BucketBufferPool ) {
BucketBufferPool p = (BucketBufferPool) bufferPool;
AbstractBucket[] buckets = p.buckets();
for(AbstractBucket b: buckets) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append(" chunkSize=").append( b.getChunkSize() ).append(",");
sBuffer.append(" queueSize=").append( b.getQueueSize() ).append( ", " );
sBuffer.append(" count=").append( b.getCount() ).append( ", " );
sBuffer.append(" useCount=").append( b.getUsedCount() ).append( ", " );
sBuffer.append(" shared=").append( b.getShared() );
lines.add( sBuffer.toString() );
}
}
return encode( lines );
// SHOW BIGKEY
} else if ( arg2.equalsIgnoreCase("BIGKEY") ) {
List<String> lines = new ArrayList<String>();
for(BigKey bigkey: StatUtil.getBigKeys()) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append( bigkey.lastCmd ).append(" ");
sBuffer.append( bigkey.key ).append( " " );
sBuffer.append( bigkey.size ).append( " " );
sBuffer.append( bigkey.count.get() );
lines.add( sBuffer.toString() );
}
return encode( lines );
// SHOW BIGKEY_COUNT
} else if ( arg2.equalsIgnoreCase("BIGKEY_COUNT") ) {
List<String> lines = new ArrayList<String>();
BigKeyCollector bkc = StatUtil.getBigKeyCollector();
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("total=").append( bkc.getBigKeyCount() ).append(", ");
sBuffer.append("bypass=").append( bkc.getBypassBigKeyCount() );
lines.add(sBuffer.toString());
return encode( lines );
// SHOW BACKEND
} else if ( arg2.equalsIgnoreCase("BACKEND") ) {
List<String> lines = new ArrayList<String>();
Map<String, AtomicInteger> poolConnections = new HashMap<String, AtomicInteger>();
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if ( c instanceof RedisBackendConnection ) {
// redis
String poolName = ((RedisBackendConnection) c).getPhysicalNode().getPoolName();
AtomicInteger poolConnCount = poolConnections.get(poolName);
if ( poolConnCount == null ) {
poolConnections.put(poolName, new AtomicInteger(1));
} else {
poolConnCount.incrementAndGet();
}
lines.add( c.toString() );
} else if ( c instanceof KafkaBackendConnection ) {
// redis
String poolName = ((KafkaBackendConnection) c).getPhysicalNode().getPoolName();
AtomicInteger poolConnCount = poolConnections.get(poolName);
if ( poolConnCount == null ) {
poolConnections.put(poolName, new AtomicInteger(1));
} else {
poolConnCount.incrementAndGet();
}
lines.add( c.toString() );
}
}
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, AtomicInteger> entry : poolConnections.entrySet()) {
sb.append(entry.getKey()).append(":").append(entry.getValue().get()).append(". ");
}
lines.add(sb.toString());
return encode( lines );
// SHOW POOL_NET_IO POOLNAME
} else if ( arg2.equalsIgnoreCase("POOL_NET_IO") && numArgs == 3 ) {
List<String> lines = new ArrayList<String>();
long minStartupTime = -1;
long totalNetInBytes = 0;
long totalNetOutBytes = 0;
String poolName = new String( request.getArgs()[2] );
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if ( c instanceof RedisBackendConnection ) {
// redis
if (((RedisBackendConnection) c).getPhysicalNode().getPoolName().equals(poolName)) {
StringBuffer sb = new StringBuffer();
sb.append("ID=").append(c.getId()).append(". ");
sb.append("StartupTime=").append(c.getStartupTime()).append(". ");
sb.append("NetInBytes=").append(c.getNetInBytes()).append(". ");
sb.append("NetOutBytes=").append(c.getNetOutBytes()).append(". ");
lines.add( sb.toString() );
minStartupTime = minStartupTime < 0 ? c.getStartupTime() : Math.min(minStartupTime, c.getStartupTime());
totalNetInBytes += c.getNetInBytes();
totalNetOutBytes += c.getNetOutBytes();
}
}
}
StringBuffer end = new StringBuffer();
end.append("MinStartupTime=").append(minStartupTime).append(". ");
end.append("TotalNetInBytes=").append(totalNetInBytes).append(". ");
end.append("TotalNetOutBytes=").append(totalNetOutBytes).append(". ");
lines.add(end.toString());
return encode( lines );
// SHOW NETBYTES/NET_IO
} else if ( arg2.equalsIgnoreCase("NETBYTES") || arg2.equalsIgnoreCase("NET_IO")) {
List<String> lines = new ArrayList<String>();
AccessStatInfoResult result = StatUtil.getTotalAccessStatInfo().get( StatUtil.STAT_KEY );
if ( result != null ) {
StringBuffer line0 = new StringBuffer();
line0.append( "NetIn/NetOut" ).append(", ");
line0.append( "total" ).append(", ");
line0.append( "max" ).append(", ");
line0.append( "min" ).append(", ");
line0.append( "avg" );
StringBuffer line1 = new StringBuffer();
line1.append( "NetIn" ).append(", ");
line1.append( result.netInBytes[0] ).append(", ");
line1.append( result.netInBytes[1] ).append(", ");
line1.append( result.netInBytes[2] ).append(", ");
line1.append( result.netInBytes[3] );
StringBuffer line2 = new StringBuffer();
line2.append( "NetOut" ).append(", ");
line2.append( result.netOutBytes[0] ).append(", ");
line2.append( result.netOutBytes[1] ).append(", ");
line2.append( result.netOutBytes[2] ).append(", ");
line2.append( result.netOutBytes[3] );
StringBuffer line3 = new StringBuffer();
line3.append( result.created );
lines.add( line0.toString() );
lines.add( line1.toString() );
lines.add( line2.toString() );
lines.add( line3.toString() );
}
return encode( lines );
// SHOW USER_NET_IO
} else if ( arg2.equalsIgnoreCase("USER_NET_IO") ) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
titleLine.append("User").append(", ");
titleLine.append("NetIn/NetOut").append(", ");
titleLine.append("total").append(", ");
titleLine.append("max").append(", ");
titleLine.append("min").append(", ");
titleLine.append("avg");
lines.add(titleLine.toString());
for (Map.Entry<String, AccessStatInfoResult> entry : StatUtil.getTotalAccessStatInfo().entrySet()) {
if (!StatUtil.STAT_KEY.equals(entry.getKey())) {
AccessStatInfoResult result = entry.getValue();
StringBuffer line1 = new StringBuffer();
line1.append(result.key).append(", ");
line1.append("NetIn").append(", ");
line1.append(result.netInBytes[0]).append(", ");
line1.append(result.netInBytes[1]).append(", ");
line1.append(result.netInBytes[2]).append(", ");
line1.append(result.netInBytes[3]);
StringBuffer line2 = new StringBuffer();
line2.append(result.key).append(", ");
line2.append("NetOut").append(", ");
line2.append(result.netOutBytes[0]).append(", ");
line2.append(result.netOutBytes[1]).append(", ");
line2.append(result.netOutBytes[2]).append(", ");
line2.append(result.netOutBytes[3]);
StringBuffer line3 = new StringBuffer();
line3.append(result.created);
lines.add(line1.toString());
lines.add(line2.toString());
lines.add(line3.toString());
}
}
return encode(lines);
//SHOW USER_DAY_NET_IO
} else if ( arg2.equalsIgnoreCase("USER_DAY_NET_IO") ) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
titleLine.append("User").append(" ");
titleLine.append("NetIn").append(" ");
titleLine.append("NetOut");
lines.add(titleLine.toString());
long totalNetIn = 0;
long totalNetOut = 0;
for (Map.Entry<String, UserFlow> entry : StatUtil.getUserFlowMap().entrySet()) {
if (!StatUtil.STAT_KEY.equals(entry.getKey())) {
StringBuffer sb = new StringBuffer();
UserFlow userNetIo = entry.getValue();
sb.append(userNetIo.password).append(" ");
sb.append( JavaUtils.bytesToString2( userNetIo.netIn.get() ) ).append(" ");
sb.append( JavaUtils.bytesToString2( userNetIo.netOut.get() ) );
totalNetIn = totalNetIn + userNetIo.netIn.get();
totalNetOut = totalNetOut + userNetIo.netOut.get();
lines.add(sb.toString());
}
}
StringBuffer total = new StringBuffer();
total.append("total").append(" ");
total.append( JavaUtils.bytesToString2(totalNetIn) ).append(" ");
total.append( JavaUtils.bytesToString2(totalNetOut) );
lines.add(total.toString());
return encode(lines);
// SHOW LOG_ERROR
} else if ( arg2.equalsIgnoreCase("LOG_ERROR") ) {
List<String> lines = showLog(request, "error.log");
return encode2( lines );
// SHOW LOG_WARN
} else if ( arg2.equalsIgnoreCase("LOG_WARN") ) {
List<String> lines = showLog(request, "warn.log");
return encode2( lines );
// SHOW LOG_INFO
} else if ( arg2.equalsIgnoreCase("LOG_INFO") ) {
List<String> lines = showLog(request, "info.log");
return encode2( lines );
// SHOW LOG_DEBUG
} else if ( arg2.equalsIgnoreCase("LOG_DEBUG") ) {
List<String> lines = showLog(request, "debug.log");
return encode2( lines );
// SHOW DF ( df -h )
} else if ( arg2.equalsIgnoreCase("DF") ) {
List<String> ret = new ArrayList<String>();
try {
// df -h /dev/shm
String resp = ShellUtils.execCommand( "bash", "-c", "df -h" );
StringBuilder sb = new StringBuilder();
sb.append(resp);
sb.append(" \n");
String[] lines = sb.toString().split("\\n");
ret.add("
for (int i=1; i<lines.length; i++) {
if (lines[i].equals(""))
continue;
ret.add(lines[i]);
}
} catch (IOException e) {
LOGGER.error("show vm err:", e );
ret.add( "show df err, df -h " );
}
return encode2(ret);
// SHOW VM
} else if ( arg2.equalsIgnoreCase("VM") ) {
List<String> ret = new ArrayList<String>();
try {
String cmd1 = ShellUtils.osType == ShellUtils.OSType.OS_TYPE_MAC ? "iostat" : "iostat -x";
String cmd2 = ShellUtils.osType == ShellUtils.OSType.OS_TYPE_MAC ? "vm_stat": "vmstat";
String iostatOut = ShellUtils.execCommand( "bash", "-c", cmd1 );
String vmstatOut = ShellUtils.execCommand( "bash", "-c", cmd2 );
StringBuilder sb = new StringBuilder();
sb.append(iostatOut);
sb.append(" \n");
sb.append("
sb.append(vmstatOut);
String[] lines = sb.toString().split("\\n");
ret.add("
for (int i=1; i<lines.length; i++) {
if (lines[i].equals(""))
continue;
ret.add(lines[i]);
}
} catch (IOException e) {
LOGGER.error("get vm err:", e );
ret.add( "SHOW VM ERROR " );
}
return encode2(ret);
// SHOW POOL
} else if ( arg2.equalsIgnoreCase("POOL") ) {
List<Object> list = new ArrayList<Object>();
Map<Integer, AbstractPool> pools = RedisEngineCtx.INSTANCE().getPoolMap();
StringBuffer titleLine = new StringBuffer();
titleLine.append(" PoolId").append(" ");
titleLine.append("PoolName").append(" ");
titleLine.append("PoolType").append(" ");
titleLine.append("Address").append(" ");
titleLine.append("MinCom").append(" ");
titleLine.append("MaxCon").append(" ");
titleLine.append("IdlCon").append(" ");
titleLine.append("ActiveCon").append(" ");
titleLine.append("NumOfGet").append(" ");
titleLine.append("NumOfCreate").append(" ");
titleLine.append("NumOfRefused").append(" ");
titleLine.append("ClusterNodeState");
list.add(titleLine.toString());
for(AbstractPool pool : pools.values() ) {
if ( pool instanceof RedisStandalonePool ) {
StringBuffer sb = new StringBuffer();
RedisStandalonePool redisStandalonePool = (RedisStandalonePool) pool;
PhysicalNode physicalNode = redisStandalonePool.getPhysicalNode();
if (physicalNode == null)
continue;
sb.append(" ");
sb.append(redisStandalonePool.getId()).append(" ");
sb.append(physicalNode.getPoolName()).append(" ");
sb.append("Standalone").append(" ");
sb.append(physicalNode.getName()).append(" ");
sb.append(physicalNode.getMinCon()).append(" ");
sb.append(physicalNode.getMaxCon()).append(" ");
sb.append(physicalNode.getIdleCount()).append(" ");
sb.append(physicalNode.getActiveCount()).append(" ");
sb.append(physicalNode.getNumOfGet()).append(" ");
sb.append(physicalNode.getNumOfCreate()).append(" ");
sb.append(physicalNode.getNumOfRefused());
list.add(sb.toString());
} else if ( pool instanceof RedisClusterPool ) {
RedisClusterPool redisClusterPool = (RedisClusterPool) pool;
Map<String, ClusterNode> masters = redisClusterPool.getMasters();
List<String> clusterInfo = new ArrayList<String>();
for (ClusterNode clusterNode : masters.values()) {
PhysicalNode physicalNode = clusterNode.getPhysicalNode();
StringBuffer sb = new StringBuffer();
sb.append(redisClusterPool.getId()).append(" ");
sb.append(physicalNode.getPoolName()).append(" ");
sb.append("cluster").append(" ");
sb.append(physicalNode.getName()).append(" ");
sb.append(physicalNode.getMinCon()).append(" ");
sb.append(physicalNode.getMaxCon()).append(" ");
sb.append(physicalNode.getIdleCount()).append(" ");
sb.append(physicalNode.getActiveCount()).append(" ");
sb.append(physicalNode.getNumOfGet()).append(" ");
sb.append(physicalNode.getNumOfCreate()).append(" ");
sb.append(physicalNode.getNumOfRefused()).append(" ");
sb.append(!clusterNode.isFail());
clusterInfo.add(sb.toString());
sb.append(clusterNode.getConnectInfo());
}
list.add(clusterInfo);
} else if (pool instanceof KafkaPool) {
KafkaPool kafkaPool = (KafkaPool) pool;
Map<Integer, PhysicalNode> physicalNodes = kafkaPool.getPhysicalNodes();
for (PhysicalNode physicalNode : physicalNodes.values()) {
StringBuffer sb = new StringBuffer();
sb.append(" ");
sb.append(kafkaPool.getId()).append(" ");
sb.append(physicalNode.getPoolName()).append(" ");
sb.append("kafka").append(" ");
sb.append(physicalNode.getName()).append(" ");
sb.append(physicalNode.getMinCon()).append(" ");
sb.append(physicalNode.getMaxCon()).append(" ");
sb.append(physicalNode.getIdleCount()).append(" ");
sb.append(physicalNode.getActiveCount()).append(" ");
sb.append(physicalNode.getNumOfGet()).append(" ");
sb.append(physicalNode.getNumOfCreate()).append(" ");
sb.append(physicalNode.getNumOfRefused());
list.add(sb.toString());
}
}
}
return encodeObject(list);
// SHOW COST
} else if (arg2.equalsIgnoreCase("COST")) {
Collection<Entry<String, AtomicLong>> entrys = StatUtil.getCommandProcTimeMap().entrySet();
List<String> lines = new ArrayList<String>();
Long total = new Long(0);
for (Entry<String, AtomicLong> entry : entrys) {
total = total + entry.getValue().get();
}
for (Entry<String, AtomicLong> entry : entrys) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append(entry.getKey()).append(": ").append(entry.getValue().get());
sBuffer.append(" ").append( String.format("%.2f", ((entry.getValue().get() / total.doubleValue()) * 100)));
sBuffer.append("%");
lines.add(sBuffer.toString());
}
return encode(lines);
// SHOW WAIT_COST
} else if (arg2.equalsIgnoreCase("WAIT_COST")) {
Collection<Entry<String, AtomicLong>> entrys = StatUtil.getCommandWaitTimeMap().entrySet();
List<String> lines = new ArrayList<String>();
for (Entry<String, AtomicLong> entry : entrys) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append(entry.getKey()).append(": ").append(entry.getValue().get());
lines.add(sBuffer.toString());
}
return encode(lines);
// SHOW BIGLENGTH
} else if(arg2.equalsIgnoreCase("BIGLENGTH")) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
titleLine.append("cmd").append(", ");
titleLine.append("key").append(", ");
titleLine.append("length").append(", ");
titleLine.append("count_1k").append(", ");
titleLine.append("count_10k");
lines.add(titleLine.toString());
for (BigLength bigLength : StatUtil.getBigLengthMap().values()) {
StringBuffer line1 = new StringBuffer();
line1.append(bigLength.cmd).append(", ");
line1.append(bigLength.key).append(", ");
line1.append(bigLength.length.get()).append(", ");
line1.append(bigLength.count_1k.get()).append(", ");
line1.append(bigLength.count_10k.get());
lines.add(line1.toString());
}
return encode(lines);
// SHOW BIGLENGTH
} else if (arg2.equalsIgnoreCase("SLOWKEY")) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
titleLine.append("cmd").append(", ");
titleLine.append("key").append(", ");
titleLine.append("count");
lines.add(titleLine.toString());
for (SlowKey slowKey : StatUtil.getSlowKey()) {
StringBuffer line1 = new StringBuffer();
line1.append(slowKey.cmd).append(", ");
line1.append(slowKey.key).append(", ");
line1.append(slowKey.count);
lines.add(line1.toString());
}
return encode(lines);
// SHOW TOPIC
} else if (arg2.equalsIgnoreCase("TOPIC") && (numArgs == 3 || numArgs == 2) ) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
if (numArgs == 2) {
titleLine.append("TOPIC").append(", ");
titleLine.append("POOLID").append(", ");
titleLine.append("PARTITION").append(", ");
titleLine.append("REPLICATION").append(", ");
titleLine.append("PRODUCER").append(", ");
titleLine.append("CONSUMER");
} else {
titleLine.append("TOPIC").append(", ");
titleLine.append("HOST").append(", ");
titleLine.append("PARTITION").append(", ");
titleLine.append("PRODUCER_START").append(", ");
titleLine.append("PRODUCER_END").append(", ");
titleLine.append("CONSUMER");
}
lines.add(titleLine.toString());
final Map<Integer, PoolCfg> poolCfgMap = RedisEngineCtx.INSTANCE().getPoolCfgMap();
for (Entry<Integer, PoolCfg> poolEntry : poolCfgMap.entrySet()) {
PoolCfg poolCfg = poolEntry.getValue();
if (poolCfg instanceof KafkaPoolCfg) {
Map<String, TopicCfg> kafkaMap = ((KafkaPoolCfg) poolCfg).getTopicCfgMap();
// topic
if (numArgs == 2) {
for (Entry<String, TopicCfg> kafkaEntry : kafkaMap.entrySet()) {
TopicCfg kafkaCfg = kafkaEntry.getValue();
StringBuffer line = new StringBuffer();
line.append(kafkaCfg.getName()).append(", ");
line.append(kafkaCfg.getPoolId()).append(", ");
line.append(kafkaCfg.getPartitions()).append(", ");
line.append(kafkaCfg.getReplicationFactor()).append(", ");
line.append(kafkaCfg.getProducers()).append(", ");
line.append(kafkaCfg.getConsumers());
lines.add(line.toString());
}
// topic
} else {
String topic = new String( request.getArgs()[2] );
TopicCfg kafkaCfg = kafkaMap.get(topic);
if (kafkaCfg != null) {
for (BrokerPartition partition : kafkaCfg.getRunningInfo().getPartitions().values()) {
int pt = partition.getPartition();
StringBuffer line = new StringBuffer();
line.append(kafkaCfg.getName()).append(", ");
line.append(partition.getLeader().getHost()).append(partition.getLeader().getPort()).append(", ");
line.append(pt).append(", ");
line.append(partition.getLogStartOffset()).append(", ");
line.append(partition.getProducerOffset()).append(", ");
for (ConsumerOffset consumerOffset : partition.getConsumerOffsets().values()) {
line.append(consumerOffset.getConsumer() );
line.append(":");
line.append(consumerOffset.getCurrentOffset() );
line.append(", ");
}
lines.add(line.toString());
}
}
}
}
}
return encode(lines);
// SHOW NetFlowCtrl
} else if (arg2.equalsIgnoreCase("NETFLOWCTRL") && numArgs == 2 ) {
List<String> lines = new ArrayList<String>();
StringBuffer titleLine = new StringBuffer();
titleLine.append("USER").append(", ");
titleLine.append("PRE_SECOND_MAX_SIZE").append(", ");
titleLine.append("REQUEST_MAX_SIZE").append(", ");
titleLine.append("HISTOGRAM");
lines.add(titleLine.toString());
NetFlowGuard nfg = RedisEngineCtx.INSTANCE().getNetflowGuard();
Map<String, Guard> map = nfg.getGuardMap();
for (Entry<String, Guard> entry : map.entrySet()) {
Guard guard = entry.getValue();
StringBuffer line = new StringBuffer();
line.append(entry.getKey()).append(", ");
line.append(guard.getPerSecondMaxSize()).append(", ");
line.append(guard.getRequestMaxSize()).append(", ");
line.append(guard.getHistogram());
lines.add(line.toString());
}
return encode(lines);
}
}
// PRINT
} else if ( arg1.length == 5 ) {
// if ( (arg1[0] == 'P' || arg1[0] == 'p' ) &&
// (arg1[1] == 'R' || arg1[1] == 'r' ) &&
// (arg1[2] == 'I' || arg1[2] == 'i' ) &&
// (arg1[3] == 'N' || arg1[3] == 'n' ) &&
// (arg1[4] == 'T' || arg1[4] == 't' ) ) {
// // print keys
// if (arg2.equalsIgnoreCase("KEYS") && request.getNumArgs() >= 4) {
// String startTime = new String(request.getArgs()[2]);
// String endTime = new String(request.getArgs()[3]);
// String size = null;
// if (request.getNumArgs() == 5) {
// size = new String(request.getArgs()[4]);
// boolean result=StatUtil.setAllKeyCollector(startTime, endTime, size);
// return ("+" + String.valueOf(result) + "\r\n").getBytes();
// RELOAD
} else if ( arg1.length == 6 ) {
if ( (arg1[0] == 'R' || arg1[0] == 'r' ) &&
(arg1[1] == 'E' || arg1[1] == 'e' ) &&
(arg1[2] == 'L' || arg1[2] == 'l' ) &&
(arg1[3] == 'O' || arg1[3] == 'o' ) &&
(arg1[4] == 'A' || arg1[4] == 'a' ) &&
(arg1[5] == 'D' || arg1[5] == 'd' ) ) {
// reload all
if ( arg2.equalsIgnoreCase("ALL") ) {
byte[] buff = RedisEngineCtx.INSTANCE().reloadAll();
return buff;
// reload user
} else if ( arg2.equalsIgnoreCase("USER") ) {
byte[] buff = RedisEngineCtx.INSTANCE().reloadUser();
return buff;
// reload netflow
} else if ( arg2.equalsIgnoreCase("NETFLOW") ) {
byte[] buff = RedisEngineCtx.INSTANCE().reloadNetflow();
return buff;
// reload front
} else if ( arg2.equalsIgnoreCase("FRONT") ) {
ConcurrentMap<Long, ClosableConnection> allConnections = NetSystem.getInstance().getAllConnectios();
Iterator<Entry<Long, ClosableConnection>> it = allConnections.entrySet().iterator();
while (it.hasNext()) {
ClosableConnection c = it.next().getValue();
if ( c instanceof RedisFrontConnection ) {
LOGGER.info("close: {}", c);
c.close("manage close");
}
}
return "+OK\r\n".getBytes();
// reload path
} else if ( arg2.equalsIgnoreCase("PATH") ) {
JAVA_BIN_PATH = new String( request.getArgs()[2] );
return "+OK\r\n".getBytes();
// reload kafka
} else if ( arg2.equalsIgnoreCase("KAFKA") ) {
try {
Map<Integer, PoolCfg> poolCfgMap = RedisEngineCtx.INSTANCE().getPoolCfgMap();
for (PoolCfg poolCfg : poolCfgMap.values()) {
if ( poolCfg instanceof KafkaPoolCfg )
poolCfg.reloadExtraCfg();
}
} catch (Exception e) {
LOGGER.error("reload kafka err:", e);
StringBuffer sb = new StringBuffer();
sb.append("-ERR ").append(e.getMessage()).append("\r\n");
return sb.toString().getBytes();
}
return "+OK\r\n".getBytes();
// reload bigkey
} else if ( arg2.equalsIgnoreCase("BIGKEY") ) {
byte[] buff = BypassService.INSTANCE().reload();
return buff;
}
}
// Repair Offset
if ( (arg1[0] == 'R' || arg1[0] == 'r' ) &&
(arg1[1] == 'E' || arg1[1] == 'e' ) &&
(arg1[2] == 'P' || arg1[2] == 'p' ) &&
(arg1[3] == 'A' || arg1[3] == 'a' ) &&
(arg1[4] == 'I' || arg1[4] == 'i' ) &&
(arg1[5] == 'R' || arg1[5] == 'r' )) {
// REPAIR OFFSET password topicName offset
if ( arg2.equalsIgnoreCase("OFFSET") ) {
String password = new String( request.getArgs()[2] );
String topicName = new String( request.getArgs()[3] );
long offset = Long.parseLong( new String( request.getArgs()[4] ) );
UserCfg userCfg = RedisEngineCtx.INSTANCE().getUserMap().get(password);
if ( userCfg != null ) {
int poolId = userCfg.getPoolId() ;
PoolCfg poolCfg = (PoolCfg) RedisEngineCtx.INSTANCE().getPoolCfgMap().get( poolId );
if ( poolCfg != null && poolCfg instanceof KafkaPoolCfg ) {
TopicCfg topicCfg = ((KafkaPoolCfg)poolCfg).getTopicCfgMap().get(topicName);
if ( topicCfg != null ) {
for(int partition=0; partition < topicCfg.getPartitions(); partition++) {
boolean isRepair = BrokerOffsetService.INSTANCE().repairOffset(password, topicCfg, partition, offset);
if ( !isRepair ) {
return ("-ERR repair failed, partition=" + partition + " exec err \r\n").getBytes();
}
}
} else {
return ("-ERR repair failed, topic="+ topicName + " no configuration \r\n").getBytes();
}
return "+OK\r\n".getBytes();
} else {
return ("-ERR repair failed, pool="+ poolId + " no configurationl or not the kafka pool type. \r\n").getBytes();
}
} else {
return ("-ERR repair failed, password=" + password + " no configuration \r\n").getBytes();
}
}
}
// cluster
} else if (arg1.length == 7) {
if ( (arg1[0] == 'C' || arg1[0] == 'c' ) &&
(arg1[1] == 'L' || arg1[1] == 'l' ) &&
(arg1[2] == 'U' || arg1[2] == 'u' ) &&
(arg1[3] == 'S' || arg1[3] == 's' ) &&
(arg1[4] == 'T' || arg1[4] == 't' ) &&
(arg1[5] == 'E' || arg1[5] == 'e' ) &&
(arg1[6] == 'R' || arg1[6] == 'r' ) ) {
AbstractPool pool = RedisEngineCtx.INSTANCE().getPoolMap().get( frontCon.getUserCfg().getPoolId() );
if ( pool.getType() != 1 ) {
return "-ERR Not cluster pool. \r\n".getBytes();
}
PhysicalNode pysicalNode = ((RedisClusterPool) pool).getPhysicalNodeBySlot(0);
if ( pysicalNode == null ) {
return "-ERR node unavailable. \r\n".getBytes();
}
try {
RedisBackendConnection backendCon = (RedisBackendConnection)pysicalNode.getConnection(new DirectTransTofrontCallBack(), frontCon);
if (backendCon == null) {
frontCon.writeErrMessage("not idle backend connection, pls wait !!!");
} else {
backendCon.write( request.encode() );
}
return null; // null, not write
} catch (IOException e) {
LOGGER.error("", e);
}
}
}
return "-ERR Not supported. \r\n".getBytes();
}
public static synchronized byte[] encode2(List<String> lines) {
StringBuffer sb = new StringBuffer();
if (lines == null || lines.size() <= 0) {
sb.append("-ERR no data.\r\n");
} else {
sb.append("+");
for (String line : lines) {
sb.append(line);
sb.append("\n");
}
sb.append("\r\n");
}
return sb.toString().getBytes();
}
public static synchronized byte[] encode(List<String> lines) throws BufferOverflowException {
int bufferSize = 0;
for(String line: lines) {
bufferSize += line.getBytes().length + 12;
}
ByteBuffer buffer = ByteBuffer.allocate( bufferSize );
if ( lines.size() == 1 ) {
buffer.put( (byte)'+' );
buffer.put( lines.get(0).getBytes() );
buffer.put( "\r\n".getBytes() );
} else if ( lines.size() > 1 ) {
buffer.put( (byte)'*' );
buffer.put( ProtoUtils.convertIntToByteArray( lines.size() ) );
buffer.put( "\r\n".getBytes() );
for(int i = 0; i < lines.size(); i++) {
byte[] lineBytes = lines.get(i).getBytes();
buffer.put( (byte)'$' );
buffer.put( ProtoUtils.convertIntToByteArray( lineBytes.length ) );
buffer.put( "\r\n".getBytes() );
buffer.put( lineBytes );
buffer.put( "\r\n".getBytes() );
}
} else {
return "-ERR no data.\r\n".getBytes();
}
buffer.flip();
byte[] data = new byte[ buffer.remaining() ];
buffer.get(data);
return data;
}
@SuppressWarnings("unchecked")
public static synchronized byte[] encodeObject(List<Object> lines) throws BufferOverflowException {
int bufferSize = getSize(lines);
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
if (lines.size() > 0) {
buffer.put((byte) '*');
buffer.put(ProtoUtils.convertIntToByteArray(lines.size()));
buffer.put("\r\n".getBytes());
for (int i = 0; i < lines.size(); i++) {
Object obj = lines.get(i);
if (obj instanceof String) {
byte[] lineBytes = String.valueOf(obj).getBytes();
buffer.put((byte) '$');
buffer.put(ProtoUtils.convertIntToByteArray(lineBytes.length));
buffer.put("\r\n".getBytes());
buffer.put(lineBytes);
buffer.put("\r\n".getBytes());
} else if (obj instanceof List) {
buffer.put( encodeObject( (List<Object>) obj ) );
}
}
} else {
return "-ERR no data.\r\n".getBytes();
}
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
return data;
}
@SuppressWarnings("unchecked")
private static int getSize(List<Object> lines) {
int bufferSize = 0;
for (Object line : lines) {
if (line instanceof String) {
bufferSize += String.valueOf(line).getBytes().length + 12;
} else if (line instanceof List) {
bufferSize += getSize( (List<Object>)line );
}
}
return bufferSize;
}
private static List<String> showLog(RedisRequest request, String fileName) {
long defaultLength = 1024;
StringBuffer logDir = new StringBuffer();
logDir.append( System.getProperty("log4jHome") );
logDir.append( File.separator );
logDir.append( "logs" );
List<String> lines = new ArrayList<String>();
if (request.getNumArgs() == 3) {
defaultLength = Long.parseLong(new String (request.getArgs()[2])) * 1024;
}
getLine( logDir.toString(), fileName, defaultLength, lines);
return lines;
}
private static void getLine(String path, String fileName, long length, List<String> list) {
RandomAccessFile rf = null;
try {
String line;
rf = new RandomAccessFile(path + File.separator + fileName, "r");
long fileLength = rf.length();
if (fileLength < length) {
String prevFileName;
if (fileName.indexOf("log") == fileName.length() - 3) {
prevFileName = fileName + ".1";
getLine(path, prevFileName, length - fileLength, list);
} else {
int index = Integer.parseInt(fileName.substring(fileName.length() - 1)) + 1;
if (index <= 5) {
prevFileName = fileName.substring(0, fileName.length() - 1) + index;
getLine(path, prevFileName, length - fileLength, list);
}
}
length = fileLength;
}
if (fileLength == length) {
while ((line = rf.readLine()) != null) {
list.add(line);
}
} else {
long next = fileLength - length - 1;
rf.seek(next);
int c = -1;
while (true) {
if (next == 0) {
break;
}
c = rf.read();
if ((c == '\n' || c == '\r')) {
break;
}
next
rf.seek(next);
}
while ((line = rf.readLine()) != null) {
list.add(line);
}
}
} catch (IOException e) {
} finally {
if (rf != null ) {
try {
rf.close();
} catch (IOException e) {
}
}
}
}
}
|
package net.mcft.copy.backpacks.entity;
import net.mcft.copy.backpacks.api.BackpackHelper;
import net.mcft.copy.backpacks.api.IBackpack;
import net.mcft.copy.backpacks.api.IBackpackData;
import net.mcft.copy.backpacks.api.IBackpackProperties;
import net.mcft.copy.core.misc.SyncedEntityProperties;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class BackpackProperties extends SyncedEntityProperties implements IBackpackProperties {
// Used by EntityUtils.getIdentifier().
public static final String IDENTIFIER = "WearableBackpack";
public static final String TAG_STACK = "stack";
public static final String TAG_DATA = "data";
public static final String TAG_TYPE = "type";
public int playersUsing = 0;
private ItemStack backpackStack = null;
private IBackpackData backpackData = null;
private IBackpack lastBackpackType = null;
// SyncedEntityProperties methods
@Override
public EntityLivingBase getEntity() { return (EntityLivingBase)super.getEntity(); }
@Override
public boolean isWrittenToEntity() { return ((getBackpackStack() != null) || (backpackData != null)); }
@Override
public boolean requiresSyncing() { return (getBackpackStack() != null); }
@Override
public void write(NBTTagCompound compound) {
if (getBackpackStack() != null)
compound.setTag(TAG_STACK, getBackpackStack().writeToNBT(new NBTTagCompound()));
}
@Override
public void read(NBTTagCompound compound) {
if (compound.hasKey(TAG_STACK))
setBackpackStack(ItemStack.loadItemStackFromNBT(compound.getCompoundTag(TAG_STACK)));
}
@Override
public void writeToEntity(NBTTagCompound compound) {
if (getBackpackData() != null) {
ItemStack backpack = BackpackHelper.getEquippedBackpack(getEntity());
if ((getBackpackStack() == null) && (backpack != null))
compound.setString(TAG_TYPE, Item.itemRegistry.getNameForObject(backpack.getItem()));
NBTTagCompound dataCompound = new NBTTagCompound();
getBackpackData().writeToNBT(dataCompound);
compound.setTag(TAG_DATA, dataCompound);
}
}
@Override
public void readFromEntity(NBTTagCompound compound) {
ItemStack backpack = BackpackHelper.getEquippedBackpack(getEntity());
IBackpack backpackType = ((backpack != null)
? BackpackHelper.getBackpackType(backpack)
: (IBackpack)Item.itemRegistry.getObject(compound.getString(TAG_TYPE)));
setLastBackpackType(backpackType);
if (compound.hasKey(TAG_DATA) && (getLastBackpackType() != null)) {
IBackpackData data = getLastBackpackType().createBackpackData();
data.readFromNBT(compound.getCompoundTag(TAG_DATA));
setBackpackData(data);
}
}
// IBackpackProperties implementation
@Override
public ItemStack getBackpackStack() { return backpackStack; }
@Override
public void setBackpackStack(ItemStack stack) { backpackStack = stack; }
@Override
public IBackpackData getBackpackData() { return backpackData; }
@Override
public void setBackpackData(IBackpackData data) { backpackData = data; }
@Override
public IBackpack getLastBackpackType() { return lastBackpackType; }
@Override
public void setLastBackpackType(IBackpack type) { lastBackpackType = type; }
}
|
package net.time4j.calendar.astro;
import net.time4j.CalendarUnit;
import net.time4j.Moment;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.PlainTimestamp;
import net.time4j.engine.CalendarDate;
import net.time4j.scale.TimeScale;
import net.time4j.tz.TZID;
import net.time4j.tz.Timezone;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
* <p>Contains various routines to determine times of some moon events like moonrise or moonset. </p>
*
* <p>Moonrise and moonset are not tightly coupled to the day cycle which follows the sun.
* Therefore it is sometimes possible to have only one or none of both events happening at a given
* calendar date. Furthermore, the moon can also first sets and then rises on the same day. Example
* of usage: </p>
*
* <pre>
* Timezone tz = Timezone.of("Europe/Berlin");
* LunarTime munich = LunarTime.ofLocation(tz.getID(), 48.1, 11.6);
* LunarTime.Moonlight moonlight = munich.on(PlainDate.of(2000, 3, 25));
* assertThat(
* moonlight.moonrise().isPresent(),
* is(false));
* assertThat(
* moonlight.moonset().get(),
* is(PlainTimestamp.of(2000, 3, 25, 8, 58, 33).in(tz)));
* </pre>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
/*[deutsch]
* <p>Enthält diverse Methoden zur Bestimmung der Zeit von lunaren Ereignissen
* wie Mondaufgang oder Monduntergang. </p>
*
* <p>Mondaufgang und Monduntergang sind nicht eng an den Tageszyklus gebunden, der der Sonne folgt.
* Deshalb ist es manchmal möglich, daß nur eines der beiden Ereignisse oder gar kein solches
* Ereignis zu einem gegebenen Kalenderdatum auftreten. Außerdem ist es oft möglich, daß
* an selben Tag der Mond zuerst untergeht und dann aufgeht. Anwendungsbeispiel: </p>
*
* <pre>
* Timezone tz = Timezone.of("Europe/Berlin");
* LunarTime munich = LunarTime.ofLocation(tz.getID(), 48.1, 11.6);
* LunarTime.Moonlight moonlight = munich.on(PlainDate.of(2000, 3, 25));
* assertThat(
* moonlight.moonrise().isPresent(),
* is(false));
* assertThat(
* moonlight.moonset().get(),
* is(PlainTimestamp.of(2000, 3, 25, 8, 58, 33).in(tz)));
* </pre>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
public final class LunarTime
implements GeoLocation, Serializable {
private static final int MRD = 1_000_000_000;
private static final long serialVersionUID = -8029871830105935048L;
/**
* @serial the geographical latitude in degrees
* @since 3.38/4.33
*/
private final double latitude;
/**
* @serial the geographical longitude in degrees
* @since 3.38/4.33
*/
private final double longitude;
/**
* @serial the geographical altitude in meters
* @since 3.38/4.33
*/
private final int altitude;
/**
* @serial zone identifier for the interpretation of calendar date input
* @since 3.38/4.33
*/
private final TZID observerZoneID;
private LunarTime(
double latitude,
double longitude,
int altitude,
TZID observerZoneID
) {
super();
check(latitude, longitude, altitude, observerZoneID);
this.latitude = latitude;
this.longitude = longitude;
this.altitude = altitude;
this.observerZoneID = observerZoneID;
}
/**
* <p>Obtains a builder for creating a new instance of local lunar time. </p>
*
* <p>This method is the recommended approach if any given geographical position is described
* in degrees including arc minutes and arc seconds in order to avoid manual conversions to
* decimal degrees. </p>
*
* @param observerZoneID timezone identifier associated with geographical position
* @return builder for creating a new instance of local lunar time
*/
/*[deutsch]
* <p>Liefert einen {@code Builder} zur Erzeugung einer neuen Instanz einer lokalen Mondzeit. </p>
*
* <p>Diese Methode ist der empfohlene Ansatz, wenn irgendeine geographische Positionsangabe
* in Grad mit Bogenminuten und Bogensekunden vorliegt, um manuelle Umrechnungen in Dezimalangaben
* zu vermeiden. </p>
*
* @param observerZoneID timezone identifier associated with geographical position
* @return builder for creating a new instance of local lunar time
*/
public static LunarTime.Builder ofLocation(TZID observerZoneID) {
return new Builder(observerZoneID);
}
public static LunarTime ofLocation(
TZID observerZoneID,
double latitude,
double longitude
) {
return LunarTime.ofLocation(observerZoneID, latitude, longitude, 0);
}
public static LunarTime ofLocation(
TZID observerZoneID,
double latitude,
double longitude,
int altitude
) {
return new LunarTime(latitude, longitude, altitude, observerZoneID);
}
@Override
public double getLatitude() {
return this.latitude;
}
@Override
public double getLongitude() {
return this.longitude;
}
@Override
public int getAltitude() {
return this.altitude;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof LunarTime){
LunarTime that = (LunarTime) obj;
return (
(this.altitude == that.altitude)
&& (Double.compare(this.latitude, that.latitude) == 0)
&& (Double.compare(this.longitude, that.longitude) == 0)
&& this.observerZoneID.canonical().equals(that.observerZoneID.canonical())
);
} else {
return false;
}
}
@Override
public int hashCode() {
return (7 * Double.hashCode(this.latitude) + 31 * Double.hashCode(this.longitude) + 37 * this.altitude);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("LunarTime[");
sb.append(",observer-tz=");
sb.append(this.observerZoneID.canonical());
sb.append(",latitude=");
sb.append(this.latitude);
sb.append(",longitude=");
sb.append(this.longitude);
if (this.altitude != 0) {
sb.append(",altitude=");
sb.append(this.altitude);
}
sb.append(']');
return sb.toString();
}
/**
* <p>Determines moonrise and moonset on given calendar date. </p>
*
* @param date calendar date
* @return data with moonrise and moonset
*/
/*[deutsch]
* <p>Ermittelt die Daten von Mondaufgang und Monduntergang zum angegebenen Kalenderdatum. </p>
*
* @param date calendar date
* @return data with moonrise and moonset
*/
public Moonlight on(CalendarDate date) {
// initialization
PlainDate d = SolarTime.toGregorian(date);
Timezone tz = Timezone.of(this.observerZoneID);
Moment start =
((tz.getHistory() == null)
? d.at(PlainTime.midnightAtStartOfDay()).in(tz)
: d.atFirstMoment(this.observerZoneID));
double mjd0 = JulianDay.ofMeanSolarTime(start).getMJD();
double longitudeRad = Math.toRadians(this.longitude);
double cosLatitude = Math.cos(Math.toRadians(this.latitude));
double sinLatitude = Math.sin(Math.toRadians(this.latitude));
double geodeticAngle = StdSolarCalculator.TIME4J.getGeodeticAngle(this.latitude, this.altitude);
double refraction = StdSolarCalculator.refractionOfStdAtmosphere(this.altitude) / 60;
double deltaT = TimeScale.deltaT(d);
double hour = 1.0;
double y_minus = sinAlt(mjd0, 0.0, longitudeRad, cosLatitude, sinLatitude, geodeticAngle, refraction, deltaT);
double[] result = new double[4];
// declaration of result data
boolean above = (y_minus > 0.0); // at start of day
boolean rises = false;
boolean sets = false;
double risingHour = Double.NaN;
double settingHour = Double.NaN;
// loop over 2-hour-search-intervals applying quadratic interpolation
do {
double y_0 =
sinAlt(mjd0, hour, longitudeRad, cosLatitude, sinLatitude, geodeticAngle, refraction, deltaT);
double y_plus =
sinAlt(mjd0, hour + 1, longitudeRad, cosLatitude, sinLatitude, geodeticAngle, refraction, deltaT);
int count =
interpolate(y_minus, y_0, y_plus, result);
if (count == 1) {
double root = result[2];
if (Double.isNaN(root)) {
root = result[3];
}
if (y_minus < 0.0) {
risingHour = hour + root;
rises = true;
} else {
settingHour = hour + root;
sets = true;
}
} else if (count == 2) {
if (result[1] < 0.0) {
risingHour = hour + result[3];
settingHour = hour + result[2];
} else {
risingHour = hour + result[2];
settingHour = hour + result[3];
}
rises = true;
sets = true;
}
y_minus = y_plus;
hour += 2.0;
} while (!((hour > 25.0) || (rises && sets))); // (> 25.0)-condition cares about possible 25-h-day (end-of-DST)
// evaluate moonrise and moonset
Moment rising = null;
Moment setting = null;
if (rises) {
rising = add(start, risingHour);
if (!rising.toZonalTimestamp(this.observerZoneID).getCalendarDate().equals(d)) {
rising = null;
// rises = false;
}
}
if (sets) {
setting = add(start, settingHour);
if (!setting.toZonalTimestamp(this.observerZoneID).getCalendarDate().equals(d)) {
setting = null;
// sets = false;
}
}
return new Moonlight(d, this.observerZoneID, rising, setting, above);
}
private static Moment add(
Moment start,
double hourValue
) {
double total = hourValue * 3600;
long secs = (long) Math.floor(total);
long nanos = (long) ((total - secs) * MRD);
return start
.plus(secs, TimeUnit.SECONDS)
.plus(nanos, TimeUnit.NANOSECONDS)
.with(Moment.PRECISION, TimeUnit.SECONDS);
}
// sinus of moon altitude above or below horizon
private static double sinAlt(
double mjd0, // earliest moment of calendar date (usually midnight)
double hour,
double longitudeRad,
double cosLatitude,
double sinLatitude,
double geodeticAngle,
double refraction,
double deltaT
) {
double mjd = mjd0 + hour / 24.0;
double jct = toJulianCenturies(mjd + (deltaT / 86400));
double[] data = MoonPosition.calculateMeeus(jct);
double nutationCorr = data[0] * Math.cos(Math.toRadians(data[1])); // for apparent sidereal time
double tau = gmst(mjd) + Math.toRadians(nutationCorr) + longitudeRad - Math.toRadians(data[2]);
double decl = Math.toRadians(data[3]);
// transformation to horizontal coordinate system
double sinAltitude = sinLatitude * Math.sin(decl) + cosLatitude * Math.cos(decl) * Math.cos(tau);
// about impact of horizontal parallax on moon diameter see also Meeus (chapter 15)
double correction = 0.7275 * getHorizontalParallax(data[4]) - refraction - geodeticAngle;
// we search for the roots of this function
return sinAltitude - Math.sin(Math.toRadians(correction));
}
// mean sidereal time of Greenwich in radians
private static double gmst(double mjd) {
double mjd0 = Math.floor(mjd);
double ut = 86400 * (mjd - mjd0);
double jct0 = toJulianCenturies(mjd0);
double jct = toJulianCenturies(mjd);
double gmstInSecs =
24110.54841 + 8640184.812866 * jct0 + 1.0027379093 * ut + (0.093104 - 0.0000062 * jct) * jct * jct;
double gmstInDays = gmstInSecs / 86400;
return (gmstInDays - Math.floor(gmstInDays)) * 2 * Math.PI;
}
private static double toJulianCenturies(double mjd) {
return (mjd - 51544.5) / 36525;
}
// quadratic interpolation
private static int interpolate(
double y_minus,
double y_0,
double y_plus,
double[] result // xe, ye, root1, root2
) {
double a = 0.5 * (y_plus + y_minus) - y_0;
double b = 0.5 * (y_plus - y_minus);
double xe = -b / (2.0 * a);
double ye = (a * xe + b) * xe + y_0;
double dis = b * b - 4 * a * y_0;
double root1 = Double.NaN;
double root2 = Double.NaN;
int count = 0;
if (dis >= 0) {
double dx = 0.5 * Math.sqrt(dis) / Math.abs(a);
if (Math.abs(xe - dx) <= 1.0) {
root1 = xe - dx;
count++;
}
if (Math.abs(xe + dx) <= 1.0) {
root2 = xe + dx;
count++;
}
}
result[0] = xe;
result[1] = ye;
result[2] = root1;
result[3] = root2;
return count;
}
// formula by Meeus
private static double getHorizontalParallax(double distance) {
return Math.toDegrees(Math.asin(6378.14 / distance));
}
private static void check(
double latitude,
double longitude,
int altitude,
TZID observerZoneID
) {
if (!Double.isFinite(latitude)) {
throw new IllegalArgumentException("Latitude must be a finite value: " + latitude);
} else if (!Double.isFinite(longitude)) {
throw new IllegalArgumentException("Longitude must be a finite value: " + longitude);
} else if ((Double.compare(latitude, 90.0) > 0) || (Double.compare(latitude, -90.0) < 0)) {
throw new IllegalArgumentException("Degrees out of range -90.0 <= latitude <= +90.0: " + latitude);
} else if ((Double.compare(longitude, 180.0) >= 0) || (Double.compare(longitude, -180.0) < 0)) {
throw new IllegalArgumentException("Degrees out of range -180.0 <= longitude < +180.0: " + longitude);
} else if ((altitude < 0) || (altitude >= 11_000)) {
throw new IllegalArgumentException("Meters out of range 0 <= altitude < +11,000: " + altitude);
} else {
Timezone.of(observerZoneID);
}
}
private void readObject(ObjectInputStream in)
throws IOException {
check(this.latitude, this.longitude, this.altitude, this.observerZoneID);
}
/**
* <p>Helper class to construct a new instance of {@code LunarTime}. </p>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
/*[deutsch]
* <p>Hilfsklasse für die Erzeugung einer neuen Instanz von {@code LunarTime}. </p>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
public static class Builder {
private double latitude = Double.NaN;
private double longitude = Double.NaN;
private int altitude = 0;
private final TZID observerZoneID;
private Builder(TZID observerZoneID) {
super();
this.observerZoneID = observerZoneID;
}
public Builder northernLatitude(
int degrees,
int minutes,
double seconds
) {
check(degrees, minutes, seconds, 90);
if (Double.isNaN(this.latitude)) {
this.latitude = degrees + minutes / 60.0 + seconds / 3600.0;
return this;
} else {
throw new IllegalStateException("Latitude has already been set.");
}
}
public Builder southernLatitude(
int degrees,
int minutes,
double seconds
) {
check(degrees, minutes, seconds, 90);
if (Double.isNaN(this.latitude)) {
this.latitude = -1 * (degrees + minutes / 60.0 + seconds / 3600.0);
return this;
} else {
throw new IllegalStateException("Latitude has already been set.");
}
}
public Builder easternLongitude(
int degrees,
int minutes,
double seconds
) {
check(degrees, minutes, seconds, 179);
if (Double.isNaN(this.longitude)) {
this.longitude = degrees + minutes / 60.0 + seconds / 3600.0;
return this;
} else {
throw new IllegalStateException("Longitude has already been set.");
}
}
public Builder westernLongitude(
int degrees,
int minutes,
double seconds
) {
check(degrees, minutes, seconds, 180);
if (Double.isNaN(this.longitude)) {
this.longitude = -1 * (degrees + minutes / 60.0 + seconds / 3600.0);
return this;
} else {
throw new IllegalStateException("Longitude has already been set.");
}
}
/**
* <p>Sets the altitude in meters. </p>
*
* <p>The altitude is used to model a geodetic correction as well as a refraction correction based
* on the simple assumption of a standard atmosphere. Users should keep in mind that the local
* topology with mountains breaking the horizon line and special weather conditions cannot be taken
* into account. </p>
*
* <p>Attention: Users should also apply an algorithm which is capable of altitude corrections. </p>
*
* @param altitude geographical altitude relative to sea level in meters ({@code 0 <= x < 11,0000})
* @return this instance for method chaining
*/
/*[deutsch]
* <p>Setzt die Höhe in Metern. </p>
*
* <p>Die Höhenangabe dient der Modellierung einer geodätischen Korrektur und auch einer
* Korrektur der atmosphärischen Lichtbeugung basierend auf der einfachen Annahme einer
* Standardatmosphäre. Anwender müssen im Auge behalten, daß die lokale Topologie
* mit Bergen, die die Horizontlinie unterbrechen und spezielle Wetterbedingungen nicht berechenbar
* sind. </p>
*
* <p>Achtung: Anwender sollten auch einen Algorithmus wählen, der in der Lage ist,
* Höhenkorrekturen vorzunehmen. </p>
*
* @param altitude geographical altitude relative to sea level in meters ({@code 0 <= x < 11,0000})
* @return this instance for method chaining
*/
public Builder atAltitude(int altitude) {
if ((altitude < 0) || (altitude >= 11_000)) {
throw new IllegalArgumentException("Meters out of range 0 <= altitude < +11,000: " + altitude);
}
this.altitude = altitude;
return this;
}
public LunarTime build() {
if (Double.isNaN(this.latitude)) {
throw new IllegalStateException("Latitude was not yet set.");
} else if (Double.isNaN(this.longitude)) {
throw new IllegalStateException("Longitude was not yet set.");
}
return new LunarTime(this.latitude, this.longitude, this.altitude, this.observerZoneID);
}
private static void check(
int degrees,
int minutes,
double seconds,
int max
) {
if (
degrees < 0
|| degrees > max
|| ((degrees == max) && (max != 179) && (minutes > 0 || Double.compare(seconds, 0.0) > 0))
) {
double v = degrees + minutes / 60.0 + seconds / 3600.0;
throw new IllegalArgumentException("Degrees out of range: " + degrees + " (decimal=" + v + ")");
} else if (minutes < 0 || minutes >= 60) {
throw new IllegalArgumentException("Arc minutes out of range: " + minutes);
} else if (Double.isNaN(seconds) || Double.isInfinite(seconds)) {
throw new IllegalArgumentException("Arc seconds must be finite.");
} else if (Double.compare(seconds, 0.0) < 0 || Double.compare(seconds, 60.0) >= 0) {
throw new IllegalArgumentException("Arc seconds out of range: " + seconds);
}
}
}
/**
* <p>Collects all moon presence data for a given calendar date and zone of observer. </p>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
/*[deutsch]
* <p>Sammelt alle Mondpräsenzdaten für einen gegebenen Kalendertag und die Beobachterzeitzone. </p>
*
* @author Meno Hochschild
* @since 3.38/4.33
*/
public static class Moonlight {
private final TZID observerZoneID;
private final Moment startOfDay;
private final Moment endOfDay;
private final Moment moonrise;
private final Moment moonset;
private final boolean above; // at start of day
private Moonlight(
PlainDate date,
TZID observerZoneID,
Moment moonrise,
Moment moonset,
boolean above
) {
super();
this.observerZoneID = observerZoneID;
Timezone tz = Timezone.of(observerZoneID);
PlainDate next = date.plus(1, CalendarUnit.DAYS);
if (tz.getHistory() == null) {
this.startOfDay = date.atStartOfDay().in(tz);
this.endOfDay = next.atStartOfDay().in(tz);
} else {
this.startOfDay = date.atFirstMoment(observerZoneID);
this.endOfDay = next.atFirstMoment(observerZoneID);
}
this.moonrise = moonrise;
this.moonset = moonset;
this.above = above;
}
/**
* <p>Obtains the moment of moonrise if it exists. </p>
*
* @return moment of moonrise
*/
/*[deutsch]
* <p>Liefert den Moment des Mondaufgangs wenn vorhanden. </p>
*
* @return moment of moonrise
*/
public Optional<Moment> moonrise() {
return checkAndGet(this.moonrise);
}
/**
* <p>Obtains the timestamp of moonrise in the local observer timezoone if it exists. </p>
*
* @return local timestamp of moonrise
*/
/*[deutsch]
* <p>Liefert den Zeitstempel des Mondaufgangs in der lokalen Zeitzone des Beobachters wenn vorhanden. </p>
*
* @return local timestamp of moonrise
*/
public Optional<PlainTimestamp> moonriseLocal() {
if (this.moonrise == null) {
return Optional.empty();
}
return Optional.of(this.moonrise.toZonalTimestamp(this.observerZoneID));
}
/**
* <p>Obtains the timestamp of moonrise in given timezoone if it exists. </p>
*
* @param tzid timezone identifier (which maybe deviates from local observer timezone)
* @return zonal timestamp of moonrise
*/
/*[deutsch]
* <p>Liefert den Zeitstempel des Mondaufgangs in der angegebenen Zeitzone wenn vorhanden. </p>
*
* @param tzid timezone identifier (which maybe deviates from local observer timezone)
* @return zonal timestamp of moonrise
*/
public Optional<PlainTimestamp> moonrise(TZID tzid) {
if (this.moonrise == null) {
return Optional.empty();
}
return Optional.of(this.moonrise.toZonalTimestamp(tzid));
}
/**
* <p>Obtains the moment of moonset if it exists. </p>
*
* @return moment of moonset (exclusive)
*/
/*[deutsch]
* <p>Liefert den Moment des Monduntergangs wenn vorhanden. </p>
*
* @return moment of moonset (exclusive)
*/
public Optional<Moment> moonset() {
return checkAndGet(this.moonset);
}
/**
* <p>Obtains the timestamp of moonset in the local observer timezoone if it exists. </p>
*
* @return local timestamp of moonset
*/
/*[deutsch]
* <p>Liefert den Zeitstempel des Monduntergangs in der lokalen Zeitzone des Beobachters wenn vorhanden. </p>
*
* @return local timestamp of moonset
*/
public Optional<PlainTimestamp> moonsetLocal() {
if (this.moonset == null) {
return Optional.empty();
}
return Optional.of(this.moonset.toZonalTimestamp(this.observerZoneID));
}
/**
* <p>Obtains the timestamp of moonset in given timezoone if it exists. </p>
*
* @param tzid timezone identifier (which maybe deviates from local observer timezone)
* @return zonal timestamp of moonset
*/
/*[deutsch]
* <p>Liefert den Zeitstempel des Monduntergangs in der angegebenen Zeitzone wenn vorhanden. </p>
*
* @param tzid timezone identifier (which maybe deviates from local observer timezone)
* @return zonal timestamp of moonset
*/
public Optional<PlainTimestamp> moonset(TZID tzid) {
if (this.moonset == null) {
return Optional.empty();
}
return Optional.of(this.moonset.toZonalTimestamp(tzid));
}
/**
* <p>Is the moon above the horizon at given moment? </p>
*
* <p>Keep in mind that the moon can even be invisible (New Moon) if it is above the horizon. </p>
*
* @param moment the instant to be queried
* @return boolean
*/
/*[deutsch]
* <p>Ist zum angegebenen Moment der Mond über dem Horizont? </p>
*
* <p>Zu beachten: Der Mond kann auch dann unsichtbar sein (Neumond), wenn er über dem Horizont ist. </p>
*
* @param moment the instant to be queried
* @return boolean
*/
public boolean isPresent(Moment moment) {
if (moment.isBefore(this.startOfDay) || !moment.isBefore(this.endOfDay)) {
return false;
} else if (this.moonrise == null) {
if (this.moonset == null) {
return this.above;
} else {
assert this.above;
return moment.isBefore(this.moonset);
}
} else if (this.moonset == null) {
assert !this.above;
return !moment.isBefore(this.moonrise);
} else if (this.moonrise.isBefore(this.moonset)) {
assert !this.above;
return !moment.isBefore(this.moonrise) && moment.isBefore(this.moonset);
} else {
assert this.above;
return moment.isBefore(this.moonset) || !moment.isBefore(this.moonrise);
}
}
/**
* <p>Checks if the moon is always above the horizon. </p>
*
* <p>Keep in mind that the moon can even be invisible (New Moon) if it is above the horizon. </p>
*
* @return {@code true} if the moon is always above the horizon else {@code false}
*/
/*[deutsch]
* <p>Prüft, ob der Mond immer oberhalb des Horizonts ist. </p>
*
* <p>Zu beachten: Der Mond kann auch dann unsichtbar sein (Neumond), wenn er über dem Horizont ist. </p>
*
* @return {@code true} if the moon is always above the horizon else {@code false}
*/
public boolean isPresentAllDay() {
return (this.above && (this.moonrise == null) && (this.moonset == null));
}
/**
* <p>Checks if the moon is always below the horizon. </p>
*
* <p>Keep in mind that the moon can even be invisible (New Moon) if it is above the horizon. </p>
*
* @return {@code true} if the moon is always below the horizon else {@code false}
*/
/*[deutsch]
* <p>Prüft, ob der Mond immer unterhalb des Horizonts ist. </p>
*
* <p>Zu beachten: Der Mond kann auch dann unsichtbar sein (Neumond), wenn er über dem Horizont ist. </p>
*
* @return {@code true} if the moon is always below the horizon else {@code false}
*/
public boolean isAbsent() {
return (this.length() == 0);
}
/**
* <p>Obtains the length of moonlight in seconds. </p>
*
* <p>Note: This method ignores the phase of moon. </p>
*
* @return physical length of moonlight in seconds (without leap seconds)
* @see TimeUnit#SECONDS
*/
/*[deutsch]
* <p>Liefert die Mondscheindauer in Sekunden. </p>
*
* <p>Hinweis: Diese Methode ignoriert die Mondphase. </p>
*
* @return physical length of moonlight in seconds (without leap seconds)
* @see TimeUnit#SECONDS
*/
public int length() {
if (this.moonrise == null) {
if (this.moonset == null) {
if (this.above) {
return (int) this.startOfDay.until(this.endOfDay, TimeUnit.SECONDS);
} else {
return 0;
}
} else {
assert this.above;
return (int) this.startOfDay.until(this.moonset, TimeUnit.SECONDS);
}
} else if (this.moonset == null) {
assert !this.above;
return (int) this.moonrise.until(this.endOfDay, TimeUnit.SECONDS);
} else if (this.moonrise.isBefore(this.moonset)) {
assert !this.above;
return (int) this.moonrise.until(this.moonset, TimeUnit.SECONDS);
} else {
assert this.above;
long sum = this.startOfDay.until(this.moonset, TimeUnit.SECONDS);
sum += this.moonrise.until(this.endOfDay, TimeUnit.SECONDS);
return (int) sum;
}
}
/**
* <p>For debugging purposes. </p>
*
* @return String
*/
/*[deutsch]
* <p>Für Debugging-Zwecke. </p>
*
* @return String
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
sb.append("Moonlight[");
sb.append("tz=");
sb.append(this.observerZoneID.canonical());
sb.append(" | ");
if (this.moonrise == null) {
if (this.moonset == null){
sb.append("always ");
sb.append(this.above ? "up" : "down");
} else {
sb.append("moonset=");
sb.append(this.moonset.toZonalTimestamp(this.observerZoneID));
}
} else if (this.moonset == null) {
sb.append("moonrise=");
sb.append(this.moonrise.toZonalTimestamp(this.observerZoneID));
} else if (this.moonrise.isBefore(this.moonset)) {
sb.append("moonrise=");
sb.append(this.moonrise.toZonalTimestamp(this.observerZoneID));
sb.append(" | moonset=");
sb.append(this.moonset.toZonalTimestamp(this.observerZoneID));
} else {
sb.append("moonset=");
sb.append(this.moonset.toZonalTimestamp(this.observerZoneID));
sb.append(" | moonrise=");
sb.append(this.moonrise.toZonalTimestamp(this.observerZoneID));
}
sb.append(" | length=");
sb.append(this.length());
sb.append(']');
return sb.toString();
}
private static <T> Optional<T> checkAndGet(T value) {
if (value == null) {
return Optional.empty();
} else {
return Optional.of(value);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.