answer
stringlengths 17
10.2M
|
|---|
package ajk.consul4spring;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Component;
import org.xbill.DNS.ARecord;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Name;
import org.xbill.DNS.PTRRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.TextParseException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.of;
import static org.apache.commons.logging.LogFactory.getLog;
import static org.springframework.util.StringUtils.collectionToCommaDelimitedString;
import static org.xbill.DNS.ReverseMap.fromAddress;
import static org.xbill.DNS.Type.A;
import static org.xbill.DNS.Type.PTR;
import static org.xbill.DNS.Type.SRV;
/**
* a convenient way to resolve SRV records in a DNS
*/
@SuppressWarnings("unused")
@Component
public class DnsResolver {
private Log log = getLog(getClass());
private String nonLoopback;
/**
* resolves an SRV record by its name and the default resolution defined at the host level
*
* @param name the DNS name of the SRV record
* @return a comma separate list of ip:port, e.g: 1.2.3.4:8080,2.3.4.5:9090 or null when unable to resolve
*/
public String resolveServiceByName(String name) {
return resolveSrvByName(null, name);
}
/**
* resolves an A record by its name using a specified DNS host and port
*
* @param resolverHost name server hostname or IP address
* @param resolverPort name server port
* @param name the DNS name of the A record - the name to resolve
* @return a comma separated list of IP addresses or an empty string when unable to resolve
*/
public String resolveHostByName(String resolverHost, int resolverPort, String name) {
try {
SimpleResolver resolver = new SimpleResolver(resolverHost);
resolver.setPort(resolverPort);
Lookup lookup = new Lookup(name, A);
List<String> addresses =
of(lookup.run())
.filter(it -> it instanceof ARecord)
.map(it -> ((ARecord) it).getAddress().getHostAddress())
.collect(toList());
return collectionToCommaDelimitedString(addresses);
} catch (UnknownHostException | TextParseException e) {
log.warn("unable to resolve using SRV record " + name, e);
return "";
}
}
/**
* reverse lookup an IP address using a specified DNS host and port
*
* @param resolverHost name server hostname or IP address
* @param resolverPort name server port
* @param address the IP address to reverse lookup
* @return a comma separated list of names or an empty string when unable to resolve
*/
public String reverseLookupByAddress(String resolverHost, int resolverPort, InetAddress address) {
try {
SimpleResolver resolver = new SimpleResolver(resolverHost);
resolver.setPort(resolverPort);
Lookup lookup = new Lookup(fromAddress(address), PTR);
List<String> addresses =
of(lookup.run())
.filter(it -> it instanceof PTRRecord)
.map(it -> ((PTRRecord) it).getTarget().toString())
.collect(toList());
return collectionToCommaDelimitedString(addresses);
} catch (UnknownHostException e) {
log.warn("unable to resolve using SRV record " + address, e);
return "";
}
}
/**
* resolves an SRV record by its name using a specified DNS host and port
*
* @param resolverHost name server hostname or IP address
* @param resolverPort name server port
* @param name the DNS name of the SRV record
* @return a comma separate list of ip:port, e.g: 1.2.3.4:8080,2.3.4.5:9090 or null when unable to resolve
*/
public String resolveServiceByName(String resolverHost, int resolverPort, String name) {
try {
SimpleResolver resolver = new SimpleResolver(resolverHost);
resolver.setPort(resolverPort);
return resolveSrvByName(resolver, name);
} catch (UnknownHostException e) {
log.warn("unable to resolve using SRV record " + name, e);
return null;
}
}
private String resolveSrvByName(Resolver resolver, String name) {
try {
Lookup lookup = new Lookup(name, SRV);
if (resolver != null) {
lookup.setResolver(resolver);
}
Record[] records = lookup.run();
if (records == null) {
return null;
}
return of(records)
.filter(it -> it instanceof SRVRecord)
.map(srv -> resolveHostByName(resolver, ((SRVRecord) srv).getTarget()) + ":" + ((SRVRecord) srv).getPort())
.distinct()
.collect(joining(","));
} catch (TextParseException e) {
log.warn("unable to resolve using SRV record " + name, e);
return null;
}
}
/**
* read the local real IP address (not the loopback address)
*
* @return the real IP address, or the loopback address when no real one could be found
*/
public String readNonLoopbackLocalAddress() {
if (nonLoopback == null) {
try {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
Enumeration<InetAddress> addresses = nic.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
nonLoopback = addr.getHostAddress();
break;
}
}
}
if (nonLoopback == null) {
nonLoopback = InetAddress.getLocalHost().getHostAddress();
}
} catch (SocketException | UnknownHostException e) {
log.info("unable to obtain a non loopback local address", e);
}
}
return nonLoopback;
}
private String resolveHostByName(Resolver resolver, Name target) {
Lookup lookup = new Lookup(target, A);
if (resolver != null) {
lookup.setResolver(resolver);
}
Record[] records = lookup.run();
Optional<InetAddress> address = of(records)
.filter(it -> it instanceof ARecord)
.map(a -> ((ARecord) a).getAddress())
.findFirst();
if (address.isPresent()) {
return address.get().getHostAddress();
} else {
log.warn("unknown name: " + target);
return null;
}
}
}
|
package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class MakeMatrix {
@Parameter(description = "input-file", required = true)
private List<String> parameters = new ArrayList<String>();
private File inputFile;
@Parameter(names = "-o", description = "Output file")
private File outputFile;
@Parameter(names = "-t", description = "Columns with text (comma-separated)")
private String textColums = "";
public static final void main(String[] args) {
MakeMatrix obj = new MakeMatrix();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
if (obj.parameters.size() != 1) {
System.err.println("ERROR: Exactly one main argument is needed");
jc.usage();
System.exit(1);
}
obj.inputFile = new File(obj.parameters.get(0));
try {
obj.run();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public MakeMatrix() {
}
public void run() throws IOException {
init();
BufferedReader r = new BufferedReader(new FileReader(inputFile), 64*1024);
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
BufferedWriter w = new BufferedWriter(new FileWriter(outputFile), 64*1024);
CsvListWriter csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
List<String> header = csvReader.read();
boolean[] textual = new boolean[header.size()];
for (String t : textColums.split(",")) {
if (t.isEmpty()) continue;
if (t.matches("[0-9]+")) {
textual[Integer.parseInt(t)] = true;
} else {
textual[header.indexOf(t)] = true;
}
}
List<String> line;
int c = 0;
while ((line = csvReader.read()) != null) {
c++;
for (int i = 0 ; i < line.size() ; i++) {
if (textual[i]) line.set(i, c + "");
}
csvWriter.write(line);
}
csvReader.close();
csvWriter.close();
}
private void init() {
if (outputFile == null) {
outputFile = new File(inputFile.getPath().replaceAll("\\.[^.]*$", "") + "-m.csv");
}
}
}
|
package ch.tschenett.s3tool;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class S3ToolApp extends Command {
public static void main(String[] args) {
try {
SpringApplication.run(S3ToolApp.class, args).getBean(S3ToolApp.class).execute();
System.exit(0);
}
catch (Exception e) {
syserr("error: " + e.getMessage());
System.exit(1);
}
}
@Value(value="${command}")
private String command;
@Autowired
private ApplicationContext ctx;
@Override
public void execute() throws IOException {
((Command) ctx.getBean(this.command + COMMAND_BEAN_NAME_SUFFIX)).execute();
}
}
|
package cn.momia.mapi.api;
import cn.momia.common.client.ClientType;
import cn.momia.common.webapp.config.Configuration;
import cn.momia.common.webapp.ctrl.BaseController;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
public abstract class AbstractApi extends BaseController {
protected int getClientType(HttpServletRequest request) {
return StringUtils.isBlank(request.getParameter("terminal")) ? ClientType.WAP : ClientType.APP;
}
protected String buildAction(String uri, int clientType) {
if (ClientType.isApp(clientType)) {
if (uri.startsWith("http")) return Configuration.getString("AppConf.Name") + "://web?url=" + URLEncoder.encode(uri);
return Configuration.getString("AppConf.Name") + "://" + uri;
}
return buildFullUrl(uri);
}
private String buildFullUrl(String uri) {
if (uri.startsWith("http")) return uri;
if (!uri.startsWith("/")) uri = "/" + uri;
return Configuration.getString("AppConf.WapDomain") + "/m" + uri;
}
}
|
package com.akiban.ais.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.akiban.ais.io.AISTarget;
import com.akiban.ais.io.Writer;
import com.akiban.ais.model.validation.AISValidations;
import com.akiban.message.ErrorCode;
import com.akiban.server.InvalidOperationException;
/**
* AISMerge is designed to merge a single UserTable definition into an existing AIS. The merge process
* does not assume that UserTable.getAIS() returns a validated and complete
* AkibanInformationSchema object.
*
* AISMerge makes a copy of the primaryAIS (from the constructor) before performing the merge process.
* The final results is this copies AIS, plus new table, with the full AISValidations suite run, and
* frozen. If you pass a frozen AIS into the merge, the copy process unfreeze the copy.
*
* @See UserTable
* @See AkibanInformationSchema
*/
public class AISMerge {
/* state */
private AkibanInformationSchema targetAIS;
private UserTable sourceTable;
private NameGenerator groupNames;
private static final Logger LOG = LoggerFactory.getLogger(AISMerge.class);
/**
* Creates an AISMerger with the starting values.
*
* @param primaryAIS - where the table will end up
* @param newTable - UserTable to merge into the primaryAIS
* @throws Exception
*/
public AISMerge (AkibanInformationSchema primaryAIS, UserTable newTable) throws Exception {
targetAIS = new AkibanInformationSchema();
new Writer(new AISTarget(targetAIS)).save(primaryAIS);
sourceTable = newTable;
groupNames = new DefaultNameGenerator().setDefaultGroupNames(targetAIS.getGroups().keySet());
}
/**
* Returns the final, updated AkibanInformationSchema. This AIS has been fully
* validated and is frozen (no more changes), hence ready for update into the
* server.
* @return - the primaryAIS, after merge() with the UserTable added.
*/
public AkibanInformationSchema getAIS () {
return targetAIS;
}
public AISMerge merge() {
// I should use TableSubsetWriter(new AISTarget(targetAIS))
// but that assumes the UserTable.getAIS() is complete and valid.
// i.e. has a group and group table, joins are accurate, etc.
// this may not be true
// Also the tableIDs need to be assigned correctly, which
// TableSubsetWriter doesn't do.
LOG.info(String.format("Merging table %s into targetAIS", sourceTable.getName().toString()));
final AISBuilder builder = new AISBuilder(targetAIS);
builder.setTableIdOffset(computeTableIdOffset(targetAIS));
if (sourceTable.getParentJoin() != null) {
String parentSchemaName = sourceTable.getParentJoin().getParent().getName().getSchemaName();
String parentTableName = sourceTable.getParentJoin().getParent().getName().getTableName();
UserTable parentTable = targetAIS.getUserTable(parentSchemaName, parentTableName);
if (parentTable == null) {
throw new InvalidOperationException (ErrorCode.JOIN_TO_UNKNOWN_TABLE,
"Table `%s`.`%s` joins to undefined table `%s`.`%s`",
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName(),
parentSchemaName,
parentTableName);
}
builder.setIndexIdOffset(computeIndexIDOffset(targetAIS, parentTable.getGroup().getName()));
}
// Add the user table to the targetAIS
addTable (builder, sourceTable);
// Joins or group table?
if (sourceTable.getParentJoin() == null) {
LOG.debug("Table is root or lone table");
String groupName = groupNames.generateGroupName(sourceTable);
String groupTableName = groupNames.generateGroupTableName(groupName);
builder.basicSchemaIsComplete();
builder.createGroup(groupName,
sourceTable.getName().getSchemaName(),
groupTableName);
builder.addTableToGroup(groupName,
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName());
} else {
// Normally there should be only one candidate parent join.
// But since the AIS supports multiples, so does the merge.
// This gets flagged in JoinToOneParent validation.
for (Join join : sourceTable.getCandidateParentJoins()) {
addJoin (builder, join);
}
}
builder.groupingIsComplete();
builder.akibanInformationSchema().validate(AISValidations.LIVE_AIS_VALIDATIONS).throwIfNecessary();
builder.akibanInformationSchema().freeze();
return this;
}
private void addTable(AISBuilder builder, final UserTable table) {
// I should use TableSubsetWriter(new AISTarget(targetAIS))
// but that assumes the UserTable.getAIS() is complete and valid.
// i.e. has a group and group table, and the joins point to a valid table
// which, given the use of AISMerge, is not true.
final String schemaName = table.getName().getSchemaName();
final String tableName = table.getName().getTableName();
builder.userTable(schemaName, tableName);
UserTable targetTable = targetAIS.getUserTable(schemaName, tableName);
targetTable.setEngine(table.getEngine());
targetTable.setCharsetAndCollation(table.getCharsetAndCollation());
// columns
for (Column column : table.getColumns()) {
builder.column(schemaName, tableName,
column.getName(), column.getPosition(),
column.getType().name(),
column.getTypeParameter1(), column.getTypeParameter2(),
column.getNullable(),
column.getInitialAutoIncrementValue() != null,
column.getCharsetAndCollation().charset(),
column.getCharsetAndCollation().collation());
// if an auto-increment column, set the starting value.
if (column.getInitialAutoIncrementValue() != null) {
targetTable.getColumn(column.getPosition()).setInitialAutoIncrementValue(column.getInitialAutoIncrementValue());
}
}
// indexes/constraints
for (TableIndex index : table.getIndexes()) {
IndexName indexName = index.getIndexName();
builder.index(schemaName, tableName,
indexName.getName(),
index.isUnique(),
index.getConstraint());
for (IndexColumn col : index.getColumns()) {
builder.indexColumn(schemaName, tableName, index.getIndexName().getName(),
col.getColumn().getName(),
col.getPosition(),
col.isAscending(),
col.getIndexedLength());
}
}
}
private void addJoin (AISBuilder builder, Join join) {
String parentSchemaName = join.getParent().getName().getSchemaName();
String parentTableName = join.getParent().getName().getTableName();
UserTable parentTable = targetAIS.getUserTable(parentSchemaName, parentTableName);
if (parentTable == null) {
throw new InvalidOperationException (ErrorCode.JOIN_TO_UNKNOWN_TABLE,
"Table `%s`.`%s` joins to undefined table `%s`.`%s`",
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName(),
parentSchemaName,
parentTableName);
}
LOG.debug(String.format("Table is child of table %s", parentTable.getName().toString()));
String joinName = groupNames.generateJoinName(parentTable, sourceTable, join.getJoinColumns());
builder.joinTables(joinName,
parentSchemaName,
parentTableName,
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName());
for (JoinColumn joinColumn : join.getJoinColumns()) {
try {
builder.joinColumns(joinName,
parentSchemaName,
parentTableName,
joinColumn.getParent().getName(),
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName(),
joinColumn.getChild().getName());
} catch (AISBuilder.NoSuchObjectException ex) {
throw new InvalidOperationException (ErrorCode.JOIN_TO_WRONG_COLUMNS,
"Table `%s`.`%s` join reference part `%s` does not match `%s`.`%s` primary key part `%s`",
sourceTable.getName().getSchemaName(),
sourceTable.getName().getTableName(),
joinColumn.getChild().getName(),
parentSchemaName,
parentTableName,
joinColumn.getParent().getName());
}
}
builder.basicSchemaIsComplete();
try {
builder.addJoinToGroup(parentTable.getGroup().getName(), joinName, 0);
} catch (AISBuilder.GroupStructureException ex) {
throw new InvalidOperationException (ErrorCode.JOIN_TO_MULTIPLE_PARENTS,
ex.getMessage());
}
}
private int computeTableIdOffset(AkibanInformationSchema ais) {
// Use 1 as default offset because the AAM uses tableID 0 as a marker value.
int offset = 1;
for(UserTable table : ais.getUserTables().values()) {
if(!table.getName().getSchemaName().equals(TableName.AKIBAN_INFORMATION_SCHEMA)) {
offset = Math.max(offset, table.getTableId() + 1);
}
}
for (GroupTable table : ais.getGroupTables().values()) {
if (!table.getName().getSchemaName().equals(TableName.AKIBAN_INFORMATION_SCHEMA)) {
offset = Math.max(offset, table.getTableId() + 1);
}
}
return offset;
}
private int computeIndexIDOffset (AkibanInformationSchema ais, String groupName) {
int offset = 1;
for (TableIndex index : ais.getGroup(groupName).getGroupTable().getIndexes()) {
offset = Math.max(offset, index.getIndexId() + 1);
}
return offset;
}
}
|
package com.algocrafts.pages;
import org.openqa.selenium.support.ui.FluentWait;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
public interface Waitable<Where> {
void save();
default public <What> What until(Locator<Where, What> locator) {
return until(30, SECONDS, locator);
}
default public void until(Predicate<Where> predicate) {
until(30, SECONDS, predicate);
}
default public <What> What until(int duration, TimeUnit timeUnit, Locator<Where, What> locator) {
try {
return getFluentWait(duration, timeUnit).until((Where where) -> locator.apply(where));
} catch (RuntimeException e) {
save();
throw e;
}
}
default public void until(int duration, TimeUnit timeUnit, Predicate<Where> predicate) {
try {
getFluentWait(duration, timeUnit).until((Where where) -> predicate.test(where));
} catch (RuntimeException e) {
save();
throw e;
}
}
default public FluentWait<Where> getFluentWait(int duration, TimeUnit timeUnit) {
return new FluentWait<>((Where) this).withTimeout(duration, timeUnit).pollingEvery(50, MILLISECONDS).ignoring(Exception.class);
}
}
|
package com.atexpose.util;
import com.google.common.base.Charsets;
import io.schinzel.basicutils.UTF8;
/**
* The purpose of this class is to hold an arbitrary amount of bytes.
* The bytes are stored in a byte array for memory efficiency and for having
* the data as native as possible to avoid inadvertent automatic
* transformations as can happen with strings.
*
* @author Schinzel
*/
public class ByteStorage {
/** The default max storage capacity. */
private static final int DEFAULT_SIZE = 512;
/** The default increment of storage capacity. */
private static final int DEFAULT_INCREMENT = 512;
/** Holds the data stored. */
private byte[] mStorage = new byte[DEFAULT_SIZE];
/** Index of the last byte in the storage array. */
private int mUboundStorage = -1;
// MISC
/**
* Clears the storage.
*/
public void clear() {
mUboundStorage = -1;
}
/**
* @return The number of bytes currently stored.
*/
public int getNoOfBytesStored() {
return mUboundStorage + 1;
}
// ADD
/**
* Adds a byte to the storage.
*
* @param b Byte to add to the storage.
*/
public void add(byte b) {
mUboundStorage++;
if (mUboundStorage == mStorage.length) {
this.increaseSize();
}
mStorage[mUboundStorage] = b;
}
/**
* @param ab A byte array to add to this storage.
*/
public void add(byte[] ab) {
this.add(ab, 0, ab.length);
}
/**
* @param s A string to add to this storage as UTF8 bytes.
*/
public void add(String s) {
this.add(UTF8.getBytes(s));
}
/**
* Appends a number of bytes to this object.
*
* @param ab The source of the bytes.
* @param start From where to start retrieving the bytes.
* @param length The number of bytes to retrieve from the argument array.
*/
public void add(byte[] ab, int start, int length) {
//If the new batch of bytes does not fit
if (!this.doesNewBytesFit(length)) {
//Increase size
this.increaseSize(length);
}
if (length > 0) {
//Copy the byte from argument array to storage array
System.arraycopy(ab, start, mStorage, mUboundStorage + 1, length);
//Set the new position of the storage array
mUboundStorage += length;
}
}
// GET
/**
* Converts the argument array to a string using the encoding in the BOM.
* If no BOM is present, then the argument default encoding is used.
*
* @return The argument byte array converted to String.
*/
public String getAsString() {
return new String(mStorage, 0, mUboundStorage + 1, Charsets.UTF_8);
}
/**
* @return Returns the all bytes stored in the array.
*/
public byte[] getBytes() {
return this.getBytes(0);
}
// PRIVATE
/**
* @param noOfBytesToDropFromTheEnd The number of bytes at the end not to
* return. For example: If there is a 100
* bytes stored in this object and this argument is ten, only
* the 90 first
* bytes will be returned.
* @return The bytes stored in this object.
*/
private byte[] getBytes(int noOfBytesToDropFromTheEnd) {
int noOfBytesToReturn = mUboundStorage + 1 - noOfBytesToDropFromTheEnd;
if (noOfBytesToReturn < 0) {
noOfBytesToReturn = 0;
}
// Create a return array with the number of bytes of the pos in the
// storage array
byte[] abReturn = new byte[noOfBytesToReturn];
// Copy the byte from storage array to return array
System.arraycopy(mStorage, 0, abReturn, 0, abReturn.length);
// Return the return array
return abReturn;
}
/**
* @return Returns true if the argument number of byte will fit into the
* current array, else false.
*/
private boolean doesNewBytesFit(int noOfNewBytes) {
// Return if the number of argument bytes fits in the storage array
return ((noOfNewBytes + mUboundStorage + 1) < mStorage.length);
}
/**
* Increase the size of the internal storage.
*/
private void increaseSize() {
// Get the new size
int newSize = mUboundStorage + 1 + DEFAULT_INCREMENT;
// Create a new array
byte[] newArray = new byte[newSize];
// Copy the contents of the storage array to the new array
System.arraycopy(mStorage, 0, newArray, 0, mStorage.length);
// Set the storage array to be the new array
mStorage = newArray;
}
/**
* Increases the size of the internal storage array.
*
* @param noOfNewBytes The number of bytes that needs to fit in the array.
*/
private void increaseSize(final int noOfNewBytes) {
// Get the new size
int newSize = this.getNewSize(noOfNewBytes);
// Create a new array
byte[] abNew = new byte[newSize];
// Copy the contents of the storage array to the new array
System.arraycopy(mStorage, 0, abNew, 0, mStorage.length);
// Set the storage array to be the new array
mStorage = abNew;
}
/**
* @param noOfNewBytes number of bytes that need to fit in the array.
* @return Returns the new size.
*/
private int getNewSize(int noOfNewBytes) {
// Calc the new size
int newSize = mStorage.length + DEFAULT_INCREMENT;
// If the new size is not large enough to contain the new no of bytes
if (newSize < (mStorage.length + noOfNewBytes)) {
// Set the new size the size of the storage array plus the new
// number of bytes plus the increment
newSize = mStorage.length + noOfNewBytes + DEFAULT_INCREMENT;
}
// Return the new size
return newSize;
}
}
|
package com.fishercoder.solutions;
import com.fishercoder.common.utils.CommonUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 22. Generate Parentheses
*
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
*
* For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]*/
public class _22 {
public static class Solution1 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
backtrack(result, "", 0, 0, n);
return result;
}
void backtrack(List<String> result, String str, int left, int right, int max) {
if (str.length() == max * 2) {
result.add(str);
return;
}
if (left < max) {
backtrack(result, str + "(", left + 1, right, max);
}
if (right < left) {
backtrack(result, str + ")", left, right + 1, max);
}
}
}
public static class Solution2 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
if (n == 0) {
return result;
}
helper(result, "", n, n);
return result;
}
void helper(List<String> result, String par, int left, int right) {
if (left > 0) {
helper(result, par + "(", left - 1, right);
}
if (right > left) {
helper(result, par + ")", left, right - 1);
}
if (right == 0) {
result.add(par);
}
}
}
}
|
package com.gft.codejam.roomba;
import robocode.BulletHitEvent;
import robocode.HitByBulletEvent;
import robocode.HitWallEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import static robocode.util.Utils.normalRelativeAngleDegrees;
public class Roomba extends Robot {
private static final int FULL_TURN = 360;
private static final int INITIAL_ENERGY = 100;
private static final int MIN_POSSIBLE_ENERGY = 0;
private static final int BULLET_POWER_DIVISOR = 500;
private static final int MAX_BULLET_POWER = 3;
private static final String logPattern = "";
private boolean moveForward = true;
private double lastBulletHitEnergy = 0.0;
private boolean logEnabled = true;
//Variables for future use:
//TODO: We should improve this. Over-storage of information
// private ArrayList<BulletHitEvent> bulletHitInfoContainer;
// private ArrayList<HitByBulletEvent> hitByBullerContainer;
private List<ScannedRobotEvent> scannedContainer = new ArrayList<ScannedRobotEvent>();
private long lastHitWallTime = 0;
public void run() {
setColors(Color.BLACK, Color.RED, Color.WHITE);
turnLeft(getHeading());
setAdjustRadarForRobotTurn(true);
while (true) {
//Radar FailSafe
turnRadarRight(FULL_TURN);
}
}
private void log(String message) {
if (logEnabled) {
if (message.contains(logPattern)) {
out.println(message);
}
}
}
private double getMaxBulletPower() {
return MAX_BULLET_POWER; //TODO should we calculate this based on energy?
}
public void onScannedRobot(ScannedRobotEvent e) {
double enemyPreviousEnergy;
/* ScannedRobotEvent Info:
double getBearing()
double getBearingRadians()
double getDistance()
double getEnergy()
double getHeading()
double getHeadingRadians()
double getVelocity()
*/
//Check previous enemy tank energy in order to detect
if (scannedContainer.isEmpty()) {
enemyPreviousEnergy = INITIAL_ENERGY; //TODO check if this constant is actually a constant
} else if (lastBulletHitEnergy > MIN_POSSIBLE_ENERGY) {
//When we hit, we lower energy, we should take into account this
enemyPreviousEnergy = lastBulletHitEnergy;
lastBulletHitEnergy = MIN_POSSIBLE_ENERGY;
} else {
enemyPreviousEnergy = scannedContainer.get(scannedContainer.size() - 1).getEnergy();
lastBulletHitEnergy = MIN_POSSIBLE_ENERGY;
}
this.scannedContainer.add(e);
printScannedRobotEvent(e);
// bulletPower
double bulletPower = Math.min(BULLET_POWER_DIVISOR / e.getDistance(), getMaxBulletPower());
double velocityPrediction = 0;
if (e.getVelocity() >= 6) {
//Predicted time:
long time = (long) (e.getDistance() / (20 - bulletPower * 3)); //Defaults: bulletSpeed = 20 - bulletPower * 3;
log(" >>> {time: " + time + "}");
velocityPrediction = (time * e.getVelocity() / 20);
//The turning rate of the gun measured in degrees, which is 20 degrees/turn
//The maximum turning rate of the robot, in degrees, which is 10 degress/turn.
}
// Lock enemy tank (almost 99% times)
// TODO: Improve this method using predictive shooting
double gunTurnAmount = normalRelativeAngleDegrees((getHeading() + e.getBearing() + velocityPrediction) - this.getGunHeading());
turnGunRight(gunTurnAmount);
fire(bulletPower);
log("{getBearing: " + e.getBearing() + "}");
log("{gunAmountTurn: " + gunTurnAmount + "}");
// TODO: Improve this method using better predictive enemy future position
// Fire enemy tank
log("{bulletPower: " + bulletPower + "}");
turnRight(normalRelativeAngleDegrees(e.getBearing()) + 75);
//Avoid enemy shoots
if (enemyPreviousEnergy > e.getEnergy()) {
String log = "";
log += "Energy { " +
"enemyPreviousEnergy: " + enemyPreviousEnergy + "," +
"e.getEnergy(): " + e.getEnergy() + "," +
"Distance: " + e.getBearing() + "}";
log(log);
if (Math.abs(e.getDistance()) <= 300) {
back(50);
} else {
ahead(50);
}
}
// Call scan again
//scan();
}
private void move() {
//Try to avoid enemy fire
if (moveForward) {
ahead(100);
} else {
back(100);
}
}
private void printScannedRobotEvent(ScannedRobotEvent e) {
String logTxt = String.format("ScannedRobotEvent { Bearing: %s,BearingRads: %s,Distance: %s,Energy: %s,Heading: %s,HeadingRads: %s,Velocity: %s}",
e.getBearing(),
e.getBearingRadians(),
e.getBearing(),
e.getBearing(),
e.getBearing(),
e.getHeadingRadians(),
e.getVelocity());
log(logTxt);
}
public void onHitWall(HitWallEvent e) {
log("{HitWall e.getBearing(): " + e.getBearing() + "}");
log("{HitWall getTime() =" + getTime());
if (getTime() - lastHitWallTime < 150) { // -> means the robot has hit the wall twice
turnRight(e.getBearing());
}
lastHitWallTime = getTime();
moveForward = !moveForward;
move();
}
public void onHitByBullet(HitByBulletEvent e) {
//Logs Event
//this.hitByBullerContainer.add(e);
//log(e.toString());
//When we are hit by bullet, we cannot use last bullet energy as the enemy tank regenerates energy
lastBulletHitEnergy = MIN_POSSIBLE_ENERGY;
/*
double getBearing;
double getBearingRadians;
Bullet getBullet;
double getHeading;
double getHeadingRadians;
String getName;
double getPower;
double getVelocity;
*/
}
public void onBulletHit(BulletHitEvent e) {
//Logs Event
//this.bulletHitInfoContainer.add(e);
//log(e.toString());
//When we hit a tank with a bullet, we reduce enemy max energy.
lastBulletHitEnergy = e.getEnergy();
/*
Bullet getBullet();
double getEnergy();
String getName();
*/
}
}
|
package com.jmms.application;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Launcher extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
Button btn = new Button();
btn.setText("Shooters");
btn.setOnAction(e -> System.out.println("Hello World!"));
Button btn2 = new Button("Match");
ToolBar toolBar = new ToolBar();
toolBar.setOrientation(Orientation.HORIZONTAL);
toolBar.getItems().add(btn);
toolBar.getItems().add(btn2);
BorderPane root = new BorderPane();
root.setTop(toolBar);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
|
package com.laxture.lib.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.laxture.lib.RuntimeContext;
import java.io.File;
import java.lang.reflect.Method;
import androidx.fragment.app.Fragment;
public class ViewUtil {
public static final ViewGroup.LayoutParams DEFAULT_LAYOUT_PARAM =
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
public static final ViewGroup.LayoutParams FILL_LAYOUT_PARAM =
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
public static final RadioGroup.OnCheckedChangeListener TOGGLE_LISTENER =
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final CompoundButton view = (CompoundButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
public static boolean isFragmentDead(Fragment fragment) {
return fragment.isDetached() || fragment.isRemoving() || !fragment.isAdded();
}
public static void removeViewFromParent(View view) {
if (view == null) return;
ViewGroup parentView = (ViewGroup) view.getParent();
if (parentView == null) return;
parentView.removeView(view);
}
/**
* Convenient method to retrieve value from TextView.
*/
public static String getViewText(TextView textView, String defaultValue) {
if (Checker.isEmpty(textView.getText())) return defaultValue;
return textView.getText().toString();
}
public static Double getViewTextAsDouble(TextView textView) {
String text = getViewText(textView, null);
if (text == null) return null;
return Double.parseDouble(text);
}
public static Integer getViewTextAsInt(TextView textView) {
String text = getViewText(textView, null);
if (text == null) return null;
return Integer.parseInt(text);
}
/**
* Convenient method to retrieve value from TextView.
*
* @param viewId the assigned view must be inherited from TextView
* @param rootView accept any Object has <code>findViewById()</code> method.
* @return
*/
public static String getViewText(int viewId, Object rootView) {
try {
TextView view = resolveTextView(viewId, rootView);
return getViewText(view, null);
} catch (Exception e) {
return null;
}
}
/**
* Convenient method to retrieve value from TextView.
*
* @param viewId the assigned view must be inherited from TextView
* @param rootView accept any Object has <code>findViewById()</code> method.
* @param color actual color that will be set. For color from Resource, use
* Context.getResources().getColor() to get the real color
*/
public static void setViewTextColor(int viewId, Object rootView, int color) {
TextView view = resolveTextView(viewId, rootView);
if (view != null) view.setTextColor(color);
}
/**
* Convenient method to set Text value for TextView.
*
* @param viewId the assigned view must be inherited from TextView
* @param rootView accept any Object has <code>findViewById()</code> method.
*/
public static void setViewText(int viewId, Object rootView, CharSequence text) {
TextView view = resolveTextView(viewId, rootView);
if (view != null) view.setText(text);
}
/**
* Convenient method to set Text value for TextView.
*
* @param viewId the assigned view must be inherited from TextView
* @param rootView accept any Object has <code>findViewById()</code> method.
*/
public static void setViewText(int viewId, Object rootView, int textResId) {
TextView view = resolveTextView(viewId, rootView);
if (view != null) view.setText(textResId);
}
public static void setImageSource(int viewId, Object rootView, int resId) {
ImageView view = resolveImageView(viewId, rootView);
if (view != null) view.setImageResource(resId);
}
public static void setImageSource(int viewId, Object rootView, Bitmap bitmap) {
ImageView view = resolveImageView(viewId, rootView);
if (view != null) view.setImageBitmap(bitmap);
}
public static void setImageSource(int viewId, Object rootView, Drawable drawable) {
ImageView view = resolveImageView(viewId, rootView);
if (view != null) view.setImageDrawable(drawable);
}
public static void setImageSource(int viewId, Object rootView, File file) {
ImageView view = resolveImageView(viewId, rootView);
if (view != null) view.setImageURI(Uri.fromFile(file));
}
private static TextView resolveTextView(int viewId, Object rootView) {
Method method;
TextView view = null;
try {
method = rootView.getClass().getMethod("findViewById", int.class);
view = (TextView) method.invoke(rootView, viewId);
} catch (Exception e) {
LLog.w("Cannot find view "+viewId);
}
return view;
}
private static ImageView resolveImageView(int viewId, Object rootView) {
Method method;
ImageView view = null;
try {
method = rootView.getClass().getMethod("findViewById", int.class);
view = (ImageView) method.invoke(rootView, viewId);
} catch (Exception e) {
LLog.w("Cannot find view "+viewId);
}
return view;
}
public static boolean isMultilineInputType(int inputType) {
return (inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) ==
(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
}
public static void showKeyboard(Context context) {
InputMethodManager imm = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public static void hideKeyboard(Activity activity) {
hideKeyboard(activity, activity.getWindow());
}
public static void hideKeyboard(Activity activity, Window window) {
InputMethodManager imm = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
View focusView = (window != null) ? window.getDecorView()
: activity.getWindow().getCurrentFocus();
if (focusView != null) imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
}
public static boolean checkIfTouchOutsideOfView(View view, MotionEvent event) {
return event.getAction() == MotionEvent.ACTION_DOWN
&& checkIfMotionOutsideOfView(view, event);
}
public static boolean checkIfMotionOutsideOfView(View view, MotionEvent event) {
if (view == null) return false;
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = event.getRawX() + view.getLeft() - scrcoords[0];
float y = event.getRawY() + view.getTop() - scrcoords[1];
return x < view.getLeft() || x >= view.getRight() || y < view.getTop() || y > view.getBottom();
}
public static void showToast(final Activity activity, final String message) {
if (activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
});
}
public static void showToast(final Activity activity, final int resId) {
showToast(activity, activity.getString(resId));
}
public static int getDisplaySize(int pixelSize) {
return Math.round(pixelSize * RuntimeContext.getResources().getDisplayMetrics().density);
}
/**
* dp px()
*/
public static int dip2px(float dpValue) {
final float scale = RuntimeContext.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static View findViewById(Fragment fragment, int id) {
return fragment.getActivity().findViewById(id);
}
/** EditText */
public static void setErrorHint(TextView textView, String errMsg) {
ForegroundColorSpan span = new ForegroundColorSpan(
RuntimeContext.getResources().getColor(android.R.color.white));
SpannableStringBuilder sb = new SpannableStringBuilder(errMsg);
sb.setSpan(span, 0, errMsg.length(), 0);
textView.setError(sb);
}
public static void setErrorHint(Spinner spinner, String errMsg) {
View view = spinner.getSelectedView();
if (view != null) {
if (view instanceof TextView) {
setErrorHint((TextView) view, errMsg);
} else if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i=0; i<viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof TextView) {
setErrorHint((TextView) viewGroup.getChildAt(i), errMsg);
}
}
}
}
}
public static void clearErrorHint(TextView textView) {
textView.setError(null);
}
public static void clearErrorHint(Spinner spinner) {
View view = spinner.getSelectedView();
if (view != null) {
if (view instanceof TextView) {
clearErrorHint((TextView) view);
} else if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i=0; i<viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof TextView) {
clearErrorHint((TextView) viewGroup.getChildAt(i));
}
}
}
}
}
}
|
package com.novocode.junit;
import java.util.Stack;
import org.scalatools.testing.Logger;
import static com.novocode.junit.Ansi.*;
final class RichLogger
{
private final Logger[] loggers;
private final RunSettings settings;
/* The top element is the test class of the currently executing test */
private final Stack<String> currentTestClassName = new Stack<String>();
RichLogger(Logger[] loggers, RunSettings settings, String testClassName)
{
this.loggers = loggers;
this.settings = settings;
currentTestClassName.push(testClassName);
}
void pushCurrentTestClassName(String s) { currentTestClassName.push(s); }
void popCurrentTestClassName()
{
if(currentTestClassName.size() > 1) currentTestClassName.pop();
}
void debug(String s)
{
for(Logger l : loggers)
if(settings.color && l.ansiCodesSupported()) l.debug(s);
else l.debug(filterAnsi(s));
}
void error(String s)
{
for(Logger l : loggers)
if(settings.color && l.ansiCodesSupported()) l.error(s);
else l.error(filterAnsi(s));
}
void error(String s, Throwable t)
{
error(s);
if(t != null && (settings.logAssert || !(t instanceof AssertionError))) logStackTrace(t);
}
void info(String s)
{
for(Logger l : loggers)
if(settings.color && l.ansiCodesSupported()) l.info(s);
else l.info(filterAnsi(s));
}
void warn(String s)
{
for(Logger l : loggers)
if(settings.color && l.ansiCodesSupported()) l.warn(s);
else l.warn(filterAnsi(s));
}
private void logStackTrace(Throwable t)
{
StackTraceElement[] trace = t.getStackTrace();
String testClassName = currentTestClassName.peek();
String testFileName = settings.color ? findTestFileName(trace, testClassName) : null;
logStackTracePart(trace, trace.length-1, 0, t, testClassName, testFileName);
}
private void logStackTracePart(StackTraceElement[] trace, int m, int framesInCommon, Throwable t, String testClassName, String testFileName)
{
final int m0 = m;
int top = 0;
for(int i=top; i<=m; i++)
{
if(trace[i].toString().startsWith("org.junit.") || trace[i].toString().startsWith("org.hamcrest."))
{
if(i == top) top++;
else
{
m = i-1;
while(m > top)
{
String s = trace[m].toString();
if(!s.startsWith("java.lang.reflect.") && !s.startsWith("sun.reflect.")) break;
m
}
break;
}
}
}
for(int i=top; i<=m; i++) error(" at " + stackTraceElementToString(trace[i], testClassName, testFileName));
if(m0 != m)
{
// skip junit-related frames
error(" ...");
}
else if(framesInCommon != 0)
{
// skip frames that were in the previous trace too
error(" ... " + framesInCommon + " more");
}
logStackTraceAsCause(trace, t.getCause(), testClassName, testFileName);
}
private void logStackTraceAsCause(StackTraceElement[] causedTrace, Throwable t, String testClassName, String testFileName)
{
if(t == null) return;
StackTraceElement[] trace = t.getStackTrace();
int m = trace.length - 1, n = causedTrace.length - 1;
while(m >= 0 && n >= 0 && trace[m].equals(causedTrace[n]))
{
m
n
}
error("Caused by: " + t);
logStackTracePart(trace, m, trace.length-1-m, t, testClassName, testFileName);
}
private String findTestFileName(StackTraceElement[] trace, String testClassName)
{
for(StackTraceElement e : trace)
{
String cln = e.getClassName();
if(testClassName.equals(cln)) return e.getFileName();
}
return null;
}
private String stackTraceElementToString(StackTraceElement e, String testClassName, String testFileName)
{
boolean highlight = settings.color && (
testClassName.equals(e.getClassName()) ||
(testFileName != null && testFileName.equals(e.getFileName()))
);
StringBuilder b = new StringBuilder();
b.append(settings.decodeName(e.getClassName() + '.' + e.getMethodName()));
b.append('(');
if(e.isNativeMethod()) b.append(c("Native Method", highlight ? TESTFILE2 : null));
else if(e.getFileName() == null) b.append(c("Unknown Source", highlight ? TESTFILE2 : null));
else
{
b.append(c(e.getFileName(), highlight ? TESTFILE1 : null));
if(e.getLineNumber() >= 0)
b.append(':').append(c(String.valueOf(e.getLineNumber()), highlight ? TESTFILE2 : null));
}
return b.append(')').toString();
}
}
|
package com.scorpiac.javarant;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.scorpiac.javarant.exceptions.AuthenticationException;
import com.scorpiac.javarant.exceptions.NoSuchRantException;
import com.scorpiac.javarant.exceptions.NoSuchUserException;
import org.apache.http.NameValuePair;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class DevRant {
static final String APP_ID = "3";
static final String PLAT_ID = "3";
static final String BASE_URL = "https:
static final String AVATARS_URL = "https://avatars.devrant.io";
static final String USER_URL = "/users";
static final String RANT_URL = "/rants";
static final String COLLAB_URL = "/collabs";
// API endpoints.
static final String API = "/api";
static final String API_DEVRANT = API + "/devrant";
static final String API_RANTS = API_DEVRANT + "/rants";
static final String API_SEARCH = API_DEVRANT + "/search";
static final String API_SURPRISE = API_RANTS + "/surprise";
static final String API_USERS = API + "/users";
static final String API_USER_ID = API + "/get-user-id";
static final String API_WEEKLY = API_DEVRANT + "/weekly-rants";
static final String API_COLLABS = API_DEVRANT + "/collabs";
static final String API_STORIES = API_DEVRANT + "/story-rants";
static final String API_AUTH_TOKEN = API_USERS + "/auth-token";
static final String API_COMMENT = "/comments";
static final String API_VOTE = "/vote";
static final String API_NOTIFS = API_USERS + "/me/notif-feed";
private Auth auth;
private int timeout = 15000;
private boolean hideReposts = false;
/**
* Log in to devRant.
*
* @param username The username.
* @param password The password.
* @throws AuthenticationException If the login data is invalid.
*/
public void login(String username, char[] password) throws AuthenticationException {
if (auth != null)
throw new IllegalStateException("A user is already logged in.");
JsonObject json = post(API_AUTH_TOKEN,
new BasicNameValuePair("username", username),
new BasicNameValuePair("password", String.valueOf(password))
);
// Clear the password.
for (int i = 0; i < password.length; i++)
password[i] = 0;
if (!Util.jsonSuccess(json))
throw new AuthenticationException();
auth = Auth.fromJson(json);
}
/**
* Log out of devRant.
*/
public void logout() {
auth = null;
}
/**
* Check whether a user is logged in.
*
* @return {@code true} if a user is logged in.
*/
public boolean isLoggedIn() {
return auth != null;
}
/**
* Get a list of rants.
*
* @param sort The sorting method.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return An list of rants.
*/
public List<Rant> getRants(Sort sort, int limit, int skip) {
return getFeed(API_RANTS, elem -> Rant.fromJson(this, elem), sort, limit, skip);
}
/**
* Search for rants matching a certain term.
*
* @param term The term to search for.
* @return A list of rants matching the search term.
*/
public List<Rant> search(String term) {
return getFeed(API_SEARCH, elem -> Rant.fromJson(this, elem), new BasicNameValuePair("term", term));
}
/**
* Get a random rant with at least 15 ++'s.
*
* @return A random rant.
*/
public Rant getSurprise() {
JsonObject json = get(API_SURPRISE);
return Util.jsonSuccess(json) ? Rant.fromJson(this, json.get("rant").getAsJsonObject()) : null;
}
/**
* Get the weekly rants.
*
* @param sort The sorting method.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return The weekly rants.
*/
public List<Rant> getWeekly(Sort sort, int limit, int skip) {
return getFeed(API_WEEKLY, elem -> Rant.fromJson(this, elem), sort, limit, skip);
}
/**
* Get the collabs.
*
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return A list of collabs.
*/
public List<Collab> getCollabs(int limit, int skip) {
return getFeed(API_COLLABS, elem -> Collab.fromJson(this, elem.getAsJsonObject()),
new BasicNameValuePair("limit", String.valueOf(limit)),
new BasicNameValuePair("skip", String.valueOf(skip))
);
}
/**
* Get the story rants.
*
* @param sort The sorting method.
* @param limit How many rants to get.
* @param skip How many rants to skip.
* @return A list of story rants.
*/
public List<Rant> getStories(Sort sort, int limit, int skip) {
return getFeed(API_STORIES, elem -> Rant.fromJson(this, elem), sort, limit, skip);
}
private <T> List<T> getFeed(String url, Function<JsonObject, T> converter, Sort sort, int limit, int skip) {
return getFeed(url, converter,
new BasicNameValuePair("sort", sort.toString()),
new BasicNameValuePair("limit", String.valueOf(limit)),
new BasicNameValuePair("skip", String.valueOf(skip))
);
}
private <T> List<T> getFeed(String url, Function<JsonObject, T> converter, NameValuePair... params) {
JsonObject json = get(url, params);
return Util.jsonSuccess(json) ? Util.jsonToList(json.get("rants").getAsJsonArray(), obj -> converter.apply(obj.getAsJsonObject())) : null;
}
/**
* Get a rant by its id.
*
* @param id The id of the rant to get.
* @return The rant.
*/
public Rant getRant(int id) {
JsonObject json = get(API_RANTS + '/' + id);
// Check if the rant exists.
if (!Util.jsonSuccess(json))
throw new NoSuchRantException(id);
return Rant.fromJson(this, json.get("rant").getAsJsonObject(), json.get("comments").getAsJsonArray());
}
/**
* Get a collab by its id.
*
* @param id The id of the collab to get.
* @return The collab.
*/
public Collab getCollab(int id) {
JsonObject json = get(API_RANTS + '/' + id);
// Check if the collab exists.
if (!Util.jsonSuccess(json))
throw new NoSuchRantException(id);
return Collab.fromJson(this, json.get("rant").getAsJsonObject(), json.get("comments").getAsJsonArray());
}
/**
* Get a user by their username.
*
* @param username The username of the user to get.
* @return The user.
*/
public User getUser(String username) {
JsonObject json = get(API_USER_ID, new BasicNameValuePair("username", username));
// Check if the user exists.
if (!Util.jsonSuccess(json))
throw new NoSuchUserException(username);
return getUser(json.get("user_id").getAsInt());
}
/**
* Get a user by their id.
*
* @param id The id of the user to get.
* @return The user.
*/
public User getUser(int id) {
return new User(this, id);
}
/**
* Vote on a rant.
*
* @param rant The rant to vote on.
* @param vote The vote.
* @return Whether the vote was successful.
*/
public boolean vote(Rant rant, Vote vote) {
return voteRant(rant.getId(), vote);
}
/**
* Vote on a rant.
*
* @param id The id of the rant.
* @param vote The vote.
* @return Whether the vote was successful.
*/
public boolean voteRant(int id, Vote vote) {
// Rants url, id, vote url.
String url = String.format("%1$s/%2$d%3$s", API_RANTS, id, API_VOTE);
return Util.jsonSuccess(post(url, new BasicNameValuePair("vote", String.valueOf(vote.getValue()))));
}
/**
* Vote on a comment.
*
* @param comment The comment to vote on.
* @param vote The vote.
* @return Whether the vote was successful.
*/
public boolean vote(Comment comment, Vote vote) {
return voteComment(comment.getId(), vote);
}
/**
* Vote on a comment.
*
* @param id The id of the comment.
* @param vote The vote.
* @return Whether the vote was successful.
*/
public boolean voteComment(int id, Vote vote) {
// API url, comments url, id, vote url.
String url = String.format("%1$s%2$s/%3$d%4$s", API, API_COMMENT, id, API_VOTE);
return Util.jsonSuccess(post(url, new BasicNameValuePair("vote", String.valueOf(vote.getValue()))));
}
/**
* Post a rant.
*
* @param rant The content of the rant.
* @param tags The tags.
* @return Whether posting the rant was successful.
*/
public boolean postRant(String rant, String tags) {
return Util.jsonSuccess(post(API_RANTS,
new BasicNameValuePair("rant", rant),
new BasicNameValuePair("tags", tags)
));
}
/**
* Post a comment.
*
* @param rant The rant to post the comment on.
* @param comment The content of the comment.
* @return Whether posting the comment was successful.
*/
public boolean postComment(Rant rant, String comment) {
return postComment(rant.getId(), comment);
}
/**
* Post a comment.
*
* @param rantId The id of the rant to post the comment on.
* @param comment The content of the comment.
* @return Whether posting the comment was successful.
*/
public boolean postComment(int rantId, String comment) {
// Rants url, rant, comments url.
String url = String.format("%1$s/%2$d%3$s", API_RANTS, rantId, API_COMMENT);
return Util.jsonSuccess(post(url, new BasicNameValuePair("comment", comment)));
}
/**
* Make a POST-request to the devRant server.
*
* @param url The url to make the request to.
* @param params The parameters to post.
* @return A {@link JsonObject} containing the response.
*/
JsonObject post(String url, NameValuePair... params) {
List<NameValuePair> paramList = getParameters(params);
return executeRequest(Request.Post(BASE_URL + url).bodyForm(paramList));
}
/**
* Make a GET-request to the devRant server.
*
* @param url The url to make the request to.
* @return A {@link JsonObject} containing the response.
*/
JsonObject get(String url, NameValuePair... params) {
StringBuilder finalUrl = new StringBuilder(url).append('?');
List<NameValuePair> paramList = getParameters(params);
// Add all parameters.
try {
for (NameValuePair param : paramList)
finalUrl.append('&').append(param.getName()).append('=').append(URLEncoder.encode(param.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// This never happens.
e.printStackTrace();
}
return executeRequest(Request.Get(BASE_URL + finalUrl.toString()));
}
/**
* Get a list with all the parameters, including default and auth parameters.
*
* @param params The parameters to use.
* @return A list containing the given parameters, the default parameters, and the auth parameters.
*/
private List<NameValuePair> getParameters(NameValuePair... params) {
List<NameValuePair> paramList = new ArrayList<>(params.length + 5);
paramList.addAll(Arrays.asList(params));
// Add the parameters which always need to be present.
paramList.add(new BasicNameValuePair("app", APP_ID));
paramList.add(new BasicNameValuePair("plat", PLAT_ID));
paramList.add(new BasicNameValuePair("hide_reposts", hideReposts ? "1" : "0"));
// Add the auth information.
if (isLoggedIn()) {
paramList.add(new BasicNameValuePair("token_id", auth.getId()));
paramList.add(new BasicNameValuePair("token_key", auth.getKey()));
paramList.add(new BasicNameValuePair("user_id", auth.getUserId()));
}
return paramList;
}
/**
* Execute a request and parse the response.
*
* @param request The request to execute.
* @return A {@link JsonObject} containing the response.
*/
private JsonObject executeRequest(Request request) {
// Make the request and get the returned content as a stream.
InputStream stream;
try {
stream = request.socketTimeout(timeout).connectTimeout(timeout).execute().returnContent().asStream();
} catch (IOException e) {
e.printStackTrace();
return null;
}
// Parse the response as json.
try (JsonReader reader = new JsonReader(new InputStreamReader(stream))) {
return new JsonParser().parse(reader).getAsJsonObject();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Set the request timeout. This timeout will be used for the socket and connection timeout.
*
* @param timeout The timeout in milliseconds to set, or -1 to set no timeout.
*/
public void setRequestTimeout(int timeout) {
this.timeout = timeout;
}
/**
* Get the current request timeout in milliseconds.
*/
public int getRequestTimeout() {
return timeout;
}
/**
* Set whether to hide reposts.
*
* @param hideReposts Whether to hide reposts.
*/
public void setHideReposts(boolean hideReposts) {
this.hideReposts = hideReposts;
}
/**
* Get whether to hide reposts.
*/
public boolean getHideReposts() {
return hideReposts;
}
}
|
package com.sipstacks.redneck;
import com.sipstacks.redneck.GetJson;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.*;
import com.sipstacks.redneck.Markov;
public class Redneck
{
public static List<String> getStrings() {
List<String> results = new ArrayList<String>();
Object resobj = GetJson.get("http://api.urbandictionary.com/v0/random");
if (! (resobj instanceof JSONObject)) {
System.err.println("Unexpected response: " + resobj.toString());
return results;
}
JSONObject obj = (JSONObject)resobj;
JSONArray list = (JSONArray)obj.get("list");
for(Object item : list) {
JSONObject defintion = (JSONObject)item;
Object result = defintion.get("example");
if(result != null) {
String sResult = result.toString(); sResult = sResult.replaceAll("\r\n", "\n");
sResult = sResult.replaceAll("\t", " ");
sResult = sResult.replaceAll("[”“]", "\"");
sResult = sResult.replaceAll("\"([^\"]*)\"", "$1");
// sResult = sResult.replaceAll("[a-zA-Z0-9]\n", ".\n");
// sResult = sResult.replaceAll("[a-zA-Z0-9]$", ".\n");
sResult = sResult.replaceAll("\\[([^\\]]*)\\]", "$1");
sResult = sResult.replaceAll("(^|\n)([ ]*)([a-z0-9]+\\.)([^\n]*)", "$4\n");
sResult = sResult.replaceAll("(^|\n)([ ]*)([a-zA-Z0-9]+\\))([^\n]*)", "$4\n");
sResult = sResult.replaceAll("(^|\n)([ ]*)([a-zA-Z0-9_# -]+\\:)([^\n]*)", "$4\n");
// nuke fake bold
sResult = sResult.replaceAll("\\*([^\\*]*)\\*", "$1");
// nuke () comments just makes the chain confused
sResult = sResult.replaceAll("\\(([^\\)]*)\\)", "");
//System.err.println(sResult);
results.add(sResult);
}
}
return results;
}
public static void main(String args[]) {
while(true) {
for (int i = 0; i < 30; i++) {
List<String> results = getStrings();
for (String res : results) {
if(res != null) {
Markov.addWords(res);
}
}
try{Thread.sleep(300);}catch(Exception e) {}
}
for (int i = 0; i < 1; i++) {
String result = Markov.generateSentence();
System.err.println(result);
}
}
}
}
|
package com.skelril.skree;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.skelril.skree.system.dropclear.DropClearSystem;
import com.skelril.skree.system.modifier.ModifierSystem;
import com.skelril.skree.system.registry.block.CustomBlockSystem;
import com.skelril.skree.system.registry.item.CustomItemSystem;
import com.skelril.skree.system.shutdown.ShutdownSystem;
import com.skelril.skree.system.world.WorldSystem;
import org.spongepowered.api.Game;
import org.spongepowered.api.event.Subscribe;
import org.spongepowered.api.event.state.PreInitializationEvent;
import org.spongepowered.api.event.state.ServerStartedEvent;
import org.spongepowered.api.plugin.Plugin;
import java.util.logging.Logger;
@Singleton
@Plugin(id = "Skree", name = "Skree", version = "1.0")
public class SkreePlugin {
@Inject
private Game game;
@Inject
private Logger logger;
public static CustomItemSystem customItemSystem;
public static CustomBlockSystem customBlockSystem;
@Subscribe
public void onPreInit(PreInitializationEvent event) {
customItemSystem = new CustomItemSystem(this, game);
customItemSystem.preInit();
customBlockSystem = new CustomBlockSystem(this, game);
customBlockSystem.preInit();
}
@Subscribe
public void onServerStart(ServerStartedEvent event) {
registerPrimaryHybridSystems();
switch (game.getPlatform().getType()) {
case CLIENT:
registerPrimaryClientSystems();
break;
case SERVER:
registerPrimaryServerSystems();
break;
}
logger.info("Skree Started! Kaw!");
}
private void registerPrimaryHybridSystems() {
}
private void registerPrimaryClientSystems() {
}
private void registerPrimaryServerSystems() {
try {
new DropClearSystem(this, game);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
new ModifierSystem(this, game);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
new ShutdownSystem(this, game);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
new WorldSystem(this, game);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
package com.swordspa;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.crypto.Mac;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpClient;
import org.vertx.java.core.http.HttpClientRequest;
import org.vertx.java.core.http.HttpClientResponse;
import org.vertx.java.core.json.DecodeException;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Verticle;
import com.jetdrone.vertx.yoke.Middleware;
import com.jetdrone.vertx.yoke.Yoke;
import com.jetdrone.vertx.yoke.engine.StringPlaceholderEngine;
import com.jetdrone.vertx.yoke.middleware.BodyParser;
import com.jetdrone.vertx.yoke.middleware.CookieParser;
import com.jetdrone.vertx.yoke.middleware.ErrorHandler;
import com.jetdrone.vertx.yoke.middleware.Router;
import com.jetdrone.vertx.yoke.middleware.Session;
import com.jetdrone.vertx.yoke.middleware.Static;
import com.jetdrone.vertx.yoke.middleware.YokeRequest;
import com.jetdrone.vertx.yoke.util.Utils;
public class YokeTestVerticle extends Verticle {
public final static String MONGODB_BUSADDR = "mongo-persistor";
public final static String MONGODB_DATABASE = "vertx";
public final static String PERSISTENCE_MONGODB_HOST = "127.0.0.1";
public final static Integer PERSISTENCE_MONGODB_PORT = Integer.valueOf(27017);
// This is an example only use a proper persistent storage
Map<String, String> storage = new HashMap<>();
public void start () {
// set up mongo
JsonObject mongo_config = new JsonObject();
mongo_config.putString("address", MONGODB_BUSADDR);
mongo_config.putString("host", PERSISTENCE_MONGODB_HOST);
mongo_config.putNumber("port", PERSISTENCE_MONGODB_PORT);
mongo_config.putNumber("pool_size", 10);
mongo_config.putString("db_name", MONGODB_DATABASE);
// deploy the mongo-persistor module, which we'll use for persistence
container.deployModule("io.vertx~mod-mongo-persistor~2.1.1", mongo_config);
// set up yoke
final Yoke yoke = new Yoke(vertx);
yoke.engine("html", new StringPlaceholderEngine());
Mac secret = Utils.newHmacSHA256("secret here");
// all environments
yoke.use(new CookieParser(secret));
yoke.use(new Session(secret));
yoke.use(new BodyParser());
yoke.use(new Static("static"));
yoke.use(new ErrorHandler(true));
// routes
yoke.use(new Router()
.get("/", new Middleware() {
@Override
public void handle(final YokeRequest request, final Handler<Object> next) {
String sid = request.getSessionId();
String email = storage.get(sid == null ? "" : sid);
if (email == null) {
request.put("email", "null");
} else {
request.put("email", "'" + email + "'");
}
request.response().render("views/persona.html", next);
}
})
.get("/search/allentries", new Middleware() {
@Override
public void handle(final YokeRequest request, final Handler<Object> next) {
String state = request.getParameter("state", "AL");
JsonObject json = new JsonObject().putString("collection", "zips")
.putString("action", "find")
.putObject("matcher", new JsonObject().putString("state", state));
vertx.eventBus().send(MONGODB_BUSADDR, json, new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
// send the response back, encoded as string
request.response().end(message.body().encodePrettily());
}
});
}
})
.post("/auth/logout", new Middleware() {
@Override
public void handle(YokeRequest request, Handler<Object> next) {
// remove session from storage
String sid = request.getSessionId();
storage.remove(sid == null ? "" : sid);
// destroy session
request.setSessionId(null);
// send OK
request.response().end(new JsonObject().putBoolean("success", true));
}
})
.post("/auth/login", new Middleware() {
@Override
public void handle(final YokeRequest request, final Handler<Object> next) {
String data;
try {
// generate the data
data = "assertion=" + URLEncoder.encode(request.formAttributes().get("assertion"), "UTF-8") +
"&audience=" + URLEncoder.encode("http://localhost:8080", "UTF-8");
} catch (UnsupportedEncodingException e) {
next.handle(e);
return;
}
HttpClient client = getVertx().createHttpClient().setSSL(true).setHost("verifier.login.persona.org").setPort(443);
HttpClientRequest clientRequest = client.post("/verify", new Handler<HttpClientResponse>() {
public void handle(HttpClientResponse response) {
// error handler
response.exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable err) {
next.handle(err);
}
});
final Buffer body = new Buffer(0);
// body handler
response.dataHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer buffer) {
body.appendBuffer(buffer);
}
});
// done
response.endHandler(new Handler<Void>() {
@Override
public void handle(Void event) {
try {
JsonObject verifierResp = new JsonObject(body.toString());
boolean valid = "okay".equals(verifierResp.getString("status"));
String email = valid ? verifierResp.getString("email") : null;
if (valid) {
// assertion is valid:
// generate a session Id
String sid = UUID.randomUUID().toString();
request.setSessionId(sid);
// save it and associate to the email address
storage.put(sid, email);
// OK response
request.response().end(new JsonObject().putBoolean("success", true));
} else {
request.response().end(new JsonObject().putBoolean("success", false));
}
} catch (DecodeException ex) {
// bogus response from verifier!
request.response().end(new JsonObject().putBoolean("success", false));
}
}
});
}
});
clientRequest.putHeader("content-type", "application/x-www-form-urlencoded");
clientRequest.putHeader("content-length", Integer.toString(data.length()));
clientRequest.end(data);
}
}));
yoke.listen(8080);
container.logger().info("Yoke server listening on port 8080");
}
}
|
package com.untamedears.humbug;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.v1_8_R2.EntityEnderPearl;
import net.minecraft.server.v1_8_R2.EntityTypes;
import net.minecraft.server.v1_8_R2.Item;
import net.minecraft.server.v1_8_R2.ItemEnderPearl;
import net.minecraft.server.v1_8_R2.MinecraftKey;
import net.minecraft.server.v1_8_R2.RegistryID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Hopper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCreatePortalEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.SheepDyeWoolEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import com.untamedears.humbug.annotations.BahHumbug;
import com.untamedears.humbug.annotations.BahHumbugs;
import com.untamedears.humbug.annotations.ConfigOption;
import com.untamedears.humbug.annotations.OptType;
public class Humbug extends JavaPlugin implements Listener {
public static void severe(String message) {
log_.severe("[Humbug] " + message);
}
public static void warning(String message) {
log_.warning("[Humbug] " + message);
}
public static void info(String message) {
log_.info("[Humbug] " + message);
}
public static void debug(String message) {
if (config_.getDebug()) {
log_.info("[Humbug] " + message);
}
}
public static Humbug getPlugin() {
return global_instance_;
}
private static final Logger log_ = Logger.getLogger("Humbug");
private static Humbug global_instance_ = null;
private static Config config_ = null;
private static int max_golden_apple_stack_ = 1;
static {
max_golden_apple_stack_ = Material.GOLDEN_APPLE.getMaxStackSize();
if (max_golden_apple_stack_ > 64) {
max_golden_apple_stack_ = 64;
}
}
private Random prng_ = new Random();
private CombatTagManager combatTag_ = new CombatTagManager();
public Humbug() {}
// Reduce registered PlayerInteractEvent count. onPlayerInteractAll handles
// cancelled events.
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
onAnvilOrEnderChestUse(event);
if (!event.isCancelled()) {
onCauldronInteract(event);
}
if (!event.isCancelled()) {
onRecordInJukebox(event);
}
if (!event.isCancelled()) {
onEnchantingTableUse(event);
}
if (!event.isCancelled()) {
onChangingSpawners(event);
}
}
@BahHumbug(opt="changing_spawners_with_eggs", def="true")
public void onChangingSpawners(PlayerInteractEvent event)
{
if (!config_.get("changing_spawners_with_eggs").getBool()) {
return;
}
if ((event.getClickedBlock() != null) && (event.getItem() != null) &&
(event.getClickedBlock().getType()==Material.MOB_SPAWNER) && (event.getItem().getType() == Material.MONSTER_EGG)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false
public void onPlayerInteractAll(PlayerInteractEvent event) {
onPlayerEatGoldenApple(event);
throttlePearlTeleport(event);
}
// Stops people from dying sheep
@BahHumbug(opt="allow_dye_sheep", def="true")
@EventHandler
public void onDyeWool(SheepDyeWoolEvent event) {
if (!config_.get("allow_dye_sheep").getBool()) {
event.setCancelled(true);
}
}
// Configurable bow buff
@EventHandler
public void onEntityShootBowEventAlreadyIntializedSoIMadeThisUniqueName(EntityShootBowEvent event) {
Integer power = event.getBow().getEnchantmentLevel(Enchantment.ARROW_DAMAGE);
MetadataValue metadata = new FixedMetadataValue(this, power);
event.getProjectile().setMetadata("power", metadata);
}
@BahHumbug(opt="bow_buff", type=OptType.Double, def="1.000000")
@EventHandler
public void onArrowHitEntity(EntityDamageByEntityEvent event) {
Double multiplier = config_.get("bow_buff").getDouble();
if(multiplier <= 1.000001 && multiplier >= 0.999999) {
return;
}
if (event.getEntity() instanceof LivingEntity) {
Entity damager = event.getDamager();
if (damager instanceof Arrow) {
Arrow arrow = (Arrow) event.getDamager();
Double damage = event.getDamage() * config_.get("bow_buff").getDouble();
Integer power = 0;
if(arrow.hasMetadata("power")) {
power = arrow.getMetadata("power").get(0).asInt();
}
damage *= Math.pow(1.25, power - 5); // f(x) = 1.25^(x - 5)
event.setDamage(damage);
}
}
}
// Fixes Teleporting through walls and doors
// ** and **
// Ender Pearl Teleportation disabling
// ** and **
// Ender pearl cooldown timer
private class PearlTeleportInfo {
public long last_teleport;
public long last_notification;
}
private Map<String, PearlTeleportInfo> pearl_teleport_info_
= new TreeMap<String, PearlTeleportInfo>();
private final static int PEARL_THROTTLE_WINDOW = 10000; // 10 sec
private final static int PEARL_NOTIFICATION_WINDOW = 1000; // 1 sec
// EventHandler registered in onPlayerInteractAll
@BahHumbug(opt="ender_pearl_teleportation_throttled", def="true")
public void throttlePearlTeleport(PlayerInteractEvent event) {
if (!config_.get("ender_pearl_teleportation_throttled").getBool()) {
return;
}
if (event.getItem() == null || !event.getItem().getType().equals(Material.ENDER_PEARL)) {
return;
}
final Action action = event.getAction();
if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) {
return;
}
final Block clickedBlock = event.getClickedBlock();
BlockState clickedState = null;
Material clickedMaterial = null;
if (clickedBlock != null) {
clickedState = clickedBlock.getState();
clickedMaterial = clickedState.getType();
}
if (clickedState != null && (
clickedState instanceof InventoryHolder
|| clickedMaterial.equals(Material.ANVIL)
|| clickedMaterial.equals(Material.ENCHANTMENT_TABLE)
|| clickedMaterial.equals(Material.ENDER_CHEST)
|| clickedMaterial.equals(Material.WORKBENCH))) {
// Prevent Combat Tag/Pearl cooldown on inventory access
return;
}
final long current_time = System.currentTimeMillis();
final Player player = event.getPlayer();
final String player_name = player.getName();
PearlTeleportInfo teleport_info = pearl_teleport_info_.get(player_name);
long time_diff = 0;
if (teleport_info == null) {
// New pearl thrown outside of throttle window
teleport_info = new PearlTeleportInfo();
teleport_info.last_teleport = current_time;
teleport_info.last_notification =
current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify
combatTag_.tagPlayer(player);
} else {
time_diff = current_time - teleport_info.last_teleport;
if (PEARL_THROTTLE_WINDOW > time_diff) {
// Pearl throw throttled
event.setCancelled(true);
} else {
// New pearl thrown outside of throttle window
combatTag_.tagPlayer(player);
teleport_info.last_teleport = current_time;
teleport_info.last_notification =
current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify
time_diff = 0;
}
}
final long notify_diff = current_time - teleport_info.last_notification;
if (notify_diff > PEARL_NOTIFICATION_WINDOW) {
teleport_info.last_notification = current_time;
Integer tagCooldown = combatTag_.remainingSeconds(player);
if (tagCooldown != null) {
player.sendMessage(String.format(
"Pearl in %d seconds. Combat Tag in %d seconds.",
(PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000,
tagCooldown));
} else {
player.sendMessage(String.format(
"Pearl Teleport Cooldown: %d seconds",
(PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000));
}
}
pearl_teleport_info_.put(player_name, teleport_info);
return;
}
@BahHumbugs({
@BahHumbug(opt="ender_pearl_teleportation", def="true"),
@BahHumbug(opt="fix_teleport_glitch", def="true")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent event) {
TeleportCause cause = event.getCause();
if (cause != TeleportCause.ENDER_PEARL) {
return;
} else if (!config_.get("ender_pearl_teleportation").getBool()) {
event.setCancelled(true);
return;
}
if (!config_.get("fix_teleport_glitch").getBool()) {
return;
}
Location to = event.getTo();
World world = to.getWorld();
// From and To are feet positions. Check and make sure we can teleport to a location with air
// above the To location.
Block toBlock = world.getBlockAt(to);
Block aboveBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()+1, to.getBlockZ());
Block belowBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()-1, to.getBlockZ());
boolean lowerBlockBypass = false;
double height = 0.0;
switch( toBlock.getType() ) {
case CHEST: // Probably never will get hit directly
case ENDER_CHEST: // Probably never will get hit directly
height = 0.875;
break;
case STEP:
lowerBlockBypass = true;
height = 0.5;
break;
case WATER_LILY:
height = 0.016;
break;
case ENCHANTMENT_TABLE:
lowerBlockBypass = true;
height = 0.75;
break;
case BED:
case BED_BLOCK:
// This one is tricky, since even with a height offset of 2.5, it still glitches.
//lowerBlockBypass = true;
//height = 0.563;
// Disabling teleporting on top of beds for now by leaving lowerBlockBypass false.
break;
case FLOWER_POT:
case FLOWER_POT_ITEM:
height = 0.375;
break;
case SKULL: // Probably never will get hit directly
height = 0.5;
break;
default:
break;
}
// Check if the below block is difficult
// This is added because if you face downward directly on a gate, it will
// teleport your feet INTO the gate, thus bypassing the gate until you leave that block.
switch( belowBlock.getType() ) {
case FENCE:
case FENCE_GATE:
case NETHER_FENCE:
case COBBLE_WALL:
height = 0.5;
break;
default:
break;
}
boolean upperBlockBypass = false;
if( height >= 0.5 ) {
Block aboveHeadBlock = world.getBlockAt(aboveBlock.getX(), aboveBlock.getY()+1, aboveBlock.getZ());
if( false == aboveHeadBlock.getType().isSolid() ) {
height = 0.5;
} else {
upperBlockBypass = true; // Cancel this event. What's happening is the user is going to get stuck due to the height.
}
}
// Normalize teleport to the center of the block. Feet ON the ground, plz.
// Leave Yaw and Pitch alone
to.setX(Math.floor(to.getX()) + 0.5000);
to.setY(Math.floor(to.getY()) + height);
to.setZ(Math.floor(to.getZ()) + 0.5000);
if(aboveBlock.getType().isSolid() ||
(toBlock.getType().isSolid() && !lowerBlockBypass) ||
upperBlockBypass ) {
// One last check because I care about Top Nether. (someone build me a shrine up there)
boolean bypass = false;
if ((world.getEnvironment() == Environment.NETHER) &&
(to.getBlockY() > 124) && (to.getBlockY() < 129)) {
bypass = true;
}
if (!bypass) {
event.setCancelled(true);
}
}
}
// Villager Trading
@BahHumbug(opt="villager_trades")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (config_.get("villager_trades").getBool()) {
return;
}
Entity npc = event.getRightClicked();
if (npc == null) {
return;
}
if (npc.getType() == EntityType.VILLAGER) {
event.setCancelled(true);
}
}
// Anvil and Ender Chest usage
// EventHandler registered in onPlayerInteract
@BahHumbugs({
@BahHumbug(opt="anvil"),
@BahHumbug(opt="ender_chest")
})
public void onAnvilOrEnderChestUse(PlayerInteractEvent event) {
if (config_.get("anvil").getBool() && config_.get("ender_chest").getBool()) {
return;
}
Action action = event.getAction();
Material material = event.getClickedBlock().getType();
boolean anvil = !config_.get("anvil").getBool() &&
action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ANVIL);
boolean ender_chest = !config_.get("ender_chest").getBool() &&
action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ENDER_CHEST);
if (anvil || ender_chest) {
event.setCancelled(true);
}
}
@BahHumbug(opt="enchanting_table", def = "false")
public void onEnchantingTableUse(PlayerInteractEvent event) {
if(!config_.get("enchanting_table").getBool()) {
return;
}
Action action = event.getAction();
Material material = event.getClickedBlock().getType();
boolean enchanting_table = action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ENCHANTMENT_TABLE);
if(enchanting_table) {
event.setCancelled(true);
}
}
@BahHumbug(opt="ender_chests_placeable", def="true")
@EventHandler(ignoreCancelled=true)
public void onEnderChestPlace(BlockPlaceEvent e) {
Material material = e.getBlock().getType();
if (!config_.get("ender_chests_placeable").getBool() && material == Material.ENDER_CHEST) {
e.setCancelled(true);
}
}
public void EmptyEnderChest(HumanEntity human) {
if (config_.get("ender_backpacks").getBool()) {
dropInventory(human.getLocation(), human.getEnderChest());
}
}
public void dropInventory(Location loc, Inventory inv) {
final World world = loc.getWorld();
final int end = inv.getSize();
for (int i = 0; i < end; ++i) {
try {
final ItemStack item = inv.getItem(i);
if (item != null) {
world.dropItemNaturally(loc, item);
inv.clear(i);
}
} catch (Exception ex) {}
}
}
// Unlimited Cauldron water
// EventHandler registered in onPlayerInteract
@BahHumbug(opt="unlimitedcauldron")
public void onCauldronInteract(PlayerInteractEvent e) {
if (!config_.get("unlimitedcauldron").getBool()) {
return;
}
// block water going down on cauldrons
if(e.getClickedBlock().getType() == Material.CAULDRON && e.getMaterial() == Material.GLASS_BOTTLE && e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
Block block = e.getClickedBlock();
if(block.getData() > 0)
{
block.setData((byte)(block.getData()+1));
}
}
}
// Quartz from Gravel
@BahHumbug(opt="quartz_gravel_percentage", type=OptType.Int)
@EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST)
public void onGravelBreak(BlockBreakEvent e) {
if(e.getBlock().getType() != Material.GRAVEL
|| config_.get("quartz_gravel_percentage").getInt() <= 0) {
return;
}
if(prng_.nextInt(100) < config_.get("quartz_gravel_percentage").getInt())
{
e.setCancelled(true);
e.getBlock().setType(Material.AIR);
e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new ItemStack(Material.QUARTZ, 1));
}
}
// Portals
@BahHumbug(opt="portalcreate", def="true")
@EventHandler(ignoreCancelled=true)
public void onPortalCreate(PortalCreateEvent e) {
if (!config_.get("portalcreate").getBool()) {
e.setCancelled(true);
}
}
@EventHandler(ignoreCancelled=true)
public void onEntityPortalCreate(EntityCreatePortalEvent e) {
if (!config_.get("portalcreate").getBool()) {
e.setCancelled(true);
}
}
// EnderDragon
@BahHumbug(opt="enderdragon", def="true")
@EventHandler(ignoreCancelled=true)
public void onDragonSpawn(CreatureSpawnEvent e) {
if (e.getEntityType() == EntityType.ENDER_DRAGON
&& !config_.get("enderdragon").getBool()) {
e.setCancelled(true);
}
}
// Join/Quit/Kick messages
@BahHumbug(opt="joinquitkick", def="true")
@EventHandler(priority=EventPriority.HIGHEST)
public void onJoin(PlayerJoinEvent e) {
if (!config_.get("joinquitkick").getBool()) {
e.setJoinMessage(null);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onQuit(PlayerQuitEvent e) {
EmptyEnderChest(e.getPlayer());
if (!config_.get("joinquitkick").getBool()) {
e.setQuitMessage(null);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onKick(PlayerKickEvent e) {
EmptyEnderChest(e.getPlayer());
if (!config_.get("joinquitkick").getBool()) {
e.setLeaveMessage(null);
}
}
// Death Messages
@BahHumbugs({
@BahHumbug(opt="deathannounce", def="true"),
@BahHumbug(opt="deathlog"),
@BahHumbug(opt="deathpersonal"),
@BahHumbug(opt="deathred"),
@BahHumbug(opt="ender_backpacks")
})
@EventHandler(priority=EventPriority.HIGHEST)
public void onDeath(PlayerDeathEvent e) {
final boolean logMsg = config_.get("deathlog").getBool();
final boolean sendPersonal = config_.get("deathpersonal").getBool();
final Player player = e.getEntity();
EmptyEnderChest(player);
if (logMsg || sendPersonal) {
Location location = player.getLocation();
String msg = String.format(
"%s ([%s] %d, %d, %d)", e.getDeathMessage(), location.getWorld().getName(),
location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (logMsg) {
info(msg);
}
if (sendPersonal) {
e.getEntity().sendMessage(ChatColor.RED + msg);
}
}
if (!config_.get("deathannounce").getBool()) {
e.setDeathMessage(null);
} else if (config_.get("deathred").getBool()) {
e.setDeathMessage(ChatColor.RED + e.getDeathMessage());
}
}
// Endermen Griefing
@BahHumbug(opt="endergrief", def="true")
@EventHandler(ignoreCancelled=true)
public void onEndermanGrief(EntityChangeBlockEvent e)
{
if (!config_.get("endergrief").getBool() && e.getEntity() instanceof Enderman) {
e.setCancelled(true);
}
}
// Wither Insta-breaking and Explosions
@BahHumbug(opt="wither_insta_break")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (config_.get("wither_insta_break").getBool()) {
return;
}
Entity npc = event.getEntity();
if (npc == null) {
return;
}
EntityType npc_type = npc.getType();
if (npc_type.equals(EntityType.WITHER)) {
event.setCancelled(true);
}
}
@BahHumbug(opt="wither_explosions")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
if (config_.get("wither_explosions").getBool()) {
return;
}
Entity npc = event.getEntity();
if (npc == null) {
return;
}
EntityType npc_type = npc.getType();
if ((npc_type.equals(EntityType.WITHER) ||
npc_type.equals(EntityType.WITHER_SKULL))) {
event.blockList().clear();
}
}
@BahHumbug(opt="wither", def="true")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onWitherSpawn(CreatureSpawnEvent event) {
if (config_.get("wither").getBool()) {
return;
}
if (!event.getEntityType().equals(EntityType.WITHER)) {
return;
}
event.setCancelled(true);
}
// Prevent specified items from dropping off mobs
public void removeItemDrops(EntityDeathEvent event) {
if (!config_.doRemoveItemDrops()) {
return;
}
if (event.getEntity() instanceof Player) {
return;
}
Set<Integer> remove_ids = config_.getRemoveItemDrops();
List<ItemStack> drops = event.getDrops();
ItemStack item;
int i = drops.size() - 1;
while (i >= 0) {
item = drops.get(i);
if (remove_ids.contains(item.getTypeId())) {
drops.remove(i);
}
--i;
}
}
// Spawn more Wither Skeletons and Ghasts
@BahHumbugs ({
@BahHumbug(opt="extra_ghast_spawn_rate", type=OptType.Int),
@BahHumbug(opt="extra_wither_skele_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_extra_ghast_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_extra_wither_skele_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_pig_spawn_multiplier", type=OptType.Int)
})
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled=true)
public void spawnMoreHellMonsters(CreatureSpawnEvent e) {
final Location loc = e.getLocation();
final World world = loc.getWorld();
boolean portalSpawn = false;
final int blockType = world.getBlockTypeIdAt(loc);
if (blockType == 90 || blockType == 49) {
// >= because we are preventing instead of spawning
if(prng_.nextInt(1000000) >= config_.get("portal_pig_spawn_multiplier").getInt()) {
e.setCancelled(true);
return;
}
portalSpawn = true;
}
if (config_.get("extra_wither_skele_spawn_rate").getInt() <= 0
&& config_.get("extra_ghast_spawn_rate").getInt() <= 0) {
return;
}
if (e.getEntityType() == EntityType.PIG_ZOMBIE) {
int adjustedwither;
int adjustedghast;
if (portalSpawn) {
adjustedwither = config_.get("portal_extra_wither_skele_spawn_rate").getInt();
adjustedghast = config_.get("portal_extra_ghast_spawn_rate").getInt();
} else {
adjustedwither = config_.get("extra_wither_skele_spawn_rate").getInt();
adjustedghast = config_.get("extra_ghast_spawn_rate").getInt();
}
if(prng_.nextInt(1000000) < adjustedwither) {
e.setCancelled(true);
world.spawnEntity(loc, EntityType.SKELETON);
} else if(prng_.nextInt(1000000) < adjustedghast) {
e.setCancelled(true);
int x = loc.getBlockX();
int z = loc.getBlockZ();
List<Integer> heights = new ArrayList<Integer>(16);
int lastBlockHeight = 2;
int emptyCount = 0;
int maxHeight = world.getMaxHeight();
for (int y = 2; y < maxHeight; ++y) {
Block block = world.getBlockAt(x, y, z);
if (block.isEmpty()) {
++emptyCount;
if (emptyCount == 11) {
heights.add(lastBlockHeight + 2);
}
} else {
lastBlockHeight = y;
emptyCount = 0;
}
}
if (heights.size() <= 0) {
return;
}
loc.setY(heights.get(prng_.nextInt(heights.size())));
world.spawnEntity(loc, EntityType.GHAST);
}
} else if (e.getEntityType() == EntityType.SKELETON
&& e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
Entity entity = e.getEntity();
if (entity instanceof Skeleton) {
Skeleton skele = (Skeleton)entity;
skele.setSkeletonType(SkeletonType.WITHER);
EntityEquipment entity_equip = skele.getEquipment();
entity_equip.setItemInHand(new ItemStack(Material.STONE_SWORD));
entity_equip.setItemInHandDropChance(0.0F);
}
}
}
// Wither Skull drop rate
public static final int skull_id_ = Material.SKULL_ITEM.getId();
public static final byte wither_skull_data_ = 1;
@BahHumbug(opt="wither_skull_drop_rate", type=OptType.Int)
public void adjustWitherSkulls(EntityDeathEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Skeleton)) {
return;
}
int rate = config_.get("wither_skull_drop_rate").getInt();
if (rate < 0 || rate > 1000000) {
return;
}
Skeleton skele = (Skeleton)entity;
if (skele.getSkeletonType() != SkeletonType.WITHER) {
return;
}
List<ItemStack> drops = event.getDrops();
ItemStack item;
int i = drops.size() - 1;
while (i >= 0) {
item = drops.get(i);
if (item.getTypeId() == skull_id_
&& item.getData().getData() == wither_skull_data_) {
drops.remove(i);
}
--i;
}
if (rate - prng_.nextInt(1000000) <= 0) {
return;
}
item = new ItemStack(Material.SKULL_ITEM);
item.setAmount(1);
item.setDurability((short)wither_skull_data_);
drops.add(item);
}
// Fix a few issues with pearls, specifically pearls in unloaded chunks and slime blocks.
@BahHumbug(opt="remove_pearls_chunks", type=OptType.Bool, def = "true")
@EventHandler()
public void onChunkUnloadEvent(ChunkUnloadEvent event){
Entity[] entities = event.getChunk().getEntities();
for (Entity ent: entities)
if (ent.getType() == EntityType.ENDER_PEARL)
ent.remove();
}
private void registerTimerForPearlCheck(){
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
@Override
public void run() {
for (Entity ent: pearlTime.keySet()){
if (pearlTime.get(ent).booleanValue()){
ent.remove();
}
else
pearlTime.put(ent, true);
}
}
}, 100, 200);
}
private Map<Entity, Boolean> pearlTime = new HashMap<Entity, Boolean>();
public void onPearlLastingTooLong(EntityInteractEvent event){
if (event.getEntityType() != EntityType.ENDER_PEARL)
return;
Entity ent = event.getEntity();
pearlTime.put(ent, false);
}
// Generic mob drop rate adjustment
@BahHumbug(opt="disable_xp_orbs", type=OptType.Bool, def = "true")
public void adjustMobItemDrops(EntityDeathEvent event){
Entity mob = event.getEntity();
if (mob instanceof Player){
return;
}
// Try specific multiplier, if that doesn't exist use generic
EntityType mob_type = mob.getType();
int multiplier = config_.getLootMultiplier(mob_type.toString());
if (multiplier < 0) {
multiplier = config_.getLootMultiplier("generic");
}
//set entity death xp to zero so they don't drop orbs
if(config_.get("disable_xp_orbs").getBool()){
event.setDroppedExp(0);
}
//if a dropped item was in the mob's inventory, drop only one, otherwise drop the amount * the multiplier
LivingEntity liveMob = (LivingEntity) mob;
EntityEquipment mobEquipment = liveMob.getEquipment();
ItemStack[] eeItem = mobEquipment.getArmorContents();
for (ItemStack item : event.getDrops()) {
boolean armor = false;
boolean hand = false;
for(ItemStack i : eeItem){
if(i.isSimilar(item)){
armor = true;
item.setAmount(1);
}
}
if(item.isSimilar(mobEquipment.getItemInHand())){
hand = true;
item.setAmount(1);
}
if(!hand && !armor){
int amount = item.getAmount() * multiplier;
item.setAmount(amount);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDeathEvent(EntityDeathEvent event) {
removeItemDrops(event);
adjustWitherSkulls(event);
adjustMobItemDrops(event);
}
// Enchanted Golden Apple
public boolean isEnchantedGoldenApple(ItemStack item) {
// Golden Apples are GOLDEN_APPLE with 0 durability
// Enchanted Golden Apples are GOLDEN_APPLE with 1 durability
if (item == null) {
return false;
}
if (item.getDurability() != 1) {
return false;
}
Material material = item.getType();
return material.equals(Material.GOLDEN_APPLE);
}
public boolean isCrackedStoneBrick(ItemStack item) {
// Cracked stone bricks are stone bricks with 2 durability
if (item == null) {
return false;
}
if (item.getDurability() != 2) {
return false;
}
Material material = item.getType();
return material.equals(Material.SMOOTH_BRICK);
}
public void replaceEnchantedGoldenApple(
String player_name, ItemStack item, int inventory_max_stack_size) {
if (!isEnchantedGoldenApple(item)) {
return;
}
int stack_size = max_golden_apple_stack_;
if (inventory_max_stack_size < max_golden_apple_stack_) {
stack_size = inventory_max_stack_size;
}
info(String.format(
"Replaced %d Enchanted with %d Normal Golden Apples for %s",
item.getAmount(), stack_size, player_name));
item.setDurability((short)0);
item.setAmount(stack_size);
}
@BahHumbugs({
@BahHumbug(opt="ench_gold_app_craftable", def = "false"),
@BahHumbug(opt="moss_stone_craftable", def = "false"),
@BahHumbug(opt="cracked_stone_craftable", def = "false")
})
public void removeRecipies() {
if (config_.get("ench_gold_app_craftable").getBool()&&config_.get("moss_stone_craftable").getBool()&&config_.get("cracked_stone_craftable").getBool()) {
return;
}
Iterator<Recipe> it = getServer().recipeIterator();
while (it.hasNext()) {
Recipe recipe = it.next();
ItemStack resulting_item = recipe.getResult();
if (!config_.get("ench_gold_app_craftable").getBool() &&
isEnchantedGoldenApple(resulting_item)) {
it.remove();
info("Enchanted Golden Apple Recipe disabled");
}else
if (!config_.get("moss_stone_craftable").getBool() &&
resulting_item.getType().equals(Material.MOSSY_COBBLESTONE)) {
it.remove();
info("Moss Stone Recipe disabled");
}else
if (!config_.get("cracked_stone_craftable").getBool() &&
isCrackedStoneBrick(resulting_item)) {
it.remove();
info("Cracked Stone Recipe disabled");
}
}
}
// EventHandler registered in onPlayerInteractAll
@BahHumbug(opt="ench_gold_app_edible")
public void onPlayerEatGoldenApple(PlayerInteractEvent event) {
// The event when eating is cancelled before even LOWEST fires when the
// player clicks on AIR.
if (config_.get("ench_gold_app_edible").getBool()) {
return;
}
Player player = event.getPlayer();
Inventory inventory = player.getInventory();
ItemStack item = event.getItem();
replaceEnchantedGoldenApple(
player.getName(), item, inventory.getMaxStackSize());
}
// Fix entities going through portals
// This needs to be removed when updated to citadel 3.0
@BahHumbug(opt="disable_entities_portal", type = OptType.Bool, def = "true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void entityPortalEvent(EntityPortalEvent event){
event.setCancelled(config_.get("disable_entities_portal").getBool());
}
// Enchanted Book
public boolean isNormalBook(ItemStack item) {
if (item == null) {
return false;
}
Material material = item.getType();
return material.equals(Material.BOOK);
}
@BahHumbug(opt="ench_book_craftable")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent event) {
if (config_.get("ench_book_craftable").getBool()) {
return;
}
ItemStack item = event.getItem();
if (isNormalBook(item)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onEnchantItemEvent(EnchantItemEvent event) {
if (config_.get("ench_book_craftable").getBool()) {
return;
}
ItemStack item = event.getItem();
if (isNormalBook(item)) {
event.setCancelled(true);
Player player = event.getEnchanter();
warning(
"Prevented book enchant. This should not trigger. Watch player " +
player.getName());
}
}
// Stop Cobble generation from lava+water
private static final BlockFace[] faces_ = new BlockFace[] {
BlockFace.NORTH,
BlockFace.SOUTH,
BlockFace.EAST,
BlockFace.WEST,
BlockFace.UP,
BlockFace.DOWN
};
private BlockFace WaterAdjacentLava(Block lava_block) {
for (BlockFace face : faces_) {
Block block = lava_block.getRelative(face);
Material material = block.getType();
if (material.equals(Material.WATER) ||
material.equals(Material.STATIONARY_WATER)) {
return face;
}
}
return BlockFace.SELF;
}
public void ConvertLava(final Block block) {
int data = (int)block.getData();
if (data == 0) {
return;
}
Material material = block.getType();
if (!material.equals(Material.LAVA) &&
!material.equals(Material.STATIONARY_LAVA)) {
return;
}
if (isLavaSourceNear(block, 3)) {
return;
}
BlockFace face = WaterAdjacentLava(block);
if (face == BlockFace.SELF) {
return;
}
Bukkit.getScheduler().runTask(this, new Runnable() {
@Override
public void run() {
block.setType(Material.AIR);
}
});
}
public boolean isLavaSourceNear(Block block, int ttl) {
int data = (int)block.getData();
if (data == 0) {
Material material = block.getType();
if (material.equals(Material.LAVA) ||
material.equals(Material.STATIONARY_LAVA)) {
return true;
}
}
if (ttl <= 0) {
return false;
}
for (BlockFace face : faces_) {
Block child = block.getRelative(face);
if (isLavaSourceNear(child, ttl - 1)) {
return true;
}
}
return false;
}
public void LavaAreaCheck(Block block, int ttl) {
ConvertLava(block);
if (ttl <= 0) {
return;
}
for (BlockFace face : faces_) {
Block child = block.getRelative(face);
LavaAreaCheck(child, ttl - 1);
}
}
@BahHumbugs ({
@BahHumbug(opt="cobble_from_lava"),
@BahHumbug(opt="cobble_from_lava_scan_radius", type=OptType.Int, def="0")
})
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPhysicsEvent(BlockPhysicsEvent event) {
if (config_.get("cobble_from_lava").getBool()) {
return;
}
Block block = event.getBlock();
LavaAreaCheck(block, config_.get("cobble_from_lava_scan_radius").getInt());
}
// Counteract 1.4.6 protection enchant nerf
@BahHumbug(opt="scale_protection_enchant", def="true")
@EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (!config_.get("scale_protection_enchant").getBool()) {
return;
}
double damage = event.getDamage();
if (damage <= 0.0000001D) {
return;
}
DamageCause cause = event.getCause();
if (!cause.equals(DamageCause.ENTITY_ATTACK) &&
!cause.equals(DamageCause.PROJECTILE)) {
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player defender = (Player)entity;
PlayerInventory inventory = defender.getInventory();
int enchant_level = 0;
for (ItemStack armor : inventory.getArmorContents()) {
enchant_level += armor.getEnchantmentLevel(Enchantment.PROTECTION_ENVIRONMENTAL);
}
int damage_adjustment = 0;
if (enchant_level >= 3 && enchant_level <= 6) {
// 0 to 2
damage_adjustment = prng_.nextInt(3);
} else if (enchant_level >= 7 && enchant_level <= 10) {
// 0 to 3
damage_adjustment = prng_.nextInt(4);
} else if (enchant_level >= 11 && enchant_level <= 14) {
// 1 to 4
damage_adjustment = prng_.nextInt(4) + 1;
} else if (enchant_level >= 15) {
// 2 to 4
damage_adjustment = prng_.nextInt(3) + 2;
}
damage = Math.max(damage - (double)damage_adjustment, 0.0D);
event.setDamage(damage);
}
@BahHumbug(opt="player_max_health", type=OptType.Int, def="20")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPlayerJoinEvent(PlayerJoinEvent event) {
Player player = event.getPlayer();
player.setMaxHealth((double)config_.get("player_max_health").getInt());
}
// Fix dupe bug with chests and other containers
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void blockExplodeEvent(EntityExplodeEvent event) {
List<HumanEntity> humans = new ArrayList<HumanEntity>();
for (Block block: event.blockList()) {
if (block.getState() instanceof InventoryHolder) {
InventoryHolder holder = (InventoryHolder) block.getState();
for (HumanEntity ent: holder.getInventory().getViewers()) {
humans.add(ent);
}
}
}
for (HumanEntity human: humans) {
human.closeInventory();
}
}
// Prevent entity dup bug
@BahHumbug(opt="fix_rail_dup_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPistonPushRail(BlockPistonExtendEvent e) {
if (!config_.get("fix_rail_dup_bug").getBool()) {
return;
}
for (Block b : e.getBlocks()) {
Material t = b.getType();
if (t == Material.RAILS ||
t == Material.POWERED_RAIL ||
t == Material.DETECTOR_RAIL) {
e.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onRailPlace(BlockPlaceEvent e) {
if (!config_.get("fix_rail_dup_bug").getBool()) {
return;
}
Block b = e.getBlock();
Material t = b.getType();
if (t == Material.RAILS ||
t == Material.POWERED_RAIL ||
t == Material.DETECTOR_RAIL) {
for (BlockFace face : faces_) {
t = b.getRelative(face).getType();
if (t == Material.PISTON_STICKY_BASE ||
t == Material.PISTON_EXTENSION ||
t == Material.PISTON_MOVING_PIECE ||
t == Material.PISTON_BASE) {
e.setCancelled(true);
return;
}
}
}
}
// Combat Tag players on server join
@BahHumbug(opt="tag_on_join", def="true")
@EventHandler
public void tagOnJoin(PlayerJoinEvent event){
if(!config_.get("tag_on_join").getBool()) {
return;
}
// Delay two ticks to tag after secure login has been denied.
// This opens a 1 tick window for a cheater to login and grab
// server info, which should be detectable and bannable.
final Player loginPlayer = event.getPlayer();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
combatTag_.tagPlayer(loginPlayer.getName());
loginPlayer.sendMessage("You have been Combat Tagged on Login");
}
}, 2L);
}
// Give introduction book to n00bs
private Set<String> playersWithN00bBooks_ = new TreeSet<String>();
@BahHumbug(opt="drop_newbie_book", def="true")
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerDeathBookDrop(PlayerDeathEvent e) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final String playerName = e.getEntity().getName();
List<ItemStack> dropList = e.getDrops();
for (int i = 0; i < dropList.size(); ++i) {
final ItemStack item = dropList.get(i);
if (item.getType().equals(Material.WRITTEN_BOOK)) {
final BookMeta bookMeta = (BookMeta)item.getItemMeta();
if (bookMeta.getTitle().equals(config_.getTitle())) {
playersWithN00bBooks_.add(playerName);
dropList.remove(i);
return;
}
}
}
playersWithN00bBooks_.remove(playerName);
}
@EventHandler
public void onGiveBookOnRespawn(PlayerRespawnEvent event) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final Player player = event.getPlayer();
final String playerName = player.getName();
if (!playersWithN00bBooks_.contains(playerName)) {
return;
}
playersWithN00bBooks_.remove(playerName);
giveN00bBook(player);
}
@EventHandler
public void onGiveBookOnJoin(PlayerJoinEvent event) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final Player player = event.getPlayer();
final String playerName = player.getName();
if (player.hasPlayedBefore() && !playersWithN00bBooks_.contains(playerName)) {
return;
}
playersWithN00bBooks_.remove(playerName);
giveN00bBook(player);
}
public void giveN00bBook(Player player) {
Inventory inv = player.getInventory();
inv.addItem(createN00bBook());
}
public ItemStack createN00bBook() {
ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
BookMeta sbook = (BookMeta)book.getItemMeta();
sbook.setTitle(config_.getTitle());
sbook.setAuthor(config_.getAuthor());
sbook.setPages(config_.getPages());
book.setItemMeta(sbook);
return book;
}
public boolean checkForInventorySpace(Inventory inv, int emptySlots) {
int foundEmpty = 0;
final int end = inv.getSize();
for (int slot = 0; slot < end; ++slot) {
ItemStack item = inv.getItem(slot);
if (item == null) {
++foundEmpty;
} else if (item.getType().equals(Material.AIR)) {
++foundEmpty;
}
}
return foundEmpty >= emptySlots;
}
public void giveHolidayPackage(Player player) {
int count = 0;
Inventory inv = player.getInventory();
while (checkForInventorySpace(inv, 4)) {
inv.addItem(createHolidayBook());
inv.addItem(createFruitcake());
inv.addItem(createTurkey());
inv.addItem(createCoal());
++count;
}
info(String.format("%s generated %d packs of holiday cheer.",
player.getName(), count));
}
public ItemStack createHolidayBook() {
ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
BookMeta sbook = (BookMeta)book.getItemMeta();
sbook.setTitle(config_.getHolidayTitle());
sbook.setAuthor(config_.getHolidayAuthor());
sbook.setPages(config_.getHolidayPages());
List<String> lore = new ArrayList<String>(1);
lore.add("December 25th, 2013");
sbook.setLore(lore);
book.setItemMeta(sbook);
return book;
}
public ItemStack createFruitcake() {
ItemStack cake = new ItemStack(Material.CAKE);
ItemMeta meta = cake.getItemMeta();
meta.setDisplayName("Fruitcake");
List<String> lore = new ArrayList<String>(1);
lore.add("Deliciously stale");
meta.setLore(lore);
cake.setItemMeta(meta);
return cake;
}
private String[] turkey_names_ = new String[] {
"Turkey",
"Turkey",
"Turkey",
"Turducken",
"Tofurkey",
"Cearc Frangach",
"Dinde",
"Kalkoen",
"Indeyka",
"Pollo d'India",
"Pelehu",
"Chilmyeonjo"
};
public ItemStack createTurkey() {
String turkey_name = turkey_names_[prng_.nextInt(turkey_names_.length)];
ItemStack turkey = new ItemStack(Material.COOKED_CHICKEN);
ItemMeta meta = turkey.getItemMeta();
meta.setDisplayName(turkey_name);
List<String> lore = new ArrayList<String>(1);
lore.add("Tastes like chicken");
meta.setLore(lore);
turkey.setItemMeta(meta);
return turkey;
}
public ItemStack createCoal() {
ItemStack coal = new ItemStack(Material.COAL);
ItemMeta meta = coal.getItemMeta();
List<String> lore = new ArrayList<String>(1);
lore.add("You've been naughty");
meta.setLore(lore);
coal.setItemMeta(meta);
return coal;
}
// Playing records in jukeboxen? Gone
// EventHandler registered in onPlayerInteract
@BahHumbug(opt="disallow_record_playing", def="true")
public void onRecordInJukebox(PlayerInteractEvent event) {
if (!config_.get("disallow_record_playing").getBool()) {
return;
}
Block cb = event.getClickedBlock();
if (cb == null || cb.getType() != Material.JUKEBOX) {
return;
}
ItemStack his = event.getItem();
if(his != null && his.getType().isRecord()) {
event.setCancelled(true);
}
}
// Water in the nether? Nope.
@BahHumbugs ({
@BahHumbug(opt="allow_water_in_nether"),
@BahHumbug(opt="indestructible_end_portals", def="true")
})
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent e) {
if(!config_.get("allow_water_in_nether").getBool()) {
if( ( e.getBlockClicked().getBiome() == Biome.HELL )
&& ( e.getBucket() == Material.WATER_BUCKET ) ) {
e.setCancelled(true);
e.getItemStack().setType(Material.BUCKET);
e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 5, 1));
}
}
if (config_.get("indestructible_end_portals").getBool()) {
Block baseBlock = e.getBlockClicked();
BlockFace face = e.getBlockFace();
Block block = baseBlock.getRelative(face);
if (block.getType() == Material.ENDER_PORTAL) {
e.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromToEvent(BlockFromToEvent e) {
if(!config_.get("allow_water_in_nether").getBool()) {
if( e.getToBlock().getBiome() == Biome.HELL ) {
if( ( e.getBlock().getType() == Material.WATER )
|| ( e.getBlock().getType() == Material.STATIONARY_WATER ) ) {
e.setCancelled(true);
}
}
}
if (config_.get("indestructible_end_portals").getBool()) {
if (e.getToBlock().getType() == Material.ENDER_PORTAL) {
e.setCancelled(true);
}
}
if(!e.isCancelled() && config_.get("obsidian_generator").getBool()) {
generateObsidian(e);
}
}
// Generates obsidian like it did in 1.7.
// Note that this does not change anything in versions where obsidian generation exists.
@BahHumbug(opt="obsidian_generator", def="false")
public void generateObsidian(BlockFromToEvent event) {
if(!event.getBlock().getType().equals(Material.STATIONARY_LAVA)) {
return;
}
if(!event.getToBlock().getType().equals(Material.TRIPWIRE)) {
return;
}
Block string = event.getToBlock();
if(!(string.getRelative(BlockFace.NORTH).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.EAST).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.WEST).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.SOUTH).getType().equals(Material.STATIONARY_WATER))) {
return;
}
string.setType(Material.OBSIDIAN);
}
// Stops perculators
private Map<Chunk, Integer> waterChunks = new HashMap<Chunk, Integer>();
BukkitTask waterSchedule = null;
@BahHumbugs ({
@BahHumbug(opt="max_water_lava_height", def="100", type=OptType.Int),
@BahHumbug(opt="max_water_lava_amount", def = "400", type=OptType.Int),
@BahHumbug(opt="max_water_lava_timer", def = "1200", type=OptType.Int)
})
@EventHandler(priority = EventPriority.LOWEST)
public void stopLiquidMoving(BlockFromToEvent event){
try {
Block to = event.getToBlock();
Block from = event.getBlock();
if (to.getLocation().getBlockY() < config_.get("max_water_lava_height").getInt()) {
return;
}
Material mat = from.getType();
if (!(mat.equals(Material.WATER) || mat.equals(Material.STATIONARY_WATER) ||
mat.equals(Material.LAVA) || mat.equals(Material.STATIONARY_LAVA))) {
return;
}
Chunk c = to.getChunk();
if (!waterChunks.containsKey(c)){
waterChunks.put(c, 0);
}
Integer i = waterChunks.get(c);
i = i + 1;
waterChunks.put(c, i);
int amount = getWaterInNearbyChunks(c);
if (amount > config_.get("max_water_lava_amount").getInt()) {
event.setCancelled(true);
}
if (waterSchedule != null) {
return;
}
waterSchedule = Bukkit.getScheduler().runTaskLater(this, new Runnable(){
@Override
public void run() {
waterChunks.clear();
waterSchedule = null;
}
}, config_.get("max_water_lava_timer").getInt());
} catch (Exception e){
getLogger().log(Level.INFO, "Tried getting info from a chunk before it generated, skipping.");
return;
}
}
public int getWaterInNearbyChunks(Chunk chunk){
World world = chunk.getWorld();
Chunk[] chunks = {
world.getChunkAt(chunk.getX(), chunk.getZ()), world.getChunkAt(chunk.getX()-1, chunk.getZ()),
world.getChunkAt(chunk.getX(), chunk.getZ()-1), world.getChunkAt(chunk.getX()-1, chunk.getZ()-1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()+1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()+1), world.getChunkAt(chunk.getX()-1, chunk.getZ()+1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()-1)
};
int count = 0;
for (Chunk c: chunks){
Integer amount = waterChunks.get(c);
if (amount == null)
continue;
count += amount;
}
return count;
}
// Changes Strength Potions, strength_multiplier 3 is roughly Pre-1.6 Level
@BahHumbugs ({
@BahHumbug(opt="nerf_strength", def="true"),
@BahHumbug(opt="strength_multiplier", type=OptType.Int, def="3")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerDamage(EntityDamageByEntityEvent event) {
if (!config_.get("nerf_strength").getBool()) {
return;
}
if (!(event.getDamager() instanceof Player)) {
return;
}
Player player = (Player)event.getDamager();
final int strengthMultiplier = config_.get("strength_multiplier").getInt();
if (player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) {
for (PotionEffect effect : player.getActivePotionEffects()) {
if (effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) {
final int potionLevel = effect.getAmplifier() + 1;
final double unbuffedDamage = event.getDamage() / (1.3 * potionLevel + 1);
final double newDamage = unbuffedDamage + (potionLevel * strengthMultiplier);
event.setDamage(newDamage);
break;
}
}
}
}
// Buffs health splash to pre-1.6 levels
@BahHumbug(opt="buff_health_pots", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
if (!config_.get("buff_health_pots").getBool()) {
return;
}
for (PotionEffect effect : event.getEntity().getEffects()) {
if (!(effect.getType().getName().equalsIgnoreCase("heal"))) { // Splash potion of poison
return;
}
}
for (LivingEntity entity : event.getAffectedEntities()) {
if (entity instanceof Player) {
if(((Damageable)entity).getHealth() > 0d) {
final double newHealth = Math.min(
((Damageable)entity).getHealth() + 4.0D,
((Damageable)entity).getMaxHealth());
entity.setHealth(newHealth);
}
}
}
}
// Bow shots cause slow debuff
@BahHumbugs ({
@BahHumbug(opt="projectile_slow_chance", type=OptType.Int, def="30"),
@BahHumbug(opt="projectile_slow_ticks", type=OptType.Int, def="100")
})
@EventHandler
public void onEDBE(EntityDamageByEntityEvent event) {
int rate = config_.get("projectile_slow_chance").getInt();
if (rate <= 0 || rate > 100) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
boolean damager_is_player_arrow = false;
int chance_scaling = 0;
Entity damager_entity = event.getDamager();
if (damager_entity != null) {
// public LivingEntity CraftArrow.getShooter()
// Playing this game to not have to take a hard dependency on
// craftbukkit internals.
try {
Class<?> damager_class = damager_entity.getClass();
if (damager_class.getName().endsWith(".CraftArrow")) {
Method getShooter = damager_class.getMethod("getShooter");
Object result = getShooter.invoke(damager_entity);
if (result instanceof Player) {
damager_is_player_arrow = true;
String player_name = ((Player)result).getName();
if (bow_level_.containsKey(player_name)) {
chance_scaling = bow_level_.get(player_name);
}
}
}
} catch(Exception ex) {}
}
if (!damager_is_player_arrow) {
return;
}
rate += chance_scaling * 5;
int percent = prng_.nextInt(100);
if (percent < rate){
int ticks = config_.get("projectile_slow_ticks").getInt();
Player player = (Player)event.getEntity();
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, ticks, 1, false));
}
}
// Used to track bow enchantment levels per player
private Map<String, Integer> bow_level_ = new TreeMap<String, Integer>();
@EventHandler
public void onEntityShootBow(EntityShootBowEvent event) {
if (!(event.getEntity() instanceof Player)) {
return;
}
int ench_level = 0;
ItemStack bow = event.getBow();
Map<Enchantment, Integer> enchants = bow.getEnchantments();
for (Enchantment ench : enchants.keySet()) {
int tmp_ench_level = 0;
if (ench.equals(Enchantment.KNOCKBACK) || ench.equals(Enchantment.ARROW_KNOCKBACK)) {
tmp_ench_level = enchants.get(ench) * 2;
} else if (ench.equals(Enchantment.ARROW_DAMAGE)) {
tmp_ench_level = enchants.get(ench);
}
if (tmp_ench_level > ench_level) {
ench_level = tmp_ench_level;
}
}
bow_level_.put(
((Player)event.getEntity()).getName(),
ench_level);
}
// BottleO refugees
// Changes the yield from an XP bottle
@BahHumbugs ({
@BahHumbug(opt="disable_experience", def="true"),
@BahHumbug(opt="xp_per_bottle", type=OptType.Int, def="10")
})
@EventHandler(priority=EventPriority.HIGHEST)
public void onExpBottleEvent(ExpBottleEvent event) {
final int bottle_xp = config_.get("xp_per_bottle").getInt();
if (config_.get("disable_experience").getBool()) {
((Player) event.getEntity().getShooter()).giveExp(bottle_xp);
event.setExperience(0);
} else {
event.setExperience(bottle_xp);
}
}
// Diables all XP gain except when manually changed via code.
@EventHandler
public void onPlayerExpChangeEvent(PlayerExpChangeEvent event) {
if (config_.get("disable_experience").getBool()) {
event.setAmount(0);
}
}
// Find the end portals
public static final int ender_portal_id_ = Material.ENDER_PORTAL.getId();
public static final int ender_portal_frame_id_ = Material.ENDER_PORTAL_FRAME.getId();
private Set<Long> end_portal_scanned_chunks_ = new TreeSet<Long>();
@BahHumbug(opt="find_end_portals", type=OptType.String)
@EventHandler
public void onFindEndPortals(ChunkLoadEvent event) {
String scanWorld = config_.get("find_end_portals").getString();
if (scanWorld.isEmpty()) {
return;
}
World world = event.getWorld();
if (!world.getName().equalsIgnoreCase(scanWorld)) {
return;
}
Chunk chunk = event.getChunk();
long chunk_id = (long)chunk.getX() << 32L + (long)chunk.getZ();
if (end_portal_scanned_chunks_.contains(chunk_id)) {
return;
}
end_portal_scanned_chunks_.add(chunk_id);
int chunk_x = chunk.getX() * 16;
int chunk_end_x = chunk_x + 16;
int chunk_z = chunk.getZ() * 16;
int chunk_end_z = chunk_z + 16;
int max_height = 0;
for (int x = chunk_x; x < chunk_end_x; x += 3) {
for (int z = chunk_z; z < chunk_end_z; ++z) {
int height = world.getMaxHeight();
if (height > max_height) {
max_height = height;
}
}
}
for (int y = 1; y <= max_height; ++y) {
int z_adj = 0;
for (int x = chunk_x; x < chunk_end_x; ++x) {
for (int z = chunk_z + z_adj; z < chunk_end_z; z += 3) {
int block_type = world.getBlockTypeIdAt(x, y, z);
if (block_type == ender_portal_id_ || block_type == ender_portal_frame_id_) {
info(String.format("End portal found at %d,%d", x, z));
return;
}
}
// This funkiness results in only searching 48 of the 256 blocks on
// each y-level. 81.25% fewer blocks checked.
++z_adj;
if (z_adj >= 3) {
z_adj = 0;
x += 2;
}
}
}
}
// Prevent inventory access while in a vehicle, unless it's the Player's
@BahHumbugs ({
@BahHumbug(opt="prevent_opening_container_carts", def="true"),
@BahHumbug(opt="prevent_vehicle_inventory_open", def="true")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventVehicleInvOpen(InventoryOpenEvent event) {
// Cheap break-able conditional statement
while (config_.get("prevent_vehicle_inventory_open").getBool()) {
HumanEntity human = event.getPlayer();
if (!(human instanceof Player)) {
break;
}
if (!human.isInsideVehicle()) {
break;
}
InventoryHolder holder = event.getInventory().getHolder();
if (holder == human) {
break;
}
event.setCancelled(true);
break;
}
if (config_.get("prevent_opening_container_carts").getBool() && !event.isCancelled()) {
InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof StorageMinecart || holder instanceof HopperMinecart) {
event.setCancelled(true);
}
}
}
// Disable outbound hopper transfers
@BahHumbug(opt="disable_hopper_out_transfers", def="false")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
if (!config_.get("disable_hopper_out_transfers").getBool()) {
return;
}
final Inventory src = event.getSource();
final InventoryHolder srcHolder = src.getHolder();
if (srcHolder instanceof Hopper) {
event.setCancelled(true);
return;
}
}
// Adjust horse speeds
@BahHumbug(opt="horse_speed", type=OptType.Double, def="0.170000")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
// 0.17 is just a tad slower than minecarts
Vehicle vehicle = event.getVehicle();
if (!(vehicle instanceof Horse)) {
return;
}
Versioned.setHorseSpeed((Entity)vehicle, config_.get("horse_speed").getDouble());
}
// Admins can view player inventories
@SuppressWarnings("deprecation")
public void onInvseeCommand(Player admin, String playerName) {
final Player player = Bukkit.getPlayerExact(playerName);
if (player == null) {
admin.sendMessage("Player not found");
return;
}
final Inventory pl_inv = player.getInventory();
final Inventory inv = Bukkit.createInventory(
admin, 36, playerName + "'s Inventory");
for (int slot = 0; slot < 36; slot++) {
final ItemStack it = pl_inv.getItem(slot);
inv.setItem(slot, it);
}
admin.openInventory(inv);
admin.updateInventory();
}
// Fix boats
@BahHumbug(opt="prevent_self_boat_break", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventLandBoats(VehicleDestroyEvent event) {
if (!config_.get("prevent_land_boats").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Boat)) {
return;
}
final Entity passenger = vehicle.getPassenger();
if (passenger == null || !(passenger instanceof Player)) {
return;
}
final Entity attacker = event.getAttacker();
if (attacker == null) {
return;
}
if (!attacker.getUniqueId().equals(passenger.getUniqueId())) {
return;
}
final Player player = (Player)passenger;
Humbug.info(String.format(
"Player '%s' kicked for self damaging boat at %s",
player.getName(), vehicle.getLocation().toString()));
vehicle.eject();
vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT));
vehicle.remove();
((Player)passenger).kickPlayer("Nope");
}
@BahHumbug(opt="prevent_land_boats", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventLandBoats(VehicleMoveEvent event) {
if (!config_.get("prevent_land_boats").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Boat)) {
return;
}
final Entity passenger = vehicle.getPassenger();
if (passenger == null || !(passenger instanceof Player)) {
return;
}
final Location to = event.getTo();
final Material boatOn = to.getBlock().getRelative(BlockFace.DOWN).getType();
if (boatOn.equals(Material.STATIONARY_WATER) || boatOn.equals(Material.WATER)) {
return;
}
Humbug.info(String.format(
"Player '%s' removed from land-boat at %s",
((Player)passenger).getName(), to.toString()));
vehicle.eject();
vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT));
vehicle.remove();
}
// Fix minecarts
public boolean checkForTeleportSpace(Location loc) {
final Block block = loc.getBlock();
final Material mat = block.getType();
if (mat.isSolid()) {
return false;
}
final Block above = block.getRelative(BlockFace.UP);
if (above.getType().isSolid()) {
return false;
}
return true;
}
public boolean tryToTeleport(Player player, Location location, String reason) {
Location loc = location.clone();
loc.setX(Math.floor(loc.getX()) + 0.500000D);
loc.setY(Math.floor(loc.getY()) + 0.02D);
loc.setZ(Math.floor(loc.getZ()) + 0.500000D);
final Location baseLoc = loc.clone();
final World world = baseLoc.getWorld();
// Check if teleportation here is viable
boolean performTeleport = checkForTeleportSpace(loc);
if (!performTeleport) {
loc.setY(loc.getY() + 1.000000D);
performTeleport = checkForTeleportSpace(loc);
}
if (performTeleport) {
player.setVelocity(new Vector());
player.teleport(loc);
Humbug.info(String.format(
"Player '%s' %s: Teleported to %s",
player.getName(), reason, loc.toString()));
return true;
}
loc = baseLoc.clone();
// Create a sliding window of block types and track how many of those
// are solid. Keep fetching the block below the current block to move down.
int air_count = 0;
LinkedList<Material> air_window = new LinkedList<Material>();
loc.setY((float)world.getMaxHeight() - 2);
Block block = world.getBlockAt(loc);
for (int i = 0; i < 4; ++i) {
Material block_mat = block.getType();
if (!block_mat.isSolid()) {
++air_count;
}
air_window.addLast(block_mat);
block = block.getRelative(BlockFace.DOWN);
}
// Now that the window is prepared, scan down the Y-axis.
while (block.getY() >= 1) {
Material block_mat = block.getType();
if (block_mat.isSolid()) {
if (air_count == 4) {
player.setVelocity(new Vector());
loc = block.getLocation();
loc.setX(Math.floor(loc.getX()) + 0.500000D);
loc.setY(loc.getY() + 1.02D);
loc.setZ(Math.floor(loc.getZ()) + 0.500000D);
player.teleport(loc);
Humbug.info(String.format(
"Player '%s' %s: Teleported to %s",
player.getName(), reason, loc.toString()));
return true;
}
} else { // !block_mat.isSolid()
++air_count;
}
air_window.addLast(block_mat);
if (!air_window.removeFirst().isSolid()) {
--air_count;
}
block = block.getRelative(BlockFace.DOWN);
}
return false;
}
@BahHumbug(opt="prevent_ender_pearl_save", def="true")
@EventHandler
public void enderPearlSave(EnderPearlUnloadEvent event) {
if(!config_.get("prevent_ender_pearl_save").getBool())
return;
event.setCancelled(true);
}
@BahHumbug(opt="fix_vehicle_logout_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onDisallowVehicleLogout(PlayerQuitEvent event) {
if (!config_.get("fix_vehicle_logout_bug").getBool()) {
return;
}
kickPlayerFromVehicle(event.getPlayer());
}
public void kickPlayerFromVehicle(Player player) {
Entity vehicle = player.getVehicle();
if (vehicle == null
|| !(vehicle instanceof Minecart || vehicle instanceof Horse || vehicle instanceof Arrow)) {
return;
}
Location vehicleLoc = vehicle.getLocation();
// Vehicle data has been cached, now safe to kick the player out
player.leaveVehicle();
if (!tryToTeleport(player, vehicleLoc, "logged out")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' logged out in vehicle: Killed", player.getName()));
}
}
@BahHumbug(opt="fix_minecart_reenter_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFixMinecartReenterBug(VehicleExitEvent event) {
if (!config_.get("fix_minecart_reenter_bug").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Minecart)) {
return;
}
final Entity passengerEntity = event.getExited();
if (passengerEntity == null || !(passengerEntity instanceof Player)) {
return;
}
// Must delay the teleport 2 ticks or else the player's mis-managed
// movement still occurs. With 1 tick it could still occur.
final Player player = (Player)passengerEntity;
final Location vehicleLoc = vehicle.getLocation();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
if (!tryToTeleport(player, vehicleLoc, "exiting vehicle")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' exiting vehicle: Killed", player.getName()));
}
}
}, 2L);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFixMinecartReenterBug(VehicleDestroyEvent event) {
if (!config_.get("fix_minecart_reenter_bug").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse)) {
return;
}
final Entity passengerEntity = vehicle.getPassenger();
if (passengerEntity == null || !(passengerEntity instanceof Player)) {
return;
}
// Must delay the teleport 2 ticks or else the player's mis-managed
// movement still occurs. With 1 tick it could still occur.
final Player player = (Player)passengerEntity;
final Location vehicleLoc = vehicle.getLocation();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
if (!tryToTeleport(player, vehicleLoc, "in destroyed vehicle")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' in destroyed vehicle: Killed", player.getName()));
}
}
}, 2L);
}
// Adjust ender pearl gravity
public final static int pearlId = 368;
public final static MinecraftKey pearlKey = new MinecraftKey("ender_pearl");
@SuppressWarnings({ "rawtypes", "unchecked" })
@BahHumbug(opt="ender_pearl_gravity", type=OptType.Double, def="0.060000")
private void hookEnderPearls() {
try {
// They thought they could stop us by preventing us from registering an
// item. We'll show them
Field idRegistryField = Item.REGISTRY.getClass().getDeclaredField("a");
idRegistryField.setAccessible(true);
Object idRegistry = idRegistryField.get(Item.REGISTRY);
Field idRegistryMapField = idRegistry.getClass().getDeclaredField("a");
idRegistryMapField.setAccessible(true);
Object idRegistryMap = idRegistryMapField.get(idRegistry);
Field idRegistryItemsField = idRegistry.getClass().getDeclaredField("b");
idRegistryItemsField.setAccessible(true);
Object idRegistryItemList = idRegistryItemsField.get(idRegistry);
// Remove ItemEnderPearl from the ID Registry
Item idItem = null;
Iterator<Item> itemListIter = ((List<Item>)idRegistryItemList).iterator();
while (itemListIter.hasNext()) {
idItem = itemListIter.next();
if (idItem == null) {
continue;
}
if (!(idItem instanceof ItemEnderPearl)) {
continue;
}
itemListIter.remove();
break;
}
if (idItem != null) {
((Map<Item, Integer>)idRegistryMap).remove(idItem);
}
// Register our custom pearl Item.
Item.REGISTRY.a(pearlId, pearlKey, new CustomNMSItemEnderPearl(config_));
// Setup the custom entity
Field fieldStringToClass = EntityTypes.class.getDeclaredField("c");
Field fieldClassToString = EntityTypes.class.getDeclaredField("d");
fieldStringToClass.setAccessible(true);
fieldClassToString.setAccessible(true);
Field fieldClassToId = EntityTypes.class.getDeclaredField("f");
Field fieldStringToId = EntityTypes.class.getDeclaredField("g");
fieldClassToId.setAccessible(true);
fieldStringToId.setAccessible(true);
Map mapStringToClass = (Map)fieldStringToClass.get(null);
Map mapClassToString = (Map)fieldClassToString.get(null);
Map mapClassToId = (Map)fieldClassToId.get(null);
Map mapStringToId = (Map)fieldStringToId.get(null);
mapStringToClass.put("ThrownEnderpearl",CustomNMSEntityEnderPearl.class);
mapStringToId.put("ThrownEnderpearl", Integer.valueOf(14));
mapClassToString.put(CustomNMSEntityEnderPearl.class, "ThrownEnderpearl");
mapClassToId.put(CustomNMSEntityEnderPearl.class, Integer.valueOf(14));
} catch (Exception e) {
Humbug.severe("Exception while overriding MC's ender pearl class");
e.printStackTrace();
}
}
// Hunger Changes
// Keep track if the player just ate.
private Map<Player, Double> playerLastEat_ = new HashMap<Player, Double>();
@BahHumbug(opt="saturation_multiplier", type=OptType.Double, def="0.0")
@EventHandler
public void setSaturationOnFoodEat(PlayerItemConsumeEvent event) {
// Each food sets a different saturation.
final Player player = event.getPlayer();
ItemStack item = event.getItem();
Material mat = item.getType();
double multiplier = config_.get("saturation_multiplier").getDouble();
if (multiplier <= 0.000001 && multiplier >= -0.000001) {
return;
}
switch(mat) {
case APPLE:
playerLastEat_.put(player, multiplier*2.4);
case BAKED_POTATO:
playerLastEat_.put(player, multiplier*7.2);
case BREAD:
playerLastEat_.put(player, multiplier*6);
case CAKE:
playerLastEat_.put(player, multiplier*0.4);
case CARROT_ITEM:
playerLastEat_.put(player, multiplier*4.8);
case COOKED_FISH:
playerLastEat_.put(player, multiplier*6);
case GRILLED_PORK:
playerLastEat_.put(player, multiplier*12.8);
case COOKIE:
playerLastEat_.put(player, multiplier*0.4);
case GOLDEN_APPLE:
playerLastEat_.put(player, multiplier*9.6);
case GOLDEN_CARROT:
playerLastEat_.put(player, multiplier*14.4);
case MELON:
playerLastEat_.put(player, multiplier*1.2);
case MUSHROOM_SOUP:
playerLastEat_.put(player, multiplier*7.2);
case POISONOUS_POTATO:
playerLastEat_.put(player, multiplier*1.2);
case POTATO:
playerLastEat_.put(player, multiplier*0.6);
case RAW_FISH:
playerLastEat_.put(player, multiplier*1);
case PUMPKIN_PIE:
playerLastEat_.put(player, multiplier*4.8);
case RAW_BEEF:
playerLastEat_.put(player, multiplier*1.8);
case RAW_CHICKEN:
playerLastEat_.put(player, multiplier*1.2);
case PORK:
playerLastEat_.put(player, multiplier*1.8);
case ROTTEN_FLESH:
playerLastEat_.put(player, multiplier*0.8);
case SPIDER_EYE:
playerLastEat_.put(player, multiplier*3.2);
case COOKED_BEEF:
playerLastEat_.put(player, multiplier*12.8);
default:
playerLastEat_.put(player, multiplier);
Bukkit.getServer().getScheduler().runTaskLater(this, new Runnable() {
// In case the player ingested a potion, this removes the
// saturation from the list. Unsure if I have every item
// listed. There is always the other cases of like food
// that shares same id
@Override
public void run() {
playerLastEat_.remove(player);
}
}, 80);
}
}
@BahHumbug(opt="hunger_slowdown", type=OptType.Double, def="0.0")
@EventHandler
public void onFoodLevelChange(FoodLevelChangeEvent event) {
final Player player = (Player) event.getEntity();
final double mod = config_.get("hunger_slowdown").getDouble();
Double saturation;
if (playerLastEat_.containsKey(player)) { // if the player just ate
saturation = playerLastEat_.get(player);
if (saturation == null) {
saturation = ((Float)player.getSaturation()).doubleValue();
}
} else {
saturation = Math.min(
player.getSaturation() + mod,
20.0D + (mod * 2.0D));
}
player.setSaturation(saturation.floatValue());
}
//Remove Book Copying
@BahHumbug(opt="copy_book_enable", def= "false")
public void removeBooks() {
if (config_.get("copy_book_enable").getBool()) {
return;
}
Iterator<Recipe> it = getServer().recipeIterator();
while (it.hasNext()) {
Recipe recipe = it.next();
ItemStack resulting_item = recipe.getResult();
if ( // !copy_book_enable_ &&
isWrittenBook(resulting_item)) {
it.remove();
info("Copying Books disabled");
}
}
}
public boolean isWrittenBook(ItemStack item) {
if (item == null) {
return false;
}
Material material = item.getType();
return material.equals(Material.WRITTEN_BOOK);
}
// Prevent tree growth wrap-around
@BahHumbug(opt="prevent_tree_wraparound", def="true")
@EventHandler(priority=EventPriority.LOWEST, ignoreCancelled = true)
public void onStructureGrowEvent(StructureGrowEvent event) {
if (!config_.get("prevent_tree_wraparound").getBool()) {
return;
}
int maxY = 0, minY = 257;
for (BlockState bs : event.getBlocks()) {
final int y = bs.getLocation().getBlockY();
maxY = Math.max(maxY, y);
minY = Math.min(minY, y);
}
if (maxY - minY > 240) {
event.setCancelled(true);
final Location loc = event.getLocation();
info(String.format("Prevented structure wrap-around at %d, %d, %d",
loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
}
// General
public void onLoad()
{
loadConfiguration();
//hookEnderPearls();
info("Loaded");
}
public void onEnable() {
registerEvents();
registerCommands();
removeRecipies();
removeBooks();
registerTimerForPearlCheck();
global_instance_ = this;
info("Enabled");
}
public void onDisable() {
if (config_.get("fix_vehicle_logout_bug").getBool()) {
for (World world: getServer().getWorlds()) {
for (Player player: world.getPlayers()) {
kickPlayerFromVehicle(player);
}
}
}
}
public boolean isInitiaized() {
return global_instance_ != null;
}
public boolean toBool(String value) {
if (value.equals("1") || value.equalsIgnoreCase("true")) {
return true;
}
return false;
}
public int toInt(String value, int default_value) {
try {
return Integer.parseInt(value);
} catch(Exception e) {
return default_value;
}
}
public double toDouble(String value, double default_value) {
try {
return Double.parseDouble(value);
} catch(Exception e) {
return default_value;
}
}
public int toMaterialId(String value, int default_value) {
try {
return Integer.parseInt(value);
} catch(Exception e) {
Material mat = Material.matchMaterial(value);
if (mat != null) {
return mat.getId();
}
}
return default_value;
}
public boolean onCommand(
CommandSender sender,
Command command,
String label,
String[] args) {
if (sender instanceof Player && command.getName().equals("invsee")) {
if (args.length < 1) {
sender.sendMessage("Provide a name");
return false;
}
onInvseeCommand((Player)sender, args[0]);
return true;
}
if (sender instanceof Player
&& command.getName().equals("introbook")) {
if (!config_.get("drop_newbie_book").getBool()) {
return true;
}
Player sendBookTo = (Player)sender;
if (args.length >= 1) {
Player possible = Bukkit.getPlayerExact(args[0]);
if (possible != null) {
sendBookTo = possible;
}
}
giveN00bBook(sendBookTo);
return true;
}
if (sender instanceof Player
&& command.getName().equals("bahhumbug")) {
giveHolidayPackage((Player)sender);
return true;
}
if (!(sender instanceof ConsoleCommandSender) ||
!command.getName().equals("humbug") ||
args.length < 1) {
return false;
}
String option = args[0];
String value = null;
String subvalue = null;
boolean set = false;
boolean subvalue_set = false;
String msg = "";
if (args.length > 1) {
value = args[1];
set = true;
}
if (args.length > 2) {
subvalue = args[2];
subvalue_set = true;
}
ConfigOption opt = config_.get(option);
if (opt != null) {
if (set) {
opt.set(value);
}
msg = String.format("%s = %s", option, opt.getString());
} else if (option.equals("debug")) {
if (set) {
config_.setDebug(toBool(value));
}
msg = String.format("debug = %s", config_.getDebug());
} else if (option.equals("loot_multiplier")) {
String entity_type = "generic";
if (set && subvalue_set) {
entity_type = value;
value = subvalue;
}
if (set) {
config_.setLootMultiplier(
entity_type, toInt(value, config_.getLootMultiplier(entity_type)));
}
msg = String.format(
"loot_multiplier(%s) = %d", entity_type, config_.getLootMultiplier(entity_type));
} else if (option.equals("remove_mob_drops")) {
if (set && subvalue_set) {
if (value.equals("add")) {
config_.addRemoveItemDrop(toMaterialId(subvalue, -1));
} else if (value.equals("del")) {
config_.removeRemoveItemDrop(toMaterialId(subvalue, -1));
}
}
msg = String.format("remove_mob_drops = %s", config_.toDisplayRemoveItemDrops());
} else if (option.equals("save")) {
config_.save();
msg = "Configuration saved";
} else if (option.equals("reload")) {
config_.reload();
msg = "Configuration loaded";
} else {
msg = String.format("Unknown option %s", option);
}
sender.sendMessage(msg);
return true;
}
public void registerCommands() {
ConsoleCommandSender console = getServer().getConsoleSender();
console.addAttachment(this, "humbug.console", true);
}
private void registerEvents() {
getServer().getPluginManager().registerEvents(this, this);
}
private void loadConfiguration() {
config_ = Config.initialize(this);
}
}
|
package de.bahr.order;
import de.bahr.DataStore;
import de.bahr.Http;
import de.bahr.SlackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@CrossOrigin
@RestController
@RequestMapping(value = "/order")
public class OrderController {
@Autowired
OrderRepository orderRepository;
@Autowired
DataStore dataStore;
@Autowired
SlackService slackService;
private static final double DELIVERY_FEE = 0.13;
private static final double PILOT_MARGIN = 0.8;
private static final String EVEPRAISAL_PATTERN = "http[s]?://(www\\.)?evepraisal\\.com/e/[0-9]*";
private static final String ID = "[a-z0-9]*";
private Pattern pattern = Pattern.compile(EVEPRAISAL_PATTERN);
private Pattern idPattern = Pattern.compile(ID);
@RequestMapping(value = "/lowitems", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> lowItems() {
List<Order> lowOrders = orderRepository.findAll().stream().filter(order -> null != order.getExpectedPrice() && order.getExpectedPrice() < 10000000.0).collect(Collectors.toList());
Map<String, Long> result = new HashMap<>();
for (Order order : lowOrders) {
List<Item> items = order.getItems();
for (Item item : items) {
String name = item.getName();
Long quantity = item.getQuantity();
if (result.containsKey(name)) {
result.put(name, result.get(name) + quantity);
} else {
result.put(name, quantity);
}
}
}
result = sortByValue(result);
return new ResponseEntity<>(result, HttpStatus.OK);
}
private static <K, V> Map<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> ((Comparable<V>) o1.getValue()).compareTo(o2.getValue()));
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
@RequestMapping(value = "/age", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> age(@RequestParam String id) {
// validate url
Matcher matcher = idPattern.matcher(id);
if (!matcher.matches()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Order order = orderRepository.findOne(id);
long age = calcAge(order.getCreated());
return new ResponseEntity<>("{ \"age\": \"" + age + "\"}", HttpStatus.OK);
}
private long calcAge(LocalDateTime created) {
long hours = LocalDateTime.now().until( created, ChronoUnit.HOURS);
return hours;
}
@RequestMapping(value = "/status", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> status(@RequestParam String id) {
// validate url
Matcher matcher = idPattern.matcher(id);
if (!matcher.matches()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Order order = orderRepository.findOne(id);
String status = order.getStatus();
return new ResponseEntity<>("{ \"status\": \"" + status + "\"}", HttpStatus.OK);
}
@RequestMapping(value = "/quote", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> quote(@RequestParam String link, @RequestParam Integer multiplier) {
// validate url
Matcher matcher = pattern.matcher(link);
if (!matcher.matches()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Long price;
// call url
try {
List<Item> items = requestItems(link);
price = calculateQuote(items);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("{ \"price\": " + ( price * multiplier ) + "}", HttpStatus.OK);
}
@RequestMapping(value = "/shippingprice", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> shippingPrice(@RequestParam String link) {
// validate url
Matcher matcher = pattern.matcher(link);
if (!matcher.matches()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Double shippingPrice;
// call url
try {
List<Item> items = requestItems(link);
Long stackPrice = calculateStackPrice(items);
// 0.13 for delivery service; 0.8 of that for the logistics pilot
// todo: assure that this is used in the frontend (it is not yet)
shippingPrice = stackPrice * DELIVERY_FEE * PILOT_MARGIN;
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("{ \"price\": " + shippingPrice.intValue() + "}", HttpStatus.OK);
}
@RequestMapping(value = "/create", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> create(@RequestBody Order order, @RequestParam Integer multiplier) {
// validate url
if (!isPraisalValid(order.getLink())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
// call url
List<Item> items;
try {
items = requestItems(order.getLink());
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
multiplyItems(multiplier, items);
order.setItems(items);
order.setStatus("requested");
Order savedOrder = orderRepository.save(order);
try {
slackService.sendNotification(order.getClient(), order.getExpectedPrice());
} catch (InterruptedException e) {
e.printStackTrace();
}
return new ResponseEntity<>(savedOrder, HttpStatus.OK);
}
protected void multiplyItems(@RequestParam Integer multiplier, List<Item> items) {
if (null != multiplier && multiplier > 1) {
for (Item item : items) {
item.setQuantity(item.getQuantity() * multiplier);
}
}
}
private boolean isPraisalValid(String link) {
Matcher matcher = pattern.matcher(link);
return matcher.matches();
}
private List<Item> requestItems(String link) throws Exception {
StringBuffer get = Http.getRequest(link, "GET");
String[] rawItems = extractRawItems(get);
return parseItems(rawItems);
}
private String[] extractRawItems(StringBuffer get) {
String html = get.toString();
String body = html.split("<body>")[1];
String resultContainer = body.split("<div class=\"span7\" id=\"result_container\">")[1];
String tableBody = resultContainer.split("<tbody>")[1].split("</tbody>")[0];
return tableBody.split("<tr class=\"line-item-row \">");
}
private Integer calculateSpaiShippingPrice(List<Item> items) {
Double totalPrice = 0.0;
for (Item item : items) {
Long price = item.getPrice();
Long quantity = item.getQuantity();
Double volume = item.getVolume();
double stackPrice = price * quantity;
double shippingCollateralFee = stackPrice * 0.02;
double stackVolume = volume * quantity;
double shippingVolumeFee = stackVolume * 300;
totalPrice += stackPrice + shippingCollateralFee + shippingVolumeFee;
}
return totalPrice.intValue();
}
private Long calculateQuote(List<Item> items) {
return (long) (calculateStackPrice(items) * (1 + DELIVERY_FEE));
}
private Long calculateStackPrice(List<Item> items) {
Long totalPrice = 0L;
for (Item item : items) {
Long price = Long.valueOf(item.getPrice());
Long quantity = Long.valueOf(item.getQuantity());
totalPrice += price * quantity;
}
return totalPrice;
}
private List<Item> parseItems(String[] rawItems) throws Exception {
List<Item> result = new ArrayList<>();
for (String rawItem : rawItems) {
if (!rawItem.replace(" ", "").isEmpty()) {
result.add(parseItem(rawItem));
}
}
return result;
}
private Item parseItem(String rawItem) throws Exception {
String rawQuantity = rawItem.split("<td style=\"text-align:right\">")[1].split("</td>")[0];
String itemName = rawItem.split("target=\"_blank\">")[2].split("</a>")[0];
itemName = itemName.replace("&
String rawItemPrice = rawItem.split("<span class=\"nowrap\">")[1].split("</span>")[0];
Long price = Double.valueOf(rawItemPrice.replace(",", "")).longValue();
Long quantity = Double.valueOf(rawQuantity.replace(",", "")).longValue();
Item item = dataStore.find(itemName);
Double volume = item.getVolume();
return new Item(itemName, quantity, volume, price);
}
}
|
package info.faceland.loot;
import info.faceland.api.FacePlugin;
import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration;
import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration;
import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings;
import info.faceland.loot.api.groups.ItemGroup;
import info.faceland.loot.api.items.ItemBuilder;
import info.faceland.loot.api.managers.ItemGroupManager;
import info.faceland.loot.api.managers.NameManager;
import info.faceland.loot.api.managers.TierManager;
import info.faceland.loot.api.tier.Tier;
import info.faceland.loot.api.tier.TierBuilder;
import info.faceland.loot.groups.LootItemGroup;
import info.faceland.loot.io.SmartTextFile;
import info.faceland.loot.items.LootItemBuilder;
import info.faceland.loot.managers.LootItemGroupManager;
import info.faceland.loot.managers.LootNameManager;
import info.faceland.loot.managers.LootTierManager;
import info.faceland.loot.tier.LootTierBuilder;
import info.faceland.loot.utils.converters.StringConverter;
import info.faceland.utils.TextUtils;
import net.nunnerycode.java.libraries.cannonball.DebugPrinter;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
public final class LootPlugin extends FacePlugin {
private DebugPrinter debugPrinter;
private VersionedIvoryYamlConfiguration itemsYAML;
private VersionedIvoryYamlConfiguration tierYAML;
private VersionedIvoryYamlConfiguration corestatsYAML;
private IvorySettings settings;
private ItemGroupManager itemGroupManager;
private TierManager tierManager;
private NameManager nameManager;
@Override
public void preEnable() {
debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log");
itemsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "items.yml"),
getResource("items.yml"),
VersionedIvoryConfiguration.VersionUpdateType
.BACKUP_AND_UPDATE);
if (itemsYAML.update()) {
getLogger().info("Updating items.yml");
debug("Updating items.yml");
}
tierYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "tier.yml"),
getResource("tier.yml"),
VersionedIvoryConfiguration.VersionUpdateType
.BACKUP_AND_UPDATE);
if (tierYAML.update()) {
getLogger().info("Updating tier.yml");
debug("Updating tier.yml");
}
corestatsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "corestats.yml"),
getResource("corestats.yml"),
VersionedIvoryConfiguration.VersionUpdateType
.BACKUP_AND_UPDATE);
if (corestatsYAML.update()) {
getLogger().info("Updating corestats.yml");
debug("Updating corestats.yml");
}
settings = IvorySettings.loadFromFiles(corestatsYAML);
itemGroupManager = new LootItemGroupManager();
tierManager = new LootTierManager();
nameManager = new LootNameManager();
}
@Override
public void enable() {
loadItemGroups();
loadTiers();
loadNames();
}
@Override
public void postEnable() {
debug("v" + getDescription().getVersion() + " enabled");
}
@Override
public void preDisable() {
}
@Override
public void disable() {
}
@Override
public void postDisable() {
nameManager = null;
tierManager = null;
itemGroupManager = null;
settings = null;
corestatsYAML = null;
tierYAML = null;
itemsYAML = null;
debugPrinter = null;
}
public void debug(String... messages) {
debug(Level.INFO, messages);
}
public void debug(Level level, String... messages) {
if (debugPrinter != null) {
debugPrinter.debug(level, messages);
}
}
private void loadNames() {
for (String s : getNameManager().getPrefixes()) {
getNameManager().removePrefix(s);
}
for (String s : getNameManager().getSuffixes()) {
getNameManager().removeSuffix(s);
}
SmartTextFile prefixFile = new SmartTextFile(new File(getDataFolder(), "prefix.txt"));
SmartTextFile suffixFile = new SmartTextFile(new File(getDataFolder(), "suffix.txt"));
for (String s : prefixFile.read()) {
getNameManager().addPrefix(s);
}
for (String s : suffixFile.read()) {
getNameManager().addSuffix(s);
}
debug("Loaded prefixes: " + getNameManager().getPrefixes().size(), "Loaded suffixes: " + getNameManager()
.getSuffixes().size());
}
private void loadItemGroups() {
for (ItemGroup ig : getItemGroupManager().getItemGroups()) {
getItemGroupManager().removeItemGroup(ig.getName());
}
Set<ItemGroup> itemGroups = new HashSet<>();
List<String> loadedItemGroups = new ArrayList<>();
for (String key : itemsYAML.getKeys(false)) {
if (!itemsYAML.isList(key)) {
continue;
}
List<String> list = itemsYAML.getStringList(key);
ItemGroup ig = new LootItemGroup(key, false);
for (String s : list) {
Material m = StringConverter.toMaterial(s);
if (m == Material.AIR) {
continue;
}
ig.addMaterial(m);
}
itemGroups.add(ig);
loadedItemGroups.add(key);
}
for (ItemGroup ig : itemGroups) {
getItemGroupManager().addItemGroup(ig);
}
debug("Loaded item groups: " + loadedItemGroups.toString());
}
private void loadTiers() {
for (Tier t : getTierManager().getLoadedTiers()) {
getTierManager().removeTier(t.getName());
}
Set<Tier> tiers = new HashSet<>();
List<String> loadedTiers = new ArrayList<>();
for (String key : tierYAML.getKeys(false)) {
if (!tierYAML.isConfigurationSection(key)) {
continue;
}
ConfigurationSection cs = tierYAML.getConfigurationSection(key);
TierBuilder builder = getNewTierBuilder(key);
builder.withDisplayName(cs.getString("display-name"));
builder.withDisplayColor(TextUtils.convertTag(cs.getString("display-color")));
builder.withIdentificationColor(TextUtils.convertTag(cs.getString("identification-color")));
builder.withSpawnWeight(cs.getDouble("spawn-weight"));
builder.withIdentifyWeight(cs.getDouble("identify-weight"));
builder.withDistanceWeight(cs.getDouble("distance-weight"));
builder.withMinimumSockets(cs.getInt("minimum-sockets"));
builder.withMaximumSockets(cs.getInt("maximum-sockets"));
builder.withMinimumBonusLore(cs.getInt("minimum-bonus-lore"));
builder.withMaximumBonusLore(cs.getInt("maximum-bonus-lore"));
builder.withBaseLore(cs.getStringList("base-lore"));
builder.withBonusLore(cs.getStringList("bonus-lore"));
List<String> sl = cs.getStringList("item-groups");
Set<ItemGroup> itemGroups = new HashSet<>();
for (String s : sl) {
ItemGroup ig;
if (s.startsWith("-")) {
ig = getItemGroupManager().getItemGroup(s.substring(1));
if (ig == null) {
continue;
}
ig = ig.getInverse();
} else {
ig = getItemGroupManager().getItemGroup(s);
if (ig == null) {
continue;
}
}
itemGroups.add(ig.getInverse());
}
builder.withItemGroups(itemGroups);
builder.withMinimumDurability(cs.getDouble("minimum-durability"));
builder.withMaximumDurability(cs.getDouble("maximum-durability"));
Tier t = builder.build();
loadedTiers.add(t.getName());
tiers.add(t);
}
for (Tier t : tiers) {
getTierManager().addTier(t);
}
debug("Loaded tiers: " + loadedTiers.toString());
}
public TierBuilder getNewTierBuilder(String name) {
return new LootTierBuilder(name);
}
public ItemBuilder getNewItemBuilder() {
return new LootItemBuilder(this);
}
public TierManager getTierManager() {
return tierManager;
}
public ItemGroupManager getItemGroupManager() {
return itemGroupManager;
}
public NameManager getNameManager() {
return nameManager;
}
public VersionedIvoryYamlConfiguration getCorestatsYAML() {
return corestatsYAML;
}
public IvorySettings getSettings() {
return settings;
}
}
|
package info.jayharris.cardgames;
public enum Suit {
CLUBS(Color.BLACK), DIAMONDS(Color.RED), SPADES(Color.BLACK), HEARTS(Color.RED);
public enum Color {
RED, BLACK;
public Color opposite() {
return this == Color.RED ? Color.BLACK : Color.RED;
}
}
public final Color color;
Suit(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return this.name().substring(0,1);
}
}
|
package infovis.embed;
import static infovis.VecUtil.*;
import infovis.ctrl.Controller;
import infovis.data.BusEdge;
import infovis.data.BusStation;
import infovis.data.BusStation.Route;
import infovis.data.BusTime;
import infovis.embed.pol.Interpolator;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Weights the station network after the distance from one start station.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public final class StationDistance implements Weighter, NodeDrawer {
/**
* The backing map for the spring nodes.
*/
private final Map<SpringNode, BusStation> map;
/**
* The reverse backing map for the spring nodes.
*/
private final Map<BusStation, SpringNode> rev;
/**
* The distances from the bus station.
*/
protected volatile Map<BusStation, Route> routes;
/**
* The current reference time.
*/
protected BusTime time = new BusTime(12, 0);
/**
* The change time for lines.
*/
protected int changeTime = 5;
/**
* The start bus station or <code>null</code> if there is none.
*/
protected BusStation from;
/**
* The factor to scale the distances.
*/
private double factor = .1;
/**
* The controller.
*/
private final Controller ctrl;
/**
* Creates a station distance without a reference station.
*
* @param ctrl The controller.
*/
public StationDistance(final Controller ctrl) {
this.ctrl = ctrl;
routes = new HashMap<BusStation, Route>();
map = new HashMap<SpringNode, BusStation>();
rev = new HashMap<BusStation, SpringNode>();
for(final BusStation s : ctrl.getStations()) {
final SpringNode node = new SpringNode();
node.setPosition(s.getDefaultX(), s.getDefaultY());
map.put(node, s);
rev.put(s, node);
}
}
/**
* The predicted next bus station.
*/
protected volatile BusStation predict;
/**
* The current waiter thread.
*/
protected volatile Thread currentCalculator;
/**
* The fading bus station.
*/
protected BusStation fadeOut;
/**
* The fading start time.
*/
protected long fadingStart;
/**
* The fading end time.
*/
protected long fadingEnd;
/**
* Whether we do fade currently.
*/
protected boolean fade;
/**
* Sets the values for the distance.
*
* @param from The reference station.
* @param time The reference time.
* @param changeTime The change time.
*/
public void set(final BusStation from, final BusTime time, final int changeTime) {
predict = from;
final Thread t = new Thread() {
@Override
public void run() {
final Map<BusStation, Route> route = new HashMap<BusStation, Route>();
if(from != null) {
final Collection<Route> routes = from.routes(time, changeTime);
for(final Route r : routes) {
route.put(r.getStation(), r);
}
}
synchronized(StationDistance.this) {
if(currentCalculator != this) return;
routes = route;
if(from != StationDistance.this.from) {
fadeOut = StationDistance.this.from;
fadingStart = System.currentTimeMillis();
fadingEnd = fadingStart + Interpolator.DURATION;
fade = true;
}
StationDistance.this.from = from;
StationDistance.this.time = time;
StationDistance.this.changeTime = changeTime;
changed = true;
}
}
};
t.setDaemon(true);
currentCalculator = t;
t.start();
}
/**
* Whether the weights have changed.
*/
protected volatile boolean changed;
@Override
public boolean hasChanged() {
final boolean res = changed;
changed = false;
return res;
}
/**
* Signals undefined changes.
*/
public void changeUndefined() {
set(from, time, changeTime);
}
/**
* Setter.
*
* @param from Sets the reference station.
*/
public void setFrom(final BusStation from) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The reference station.
*/
public BusStation getFrom() {
return from;
}
/**
* Setter.
*
* @param time Sets the reference time.
*/
public void setTime(final BusTime time) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The reference time.
*/
public BusTime getTime() {
return time;
}
/**
* Setter.
*
* @param changeTime Sets the change time.
*/
public void setChangeTime(final int changeTime) {
set(from, time, changeTime);
}
/**
* Getter.
*
* @return The change time.
*/
public int getChangeTime() {
return changeTime;
}
/**
* Setter.
*
* @param factor Sets the distance factor.
*/
public void setFactor(final double factor) {
this.factor = factor;
}
/**
* Getter.
*
* @return The distance factor.
*/
public double getFactor() {
return factor;
}
/**
* The minimal distance between nodes.
*/
private double minDist = 15;
/**
* Setter.
*
* @param minDist Sets the minimal distance between nodes.
*/
public void setMinDist(final double minDist) {
this.minDist = minDist;
}
/**
* Getter.
*
* @return The minimal distance between nodes.
*/
public double getMinDist() {
return minDist;
}
@Override
public double weight(final SpringNode f, final SpringNode t) {
if(from == null || t == f) return 0;
final BusStation fr = map.get(f);
if(fr.equals(from)) return 0;
final BusStation to = map.get(t);
if(to.equals(from)) {
final Integer d = routes.get(fr).minutes();
if(d == null) return 0;
return factor * d;
}
return -minDist;
}
@Override
public boolean hasWeight(final SpringNode f, final SpringNode t) {
if(from == null || t == f) return false;
final BusStation fr = map.get(f);
if(fr.equals(from)) return false;
final BusStation to = map.get(t);
if(to.equals(from)) return !routes.get(fr).isNotReachable();
return true;
}
@Override
public Iterable<SpringNode> nodes() {
return map.keySet();
}
@Override
public double springConstant() {
return 0.75;
}
@Override
public void drawNode(final Graphics2D g, final SpringNode n) {
final BusStation station = map.get(n);
if(from != null) {
routes.get(station).getFrom();
}
final Route route = routes.get(station);
if(route != null && route.isNotReachable()) return;
final double x1 = n.getX();
final double y1 = n.getY();
// edge
for(final BusEdge edge : station.getEdges(getTime())) {
final SpringNode node = rev.get(edge.getTo());
final double x2 = node.getX();
final double y2 = node.getY();
g.setColor(edge.getLine().getColor());
g.draw(new Line2D.Double(x1, y1, x2, y2));
}
g.setColor(!station.equals(from) ? Color.BLUE : Color.RED);
g.fill(nodeClickArea(n));
final Graphics2D gfx = (Graphics2D) g.create();
gfx.setColor(Color.BLACK);
gfx.translate(x1, y1);
gfx.drawString(station.getName(), 0, 0);
gfx.dispose();
}
@Override
public void dragNode(final SpringNode n, final double startX, final double startY,
final double dx, final double dy) {
n.setPosition(startX + dx, startY + dy);
}
@Override
public void selectNode(final SpringNode n) {
final BusStation station = map.get(n);
if(!station.equals(from)) {
ctrl.selectStation(station);
}
}
@Override
public Shape nodeClickArea(final SpringNode n) {
return new Ellipse2D.Double(n.getX() - 5, n.getY() - 5, 10, 10);
}
@Override
public void drawBackground(final Graphics2D g) {
final SpringNode ref = getReferenceNode();
if(ref == null && !fade) return;
Point2D center;
Color col;
if(fade) {
final long time = System.currentTimeMillis();
final double t = ((double) time - fadingStart) / ((double) fadingEnd - fadingStart);
final double f = Interpolator.INTERPOLATOR.interpolate(t);
final SpringNode n = f > 0.5 ? ref : rev.get(fadeOut);
center = n != null ? n.getPos() : null;
final double split = f > 0.5 ? (f - 0.5) * 2 : 1 - f * 2;
final int alpha = Math.max(0, Math.min((int) (split * 255), 255));
col = new Color(alpha << 24
| (Color.LIGHT_GRAY.getRGB() & 0x00ffffff), true);
if(t >= 1.0) {
fadeOut = null;
fade = false;
}
} else {
center = ref.getPos();
col = Color.LIGHT_GRAY;
}
if(center == null) return;
boolean b = true;
for(int i = MAX_INTERVAL; i > 0; --i) {
final Shape circ = getCircle(i, center);
g.setColor(b ? col : Color.WHITE);
b = !b;
g.fill(circ);
}
}
/**
* The highest drawn circle interval.
*/
public static final int MAX_INTERVAL = 12;
/**
* Getter.
*
* @param i The interval.
* @param center The center of the circle.
* @return The circle.
*/
public Ellipse2D getCircle(final int i, final Point2D center) {
final Point2D c = center != null ? center : getReferenceNode().getPos();
final double radius = factor * 5 * i;
final double r2 = radius * 2;
return new Ellipse2D.Double(c.getX() - radius, c.getY() - radius, r2, r2);
}
@Override
public Point2D getDefaultPosition(final SpringNode node) {
final BusStation station = map.get(node);
return new Point2D.Double(station.getDefaultX(), station.getDefaultY());
}
@Override
public SpringNode getReferenceNode() {
return from == null ? null : rev.get(from);
}
@Override
public String getTooltipText(final SpringNode node) {
final BusStation station = map.get(node);
String dist;
if(from != null && from != station) {
final Route route = routes.get(station);
if(!route.isNotReachable()) {
dist = " (" + BusTime.minutesToString(route.minutes()) + ")";
} else {
dist = " (not reachable)";
}
} else {
dist = "";
}
return station.getName() + dist;
}
@Override
public void moveMouse(final Point2D cur) {
if(from != null) {
ctrl.setTitle(BusTime.minutesToString((int) Math.ceil(getLength(subVec(cur,
getReferenceNode().getPos())) / factor)));
} else {
ctrl.setTitle(null);
}
}
/**
* Getter.
*
* @return The predicted next bus station.
*/
public BusStation getPredict() {
return predict;
}
/**
* Getter.
*
* @param station The station.
* @return The corresponding node.
*/
public SpringNode getNode(final BusStation station) {
return station == null ? null : rev.get(station);
}
}
|
package io;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.zip.GZIPOutputStream;
import org.janelia.saalfeldlab.n5.DataType;
import org.janelia.saalfeldlab.n5.DatasetAttributes;
import org.janelia.saalfeldlab.n5.N5Reader;
import org.janelia.saalfeldlab.n5.hdf5.N5HDF5Reader;
import org.janelia.saalfeldlab.n5.imglib2.N5Utils;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import ij.IJ;
import ij.ImagePlus;
import ij.io.FileInfo;
import ij.measure.Calibration;
import io.nii.NiftiIo;
import loci.formats.FormatException;
import net.imglib2.Cursor;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.RealLocalizable;
import net.imglib2.RealPoint;
import net.imglib2.RealPositionable;
import net.imglib2.converter.Converter;
import net.imglib2.converter.Converters;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.realtransform.AffineGet;
import net.imglib2.realtransform.AffineTransform;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.realtransform.ants.ANTSLoadAffine;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.util.Util;
import net.imglib2.view.Views;
import net.imglib2.view.composite.CompositeIntervalView;
import net.imglib2.view.composite.GenericComposite;
import sc.fiji.io.Dfield_Nrrd_Reader;
import sc.fiji.io.Dfield_Nrrd_Writer;
public class WriteNrrdDisplacementField {
public static class Options implements Serializable
{
private static final long serialVersionUID = -5666039337474416226L;
@Option( name = "-d", aliases = {"--dfield"}, required = true, usage = "" )
private String field;
@Option( name = "-o", aliases = {"--output"}, required = true, usage = "" )
private String output;
@Option( name = "-i", aliases = {"--inverse"}, required = false, usage = "" )
private boolean isInverse = false;
@Option( name = "-a", aliases = {"--affine"}, required = false, usage = "" )
private String affine = "";
@Option( name = "-e", aliases = {"--encoding"}, required = false, usage = "" )
private String encoding = "raw";
@Option( name = "--affineFirst", required = false, usage = "" )
private boolean isAffineFirst = false;
public Options(final String[] args) {
final CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
} catch (final CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
}
}
/**
* @return is this an inverse transform
*/
public boolean isInverse()
{
return isInverse;
}
/**
* @return is this an inverse transform
*/
public boolean affineFirst()
{
return isAffineFirst;
}
/**
* @return output path
*/
public String getOutput()
{
return output;
}
/**
* @return output path
*/
public String getField()
{
return field;
}
/**
* @return affine File
*/
public String getAffine() {
return affine;
}
/**
* @return nrrd encoding
*/
public String getEncoding() {
return encoding;
}
}
public static void main(String[] args) throws FormatException, IOException
{
final Options options = new Options(args);
String imF = options.getField();
String fout = options.getOutput();
String affineFile = options.getAffine();
String nrrdEncoding = options.getEncoding();
boolean invert = options.isInverse();
boolean affineFirst = options.affineFirst();
AffineGet affine = null;
if( !affineFile.isEmpty() )
affine = loadAffine( affineFile, invert );
if( imF.endsWith("h5"))
{
System.out.println( "N5" );
N5Reader n5 = new N5HDF5Reader( imF, 3, 32, 32, 32 );
writeImage( n5, affine, affineFirst, nrrdEncoding, new File( fout ));
return;
}
ImagePlus baseIp = null;
if( imF.endsWith( "nii" ))
{
try
{
baseIp = NiftiIo.readNifti( new File( imF ) );
} catch ( FormatException e )
{
e.printStackTrace();
} catch ( IOException e )
{
e.printStackTrace();
}
}
else if( imF.endsWith( "nrrd" ))
{
// This will never work since the Nrrd_Reader can't handle 4d volumes, actually
Dfield_Nrrd_Reader nr = new Dfield_Nrrd_Reader();
File imFile = new File( imF );
baseIp = nr.load( imFile.getParent(), imFile.getName());
}
else
{
baseIp = IJ.openImage( imF );
}
// final long[] subsample_factors = new long[]{ 4, 4, 4, 1 };
final long[] subsample_factors = new long[]{ 1, 1, 1, 1 };
System.out.println("ip: " + baseIp);
writeImage( baseIp, affine, affineFirst, nrrdEncoding,
subsample_factors, new File( fout ));
}
@SuppressWarnings("unchecked")
public static void writeImage(final N5Reader n5, final AffineGet affine,
final boolean affineFirst, final String nrrdEncoding,
final File outFile )
throws IOException
{
long[] subsample_factors = null;
RandomAccessibleInterval<?> img = N5Utils.open(n5, "/dfield");
DatasetAttributes attr = n5.getDatasetAttributes("dfield");
DataType type = attr.getDataType();
HashMap<String, Object> attrMap = n5.getDatasetAttributes("dfield").asMap();
double[] spacing;
if( attrMap.containsKey("spacing"))
spacing= (double[])attrMap.get("spacing");
else
spacing = new double[]{ 1, 1, 1 };
double m = 1;
if( attrMap.containsKey("multiplier"))
m = (double)(attrMap.get("multiplier"));
System.out.println( "multiplier: " + m );
RandomAccessibleInterval<FloatType> write_me = null;
if( type.equals( DataType.INT16 ))
{
write_me = toFloat( (RandomAccessibleInterval<ShortType>)img, m );
}
else if( type.equals( DataType.FLOAT32 ) )
{
write_me = (RandomAccessibleInterval<FloatType>)img;
}
else
{
System.err.println("CURRENTLY ONLY WORKS FOR FLOAT AND SIGNED-SHORT");
return;
}
FileOutputStream out = new FileOutputStream( outFile );
// First write out the full header
Writer bw = new BufferedWriter(new OutputStreamWriter(out));
long[] dims = new long[img.numDimensions()];
img.dimensions(dims);
String nrrdHeader = makeDisplacementFieldHeader(
img.numDimensions(),
"float", "raw", true,
dims, spacing, subsample_factors );
// Blank line terminates header
bw.write( nrrdHeader + "\n" );
// Flush rather than close
bw.flush();
OutputStream dataStream;
if(nrrdEncoding.equals("gzip")) {
dataStream = new GZIPOutputStream(new BufferedOutputStream( out ));
}
else
{
dataStream = out;
}
if( affine == null )
{
dumpFloatImg( write_me, subsample_factors, false, dataStream );
}
else
{
dumpFloatImg( write_me, affine, affineFirst, spacing, dataStream );
}
}
public static <T extends RealType<T>> RandomAccessibleInterval<FloatType> toFloat( RandomAccessibleInterval<T> img, double m )
{
return Converters.convert(
img,
new Converter<T, FloatType>()
{
@Override
public void convert( T input, FloatType output) {
output.setReal( input.getRealDouble() * m );
}
},
new FloatType());
}
public static void writeImage(final ImagePlus ip, final AffineGet affine,
final boolean affineFirst, final String nrrdEncoding,
final long[] subsample_factors,
final File outFile )
throws IOException
{
FileInfo fi = ip.getFileInfo();
String nrrdHeader = makeDisplacementFieldHeader( ip, subsample_factors, nrrdEncoding );
if( nrrdHeader == null )
{
System.err.println("Failed");
return;
}
FileOutputStream out = new FileOutputStream( outFile );
// First write out the full header
Writer bw = new BufferedWriter(new OutputStreamWriter(out));
// Note, right now this is the only way compression that is implemented
if(nrrdEncoding.equals("gzip"))
fi.compression=GZIP;
// Blank line terminates header
bw.write( nrrdHeader + "\n" );
// Flush rather than close
bw.flush();
// Then the image data
if(nrrdEncoding.equals("gzip")) {
GZIPOutputStream zStream = new GZIPOutputStream(new BufferedOutputStream( out ));
if( affine != null )
dumpFloatImg( ip, affine, affineFirst, zStream );
else
dumpFloatImg( ip, subsample_factors, true, zStream );
zStream.flush();
zStream.close();
} else {
if( affine != null )
dumpFloatImg( ip, affine, affineFirst, out );
else
dumpFloatImg( ip, subsample_factors, true, out );
out.flush();
out.close();
}
}
public static AffineGet loadAffine( String filePath, boolean invert ) throws IOException
{
if( filePath.endsWith( "mat" ))
{
try
{
AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath );
if( invert )
{
System.out.println("inverting");
System.out.println( "xfm: " + xfm );
return xfm.inverse().copy();
}
return xfm;
} catch ( IOException e )
{
e.printStackTrace();
}
}
else if( filePath.endsWith( "txt" ))
{
if( Files.readAllLines( Paths.get( filePath ) ).get( 0 ).startsWith( "#Insight Transform File" ))
{
System.out.println("Reading itk transform file");
try
{
AffineTransform3D xfm = ANTSLoadAffine.loadAffine( filePath );
if( invert )
{
System.out.println("inverting");
return xfm.inverse().copy();
}
return xfm;
} catch ( IOException e )
{
e.printStackTrace();
}
}
else
{
System.out.println("Reading imglib2 transform file");
try
{
AffineTransform xfm = AffineImglib2IO.readXfm( 3, new File( filePath ) );
System.out.println( Arrays.toString(xfm.getRowPackedCopy() ));
if( invert )
{
System.out.println("inverting");
return xfm.inverse().copy();
}
return xfm;
} catch ( IOException e )
{
e.printStackTrace();
}
}
}
return null;
}
public static void dumpFloatImg(
final RandomAccessibleInterval<FloatType> img,
final long[] subsample_factors,
final boolean permute,
final OutputStream out ) throws IOException
{
RandomAccessibleInterval<FloatType> imgToPermute;
DataOutputStream dout = new DataOutputStream( out );
if( subsample_factors != null )
{
imgToPermute = Views.subsample( img, subsample_factors );
}
else
{
imgToPermute = img;
}
System.out.println("img size: " + Util.printInterval(img));
System.out.println("imgToPermute size: " + Util.printInterval(imgToPermute));
RandomAccessibleInterval<FloatType> img_perm;
if( permute )
img_perm = Views.permute( Views.permute( Views.permute( imgToPermute, 0, 3 ), 1, 3 ), 2, 3 );
else
img_perm = imgToPermute;
System.out.println("img size: " + Util.printInterval(img));
System.out.println("imgToPermute size: " + Util.printInterval(imgToPermute));
System.out.println("img_perm size: " + Util.printInterval(img_perm));
Cursor<FloatType> c = Views.flatIterable( img_perm ).cursor();
while( c.hasNext() )
{
c.fwd();
//System.out.println( Util.printCoordinates( c ));
dout.writeFloat( c.get().getRealFloat() );
}
dout.flush();
dout.close();
System.out.println( "Wrote " + dout.size() + " bytes." );
}
public static void dumpFloatImg(
final ImagePlus ip,
final long[] subsample_factors,
final boolean permute,
final OutputStream out ) throws IOException
{
final Img<FloatType> img = ImageJFunctions.wrapFloat( ip );
dumpFloatImg(img, subsample_factors, permute, out );
}
public static void dumpFloatImg( final ImagePlus ip, final AffineGet affine,
final boolean affineFirst,
final OutputStream out ) throws IOException
{
final Img<FloatType> img = ImageJFunctions.wrapFloat( ip );
double[] pixelSpacing = new double[]{
ip.getCalibration().pixelWidth,
ip.getCalibration().pixelHeight,
ip.getCalibration().pixelDepth
};
dumpFloatImg( img, affine, affineFirst, pixelSpacing, out );
}
public static void dumpFloatImg( final RandomAccessibleInterval<FloatType> img,
final AffineGet affine,
final boolean affineFirst, final double[] pixelSpacing,
final OutputStream out ) throws IOException
{
DataOutputStream dout = new DataOutputStream( out );
CompositeIntervalView<FloatType, ? extends GenericComposite<FloatType>> img_col = Views.collapse( img );
AffineTransform3D pix2Physical = new AffineTransform3D();
pix2Physical.set( pixelSpacing[0], 0, 0 );
pix2Physical.set( pixelSpacing[1], 1, 1 );
pix2Physical.set( pixelSpacing[2], 2, 2 );
RealPoint pix = new RealPoint( 3 );
RealPoint p = new RealPoint( 3 );
RealPoint q = new RealPoint( 3 );
RealPoint result = new RealPoint( 3 );
Cursor<? extends GenericComposite<FloatType>> c = Views.flatIterable( img_col ).cursor();
while( c.hasNext() )
{
c.fwd();
pix.setPosition( c.getIntPosition( 0 ), 0 );
pix.setPosition( c.getIntPosition( 1 ), 1 );
pix.setPosition( c.getIntPosition( 2 ), 2 );
// if( c.getIntPosition(0) == 100 &&
// c.getIntPosition(1) == 30 &&./x
// c.getIntPosition(2) == 40 )
// System.out.println("HERE");
pix2Physical.apply( pix, p );
if( affineFirst )
{
affine.apply( p, q );
displacePoint( q, c.get(), result );
}
else
{
displacePoint( p, c.get(), q );
affine.apply( q, result );
}
// the point 'q' must hold
getDisplacement( p, result, q );
dout.writeFloat( q.getFloatPosition( 0 ) );
dout.writeFloat( q.getFloatPosition( 1 ) );
dout.writeFloat( q.getFloatPosition( 2 ) );
}
dout.flush();
dout.close();
System.out.println( "Wrote " + dout.size() + " bytes." );
}
/**
* Only works for 3D
* @param p must be 3D
* @param destination
* @param vec
*/
public static <C extends GenericComposite<FloatType>> void displacePoint( RealPoint p, C vec , RealPositionable destination)
{
destination.setPosition( p.getDoublePosition(0) + vec.get(0).getRealDouble(), 0 );
destination.setPosition( p.getDoublePosition(1) + vec.get(1).getRealDouble(), 1 );
destination.setPosition( p.getDoublePosition(2) + vec.get(2).getRealDouble(), 2 );
}
/**
* Only works for 3D
* @param p must be 3D
* @param destination
* @param vec
*/
public static <C extends GenericComposite<FloatType>> void getDisplacement(
RealLocalizable currentPosition, RealLocalizable destinationPosition, RealPositionable output )
{
// output.setPosition( currentPosition.getDoublePosition(0) - destinationPosition.getDoublePosition(0), 0 );
// output.setPosition( currentPosition.getDoublePosition(1) - destinationPosition.getDoublePosition(1), 1 );
// output.setPosition( currentPosition.getDoublePosition(2) - destinationPosition.getDoublePosition(2), 2 );
output.setPosition( destinationPosition.getDoublePosition(0) - currentPosition.getDoublePosition(0), 0 );
output.setPosition( destinationPosition.getDoublePosition(1) - currentPosition.getDoublePosition(1), 1 );
output.setPosition( destinationPosition.getDoublePosition(2) - currentPosition.getDoublePosition(2), 2 );
}
public static String makeDisplacementFieldHeader(
int dimension,
String type,
String encoding,
boolean little_endian,
long[] size,
double[] pixel_spacing,
long[] subsample_factors )
{
System.out.println("Nrrd_Writer makeDisplacementFieldHeader");
if( dimension != 4 )
return null;
StringWriter out=new StringWriter();
out.write("NRRD0004\n");
out.write("
// Fetch and write the data type
out.write("type: "+ type +"\n");
// write dimensionality
out.write("dimension: "+dimension+"\n");
// Fetch and write the encoding
out.write("encoding: "+ encoding +"\n");
out.write("space: right-anterior-superior\n");
if( subsample_factors != null )
{
out.write(dimmedLine("sizes",dimension,"3",
size[0] / subsample_factors[0]+"",
size[1] / subsample_factors[1]+"",
size[2] / subsample_factors[2]+""));
//out.write("space dimension"+dimension+"\n");
out.write(dimmedLine("space directions", dimension, "none",
"("+subsample_factors[0] * pixel_spacing[0]+",0,0)",
"(0,"+subsample_factors[1] * pixel_spacing[1]+",0)",
"(0,0,"+subsample_factors[2] * pixel_spacing[2]+")"));
}
else
{
out.write(dimmedLine("sizes",dimension,
size[0] + "",
size[1] + "",
size[2] + "",
size[3] + ""));
//out.write("space dimension"+dimension+"\n");
out.write(dimmedLine("space directions", dimension, "none",
"("+ pixel_spacing[0]+",0,0)",
"(0,"+ pixel_spacing[1]+",0)",
"(0,0,"+ pixel_spacing[2]+")"));
}
out.write("kinds: vector domain domain domain\n");
out.write("labels: \"Vx;Vy;Vz\" \"x\" \"y\" \"z\"\n");
if( little_endian ) out.write("endian: little\n");
else out.write("endian: big\n");
out.write("space origin: (0,0,0)\n");
return out.toString();
}
public static String makeDisplacementFieldHeader( ImagePlus ip, long[] subsample_factors, String encoding )
{
System.out.println("Nrrd_Writer makeDisplacementFieldHeader");
FileInfo fi = ip.getFileInfo();
Calibration cal = ip.getCalibration();
int dimension = ip.getNDimensions();
if( dimension != 4 )
return null;
System.out.println( "nrrd nc: " + ip.getNChannels() );
System.out.println( "nrrd nz: " + ip.getNSlices() );
System.out.println( "nrrd nt: " + ip.getNFrames() );
boolean channels = true;
if( ip.getNChannels() == 3 && ip.getNFrames() == 1)
{
channels = true;
}
else if( ip.getNChannels() == 1 && ip.getNFrames() == 3 )
{
channels = false;
}
else
{
System.err.println("Either NChannels or NFrames must equal 3");
return null;
}
StringWriter out=new StringWriter();
out.write("NRRD0004\n");
out.write("
// Fetch and write the data type
out.write("type: "+Dfield_Nrrd_Writer.imgType(fi.fileType)+"\n");
// write dimensionality
out.write("dimension: "+dimension+"\n");
// Fetch and write the encoding
out.write("encoding: "+ encoding +"\n");
out.write("space: right-anterior-superior\n");
out.write(dimmedLine("sizes",dimension,"3",
fi.width/subsample_factors[0]+"",
fi.height/subsample_factors[1]+"",
ip.getNSlices()/subsample_factors[2]+""));
if(cal!=null){
//out.write("space dimension"+dimension+"\n");
out.write(dimmedLine("space directions", dimension, "none",
"("+subsample_factors[0]*cal.pixelWidth+",0,0)",
"(0,"+subsample_factors[1]*cal.pixelHeight+",0)",
"(0,0,"+subsample_factors[2]*cal.pixelDepth+")"));
}
out.write("kinds: vector domain domain domain\n");
out.write("labels: \"Vx;Vy;Vz\" \"x\" \"y\" \"z\"\n");
if(fi.intelByteOrder) out.write("endian: little\n");
else out.write("endian: big\n");
out.write("space origin: (0,0,0)\n");
return out.toString();
}
private static String dimmedLine(String tag,int dimension,String x1,String x2,String x3,String x4) {
String rval=null;
if(dimension==2) rval=tag+": "+x1+" "+x2+"\n";
else if(dimension==3) rval=tag+": "+x1+" "+x2+" "+x3+"\n";
else if(dimension==4) rval=tag+": "+x1+" "+x2+" "+x3+" "+x4+"\n";
return rval;
}
// Additional compression modes for fi.compression
public static final int GZIP = 1001;
public static final int ZLIB = 1002;
public static final int BZIP2 = 1003;
// Additional file formats for fi.fileFormat
public static final int NRRD = 1001;
public static final int NRRD_TEXT = 1002;
public static final int NRRD_HEX = 1003;
}
|
package io.cfp.api;
import io.cfp.domain.exception.ForbiddenException;
import io.cfp.model.Role;
import io.cfp.mapper.CommentMapper;
import io.cfp.mapper.ProposalMapper;
import io.cfp.model.Comment;
import io.cfp.model.Proposal;
import io.cfp.model.User;
import io.cfp.model.queries.CommentQuery;
import io.cfp.multitenant.TenantId;
import io.cfp.service.email.EmailingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.Date;
import static io.cfp.model.Role.REVIEWER;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
@RestController
@RequestMapping(value = { "/v1/proposals/{proposalId}/comments", "/api/proposals/{proposalId}/comments" }, produces = APPLICATION_JSON_UTF8_VALUE)
public class CommentsController {
private static final Logger LOGGER = LoggerFactory.getLogger(CommentsController.class);
@Autowired
private CommentMapper comments;
@Autowired
private ProposalMapper proposals;
@Autowired
private EmailingService emailingService;
@GetMapping
@Secured(Role.AUTHENTICATED)
public Collection<Comment> all(@AuthenticationPrincipal User user,
@PathVariable int proposalId,
@TenantId String eventId) {
LOGGER.info("Get comments of proposal {}", proposalId);
CommentQuery query = new CommentQuery();
query.setEventId(eventId);
query.setProposalId(proposalId);
if (!user.hasRole(REVIEWER)) {
query.setInternal(false);
// FIXME speaker should not be able to read comments on other's proposals
}
return comments.findAll(query);
}
@PostMapping
@Transactional
@Secured(Role.AUTHENTICATED)
@ResponseStatus(HttpStatus.CREATED)
public Comment create(@AuthenticationPrincipal User user,
@PathVariable int proposalId,
@RequestBody Comment comment,
@TenantId String eventId) {
Proposal proposal = proposals.findById(proposalId, eventId);
// si on est pas reviewer, on ne peut poster de commentaires que sur son propre proposal
if (!user.hasRole(Role.REVIEWER)) {
if (proposal.getSpeaker().getId() != user.getId()) {
throw new ForbiddenException("Vous n'êtes pas autorisé à commenter le Proposal "+proposalId);
}
}
LOGGER.info("User {} add a comment on proposal {}", user.getId(), proposalId);
comment.setEventId(eventId);
comment.setUser(user);
comment.setProposalId(proposalId);
comment.setAdded(new Date());
comments.insert(comment);
if (comment.isInternal()) {
emailingService.sendNewCommentToAdmins(user, proposal, comment.getComment());
} else {
if (user.getEmail().equals(proposal.getSpeaker().getEmail())) {
emailingService.sendNewCommentToAdmins(user, proposal, comment.getComment());
} else {
emailingService.sendNewCommentToSpeaker(user, proposal, comment.getComment());
}
}
return comment;
}
@PutMapping(value = "/{id}")
@Transactional
@Secured(Role.AUTHENTICATED)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable int proposalId,
@PathVariable int id,
@AuthenticationPrincipal User user,
@RequestBody Comment comment,
@TenantId String eventId) {
LOGGER.info("User {} update its comment on proposal {}", user.getId(), proposalId);
Proposal proposal = proposals.findById(proposalId, eventId);
comment.setId(id);
comment.setEventId(eventId);
comment.setUser(user);
comment.setProposalId(proposalId);
if (!user.hasRole(REVIEWER)) {
comment.setInternal(false);
}
comments.update(comment);
if (comment.isInternal()) {
emailingService.sendNewCommentToAdmins(user, proposal, comment.getComment());
} else {
if (user.getEmail().equals(proposal.getSpeaker().getEmail())) {
emailingService.sendNewCommentToAdmins(user, proposal, comment.getComment());
} else {
emailingService.sendNewCommentToSpeaker(user, proposal, comment.getComment());
}
}
}
@DeleteMapping(value = "/{id}")
@Transactional
@Secured(Role.AUTHENTICATED)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable int proposalId,
@PathVariable int id,
@AuthenticationPrincipal User user,
@TenantId String eventId) {
LOGGER.info("User {} delete its comment", user.getId());
Comment comment = new Comment();
comment.setId(id);
comment.setUser(user);
comment.setEventId(eventId);
comment.setProposalId(proposalId);
comments.delete(comment);
}
}
|
package io.kaitai.struct;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public class KaitaiStream {
private KaitaiSeekableStream st;
/**
* Initializes a stream, reading from a local file with specified fileName. Internally, RandomAccessFile would be
* used to allow seeking within the stream and reading arbitrary bytes.
* @param fileName file to read
* @throws FileNotFoundException
*/
public KaitaiStream(String fileName) throws FileNotFoundException {
st = new RAFWrapper(fileName, "r");
}
/**
* Initializes a stream that will get data from given byte array when read. Internally, ByteArrayInputStream will
* be used.
* @param arr byte array to read
*/
public KaitaiStream(byte[] arr) {
st = new BAISWrapper(arr);
}
/**
* Closes the stream safely. If there was an open file associated with it, closes that file.
* For streams that were reading from in-memory array, does nothing.
*/
public void close() throws IOException {
st.close();
}
//region Stream positioning
/**
* Check if stream pointer is at the end of stream.
* @return true if we are located at the end of the stream
* @throws IOException
*/
public boolean isEof() throws IOException {
return st.isEof();
}
/**
* Set stream pointer to designated position.
* @param newPos new position (offset in bytes from the beginning of the stream)
* @throws IOException
*/
public void seek(long newPos) throws IOException {
st.seek(newPos);
}
/**
* Get current position of a stream pointer.
* @return pointer position, number of bytes from the beginning of the stream
* @throws IOException
*/
public long pos() throws IOException {
return st.pos();
}
/**
* Get total size of the stream in bytes.
* @return size of the stream in bytes
* @throws IOException
*/
public long size() throws IOException {
return st.size();
}
//endregion
//region Integer numbers
//region Signed
/**
* Reads one signed 1-byte integer, returning it properly as Java's "byte" type.
* @return 1-byte integer read from a stream
* @throws IOException
*/
public byte readS1() throws IOException {
int t = st.read();
if (t < 0) {
throw new EOFException();
} else {
return (byte) t;
}
}
//region Big-endian
public short readS2be() throws IOException {
int b1 = st.read();
int b2 = st.read();
if ((b1 | b2) < 0) {
throw new EOFException();
} else {
return (short) ((b1 << 8) + (b2 << 0));
}
}
public int readS4be() throws IOException {
int b1 = st.read();
int b2 = st.read();
int b3 = st.read();
int b4 = st.read();
if ((b1 | b2 | b3 | b4) < 0) {
throw new EOFException();
} else {
return (b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0);
}
}
public long readS8be() throws IOException {
long b1 = readU4be();
long b2 = readU4be();
return (b1 << 32) + (b2 << 0);
}
//endregion
//region Little-endian
public short readS2le() throws IOException {
int b1 = st.read();
int b2 = st.read();
if ((b1 | b2) < 0) {
throw new EOFException();
} else {
return (short) ((b2 << 8) + (b1 << 0));
}
}
public int readS4le() throws IOException {
int b1 = st.read();
int b2 = st.read();
int b3 = st.read();
int b4 = st.read();
if ((b1 | b2 | b3 | b4) < 0) {
throw new EOFException();
} else {
return (b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0);
}
}
public long readS8le() throws IOException {
long b1 = readU4le();
long b2 = readU4le();
return (b2 << 32) + (b1 << 0);
}
//endregion
//endregion
//region Unsigned
public int readU1() throws IOException {
int t = st.read();
if (t < 0) {
throw new EOFException();
} else {
return t;
}
}
//region Big-endian
public int readU2be() throws IOException {
int b1 = st.read();
int b2 = st.read();
if ((b1 | b2) < 0) {
throw new EOFException();
} else {
return (b1 << 8) + (b2 << 0);
}
}
public long readU4be() throws IOException {
long b1 = st.read();
long b2 = st.read();
long b3 = st.read();
long b4 = st.read();
if ((b1 | b2 | b3 | b4) < 0) {
throw new EOFException();
} else {
return (b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0);
}
}
public long readU8be() throws IOException {
return readS8be();
}
//endregion
//region Little-endian
public int readU2le() throws IOException {
int b1 = st.read();
int b2 = st.read();
if ((b1 | b2) < 0) {
throw new EOFException();
} else {
return (b2 << 8) + (b1 << 0);
}
}
public long readU4le() throws IOException {
long b1 = st.read();
long b2 = st.read();
long b3 = st.read();
long b4 = st.read();
if ((b1 | b2 | b3 | b4) < 0) {
throw new EOFException();
} else {
return (b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0);
}
}
public long readU8le() throws IOException {
return readS8le();
}
//endregion
//endregion
//endregion
//region Floating point numbers
//region Big-endian
public float readF4be() throws IOException {
return wrapBufferBe(4).getFloat();
}
public double readF8be() throws IOException {
return wrapBufferBe(8).getDouble();
}
//endregion
//region Little-endian
public float readF4le() throws IOException {
return wrapBufferLe(4).getFloat();
}
public double readF8le() throws IOException {
return wrapBufferLe(8).getDouble();
}
//endregion
//endregion
//region Byte arrays
/**
* Reads designated number of bytes from the stream.
* @param n number of bytes to read
* @return read bytes as byte array
* @throws IOException
* @throws EOFException if there were less bytes than requested available in the stream
*/
public byte[] readBytes(long n) throws IOException {
if (n > Integer.MAX_VALUE) {
throw new RuntimeException(
"Java byte arrays can be indexed only up to 31 bits, but " + n + " size was requested"
);
}
byte[] buf = new byte[(int) n];
// Reading 0 bytes is always ok and never raises an exception
if (n == 0)
return buf;
int readCount = st.read(buf);
if (readCount < n) {
throw new EOFException();
}
return buf;
}
private static final int DEFAULT_BUFFER_SIZE = 4 * 1024;
/**
* Reads all the remaining bytes in a stream as byte array.
* @return all remaining bytes in a stream as byte array
* @throws IOException
*/
public byte[] readBytesFull() throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int readCount;
while (-1 != (readCount = st.read(buffer)))
baos.write(buffer, 0, readCount);
return baos.toByteArray();
}
/**
* Reads next len bytes from the stream and ensures that they match expected
* fixed byte array. If they differ, throws a {@link UnexpectedDataError}
* runtime exception.
* @param len number of bytes to read
* @param expected contents to be expected
* @return read bytes as byte array, which are guaranteed to equal to expected
* @throws IOException
* @throws UnexpectedDataError
*/
public byte[] ensureFixedContents(int len, byte[] expected) throws IOException {
byte[] actual = readBytes(len);
if (!Arrays.equals(actual, expected))
throw new UnexpectedDataError(actual, expected);
return actual;
}
//endregion
//region Strings
public String readStrEos(String encoding) throws IOException {
return new String(readBytesFull(), Charset.forName(encoding));
}
public String readStrByteLimit(long len, String encoding) throws IOException {
return new String(readBytes(len), Charset.forName(encoding));
}
public String readStrz(String encoding, int term, boolean includeTerm, boolean consumeTerm, boolean eosError) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
Charset cs = Charset.forName(encoding);
while (true) {
int c = st.read();
if (c < 0) {
if (eosError) {
throw new RuntimeException("End of stream reached, but no terminator " + term + " found");
} else {
return new String(buf.toByteArray(), cs);
}
} else if (c == term) {
if (includeTerm)
buf.write(c);
if (!consumeTerm)
st.seek(st.pos() - 1);
return new String(buf.toByteArray(), cs);
}
buf.write(c);
}
}
//endregion
//region Byte array processing
/**
* Performs a XOR processing with given data, XORing every byte of input with a single
* given value.
* @param data data to process
* @param key value to XOR with
* @return processed data
*/
public static byte[] processXor(byte[] data, int key) {
int dataLen = data.length;
byte[] r = new byte[dataLen];
for (int i = 0; i < dataLen; i++)
r[i] = (byte) (data[i] ^ key);
return r;
}
/**
* Performs a XOR processing with given data, XORing every byte of input with a key
* array, repeating key array many times, if necessary (i.e. if data array is longer
* than key array).
* @param data data to process
* @param key array of bytes to XOR with
* @return processed data
*/
public static byte[] processXor(byte[] data, byte[] key) {
int dataLen = data.length;
int valueLen = key.length;
byte[] r = new byte[dataLen];
int j = 0;
for (int i = 0; i < dataLen; i++) {
r[i] = (byte) (data[i] ^ key[j]);
j = (j + 1) % valueLen;
}
return r;
}
/**
* Performs a circular left rotation shift for a given buffer by a given amount of bits,
* using groups of groupSize bytes each time. Right circular rotation should be performed
* using this procedure with corrected amount.
* @param data source data to process
* @param amount number of bits to shift by
* @param groupSize number of bytes per group to shift
* @return copy of source array with requested shift applied
*/
public static byte[] processRotateLeft(byte[] data, int amount, int groupSize) {
byte[] r = new byte[data.length];
switch (groupSize) {
case 1:
for (int i = 0; i < data.length; i++) {
byte bits = data[i];
r[i] = (byte) (((bits & 0xff) << amount) | ((bits & 0xff) >>> (8 - amount)));
}
break;
default:
throw new UnsupportedOperationException("unable to rotate group of " + groupSize + " bytes yet");
}
return r;
}
private final static int ZLIB_BUF_SIZE = 4096;
/**
* Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers.
* @param data data to unpack
* @return unpacked data
* @throws IOException
*/
public static byte[] processZlib(byte[] data) throws IOException {
Inflater ifl = new Inflater();
ifl.setInput(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[ZLIB_BUF_SIZE];
while (!ifl.finished()) {
try {
int decBytes = ifl.inflate(buf);
baos.write(buf, 0, decBytes);
} catch (DataFormatException e) {
throw new IOException(e);
}
}
ifl.end();
return baos.toByteArray();
}
//endregion
//region Misc runtime operations
/**
* Performs modulo operation between two integers: dividend `a`
* and divisor `b`. Divisor `b` is expected to be positive. The
* result is always 0 <= x <= b - 1.
* @param a dividend
* @param b divisor
*/
public static int mod(int a, int b) {
if (b <= 0)
throw new ArithmeticException("mod divisor <= 0");
int r = a % b;
if (r < 0)
r += b;
return r;
}
/**
* Performs modulo operation between two integers: dividend `a`
* and divisor `b`. Divisor `b` is expected to be positive. The
* result is always 0 <= x <= b - 1.
* @param a dividend
* @param b divisor
*/
public static long mod(long a, long b) {
if (b <= 0)
throw new ArithmeticException("mod divisor <= 0");
long r = a % b;
if (r < 0)
r += b;
return r;
}
//endregion
private ByteBuffer wrapBufferLe(int count) throws IOException {
return ByteBuffer.wrap(readBytes(count)).order(ByteOrder.LITTLE_ENDIAN);
}
private ByteBuffer wrapBufferBe(int count) throws IOException {
return ByteBuffer.wrap(readBytes(count)).order(ByteOrder.BIG_ENDIAN);
}
interface KaitaiSeekableStream {
void close() throws IOException;
long pos() throws IOException;
long size() throws IOException;
void seek(long l) throws IOException;
int read() throws IOException;
int read(byte[] buf) throws IOException;
boolean isEof() throws IOException;
}
static class BAISWrapper extends ByteArrayInputStream implements KaitaiSeekableStream {
public BAISWrapper(byte[] bytes) {
super(bytes);
}
@Override
public long pos() {
return pos;
}
@Override
public long size() {
return count;
}
@Override
public void seek(long newPos) {
if (newPos > Integer.MAX_VALUE) {
throw new RuntimeException(
"Java in-memory ByteArrays can be indexed only up to 31 bits, but " + newPos + " offset was requested"
);
} else {
pos = (int) newPos;
}
}
@Override
public boolean isEof() {
return !(this.pos < this.count);
}
}
static class RAFWrapper extends RandomAccessFile implements KaitaiSeekableStream {
public RAFWrapper(String fileName, String r) throws FileNotFoundException {
super(fileName, r);
}
@Override
public long pos() throws IOException {
return getFilePointer();
}
@Override
public long size() throws IOException {
return length();
}
@Override
public boolean isEof() throws IOException {
return !(getFilePointer() < length());
}
}
/**
* Exception class for an error that occurs when some fixed content
* was expected to appear, but actual data read was different.
*/
public static class UnexpectedDataError extends RuntimeException {
public UnexpectedDataError(byte[] actual, byte[] expected) {
super(
"Unexpected fixed contents: got " + byteArrayToHex(actual) +
" , was waiting for " + byteArrayToHex(expected)
);
}
private static String byteArrayToHex(byte[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (i > 0)
sb.append(' ');
sb.append(String.format("%02x", arr[i]));
}
return sb.toString();
}
}
}
|
package maritech.items;
import java.util.List;
import mariculture.api.core.MaricultureTab;
import mariculture.core.Core;
import mariculture.core.items.ItemMCBaseArmor;
import mariculture.core.lib.CraftingMeta;
import mariculture.lib.util.Text;
import maritech.extensions.modules.ExtensionDiving;
import maritech.handlers.ScubaMask;
import maritech.lib.MTModInfo;
import maritech.model.ModelFlippers;
import maritech.util.MTTranslate;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemArmorScuba extends ItemMCBaseArmor {
public ItemArmorScuba(ArmorMaterial material, int j, int k) {
super(MTModInfo.MODPATH, MaricultureTab.tabWorld, material, j, k);
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) {
if (stack.getItem() == ExtensionDiving.swimfin) return MTModInfo.MODPATH + ":textures/armor/flippers.png";
if (stack.getItem() == ExtensionDiving.scubaSuit) return MTModInfo.MODPATH + ":" + "textures/armor/scuba" + "_2.png";
return MTModInfo.MODPATH + ":" + "textures/armor/scuba" + "_1.png";
}
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack stack, int armorSlot) {
return stack.getItem() == ExtensionDiving.swimfin ? new ModelFlippers() : null;
}
@Override
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean bool) {
if (stack.getItem() == ExtensionDiving.scubaMask) {
if (stack.hasTagCompound()) {
String display = MTTranslate.translate("landlights.format");
display = display.replace("%L", MTTranslate.translate("landlights"));
boolean landLightOn = stack.getTagCompound().getBoolean("ScubaMaskOnOutOfWater");
if (landLightOn) {
display = display.replace("%O", Text.DARK_GREEN + MTTranslate.translate("on"));
} else {
display = display.replace("%O", Text.RED + MTTranslate.translate("off"));
}
list.add(display);
} else {
String display = MTTranslate.translate("landlights.format");
display = display.replace("%L", MTTranslate.translate("landlights"));
display = display.replace("%O", Text.RED + MTTranslate.translate("off"));
list.add(display);
}
}
}
@Override
public boolean getIsRepairable(ItemStack stack1, ItemStack stack2) {
if (stack1.getItem() != ExtensionDiving.scubaTank) return stack2.getItem() == Core.crafting && stack2.getItemDamage() == CraftingMeta.NEOPRENE;
return false;
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (!world.isRemote) if (stack.getItem() == ExtensionDiving.scubaMask) {
if (!stack.hasTagCompound()) {
stack.setTagCompound(new NBTTagCompound());
}
if (player.isSneaking()) {
stack.stackTagCompound.setBoolean("ScubaMaskOnOutOfWater", true);
} else {
stack.stackTagCompound.setBoolean("ScubaMaskOnOutOfWater", false);
}
}
return stack;
}
@Override
public void onArmorTick(World world, EntityPlayer player, ItemStack stack) {
if (!world.isRemote) {
if (stack.getItem() == ExtensionDiving.scubaMask && world.getTotalWorldTime() % 5 == 0) {
ScubaMask.activate(player, stack);
}
}
}
}
|
package net.davidstrickland;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
/**
* Usage:tesseract imagename outputbase [-l lang] [-psm pagesegmode] [configfile...]
pagesegmode values are:
0 = Orientation and script detection (OSD) only.
1 = Automatic page segmentation with OSD.
2 = Automatic page segmentation, but no OSD, or OCR
3 = Fully automatic page segmentation, but no OSD. (Default)
4 = Assume a single column of text of variable sizes.
5 = Assume a single uniform block of vertically aligned text.
6 = Assume a single uniform block of text.
7 = Treat the image as a single text line.
8 = Treat the image as a single word.
9 = Treat the image as a single word in a circle.
10 = Treat the image as a single character.
-l lang and/or -psm pagesegmode must occur before anyconfigfile.
* @author david
*
*/
public class Tesseract {
public static String process(String imagename) throws IOException {
return process(imagename, null);
}
public static String process(String imagename, String language) throws IOException {
String tesseractPath = System.getProperty("tesseract");
if(tesseractPath == null) {
throw new UnsupportedOperationException("Required 'tesseract' system variable not set");
}
String id = UUID.randomUUID().toString();
List<String> args = new ArrayList<String>();
args.add(tesseractPath);
args.add(imagename);
args.add(id);
if(language != null) {
args.add("-l " + language);
}
ProcessBuilder builder = new ProcessBuilder(args);
Process p = builder.start();
try {
p.waitFor();
} catch (InterruptedException e) {
// continue on, trying to read what is available
}
// TODO: check whether the file exists or not... if not then no text was extracted??
File result = new File(id + ".txt");
String text = FileUtils.readFileToString(result);
result.delete();
return text;
}
public static String process(InputStream image) throws IOException {
File tempFile = File.createTempFile("tesseract_", ".tmp");
FileUtils.copyInputStreamToFile(image, tempFile);
String text = process(tempFile.getPath());
tempFile.delete();
return text;
}
public static String process(BufferedImage image, String type) throws IOException {
String text = "";
File temp = File.createTempFile("tesseract_", ".tmp");
ImageIO.write(image, type, temp);
text = process(temp.getAbsolutePath());
temp.delete();
return text;
}
}
|
package net.dean.jraw.models;
import net.dean.jraw.models.meta.JsonProperty;
import net.dean.jraw.models.meta.Model;
import org.codehaus.jackson.JsonNode;
import java.util.Date;
@Model(kind = Model.Kind.WIKI_PAGE)
public class WikiPage extends RedditObject {
/**
* Instantiates a new WikiPage
*
* @param dataNode The node to parse data from
*/
public WikiPage(JsonNode dataNode) {
super(dataNode);
}
/**
* Checks if the current user can edit this page
*
* @return If the current user can edit this page
*/
@JsonProperty
public Boolean mayRevise() {
return data("may_revise", Boolean.class);
}
/**
* Gets the date of last revision (or creation?)
*
* @return The date of last revision
*/
@JsonProperty
public Date getRevisionDate() {
return data("revision_date", Date.class);
}
/**
* Gets the content of this page
*
* @return The content
*/
@JsonProperty
public String getContent() {
return data("content_md");
}
/**
* Gets the person who last revised this page
*
* @return The person ({@link Account}) who last revised this page
*/
@JsonProperty(nullable = true)
public Account getCurrentRevisionAuthor() {
if (data.get("revision_by").isNull()) {
return null;
}
return new Account(data.get("revision_by").get("data"));
}
}
|
package net.qbar.common.grid;
import java.util.HashSet;
import javax.annotation.Nonnull;
import net.minecraftforge.fluids.Fluid;
import net.qbar.common.fluid.LimitedTank;
public class PipeGrid extends CableGrid
{
private final LimitedTank tank;
private int transferCapacity;
private final HashSet<IFluidPipe> outputs;
public PipeGrid(final int identifier, final int transferCapacity)
{
super(identifier);
this.transferCapacity = transferCapacity;
this.tank = new LimitedTank("PipeGrid", transferCapacity * 4, transferCapacity);
this.outputs = new HashSet<>();
}
@Override
public void addCable(@Nonnull final ITileCable cable)
{
super.addCable(cable);
this.getTank().setCapacity(this.getCapacity());
}
@Override
public boolean removeCable(final ITileCable cable)
{
if (super.removeCable(cable))
{
this.getTank().setCapacity(this.getCapacity());
if (this.getTank().getFluidAmount() > 0)
this.getTank().drainInternal(this.getTank().getFluidAmount() / (this.getCables().size() + 1), true);
this.outputs.remove(cable);
return true;
}
return false;
}
public int getTransferCapacity()
{
return this.transferCapacity;
}
@Override
public void tick()
{
if (!this.getOutputs().isEmpty())
this.getOutputs().forEach(pipe -> pipe.fillNeighbors());
}
@Override
CableGrid copy(final int identifier)
{
return new PipeGrid(identifier, this.transferCapacity);
}
@Override
void applyData(final CableGrid grid)
{
if (grid instanceof PipeGrid)
{
this.transferCapacity = ((PipeGrid) grid).getTransferCapacity();
}
}
@Override
boolean canMerge(final CableGrid grid)
{
if (grid instanceof PipeGrid)
{
if (((PipeGrid) grid).getFluid() == null || this.getFluid() == null
|| ((PipeGrid) grid).getFluid().equals(this.getFluid()))
return super.canMerge(grid);
}
return false;
}
@Override
void onMerge(final CableGrid grid)
{
this.getTank().setCapacity(this.getCapacity());
if (((PipeGrid) grid).getTank().getFluid() != null)
this.getTank().fillInternal(((PipeGrid) grid).getTank().getFluid(), true);
}
@Override
void onSplit(final CableGrid grid)
{
this.getTank().fillInternal(((PipeGrid) grid).getTank().drainInternal(
((PipeGrid) grid).getTank().getFluidAmount() / grid.getCables().size() * this.getCables().size(),
false), true);
}
public Fluid getFluid()
{
return this.getTank().getFluidType();
}
public LimitedTank getTank()
{
return this.tank;
}
public int getCapacity()
{
return this.getCables().size() * this.getTransferCapacity();
}
public boolean isEmpty()
{
return this.getFluid() == null || this.getTank().getFluidAmount() == 0;
}
public HashSet<IFluidPipe> getOutputs()
{
return this.outputs;
}
public void addOutput(final IFluidPipe output)
{
this.outputs.add(output);
}
public void removeOutput(final IFluidPipe output)
{
this.outputs.remove(output);
}
}
|
package net.wendal.nutzbook;
import java.nio.charset.Charset;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.integration.quartz.NutQuartzCronJobFactory;
import org.nutz.integration.shiro.NutShiro;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.lang.Encoding;
import org.nutz.lang.Mirror;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import org.nutz.plugins.view.freemarker.FreeMarkerConfigurer;
import org.quartz.Scheduler;
import freemarker.template.Configuration;
import net.sf.ehcache.CacheManager;
import net.wendal.nutzbook.bean.User;
import net.wendal.nutzbook.bean.UserProfile;
import net.wendal.nutzbook.bean.yvr.Topic;
import net.wendal.nutzbook.bean.yvr.TopicReply;
import net.wendal.nutzbook.service.AuthorityService;
import net.wendal.nutzbook.service.BigContentService;
import net.wendal.nutzbook.service.UserService;
import net.wendal.nutzbook.service.syslog.SysLogService;
import net.wendal.nutzbook.service.yvr.YvrService;
import net.wendal.nutzbook.util.Markdowns;
/**
* Nutz
*
* @author wendal
*
*/
public class MainSetup implements Setup {
private static final Log log = Logs.get();
public static PropertiesProxy conf;
public void init(NutConfig nc) {
NutShiro.DefaultLoginURL = "/admin/logout";
if (!Charset.defaultCharset().name().equalsIgnoreCase(Encoding.UTF8)) {
log.warn("This project must run in UTF-8, pls add -Dfile.encoding=UTF-8 to JAVA_OPTS");
}
// IocDao
Ioc ioc = nc.getIoc();
// freemarker
ioc.get(Configuration.class).setAutoImports(new NutMap().setv("p", "/ftl/pony/index.ftl").setv("s", "/ftl/spring.ftl"));
ioc.get(FreeMarkerConfigurer.class, "mapTags");
Dao dao = ioc.get(Dao.class);
// @Tablebean
Daos.createTablesInPackage(dao, getClass().getPackage().getName()+".bean", false);
Daos.migration(dao, Topic.class, true, false);
Daos.migration(dao, TopicReply.class, true, false);
// TopicTopicReplyBigContent
BigContentService bcs = ioc.get(BigContentService.class);
for (String topicId : dao.execute(Sqls.queryString("select id from t_topic where cid is null")).getObject(String[].class)) {
Topic topic = dao.fetch(Topic.class, topicId);
String cid = bcs.put(topic.getContent());
topic.setContentId(cid);
topic.setContent(null);
dao.update(topic, "(content|contentId)");
}
for (String topicId : dao.execute(Sqls.queryString("select id from t_topic_reply where cid is null")).getObject(String[].class)) {
TopicReply reply = dao.fetch(TopicReply.class, topicId);
String cid = bcs.put(reply.getContent());
reply.setContentId(cid);
reply.setContent(null);
dao.update(reply, "(content|contentId)");
}
conf = ioc.get(PropertiesProxy.class, "conf");
// SysLog,
ioc.get(SysLogService.class);
User admin = dao.fetch(User.class, "admin");
if (admin == null) {
UserService us = ioc.get(UserService.class);
admin = us.add("admin", "123456");
}
User guest = dao.fetch(User.class, "guest");
if (guest == null) {
UserService us = ioc.get(UserService.class);
guest = us.add("guest", "123456");
UserProfile profile = dao.fetch(UserProfile.class, guest.getId());
profile.setNickname("");
dao.update(profile, "nickname");
}
// NutQuartzCronJobFactory
ioc.get(NutQuartzCronJobFactory.class);
AuthorityService as = ioc.get(AuthorityService.class);
as.initFormPackage(getClass().getPackage().getName());
as.checkBasicRoles(admin);
// Ehcache CacheManager .
CacheManager cacheManager = ioc.get(CacheManager.class);
log.debug("Ehcache CacheManager = " + cacheManager);
// CachedNutDaoExecutor.DEBUG = true;
// Markdown
if (cacheManager.getCache("markdown") == null)
cacheManager.addCache("markdown");
Markdowns.cache = cacheManager.getCache("markdown");
if (dao.meta().isMySql()) {
String schema = dao.execute(Sqls.fetchString("SELECT DATABASE()")).getString();
// ,MyISAM,InnoDB
Sql sql = Sqls.queryString("SELECT TABLE_NAME FROM information_schema.TABLES where TABLE_SCHEMA = @schema and engine = 'MyISAM'");
sql.params().set("schema", schema);
for (String tableName : dao.execute(sql).getObject(String[].class)) {
if (tableName.startsWith("t_syslog") || tableName.startsWith("t_user_message"))
continue;
dao.execute(Sqls.create("alter table "+tableName+" ENGINE = InnoDB"));
}
}
ioc.get(YvrService.class).updateTopicTypeCount();
Mvcs.disableFastClassInvoker = false;
}
public void destroy(NutConfig conf) {
Markdowns.cache = null;
// mysql,webappmysql,
try {
Mirror.me(Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread")).invoke(null, "shutdown");
} catch (Throwable e) {
}
// quartz
try {
conf.getIoc().get(Scheduler.class).shutdown(true);
} catch (Exception e) {
}
// com.alibaba.druid.proxy.DruidDrivercom.mysql.jdbc.Driverreloadwarning
// webappmysql,
Enumeration<Driver> en = DriverManager.getDrivers();
while (en.hasMoreElements()) {
try {
Driver driver = en.nextElement();
String className = driver.getClass().getName();
if ("com.alibaba.druid.proxy.DruidDriver".equals(className)
|| "com.mysql.jdbc.Driver".equals(className)) {
log.debug("deregisterDriver: " + className);
DriverManager.deregisterDriver(driver);
}
}
catch (Exception e) {
}
}
}
}
|
package nl.mpi.kinnate.svg;
import nl.mpi.kinnate.ui.GraphPanelContextMenu;
import nl.mpi.kinnate.ui.KinTypeEgoSelectionTestPanel;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import javax.xml.transform.TransformerException;
import nl.mpi.arbil.GuiHelper;
import nl.mpi.arbil.ImdiTableModel;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.arbil.data.ImdiLoader;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.SavePanel;
import org.apache.batik.bridge.UpdateManager;
import org.apache.batik.dom.events.DOMMouseEvent;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.JSVGScrollPane;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGLocatable;
import org.w3c.dom.svg.SVGRect;
public class GraphPanel extends JPanel implements SavePanel {
private JSVGScrollPane jSVGScrollPane;
private JSVGCanvas svgCanvas;
private SVGDocument doc;
private Element currentDraggedElement;
private Cursor preDragCursor;
private HashSet<URI> egoSet = new HashSet<URI>();
private String[] kinTypeStrings = new String[]{};
private IndexerParameters indexParameters;
private ImdiTableModel imdiTableModel;
private GraphData graphData;
private boolean requiresSave = false;
private File svgFile = null;
private GraphPanelSize graphPanelSize;
private ArrayList<String> selectedGroupElement;
private String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI;
private String kinDataNameSpace = "kin";
private String kinDataNameSpaceLocation = "http://mpi.nl/tla/kin";
public GraphPanel(KinTypeEgoSelectionTestPanel egoSelectionPanel) {
selectedGroupElement = new ArrayList<String>();
graphPanelSize = new GraphPanelSize();
indexParameters = new IndexerParameters();
this.setLayout(new BorderLayout());
svgCanvas = new JSVGCanvas();
// svgCanvas.setMySize(new Dimension(600, 400));
svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
// drawNodes();
svgCanvas.setEnableImageZoomInteractor(false);
svgCanvas.setEnablePanInteractor(false);
svgCanvas.setEnableRotateInteractor(false);
svgCanvas.setEnableZoomInteractor(false);
svgCanvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
AffineTransform at = new AffineTransform();
// System.out.println("R: " + e.getWheelRotation());
// System.out.println("A: " + e.getScrollAmount());
// System.out.println("U: " + e.getUnitsToScroll());
at.scale(1 + e.getUnitsToScroll() / 10.0, 1 + e.getUnitsToScroll() / 10.0);
// at.translate(e.getX()/10.0, e.getY()/10.0);
// System.out.println("x: " + e.getX());
// System.out.println("y: " + e.getY());
at.concatenate(svgCanvas.getRenderingTransform());
svgCanvas.setRenderingTransform(at);
}
});
// svgCanvas.setEnableResetTransformInteractor(true);
// svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas
MouseInputAdapter mouseInputAdapter = new MouseInputAdapter() {
@Override
public void mouseDragged(MouseEvent me) {
// System.out.println("mouseDragged: " + me.toString());
if (currentDraggedElement != null) {
svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
updateDragNode(currentDraggedElement, me.getX(), me.getY());
}
}
@Override
public void mouseReleased(MouseEvent me) {
// System.out.println("mouseReleased: " + me.toString());
if (currentDraggedElement != null) {
svgCanvas.setCursor(preDragCursor);
updateDragNode(currentDraggedElement, me.getX(), me.getY());
currentDraggedElement = null;
}
}
};
svgCanvas.addMouseListener(mouseInputAdapter);
svgCanvas.addMouseMotionListener(mouseInputAdapter);
jSVGScrollPane = new JSVGScrollPane(svgCanvas);
this.add(BorderLayout.CENTER, jSVGScrollPane);
svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(egoSelectionPanel, this, graphPanelSize));
}
public void setImdiTableModel(ImdiTableModel imdiTableModelLocal) {
imdiTableModel = imdiTableModelLocal;
}
public void readSvg(File svgFilePath) {
svgFile = svgFilePath;
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser);
try {
doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toURI().toString());
svgCanvas.setDocument(doc);
requiresSave = false;
} catch (IOException ioe) {
GuiHelper.linorgBugCatcher.logError(ioe);
}
// svgCanvas.setURI(svgFilePath.toURI().toString());
ArrayList<String> egoStringArray = new ArrayList<String>();
egoSet.clear();
for (String currentEgoString : getSingleParametersFromDom("EgoList")) {
try {
egoSet.add(new URI(currentEgoString));
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
kinTypeStrings = getSingleParametersFromDom("KinTypeStrings");
indexParameters.ancestorFields.setValues(getDoubleParametersFromDom("AncestorFields"));
indexParameters.decendantFields.setValues(getDoubleParametersFromDom("DecendantFields"));
indexParameters.labelFields.setValues(getDoubleParametersFromDom("LabelFields"));
indexParameters.symbolFieldsFields.setValues(getDoubleParametersFromDom("SymbolFieldsFields"));
}
private void saveSvg(File svgFilePath) {
svgFile = svgFilePath;
new CmdiComponentBuilder().savePrettyFormatting(doc, svgFilePath);
requiresSave = false;
}
private void printNodeNames(Node nodeElement) {
System.out.println(nodeElement.getLocalName());
System.out.println(nodeElement.getNamespaceURI());
Node childNode = nodeElement.getFirstChild();
while (childNode != null) {
printNodeNames(childNode);
childNode = childNode.getNextSibling();
}
}
private String[] getSingleParametersFromDom(String parameterName) {
ArrayList<String> parameterList = new ArrayList<String>();
if (doc != null) {
// printNodeNames(doc);
try {
// todo: resolve names space issue
// todo: try setting the XPath namespaces
NodeList parameterNodeList = org.apache.xpath.XPathAPI.selectNodeList(doc, "/svg:svg/kin:KinDiagramData/kin:" + parameterName);
for (int nodeCounter = 0; nodeCounter < parameterNodeList.getLength(); nodeCounter++) {
Node parameterNode = parameterNodeList.item(nodeCounter);
if (parameterNode != null) {
parameterList.add(parameterNode.getAttributes().getNamedItem("value").getNodeValue());
}
}
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
}
// // todo: populate the avaiable symbols indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
return parameterList.toArray(new String[]{});
}
private String[][] getDoubleParametersFromDom(String parameterName) {
ArrayList<String[]> parameterList = new ArrayList<String[]>();
if (doc != null) {
try {
// todo: resolve names space issue
NodeList parameterNodeList = org.apache.xpath.XPathAPI.selectNodeList(doc, "/svg/KinDiagramData/" + parameterName);
for (int nodeCounter = 0; nodeCounter < parameterNodeList.getLength(); nodeCounter++) {
Node parameterNode = parameterNodeList.item(nodeCounter);
if (parameterNode != null) {
parameterList.add(new String[]{parameterNode.getAttributes().getNamedItem("path").getNodeValue(), parameterNode.getAttributes().getNamedItem("value").getNodeValue()});
}
}
} catch (TransformerException transformerException) {
GuiHelper.linorgBugCatcher.logError(transformerException);
}
// // todo: populate the avaiable symbols indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
return parameterList.toArray(new String[][]{});
}
public String[] getKinTypeStrigs() {
return kinTypeStrings;
}
public void setKinTypeStrigs(String[] kinTypeStringArray) {
// strip out any white space, blank lines and remove duplicates
HashSet<String> kinTypeStringSet = new HashSet<String>();
for (String kinTypeString : kinTypeStringArray) {
if (kinTypeString != null && kinTypeString.trim().length() > 0) {
kinTypeStringSet.add(kinTypeString.trim());
}
}
kinTypeStrings = kinTypeStringSet.toArray(new String[]{});
}
public IndexerParameters getIndexParameters() {
return indexParameters;
}
public URI[] getEgoList() {
return egoSet.toArray(new URI[]{});
}
public void setEgoList(URI[] egoListArray) {
egoSet = new HashSet<URI>(Arrays.asList(egoListArray));
}
public String[] getSelectedPaths() {
return selectedGroupElement.toArray(new String[]{});
}
private void storeParameter(Element dataStoreElement, String parameterName, String[] ParameterValues) {
for (String currentKinType : ParameterValues) {
Element dataRecordNode = doc.createElementNS(kinDataNameSpace, parameterName);
// Element dataRecordNode = doc.createElement(kinDataNameSpace + ":" + parameterName);
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType);
dataStoreElement.appendChild(dataRecordNode);
}
}
private void storeParameter(Element dataStoreElement, String parameterName, String[][] ParameterValues) {
for (String[] currentKinType : ParameterValues) {
Element dataRecordNode = doc.createElementNS(kinDataNameSpace, parameterName);
// Element dataRecordNode = doc.createElement(kinDataNameSpace + ":" + parameterName);
if (currentKinType.length == 1) {
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType[0]);
} else if (currentKinType.length == 2) {
dataRecordNode.setAttributeNS(kinDataNameSpace, "path", currentKinType[0]);
dataRecordNode.setAttributeNS(kinDataNameSpace, "value", currentKinType[1]);
} else {
// todo: add any other datatypes if required
throw new UnsupportedOperationException();
}
dataStoreElement.appendChild(dataRecordNode);
}
}
public void resetZoom() {
AffineTransform at = new AffineTransform();
at.scale(1, 1);
at.setToTranslation(1, 1);
svgCanvas.setRenderingTransform(at);
}
public void drawNodes() {
drawNodes(graphData);
}
private void updateDragNode(final Element updateDragNodeElement, final int updateDragNodeX, final int updateDragNodeY) {
// UpdateManager updateManager = svgCanvas.getUpdateManager();
// updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
// public void run() {
// if (updateDragNodeElement != null) {
// updateDragNodeElement.setAttribute("x", String.valueOf(updateDragNodeX));
// updateDragNodeElement.setAttribute("y", String.valueOf(updateDragNodeY));
// // SVGRect bbox = ((SVGLocatable) currentDraggedElement).getBBox();
//// System.out.println("bbox X: " + bbox.getX());
//// System.out.println("bbox Y: " + bbox.getY());
//// System.out.println("bbox W: " + bbox.getWidth());
//// System.out.println("bbox H: " + bbox.getHeight());
//// todo: look into transform issues when dragging ellements eg when the canvas is scaled or panned
//// SVGLocatable.getTransformToElement()
//// SVGPoint.matrixTransform()
}
private void addHighlightToGroup() {
UpdateManager updateManager = svgCanvas.getUpdateManager();
updateManager.getUpdateRunnableQueue().invokeLater(new Runnable() {
public void run() {
if (doc != null) {
Element svgRoot = doc.getDocumentElement();
for (Node currentChild = svgRoot.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) {
if ("g".equals(currentChild.getLocalName())) {
Node idAttrubite = currentChild.getAttributes().getNamedItem("id");
if (idAttrubite != null) {
String entityPath = idAttrubite.getTextContent();
System.out.println("group id (entityPath): " + entityPath);
Node existingHighlight = null;
// find any existing highlight
for (Node subGoupNode = currentChild.getFirstChild(); subGoupNode != null; subGoupNode = subGoupNode.getNextSibling()) {
if ("rect".equals(subGoupNode.getLocalName())) {
Node subGroupIdAttrubite = subGoupNode.getAttributes().getNamedItem("id");
if (subGroupIdAttrubite != null) {
if ("highlight".equals(subGroupIdAttrubite.getTextContent())) {
existingHighlight = subGoupNode;
}
}
}
}
if (!selectedGroupElement.contains(entityPath)) {
// remove all old highlights
if (existingHighlight != null) {
currentChild.removeChild(existingHighlight);
}
// add the current highlights
} else {
if (existingHighlight == null) {
svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
SVGRect bbox = ((SVGLocatable) currentChild).getBBox();
System.out.println("bbox X: " + bbox.getX());
System.out.println("bbox Y: " + bbox.getY());
System.out.println("bbox W: " + bbox.getWidth());
System.out.println("bbox H: " + bbox.getHeight());
Element symbolNode = doc.createElementNS(svgNameSpace, "rect");
int paddingDistance = 20;
symbolNode.setAttribute("id", "highlight");
symbolNode.setAttribute("x", Float.toString(bbox.getX() - paddingDistance));
symbolNode.setAttribute("y", Float.toString(bbox.getY() - paddingDistance));
symbolNode.setAttribute("width", Float.toString(bbox.getWidth() + paddingDistance * 2));
symbolNode.setAttribute("height", Float.toString(bbox.getHeight() + paddingDistance * 2));
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("stroke-width", "1");
symbolNode.setAttribute("stroke", "blue");
symbolNode.setAttribute("stroke-dasharray", "3");
symbolNode.setAttribute("stroke-dashoffset", "0");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("id", "Highlight");
// symbolNode.setAttribute("style", ":none;fill-opacity:1;fill-rule:nonzero;stroke:#6674ff;stroke-opacity:1;stroke-width:1;stroke-miterlimit:4;"
// + "stroke-dasharray:1, 1;stroke-dashoffset:0");
currentChild.appendChild(symbolNode);
}
}
}
}
}
}
}
});
}
private Element createEntitySymbol(GraphDataNode currentNode, int hSpacing, int vSpacing, int symbolSize) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
groupNode.setAttribute("id", currentNode.getEntityPath());
// counterTest++;
Element symbolNode;
String symbolType = currentNode.getSymbolType();
if ("circle".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "circle");
symbolNode.setAttribute("cx", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
symbolNode.setAttribute("cy", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
symbolNode.setAttribute("r", Integer.toString(symbolSize / 2));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
// <circle id="_16" cx="120.0" cy="155.0" r="50" fill="red" stroke="black" stroke-width="1"/>
// <polygon id="_17" transform="matrix(0.7457627,0.0,0.0,circle0.6567164,467.339,103.462685)" points="20,10 80,40 40,80" fill="blue" stroke="black" stroke-width="1"/>
} else if ("square".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "rect");
symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
symbolNode.setAttribute("width", Integer.toString(symbolSize));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
} else if ("resource".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "rect");
symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
symbolNode.setAttribute("width", Integer.toString(symbolSize));
symbolNode.setAttribute("height", Integer.toString(symbolSize));
symbolNode.setAttribute("transform", "rotate(-45 " + Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2) + " " + Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + ")");
symbolNode.setAttribute("stroke-width", "4");
symbolNode.setAttribute("fill", "black");
} else if ("union".equals(symbolType)) {
// DOMUtilities.deepCloneDocument(doc, doc.getImplementation());
// symbolNode = doc.createElementNS(svgNS, "layer");
// Element upperNode = doc.createElementNS(svgNS, "rect");
// Element lowerNode = doc.createElementNS(svgNS, "rect");
// upperNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2));
// upperNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// upperNode.setAttribute("width", Integer.toString(symbolSize));
// upperNode.setAttribute("height", Integer.toString(symbolSize / 3));
// lowerNode.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing - symbolSize / 2 + (symbolSize / 3) * 2));
// lowerNode.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// lowerNode.setAttribute("width", Integer.toString(symbolSize));
// lowerNode.setAttribute("height", Integer.toString(symbolSize / 3));
// lowerNode.appendChild(upperNode);
// symbolNode.appendChild(lowerNode);
symbolNode = doc.createElementNS(svgNameSpace, "polyline");
int posXa = currentNode.xPos * hSpacing + hSpacing - symbolSize / 2;
int posYa = currentNode.yPos * vSpacing + vSpacing + symbolSize / 2;
int offsetAmounta = symbolSize / 2;
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("points", (posXa + offsetAmounta * 3) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa + offsetAmounta) + " " + (posXa - offsetAmounta) + "," + (posYa - offsetAmounta) + " " + (posXa + offsetAmounta * 3) + "," + (posYa - offsetAmounta));
} else if ("triangle".equals(symbolType)) {
symbolNode = doc.createElementNS(svgNameSpace, "polygon");
int posXt = currentNode.xPos * hSpacing + hSpacing;
int posYt = currentNode.yPos * vSpacing + vSpacing;
int triangleHeight = (int) (Math.sqrt(3) * symbolSize / 2);
symbolNode.setAttribute("points",
(posXt - symbolSize / 2) + "," + (posYt + triangleHeight / 2) + " "
+ (posXt) + "," + (posYt - +triangleHeight / 2) + " "
+ (posXt + symbolSize / 2) + "," + (posYt + triangleHeight / 2));
// case equals:
// symbolNode = doc.createElementNS(svgNS, "rect");
// symbolNode.setAttribute("x", Integer.toString(currentNode.xPos * stepNumber + stepNumber - symbolSize));
// symbolNode.setAttribute("y", Integer.toString(currentNode.yPos * stepNumber + stepNumber));
// symbolNode.setAttribute("width", Integer.toString(symbolSize / 2));
// symbolNode.setAttribute("height", Integer.toString(symbolSize / 2));
// break;
} else {
symbolNode = doc.createElementNS(svgNameSpace, "polyline");
int posX = currentNode.xPos * hSpacing + hSpacing - symbolSize / 2;
int posY = currentNode.yPos * vSpacing + vSpacing + symbolSize / 2;
int offsetAmount = symbolSize / 2;
symbolNode.setAttribute("fill", "none");
symbolNode.setAttribute("points", (posX - offsetAmount) + "," + (posY - offsetAmount) + " " + (posX + offsetAmount) + "," + (posY + offsetAmount) + " " + (posX) + "," + (posY) + " " + (posX - offsetAmount) + "," + (posY + offsetAmount) + " " + (posX + offsetAmount) + "," + (posY - offsetAmount));
}
// if (currentNode.isEgo) {
// symbolNode.setAttribute("fill", "red");
// } else {
// symbolNode.setAttribute("fill", "none");
if (currentNode.isEgo) {
symbolNode.setAttribute("fill", "black");
} else {
symbolNode.setAttribute("fill", "white");
}
symbolNode.setAttribute("stroke", "black");
symbolNode.setAttribute("stroke-width", "2");
groupNode.appendChild(symbolNode);
////////////////////////////// tspan method appears to fail in batik rendering process unless saved and reloaded ////////////////////////////////////////////////
// Element labelText = doc.createElementNS(svgNS, "text");
//// labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
//// labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2));
// labelText.setAttribute("fill", "black");
// labelText.setAttribute("fill-opacity", "1");
// labelText.setAttribute("stroke-width", "0");
// labelText.setAttribute("font-size", "14px");
//// labelText.setAttribute("text-anchor", "end");
//// labelText.setAttribute("style", "font-size:14px;text-anchor:end;fill:black;fill-opacity:1");
// //labelText.setNodeValue(currentChild.toString());
// //String textWithUni = "\u0041";
// int textSpanCounter = 0;
// int lineSpacing = 10;
// for (String currentTextLable : currentNode.getLabel()) {
// Text textNode = doc.createTextNode(currentTextLable);
// Element tspanElement = doc.createElement("tspan");
// tspanElement.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
// tspanElement.setAttribute("y", Integer.toString((currentNode.yPos * vSpacing + vSpacing - symbolSize / 2) + textSpanCounter));
//// tspanElement.setAttribute("y", Integer.toString(textSpanCounter * lineSpacing));
// tspanElement.appendChild(textNode);
// labelText.appendChild(tspanElement);
// textSpanCounter += lineSpacing;
// groupNode.appendChild(labelText);
////////////////////////////// end tspan method appears to fail in batik rendering process ////////////////////////////////////////////////
////////////////////////////// alternate method ////////////////////////////////////////////////
// todo: this method has the draw back that the text is not selectable as a block
int textSpanCounter = 0;
int lineSpacing = 15;
for (String currentTextLable : currentNode.getLabel()) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("x", Integer.toString(currentNode.xPos * hSpacing + hSpacing + symbolSize / 2));
labelText.setAttribute("y", Integer.toString(currentNode.yPos * vSpacing + vSpacing - symbolSize / 2 + textSpanCounter));
labelText.setAttribute("fill", "black");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
Text textNode = doc.createTextNode(currentTextLable);
labelText.appendChild(textNode);
textSpanCounter += lineSpacing;
groupNode.appendChild(labelText);
}
////////////////////////////// end alternate method ////////////////////////////////////////////////
((EventTarget) groupNode).addEventListener("mousedown", new EventListener() {
public void handleEvent(Event evt) {
boolean shiftDown = false;
if (evt instanceof DOMMouseEvent) {
shiftDown = ((DOMMouseEvent) evt).getShiftKey();
}
System.out.println("mousedown: " + evt.getCurrentTarget());
currentDraggedElement = ((Element) evt.getCurrentTarget());
preDragCursor = svgCanvas.getCursor();
// get the entityPath
String entityPath = currentDraggedElement.getAttribute("id");
System.out.println("entityPath: " + entityPath);
boolean nodeAlreadySelected = selectedGroupElement.contains(entityPath);
if (!shiftDown) {
System.out.println("Clear selection");
selectedGroupElement.clear();
}
// toggle the highlight
if (nodeAlreadySelected) {
selectedGroupElement.remove(entityPath);
} else {
selectedGroupElement.add(entityPath);
}
addHighlightToGroup();
// update the table selection
if (imdiTableModel != null) {
imdiTableModel.removeAllImdiRows();
try {
for (String currentSelectedPath : selectedGroupElement) {
imdiTableModel.addSingleImdiObject(ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentSelectedPath)));
}
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
}, false);
return groupNode;
}
public void drawNodes(GraphData graphDataLocal) {
requiresSave = true;
graphData = graphDataLocal;
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null);
// Document doc = impl.createDocument(svgNS, "svg", null);
// SVGDocument doc = svgCanvas.getSVGDocument();
// Get the root element (the 'svg' element).
Element svgRoot = doc.getDocumentElement();
// todo: set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places
// int maxTextLength = 0;
// for (GraphDataNode currentNode : graphData.getDataNodes()) {
// if (currentNode.getLabel()[0].length() > maxTextLength) {
// maxTextLength = currentNode.getLabel()[0].length();
int vSpacing = graphPanelSize.getVerticalSpacing(graphData.gridHeight);
// todo: find the real text size from batik
// todo: get the user selected canvas size and adjust the hSpacing and vSpacing to fit
// int hSpacing = maxTextLength * 10 + 100;
int hSpacing = graphPanelSize.getHorizontalSpacing(graphData.gridWidth);
int symbolSize = 15;
int strokeWidth = 2;
// int preferedWidth = graphData.gridWidth * hSpacing + hSpacing * 2;
// int preferedHeight = graphData.gridHeight * vSpacing + vSpacing * 2;
// Set the width and height attributes on the root 'svg' element.
svgRoot.setAttribute("width", Integer.toString(graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
svgRoot.setAttribute("height", Integer.toString(graphPanelSize.getHeight(graphData.gridHeight, vSpacing)));
this.setPreferredSize(new Dimension(graphPanelSize.getHeight(graphData.gridHeight, vSpacing), graphPanelSize.getWidth(graphData.gridWidth, hSpacing)));
// create string array to store the selected ego nodes in the dom
ArrayList<String> egoStringArray = new ArrayList<String>();
for (URI currentEgoUri : egoSet) {
egoStringArray.add(currentEgoUri.toASCIIString());
}
// store the selected kin type strings and other data in the dom
// Namespace sNS = Namespace.getNamespace("someNS", "someNamespace");
// Element element = new Element("SomeElement", sNS);
Element kinTypesRecordNode = doc.createElementNS(kinDataNameSpace, "KinDiagramData");
// Element kinTypesRecordNode = doc.createElement(kinDataNameSpace + ":KinDiagramData");
kinTypesRecordNode.setAttribute("xmlns:" + kinDataNameSpace, kinDataNameSpaceLocation); // todo: this surely is not the only nor the best way to st the namespace
storeParameter(kinTypesRecordNode, "EgoList", egoStringArray.toArray(new String[]{}));
storeParameter(kinTypesRecordNode, "KinTypeStrings", kinTypeStrings);
storeParameter(kinTypesRecordNode, "AncestorFields", indexParameters.ancestorFields.getValues());
storeParameter(kinTypesRecordNode, "DecendantFields", indexParameters.decendantFields.getValues());
storeParameter(kinTypesRecordNode, "LabelFields", indexParameters.labelFields.getValues());
storeParameter(kinTypesRecordNode, "SymbolFieldsFields", indexParameters.symbolFieldsFields.getValues());
svgRoot.appendChild(kinTypesRecordNode);
// end store the selected kin type strings and other data in the dom
svgCanvas.setSVGDocument(doc);
// svgCanvas.setDocument(doc);
// int counterTest = 0;
for (GraphDataNode currentNode : graphData.getDataNodes()) {
// set up the mouse listners on the group node
// ((EventTarget) groupNode).addEventListener("mouseover", new EventListener() {
// public void handleEvent(Event evt) {
// System.out.println("OnMouseOverCircleAction: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "green");
// }, false);
// ((EventTarget) groupNode).addEventListener("mouseout", new EventListener() {
// public void handleEvent(Event evt) {
// System.out.println("mouseout: " + evt.getCurrentTarget());
// if (currentDraggedElement == null) {
// ((Element) evt.getCurrentTarget()).setAttribute("fill", "none");
// }, false);
// draw links
for (GraphDataNode.NodeRelation graphLinkNode : currentNode.getNodeRelations()) {
if (graphLinkNode.sourceNode.equals(currentNode)) {
Element groupNode = doc.createElementNS(svgNameSpace, "g");
Element defsNode = doc.createElementNS(svgNameSpace, "defs");
String lineIdString = currentNode.getEntityPath() + "-" + graphLinkNode.linkedNode.getEntityPath();
// todo: groupNode.setAttribute("id", currentNode.getEntityPath()+ ";"+and the other end);
// set the line end points
int fromX = (currentNode.xPos * hSpacing + hSpacing);
int fromY = (currentNode.yPos * vSpacing + vSpacing);
int toX = (graphLinkNode.linkedNode.xPos * hSpacing + hSpacing);
int toY = (graphLinkNode.linkedNode.yPos * vSpacing + vSpacing);
// set the label position
int labelX = (fromX + toX) / 2;
int labelY = (fromY + toY) / 2;
switch (graphLinkNode.relationLineType) {
case horizontalCurve:
// this case uses the following case
case verticalCurve:
// todo: groupNode.setAttribute("id", );
// System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
//// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
// Element linkLine = doc.createElementNS(svgNS, "line");
// linkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// linkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// linkLine.setAttribute("stroke", "black");
// linkLine.setAttribute("stroke-width", "1");
// // Attach the rectangle to the root 'svg' element.
// svgRoot.appendChild(linkLine);
System.out.println("link: " + graphLinkNode.linkedNode.xPos + ":" + graphLinkNode.linkedNode.yPos);
// <line id="_15" transform="translate(146.0,112.0)" x1="0" y1="0" x2="100" y2="100" ="black" stroke-width="1"/>
Element linkLine = doc.createElementNS(svgNameSpace, "path");
int fromBezX;
int fromBezY;
int toBezX;
int toBezY;
if (graphLinkNode.relationLineType == GraphDataNode.RelationLineType.verticalCurve) {
fromBezX = fromX;
fromBezY = toY;
toBezX = toX;
toBezY = fromY;
if (currentNode.yPos == graphLinkNode.linkedNode.yPos) {
fromBezX = fromX;
fromBezY = toY - vSpacing / 2;
toBezX = toX;
toBezY = fromY - vSpacing / 2;
// set the label postion and lower it a bit
labelY = toBezY + vSpacing / 3;
;
}
} else {
fromBezX = toX;
fromBezY = fromY;
toBezX = fromX;
toBezY = toY;
if (currentNode.xPos == graphLinkNode.linkedNode.xPos) {
fromBezY = fromY;
fromBezX = toX - hSpacing / 2;
toBezY = toY;
toBezX = fromX - hSpacing / 2;
// set the label postion
labelX = toBezX;
}
}
linkLine.setAttribute("d", "M " + fromX + "," + fromY + " C " + fromBezX + "," + fromBezY + " " + toBezX + "," + toBezY + " " + toX + "," + toY);
// linkLine.setAttribute("x1", );
// linkLine.setAttribute("y1", );
// linkLine.setAttribute("x2", );
linkLine.setAttribute("fill", "none");
linkLine.setAttribute("stroke", "blue");
linkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
linkLine.setAttribute("id", lineIdString);
defsNode.appendChild(linkLine);
break;
case square:
// Element squareLinkLine = doc.createElement("line");
// squareLinkLine.setAttribute("x1", Integer.toString(currentNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y1", Integer.toString(currentNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("x2", Integer.toString(graphLinkNode.linkedNode.xPos * hSpacing + hSpacing));
// squareLinkLine.setAttribute("y2", Integer.toString(graphLinkNode.linkedNode.yPos * vSpacing + vSpacing));
// squareLinkLine.setAttribute("stroke", "grey");
// squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
Element squareLinkLine = doc.createElementNS(svgNameSpace, "polyline");
int midY = (fromY + toY) / 2;
if (toY == fromY) {
// make sure that union lines go below the entities and sibling lines go above
if (graphLinkNode.relationType == GraphDataNode.RelationType.sibling) {
midY = toY - vSpacing / 2;
} else if (graphLinkNode.relationType == GraphDataNode.RelationType.union) {
midY = toY + vSpacing / 2;
}
}
squareLinkLine.setAttribute("points",
fromX + "," + fromY + " "
+ fromX + "," + midY + " "
+ toX + "," + midY + " "
+ toX + "," + toY);
squareLinkLine.setAttribute("fill", "none");
squareLinkLine.setAttribute("stroke", "grey");
squareLinkLine.setAttribute("stroke-width", Integer.toString(strokeWidth));
squareLinkLine.setAttribute("id", lineIdString);
defsNode.appendChild(squareLinkLine);
break;
}
groupNode.appendChild(defsNode);
Element useNode = doc.createElementNS(svgNameSpace, "use");
useNode.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
// useNode.setAttribute("href", "#" + lineIdString);
groupNode.appendChild(useNode);
// add the relation label
if (graphLinkNode.labelString != null) {
Element labelText = doc.createElementNS(svgNameSpace, "text");
labelText.setAttribute("text-anchor", "middle");
// labelText.setAttribute("x", Integer.toString(labelX));
// labelText.setAttribute("y", Integer.toString(labelY));
labelText.setAttribute("fill", "blue");
labelText.setAttribute("stroke-width", "0");
labelText.setAttribute("font-size", "14");
// labelText.setAttribute("transform", "rotate(45)");
Element textPath = doc.createElementNS(svgNameSpace, "textPath");
textPath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + lineIdString); // the xlink: of "xlink:href" is required for some svg viewers to render correctly
textPath.setAttribute("startOffset", "50%");
// textPath.setAttribute("text-anchor", "middle");
Text textNode = doc.createTextNode(graphLinkNode.labelString);
textPath.appendChild(textNode);
labelText.appendChild(textPath);
groupNode.appendChild(labelText);
}
svgRoot.appendChild(groupNode);
}
}
}
// add the entity symbols on top of the links
for (GraphDataNode currentNode : graphData.getDataNodes()) {
svgRoot.appendChild(createEntitySymbol(currentNode, hSpacing, vSpacing, symbolSize));
}
//new CmdiComponentBuilder().savePrettyFormatting(doc, new File("/Users/petwit/Documents/SharedInVirtualBox/mpi-co-svn-mpi-nl/LAT/Kinnate/trunk/src/main/resources/output.svg"));
svgCanvas.revalidate();
// todo: populate this correctly with the available symbols
indexParameters.symbolFieldsFields.setAvailableValues(new String[]{"circle", "triangle", "square", "union"});
}
public boolean hasSaveFileName() {
return svgFile != null;
}
public boolean requiresSave() {
return requiresSave;
}
public void saveToFile() {
saveSvg(svgFile);
}
public void saveToFile(File saveAsFile) {
saveSvg(saveAsFile);
}
}
|
package org.bviktor.certzure;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import com.microsoft.aad.adal4j.*;
import com.microsoft.windowsazure.*;
import com.microsoft.windowsazure.core.*;
import com.microsoft.windowsazure.management.configuration.*;
import com.microsoft.azure.management.dns.*;
import com.microsoft.azure.management.dns.models.*;
public class Certzure
{
static final String settingsFileName = "certzure.properties";
static final String challengeString = "_acme-challenge";
static final String[] supportedOperations = { "deploy_challenge", "clean_challenge" };
static final String accessUri = "https://management.azure.com/";
static final String loginUri = "https://login.microsoftonline.com/common/";
public enum extractMode
{
HOST,
ZONE
}
public static void printHelp()
{
System.out.println("certzure operationName domainName challengeToken domainToken\n");
System.out.println("Supported operationName values:");
System.out.println("\tdeploy_challenge");
System.out.println("\tclean_challenge");
}
/*
* Get the TenantID for a given Azure subscription
*/
public static String getSubscriptionTenantId(String subscriptionId) throws Exception
{
String tenantId = null;
String url = accessUri + "subscriptions/" + subscriptionId + "?api-version=2016-01-01";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
Header[] headers = response.getAllHeaders();
for (Header header : headers)
{
if (header.getName().equals("WWW-Authenticate"))
{
/* split by '"' to get the URL, split the URL by '/' to get the ID */
tenantId = header.getValue().split("\"")[1].split("/")[3];
}
}
return tenantId;
}
private static Configuration createConfiguration(String subscriptionId, String clientId, String username, String password) throws Exception
{
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
Future<AuthenticationResult> future = null;
try
{
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(loginUri, false, service);
// FileInputStream fis = new FileInputStream(keyStoreLocation);
// AsymmetricKeyCredential cred =
// AsymmetricKeyCredential.create(clientID, fis, keyStorePassword);
// future = context.acquireToken(accessURI, cred, null);
future = context.acquireToken(accessUri, clientId, username, password, null);
result = future.get();
}
finally
{
service.shutdown();
}
if (result == null)
{
throw new Exception("authentication result was null");
}
return ManagementConfiguration.configure(null, new URI(accessUri), subscriptionId, result.getAccessToken());
/*
* Doesn't work
*/
// HttpClient client = HttpClientBuilder.create().build();
// HttpGet request = new HttpGet(accessURI);
// request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " +
// result.getAccessToken());
// System.out.println(request.toString());
// Header[] headers = request.getAllHeaders();
// for (Header header : headers)
// System.out.println(header.toString());
// System.out.println(client.execute(request));
// return ManagementConfiguration.configure (new URI(accessURI),
// subscriptionID, keyStoreLocation, keyStorePassword,
// KeyStoreType.jks); */
}
private static String parseProperty(Properties prop, String key)
{
String trimmed = prop.getProperty(key, "").trim();
return trimmed.substring(1, trimmed.length() - 1);
}
public static String extractFqdn(String domainName, extractMode mode)
{
String[] parts = domainName.split("\\.");
String rootDomain = parts[parts.length - 2] + "." + parts[parts.length - 1];
String subDomain = "";
for (int i = 0; i < parts.length - 2; i++)
{
subDomain += parts[i] + ".";
}
switch (mode)
{
case HOST:
/* if host is not empty, cut the trailing dot */
return subDomain.isEmpty() ? "" : subDomain.substring(0, subDomain.length() - 1);
case ZONE:
return rootDomain;
default:
return null;
}
}
public static Zone getZone(DnsManagementClient dnsClient, String resourceGroupName, String zoneName)
{
try
{
return dnsClient.getZonesOperations().get(resourceGroupName, zoneName).getZone();
}
catch (Exception e)
{
return new Zone();
}
}
public static ArrayList<Zone> getAllZones(DnsManagementClient dnsClient, String resourceGroupName) throws Exception
{
/* you have to iterate over it so it's not a problem if it's null */
ZoneListResponse zones = dnsClient.getZonesOperations().list(resourceGroupName, null);
return zones.getZones();
}
public static RecordSet getTxtRecord(DnsManagementClient dnsClient, String resourceGroupName, String domainName) throws Exception
{
try
{
String host = extractFqdn(domainName, extractMode.HOST);
if (host.isEmpty())
{
host = "@";
}
return dnsClient.getRecordSetsOperations().get(resourceGroupName, extractFqdn(domainName, extractMode.ZONE), host, RecordType.TXT).getRecordSet();
}
catch (Exception e)
{
return new RecordSet();
}
}
public static ArrayList<RecordSet> getAllTxtRecords(DnsManagementClient dnsClient, String resourceGroupName, String domainName) throws Exception
{
RecordSetListResponse records = dnsClient.getRecordSetsOperations().list(resourceGroupName, extractFqdn(domainName, extractMode.ZONE), RecordType.TXT, null);
return records.getRecordSets();
}
public static String getTxtRecordValue(RecordSet record) throws Exception
{
try
{
return record.getProperties().getTxtRecords().get(0).getValue();
}
catch (Exception e)
{
return null;
}
}
public static boolean httpSuccess(int code)
{
if (code == HttpStatus.SC_OK || code == HttpStatus.SC_CREATED || code == HttpStatus.SC_ACCEPTED)
{
return true;
}
else
{
return false;
}
}
public static boolean deployChallenge(DnsManagementClient dnsClient, String resourceGroupName, String domainName, String token, boolean verifyRecord) throws Exception
{
String zone = extractFqdn(domainName, extractMode.ZONE);
String host = extractFqdn(domainName, extractMode.HOST);
String recordSuffix = "";
/*
* If we add the challenge to the root, there must not be a dot.
* If we add it to a subdomain, there must be a dot.
*/
if (!host.isEmpty())
{
recordSuffix = ".";
}
TxtRecord myTxt = new TxtRecord(token);
ArrayList<TxtRecord> myTxtList = new ArrayList<TxtRecord>();
myTxtList.add(myTxt);
RecordSetProperties myProps = new RecordSetProperties();
myProps.setTxtRecords(myTxtList);
myProps.setTtl(60);
RecordSet mySet = new RecordSet("global");
mySet.setProperties(myProps);
RecordSetCreateOrUpdateParameters myParams = new RecordSetCreateOrUpdateParameters(mySet);
RecordSetCreateOrUpdateResponse myResponse = dnsClient.getRecordSetsOperations().createOrUpdate(resourceGroupName, zone, challengeString + recordSuffix + host,
RecordType.TXT, myParams);
int ret = myResponse.getStatusCode();
if (!httpSuccess(ret))
{
return false;
}
if (!verifyRecord)
{
return true;
}
RecordSet check = getTxtRecord(dnsClient, resourceGroupName, challengeString + "." + domainName);
if (getTxtRecordValue(check).equals(token))
{
return true;
}
else
{
return false;
}
}
public static boolean cleanChallenge(DnsManagementClient dnsClient, String resourceGroupName, String domainName) throws Exception
{
String zone = extractFqdn(domainName, extractMode.ZONE);
String host = extractFqdn(domainName, extractMode.HOST);
String recordSuffix = "";
/*
* If we add the challenge to the root, there must not be a dot.
* If we add it to a subdomain, there must be a dot.
*/
if (!host.isEmpty())
{
recordSuffix = ".";
}
RecordSetDeleteParameters myParams = new RecordSetDeleteParameters();
OperationResponse myResponse = dnsClient.getRecordSetsOperations().delete(resourceGroupName, zone, challengeString + recordSuffix + host, RecordType.TXT, myParams);
int ret = myResponse.getStatusCode();
if (httpSuccess(ret))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
String operationName = null;
String domainName = null;
// String challengeToken = null;
String domainToken = null;
if (args.length != 4)
{
printHelp();
return;
}
else
{
operationName = args[0];
domainName = args[1];
// challengeToken = args[2];
domainToken = args[3];
}
if (!Arrays.asList(supportedOperations).contains(operationName))
{
printHelp();
return;
}
/* parse the properties file */
Properties properties = new Properties();
try
{
InputStream iStream = Certzure.class.getClassLoader().getResourceAsStream(settingsFileName);
properties.load(iStream);
}
catch (Exception e)
{
System.out.println("Make sure you have your configured \"certzure.properties\" file in place. Example:\n");
System.out.println("subscriptionId = \"2a4da06c-ff07-410d-af8a-542a512f5092\"");
System.out.println("clientId = \"1950a258-227b-4e31-a9cf-717495945fc2\"");
System.out.println("username = \"dns@foobar.com\"");
System.out.println("password = \"whatever\"");
// System.out.println("keyStoreLocation = \"c:\\azure.pfx\"");
// System.out.println("keyStorePassword = \"whatnever\"");
System.out.println("resourceGroupName = \"DNSGroup\"\n");
System.out.println("Also make sure to secure this file with chmod and/or chown.");
System.exit(1);
}
String subscriptionId = parseProperty(properties, "subscriptionId");
String clientId = parseProperty(properties, "clientId");
String username = parseProperty(properties, "username");
String password = parseProperty(properties, "password");
String resourceGroupName = parseProperty(properties, "resourceGroupName");
Configuration config;
try
{
config = createConfiguration(subscriptionId, clientId, username, password);
DnsManagementClient dnsClient = DnsManagementService.create(config);
if (operationName.equals("deploy_challenge"))
{
deployChallenge(dnsClient, resourceGroupName, domainName, domainToken, true);
}
else if (operationName.equals("clean_challenge"))
{
cleanChallenge(dnsClient, resourceGroupName, domainName);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package org.dada.ltw;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class RelationalAspect {
public static final Map<String, Map<Integer, Integer>> model = new HashMap<String, Map<Integer,Integer>>();
protected Map<Integer, Integer> ensureTable(String fieldName) {
Map<Integer, Integer> table = model.get(fieldName);
if (table==null) {
model.put(fieldName, table = new HashMap<Integer, Integer>());
}
return table;
}
private static final Logger LOG = LoggerFactory.getLogger(RelationalAspect.class);
@Around("getterPointcut()")
public Object getterAdvice(ProceedingJoinPoint pjp) throws Throwable {
String fieldName = fieldName(pjp);
//Map<Integer, Integer> table = ensureTable(fieldName);
Identifiable target = (Identifiable)pjp.getTarget();
Identifiable value = (Identifiable)pjp.proceed();
LOG.info("get: " + target + "." + fieldName + " = " + value);
return value;
}
private String fieldName(ProceedingJoinPoint pjp) {
return pjp.getSignature().getName().substring(3);
}
@Around("setterPointcut()")
public Object setterAdvice(ProceedingJoinPoint pjp) throws Throwable {
Identifiable target = (Identifiable)pjp.getTarget();
Identifiable value = (Identifiable)pjp.getArgs()[0];
try {
String fieldName = fieldName(pjp);
Map<Integer, Integer> table = ensureTable(fieldName);
table.put(target.getId(), value.getId());
return pjp.proceed();
} finally {
LOG.info("set: " + target + "." + fieldName(pjp)+" = "+value);
}
}
@Pointcut("execution(public org.dada.ltw.Identifiable+ org.dada.ltw.Identifiable+.get*())")
public void getterPointcut() {}
@Pointcut("execution(public void org.dada.ltw.Identifiable+.set*(org.dada.ltw.Identifiable+))")
public void setterPointcut() {}
}
|
package org.hid4java;
import org.hid4java.event.HidServicesListenerList;
import org.hid4java.jna.HidApi;
import org.hid4java.jna.HidDeviceInfoStructure;
import java.util.*;
/**
* Manager to provide the following to HID services:
* <ul>
* <li>Access to the underlying JNA and hidapi library</li>
* <li>Device attach/detach detection (if configured)</li>
* <li>Device data read (if configured)</li>
* </ul>
*
* @since 0.0.1
*/
class HidDeviceManager {
/**
* The HID services specification providing configuration parameters
*/
private final HidServicesSpecification hidServicesSpecification;
/**
* The currently attached devices keyed on ID
*/
private final Map<String, HidDevice> attachedDevices = Collections.synchronizedMap(new HashMap<String, HidDevice>());
/**
* HID services listener list
*/
private final HidServicesListenerList listenerList;
/**
* The device enumeration thread
*
* We use a Thread instead of Executor since it may be stopped/paused/restarted frequently
* and executors are more heavyweight in this regard
*/
private Thread scanThread = null;
/**
* Constructs a new device manager
*
* @param listenerList The HID services providing access to the event model
* @param hidServicesSpecification Provides various parameters for configuring HID services
*
* @throws HidException If USB HID initialization fails
*/
HidDeviceManager(HidServicesListenerList listenerList, HidServicesSpecification hidServicesSpecification) throws HidException {
this.listenerList = listenerList;
this.hidServicesSpecification = hidServicesSpecification;
// Attempt to initialise and fail fast
try {
HidApi.init();
} catch (Throwable t) {
// Typically this is a linking issue with the native library
throw new HidException("Hidapi did not initialise: " + t.getMessage(), t);
}
}
/**
* Starts the manager
*
* If already started (scanning) it will immediately return without doing anything
*
* Otherwise this will perform a one-off scan of all devices then if the scan interval
* is zero will stop there or will start the scanning daemon thread at the required interval.
*
* @throws HidException If something goes wrong (such as Hidapi not initialising correctly)
*/
public void start() {
// Check for previous start
if (this.isScanning()) {
return;
}
// Perform a one-off scan to populate attached devices
scan();
// Ensure we have a scan thread available
configureScanThread(getScanRunnable());
}
/**
* Stop the scan thread and close all attached devices
*
* This is normally part of a general application shutdown
*/
public synchronized void stop() {
stopScanThread();
// Close all attached devices
for (HidDevice hidDevice: attachedDevices.values()) {
hidDevice.close();
}
}
/**
* Updates the device list by adding newly connected devices to it and by
* removing no longer connected devices.
*
* Will fire attach/detach events as appropriate.
*/
public synchronized void scan() {
List<String> removeList = new ArrayList<>();
List<HidDevice> attachedHidDeviceList = getAttachedHidDevices();
for (HidDevice attachedDevice : attachedHidDeviceList) {
if (!this.attachedDevices.containsKey(attachedDevice.getId())) {
// Device has become attached so add it but do not open
attachedDevices.put(attachedDevice.getId(), attachedDevice);
// Fire the event on a separate thread
listenerList.fireHidDeviceAttached(attachedDevice);
}
}
for (Map.Entry<String, HidDevice> entry : attachedDevices.entrySet()) {
String deviceId = entry.getKey();
HidDevice hidDevice = entry.getValue();
if (!attachedHidDeviceList.contains(hidDevice)) {
// Keep track of removals
removeList.add(deviceId);
// Fire the event on a separate thread
listenerList.fireHidDeviceDetached(this.attachedDevices.get(deviceId));
}
}
if (!removeList.isEmpty()) {
// Update the attached devices map
this.attachedDevices.keySet().removeAll(removeList);
}
}
/**
* @return True if the scan thread is running, false otherwise.
*/
public boolean isScanning() {
return scanThread != null && scanThread.isAlive();
}
/**
* @return A list of all attached HID devices
*/
public List<HidDevice> getAttachedHidDevices() {
List<HidDevice> hidDeviceList = new ArrayList<>();
final HidDeviceInfoStructure root;
try {
// Use 0,0 to list all attached devices
// This comes back as a linked list from hidapi
root = HidApi.enumerateDevices(0, 0);
} catch (Throwable e) {
// Could not initialise hidapi (possibly an unknown platform)
// Trigger a general stop as something serious has happened
stop();
// Inform the caller that something serious has gone wrong
throw new HidException("Unable to start HidApi: " + e.getMessage());
}
if (root != null) {
HidDeviceInfoStructure hidDeviceInfoStructure = root;
do {
// Wrap in HidDevice
hidDeviceList.add(new HidDevice(
hidDeviceInfoStructure,
this,
hidServicesSpecification));
// Move to the next in the linked list
hidDeviceInfoStructure = hidDeviceInfoStructure.next();
} while (hidDeviceInfoStructure != null);
// Dispose of the device list to free memory
HidApi.freeEnumeration(root);
}
return hidDeviceList;
}
/**
* Indicate that a device write has occurred which may require a change in scanning frequency
*/
public void afterDeviceWrite() {
if (ScanMode.SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE == hidServicesSpecification.getScanMode() && isScanning()) {
stopScanThread();
// Ensure we have a new scan executor service available
configureScanThread(getScanRunnable());
}
}
/**
* Indicate that an automatic data read has occurred which may require an event to be fired
*
* @param hidDevice The device that has received data
* @param dataReceived The data received
* @since 0.8.0
*/
public void afterDeviceDataRead(HidDevice hidDevice, byte[] dataReceived) {
if (dataReceived != null && dataReceived.length > 0) {
this.listenerList.fireHidDataReceived(hidDevice, dataReceived);
}
}
/**
* Stop the scan thread
*/
private synchronized void stopScanThread() {
if (isScanning()) {
scanThread.interrupt();
}
}
/**
* Configures the scan thread to allow recovery from stop or pause
*/
private synchronized void configureScanThread(Runnable scanRunnable) {
if (isScanning()) {
stopScanThread();
}
// Require a new one
scanThread = new Thread(scanRunnable);
scanThread.setDaemon(true);
scanThread.setName("hid4java device scanner");
scanThread.start();
}
private synchronized Runnable getScanRunnable() {
final int scanInterval = hidServicesSpecification.getScanInterval();
final int pauseInterval = hidServicesSpecification.getPauseInterval();
switch (hidServicesSpecification.getScanMode()) {
case NO_SCAN:
return new Runnable() {
@Override
public void run() {
// Do nothing
}
};
case SCAN_AT_FIXED_INTERVAL:
return new Runnable() {
@Override
public void run() {
while (true) {
try {
//noinspection BusyWait
Thread.sleep(scanInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
scan();
}
}
};
case SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE:
return new Runnable() {
@Override
public void run() {
// Provide an initial pause
try {
Thread.sleep(pauseInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
// Switch to continuous running
while (true) {
try {
//noinspection BusyWait
Thread.sleep(scanInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
scan();
}
}
};
default:
return null;
}
}
}
|
package org.inventivetalent.nbt;
public class TagID {
public static final int TAG_END = 0;
public static final int TAG_BYTE = 1;
public static final int TAG_SHORT = 2;
public static final int TAG_INT = 3;
public static final int TAG_LONG = 4;
public static final int TAG_FLOAT = 5;
public static final int TAG_DOUBLE = 6;
public static final int TAG_BYTE_ARRAY = 7;
public static final int TAG_STRING = 8;
public static final int TAG_LIST = 9;
public static final int TAG_COMPOUND = 10;
public static final int TAG_INT_ARRAY = 11;
public static int forClass(Class<? extends NBTTag> clazz) {
return forName(clazz.getSimpleName());
}
public static int forValueClass(Class<?> clazz) {
if (byte.class.isAssignableFrom(clazz) || boolean.class.isAssignableFrom(clazz)) {
return TAG_BYTE;
}
if (short.class.isAssignableFrom(clazz)) {
return TAG_SHORT;
}
if (int.class.isAssignableFrom(clazz)) {
return TAG_INT;
}
if (long.class.isAssignableFrom(clazz)) {
return TAG_LONG;
}
if (float.class.isAssignableFrom(clazz)) {
return TAG_FLOAT;
}
if (double.class.isAssignableFrom(clazz)) {
return TAG_DOUBLE;
}
if (String.class.isAssignableFrom(clazz)) {
return TAG_STRING;
}
if (byte[].class.isAssignableFrom(clazz)) {
return TAG_BYTE_ARRAY;
}
if (int[].class.isAssignableFrom(clazz)) {
return TAG_INT_ARRAY;
}
return -1;
}
public static int forName(String name) {
switch (name) {
case "ByteArrayTag":
case "Tag_Byte_Array":
return TAG_BYTE_ARRAY;
case "ByteTag":
case "Tag_Byte":
return TAG_BYTE;
case "CompoundTag":
case "TAG_Compound":
return TAG_COMPOUND;
case "DoubleTag":
case "TAG_Double":
return TAG_DOUBLE;
case "EndTag":
case "TAG_End":
return TAG_END;
case "FloatTag":
case "TAG_Float":
return TAG_FLOAT;
case "IntArrayTag":
case "TAG_Int_Array":
return TAG_INT_ARRAY;
case "IntTag":
case "TAG_Int":
return TAG_INT;
case "ListTag":
case "TAG_List":
return TAG_LIST;
case "LongTag":
case "TAG_Long":
return TAG_LONG;
case "ShortTag":
case "TAG_Short":
return TAG_SHORT;
case "StringTag":
case "TAG_String":
return TAG_STRING;
default:
throw new IllegalArgumentException("Invalid NBTTag name: " + name);
}
}
}
|
package org.inventivetalent.nbt;
import java.util.List;
import java.util.Map;
public class TagID {
public static final int TAG_END = 0;
public static final int TAG_BYTE = 1;
public static final int TAG_SHORT = 2;
public static final int TAG_INT = 3;
public static final int TAG_LONG = 4;
public static final int TAG_FLOAT = 5;
public static final int TAG_DOUBLE = 6;
public static final int TAG_BYTE_ARRAY = 7;
public static final int TAG_STRING = 8;
public static final int TAG_LIST = 9;
public static final int TAG_COMPOUND = 10;
public static final int TAG_INT_ARRAY = 11;
public static int forClass(Class<? extends NBTTag> clazz) {
return forName(clazz.getSimpleName());
}
public static int forValueClass(Class<?> clazz) {
if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz) || boolean.class.isAssignableFrom(clazz)) {
return TAG_BYTE;
}
if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) {
return TAG_SHORT;
}
if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) {
return TAG_INT;
}
if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) {
return TAG_LONG;
}
if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
return TAG_FLOAT;
}
if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) {
return TAG_DOUBLE;
}
if (String.class.isAssignableFrom(clazz)) {
return TAG_STRING;
}
if (byte[].class.isAssignableFrom(clazz) || Byte[].class.isAssignableFrom(clazz)) {
return TAG_BYTE_ARRAY;
}
if (int[].class.isAssignableFrom(clazz) || Integer[].class.isAssignableFrom(clazz)) {
return TAG_INT_ARRAY;
}
if (List.class.isAssignableFrom(clazz)) {
return TAG_LIST;
}
if (Map.class.isAssignableFrom(clazz)) {
return TAG_COMPOUND;
}
return forName(clazz.getSimpleName());
}
public static int forName(String name) {
switch (name) {
case "ByteArrayTag":
case "Tag_Byte_Array":
return TAG_BYTE_ARRAY;
case "ByteTag":
case "Tag_Byte":
return TAG_BYTE;
case "CompoundTag":
case "TAG_Compound":
return TAG_COMPOUND;
case "DoubleTag":
case "TAG_Double":
return TAG_DOUBLE;
case "EndTag":
case "TAG_End":
return TAG_END;
case "FloatTag":
case "TAG_Float":
return TAG_FLOAT;
case "IntArrayTag":
case "TAG_Int_Array":
return TAG_INT_ARRAY;
case "IntTag":
case "TAG_Int":
return TAG_INT;
case "ListTag":
case "TAG_List":
return TAG_LIST;
case "LongTag":
case "TAG_Long":
return TAG_LONG;
case "ShortTag":
case "TAG_Short":
return TAG_SHORT;
case "StringTag":
case "TAG_String":
return TAG_STRING;
default:
throw new IllegalArgumentException("Invalid NBTTag name: " + name);
}
}
}
|
package org.jtrfp.trcl;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.TimerTask;
import javax.media.opengl.GL3;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.beh.FacingObject;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.RotateAroundObject;
import org.jtrfp.trcl.core.Camera;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.TXTMissionBriefFile;
import org.jtrfp.trcl.flow.Game;
import org.jtrfp.trcl.flow.Mission.Result;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.img.vq.ColorPaletteVectorList;
import org.jtrfp.trcl.obj.EnemyIntro;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.Sprite2D;
import org.jtrfp.trcl.obj.WorldObject;
public class BriefingScreen extends RenderableSpacePartitioningGrid {
private static final double Z = .000000001;
private final TR tr;
private final Sprite2D briefingScreen;
private final CharAreaDisplay briefingChars;
private final Sprite2D blackRectangle;
private volatile double scrollPos = 0;
private double scrollIncrement=.01;
private final int NUM_LINES=10;
private final int WIDTH_CHARS=36;
private ArrayList<Runnable> scrollFinishCallbacks = new ArrayList<Runnable>();
private TXTMissionBriefFile missionTXT;
private ColorPaletteVectorList palette;
private LVLFile lvl;
private TimerTask scrollTimer;
private WorldObject planetObject;
public BriefingScreen(SpacePartitioningGrid<PositionedRenderable> parent, final TR tr, GLFont font) {
super(parent);
briefingScreen = new Sprite2D(tr,0, 2, 2,
tr.getResourceManager().getSpecialRAWAsTextures("BRIEF.RAW", tr.getGlobalPalette(),
tr.gpu.get().getGl(), 0,false),true);
add(briefingScreen);
this.tr = tr;
briefingChars = new CharAreaDisplay(this,.047,WIDTH_CHARS,NUM_LINES,tr,font);
//briefingChars.setFontSize(.035);//TODO: Implement
briefingChars.activate();
briefingChars.setPosition(-.7, -.45, Z*200);
briefingScreen.setPosition(0,0,Z);
briefingScreen.notifyPositionChange();
briefingScreen.setActive(true);
briefingScreen.setVisible(true);
blackRectangle = new Sprite2D(tr,0, 2, .6, tr.gpu.get().textureManager.get().solidColor(Color.BLACK), true);
add(blackRectangle);
blackRectangle.setPosition(0, -.7, Z*300);
blackRectangle.setVisible(true);
blackRectangle.setActive(true);
}//end constructor
protected void notifyScrollFinishCallbacks() {
for(Runnable r:scrollFinishCallbacks){
r.run();
}
}//end notifyScrollFinishCallbacks()
public void addScrollFinishCallback(Runnable r){
scrollFinishCallbacks.add(r);
}
public void removeScrollFinishCallback(Runnable r){
scrollFinishCallbacks.remove(r);
}
public void setContent(String content) {
briefingChars.setContent(content);
}
public void startScroll() {
scrollPos=0;
tr.getThreadManager().getLightweightTimer().scheduleAtFixedRate(scrollTimer = new TimerTask(){
@Override
public void run() {
scrollPos+=scrollIncrement;
briefingChars.setScrollPosition(scrollPos);
if(scrollPos>briefingChars.getNumActiveLines()+NUM_LINES){
BriefingScreen.this.stopScroll();
notifyScrollFinishCallbacks();
scrollFinishCallbacks.clear();
}
}}, 0, 20);
}//end startScroll()
public void stopScroll() {
scrollTimer.cancel();
}
private void planetDisplayMode(LVLFile lvl){
final Game game = tr.getGame();
final ResourceManager rm = tr.getResourceManager();
final Camera camera = tr.renderer.get().getCamera();
final GL3 gl = tr.gpu.get().getGl();
this.lvl = lvl;
camera.probeForBehavior(MatchPosition.class) .setEnable(false);
camera.probeForBehavior(MatchDirection.class) .setEnable(false);
camera.probeForBehavior(FacingObject.class) .setEnable(true);
camera.probeForBehavior(RotateAroundObject.class).setEnable(true);
//Planet introduction
game.setDisplayMode(game.briefingMode);
if(planetObject!=null){
remove(planetObject);
planetObject=null;
}
try{
final Model planetModel = rm.getBINModel(
missionTXT.getPlanetModelFile(),
rm.getRAWAsTexture(missionTXT.getPlanetTextureFile(),
getPalette(), gl,false, true),
8,false,getPalette(),gl);
planetObject = new WorldObject(tr,planetModel);
planetObject.setPosition(0, TR.mapSquareSize*20, 0);
add(planetObject);
planetObject.setVisible(true);
camera.probeForBehavior(FacingObject.class) .setTarget(planetObject);
camera.probeForBehavior(RotateAroundObject.class).setTarget(planetObject);
camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.05);
camera.probeForBehavior(RotateAroundObject.class).setOffset(
new double []{0,-planetModel.getTriangleList().getMaximumVertexDims().getY(),0});
camera.probeForBehavior(RotateAroundObject.class).setDistance(
planetModel.getTriangleList().getMaximumVertexDims().getX()*4);
}catch(Exception e){tr.showStopper(e);}
}//end planetDisplayMode()
public void missionCompleteSummary(LVLFile lvl, Result r){
planetDisplayMode(lvl);
final Game game = tr.getGame();
setContent("Air targets destroyed: "+r.getAirTargetsDestroyed()+
"\nGround targets destroyed: "+r.getGroundTargetsDestroyed()+
"\nVegetation destroyed: "+r.getFoliageDestroyed()+
"\nTunnels found: "+(int)(r.getTunnelsFoundPctNorm()*100.)+"%");
game.getCurrentMission().getOverworldSystem().activate();
tr.getWorld().setFogColor(Color.black);
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
final Camera camera = tr.renderer.get().getCamera();
camera.probeForBehavior(MatchPosition.class) .setEnable(true);
camera.probeForBehavior(MatchDirection.class) .setEnable(true);
camera.probeForBehavior(FacingObject.class) .setEnable(false);
camera.probeForBehavior(RotateAroundObject.class).setEnable(false);
game.getCurrentMission().getOverworldSystem().deactivate();
}//end missionCompleteSummary()
public void briefingSequence(LVLFile lvl) {
final Game game = tr.getGame();
final ResourceManager rm = tr.getResourceManager();
final Camera camera = tr.renderer.get().getCamera();
missionTXT = rm.getMissionText(lvl.getBriefingTextFile());
planetDisplayMode(lvl);
setContent(
missionTXT.getMissionText().replace("\r","").replace("$C", ""+game.getPlayerName()));
game.getCurrentMission().getOverworldSystem().activate();
tr.getWorld().setFogColor(Color.black);
startScroll();
final boolean [] mWait = new boolean[]{false};
addScrollFinishCallback(new Runnable(){
@Override
public void run() {
synchronized(mWait){mWait[0] = true; mWait.notifyAll();}
}});
final Thread spacebarWaitThread;
(spacebarWaitThread = new Thread(){
@Override
public void run(){
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
synchronized(mWait){mWait[0] = true; mWait.notifyAll();}
}//end run()
}).start();
try{synchronized(mWait){while(!mWait[0])mWait.wait();}}
catch(InterruptedException e){}
stopScroll();
spacebarWaitThread.interrupt();
//Enemy introduction
tr.getWorld().setFogColor(game.getCurrentMission().getOverworldSystem().getFogColor());
for(EnemyIntro intro:game.getCurrentMission().getOverworldSystem().getObjectSystem().getDefPlacer().getEnemyIntros()){
final WorldObject wo = intro.getWorldObject();
camera.probeForBehavior(FacingObject.class).setTarget(wo);
camera.probeForBehavior(RotateAroundObject.class).setTarget(wo);
camera.probeForBehavior(RotateAroundObject.class).setAngularVelocityRPS(.3);
//Roughly center the object (ground objects have their bottom at Y=0)
if(wo.getModel().getTriangleList()!=null){
camera.probeForBehavior(RotateAroundObject.class).setOffset(
new double []{
0,
wo.getModel().
getTriangleList().
getMaximumVertexDims().
getY()/2,
0});
camera.probeForBehavior(RotateAroundObject.class).setDistance(
wo.getModel().getTriangleList().getMaximumVertexDims().getX()*6);}
else if(wo.getModel().getTransparentTriangleList()!=null){
camera.probeForBehavior(RotateAroundObject.class).setOffset(
new double []{
0,
wo.getModel().
getTransparentTriangleList().
getMaximumVertexDims().
getY()/2,
0});
camera.probeForBehavior(RotateAroundObject.class).setDistance(
wo.getModel().getTransparentTriangleList().getMaximumVertexDims().getX()*6);}
wo.tick(System.currentTimeMillis());//Make sure its position and state is sane.
camera.tick(System.currentTimeMillis());//Make sure the camera knows what is going on.
wo.setRespondToTick(false);//freeze
briefingChars.setScrollPosition(NUM_LINES-2);
setContent(intro.getDescriptionString());
tr.getKeyStatus().waitForSequenceTyped(KeyEvent.VK_SPACE);
wo.setRespondToTick(true);//unfreeze
}//end for(enemyIntros)
camera.probeForBehavior(FacingObject.class).setEnable(false);
camera.probeForBehavior(RotateAroundObject.class).setEnable(false);
camera.probeForBehavior(MatchPosition.class).setEnable(true);
camera.probeForBehavior(MatchDirection.class).setEnable(true);
}//end briefingSequence
private ColorPaletteVectorList getPalette(){
if(palette==null){
try{palette = new ColorPaletteVectorList(tr.getResourceManager().getPalette(lvl.getGlobalPaletteFile()));}
catch(Exception e){tr.showStopper(e);}
}//end if(null)
return palette;
}//end ColorPaletteVectorList
}//end BriefingScreen
|
package org.mcupdater.gui;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConsoleArea extends JTextPane {
private final StyledDocument doc = this.getStyledDocument();
public final Style infoStyle = doc.addStyle("Info", null);
public final Style warnStyle = doc.addStyle("Warning", null);
public final Style errorStyle = doc.addStyle("Error", null);
private final ConcurrentLinkedQueue<Entry> logQueue = new ConcurrentLinkedQueue<>();
public ConsoleArea() {
this.setBackground(Color.white);
StyleConstants.setForeground(infoStyle, new Color(0x007700));
StyleConstants.setForeground(warnStyle, new Color(0xaaaa00));
StyleConstants.setForeground(errorStyle, Color.red);
this.setEditable(false);
//this.getDocument().addDocumentListener(new LimitLinesDocumentListener(200));
this.startQueue();
}
private void startQueue() {
Thread queueDaemon = new Thread() {
@SuppressWarnings("InfiniteLoopStatement")
@Override
public void run() {
while (true) {
Entry current = logQueue.poll();
if (current != null) {
try {
doc.insertString(doc.getLength(), current.msg, current.style);
setCaretPosition(doc.getLength());
} catch (BadLocationException e) {
e.printStackTrace();
}
} else {
while (doc.getDefaultRootElement().getElementCount() > 200) {
Element line = doc.getDefaultRootElement().getElement(0);
try {
doc.remove(0,line.getEndOffset());
} catch (BadLocationException e) {
e.printStackTrace();
}
}
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
queueDaemon.setDaemon(true);
queueDaemon.start();
}
public void log(String msg) {
log(msg, null);
}
public void log(String msg, Style a) {
logQueue.add(new Entry(msg, a));
}
@Override
public boolean getScrollableTracksViewportWidth() {
return getUI().getPreferredSize(this).width <= getParent().getSize().width;
}
private class Entry {
public String msg;
public Style style;
Entry(String msg, Style style) {
this.msg = msg;
this.style = style;
}
}
}
|
package org.oucs.gaboto.entities;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*<p>This class was automatically generated by Gaboto<p>
*/
public class Site extends Place {
private static Map<String, List<Method>> indirectPropertyLookupTable;
static{
indirectPropertyLookupTable = new HashMap<String, List<Method>>();
List<Method> list;
try{
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getType(){
return "http://ns.ox.ac.uk/namespace/oxpoints/2009/02/owl#Site";
}
protected List<Method> getIndirectMethodsForProperty(String propertyURI){
List<Method> list = super.getIndirectMethodsForProperty(propertyURI);
if(null == list)
return indirectPropertyLookupTable.get(propertyURI);
else{
List<Method> tmp = indirectPropertyLookupTable.get(propertyURI);
if(null != tmp)
list.addAll(tmp);
}
return list;
}
}
|
package org.spout.renderer.gl;
import java.nio.ByteBuffer;
import org.spout.renderer.Creatable;
import org.spout.renderer.GLVersioned;
import org.spout.renderer.data.VertexAttribute.DataType;
/**
* Represents a texture for OpenGL. Image data can be set with one of the <code>setImageData(...)</code> methods before creation, but this is not obligatory. This results in an empty texture, with an
* undefined content. This is mostly used for frame buffers.
*/
public abstract class Texture extends Creatable implements GLVersioned {
protected int id = 0;
// The format
protected Format format = Format.RGB;
protected InternalFormat internalFormat = null;
protected DataType type = DataType.UNSIGNED_BYTE;
// Wrapping modes for s and t
protected WrapMode wrapT = WrapMode.REPEAT;
protected WrapMode wrapS = WrapMode.REPEAT;
// Minimisation and magnification modes
protected FilterMode minFilter = FilterMode.NEAREST;
protected FilterMode magFilter = FilterMode.NEAREST;
// Anisotropic filtering
protected float anisotropicFiltering = 0;
// Compare modes for PCF
protected CompareMode compareMode = null;
// The texture image data
protected ByteBuffer imageData;
// Texture image dimensions
protected int width;
protected int height;
@Override
public void create() {
imageData = null;
super.create();
}
@Override
public void destroy() {
id = 0;
super.destroy();
}
/**
* Binds the texture to the OpenGL context.
*
* @param unit The unit to bind the texture to, or -1 to just bind the texture
*/
public abstract void bind(int unit);
/**
* Unbinds the texture from the OpenGL context.
*/
public abstract void unbind();
/**
* Gets the ID for this texture as assigned by OpenGL.
*
* @return The ID
*/
public int getID() {
return id;
}
/**
* Sets the texture's format.
*
* @param format The format to set
*/
public void setFormat(Format format) {
if (format == null) {
throw new IllegalArgumentException("Format cannot be null");
}
this.format = format;
}
/**
* Sets the texture's internal format. Set to null to use the un-sized format instead.
*
* @param internalFormat The internal format to set
*/
public void setInternalFormat(InternalFormat internalFormat) {
this.internalFormat = internalFormat;
}
/**
* Sets the value for anisotropic filtering. A value smaller or equal to zero is considered as no filtering. Note that this is EXT based and might not be supported on all hardware.
*
* @param value The anisotropic filtering value
*/
public void setAnisotropicFiltering(float value) {
this.anisotropicFiltering = value;
}
/**
* Sets the texture's data type.
*
* @param type The type to set
*/
public void setComponentType(DataType type) {
if (type == null) {
throw new IllegalArgumentException("Type cannot be null");
}
this.type = type;
}
/**
* Sets the horizontal texture wrap.
*
* @param wrapS Horizontal texture wrap
*/
public void setWrapS(WrapMode wrapS) {
if (wrapS == null) {
throw new IllegalArgumentException("Wrap cannot be null");
}
this.wrapS = wrapS;
}
/**
* Sets the vertical texture wrap.
*
* @param wrapT Vertical texture wrap
*/
public void setWrapT(WrapMode wrapT) {
if (wrapT == null) {
throw new IllegalArgumentException("Wrap cannot be null");
}
this.wrapT = wrapT;
}
/**
* Sets the texture's min filter.
*
* @param minFilter The min filter
*/
public void setMinFilter(FilterMode minFilter) {
if (minFilter == null) {
throw new IllegalArgumentException("Filter cannot be null");
}
this.minFilter = minFilter;
}
/**
* Sets the texture's mag filter. Filters that require mipmaps generation cannot be used here.
*
* @param magFilter The mag filter
*/
public void setMagFilter(FilterMode magFilter) {
if (magFilter == null) {
throw new IllegalArgumentException("Filter cannot be null");
}
if (magFilter.needsMipMaps()) {
throw new IllegalArgumentException("Mimpmap filters cannot be used for texture magnification");
}
this.magFilter = magFilter;
}
/**
* Sets the compare mode. If null, this feature is deactivated. Used this for PCF with shadow samplers.
*
* @param compareMode The compare mode
*/
public void setCompareMode(CompareMode compareMode) {
this.compareMode = compareMode;
}
/**
* Sets the texture's image data. The image data reading is done according the the set {@link org.spout.renderer.gl.Texture.Format}.
*
* @param imageData The image data
* @param width The width of the image
* @param height the height of the image
*/
public void setImageData(ByteBuffer imageData, int width, int height) {
this.imageData = imageData;
this.width = width;
this.height = height;
}
/**
* Returns the image data. After creation is over, it returns null.
*
* @return The image data
*/
public ByteBuffer getImageData() {
return imageData;
}
/**
* Returns the width of the image.
*
* @return The image width
*/
public int getWidth() {
return width;
}
/**
* Returns the height of the image.
*
* @return The image height
*/
public int getHeight() {
return height;
}
/**
* An enum of texture component formats.
*/
public static enum Format {
RED(0x1903, 1, true, false, false, false, false, false), // GL11.GL_RED
RGB(0x1907, 3, true, true, true, false, false, false), // GL11.GL_RGB
RGBA(0x1908, 4, true, true, true, true, false, false), // GL11.GL_RGBA
DEPTH(0x1902, 1, false, false, false, false, true, false), // GL11.GL_DEPTH_COMPONENT
RG(0x8227, 2, true, true, false, false, false, false), // GL30.GL_RG
DEPTH_STENCIL(0x84F9, 1, false, false, false, false, false, true); // GL30.GL_DEPTH_STENCIL
private final int glConstant;
private final int components;
private final boolean hasRed;
private final boolean hasGreen;
private final boolean hasBlue;
private final boolean hasAlpha;
private final boolean hasDepth;
private final boolean hasStencil;
private Format(int glConstant, int components, boolean hasRed, boolean hasGreen, boolean hasBlue, boolean hasAlpha, boolean hasDepth, boolean hasStencil) {
this.glConstant = glConstant;
this.components = components;
this.hasRed = hasRed;
this.hasGreen = hasGreen;
this.hasBlue = hasBlue;
this.hasAlpha = hasAlpha;
this.hasDepth = hasDepth;
this.hasStencil = hasStencil;
}
/**
* Gets the OpenGL constant for this format.
*
* @return The OpenGL Constant
*/
public int getGLConstant() {
return glConstant;
}
/**
* Returns the number of components in the format.
*
* @return The number of components
*/
public int getComponentCount() {
return components;
}
/**
* Returns true if this format has a red component.
*
* @return True if a red component is present
*/
public boolean hasRed() {
return hasRed;
}
/**
* Returns true if this format has a green component.
*
* @return True if a green component is present
*/
public boolean hasGreen() {
return hasGreen;
}
/**
* Returns true if this format has a blue component.
*
* @return True if a blue component is present
*/
public boolean hasBlue() {
return hasBlue;
}
/**
* Returns true if this format has an alpha component.
*
* @return True if an alpha component is present
*/
public boolean hasAlpha() {
return hasAlpha;
}
/**
* Returns true if this format has a depth component.
*
* @return True if a depth component is present
*/
public boolean hasDepth() {
return hasDepth;
}
/**
* Returns true if this format has a stencil component.
*
* @return True if a stencil component is present
*/
public boolean hasStencil() {
return hasStencil;
}
}
/**
* An enum of sized texture component formats.
*/
public static enum InternalFormat {
RGB8(0x8051), // GL11.GL_RGB8
RGBA8(0x8058), // GL11.GL_RGBA8
RGBA16(0x805B), // GL11.GL_RGBA16
DEPTH_COMPONENT16(0x81A5), // GL14.GL_DEPTH_COMPONENT16
DEPTH_COMPONENT24(0x81A6), // GL14.GL_DEPTH_COMPONENT24
DEPTH_COMPONENT32(0x81A7), // GL14.GL_DEPTH_COMPONENT32
R8(0x8229), // GL30.GL_R8
R16(0x822A), // GL30.GL_R16
RG8(0x822B), // GL30.GL_RG8
RG16(0x822C), // GL30.GL_RG16
R16F(0x822D), // GL30.GL_R16F
R32F(0x822E), // GL30.GL_R32F
RG16F(0x822F), // GL30.GL_RG16F
RG32F(0x8230), // GL30.GL_RG32F
RGBA32F(0x8814), // GL30.GL_RGBA32F
RGB32F(0x8815), // GL30.GL_RGB32F
RGBA16F(0x881A), // GL30.GL_RGBA16F
RGB16F(0x881B); // GL30.GL_RGB16F
private final int glConstant;
private InternalFormat(int glConstant) {
this.glConstant = glConstant;
}
/**
* Gets the OpenGL constant for this internal format.
*
* @return The OpenGL Constant
*/
public int getGLConstant() {
return glConstant;
}
}
/**
* An enum for the texture wrapping modes.
*/
public static enum WrapMode {
REPEAT(0x2901), // GL11.GL_REPEAT
CLAMP_TO_EDGE(0x812F), // GL12.GL_CLAMP_TO_EDGE
CLAMP_TO_BORDER(0x812D), // GL13.GL_CLAMP_TO_BORDER
MIRRORED_REPEAT(0x8370); // GL14.GL_MIRRORED_REPEAT
private final int glConstant;
private WrapMode(int glConstant) {
this.glConstant = glConstant;
}
/**
* Gets the OpenGL constant for this texture wrap.
*
* @return The OpenGL Constant
*/
public int getGLConstant() {
return glConstant;
}
}
/**
* An enum for the texture filtering modes.
*/
public static enum FilterMode {
LINEAR(0x2601), // GL11.GL_LINEAR
NEAREST(0x2600), // GL11.GL_NEAREST
NEAREST_MIPMAP_NEAREST(0x2700), // GL11.GL_NEAREST_MIPMAP_NEAREST
LINEAR_MIPMAP_NEAREST(0x2701), //GL11.GL_LINEAR_MIPMAP_NEAREST
NEAREST_MIPMAP_LINEAR(0x2702), // GL11.GL_NEAREST_MIPMAP_LINEAR
LINEAR_MIPMAP_LINEAR(0x2703); // GL11.GL_LINEAR_MIPMAP_LINEAR
private final int glConstant;
private FilterMode(int glConstant) {
this.glConstant = glConstant;
}
/**
* Gets the OpenGL constant for this texture filter.
*
* @return The OpenGL Constant
*/
public int getGLConstant() {
return glConstant;
}
/**
* Returns true if the filtering mode required generation of mipmaps.
*
* @return Whether or not mipmaps are required
*/
public boolean needsMipMaps() {
return this == NEAREST_MIPMAP_NEAREST || this == LINEAR_MIPMAP_NEAREST
|| this == NEAREST_MIPMAP_LINEAR || this == LINEAR_MIPMAP_LINEAR;
}
}
public static enum CompareMode {
LEQUAL(0x203), // GL11.GL_LEQUAL
GEQUAL(0x206), // GL11.GL_GEQUAL
LESS(0x201), // GL11.GL_LESS
GREATER(0x204), // GL11.GL_GREATER
EQUAL(0x202), // GL11.GL_EQUAL
NOTEQUAL(0x205), // GL11.GL_NOTEQUAL
ALWAYS(0x206), // GL11.GL_ALWAYS
NEVER(0x200); // GL11.GL_NEVER
private final int glConstant;
private CompareMode(int glConstant) {
this.glConstant = glConstant;
}
/**
* Gets the OpenGL constant for this texture filter.
*
* @return The OpenGL Constant
*/
public int getGLConstant() {
return glConstant;
}
}
}
|
package org.waag.histograph.es;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.waag.histograph.util.Configuration;
/**
* A wrapper class that initializes the Elasticsearch client, based on the provided configuration parameters.
* @author Rutger van Willigen
* @author Bert Spaan
*/
public class ESInit {
/**
* Static method that creates an Elasticsearch client
* @param config Configuration object containing Elasticsearch connection parameters.
* @return Returns a {@link JestClient} object with a succesfully established Elasticsearch connection.
* @throws Exception Thrown if the connection of the newly created client fails.
*/
public static JestClient initES (Configuration config) throws Exception {
JestClientFactory factory = new JestClientFactory();
String url = "http://" + config.ELASTICSEARCH_HOST + ":" + config.ELASTICSEARCH_PORT;
factory.setHttpClientConfig(new HttpClientConfig.Builder(url)
.multiThreaded(true)
.readTimeout(20000)
.build());
JestClient client = factory.getObject();
ESMethods.testConnection(client, config);
return client;
}
}
|
package org.zendesk.client.v2;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.asynchttpclient.request.body.multipart.FilePart;
import org.asynchttpclient.request.body.multipart.StringPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zendesk.client.v2.model.AgentRole;
import org.zendesk.client.v2.model.Attachment;
import org.zendesk.client.v2.model.Audit;
import org.zendesk.client.v2.model.Automation;
import org.zendesk.client.v2.model.Brand;
import org.zendesk.client.v2.model.Comment;
import org.zendesk.client.v2.model.Field;
import org.zendesk.client.v2.model.Forum;
import org.zendesk.client.v2.model.Group;
import org.zendesk.client.v2.model.GroupMembership;
import org.zendesk.client.v2.model.Identity;
import org.zendesk.client.v2.model.JobStatus;
import org.zendesk.client.v2.model.Macro;
import org.zendesk.client.v2.model.Metric;
import org.zendesk.client.v2.model.Organization;
import org.zendesk.client.v2.model.OrganizationField;
import org.zendesk.client.v2.model.OrganizationMembership;
import org.zendesk.client.v2.model.SatisfactionRating;
import org.zendesk.client.v2.model.SearchResultEntity;
import org.zendesk.client.v2.model.Status;
import org.zendesk.client.v2.model.SuspendedTicket;
import org.zendesk.client.v2.model.Ticket;
import org.zendesk.client.v2.model.TicketForm;
import org.zendesk.client.v2.model.TicketImport;
import org.zendesk.client.v2.model.TicketResult;
import org.zendesk.client.v2.model.Topic;
import org.zendesk.client.v2.model.Trigger;
import org.zendesk.client.v2.model.TwitterMonitor;
import org.zendesk.client.v2.model.User;
import org.zendesk.client.v2.model.UserField;
import org.zendesk.client.v2.model.hc.Article;
import org.zendesk.client.v2.model.hc.ArticleAttachments;
import org.zendesk.client.v2.model.hc.Category;
import org.zendesk.client.v2.model.hc.Section;
import org.zendesk.client.v2.model.hc.Subscription;
import org.zendesk.client.v2.model.hc.Translation;
import org.zendesk.client.v2.model.schedules.Holiday;
import org.zendesk.client.v2.model.schedules.Schedule;
import org.zendesk.client.v2.model.targets.BasecampTarget;
import org.zendesk.client.v2.model.targets.CampfireTarget;
import org.zendesk.client.v2.model.targets.EmailTarget;
import org.zendesk.client.v2.model.targets.PivotalTarget;
import org.zendesk.client.v2.model.targets.Target;
import org.zendesk.client.v2.model.targets.TwitterTarget;
import org.zendesk.client.v2.model.targets.UrlTarget;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* @author stephenc
* @since 04/04/2013 13:08
*/
public class Zendesk implements Closeable {
private static final String JSON = "application/json; charset=UTF-8";
private final boolean closeClient;
private final AsyncHttpClient client;
private final Realm realm;
private final String url;
private final String oauthToken;
private final ObjectMapper mapper;
private final Logger logger;
private boolean closed = false;
private static final Map<String, Class<? extends SearchResultEntity>> searchResultTypes = searchResultTypes();
private static final Map<String, Class<? extends Target>> targetTypes = targetTypes();
private static Map<String, Class<? extends SearchResultEntity>> searchResultTypes() {
Map<String, Class<? extends SearchResultEntity>> result = new HashMap<>();
result.put("ticket", Ticket.class);
result.put("user", User.class);
result.put("group", Group.class);
result.put("organization", Organization.class);
result.put("topic", Topic.class);
result.put("article", Article.class);
return Collections.unmodifiableMap(result);
}
private static Map<String, Class<? extends Target>> targetTypes() {
Map<String, Class<? extends Target>> result = new HashMap<>();
result.put("url_target", UrlTarget.class);
result.put("email_target",EmailTarget.class);
result.put("basecamp_target", BasecampTarget.class);
result.put("campfire_target", CampfireTarget.class);
result.put("pivotal_target", PivotalTarget.class);
result.put("twitter_target", TwitterTarget.class);
// TODO: Implement other Target types
//result.put("clickatell_target", ClickatellTarget.class);
//result.put("flowdock_target", FlowdockTarget.class);
//result.put("get_satisfaction_target", GetSatisfactionTarget.class);
//result.put("yammer_target", YammerTarget.class);
return Collections.unmodifiableMap(result);
}
private Zendesk(AsyncHttpClient client, String url, String username, String password) {
this.logger = LoggerFactory.getLogger(Zendesk.class);
this.closeClient = client == null;
this.oauthToken = null;
this.client = client == null ? new DefaultAsyncHttpClient() : client;
this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2";
if (username != null) {
this.realm = new Realm.Builder(username, password)
.setScheme(Realm.AuthScheme.BASIC)
.setUsePreemptiveAuth(true)
.build();
} else {
if (password != null) {
throw new IllegalStateException("Cannot specify token or password without specifying username");
}
this.realm = null;
}
this.mapper = createMapper();
}
private Zendesk(AsyncHttpClient client, String url, String oauthToken) {
this.logger = LoggerFactory.getLogger(Zendesk.class);
this.closeClient = client == null;
this.realm = null;
this.client = client == null ? new DefaultAsyncHttpClient() : client;
this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2";
if (oauthToken != null) {
this.oauthToken = oauthToken;
} else {
throw new IllegalStateException("Cannot specify token or password without specifying username");
}
this.mapper = createMapper();
}
// Closeable interface methods
public boolean isClosed() {
return closed || client.isClosed();
}
public void close() {
if (closeClient && !client.isClosed()) {
try {
client.close();
} catch (IOException e) {
logger.warn("Unexpected error on client close", e);
}
}
closed = true;
}
// Action methods
public <T> JobStatus<T> getJobStatus(JobStatus<T> status) {
return complete(getJobStatusAsync(status));
}
public <T> ListenableFuture<JobStatus<T>> getJobStatusAsync(JobStatus<T> status) {
return submit(req("GET", tmpl("/job_statuses/{id}.json").set("id", status.getId())), handleJobStatus(status.getResultsClass()));
}
public List<JobStatus<HashMap<String, Object>>> getJobStatuses(List<JobStatus> statuses) {
return complete(getJobStatusesAsync(statuses));
}
public ListenableFuture<List<JobStatus<HashMap<String, Object>>>> getJobStatusesAsync(List<JobStatus> statuses) {
List<String> ids = new ArrayList<>(statuses.size());
for (JobStatus status : statuses) {
ids.add(status.getId());
}
Class<JobStatus<HashMap<String, Object>>> clazz = (Class<JobStatus<HashMap<String, Object>>>)(Object)JobStatus.class;
return submit(req("GET", tmpl("/job_statuses/show_many.json{?ids}").set("ids", ids)), handleList(clazz, "job_statuses"));
}
public List<Brand> getBrands(){
return complete(submit(req("GET", cnst("/brands.json")), handleList(Brand.class,
"brands")));
}
public TicketForm getTicketForm(long id) {
return complete(submit(req("GET", tmpl("/ticket_forms/{id}.json").set("id", id)), handle(TicketForm.class,
"ticket_form")));
}
public List<TicketForm> getTicketForms() {
return complete(submit(req("GET", cnst("/ticket_forms.json")), handleList(TicketForm.class,
"ticket_forms")));
}
public TicketForm createTicketForm(TicketForm ticketForm) {
return complete(submit(req("POST", cnst("/ticket_forms.json"), JSON, json(
Collections.singletonMap("ticket_form", ticketForm))), handle(TicketForm.class, "ticket_form")));
}
public Ticket importTicket(TicketImport ticketImport) {
return complete(submit(req("POST", cnst("/imports/tickets.json"),
JSON, json(Collections.singletonMap("ticket", ticketImport))),
handle(Ticket.class, "ticket")));
}
public JobStatus<Ticket> importTickets(TicketImport... ticketImports) {
return importTickets(Arrays.asList(ticketImports));
}
public JobStatus<Ticket> importTickets(List<TicketImport> ticketImports) {
return complete(importTicketsAsync(ticketImports));
}
public ListenableFuture<JobStatus<Ticket>> importTicketsAsync(List<TicketImport> ticketImports) {
return submit(req("POST", cnst("/imports/tickets/create_many.json"), JSON, json(
Collections.singletonMap("tickets", ticketImports))), handleJobStatus(Ticket.class));
}
public Ticket getTicket(long id) {
return complete(submit(req("GET", tmpl("/tickets/{id}.json").set("id", id)), handle(Ticket.class,
"ticket")));
}
public List<Ticket> getTicketIncidents(long id) {
return complete(submit(req("GET", tmpl("/tickets/{id}/incidents.json").set("id", id)),
handleList(Ticket.class, "tickets")));
}
public List<User> getTicketCollaborators(long id) {
return complete(submit(req("GET", tmpl("/tickets/{id}/collaborators.json").set("id", id)),
handleList(User.class, "users")));
}
public void deleteTicket(Ticket ticket) {
checkHasId(ticket);
deleteTicket(ticket.getId());
}
public void deleteTicket(long id) {
complete(submit(req("DELETE", tmpl("/tickets/{id}.json").set("id", id)), handleStatus()));
}
public ListenableFuture<JobStatus<Ticket>> queueCreateTicketAsync(Ticket ticket) {
return submit(req("POST", cnst("/tickets.json?async=true"),
JSON, json(Collections.singletonMap("ticket", ticket))),
handleJobStatus(Ticket.class));
}
public ListenableFuture<Ticket> createTicketAsync(Ticket ticket) {
return submit(req("POST", cnst("/tickets.json"),
JSON, json(Collections.singletonMap("ticket", ticket))),
handle(Ticket.class, "ticket"));
}
public Ticket createTicket(Ticket ticket) {
return complete(createTicketAsync(ticket));
}
public JobStatus<Ticket> createTickets(Ticket... tickets) {
return createTickets(Arrays.asList(tickets));
}
public JobStatus<Ticket> createTickets(List<Ticket> tickets) {
return complete(createTicketsAsync(tickets));
}
public ListenableFuture<JobStatus<Ticket>> createTicketsAsync(List<Ticket> tickets) {
return submit(req("POST", cnst("/tickets/create_many.json"), JSON, json(
Collections.singletonMap("tickets", tickets))), handleJobStatus(Ticket.class));
}
public Ticket updateTicket(Ticket ticket) {
checkHasId(ticket);
return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticket.getId()),
JSON, json(Collections.singletonMap("ticket", ticket))),
handle(Ticket.class, "ticket")));
}
public void markTicketAsSpam(Ticket ticket) {
checkHasId(ticket);
markTicketAsSpam(ticket.getId());
}
public void markTicketAsSpam(long id) {
complete(submit(req("PUT", tmpl("/tickets/{id}/mark_as_spam.json").set("id", id)), handleStatus()));
}
public void deleteTickets(long id, long... ids) {
complete(submit(req("DELETE", tmpl("/tickets/destroy_many.json{?ids}").set("ids", idArray(id, ids))),
handleStatus()));
}
public Iterable<Ticket> getTickets() {
return new PagedIterable<>(cnst("/tickets.json"), handleList(Ticket.class, "tickets"));
}
/**
* @deprecated This API is no longer available from the vendor. Use the {@link #getTicketsFromSearch(String)} method instead
* @param ticketStatus
* @return
*/
@Deprecated
public Iterable<Ticket> getTicketsByStatus(Status... ticketStatus) {
return new PagedIterable<>(tmpl("/tickets.json{?status}").set("status", statusArray(ticketStatus)),
handleList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getTicketsByExternalId(String externalId, boolean includeArchived) {
Iterable<Ticket> results =
new PagedIterable<>(tmpl("/tickets.json{?external_id}").set("external_id", externalId),
handleList(Ticket.class, "tickets"));
if (!includeArchived || results.iterator().hasNext()) {
return results;
}
return new PagedIterable<>(
tmpl("/search.json{?query}{&type}").set("query", "external_id:" + externalId).set("type", "ticket"),
handleList(Ticket.class, "results"));
}
public Iterable<Ticket> getTicketsByExternalId(String externalId) {
return getTicketsByExternalId(externalId, false);
}
public Iterable<Ticket> getTicketsFromSearch(String searchTerm) {
return new PagedIterable<>(tmpl("/search.json{?query}").set("query", searchTerm + "+type:ticket"),
handleList(Ticket.class, "results"));
}
public Iterable<Article> getArticleFromSearch(String searchTerm) {
return new PagedIterable<>(tmpl("/help_center/articles/search.json{?query}").set("query", searchTerm),
handleList(Article.class, "results"));
}
public Iterable<Article> getArticleFromSearch(String searchTerm, Long sectionId) {
return new PagedIterable<>(tmpl("/help_center/articles/search.json{?section,query}")
.set("query", searchTerm).set("section", sectionId), handleList(Article.class, "results"));
}
public List<ArticleAttachments> getAttachmentsFromArticle(Long articleID) {
return complete(submit(req("GET", tmpl("/help_center/articles/{id}/attachments.json").set("id", articleID)),
handleArticleAttachmentsList("article_attachments")));
}
public List<Ticket> getTickets(long id, long... ids) {
return complete(submit(req("GET", tmpl("/tickets/show_many.json{?ids}").set("ids", idArray(id, ids))),
handleList(Ticket.class, "tickets")));
}
public Iterable<Ticket> getRecentTickets() {
return new PagedIterable<>(cnst("/tickets/recent.json"), handleList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getTicketsIncrementally(Date startTime) {
return new PagedIterable<>(
tmpl("/incremental/tickets.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())),
handleIncrementalList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) {
return new PagedIterable<>(
tmpl("/incremental/tickets.json{?start_time,end_time}")
.set("start_time", msToSeconds(startTime.getTime()))
.set("end_time", msToSeconds(endTime.getTime())),
handleIncrementalList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getOrganizationTickets(long organizationId) {
return new PagedIterable<>(
tmpl("/organizations/{organizationId}/tickets.json").set("organizationId", organizationId),
handleList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getUserRequestedTickets(long userId) {
return new PagedIterable<>(tmpl("/users/{userId}/tickets/requested.json").set("userId", userId),
handleList(Ticket.class, "tickets"));
}
public Iterable<Ticket> getUserCCDTickets(long userId) {
return new PagedIterable<>(tmpl("/users/{userId}/tickets/ccd.json").set("userId", userId),
handleList(Ticket.class, "tickets"));
}
public Iterable<Metric> getTicketMetrics() {
return new PagedIterable<>(cnst("/ticket_metrics.json"), handleList(Metric.class, "ticket_metrics"));
}
public Metric getTicketMetricByTicket(long id) {
return complete(submit(req("GET", tmpl("/tickets/{ticketId}/metrics.json").set("ticketId", id)), handle(Metric.class, "ticket_metric")));
}
public Metric getTicketMetric(long id) {
return complete(submit(req("GET", tmpl("/ticket_metrics/{ticketMetricId}.json").set("ticketMetricId", id)), handle(Metric.class, "ticket_metric")));
}
public Iterable<Audit> getTicketAudits(Ticket ticket) {
checkHasId(ticket);
return getTicketAudits(ticket.getId());
}
public Iterable<Audit> getTicketAudits(Long id) {
return new PagedIterable<>(tmpl("/tickets/{ticketId}/audits.json").set("ticketId", id),
handleList(Audit.class, "audits"));
}
public Audit getTicketAudit(Ticket ticket, Audit audit) {
checkHasId(audit);
return getTicketAudit(ticket, audit.getId());
}
public Audit getTicketAudit(Ticket ticket, long id) {
checkHasId(ticket);
return getTicketAudit(ticket.getId(), id);
}
public Audit getTicketAudit(long ticketId, long auditId) {
return complete(submit(req("GET",
tmpl("/tickets/{ticketId}/audits/{auditId}.json").set("ticketId", ticketId)
.set("auditId", auditId)),
handle(Audit.class, "audit")));
}
public void trustTicketAudit(Ticket ticket, Audit audit) {
checkHasId(audit);
trustTicketAudit(ticket, audit.getId());
}
public void trustTicketAudit(Ticket ticket, long id) {
checkHasId(ticket);
trustTicketAudit(ticket.getId(), id);
}
public void trustTicketAudit(long ticketId, long auditId) {
complete(submit(req("PUT", tmpl("/tickets/{ticketId}/audits/{auditId}/trust.json").set("ticketId", ticketId)
.set("auditId", auditId)), handleStatus()));
}
public void makePrivateTicketAudit(Ticket ticket, Audit audit) {
checkHasId(audit);
makePrivateTicketAudit(ticket, audit.getId());
}
public void makePrivateTicketAudit(Ticket ticket, long id) {
checkHasId(ticket);
makePrivateTicketAudit(ticket.getId(), id);
}
public void makePrivateTicketAudit(long ticketId, long auditId) {
complete(submit(req("PUT",
tmpl("/tickets/{ticketId}/audits/{auditId}/make_private.json").set("ticketId", ticketId)
.set("auditId", auditId)), handleStatus()));
}
public List<Field> getTicketFields() {
return complete(submit(req("GET", cnst("/ticket_fields.json")), handleList(Field.class, "ticket_fields")));
}
public Field getTicketField(long id) {
return complete(submit(req("GET", tmpl("/ticket_fields/{id}.json").set("id", id)), handle(Field.class,
"ticket_field")));
}
public Field createTicketField(Field field) {
return complete(submit(req("POST", cnst("/ticket_fields.json"), JSON, json(
Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field")));
}
public Field updateTicketField(Field field) {
checkHasId(field);
return complete(submit(req("PUT", tmpl("/ticket_fields/{id}.json").set("id", field.getId()), JSON,
json(Collections.singletonMap("ticket_field", field))), handle(Field.class, "ticket_field")));
}
public void deleteTicketField(Field field) {
checkHasId(field);
deleteTicket(field.getId());
}
public void deleteTicketField(long id) {
complete(submit(req("DELETE", tmpl("/ticket_fields/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<SuspendedTicket> getSuspendedTickets() {
return new PagedIterable<>(cnst("/suspended_tickets.json"),
handleList(SuspendedTicket.class, "suspended_tickets"));
}
public void deleteSuspendedTicket(SuspendedTicket ticket) {
checkHasId(ticket);
deleteSuspendedTicket(ticket.getId());
}
public void deleteSuspendedTicket(long id) {
complete(submit(req("DELETE", tmpl("/suspended_tickets/{id}.json").set("id", id)), handleStatus()));
}
public Attachment.Upload createUpload(String fileName, byte[] content) {
return createUpload(null, fileName, "application/binary", content);
}
public Attachment.Upload createUpload(String fileName, String contentType, byte[] content) {
return createUpload(null, fileName, contentType, content);
}
public Attachment.Upload createUpload(String token, String fileName, String contentType, byte[] content) {
TemplateUri uri = tmpl("/uploads.json{?filename,token}").set("filename", fileName);
if (token != null) {
uri.set("token", token);
}
return complete(
submit(req("POST", uri, contentType,
content), handle(Attachment.Upload.class, "upload")));
}
public void associateAttachmentsToArticle(String idArticle, List<Attachment> attachments) {
TemplateUri uri = tmpl("/help_center/articles/{article_id}/bulk_attachments.json").set("article_id", idArticle);
List<Long> attachmentsIds = new ArrayList<>();
for(Attachment item : attachments){
attachmentsIds.add(item.getId());
}
complete(submit(req("POST", uri, JSON, json(Collections.singletonMap("attachment_ids", attachmentsIds))), handleStatus()));
}
/**
* Create upload article with inline false
*/
public ArticleAttachments createUploadArticle(long articleId, File file) throws IOException {
return createUploadArticle(articleId, file, false);
}
public ArticleAttachments createUploadArticle(long articleId, File file, boolean inline) throws IOException {
BoundRequestBuilder builder = client.preparePost(tmpl("/help_center/articles/{id}/attachments.json").set("id", articleId).toString());
if (realm != null) {
builder.setRealm(realm);
} else {
builder.addHeader("Authorization", "Bearer " + oauthToken);
}
builder.setHeader("Content-Type", "multipart/form-data");
if (inline)
builder.addBodyPart(new StringPart("inline", "true"));
builder.addBodyPart(
new FilePart("file", file, "application/octet-stream", Charset.forName("UTF-8"), file.getName()));
final Request req = builder.build();
return complete(submit(req, handle(ArticleAttachments.class, "article_attachment")));
}
public void deleteUpload(Attachment.Upload upload) {
checkHasToken(upload);
deleteUpload(upload.getToken());
}
public void deleteUpload(String token) {
complete(submit(req("DELETE", tmpl("/uploads/{token}.json").set("token", token)), handleStatus()));
}
public Attachment getAttachment(Attachment attachment) {
checkHasId(attachment);
return getAttachment(attachment.getId());
}
public Attachment getAttachment(long id) {
return complete(submit(req("GET", tmpl("/attachments/{id}.json").set("id", id)), handle(Attachment.class,
"attachment")));
}
public void deleteAttachment(Attachment attachment) {
checkHasId(attachment);
deleteAttachment(attachment.getId());
}
public void deleteAttachment(long id) {
complete(submit(req("DELETE", tmpl("/attachments/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<Target> getTargets() {
return new PagedIterable<>(cnst("/targets.json"), handleTargetList("targets"));
}
public Target getTarget(long id) {
return complete(submit(req("GET", tmpl("/targets/{id}.json").set("id", id)), handle(Target.class, "target")));
}
public Target createTarget(Target target) {
return complete(submit(req("POST", cnst("/targets.json"), JSON, json(Collections.singletonMap("target", target))),
handle(Target.class, "target")));
}
public void deleteTarget(long targetId) {
complete(submit(req("DELETE", tmpl("/targets/{id}.json").set("id", targetId)), handleStatus()));
}
public Iterable<Trigger> getTriggers() {
return new PagedIterable<>(cnst("/triggers.json"), handleList(Trigger.class, "triggers"));
}
public Trigger getTrigger(long id) {
return complete(submit(req("GET", tmpl("/triggers/{id}.json").set("id", id)), handle(Trigger.class, "trigger")));
}
public Trigger createTrigger(Trigger trigger) {
return complete(submit(req("POST", cnst("/triggers.json"), JSON, json(Collections.singletonMap("trigger", trigger))),
handle(Trigger.class, "trigger")));
}
public Trigger updateTrigger(Long triggerId, Trigger trigger) {
return complete(submit(req("PUT", tmpl("/triggers/{id}.json").set("id", triggerId), JSON, json(Collections.singletonMap("trigger", trigger))),
handle(Trigger.class, "trigger")));
}
public void deleteTrigger(long triggerId) {
complete(submit(req("DELETE", tmpl("/triggers/{id}.json").set("id", triggerId)), handleStatus()));
}
// Automations
public Iterable<Automation> getAutomations() {
return new PagedIterable<>(cnst("/automations.json"),
handleList(Automation.class, "automations"));
}
public Automation getAutomation(long id) {
return complete(submit(req("GET", tmpl("/automations/{id}.json").set("id", id)),
handle(Automation.class, "automation")));
}
public Automation createAutomation(Automation automation) {
return complete(submit(
req("POST", cnst("/automations.json"), JSON,
json(Collections.singletonMap("automation", automation))),
handle(Automation.class, "automation")));
}
public Automation updateAutomation(Long automationId, Automation automation) {
return complete(submit(
req("PUT", tmpl("/automations/{id}.json").set("id", automationId), JSON,
json(Collections.singletonMap("automation", automation))),
handle(Automation.class, "automation")));
}
public void deleteAutomation(long automationId) {
complete(submit(req("DELETE", tmpl("/automations/{id}.json").set("id", automationId)),
handleStatus()));
}
public Iterable<TwitterMonitor> getTwitterMonitors() {
return new PagedIterable<>(cnst("/channels/twitter/monitored_twitter_handles.json"),
handleList(TwitterMonitor.class, "monitored_twitter_handles"));
}
public Iterable<User> getUsers() {
return new PagedIterable<>(cnst("/users.json"), handleList(User.class, "users"));
}
public Iterable<User> getUsersByRole(String role, String... roles) {
// Going to have to build this URI manually, because the RFC6570 template spec doesn't support
// variables like ?role[]=...role[]=..., which is what Zendesk requires.
// See https://developer.zendesk.com/rest_api/docs/core/users#filters
final StringBuilder uriBuilder = new StringBuilder("/users.json");
if (roles.length == 0) {
uriBuilder.append("?role=").append(encodeUrl(role));
} else {
uriBuilder.append("?role[]=").append(encodeUrl(role));
}
for (final String curRole : roles) {
uriBuilder.append("&role[]=").append(encodeUrl(curRole));
}
return new PagedIterable<>(cnst(uriBuilder.toString()), handleList(User.class, "users"));
}
public Iterable<User> getUsersIncrementally(Date startTime) {
return new PagedIterable<>(
tmpl("/incremental/users.json{?start_time}").set("start_time", msToSeconds(startTime.getTime())),
handleIncrementalList(User.class, "users"));
}
public Iterable<User> getGroupUsers(long id) {
return new PagedIterable<>(tmpl("/groups/{id}/users.json").set("id", id), handleList(User.class, "users"));
}
public Iterable<User> getOrganizationUsers(long id) {
return new PagedIterable<>(tmpl("/organizations/{id}/users.json").set("id", id),
handleList(User.class, "users"));
}
public User getUser(long id) {
return complete(submit(req("GET", tmpl("/users/{id}.json").set("id", id)), handle(User.class, "user")));
}
public User getAuthenticatedUser() {
return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user")));
}
public Iterable<UserField> getUserFields() {
return complete(submit(req("GET", cnst("/user_fields.json")),
handleList(UserField.class, "user_fields")));
}
public User createUser(User user) {
return complete(submit(req("POST", cnst("/users.json"), JSON, json(
Collections.singletonMap("user", user))), handle(User.class, "user")));
}
public JobStatus<User> createUsers(User... users) {
return createUsers(Arrays.asList(users));
}
public JobStatus<User> createUsers(List<User> users) {
return complete(createUsersAsync(users));
}
public User createOrUpdateUser(User user) {
return complete(submit(req("POST", cnst("/users/create_or_update.json"), JSON, json(
Collections.singletonMap("user", user))), handle(User.class, "user")));
}
public ListenableFuture<JobStatus<User>> createUsersAsync(List<User> users) {
return submit(req("POST", cnst("/users/create_many.json"), JSON, json(
Collections.singletonMap("users", users))), handleJobStatus(User.class));
}
public User updateUser(User user) {
checkHasId(user);
return complete(submit(req("PUT", tmpl("/users/{id}.json").set("id", user.getId()), JSON, json(
Collections.singletonMap("user", user))), handle(User.class, "user")));
}
public void deleteUser(User user) {
checkHasId(user);
deleteUser(user.getId());
}
public void deleteUser(long id) {
complete(submit(req("DELETE", tmpl("/users/{id}.json").set("id", id)), handleStatus()));
}
public User suspendUser(long id) {
User user = new User();
user.setId(id);
user.setSuspended(true);
return updateUser(user);
}
public User unsuspendUser(long id) {
User user = new User();
user.setId(id);
user.setSuspended(false);
return updateUser(user);
}
public Iterable<User> lookupUserByEmail(String email) {
return new PagedIterable<>(tmpl("/users/search.json{?query}").set("query", email),
handleList(User.class, "users"));
}
public Iterable<User> lookupUserByExternalId(String externalId) {
return new PagedIterable<>(tmpl("/users/search.json{?external_id}").set("external_id", externalId),
handleList(User.class, "users"));
}
public User getCurrentUser() {
return complete(submit(req("GET", cnst("/users/me.json")), handle(User.class, "user")));
}
public void resetUserPassword(User user, String password) {
checkHasId(user);
resetUserPassword(user.getId(), password);
}
public void resetUserPassword(long id, String password) {
complete(submit(req("POST", tmpl("/users/{id}/password.json").set("id", id), JSON,
json(Collections.singletonMap("password", password))), handleStatus()));
}
public void changeUserPassword(User user, String oldPassword, String newPassword) {
checkHasId(user);
Map<String, String> req = new HashMap<>();
req.put("previous_password", oldPassword);
req.put("password", newPassword);
complete(submit(req("PUT", tmpl("/users/{id}/password.json").set("id", user.getId()), JSON,
json(req)), handleStatus()));
}
public List<Identity> getUserIdentities(User user) {
checkHasId(user);
return getUserIdentities(user.getId());
}
public List<Identity> getUserIdentities(long userId) {
return complete(submit(req("GET", tmpl("/users/{id}/identities.json").set("id", userId)),
handleList(Identity.class, "identities")));
}
public Identity getUserIdentity(User user, Identity identity) {
checkHasId(identity);
return getUserIdentity(user, identity.getId());
}
public Identity getUserIdentity(User user, long identityId) {
checkHasId(user);
return getUserIdentity(user.getId(), identityId);
}
public Identity getUserIdentity(long userId, long identityId) {
return complete(submit(req("GET", tmpl("/users/{userId}/identities/{identityId}.json").set("userId", userId)
.set("identityId", identityId)), handle(
Identity.class, "identity")));
}
public List<Identity> setUserPrimaryIdentity(User user, Identity identity) {
checkHasId(identity);
return setUserPrimaryIdentity(user, identity.getId());
}
public List<Identity> setUserPrimaryIdentity(User user, long identityId) {
checkHasId(user);
return setUserPrimaryIdentity(user.getId(), identityId);
}
public List<Identity> setUserPrimaryIdentity(long userId, long identityId) {
return complete(submit(req("PUT",
tmpl("/users/{userId}/identities/{identityId}/make_primary.json").set("userId", userId)
.set("identityId", identityId), JSON, null),
handleList(Identity.class, "identities")));
}
public Identity verifyUserIdentity(User user, Identity identity) {
checkHasId(identity);
return verifyUserIdentity(user, identity.getId());
}
public Identity verifyUserIdentity(User user, long identityId) {
checkHasId(user);
return verifyUserIdentity(user.getId(), identityId);
}
public Identity verifyUserIdentity(long userId, long identityId) {
return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/verify.json")
.set("userId", userId)
.set("identityId", identityId), JSON, null), handle(Identity.class, "identity")));
}
public Identity requestVerifyUserIdentity(User user, Identity identity) {
checkHasId(identity);
return requestVerifyUserIdentity(user, identity.getId());
}
public Identity requestVerifyUserIdentity(User user, long identityId) {
checkHasId(user);
return requestVerifyUserIdentity(user.getId(), identityId);
}
public Identity requestVerifyUserIdentity(long userId, long identityId) {
return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}/request_verification.json")
.set("userId", userId)
.set("identityId", identityId), JSON, null), handle(Identity.class, "identity")));
}
public Identity updateUserIdentity(long userId, Identity identity) {
checkHasId(identity);
return complete(submit(req("PUT", tmpl("/users/{userId}/identities/{identityId}.json")
.set("userId", userId)
.set("identityId", identity.getId()), JSON, json(Collections.singletonMap("identity", identity))), handle(Identity.class, "identity")));
}
public Identity updateUserIdentity(User user, Identity identity) {
checkHasId(user);
return updateUserIdentity(user.getId(), identity);
}
public void deleteUserIdentity(User user, Identity identity) {
checkHasId(identity);
deleteUserIdentity(user, identity.getId());
}
public void deleteUserIdentity(User user, long identityId) {
checkHasId(user);
deleteUserIdentity(user.getId(), identityId);
}
public void deleteUserIdentity(long userId, long identityId) {
complete(submit(req("DELETE", tmpl("/users/{userId}/identities/{identityId}.json")
.set("userId", userId)
.set("identityId", identityId)
), handleStatus()));
}
public Identity createUserIdentity(long userId, Identity identity) {
return complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", userId), JSON,
json(Collections.singletonMap("identity", identity))), handle(Identity.class, "identity")));
}
public Identity createUserIdentity(User user, Identity identity) {
return complete(submit(req("POST", tmpl("/users/{userId}/identities.json").set("userId", user.getId()), JSON,
json(Collections.singletonMap("identity", identity))), handle(Identity.class, "identity")));
}
public Iterable<AgentRole> getCustomAgentRoles() {
return new PagedIterable<>(cnst("/custom_roles.json"),
handleList(AgentRole.class, "custom_roles"));
}
public Iterable<org.zendesk.client.v2.model.Request> getRequests() {
return new PagedIterable<>(cnst("/requests.json"),
handleList(org.zendesk.client.v2.model.Request.class, "requests"));
}
public Iterable<org.zendesk.client.v2.model.Request> getOpenRequests() {
return new PagedIterable<>(cnst("/requests/open.json"),
handleList(org.zendesk.client.v2.model.Request.class, "requests"));
}
public Iterable<org.zendesk.client.v2.model.Request> getSolvedRequests() {
return new PagedIterable<>(cnst("/requests/solved.json"),
handleList(org.zendesk.client.v2.model.Request.class, "requests"));
}
public Iterable<org.zendesk.client.v2.model.Request> getCCRequests() {
return new PagedIterable<>(cnst("/requests/ccd.json"),
handleList(org.zendesk.client.v2.model.Request.class, "requests"));
}
public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(User user) {
checkHasId(user);
return getUserRequests(user.getId());
}
public Iterable<org.zendesk.client.v2.model.Request> getUserRequests(long id) {
return new PagedIterable<>(tmpl("/users/{id}/requests.json").set("id", id),
handleList(org.zendesk.client.v2.model.Request.class, "requests"));
}
public org.zendesk.client.v2.model.Request getRequest(long id) {
return complete(submit(req("GET", tmpl("/requests/{id}.json").set("id", id)),
handle(org.zendesk.client.v2.model.Request.class, "request")));
}
public org.zendesk.client.v2.model.Request createRequest(org.zendesk.client.v2.model.Request request) {
return complete(submit(req("POST", cnst("/requests.json"),
JSON, json(Collections.singletonMap("request", request))),
handle(org.zendesk.client.v2.model.Request.class, "request")));
}
public org.zendesk.client.v2.model.Request updateRequest(org.zendesk.client.v2.model.Request request) {
checkHasId(request);
return complete(submit(req("PUT", tmpl("/requests/{id}.json").set("id", request.getId()),
JSON, json(Collections.singletonMap("request", request))),
handle(org.zendesk.client.v2.model.Request.class, "request")));
}
public Iterable<Comment> getRequestComments(org.zendesk.client.v2.model.Request request) {
checkHasId(request);
return getRequestComments(request.getId());
}
public Iterable<Comment> getRequestComments(long id) {
return new PagedIterable<>(tmpl("/requests/{id}/comments.json").set("id", id),
handleList(Comment.class, "comments"));
}
public Iterable<Comment> getTicketComments(long id) {
return new PagedIterable<>(tmpl("/tickets/{id}/comments.json").set("id", id),
handleList(Comment.class, "comments"));
}
public Comment getRequestComment(org.zendesk.client.v2.model.Request request, Comment comment) {
checkHasId(comment);
return getRequestComment(request, comment.getId());
}
public Comment getRequestComment(org.zendesk.client.v2.model.Request request, long commentId) {
checkHasId(request);
return getRequestComment(request.getId(), commentId);
}
public Comment getRequestComment(long requestId, long commentId) {
return complete(submit(req("GET", tmpl("/requests/{requestId}/comments/{commentId}.json")
.set("requestId", requestId)
.set("commentId", commentId)),
handle(Comment.class, "comment")));
}
public Ticket createComment(long ticketId, Comment comment) {
Ticket ticket = new Ticket();
ticket.setComment(comment);
return complete(submit(req("PUT", tmpl("/tickets/{id}.json").set("id", ticketId), JSON,
json(Collections.singletonMap("ticket", ticket))),
handle(Ticket.class, "ticket")));
}
public Ticket createTicketFromTweet(long tweetId, long monitorId) {
Map<String,Object> map = new HashMap<>();
map.put("twitter_status_message_id", tweetId);
map.put("monitored_twitter_handle_id", monitorId);
return complete(submit(req("POST", cnst("/channels/twitter/tickets.json"), JSON,
json(Collections.singletonMap("ticket", map))),
handle(Ticket.class, "ticket")));
}
public Iterable<Organization> getOrganizations() {
return new PagedIterable<>(cnst("/organizations.json"),
handleList(Organization.class, "organizations"));
}
public Iterable<Organization> getOrganizationsIncrementally(Date startTime) {
return new PagedIterable<>(
tmpl("/incremental/organizations.json{?start_time}")
.set("start_time", msToSeconds(startTime.getTime())),
handleIncrementalList(Organization.class, "organizations"));
}
public Iterable<OrganizationField> getOrganizationFields() {
//The organization_fields api doesn't seem to support paging
return complete(submit(req("GET", cnst("/organization_fields.json")),
handleList(OrganizationField.class, "organization_fields")));
}
public Iterable<Organization> getAutoCompleteOrganizations(String name) {
if (name == null || name.length() < 2) {
throw new IllegalArgumentException("Name must be at least 2 characters long");
}
return new PagedIterable<>(tmpl("/organizations/autocomplete.json{?name}").set("name", name),
handleList(Organization.class, "organizations"));
}
// TODO getOrganizationRelatedInformation
public Organization getOrganization(long id) {
return complete(submit(req("GET", tmpl("/organizations/{id}.json").set("id", id)),
handle(Organization.class, "organization")));
}
public Organization createOrganization(Organization organization) {
return complete(submit(req("POST", cnst("/organizations.json"), JSON, json(
Collections.singletonMap("organization", organization))), handle(Organization.class, "organization")));
}
public JobStatus<Organization> createOrganizations(Organization... organizations) {
return createOrganizations(Arrays.asList(organizations));
}
public JobStatus createOrganizations(List<Organization> organizations) {
return complete(createOrganizationsAsync(organizations));
}
public ListenableFuture<JobStatus<Organization>> createOrganizationsAsync(List<Organization> organizations) {
return submit(req("POST", cnst("/organizations/create_many.json"), JSON, json(
Collections.singletonMap("organizations", organizations))), handleJobStatus(Organization.class));
}
public Organization updateOrganization(Organization organization) {
checkHasId(organization);
return complete(submit(req("PUT", tmpl("/organizations/{id}.json").set("id", organization.getId()), JSON, json(
Collections.singletonMap("organization", organization))), handle(Organization.class, "organization")));
}
public void deleteOrganization(Organization organization) {
checkHasId(organization);
deleteOrganization(organization.getId());
}
public void deleteOrganization(long id) {
complete(submit(req("DELETE", tmpl("/organizations/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<Organization> lookupOrganizationsByExternalId(String externalId) {
if (externalId == null || externalId.length() < 2) {
throw new IllegalArgumentException("Name must be at least 2 characters long");
}
return new PagedIterable<>(
tmpl("/organizations/search.json{?external_id}").set("external_id", externalId),
handleList(Organization.class, "organizations"));
}
public Iterable<OrganizationMembership> getOrganizationMemberships() {
return new PagedIterable<>(cnst("/organization_memberships.json"),
handleList(OrganizationMembership.class, "organization_memberships"));
}
public Iterable<OrganizationMembership> getOrganizationMembershipsForOrg(long organization_id) {
return new PagedIterable<>(tmpl("/organizations/{organization_id}/organization_memberships.json")
.set("organization_id", organization_id),
handleList(OrganizationMembership.class, "organization_memberships"));
}
public Iterable<OrganizationMembership> getOrganizationMembershipsForUser(long user_id) {
return new PagedIterable<>(tmpl("/users/{user_id}/organization_memberships.json").set("user_id", user_id),
handleList(OrganizationMembership.class, "organization_memberships"));
}
public OrganizationMembership getOrganizationMembershipForUser(long user_id, long id) {
return complete(submit(req("GET",
tmpl("/users/{user_id}/organization_memberships/{id}.json").set("user_id", user_id).set("id", id)),
handle(OrganizationMembership.class, "organization_membership")));
}
public OrganizationMembership getOrganizationMembership(long id) {
return complete(submit(req("GET",
tmpl("/organization_memberships/{id}.json").set("id", id)),
handle(OrganizationMembership.class, "organization_membership")));
}
public OrganizationMembership createOrganizationMembership(OrganizationMembership organizationMembership) {
return complete(submit(req("POST",
cnst("/organization_memberships.json"), JSON, json(
Collections.singletonMap("organization_membership",
organizationMembership))), handle(OrganizationMembership.class, "organization_membership")));
}
public void deleteOrganizationMembership(long id) {
complete(submit(req("DELETE", tmpl("/organization_memberships/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<Group> getGroups() {
return new PagedIterable<>(cnst("/groups.json"),
handleList(Group.class, "groups"));
}
public Iterable<Group> getAssignableGroups() {
return new PagedIterable<>(cnst("/groups/assignable.json"),
handleList(Group.class, "groups"));
}
public Group getGroup(long id) {
return complete(submit(req("GET", tmpl("/groups/{id}.json").set("id", id)),
handle(Group.class, "group")));
}
public Group createGroup(Group group) {
return complete(submit(req("POST", cnst("/groups.json"), JSON, json(
Collections.singletonMap("group", group))), handle(Group.class, "group")));
}
@Deprecated
public List<Group> createGroups(Group... groups) {
return createGroups(Arrays.asList(groups));
}
@Deprecated
public List<Group> createGroups(List<Group> groups) {
throw new ZendeskException("API Endpoint for createGroups does not exist.");
}
public Group updateGroup(Group group) {
checkHasId(group);
return complete(submit(req("PUT", tmpl("/groups/{id}.json").set("id", group.getId()), JSON, json(
Collections.singletonMap("group", group))), handle(Group.class, "group")));
}
public void deleteGroup(Group group) {
checkHasId(group);
deleteGroup(group.getId());
}
public void deleteGroup(long id) {
complete(submit(req("DELETE", tmpl("/groups/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<Macro> getMacros(){
return new PagedIterable<>(cnst("/macros.json"),
handleList(Macro.class, "macros"));
}
public Macro getMacro(long macroId){
return complete(submit(req("GET", tmpl("/macros/{id}.json").set("id", macroId)), handle(Macro.class, "macro")));
}
public Macro createMacro(Macro macro) {
return complete(submit(
req("POST", cnst("/macros.json"), JSON, json(Collections.singletonMap("macro", macro))),
handle(Macro.class, "macro")));
}
public Macro updateMacro(Long macroId, Macro macro) {
return complete(submit(req("PUT", tmpl("/macros/{id}.json").set("id", macroId), JSON,
json(Collections.singletonMap("macro", macro))), handle(Macro.class, "macro")));
}
public Ticket macrosShowChangesToTicket(long macroId) {
return complete(submit(req("GET", tmpl("/macros/{id}/apply.json").set("id", macroId)),
handle(TicketResult.class, "result"))).getTicket();
}
public Ticket macrosShowTicketAfterChanges(long ticketId, long macroId) {
return complete(submit(req("GET", tmpl("/tickets/{ticket_id}/macros/{id}/apply.json")
.set("ticket_id", ticketId)
.set("id", macroId)),
handle(TicketResult.class, "result"))).getTicket();
}
public List<String> addTagToTicket(long id, String... tags) {
return complete(submit(
req("PUT", tmpl("/tickets/{id}/tags.json").set("id", id), JSON,
json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> addTagToTopics(long id, String... tags) {
return complete(submit(
req("PUT", tmpl("/topics/{id}/tags.json").set("id", id), JSON,
json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> addTagToOrganisations(long id, String... tags) {
return complete(submit(
req("PUT", tmpl("/organizations/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> setTagOnTicket(long id, String... tags) {
return complete(submit(
req("POST", tmpl("/tickets/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> setTagOnTopics(long id, String... tags) {
return complete(submit(
req("POST", tmpl("/topics/{id}/tags.json").set("id", id), JSON,
json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> setTagOnOrganisations(long id, String... tags) {
return complete(submit(
req("POST",
tmpl("/organizations/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> removeTagFromTicket(long id, String... tags) {
return complete(submit(
req("DELETE", tmpl("/tickets/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> removeTagFromTopics(long id, String... tags) {
return complete(submit(
req("DELETE", tmpl("/topics/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public List<String> removeTagFromOrganisations(long id, String... tags) {
return complete(submit(
req("DELETE",
tmpl("/organizations/{id}/tags.json").set("id", id),
JSON, json(Collections.singletonMap("tags", tags))),
handle(List.class, "tags")));
}
public Map getIncrementalTicketsResult(long unixEpochTime) {
return complete(submit(
req("GET",
tmpl("/exports/tickets.json?start_time={time}").set(
"time", unixEpochTime)), handle(Map.class)));
}
public Iterable<GroupMembership> getGroupMemberships() {
return new PagedIterable<>(cnst("/group_memberships.json"),
handleList(GroupMembership.class, "group_memberships"));
}
public List<GroupMembership> getGroupMembershipByUser(long user_id) {
return complete(submit(req("GET", tmpl("/users/{user_id}/group_memberships.json").set("user_id", user_id)),
handleList(GroupMembership.class, "group_memberships")));
}
public List<GroupMembership> getGroupMemberships(long group_id) {
return complete(submit(req("GET", tmpl("/groups/{group_id}/memberships.json").set("group_id", group_id)),
handleList(GroupMembership.class, "group_memberships")));
}
public Iterable<GroupMembership> getAssignableGroupMemberships() {
return new PagedIterable<>(cnst("/group_memberships/assignable.json"),
handleList(GroupMembership.class, "group_memberships"));
}
public List<GroupMembership> getAssignableGroupMemberships(long group_id) {
return complete(submit(req("GET",
tmpl("/groups/{group_id}/memberships/assignable.json").set("group_id", group_id)),
handleList(GroupMembership.class, "group_memberships")));
}
public GroupMembership getGroupMembership(long id) {
return complete(submit(req("GET", tmpl("/group_memberships/{id}.json").set("id", id)),
handle(GroupMembership.class, "group_membership")));
}
public GroupMembership getGroupMembership(long user_id, long group_membership_id) {
return complete(submit(req("GET", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id)
.set("gmid", group_membership_id)),
handle(GroupMembership.class, "group_membership")));
}
public GroupMembership createGroupMembership(GroupMembership groupMembership) {
return complete(submit(req("POST", cnst("/group_memberships.json"), JSON, json(
Collections.singletonMap("group_membership", groupMembership))),
handle(GroupMembership.class, "group_membership")));
}
public GroupMembership createGroupMembership(long user_id, GroupMembership groupMembership) {
return complete(submit(req("POST", tmpl("/users/{id}/group_memberships.json").set("id", user_id), JSON,
json(Collections.singletonMap("group_membership", groupMembership))),
handle(GroupMembership.class, "group_membership")));
}
public void deleteGroupMembership(GroupMembership groupMembership) {
checkHasId(groupMembership);
deleteGroupMembership(groupMembership.getId());
}
public void deleteGroupMembership(long id) {
complete(submit(req("DELETE", tmpl("/group_memberships/{id}.json").set("id", id)), handleStatus()));
}
public void deleteGroupMembership(long user_id, GroupMembership groupMembership) {
checkHasId(groupMembership);
deleteGroupMembership(user_id, groupMembership.getId());
}
public void deleteGroupMembership(long user_id, long group_membership_id) {
complete(submit(req("DELETE", tmpl("/users/{uid}/group_memberships/{gmid}.json").set("uid", user_id)
.set("gmid", group_membership_id)), handleStatus()));
}
public List<GroupMembership> setGroupMembershipAsDefault(long user_id, GroupMembership groupMembership) {
checkHasId(groupMembership);
return complete(submit(req("PUT", tmpl("/users/{uid}/group_memberships/{gmid}/make_default.json")
.set("uid", user_id).set("gmid", groupMembership.getId()), JSON, json(
Collections.singletonMap("group_memberships", groupMembership))),
handleList(GroupMembership.class, "results")));
}
public Iterable<Forum> getForums() {
return new PagedIterable<>(cnst("/forums.json"), handleList(Forum.class, "forums"));
}
public List<Forum> getForums(long category_id) {
return complete(submit(req("GET", tmpl("/categories/{id}/forums.json").set("id", category_id)),
handleList(Forum.class, "forums")));
}
public Forum getForum(long id) {
return complete(submit(req("GET", tmpl("/forums/{id}.json").set("id", id)),
handle(Forum.class, "forum")));
}
public Forum createForum(Forum forum) {
return complete(submit(req("POST", cnst("/forums.json"), JSON, json(
Collections.singletonMap("forum", forum))), handle(Forum.class, "forum")));
}
public Forum updateForum(Forum forum) {
checkHasId(forum);
return complete(submit(req("PUT", tmpl("/forums/{id}.json").set("id", forum.getId()), JSON, json(
Collections.singletonMap("forum", forum))), handle(Forum.class, "forum")));
}
public void deleteForum(Forum forum) {
checkHasId(forum);
complete(submit(req("DELETE", tmpl("/forums/{id}.json").set("id", forum.getId())), handleStatus()));
}
public Iterable<Topic> getTopics() {
return new PagedIterable<>(cnst("/topics.json"), handleList(Topic.class, "topics"));
}
public List<Topic> getTopics(long forum_id) {
return complete(submit(req("GET", tmpl("/forums/{id}/topics.json").set("id", forum_id)),
handleList(Topic.class, "topics")));
}
public List<Topic> getTopicsByUser(long user_id) {
return complete(submit(req("GET", tmpl("/users/{id}/topics.json").set("id", user_id)),
handleList(Topic.class, "topics")));
}
public Topic getTopic(long id) {
return complete(submit(req("GET", tmpl("/topics/{id}.json").set("id", id)),
handle(Topic.class, "topic")));
}
public Topic createTopic(Topic topic) {
checkHasId(topic);
return complete(submit(req("POST", cnst("/topics.json"), JSON, json(
Collections.singletonMap("topic", topic))), handle(Topic.class, "topic")));
}
public Topic importTopic(Topic topic) {
checkHasId(topic);
return complete(submit(req("POST", cnst("/import/topics.json"), JSON, json(
Collections.singletonMap("topic", topic))), handle(Topic.class, "topic")));
}
public List<Topic> getTopics(long id, long... ids) {
return complete(submit(req("POST", tmpl("/topics/show_many.json{?ids}").set("ids", idArray(id, ids))),
handleList(Topic.class, "topics")));
}
public Topic updateTopic(Topic topic) {
checkHasId(topic);
return complete(submit(req("PUT", tmpl("/topics/{id}.json").set("id", topic.getId()), JSON, json(
Collections.singletonMap("topic", topic))), handle(Topic.class, "topic")));
}
public void deleteTopic(Topic topic) {
checkHasId(topic);
complete(submit(req("DELETE", tmpl("/topics/{id}.json").set("id", topic.getId())), handleStatus()));
}
public List<OrganizationMembership> getOrganizationMembershipByUser(long user_id) {
return complete(submit(req("GET", tmpl("/users/{user_id}/organization_memberships.json").set("user_id", user_id)),
handleList(OrganizationMembership.class, "organization_memberships")));
}
public OrganizationMembership getGroupOrganization(long user_id, long organization_membership_id) {
return complete(submit(req("GET", tmpl("/users/{uid}/organization_memberships/{oid}.json").set("uid", user_id)
.set("oid", organization_membership_id)),
handle(OrganizationMembership.class, "organization_membership")));
}
public OrganizationMembership createOrganizationMembership(long user_id, OrganizationMembership organizationMembership) {
return complete(submit(req("POST", tmpl("/users/{id}/organization_memberships.json").set("id", user_id), JSON,
json(Collections.singletonMap("organization_membership", organizationMembership))),
handle(OrganizationMembership.class, "organization_membership")));
}
public void deleteOrganizationMembership(long user_id, OrganizationMembership organizationMembership) {
checkHasId(organizationMembership);
deleteOrganizationMembership(user_id, organizationMembership.getId());
}
public void deleteOrganizationMembership(long user_id, long organization_membership_id) {
complete(submit(req("DELETE", tmpl("/users/{uid}/organization_memberships/{oid}.json").set("uid", user_id)
.set("oid", organization_membership_id)), handleStatus()));
}
public List<OrganizationMembership> setOrganizationMembershipAsDefault(long user_id, OrganizationMembership organizationMembership) {
checkHasId(organizationMembership);
return complete(submit(req("PUT", tmpl("/users/{uid}/organization_memberships/{omid}/make_default.json")
.set("uid", user_id).set("omid", organizationMembership.getId()), JSON, json(
Collections.singletonMap("organization_memberships", organizationMembership))),
handleList(OrganizationMembership.class, "results")));
}
//-- END BETA
public Iterable<SearchResultEntity> getSearchResults(String query) {
return new PagedIterable<>(tmpl("/search.json{?query}").set("query", query),
handleSearchList("results"));
}
public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query) {
return getSearchResults(type, query, null);
}
public <T extends SearchResultEntity> Iterable<T> getSearchResults(Class<T> type, String query, String params) {
String typeName = null;
for (Map.Entry<String, Class<? extends SearchResultEntity>> entry : searchResultTypes.entrySet()) {
if (type.equals(entry.getValue())) {
typeName = entry.getKey();
break;
}
}
if (typeName == null) {
return Collections.emptyList();
}
return new PagedIterable<>(tmpl("/search.json{?query,params}")
.set("query", query + "+type:" + typeName)
.set("params", params),
handleList(type, "results"));
}
public void notifyApp(String json) {
complete(submit(req("POST", cnst("/apps/notify.json"), JSON, json.getBytes()), handleStatus()));
}
public void updateInstallation(int id, String json) {
complete(submit(req("PUT", tmpl("/apps/installations/{id}.json").set("id", id), JSON, json.getBytes()), handleStatus()));
}
public Iterable<SatisfactionRating> getSatisfactionRatings() {
return new PagedIterable<>(cnst("/satisfaction_ratings.json"),
handleList(SatisfactionRating.class, "satisfaction_ratings"));
}
public SatisfactionRating getSatisfactionRating(long id) {
return complete(submit(req("GET", tmpl("/satisfaction_ratings/{id}.json").set("id", id)),
handle(SatisfactionRating.class, "satisfaction_rating")));
}
public SatisfactionRating createSatisfactionRating(long ticketId, SatisfactionRating satisfactionRating) {
return complete(submit(req("POST", tmpl("/tickets/{ticketId}/satisfaction_rating.json")
.set("ticketId", ticketId), JSON,
json(Collections.singletonMap("satisfaction_rating", satisfactionRating))),
handle(SatisfactionRating.class, "satisfaction_rating")));
}
public SatisfactionRating createSatisfactionRating(Ticket ticket, SatisfactionRating satisfactionRating) {
return createSatisfactionRating(ticket.getId(), satisfactionRating);
}
// TODO search with sort order
// TODO search with query building API
// Action methods for Help Center
/**
* Get all articles from help center.
*
* @return List of Articles.
*/
public Iterable<Article> getArticles() {
return new PagedIterable<>(cnst("/help_center/articles.json"),
handleList(Article.class, "articles"));
}
public Iterable<Article> getArticles(Category category) {
checkHasId(category);
return new PagedIterable<>(
tmpl("/help_center/categories/{id}/articles.json").set("id", category.getId()),
handleList(Article.class, "articles"));
}
public Iterable<Article> getArticlesIncrementally(Date startTime) {
return new PagedIterable<>(
tmpl("/help_center/incremental/articles.json{?start_time}")
.set("start_time", msToSeconds(startTime.getTime())),
handleIncrementalList(Article.class, "articles"));
}
public List<Article> getArticlesFromPage(int page) {
return complete(submit(req("GET", tmpl("/help_center/articles.json?page={page}").set("page", page)),
handleList(Article.class, "articles")));
}
public Article getArticle(long id) {
return complete(submit(req("GET", tmpl("/help_center/articles/{id}.json").set("id", id)),
handle(Article.class, "article")));
}
public Iterable<Translation> getArticleTranslations(Long articleId) {
return new PagedIterable<>(
tmpl("/help_center/articles/{articleId}/translations.json").set("articleId", articleId),
handleList(Translation.class, "translations"));
}
public Article createArticle(Article article) {
checkHasSectionId(article);
return complete(submit(req("POST", tmpl("/help_center/sections/{id}/articles.json").set("id", article.getSectionId()),
JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article")));
}
public Article updateArticle(Article article) {
checkHasId(article);
return complete(submit(req("PUT", tmpl("/help_center/articles/{id}.json").set("id", article.getId()),
JSON, json(Collections.singletonMap("article", article))), handle(Article.class, "article")));
}
public Translation createArticleTranslation(Long articleId, Translation translation) {
checkHasArticleId(articleId);
return complete(submit(req("POST", tmpl("/help_center/articles/{id}/translations.json").set("id", articleId),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public Translation updateArticleTranslation(Long articleId, String locale, Translation translation) {
checkHasId(translation);
return complete(submit(req("PUT", tmpl("/help_center/articles/{id}/translations/{locale}.json").set("id", articleId).set("locale",locale),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public void deleteArticle(Article article) {
checkHasId(article);
complete(submit(req("DELETE", tmpl("/help_center/articles/{id}.json").set("id", article.getId())),
handleStatus()));
}
/**
* Delete attachment from article.
* @param attachment
*/
public void deleteArticleAttachment(ArticleAttachments attachment) {
checkHasId(attachment);
deleteArticleAttachment(attachment.getId());
}
/**
* Delete attachment from article.
* @param id attachment identifier.
*/
public void deleteArticleAttachment(long id) {
complete(submit(req("DELETE", tmpl("/help_center/articles/attachments/{id}.json").set("id", id)), handleStatus()));
}
public Iterable<Category> getCategories() {
return new PagedIterable<>(cnst("/help_center/categories.json"),
handleList(Category.class, "categories"));
}
public Category getCategory(long id) {
return complete(submit(req("GET", tmpl("/help_center/categories/{id}.json").set("id", id)),
handle(Category.class, "category")));
}
public Iterable<Translation> getCategoryTranslations(Long categoryId) {
return new PagedIterable<>(
tmpl("/help_center/categories/{categoryId}/translations.json").set("categoryId", categoryId),
handleList(Translation.class, "translations"));
}
public Category createCategory(Category category) {
return complete(submit(req("POST", cnst("/help_center/categories.json"),
JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category")));
}
public Category updateCategory(Category category) {
checkHasId(category);
return complete(submit(req("PUT", tmpl("/help_center/categories/{id}.json").set("id", category.getId()),
JSON, json(Collections.singletonMap("category", category))), handle(Category.class, "category")));
}
public Translation createCategoryTranslation(Long categoryId, Translation translation) {
checkHasCategoryId(categoryId);
return complete(submit(req("POST", tmpl("/help_center/categories/{id}/translation.json").set("id", categoryId),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public Translation updateCategoryTranslation(Long categoryId, String locale, Translation translation) {
checkHasId(translation);
return complete(submit(req("PUT", tmpl("/help_center/categories/{id}/translations/{locale}.json").set("id", categoryId).set("locale",locale),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public void deleteCategory(Category category) {
checkHasId(category);
complete(submit(req("DELETE", tmpl("/help_center/categories/{id}.json").set("id", category.getId())),
handleStatus()));
}
public Iterable<Section> getSections() {
return new PagedIterable<>(
cnst("/help_center/sections.json"), handleList(Section.class, "sections"));
}
public Iterable<Section> getSections(Category category) {
checkHasId(category);
return new PagedIterable<>(
tmpl("/help_center/categories/{id}/sections.json").set("id", category.getId()),
handleList(Section.class, "sections"));
}
public Section getSection(long id) {
return complete(submit(req("GET", tmpl("/help_center/sections/{id}.json").set("id", id)),
handle(Section.class, "section")));
}
public Iterable<Translation> getSectionTranslations(Long sectionId) {
return new PagedIterable<>(
tmpl("/help_center/sections/{sectionId}/translations.json").set("sectionId", sectionId),
handleList(Translation.class, "translations"));
}
public Section createSection(Section section) {
return complete(submit(req("POST", cnst("/help_center/sections.json"), JSON,
json(Collections.singletonMap("section", section))), handle(Section.class, "section")));
}
public Section updateSection(Section section) {
checkHasId(section);
return complete(submit(req("PUT", tmpl("/help_center/sections/{id}.json").set("id", section.getId()),
JSON, json(Collections.singletonMap("section", section))), handle(Section.class, "section")));
}
public Translation createSectionTranslation(Long sectionId, Translation translation) {
checkHasSectionId(sectionId);
return complete(submit(req("POST", tmpl("/help_center/sections/{id}/translation.json").set("id", sectionId),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public Translation updateSectionTranslation(Long sectionId, String locale, Translation translation) {
checkHasId(translation);
return complete(submit(req("PUT", tmpl("/help_center/sections/{id}/translations/{locale}.json").set("id", sectionId).set("locale",locale),
JSON, json(Collections.singletonMap("translation", translation))), handle(Translation.class, "translation")));
}
public void deleteSection(Section section) {
checkHasId(section);
complete(submit(req("DELETE", tmpl("/help_center/sections/{id}.json").set("id", section.getId())),
handleStatus()));
}
public Iterable<Subscription> getUserSubscriptions(User user) {
checkHasId(user);
return getUserSubscriptions(user.getId());
}
public Iterable<Subscription> getUserSubscriptions(Long userId) {
return new PagedIterable<>(
tmpl("/help_center/users/{userId}/subscriptions.json").set("userId", userId),
handleList(Subscription.class, "subscriptions"));
}
public Iterable<Subscription> getArticleSubscriptions(Long articleId) {
return getArticleSubscriptions(articleId, null);
}
public Iterable<Subscription> getArticleSubscriptions(Long articleId, String locale) {
return new PagedIterable<>(
tmpl("/help_center{/locale}/articles/{articleId}/subscriptions.json").set("locale", locale)
.set("articleId", articleId),
handleList(Subscription.class, "subscriptions"));
}
public Iterable<Subscription> getSectionSubscriptions(Long sectionId) {
return getSectionSubscriptions(sectionId, null);
}
public Iterable<Subscription> getSectionSubscriptions(Long sectionId, String locale) {
return new PagedIterable<>(
tmpl("/help_center{/locale}/sections/{sectionId}/subscriptions.json").set("locale", locale)
.set("sectionId", sectionId),
handleList(Subscription.class, "subscriptions"));
}
/**
* Get a list of the current business hours schedules
* @return A List of Schedules
*/
public Iterable<Schedule> getSchedules() {
return complete(submit(req("GET", cnst("/business_hours/schedules.json")),
handleList(Schedule.class, "schedules")));
}
public Schedule getSchedule(Schedule schedule) {
checkHasId(schedule);
return getSchedule(schedule.getId());
}
public Schedule getSchedule(Long scheduleId) {
return complete(submit(req("GET", tmpl("/business_hours/schedules/{id}.json").set("id", scheduleId)),
handle(Schedule.class, "schedule")));
}
public Iterable<Holiday> getHolidaysForSchedule(Schedule schedule) {
checkHasId(schedule);
return getHolidaysForSchedule(schedule.getId());
}
public Iterable<Holiday> getHolidaysForSchedule(Long scheduleId) {
return complete(submit(req("GET",
tmpl("/business_hours/schedules/{id}/holidays.json").set("id", scheduleId)),
handleList(Holiday.class, "holidays")));
}
// Helper methods
private byte[] json(Object object) {
try {
return mapper.writeValueAsBytes(object);
} catch (JsonProcessingException e) {
throw new ZendeskException(e.getMessage(), e);
}
}
private <T> ListenableFuture<T> submit(Request request, ZendeskAsyncCompletionHandler<T> handler) {
if (logger.isDebugEnabled()) {
if (request.getStringData() != null) {
logger.debug("Request {} {}\n{}", request.getMethod(), request.getUrl(), request.getStringData());
} else if (request.getByteData() != null) {
logger.debug("Request {} {} {} {} bytes", request.getMethod(), request.getUrl(),
request.getHeaders().get("Content-type"), request.getByteData().length);
} else {
logger.debug("Request {} {}", request.getMethod(), request.getUrl());
}
}
return client.executeRequest(request, handler);
}
private static abstract class ZendeskAsyncCompletionHandler<T> extends AsyncCompletionHandler<T> {
@Override
public void onThrowable(Throwable t) {
if (t instanceof IOException) {
throw new ZendeskException(t);
} else {
super.onThrowable(t);
}
}
}
private Request req(String method, Uri template) {
return req(method, template.toString());
}
private static final Pattern RESTRICTED_PATTERN = Pattern.compile("%2B", Pattern.LITERAL);
private Request req(String method, String url) {
RequestBuilder builder = new RequestBuilder(method);
if (realm != null) {
builder.setRealm(realm);
} else {
builder.addHeader("Authorization", "Bearer " + oauthToken);
}
builder.setUrl(RESTRICTED_PATTERN.matcher(url).replaceAll("+")); // replace out %2B with + due to API restriction
return builder.build();
}
private Request req(String method, Uri template, String contentType, byte[] body) {
RequestBuilder builder = new RequestBuilder(method);
if (realm != null) {
builder.setRealm(realm);
} else {
builder.addHeader("Authorization", "Bearer " + oauthToken);
}
builder.setUrl(RESTRICTED_PATTERN.matcher(template.toString()).replaceAll("+")); //replace out %2B with + due to API restriction
builder.addHeader("Content-type", contentType);
builder.setBody(body);
return builder.build();
}
protected ZendeskAsyncCompletionHandler<Void> handleStatus() {
return new ZendeskAsyncCompletionHandler<Void>() {
@Override
public Void onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
return null;
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
throw new ZendeskResponseException(response);
}
};
}
@SuppressWarnings("unchecked")
protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz) {
return new ZendeskAsyncCompletionHandler<T>() {
@Override
public T onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsStream());
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
if (response.getStatusCode() == 404) {
return null;
}
throw new ZendeskResponseException(response);
}
};
}
private class BasicAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> {
private final Class<T> clazz;
private final String name;
private final Class[] typeParams;
public BasicAsyncCompletionHandler(Class clazz, String name, Class... typeParams) {
this.clazz = clazz;
this.name = name;
this.typeParams = typeParams;
}
@Override
public T onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
if (typeParams.length > 0) {
JavaType type = mapper.getTypeFactory().constructParametricType(clazz, typeParams);
return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), type);
}
return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz);
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
if (response.getStatusCode() == 404) {
return null;
}
throw new ZendeskResponseException(response);
}
}
protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz, final String name, final Class... typeParams) {
return new BasicAsyncCompletionHandler<>(clazz, name, typeParams);
}
protected <T> ZendeskAsyncCompletionHandler<JobStatus<T>> handleJobStatus(final Class<T> resultClass) {
return new BasicAsyncCompletionHandler<JobStatus<T>>(JobStatus.class, "job_status", resultClass) {
@Override
public JobStatus<T> onCompleted(Response response) throws Exception {
JobStatus<T> result = super.onCompleted(response);
result.setResultsClass(resultClass);
return result;
}
};
}
private static final String NEXT_PAGE = "next_page";
private static final String END_TIME = "end_time";
private static final String COUNT = "count";
private static final int INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST = 1000;
private abstract class PagedAsyncCompletionHandler<T> extends ZendeskAsyncCompletionHandler<T> {
private String nextPage;
public void setPagedProperties(JsonNode responseNode, Class<?> clazz) {
JsonNode node = responseNode.get(NEXT_PAGE);
if (node == null) {
this.nextPage = null;
if (logger.isDebugEnabled()) {
logger.debug(NEXT_PAGE + " property not found, pagination not supported" +
(clazz != null ? " for " + clazz.getName() : ""));
}
} else {
this.nextPage = node.asText();
}
}
public String getNextPage() {
return nextPage;
}
public void setNextPage(String nextPage) {
this.nextPage = nextPage;
}
}
private class PagedAsyncListCompletionHandler<T> extends PagedAsyncCompletionHandler<List<T>> {
private final Class<T> clazz;
private final String name;
public PagedAsyncListCompletionHandler(Class<T> clazz, String name) {
this.clazz = clazz;
this.name = name;
}
@Override
public List<T> onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes());
setPagedProperties(responseNode, clazz);
List<T> values = new ArrayList<>();
for (JsonNode node : responseNode.get(name)) {
values.add(mapper.convertValue(node, clazz));
}
return values;
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
throw new ZendeskResponseException(response);
}
}
protected <T> PagedAsyncCompletionHandler<List<T>> handleList(final Class<T> clazz, final String name) {
return new PagedAsyncListCompletionHandler<>(clazz, name);
}
private static final long FIVE_MINUTES = TimeUnit.MINUTES.toMillis(5);
protected <T> PagedAsyncCompletionHandler<List<T>> handleIncrementalList(final Class<T> clazz, final String name) {
return new PagedAsyncListCompletionHandler<T>(clazz, name) {
@Override
public void setPagedProperties(JsonNode responseNode, Class<?> clazz) {
JsonNode node = responseNode.get(NEXT_PAGE);
if (node == null) {
if (logger.isDebugEnabled()) {
logger.debug(NEXT_PAGE + " property not found, pagination not supported" +
(clazz != null ? " for " + clazz.getName() : ""));
}
setNextPage(null);
return;
}
JsonNode endTimeNode = responseNode.get(END_TIME);
if (endTimeNode == null || endTimeNode.asLong() == 0) {
if (logger.isDebugEnabled()) {
logger.debug(END_TIME + " property not found, incremental export pagination not supported" +
(clazz != null ? " for " + clazz.getName() : ""));
}
setNextPage(null);
return;
}
/*
A request after five minutes ago will result in a 422 responds from Zendesk.
Therefore, we stop pagination.
*/
if (TimeUnit.SECONDS.toMillis(endTimeNode.asLong()) > System.currentTimeMillis() - FIVE_MINUTES) {
setNextPage(null);
} else {
// Taking into account documentation found at https://developer.zendesk.com/rest_api/docs/core/incremental_export#polling-strategy
JsonNode countNode = responseNode.get(COUNT);
if (countNode == null) {
if (logger.isDebugEnabled()) {
logger.debug(COUNT + " property not found, incremental export pagination not supported" +
(clazz != null ? " for " + clazz.getName() : ""));
}
setNextPage(null);
return;
}
if (countNode.asInt() < INCREMENTAL_EXPORT_MAX_COUNT_BY_REQUEST) {
setNextPage(null);
} else {
setNextPage(node.asText());
}
}
}
};
}
protected PagedAsyncCompletionHandler<List<SearchResultEntity>> handleSearchList(final String name) {
return new PagedAsyncCompletionHandler<List<SearchResultEntity>>() {
@Override
public List<SearchResultEntity> onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
JsonNode responseNode = mapper.readTree(response.getResponseBodyAsStream()).get(name);
setPagedProperties(responseNode, null);
List<SearchResultEntity> values = new ArrayList<>();
for (JsonNode node : responseNode) {
Class<? extends SearchResultEntity> clazz = searchResultTypes.get(node.get("result_type").asText());
if (clazz != null) {
values.add(mapper.convertValue(node, clazz));
}
}
return values;
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
throw new ZendeskResponseException(response);
}
};
}
protected PagedAsyncCompletionHandler<List<Target>> handleTargetList(final String name) {
return new PagedAsyncCompletionHandler<List<Target>>() {
@Override
public List<Target> onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes());
setPagedProperties(responseNode, null);
List<Target> values = new ArrayList<>();
for (JsonNode node : responseNode.get(name)) {
Class<? extends Target> clazz = targetTypes.get(node.get("type").asText());
if (clazz != null) {
values.add(mapper.convertValue(node, clazz));
}
}
return values;
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
throw new ZendeskResponseException(response);
}
};
}
protected PagedAsyncCompletionHandler<List<ArticleAttachments>> handleArticleAttachmentsList(final String name) {
return new PagedAsyncCompletionHandler<List<ArticleAttachments>>() {
@Override
public List<ArticleAttachments> onCompleted(Response response) throws Exception {
logResponse(response);
if (isStatus2xx(response)) {
JsonNode responseNode = mapper.readTree(response.getResponseBodyAsBytes());
List<ArticleAttachments> values = new ArrayList<>();
for (JsonNode node : responseNode.get(name)) {
values.add(mapper.convertValue(node, ArticleAttachments.class));
}
return values;
} else if (isRateLimitResponse(response)) {
throw new ZendeskResponseRateLimitException(response);
}
throw new ZendeskResponseException(response);
}
};
}
private TemplateUri tmpl(String template) {
return new TemplateUri(url + template);
}
private Uri cnst(String template) {
return new FixedUri(url + template);
}
private void logResponse(Response response) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(),
response.getResponseBody());
}
if (logger.isTraceEnabled()) {
logger.trace("Response headers {}", response.getHeaders());
}
}
private static final String UTF_8 = "UTF-8";
private static String encodeUrl(String input) {
try {
return URLEncoder.encode(input, UTF_8);
} catch (UnsupportedEncodingException impossible) {
return input;
}
}
private static long msToSeconds(long millis) {
return TimeUnit.MILLISECONDS.toSeconds(millis);
}
private boolean isStatus2xx(Response response) {
return response.getStatusCode() / 100 == 2;
}
private boolean isRateLimitResponse(Response response) {
return response.getStatusCode() == 429;
}
// Static helper methods
private static <T> T complete(ListenableFuture<T> future) {
try {
return future.get();
} catch (InterruptedException e) {
throw new ZendeskException(e.getMessage(), e);
} catch (ExecutionException e) {
if (e.getCause() instanceof ZendeskException) {
if (e.getCause() instanceof ZendeskResponseRateLimitException) {
throw new ZendeskResponseRateLimitException((ZendeskResponseRateLimitException) e.getCause());
}
if (e.getCause() instanceof ZendeskResponseException) {
throw new ZendeskResponseException((ZendeskResponseException)e.getCause());
}
throw new ZendeskException(e.getCause());
}
throw new ZendeskException(e.getMessage(), e);
}
}
private static void checkHasId(Ticket ticket) {
if (ticket.getId() == null) {
throw new IllegalArgumentException("Ticket requires id");
}
}
private static void checkHasId(org.zendesk.client.v2.model.Request request) {
if (request.getId() == null) {
throw new IllegalArgumentException("Request requires id");
}
}
private static void checkHasId(Audit audit) {
if (audit.getId() == null) {
throw new IllegalArgumentException("Audit requires id");
}
}
private static void checkHasId(Comment comment) {
if (comment.getId() == null) {
throw new IllegalArgumentException("Comment requires id");
}
}
private static void checkHasId(Field field) {
if (field.getId() == null) {
throw new IllegalArgumentException("Field requires id");
}
}
private static void checkHasId(Attachment attachment) {
if (attachment.getId() == null) {
throw new IllegalArgumentException("Attachment requires id");
}
}
private static void checkHasId(ArticleAttachments attachments) {
if (attachments.getId() == null) {
throw new IllegalArgumentException("Attachment requires id");
}
}
private static void checkHasId(User user) {
if (user.getId() == null) {
throw new IllegalArgumentException("User requires id");
}
}
private static void checkHasId(Identity identity) {
if (identity.getId() == null) {
throw new IllegalArgumentException("Identity requires id");
}
}
private static void checkHasId(Organization organization) {
if (organization.getId() == null) {
throw new IllegalArgumentException("Organization requires id");
}
}
private static void checkHasId(Group group) {
if (group.getId() == null) {
throw new IllegalArgumentException("Group requires id");
}
}
private static void checkHasId(GroupMembership groupMembership) {
if (groupMembership.getId() == null) {
throw new IllegalArgumentException("GroupMembership requires id");
}
}
private void checkHasId(Forum forum) {
if (forum.getId() == null) {
throw new IllegalArgumentException("Forum requires id");
}
}
private void checkHasId(Topic topic) {
if (topic.getId() == null) {
throw new IllegalArgumentException("Topic requires id");
}
}
private static void checkHasId(OrganizationMembership organizationMembership) {
if (organizationMembership.getId() == null) {
throw new IllegalArgumentException("OrganizationMembership requires id");
}
}
private static void checkHasId(Article article) {
if (article.getId() == null) {
throw new IllegalArgumentException("Article requires id");
}
}
private static void checkHasSectionId(Article article) {
if (article.getSectionId() == null) {
throw new IllegalArgumentException("Article requires section id");
}
}
private static void checkHasArticleId(Long articleId) {
if (articleId == null) {
throw new IllegalArgumentException("Translation requires article id");
}
}
private static void checkHasSectionId(Long articleId) {
if (articleId == null) {
throw new IllegalArgumentException("Translation requires section id");
}
}
private static void checkHasCategoryId(Long articleId) {
if (articleId == null) {
throw new IllegalArgumentException("Translation requires category id");
}
}
private static void checkHasId(Category category) {
if (category.getId() == null) {
throw new IllegalArgumentException("Category requires id");
}
}
private static void checkHasId(Section section) {
if (section.getId() == null) {
throw new IllegalArgumentException("Section requires id");
}
}
private static void checkHasId(SuspendedTicket ticket) {
if (ticket == null || ticket.getId() == null) {
throw new IllegalArgumentException("SuspendedTicket requires id");
}
}
private static void checkHasId(Translation translation) {
if (translation.getId() == null) {
throw new IllegalArgumentException("Translation requires id");
}
}
private static void checkHasId(Schedule schedule) {
if (schedule == null || schedule.getId() == null) {
throw new IllegalArgumentException("Schedule requires id");
}
}
private static void checkHasId(Holiday holiday) {
if (holiday == null || holiday.getId() == null) {
throw new IllegalArgumentException("Holiday requires id");
}
}
private static void checkHasToken(Attachment.Upload upload) {
if (upload.getToken() == null) {
throw new IllegalArgumentException("Upload requires token");
}
}
private static List<Long> idArray(long id, long... ids) {
List<Long> result = new ArrayList<>(ids.length + 1);
result.add(id);
for (long i : ids) {
result.add(i);
}
return result;
}
private static List<String> statusArray(Status... statuses) {
List<String> result = new ArrayList<>(statuses.length);
for (Status s : statuses) {
result.add(s.toString());
}
return result;
}
public static ObjectMapper createMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new ISO8601DateFormat());
return mapper;
}
// Helper classes
private class PagedIterable<T> implements Iterable<T> {
private final Uri url;
private final PagedAsyncCompletionHandler<List<T>> handler;
private PagedIterable(Uri url, PagedAsyncCompletionHandler<List<T>> handler) {
this.handler = handler;
this.url = url;
}
public Iterator<T> iterator() {
return new PagedIterator(url);
}
private class PagedIterator implements Iterator<T> {
private Iterator<T> current;
private String nextPage;
public PagedIterator(Uri url) {
this.nextPage = url.toString();
}
public boolean hasNext() {
if (current == null || !current.hasNext()) {
if (nextPage == null || nextPage.equalsIgnoreCase("null")) {
return false;
}
List<T> values = complete(submit(req("GET", nextPage), handler));
nextPage = handler.getNextPage();
current = values.iterator();
}
return current.hasNext();
}
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return current.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
public static class Builder {
private AsyncHttpClient client = null;
private final String url;
private String username = null;
private String password = null;
private String token = null;
private String oauthToken = null;
public Builder(String url) {
this.url = url;
}
public Builder setClient(AsyncHttpClient client) {
this.client = client;
return this;
}
public Builder setUsername(String username) {
this.username = username;
return this;
}
public Builder setPassword(String password) {
this.password = password;
if (password != null) {
this.token = null;
this.oauthToken = null;
}
return this;
}
public Builder setToken(String token) {
this.token = token;
if (token != null) {
this.password = null;
this.oauthToken = null;
}
return this;
}
public Builder setOauthToken(String oauthToken) {
this.oauthToken = oauthToken;
if (oauthToken != null) {
this.password = null;
this.token = null;
}
return this;
}
public Builder setRetry(boolean retry) {
return this;
}
public Zendesk build() {
if (token != null) {
return new Zendesk(client, url, username + "/token", token);
} else if (oauthToken != null) {
return new Zendesk(client, url, oauthToken);
}
return new Zendesk(client, url, username, password);
}
}
}
|
package seedu.address.model.task;
import seedu.address.commons.exceptions.IllegalValueException;
/**
* Represents a task's due time in the task manager.
* Guarantees: immutable; is valid as declared in {@link #isValidTime(String)}
*/
public class Time implements TaskField {
public static final String MESSAGE_TIME_CONSTRAINTS =
"Task time should be the form hh:mm";
/*
* The first character of the time must not be a whitespace,
* otherwise " " (a blank string) becomes a valid input.
*/
public static final String HOUR_VALIDATION_REGEX = "(\\d)|(0\\d)|(1\\d)|(2[0-3])";
public static final String MINUTE_VALIDATION_REGEX = "[0-5][0-9]";
public static final String TIME_VALIDATION_REGEX = ".*:.*";
public static final String HOUR_MINUTE_SEPARATOR = ":";
private final String value;
public Time(String time) throws IllegalValueException {
assert time != null;
if (!isValidTime(time)) {
throw new IllegalValueException(MESSAGE_TIME_CONSTRAINTS);
}
this.value = time;
}
/**
* Returns true if a given string is a valid person email.
*/
public static boolean isValidTime(String test) {
if (test.equals("")) {
return true;
}
if (!test.matches(TIME_VALIDATION_REGEX)) {
return false;
}
String[] hourAndMinute = test.split(HOUR_MINUTE_SEPARATOR);
String hour = hourAndMinute[0];
String minute = hourAndMinute[1];
return isValidHour(hour) && isValidMinute(minute);
}
private static boolean isValidHour(String test) {
return test.matches(HOUR_VALIDATION_REGEX);
}
private static boolean isValidMinute(String test) {
return test.matches(MINUTE_VALIDATION_REGEX);
}
public String getValue() {
return this.value;
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Time // instanceof handles nulls
&& this.value.equals(((Time) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
//@@author A0143409J
@Override
public String getDisplayText() {
if ((value == null) || (value == "")) {
return "";
} else {
return "Time: " + value;
}
}
}
|
package seedu.gtd.logic.parser;
import static seedu.gtd.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.gtd.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.gtd.commons.exceptions.IllegalValueException;
import seedu.gtd.commons.util.StringUtil;
import seedu.gtd.logic.commands.*;
/**
* Parses user input.
*/
public class Parser {
//@@author addressbook-level4
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
// private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
// Pattern.compile("(?<name>[^/]+)"
// + " d/(?<dueDate>[^/]+)"
// + " a/(?<address>[^/]+)"
// + " p/(?<priority>[^/]+)"
// + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags
private static final Pattern NAME_TASK_DATA_ARGS_FORMAT =
Pattern.compile("(?<name>[^/]+) (t|p|a|d|z)/.*");
private static final Pattern PRIORITY_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* p/(?<priority>[^/]+) (t|a|d|z)/.*");
private static final Pattern ADDRESS_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* a/(?<address>[^/]+) (t|p|d|z)/.*");
private static final Pattern DUEDATE_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* d/(?<dueDate>[^/]+) (t|a|p|z)/.*");
private static final Pattern TAGS_TASK_DATA_ARGS_FORMAT =
Pattern.compile(".* t/(?<tagArguments>[^/]+) (d|a|p|z)/.*");
private static final Pattern EDIT_DATA_ARGS_FORMAT =
Pattern.compile("(?<targetIndex>\\S+)"
+ " (?<newDetails>\\S+(?:\\s+\\S+)*)");
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case DoneCommand.COMMAND_WORD:
return prepareDone(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return prepareList(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return prepareHelp(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
String preprocessedArg = appendEnd(args.trim());
final Matcher nameMatcher = NAME_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
final Matcher tagsMatcher = TAGS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArg);
String nameToAdd = checkEmptyAndAddDefault(nameMatcher, "name", "none");
String dueDateToAdd = checkEmptyAndAddDefault(dueDateMatcher, "dueDate", "none");
String addressToAdd = checkEmptyAndAddDefault(addressMatcher, "address", "none");
String priorityToAdd = checkEmptyAndAddDefault(priorityMatcher, "priority", "1");
// String tagsToAdd = checkEmptyAndAddDefault(tagsMatcher, "tagsArgument", "");
// format date if due date is specified
if (dueDateMatcher.matches()) {
dueDateToAdd = parseDueDate(dueDateToAdd);
}
Set<String> tagsProcessed = Collections.emptySet();
if (tagsMatcher.matches()) {
tagsProcessed = getTagsFromArgs(tagsMatcher.group("tagArguments"));
}
// Validate arg string format
if (!nameMatcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
nameToAdd,
dueDateToAdd,
addressToAdd,
priorityToAdd,
tagsProcessed
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
private String appendEnd(String args) {
return args + " z/";
}
private String checkEmptyAndAddDefault(Matcher matcher, String groupName, String defaultValue) {
if (matcher.matches()) {
return matcher.group(groupName);
} else {
return defaultValue;
}
}
//@@author A0146130W
private String parseDueDate(String dueDateRaw) {
NaturalLanguageProcessor nlp = new DateNaturalLanguageProcessor();
return nlp.formatString(dueDateRaw);
}
// remove time on date parsed to improve search results
private String removeTimeOnDate(String dueDateRaw) {
String[] dateTime = dueDateRaw.split(" ");
return dateTime[0];
}
//@@author addressbook-level4
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.split(" "));
return new HashSet<>(tagStrings);
}
//@@author A0146130W
/**
* Parses arguments in the context of the edit task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
Optional<Integer> index = parseIndex(args, EDIT_DATA_ARGS_FORMAT);
final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
final String[] splitNewDetails = matcher.group("newDetails").split("\\s+");
ArrayList<String> combinedDetails = combineSameDetails(splitNewDetails);
Hashtable<String, String> newDetailsSet = new Hashtable<String, String>();
for (String detail : combinedDetails) {
String detailType = extractDetailType(detail);
String preparedNewDetail = prepareNewDetail(detailType, detail);
System.out.println("before adding to hashtable: " + detailType + " " + preparedNewDetail);
newDetailsSet.put(detailType, preparedNewDetail);
}
return new EditCommand(
index.get()-1,
newDetailsSet
);
}
private ArrayList<String> combineSameDetails(String[] details) {
ArrayList<String> alDetails = new ArrayList<String>(Arrays.asList(details));
System.out.println(alDetails.toString());
String name = new String();
String address = new String();
String dueDate = new String();
String priority = new String();
int currentDetailType = 0;
if(alDetails.size() == 1) {
return alDetails;
}
for (String detail: alDetails) {
System.out.println("detail: " + detail);
if(extractDetailType(detail).equals("name")) {
System.out.println("current detail type: " + currentDetailType);
switch(currentDetailType) {
case 1: address = address + " " + detail; break;
case 2: dueDate = dueDate + " " + detail; break;
case 3: priority = priority + " " + detail; break;
default: {
if(name.isEmpty()) name = detail;
else name = name + " " + detail;
break;
}
}
}
else if(extractDetailType(detail).equals("address")) {
System.out.println("detected address " + detail);
address = detail;
currentDetailType = 1;
}
else if(extractDetailType(detail).equals("dueDate")) {
System.out.println("detected dueDate " + detail);
dueDate = detail;
currentDetailType = 2;
}
else if(extractDetailType(detail).equals("priority")) {
System.out.println("detected priority " + detail);
address = detail;
currentDetailType = 3;
}
}
ArrayList<String> finalCombined = new ArrayList<String>();
//does not remove the separate words from the list, they will be overwritten by the final combined string
if(!name.isEmpty()) finalCombined.add(name);
System.out.println("from combining name: " + name);
if(!address.isEmpty()) finalCombined.add(address);
System.out.println("from combining address: " + address);
if(!dueDate.isEmpty()) finalCombined.add(dueDate);
if(!priority.isEmpty()) finalCombined.add(priority);
System.out.println("from combining: " + finalCombined.toString());
return finalCombined;
}
private String removeDetailPrefix(String detailWithPrefix) {
return detailWithPrefix.substring(detailWithPrefix.indexOf('/') + 1);
}
private String prepareNewDetail(String detailType, String detailWithPrefix) {
String detail = removeDetailPrefix(detailWithPrefix);
if(detailType.equals("dueDate")) detail = parseDueDate(detail);
return detail;
}
//@@author A0146130W-reused
private String extractDetailType(String args) {
String preprocessedArgs = " " + appendEnd(args.trim());
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
if(addressMatcher.matches()) {
return "address";
}
else if(dueDateMatcher.matches()) {
return "dueDate";
}
else if(priorityMatcher.matches()) {
return "priority";
}
return "name";
}
//@@author addressbook-level4
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
private Command prepareDone(String args) {
Optional<Integer> index = parseIndex(args);
System.out.println("index at preparedone:" + index.get());
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE));
}
return new DoneCommand(index.get());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
//@@author A0146130W
private Optional<Integer> parseIndex(String command, Pattern matcherFormat) {
final Matcher matcher = matcherFormat.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
//@@author addressbook-level4
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
// check if parameters are specified and pass specified field to FindCommand
String preprocessedArgs = " " + appendEnd(args.trim());
final Matcher addressMatcher = ADDRESS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher priorityMatcher = PRIORITY_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher dueDateMatcher = DUEDATE_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
final Matcher tagsMatcher = TAGS_TASK_DATA_ARGS_FORMAT.matcher(preprocessedArgs);
Set<String> defaultSet = new HashSet<String>();
if (addressMatcher.matches()) {
String addressToBeFound = addressMatcher.group("address");
return new FindCommand(addressToBeFound, defaultSet,"address");
}
if (priorityMatcher.matches()) {
String priorityToBeFound = priorityMatcher.group("priority");
return new FindCommand(priorityToBeFound, defaultSet, "priority");
}
if (dueDateMatcher.matches()) {
String dueDateToBeFound = dueDateMatcher.group("dueDate");
String parsedDueDateToBeFound = removeTimeOnDate(parseDueDate(dueDateToBeFound));
return new FindCommand(parsedDueDateToBeFound, defaultSet, "dueDate");
}
if (tagsMatcher.matches()) {
String tagsToBeFound = tagsMatcher.group("tagArguments");
return new FindCommand(tagsToBeFound, defaultSet,"tagArguments");
}
// free-form search by keywords
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] splitKeywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(splitKeywords));
final String keywords = matcher.group("keywords");
return new FindCommand(keywords, keywordSet, "nil");
}
private Command prepareList(String args) {
// check if parameters are specified and pass specified field to FindCommand
//String preprocessedArgs = " " + appendEnd(args.trim());
return new ListCommand(args);
}
/**
* Parses arguments in the context of the help command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareHelp(String args) {
//if no argument
if (args.equals("")) {
args="help";
}
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
return new HelpCommand(commandWord);
}
}
|
package seedu.task.model;
import com.google.common.eventbus.Subscribe;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import seedu.task.commons.core.ComponentManager;
import seedu.task.commons.core.EventsCenter;
import seedu.task.commons.core.LogsCenter;
import seedu.task.commons.core.UnmodifiableObservableList;
import seedu.task.commons.events.model.TaskBookChangedEvent;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.commons.util.StringUtil;
import seedu.task.logic.parser.TaskParser;
import seedu.task.model.tag.Tag;
import seedu.task.model.task.ReadOnlyTask;
import seedu.task.model.task.Status;
import seedu.task.model.task.Task;
import seedu.task.model.task.TaskPriority;
import seedu.task.model.task.UniqueTaskList;
import seedu.task.model.task.UniqueTaskList.DateClashTaskException;
import seedu.task.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.task.model.task.UniqueTaskList.TaskNotFoundException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.logging.Logger;
import seedu.task.commons.events.model.TaskBookChangedEvent;
import org.junit.Assert;
/**
* Represents the in-memory model of the task book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final TaskBook taskBook;
private final FilteredList<Task> filteredTasks;
//@@author A0138301U
private SortedList<Task> sortedTasks;
//@@author
/**
* Initializes a ModelManager with the given TaskBook
* TaskBook and its variables should not be null
*/
public ModelManager(TaskBook src, UserPrefs userPrefs) {
super();
assert src != null;
assert userPrefs != null;
logger.fine("Initializing with task book: " + src + " and user prefs " + userPrefs);
taskBook = new TaskBook(src);
filteredTasks = new FilteredList<>(taskBook.getTasks());
registerAsAnEventHandler(this);
}
public ModelManager() {
this(new TaskBook(), new UserPrefs());
}
public ModelManager(ReadOnlyTaskBook initialData, UserPrefs userPrefs) {
taskBook = new TaskBook(initialData);
filteredTasks = new FilteredList<>(taskBook.getTasks());
//@@author A0138301U
registerAsAnEventHandler(this);
updateTaskStatus();
}
protected void registerAsAnEventHandler(Object handler) {
EventsCenter.getInstance().registerHandler(handler);
}
//@@author
@Override
public void resetData(ReadOnlyTaskBook newData) {
taskBook.resetData(newData);
indicateTaskBookChanged();
}
@Override
public ReadOnlyTaskBook getTaskBook() {
return taskBook;
}
/** Raises an event to indicate the model has changed */
private void indicateTaskBookChanged() {
raise(new TaskBookChangedEvent(taskBook));
}
@Override
public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
taskBook.removeTask(target);
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
indicateTaskBookChanged();
}
//@@author A0139958H
@Override
public synchronized int addTask(Task task) throws UniqueTaskList.DuplicateTaskException, DateClashTaskException {
int position = taskBook.addTask(task);
updateFilteredListToShowAll();
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
indicateTaskBookChanged();
return position;
}
@Override
public synchronized int addTask(int index, Task task) throws UniqueTaskList.DuplicateTaskException, DateClashTaskException {
int position = taskBook.addTask(index, task);
updateFilteredListToShowAll();
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
indicateTaskBookChanged();
return position;
}
@Override
public synchronized void updateTask(Task toReplace, Task toUpdate) throws DateClashTaskException {
taskBook.updateTask(toReplace, toUpdate);
updateFilteredListToShowAll();
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
indicateTaskBookChanged();
}
public synchronized void updateTaskStatus() {
taskBook.updateTaskStatus();
updateFilteredListToShowAll();
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
indicateTaskBookChanged();
}
//@@author A0138301U
@Override
public UnmodifiableObservableList<ReadOnlyTask> getSortedTaskList() {
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
Assert.assertNotNull("This object should not be null", sortedTasks);
return new UnmodifiableObservableList<>(sortedTasks);
}
public Task getTaskByIndex(int index) {
Task task = sortedTasks.get(index);
return task;
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskListByKeywords(Set<String> keywords){
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
public void updateFilteredTaskListByHighPriority() {
filteredTasks.setPredicate(task -> {
if(task.getPriority().equals(TaskPriority.HIGH)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByMediumPriority() {
filteredTasks.setPredicate(task -> {
if(task.getPriority().equals(TaskPriority.MEDIUM)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByLowPriority() {
filteredTasks.setPredicate(task -> {
if(task.getPriority().equals(TaskPriority.LOW)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByActiveStatus() {
filteredTasks.setPredicate(task -> {
if(task.getStatus().equals(Status.ACTIVE)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByExpiredStatus() {
filteredTasks.setPredicate(task -> {
if(task.getStatus().equals(Status.EXPIRED)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByDoneStatus() {
filteredTasks.setPredicate(task -> {
if(task.getStatus().equals(Status.DONE)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByIgnoreStatus() {
filteredTasks.setPredicate(task -> {
if(task.getStatus().equals(Status.IGNORE)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByVenue(String venue) {
filteredTasks.setPredicate(task -> {
if(task.getVenue().toString().contains(venue)) {
return true;
} else {
return false;
}
});
}
public void updateFilteredTaskListByTag(Tag tag){
filteredTasks.setPredicate(task -> {
if(task.getTags().contains(tag)) {
return true;
} else {
return false;
}
});
}
/**
* default comparator: arranges tasks by status (active and expired first, followed by done and ignore)
* then pin, then priority level, then by start date or end date where applicable, then by alphabetical order*/
public static class TaskComparator implements Comparator<ReadOnlyTask>
{
public int compare(ReadOnlyTask task1, ReadOnlyTask task2)
{
int value = compareTaskByStatus(task1.getStatus(), task2.getStatus());//by status
if(value == 0) {
value = task1.getPinTask().compareTo(task2.getPinTask());//by pin
if(value == 0) {
value = task1.getPriority().compareTo(task2.getPriority());//by priority
if(value == 0) {
Date date1;
Date date2;
//assign date if possible, if not sort by alphabetical order
if(hasStartDate(task1)){
date1 = convertStringToDateObject(task1.getStartDate().toString());
} else if (hasEndDate(task1)){
date1 = convertStringToDateObject(task1.getEndDate().toString());
} else {
return task1.getName().fullName.compareTo(task2.getName().fullName);
}
//assign date if possible, if not sort by alphabetical order
if(hasStartDate(task2)){
date2 = convertStringToDateObject(task2.getStartDate().toString());
} else if (hasEndDate(task2)){
date2 = convertStringToDateObject(task2.getEndDate().toString());
} else {
return task1.getName().fullName.compareTo(task2.getName().fullName);
}
//compare by alphabetical order if same date
if(date1.equals(date2)) {
return task1.getName().fullName.compareTo(task2.getName().fullName);
}
if(date1.after(date2)) {
return 1;
} else {
return 0;
}
}
return value;
}
return value;
}
return value;
}
private int compareTaskByStatus(Status s1, Status s2) {
int value;
if(statusIsActiveOrExpired(s1)) {
if(statusIsActiveOrExpired(s2)) {
value = 0;
} else {
value = -1;
}
} else {
if(statusIsActiveOrExpired(s2)) {
value = 1;
} else {
value = 0;
}
}
return value;
}
}
private static boolean hasEndDate(ReadOnlyTask task) {
return !task.getEndDate().value.isEmpty();
}
private static boolean hasStartDate(ReadOnlyTask task) {
return !task.getStartDate().value.isEmpty();
}
private static Date convertStringToDateObject(String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E MMM d HH:mm:ss zzz yyyy");
LocalDateTime parsedDate = LocalDateTime.parse(date, formatter);
Date dateFromParsedDate = Date.from(parsedDate.atZone(ZoneId.systemDefault()).toInstant());
return dateFromParsedDate;
}
private static boolean statusIsActiveOrExpired(Status status) {
if(status.equals(Status.ACTIVE) || status.equals(Status.EXPIRED)) {
return true;
}
return false;
}
//@@author
interface Expression {
boolean satisfies(ReadOnlyTask task);
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsIgnoreCase(task.getName().fullName, keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
@Subscribe
public void handleTaskBookChangedEvent(TaskBookChangedEvent tbce) {
sortedTasks = new SortedList<>(filteredTasks, new TaskComparator());
}
}
|
package uk.me.mjt.ch;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ColocatedNodeSet implements Set<Node> {
private Set<Node> underlying;
public ColocatedNodeSet(Collection<Node> nodes) {
underlying = Collections.unmodifiableSet(new HashSet<Node>(nodes));
checkNodesAreColocated(underlying);
}
private void checkNodesAreColocated(Collection<Node> nodes) {
Preconditions.require(!nodes.isEmpty());
Node referenceLocation = null;
for (Node n : nodes) {
if (referenceLocation==null)
referenceLocation=n;
else
Preconditions.require(
n.lat==referenceLocation.lat,
n.sourceDataNodeId==referenceLocation.sourceDataNodeId,
n.lon==referenceLocation.lon);
}
}
public static ColocatedNodeSet singleton(Node node) {
return new ColocatedNodeSet(Collections.singleton(node));
}
public int size() {
return underlying.size();
}
public boolean isEmpty() {
return underlying.isEmpty();
}
public boolean contains(Object o) {
return underlying.contains(o);
}
public Iterator<Node> iterator() {
return underlying.iterator();
}
public Object[] toArray() {
return underlying.toArray();
}
public <T> T[] toArray(T[] a) {
return underlying.toArray(a);
}
public boolean add(Node e) {
return underlying.add(e);
}
public boolean remove(Object o) {
return underlying.remove(o);
}
public boolean containsAll(Collection<?> c) {
return underlying.containsAll(c);
}
public boolean addAll(Collection<? extends Node> c) {
return underlying.addAll(c);
}
public boolean retainAll(Collection<?> c) {
return underlying.retainAll(c);
}
public boolean removeAll(Collection<?> c) {
return underlying.removeAll(c);
}
public void clear() {
underlying.clear();
}
public boolean equals(Object o) {
return underlying.equals(o);
}
public int hashCode() {
return underlying.hashCode();
}
public String toString() {
if (underlying.size()<20)
return "ColocatedNodeSet:"+underlying.toString();
else
return "ColocatedNodeSet:"+underlying.size()+" elements";
}
}
|
package org.codehaus.groovy.ast;
import groovy.lang.Script;
import groovy.lang.Binding;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.objectweb.asm.Constants;
/**
* Represents a module, which consists typically of a class declaration
* but could include some imports, some statements and multiple classes
* intermixed with statements like scripts in Python or Ruby
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @version $Revision$
*/
public class ModuleNode extends ASTNode implements Constants {
private BlockStatement statementBlock = new BlockStatement();
private List classes = new ArrayList();
private List methods = new ArrayList();
private List imports = new ArrayList();
private List importPackages = new ArrayList();
private Map importIndex = new HashMap();
private CompileUnit unit;
private String packageName;
private String description;
private boolean createClassForStatements = true;
public ModuleNode() {
}
public BlockStatement getStatementBlock() {
return statementBlock;
}
public List getMethods() {
return methods;
}
public List getClasses() {
if (createClassForStatements && (!statementBlock.isEmpty() || !methods.isEmpty())) {
ClassNode mainClass = createStatementsClass();
classes.add(0, mainClass);
mainClass.setModule(this);
createClassForStatements = false;
}
return classes;
}
public List getImports() {
return imports;
}
public List getImportPackages() {
return importPackages;
}
/**
* @return the class name for the given alias or null if none is available
*/
public String getImport(String alias) {
return (String) importIndex.get(alias);
}
public void addImport(String alias, String className) {
imports.add(new ImportNode(className, alias));
importIndex.put(alias, className);
}
public void addImportPackage(String packageName) {
importPackages.add(packageName);
}
public void addStatement(Statement node) {
statementBlock.addStatement(node);
}
public void addClass(ClassNode node) {
classes.add(node);
node.setModule(this);
}
public void addMethod(MethodNode node) {
methods.add(node);
}
public void visit(GroovyCodeVisitor visitor) {
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
/**
* @return the underlying character stream description
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Appends all of the fully qualified class names in this
* module into the given map
*/
public void addClasses(Map classMap) {
for (Iterator iter = classes.iterator(); iter.hasNext();) {
ClassNode node = (ClassNode) iter.next();
String name = node.getName();
if (classMap.containsKey(name)) {
throw new RuntimeException(
"Error: duplicate class declaration for name: " + name + " and class: " + node);
}
classMap.put(name, node);
}
}
public CompileUnit getUnit() {
return unit;
}
void setUnit(CompileUnit unit) {
this.unit = unit;
}
protected ClassNode createStatementsClass() {
String name = getPackageName();
if (name == null) {
name = "";
}
else {
name = name + ".";
}
// now lets use the file name to determine the class name
if (description == null) {
throw new RuntimeException("Cannot generate main(String[]) class for statements when we have no file description");
}
name += extractClassFromFileDescription();
String baseClass = null;
if (unit != null) {
baseClass = unit.getConfig().getScriptBaseClass();
}
if (baseClass == null) {
baseClass = Script.class.getName();
}
ClassNode classNode = new ClassNode(name, ACC_PUBLIC, baseClass);
classNode.setScript(true);
// return new Foo(new ShellContext(args)).run()
classNode.addMethod(
new MethodNode(
"main",
ACC_PUBLIC | ACC_STATIC,
"void",
new Parameter[] { new Parameter("java.lang.String[]", "args")},
new ExpressionStatement(
new MethodCallExpression(
new ClassExpression(InvokerHelper.class.getName()),
"runScript",
new ArgumentListExpression(
new Expression[] {
new ClassExpression(classNode.getName()),
new VariableExpression("args")})))));
classNode.addMethod(
new MethodNode("run", ACC_PUBLIC, Object.class.getName(), Parameter.EMPTY_ARRAY, statementBlock));
classNode.addConstructor(ACC_PUBLIC, Parameter.EMPTY_ARRAY, new BlockStatement());
classNode.addConstructor(
ACC_PUBLIC,
new Parameter[] { new Parameter(Binding.class.getName(), "context")},
new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("super"),
"<init>",
new VariableExpression("context"))));
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MethodNode node = (MethodNode) iter.next();
int modifiers = node.getModifiers();
if ((modifiers & ACC_ABSTRACT) != 0) {
throw new RuntimeException(
"Cannot use abstract methods in a script, they are only available inside classes. Method: "
+ node.getName());
}
node.setModifiers(modifiers | ACC_STATIC);
classNode.addMethod(node);
}
return classNode;
}
protected String extractClassFromFileDescription() {
// lets strip off everything after the last .
String answer = description;
int idx = answer.lastIndexOf('.');
if (idx > 0) {
answer = answer.substring(0, idx);
}
// new lets trip the path separators
idx = answer.lastIndexOf('/');
if (idx >= 0) {
answer = answer.substring(idx + 1);
}
idx = answer.lastIndexOf(File.separatorChar);
if (idx >= 0) {
answer = answer.substring(idx + 1);
}
return answer;
}
public boolean isEmpty() {
return classes.isEmpty() && statementBlock.getStatements().isEmpty();
}
}
|
package com.exedio.cope.pattern;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.exedio.cope.Attribute;
import com.exedio.cope.BooleanAttribute;
import com.exedio.cope.ConstraintViolationException;
import com.exedio.cope.DataAttribute;
import com.exedio.cope.Item;
import com.exedio.cope.MandatoryViolationException;
import com.exedio.cope.Model;
import com.exedio.cope.NestingRuntimeException;
import com.exedio.cope.NoSuchIDException;
import com.exedio.cope.ObjectAttribute;
import com.exedio.cope.Pattern;
import com.exedio.cope.StringAttribute;
import com.exedio.cope.Transaction;
import com.exedio.cope.Attribute.Option;
public final class Media extends HttpPath
{
final boolean notNull;
final String fixedMimeMajor;
final String fixedMimeMinor;
final DataAttribute data;
final StringAttribute mimeMajor;
final StringAttribute mimeMinor;
final BooleanAttribute exists;
final ObjectAttribute isNull;
public Media(final Option option, final String fixedMimeMajor, final String fixedMimeMinor)
{
if(option==null)
throw new NullPointerException("option must not be null");
if(fixedMimeMajor==null)
throw new NullPointerException("fixedMimeMajor must not be null");
if(fixedMimeMinor==null)
throw new NullPointerException("fixedMimeMinor must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = fixedMimeMajor;
this.fixedMimeMinor = fixedMimeMinor;
registerSource(this.data = Item.dataAttribute(option));
this.mimeMajor = null;
this.mimeMinor = null;
this.exists = option.mandatory ? null : Item.booleanAttribute(Item.OPTIONAL);
this.isNull = exists;
if(data==null)
throw new NullPointerException("data must not be null");
if(this.exists!=null)
registerSource(this.exists);
}
public Media(final Option option, final String fixedMimeMajor)
{
if(option==null)
throw new NullPointerException("option must not be null");
if(fixedMimeMajor==null)
throw new NullPointerException("fixedMimeMajor must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = fixedMimeMajor;
this.fixedMimeMinor = null;
registerSource(this.data = Item.dataAttribute(option));
this.mimeMajor = null;
registerSource(this.mimeMinor = Item.stringAttribute(option, 1, 30));
this.exists = null;
this.isNull = mimeMinor;
if(data==null)
throw new NullPointerException("data must not be null");
if(mimeMinor==null)
throw new NullPointerException("mimeMinor must not be null");
if(mimeMinor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMinor cannot be unique");
if(mimeMinor.isMandatory())
throw new RuntimeException("mimeMinor cannot be mandatory");
if(mimeMinor.isReadOnly())
throw new RuntimeException("mimeMinor cannot be read-only");
}
public Media(final Option option)
{
if(option==null)
throw new NullPointerException("option must not be null");
this.notNull = option.mandatory;
this.fixedMimeMajor = null;
this.fixedMimeMinor = null;
registerSource(this.data = Item.dataAttribute(option));
registerSource(this.mimeMajor = Item.stringAttribute(option, 1, 30));
registerSource(this.mimeMinor = Item.stringAttribute(option, 1, 30));
this.exists = null;
this.isNull = mimeMajor;
if(data==null)
throw new NullPointerException("data must not be null");
if(mimeMajor==null)
throw new NullPointerException("mimeMajor must not be null");
if(mimeMajor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMajor cannot be unique");
if(mimeMajor.isMandatory())
throw new RuntimeException("mimeMajor cannot be mandatory");
if(mimeMajor.isReadOnly())
throw new RuntimeException("mimeMajor cannot be read-only");
if(mimeMinor==null)
throw new NullPointerException("mimeMinor must not be null");
if(mimeMinor.getSingleUniqueConstraint()!=null)
throw new RuntimeException("mimeMinor cannot be unique");
if(mimeMinor.isMandatory())
throw new RuntimeException("mimeMinor cannot be mandatory");
if(mimeMinor.isReadOnly())
throw new RuntimeException("mimeMinor cannot be read-only");
}
public final String getFixedMimeMajor()
{
return fixedMimeMajor;
}
public final String getFixedMimeMinor()
{
return fixedMimeMinor;
}
public final DataAttribute getData()
{
return data;
}
public final StringAttribute getMimeMajor()
{
return mimeMajor;
}
public final StringAttribute getMimeMinor()
{
return mimeMinor;
}
public final BooleanAttribute getExists()
{
return exists;
}
public void initialize()
{
super.initialize();
final String name = getName();
if(data!=null && !data.isInitialized())
initialize(data, name+"Data");
if(mimeMajor!=null && !mimeMajor.isInitialized())
initialize(mimeMajor, name+"Major");
if(mimeMinor!=null && !mimeMinor.isInitialized())
initialize(mimeMinor, name+"Minor");
if(exists!=null && !exists.isInitialized())
initialize(exists, name+"Exists");
}
public boolean isNull(final Item item)
{
return notNull ? false : (item.get(isNull)==null);
}
/**
* Returns the major mime type of this media.
* Returns null, if there is no data for this media.
*/
public final String getMimeMajor(final Item item)
{
if(isNull(item))
return null;
return (mimeMajor!=null) ? (String)item.get(mimeMajor) : fixedMimeMajor;
}
/**
* Returns the minor mime type of this media.
* Returns null, if there is no data for this media.
*/
public final String getMimeMinor(final Item item)
{
if(isNull(item))
return null;
return (mimeMinor!=null) ? (String)item.get(mimeMinor) : fixedMimeMinor;
}
/**
* Returns the content type of this media.
* Returns null, if there is no data for this media.
*/
public final String getContentType(final Item item)
{
if(isNull(item))
return null;
return getMimeMajor(item) + '/' + getMimeMinor(item);
}
private final RuntimeException newNoDataException(final Item item)
{
return new RuntimeException("missing data for "+this.toString()+" on "+item.toString());
}
/**
* Returns a stream for fetching the data of this media.
* <b>You are responsible for closing the stream, when you are finished!</b>
* Returns null, if there is no data for this media.
*/
public final InputStream getData(final Item item)
{
if(isNull(item))
return null;
final InputStream result = item.get(data);
if(result==null)
throw newNoDataException(item);
return result;
}
/**
* Returns the length of the data of this media.
* Returns -1, if there is no data for this media.
*/
public final long getDataLength(final Item item)
{
if(isNull(item))
return -1;
final long result = item.getDataLength(data);
if(result<0)
throw newNoDataException(item);
return result;
}
/**
* Returns the date of the last modification
* of the data of this media.
* Returns -1, if there is no data for this media.
*/
public final long getDataLastModified(final Item item)
{
if(isNull(item))
return -1;
final long result = item.getDataLastModified(data);
if(result<=0)
throw newNoDataException(item);
return result;
}
/**
* Returns a URL pointing to the data of this media.
* Returns null, if there is no data for this media.
*/
public final String getURL(final Item item)
{
if(isNull(item))
return null;
final StringBuffer bf = new StringBuffer(getMediaRootUrl());
appendDataPath(item, bf);
appendExtension(item, bf);
return bf.toString();
}
/**
* Provides data for this persistent media.
* Closes <data>data</data> after reading the contents of the stream.
* @param data give null to remove data.
* @throws MandatoryViolationException
* if data is null and attribute is {@link Attribute#isMandatory() mandatory}.
* @throws IOException if reading data throws an IOException.
*/
public final void set(final Item item, final InputStream data, final String mimeMajor, final String mimeMinor)
throws IOException
{
try
{
if(data!=null)
{
if((mimeMajor==null&&fixedMimeMajor==null) ||
(mimeMinor==null&&fixedMimeMinor==null))
throw new RuntimeException("if data is not null, mime types must also be not null");
}
else
{
if(mimeMajor!=null||mimeMinor!=null)
throw new RuntimeException("if data is null, mime types must also be null");
}
// TODO use Item.set(AttributeValue[])
if(this.mimeMajor!=null)
item.set(this.mimeMajor, mimeMajor);
if(this.mimeMinor!=null)
item.set(this.mimeMinor, mimeMinor);
if(this.exists!=null)
item.set(this.exists, (data!=null) ? Boolean.TRUE : null);
item.set(this.data, data);
}
catch(ConstraintViolationException e)
{
throw new NestingRuntimeException(e);
}
finally
{
if(data!=null)
data.close();
}
}
private final void appendDataPath(final Item item, final StringBuffer bf)
{
final String id = item.getCopeID();
final int dot = id.indexOf('.');
if(dot<0)
throw new RuntimeException(id);
bf.append(getUrlPath()).
append(id.substring(dot+1));
}
private final void appendExtension(final Item item, final StringBuffer bf)
{
final String major = getMimeMajor(item);
final String minor = getMimeMinor(item);
final String compactExtension = getCompactExtension(major, minor);
if(compactExtension==null)
{
bf.append('.').
append(major).
append('.').
append(minor);
}
else
bf.append(compactExtension);
}
private static final String getCompactExtension(final String mimeMajor, final String mimeMinor)
{
if("image".equals(mimeMajor))
{
if("jpeg".equals(mimeMinor) || "pjpeg".equals(mimeMinor))
return ".jpg";
else if("gif".equals(mimeMinor))
return ".gif";
else if("png".equals(mimeMinor))
return ".png";
else
return null;
}
else if("text".equals(mimeMajor))
{
if("html".equals(mimeMinor))
return ".html";
else if("plain".equals(mimeMinor))
return ".txt";
else if("css".equals(mimeMinor))
return ".css";
else
return null;
}
else
return null;
}
public final static Media get(final DataAttribute attribute)
{
for(Iterator i = attribute.getPatterns().iterator(); i.hasNext(); )
{
final Pattern pattern = (Pattern)i.next();
if(pattern instanceof Media)
{
final Media entity = (Media)pattern;
if(entity.getData()==attribute)
return entity;
}
}
throw new NullPointerException(attribute.toString());
}
private long start = System.currentTimeMillis();
private final Object startLock = new Object();
public final Log mediumFound = new Log();
public final Log itemFound = new Log();
public final Log dataNotNull = new Log();
public final Log modified = new Log();
public final Log fullyDelivered = new Log();
public final Date getStart()
{
final long startLocal;
synchronized(startLock)
{
startLocal = this.start;
}
return new Date(startLocal);
}
public final void resetLogs()
{
final long now = System.currentTimeMillis();
synchronized(startLock)
{
start = now;
}
mediumFound.reset();
itemFound.reset();
dataNotNull.reset();
modified.reset();
fullyDelivered.reset();
}
/**
* Sets the offset, the Expires http header is set into the future.
* Together with a http reverse proxy this ensures,
* that for that time no request for that data will reach the servlet.
* This may reduce the load on the server.
*
* TODO: make this configurable, at best per media.
*/
private static final long EXPIRES_OFFSET = 1000 * 5; // 5 seconds
private static final String REQUEST_IF_MODIFIED_SINCE = "If-Modified-Since";
private static final String RESPONSE_EXPIRES = "Expires";
private static final String RESPONSE_LAST_MODIFIED = "Last-Modified";
private static final String RESPONSE_CONTENT_LENGTH = "Content-Length";
final boolean serveContent(
final HttpServletRequest request, final HttpServletResponse response,
final String pathInfo, final int trailingSlash)
throws ServletException, IOException
{
//System.out.println("entity="+this);
Log state = mediumFound;
final int dotAfterSlash = pathInfo.indexOf('.', trailingSlash);
//System.out.println("trailingDot="+trailingDot);
final String pkString =
(dotAfterSlash>=0)
? pathInfo.substring(trailingSlash+1, dotAfterSlash)
: pathInfo.substring(trailingSlash+1);
//System.out.println("pkString="+pkString);
final String id = getType().getID() + '.' + pkString;
//System.out.println("ID="+id);
try
{
final Model model = getType().getModel();
model.startTransaction("DataServlet");
final Item item = model.findByID(id);
//System.out.println("item="+item);
state = itemFound;
final String contentType = getContentType(item);
//System.out.println("contentType="+contentType);
if(contentType!=null)
{
state = dataNotNull;
response.setContentType(contentType);
final long lastModified = getDataLastModified(item);
//System.out.println("lastModified="+formatHttpDate(lastModified));
response.setDateHeader(RESPONSE_LAST_MODIFIED, lastModified);
final long now = System.currentTimeMillis();
response.setDateHeader(RESPONSE_EXPIRES, now+EXPIRES_OFFSET);
final long ifModifiedSince = request.getDateHeader(REQUEST_IF_MODIFIED_SINCE);
//System.out.println("ifModifiedSince="+request.getHeader(REQUEST_IF_MODIFIED_SINCE));
//System.out.println("ifModifiedSince="+ifModifiedSince);
if(ifModifiedSince>=0 && ifModifiedSince>=lastModified)
{
//System.out.println("not modified");
response.setStatus(response.SC_NOT_MODIFIED);
System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" NOT modified");
}
else
{
state = modified;
final long contentLength = getDataLength(item);
//System.out.println("contentLength="+String.valueOf(contentLength));
response.setHeader(RESPONSE_CONTENT_LENGTH, String.valueOf(contentLength));
//response.setHeader("Cache-Control", "public");
System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" modified: "+contentLength);
ServletOutputStream out = null;
InputStream in = null;
try
{
out = response.getOutputStream();
in = getData(item);
final byte[] buffer = new byte[Math.max((int)contentLength, 50*1024)];
for(int len = in.read(buffer); len != -1; len = in.read(buffer))
out.write(buffer, 0, len);
}
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
state = fullyDelivered;
}
Transaction.commit();
return true;
}
else
{
Transaction.commit();
return false;
}
}
catch(NoSuchIDException e)
{
return false;
}
finally
{
Transaction.rollbackIfNotCommitted();
state.increment();
}
}
private final static String format(final long date)
{
final SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
return df.format(new Date(date));
}
}
|
package controllers;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import controllers.auth.Authorization;
import core.GoogleCloudMessaging;
import core.event.Event;
import core.event.EventHandler;
import core.event.EventType;
import core.event.MonitorEvent;
import models.*;
import models.sensors.ComponentReading;
import models.sensors.Sensor;
import play.Logger;
import play.Routes;
import play.api.libs.json.JsPath;
import play.cache.Cache;
import play.data.*;
import play.libs.F;
import play.libs.Json;
import play.libs.WS;
import play.mvc.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import core.Global;
import core.MyWebSocketManager;
import controllers.auth.Authentication;
public class Application extends Controller {
// We keep the Web Socket Manager singleton as a field for easier reference
private static MyWebSocketManager WS = MyWebSocketManager.getInstance();
static Form<Alarm> alarmForm = Form.form(Alarm.class);
public static Result index() {
return redirect(controllers.routes.Application.openAlarms());
}
/**
* Default login controller
* @return A Result object containing the response body
*/
public static Result login() {
// If user is already logged in, redirect to dashboard
if (session().get("id") != null) {
return redirect(controllers.routes.Application.openAlarms());
}
return ok(views.html.login.render(Authentication.loginForm));
}
/**
* Default logout controller
* @return
*/
public static Result logout() {
session().clear();
return redirect(controllers.routes.Application.login());
}
/**
* Default authentication controller. This controller passes the provided credentials
* from the login form onto the Authentication class for validation.
* @return A Result object containing the response body
*/
public static Result authenticate() {
Form<Authentication.Login> filledForm = Authentication.loginForm.bindFromRequest();
// Return a bad request if validation failed
if (filledForm.hasErrors()) {
Logger.debug("Failed authentication attempt for: " + filledForm.data().get("username"));
return badRequest(views.html.login.render(filledForm));
}
else {
// Fetch the user object, as all invalid login attempts will cause the form to contain errors
AlarmAttendant user = AlarmAttendant.getAttendantFromUsername(filledForm.get().username);
Logger.debug("Successfull authentication from: " + user.username);
// Set the user ID in session and cache the user object
session("id", Long.toString(user.id));
session("username", user.username);
session("role", Integer.toString(user.role));
Cache.set(Long.toString(user.id), user);
return redirect(controllers.routes.Application.openAlarms());
}
}
/* BEGIN ENDPOINTS */
/**
* Returns a JSON object of the currently logged in user
* @return
*/
@Security.Authenticated(Authorization.Authorized.class)
public static Result me() {
AlarmAttendant aa = AlarmAttendant.find.byId(Long.parseLong(session().get("id")));
if (aa == null || aa.id == 0) return notFound(); // Should never happen
return ok(AlarmAttendant.toJson(aa));
}
/**
* Retrieve the main dashboard view
* @return HTTP response with the main Dashboard
*/
@Security.Authenticated(Authorization.Authorized.class)
public static Result openAlarms() {
List<Alarm> alarms = Alarm.allOpenAlarms();
Content html = views.html.index.render(alarms, alarmForm, session().get("username"));
return ok(html);
}
/**
* Retrieves a list of alarms currently assigned to the logged in user
* @return A JSON object containing an array of alarms
*/
@Security.Authenticated(Authorization.Authorized.class)
@Authorization.PrivilegeLevel(Authorization.FIELD_OPERATOR)
public static Result alarmsAssignedToMe() {
ObjectNode jsonAlarms = Json.newObject();
AlarmAttendant currentUser = AlarmAttendant.get(Long.parseLong(session().get("id")));
List<Alarm> alarms;
if (currentUser.role == 3) {
alarms = Alarm.openAlarmsAssignedToMobileCareTaker(currentUser);
} else {
alarms = Alarm.assignedToUser(currentUser);
}
jsonAlarms.put("userId", currentUser.id);
jsonAlarms.put("username", currentUser.username);
jsonAlarms.put("role", currentUser.role);
ArrayNode assignedToUser = new ArrayNode(JsonNodeFactory.instance);
for (Alarm a : alarms) {
ObjectNode alarm = Alarm.toJson(a);
assignedToUser.add(alarm);
}
// Add the alarm array to the wrapper object
jsonAlarms.put("alarms", assignedToUser);
return ok(jsonAlarms);
}
/**
* Retrieve all open alarms as JSON
* @return A JSON Result
*/
public static Result allOpenAlarmsJson() {
List<Alarm> alarms = Alarm.allOpenAlarms();
ObjectNode wrapper = Json.newObject();
wrapper.put("total", alarms.size());
ArrayNode jsonAlarms = wrapper.putArray("alarms");
for (Alarm a : alarms) {
jsonAlarms.add(Alarm.toJson(a));
}
return ok(wrapper);
}
/**
* Create a new alarm from POST request body
* @return 200 OK or Bad request if callee was not provided
*/
public static Result newAlarm() {
Form<Alarm> filledForm = alarmForm.bindFromRequest(); // create a new form with the request data
if (filledForm.hasErrors()) {
return badRequest();
} else {
Alarm formAlarm = filledForm.get();
if (null != formAlarm.callee) {
formAlarm.callee = Callee.getOrCreate(formAlarm.callee);
//formAlarm.patient = Patient.getOrCreate(formAlarm.patient);
Alarm a = Alarm.create(formAlarm);
return ok(Alarm.toJson(a));
} else {
System.out.println("calle was not found in the form");
return badRequest();
}
}
}
/**
* Retrieve an Alarm object based on its ID
* @param id The ID of the Alarm requested
* @return An Alarm instance as JSON
*/
public static Result getAlarm(Long id) {
Alarm a = Alarm.get(id);
ObjectNode jsonAlarm = Alarm.toJson(a);
return ok(jsonAlarm);
}
/**
* Update an Alarm object with latitude and longitude coordinates
* @param id The ID of the Alarm to update
* @return An Alarm instance as JSON
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result setLocationOfAlarm(Long id) {
JsonNode latLng = request().body().asJson();
Double latitude = latLng.findPath("latitude").asDouble();
Double longitude = latLng.findPath("longitude").asDouble();
String location = latLng.findPath("location").asText();
Alarm a = Alarm.setLocationFromResolvedAddress(id, location, latitude, longitude);
return ok(Alarm.toJson(a));
}
/**
* Update an Alarm object with a new patient
* @param id The ID of the Alarm to update
* @return An Alarm instance as JSON
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result setPatientOfAlarm(Long id) {
Alarm a = Alarm.find.byId(id);
if (a == null || a.id == 0) return notFound("Alarm does not exist");
JsonNode patient = request().body().asJson();
Long patientId = patient.get("id").asLong();
Patient p;
if (patientId != 0) {
p = Patient.find.byId(patientId);
if (p == null || p.id == 0) return notFound("Patient does not exist");
} else {
p = new Patient();
p.name = patient.findPath("name").textValue();
p.personalNumber = patient.findPath("personalNumber").textValue();
p.phoneNumber = patient.findPath("phoneNumber").textValue();
p.address = patient.findPath("address").textValue();
p.age = patient.findPath("age").asInt();
// inserts on the db and return the db instance (which will include the id of the patient)
p = Patient.getOrCreate(p);
}
a.patient = p;
a.save();
return ok(Patient.toJson(p));
}
/**
* Return the type and date of each one of the past alarms of the callee
* @param calleeId The ID of the Callee requested
* @return A pre-formatted alarm log as JSON
*/
public static Result getPastAlarmsFromCallee(Long calleeId) {
List<Alarm> alarmList = Alarm.pastAlarmsFromCallee(calleeId);
return alarmListToJsonAlarmLog(alarmList);
}
/**
* Return the type and date of each one of the past alarms of the patient
* @param patientId The ID of the Patient requested
* @return A pre-formatted alarm log as JSON
*/
public static Result getPastAlarmsFromPatient(Long patientId) {
List<Alarm> alarmList = Alarm.pastAlarmsFromPatient(patientId);
return alarmListToJsonAlarmLog(alarmList);
}
/**
* Convert a list of alarms into json alarm logs containing date and type of alarms
* @param alarmList A list of Alarm objects
* @return A formatted array of alarm log instances as JSON
*/
private static Result alarmListToJsonAlarmLog(List<Alarm> alarmList) {
SimpleDateFormat ddMMyy = new SimpleDateFormat ("dd/MM yyyy");
SimpleDateFormat hhMin = new SimpleDateFormat ("HH:mm");
ObjectNode result = Json.newObject();
ArrayNode alarmArray = new ArrayNode(JsonNodeFactory.instance);
for (Alarm temp : alarmList) {
ObjectNode alarm = Json.newObject();
alarm.put("day", ddMMyy.format(temp.closingTime));
alarm.put("hour", hhMin.format(temp.closingTime));
alarm.put("type", temp.type);
alarm.put("notes", temp.notes);
alarmArray.add(alarm);
}
result.put("alarmArray",alarmArray);
return ok(result);
}
/**
* Retrieve a list of potential patients based on an Alarm instance
* @param id The ID of the alarm to use as query
* @return An arrey of Patients as JSON
*/
public static Result getProspectPatients(Long id) {
List<Patient> patientList = Patient.prospectPatientsFromAlarm(id);
ObjectNode result = Json.newObject();
ArrayNode patients = result.putArray("patients");
for (Patient p : patientList) {
patients.add(Patient.toJson(p));
}
result.put("patients", patients);
return ok(result);
}
/**
* Endpoint for handling patient searching
* @return A JSON array of Patient objects
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result patientSearch() {
JsonNode searchData = request().body().asJson();
String searchString = searchData.findPath("query").asText();
List<Patient> results = Patient.search(searchString);
ObjectNode jsonResult = Json.newObject();
jsonResult.put("total", results.size());
ArrayNode patients = jsonResult.putArray("results");
for (Patient p : results) {
patients.add(Patient.toJson(p));
}
return ok(jsonResult);
}
/**
* Retrieve a Callee based on an Alarm ID
* @param id The ID of the Alarm to use as query
* @return A Callee object as JSON
*/
public static Result getCalleeFromAlarm(Long id) {
Alarm a = Alarm.get(id);
ObjectNode calle = Json.newObject();
calle.put("id", a.callee.id);
calle.put("name", a.callee.name);
calle.put("phoneNumber", a.callee.phoneNumber);
calle.put("address", a.callee.address);
return ok(calle);
}
/**
* Create and insert a Patient into the database from the POST request body
* @return A Patient object as JSON
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result insertPatientFromJson() {
JsonNode json = request().body().asJson();
Patient p = new Patient();
p.name = json.findPath("name").textValue();
p.personalNumber = json.findPath("personalNumber").textValue();
p.phoneNumber = json.findPath("phoneNumber").textValue();
p.address = json.findPath("address").textValue();
p.age = json.findPath("age").asInt();
// inserts on the db and return the db instance (which will include the id of the patient)
Patient retObj = Patient.getOrCreate(p);
ObjectNode patient = Patient.toJson(retObj);
// Trigger the event
EventHandler.dispatch(new MonitorEvent(EventType.PATIENT_NEW, null, null, retObj));
return ok(patient);
}
/**
* Close a case based on provided alarm data from POST request body
* @return 200 OK
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result closeCase() {
JsonNode json = request().body().asJson();
JsonNode patient = json.get("patient");
Long patientId = 0L;
if (!patient.isNull()) patientId = json.get("patient").get("id").asLong();
String notes = json.findPath("notes").asText();
String alarmOccurance = json.findPath("occuranceAddress").asText();
long alarmId = json.findPath("id").asLong();
Alarm a = new Alarm();
a.occuranceAddress = alarmOccurance;
a.id = alarmId;
// If we have addition to the notes, append and template it
if (notes != null && notes.length() > 0) {
a.setNotes(session().getOrDefault("username", "unknown"), notes);
}
if (0 != patientId) {
a.patient = Patient.getFromId(patientId);
}
Alarm.closeAlarm(a);
return ok();
}
/**
* Flag an Alarm object as being finished by the mobile care taker
* @param id The ID of the Alarm in question
* @return The Alarm object as JSON if ok, unauthorized if mismatch between reporting caretaker and
* registered caretaker. Not found if alarm id does not exist.
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result finishCase(Long id) {
String careTaker = session().get("username");
Alarm a = Alarm.get(id);
if (a != null) {
Logger.debug("finishAlarm called on: " + id.toString());
/* TODO: ENABLE BELOW CODE DURING REGULAR OPERATION (It's disabled for development purposes)
if (!a.mobileCareTaker.username.equals(careTaker)) {
Logger.debug("Attempt to finish a case not designated for that user");
return unauthorized("Attempt to finish a case not designated for that user");
}
*/
a.finished = true;
a.mobileCareTaker = null;
a.save();
// Trigger the event
EventHandler.dispatch(new MonitorEvent(EventType.ALARM_FINISHED, a, null, null));
return ok(Alarm.toJson(a));
} else {
Logger.debug("Attempt to finish a non-existant case: " + id);
return notFound();
}
}
/**
* Update the data of an alarm based on the POST request body
* @return An updated Alarm object as JSON
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result saveAndFollowupCase() {
AlarmAttendant at = AlarmAttendant.find.byId(Long.parseLong(session().getOrDefault("id", "0")));
Logger.debug(request().body().toString());
JsonNode json = request().body().asJson();
long patientId;
JsonNode patient = json.get("patient");
if (!patient.isNull()) patientId = patient.get("id").asLong();
else patientId = 0;
String notes = json.findPath("notes").asText();
String alarmOccurance = json.findPath("occuranceAddress").asText();
long alarmId = json.findPath("id").asLong();
Long mobileCareTaker = json.findPath("mobileCareTaker").asLong();
boolean finished = json.findPath("finished").asBoolean();
Alarm a = Alarm.get(alarmId);
a.occuranceAddress = alarmOccurance;
a.finished = finished;
// Do we have a provided assessment from attendant?
if (json.hasNonNull("assessment")) {
JsonNode attendantAssessment = json.get("assessment");
a.assessment.sensorsChecked = attendantAssessment.get("sensorsChecked").asBoolean();
a.assessment.patientInformationChecked = attendantAssessment.get("patientInformationChecked").asBoolean();
if (attendantAssessment.hasNonNull("nmi")) {
JsonNode nmi = attendantAssessment.get("nmi");
if (!nmi.get("conscious").isNull()) a.assessment.nmi.conscious = nmi.get("conscious").asBoolean();
else a.assessment.nmi.conscious = null;
if (!nmi.get("breathing").isNull()) a.assessment.nmi.breathing = nmi.get("breathing").asBoolean();
else a.assessment.nmi.breathing = null;
if (!nmi.get("movement").isNull()) a.assessment.nmi.movement = nmi.get("movement").asBoolean();
else a.assessment.nmi.movement = null;
if (!nmi.get("standing").isNull()) a.assessment.nmi.standing = nmi.get("standing").asBoolean();
else a.assessment.nmi.standing = null;
if (!nmi.get("talking").isNull()) a.assessment.nmi.talking = nmi.get("talking").asBoolean();
else a.assessment.nmi.talking = null;
}
}
// Do we have a provided assessment from field operator?
if (json.hasNonNull("fieldAssessment")) {
JsonNode fieldOperatorAssessment = json.get("fieldAssessment");
a.fieldAssessment.sensorsChecked = fieldOperatorAssessment.get("sensorsChecked").asBoolean();
a.fieldAssessment.patientInformationChecked = fieldOperatorAssessment.get("patientInformationChecked").asBoolean();
if (fieldOperatorAssessment.hasNonNull("nmi")) {
JsonNode nmi = fieldOperatorAssessment.get("nmi");
if (!nmi.get("conscious").isNull()) a.fieldAssessment.nmi.conscious = nmi.get("conscious").asBoolean();
else a.fieldAssessment.nmi.conscious = null;
if (!nmi.get("breathing").isNull()) a.fieldAssessment.nmi.breathing = nmi.get("breathing").asBoolean();
else a.fieldAssessment.nmi.breathing = null;
if (!nmi.get("movement").isNull()) a.fieldAssessment.nmi.movement = nmi.get("movement").asBoolean();
else a.fieldAssessment.nmi.movement = null;
if (!nmi.get("standing").isNull()) a.fieldAssessment.nmi.standing = nmi.get("standing").asBoolean();
else a.fieldAssessment.nmi.standing = null;
if (!nmi.get("talking").isNull()) a.fieldAssessment.nmi.talking = nmi.get("talking").asBoolean();
else a.fieldAssessment.nmi.talking = null;
}
}
if (0 != patientId) {
a.patient = new Patient();
a.patient.id = patientId;
}
// If we have assigned a field operator of type mobileCareTaker (role == 3)
if (mobileCareTaker != null && mobileCareTaker > 0) {
a.mobileCareTaker = AlarmAttendant.get(mobileCareTaker);
// Notify the Field Operator through GCM
F.Promise<WS.Response> resp = GoogleCloudMessaging.dispatchAlarm(a.mobileCareTaker);
if (resp != null) Logger.debug("GCM Response: " + resp.get(5000).getBody());
}
// If we have addition to the notes, append and template it
if (notes != null && notes.length() > 0) {
a.setNotes(session().getOrDefault("username", "unknown"), notes);
}
Alarm.saveAndFollowupAlarm(a);
return ok(Alarm.toJson(a));
}
/**
* Assign an attendant to an Alarm based on the POST request body and active user
* @return 200 OK, or Unauthorized if lacking privileges
*/
@Security.Authenticated(Authorization.Authorized.class)
@Authorization.PrivilegeLevel(Authorization.ATTENDANT)
@BodyParser.Of(BodyParser.Json.class)
public static Result assignAlarmFromJson() {
JsonNode json = request().body().asJson();
Long alarmId = json.findPath("alarmId").asLong();
AlarmAttendant a = AlarmAttendant.getAttendantFromUsername(session().get("username"));
Alarm alarm = Alarm.get(alarmId);
if (alarm.attendant != null) return forbidden("Alarm already assigned!");
return ok(Alarm.toJson(Alarm.assignAttendantToAlarm(alarmId, a)));
}
/**
* Update an Alarm with external data in notes, and notify all web socket connections of
* the updated alarm from external source. Retrieves updated notes from POST request body.
* @param id The ID of the Alarm in question
* @return 200 OK or Bad request if state of the Alarm is non-existent, not dispatched or closed.
*/
@BodyParser.Of(BodyParser.Json.class)
public static Result notifyFollowup(Long id) {
JsonNode alarmNotes = request().body().asJson();
String notes = alarmNotes.findPath("notes").asText();
Alarm a = Alarm.get(id);
// Test if alarm exists and is on following up list
if (null == a || a.dispatchingTime == null || a.closingTime != null) {
return badRequest();
}
else {
if (notes != null && notes.length() > 0) {
a.setNotes(session().getOrDefault("username", "unknown"), notes);
a.save();
}
// Trigger the event
EventHandler.dispatch(new MonitorEvent(EventType.ALARM_EXTERNAL_FOLLOWUP_NOTIFY, a, null, null));
return ok(Alarm.toJson(a));
}
}
/**
* Dynamic rendered JavaScript routes exposure
* @return A JavaScript router
*/
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("myJsRoutes",
controllers.routes.javascript.Application.getPastAlarmsFromCallee(),
controllers.routes.javascript.Application.saveAndFollowupCase(),
controllers.routes.javascript.Application.closeCase(),
controllers.routes.javascript.Application.insertPatientFromJson(),
controllers.routes.javascript.Application.setPatientOfAlarm(),
controllers.routes.javascript.Application.assignAlarmFromJson(),
controllers.routes.javascript.Application.getCalleeFromAlarm(),
controllers.routes.javascript.Application.getProspectPatients(),
controllers.routes.javascript.Application.patientSearch(),
controllers.routes.javascript.Application.notifyFollowup(),
controllers.routes.javascript.Application.finishCase(),
controllers.routes.javascript.Application.getAlarm(),
controllers.routes.javascript.Application.setLocationOfAlarm()
)
);
}
/**
* Generic WebSocket JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result wsJs() {
return ok(views.js.ws.render());
}
/**
* Generic Alarm selection JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result getalarmSelectTemplateJs() {
return ok(views.js.alarmSelectTemplate.render());
}
/**
* Generic Patient scripts JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result getpatientTemplateScriptsJs() {
return ok(views.js.patientTemplateScripts.render());
}
/**
* Generic Actions scripts JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result getactionsAndClosingScriptsJs() {
return ok(views.js.actionsAndClosingScripts.render());
}
/**
* Generic Assessment scripts JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result getassesmentPageScriptsJs() {
return ok(views.js.assesmentPageScripts.render());
}
/**
* Generic MapView JavaScript renderer
* @return A rendered JavaScript file
*/
public static Result getmapViewScriptsJs() { return ok(views.js.mapViewScripts.render()); }
/**
* Generic SensorReading JavaScript renderer
* @return
*/
public static Result getsensorReadingScriptsJs() { return ok(views.js.sensorReadingScripts.render()); }
/**
* WebSocket interface renderer
* @return A WebSocket endpoint for handshaking and connection handling
*/
@Security.Authenticated(Authorization.Authorized.class)
public static WebSocket<JsonNode> wsInterface() {
// Prefetch the username as it is not available in the returned WebSocket object's scope.
String username = session().get("username");
return new WebSocket<JsonNode>() {
// Called when WebSocket handshake is done
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
WS.start(username, in, out);
}
};
}
}
|
package helpers;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import play.Logger;
import play.libs.ws.*;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.libs.ws.WSResponse;
import com.typesafe.config.ConfigFactory;
import models.DnsEntry;
import models.Domain;
public class DnsUpdateHelper {
private final static String AUTODNS_HOST = ConfigFactory.load().getString("autodns.host");
private final static String AUTODNS_USERNAME = ConfigFactory.load().getString("autodns.user");
private final static String AUTODNS_PASSWORD = ConfigFactory.load().getString("autodns.pass");
private final static String AUTODNS_CONTEXT = ConfigFactory.load().getString("autodns.context");
private final static String AUTODNS_NS_1 = ConfigFactory.load().getString("autodns.ns1");
private final static String AUTODNS_NS_2 = ConfigFactory.load().getString("autodns.ns2");
private final static String AUTODNS_NS_3 = ConfigFactory.load().getString("autodns.ns3");
private final static String AUTODNS_NS_4 = ConfigFactory.load().getString("autodns.ns4");
private Domain domain;
private final static int SUBDOMAIN_TTL = parseInteger("autodns.subdomain.ttl", 60);
private final static int DOMAIN_TTL = parseInteger("autodns.domain.ttl", 3600);
private final static int NS_TTL = parseInteger("autodns.nameserver.ttl", 86400);
public DnsUpdateHelper(Domain domain) {
this.domain = domain;
}
public void update() {
String message = getHeader() + buildUpdateList() + getFooter();
Logger.debug("@"+System.currentTimeMillis()+" sending Update: \n" + message + "\n");
performUpdate(message);
}
// TODO move string to template
private String getHeader() {
return "<request>" + "<auth>" + "<user>"
+ AUTODNS_USERNAME
+ "</user>"
+ "<password>"
+ AUTODNS_PASSWORD
+ "</password>"
+ "<context>"
+ AUTODNS_CONTEXT
+ "</context>"
+ "</auth>"
+ "<task>"
+ "<code>"
+ domain.code
+ "</code>"
+ "<zone>"
+ "<internal_ns>"
+ AUTODNS_NS_1
+ "</internal_ns>"
+ "<name>"
+ domain.name
+ "</name>"
+ "<ns_action>complete</ns_action>"
+ "<main>"
+ "<value>"
+ domain.ip
+ "</value>"
+ "<ttl>"+DOMAIN_TTL+"</ttl>"
+ "</main>"
+ "<www_include>1</www_include>"
+ "<soa>"
+ "<ttl>86400</ttl>"
+ "<refresh>39940</refresh>"
+ "<retry>14400</retry>"
+ "<expire>604800</expire>"
+ "<email>"
+ domain.hostmaster
+ "</email>"
+ "</soa>"
+ "<nserver>"
+ "<name>"
+ AUTODNS_NS_1
+ "</name>"
+ "<ttl>"+NS_TTL+"</ttl>"
+ "</nserver>"
+ "<nserver>"
+ "<name>"
+ AUTODNS_NS_2
+ "</name>"
+ "<ttl>"+NS_TTL+"</ttl>"
+ "</nserver>"
+ "<nserver>"
+ "<name>"
+ AUTODNS_NS_3
+ "</name>"
+ "<ttl>"+NS_TTL+"</ttl>"
+ "</nserver>"
+ "<nserver>"
+ "<name>"
+ AUTODNS_NS_4
+ "</name>"
+ "<ttl>"+NS_TTL+"</ttl>"
+ "</nserver>"
+ "<allow_transfer_from/>"
+ "<free/>"
+ "<rr>"
+ "<name>*</name>"
+ "<ttl>"+SUBDOMAIN_TTL+"</ttl>"
+ "<type>A</type>"
+ "<value>" + domain.ip + "</value>" + "</rr>";
}
// TODO move string to template
private String getFooter() {
return "</zone>"
+ "<ns_group>default</ns_group>"
+ "<ctid/>"
+ "</task>"
+ "</request>";
}
/**
* We need to update all Entries all Time. API is an all or nothing approach.
*/
private void updateEntries() {
for (DnsEntry entry : domain.findNeedsToChanged()) {
entry.actualIp = entry.updatedIp;
entry.actualIp6 = entry.updatedIp6;
if(entry.needsUpdate6()) {
entry.updated6 = new Date();
} else {
entry.updated = new Date();
}
Logger.info("@"+System.currentTimeMillis()+" did update for " + entry);
entry.save();
}
domain.forceUpdate = false;
domain.save();
}
private void performUpdate(String content) {
Logger.debug("update: "+content);
Promise<Document> xmlPromise = WS.url(AUTODNS_HOST)
.setHeader("Content-Type", "text/xml; charset=utf-8")
.post(content).map(new Function<WSResponse, Document>() {
public Document apply(WSResponse response) {
Document doc = response.asXml();
if (getUpdateStatus(doc)) {
Logger.info("@"+System.currentTimeMillis()+" success!");
updateEntries();
} else {
Logger.error(doc.toString());
}
return doc;
}
});
}
private static String getCName(String fullName, String domainName){
return fullName.replace("."+domainName, "").trim();
}
private String buildUpdateList() {
StringBuilder sb = new StringBuilder();
for (DnsEntry entry : domain.findValidEntries()) {
if(!entry.toDelete) {
if(entry.updatedIp6 != null) {
sb.append("<rr>")
.append("<name>")
.append(getCName(entry.name+"."+entry.subDomain.name, entry.domain.name))
.append("</name>")
.append("<ttl>"+SUBDOMAIN_TTL+"</ttl>")
.append("<type>AAAA</type>")
.append("<value>")
.append(entry.updatedIp6)
.append("</value>")
.append("</rr>");
}
if(entry.updatedIp != null) {
sb.append("<rr>")
.append("<name>")
.append(getCName(entry.name+"."+entry.subDomain.name, entry.domain.name))
.append("</name>")
.append("<ttl>"+SUBDOMAIN_TTL+"</ttl>")
.append("<type>A</type>")
.append("<value>")
.append(entry.updatedIp)
.append("</value>")
.append("</rr>");
}
} else {
entry.delete();
Logger.info("@"+System.currentTimeMillis()+" deleting "+entry);
}
}
return sb.toString();
}
private boolean getUpdateStatus(Document doc) {
doc.getDocumentElement().normalize();
NodeList layerConfigList = doc.getElementsByTagName("type");
Node node = layerConfigList.item(0);
return node != null && node.getTextContent().toLowerCase().equals("success");
}
private static int parseInteger(String key, int fallback){
if(key != null && ConfigFactory.load().hasPath(key)){
try {
return Integer.parseInt(ConfigFactory.load().getString(key));
} catch(NumberFormatException ex){
Logger.warn("cannot parse "+ex.getLocalizedMessage());
}
}
return fallback;
}
}
|
package com.openxc.measurements;
import com.openxc.units.Unit;
import com.openxc.util.Range;
/**
* The MeasurementInterface is the base for all OpenXC measurements.
*
* A Measurement has at least a value and an age, and optionally a range of
* valid values.
*/
public interface MeasurementInterface {
public interface Listener {
public void receive(MeasurementInterface measurement);
}
/**
* Retreive the age of this measurement.
*
* @return the age of the data in seconds.
*/
public double getAge();
/**
* Set the birth timestamp for this measurement.
*
*/
public void setTimestamp(double timestamp);
/**
* Determine if this measurement has a valid range.
*
* @return true if the measurement has a non-null range.
*/
public boolean hasRange();
/**
* Retrieve the valid range of the measurement.
*
* @return the Range of the measurement
* @throws NoRangeException if the measurement doesn't have a range.
*/
public Range<? extends Unit> getRange() throws NoRangeException;
/**
* Return the value of this measurement.
*
* @return The wrapped value (an instance of TheUnit)
*/
public Unit getValue();
/**
* Return the value of this measurement as a type good for serialization.
*
* This is required because we go through this process with each
* measurement:
*
* - Incoming JSON is parsed to String, boolean, double, and int.
* - All types are converted to double by RawMeasurement in order to fit
* over AIDL (TODO this seems really, really wrong and adds a ton of
* complication - I know I spent 2 or 3 days on trying to do templated
* classes over AIDL and it just didn't seem to work, but there must be
* a better way)
* - Converted to full Measurement in VehicleService (the specific
* Measurement classes know how to convert from a double back to the
* real value.
* - Output the original values (as if they were directly from JSON)
* form the Measurement for the data sinks in the VehicleService.
*
* @return something easily serializable - e.g. String, Double, Boolean.
*/
public Object getSerializedValue();
/**
* Return an optional event associated with this measurement.
*
* TODO argh, no easy way to get a type for this without having two template
* parameters. can we have an optional template parameter in Java?
*/
public Object getEvent();
/**
* Return the event of this measurement as a type good for serialization.
*
* @see #getSerializedValue()
*/
public Object getSerializedEvent();
}
|
package org.caleydo.core.data.collection.table;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.NotImplementedException;
import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.EDataType;
import org.caleydo.core.data.collection.column.AColumn;
import org.caleydo.core.data.collection.column.container.CategoricalClassDescription;
import org.caleydo.core.data.collection.column.container.CategoryProperty;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.graph.tree.ClusterTree;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.perspective.variable.PerspectiveInitializationData;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.data.virtualarray.group.GroupList;
import org.caleydo.core.event.data.DataDomainUpdateEvent;
import org.caleydo.core.io.DataSetDescription;
import org.caleydo.core.io.NumericalProperties;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.util.collection.Pair;
import org.caleydo.core.util.color.Color;
import org.caleydo.core.util.color.mapping.ColorMapper;
import org.caleydo.core.util.function.AdvancedDoubleStatistics;
import org.caleydo.core.util.logging.Logger;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* <p>
* A table is the main container for matrix data in Caleydo. It is made up of {@link AColumn}s, where each column
* corresponds to a column in an input file.
* </p>
* <p>
* The table does not provide direct access to columns and rows, but abstracts it through <b>dimensions</b> and
* <b>records</b> to allow a de-facto transposition of the input data.
* <p>
* Every column in the table has to have the same length. Data is immutable.
* </p>
* <p>
* The base implementation of Table does not make any assumptions on the relationship of data between individual
* columns. Specific implementations for homogeneous numerical ({@link NumericalTable}) and for homogeneous categorical
* ({@link CategoricalTable}) exist.
* </p>
* <p>
* The data should be accessed through {@link VirtualArray}s, which are stored in {@link Perspective}s. The table
* creates default instances for both records and dimensions, but modification to these are common.
* </p>
* <h2>Table Creation</h2>
* <p>
* A data table is created using the {@link TableUtils} implementation.
* </p>
*
* @author Alexander Lex
*/
public class Table {
private static final double NAN_THRESHOLD = 0.8;
public class Transformation {
/** Untransformed data */
public static final String LINEAR = "None";
public static final String INVERT = "Inverted";
}
/** The data domain holding this table */
protected final ATableBasedDataDomain dataDomain;
/** The color-mapper for this table */
private ColorMapper colorMapper;
/**
* The transformation delivered when calling the {@link #getNormalizedValue(Integer, Integer)} method without and
* explicit transformation
*/
protected String defaultDataTransformation = Table.Transformation.LINEAR;
/** The columns of the table hashed by their column ID */
protected List<AColumn<?, ?>> columns;
/** List of column IDs in the order as they have been added */
private ArrayList<Integer> defaultColumnIDs;
/** Container holding all the record perspectives registered. The perspectiveIDs are the keys */
private HashMap<String, Perspective> hashRecordPerspectives;
/** same as {@link #hashRecordPerspectives} for dimensions */
private HashMap<String, Perspective> hashDimensionPerspectives;
/**
* Default record perspective. Initially all the data is contained in this perspective. If not otherwise specified,
* filters, clusterings etc. are always applied to this perspective
*/
private Perspective defaultRecordPerspective;
/** Same as {@link #defaultRecordPerspective} for dimensions */
private Perspective defaultDimensionPerspective;
/**
* Sampled record perspective that only contains a subset of the full dataset. How big the sampled subset is, is
* determined during the data loading. Will return the default record perspective if no sampled version is
* available.
*/
private Perspective sampledRecordPerspective;
/** Same as {@link #defaultRecordPerspective} for dimensions */
private Perspective sampledDimensionPerspective;
/**
* Flag telling whether the columns correspond to dimensions (false) or whether the columns correspond to records
* (true)
*/
protected boolean isColumnDimension = false;
protected final DataSetDescription dataSetDescription;
/**
* Constructor for the table. Creates and initializes members and registers the set whit the set manager. Also
* creates a new default tree. This should not be called by implementing sub-classes.
*/
public Table(ATableBasedDataDomain dataDomain) {
this.dataDomain = dataDomain;
this.dataSetDescription = dataDomain.getDataSetDescription();
isColumnDimension = !dataSetDescription.isTransposeMatrix();
columns = new ArrayList<>();
hashRecordPerspectives = new HashMap<String, Perspective>(6);
hashDimensionPerspectives = new HashMap<String, Perspective>(3);
defaultColumnIDs = new ArrayList<Integer>();
}
/**
* Returns a boolean specifying whether the data is homogenous (i.e. all columns have the same data type and value
* ranges. False for base class. Implementing classes may override this
*/
public boolean isDataHomogeneous() {
return false;
}
/**
* Get the number of dimensions in a set
*
* @return
*/
public int size() {
if (isColumnDimension)
return getNrColumns();
else
return getNrRows();
}
/**
* Get the depth of the set, which is the number of records, the length of the dimensions
*
* @return the number of elements in the dimensions contained in the list
*/
public int depth() {
if (isColumnDimension)
return getNrRows();
else
return getNrColumns();
}
/**
* Get parent data domain
*
* @param dataDomain
*/
public ATableBasedDataDomain getDataDomain() {
return dataDomain;
}
/**
* Returns the normalized value using the dataTransformation set in {@link #defaultDataTransformation}
*
* @param dimensionID
* @param recordID
* @return
*/
public Float getNormalizedValue(Integer dimensionID, Integer recordID) {
if (dimensionID == null || recordID == null) {
throw new IllegalArgumentException("Dimension ID or record ID was null. Dimension ID: " + dimensionID
+ ", Record ID: " + recordID);
}
try {
if (isColumnDimension) {
return columns.get(dimensionID).getNormalizedValue(defaultDataTransformation, recordID);
} else {
AColumn<?, ?> column = columns.get(recordID);
return column.getNormalizedValue(defaultDataTransformation, dimensionID);
}
} catch (NullPointerException npe) {
Logger.log(new Status(IStatus.ERROR, this.toString(), "Data table does not contain a value for record: "
+ recordID + " and dimension " + dimensionID, npe));
return null;
}
}
public Float getNormalizedValue(String dataTransformation, Integer dimensionID, Integer recordID) {
try {
int colID;
int rowID;
if (isColumnDimension) {
colID = dimensionID;
rowID = recordID;
} else {
rowID = dimensionID;
colID = recordID;
}
AColumn<?, ?> col = columns.get(colID);
return col.getNormalizedValue(dataTransformation, rowID);
} catch (NullPointerException npe) {
Logger.log(new Status(IStatus.ERROR, this.toString(), "Data table does not contain a value for record: "
+ recordID + " and dimension " + dimensionID, npe));
return null;
}
}
public String getRawAsString(Integer dimensionID, Integer recordID) {
Integer columnID = dimensionID;
Integer rowID = recordID;
if (!isColumnDimension) {
columnID = recordID;
rowID = dimensionID;
}
return columns.get(columnID).getRawAsString(rowID);
}
// public boolean containsDataRepresentation(DataRepresentation dataRepresentation, Integer dimensionID,
// Integer recordID) {
// Integer columnID = dimensionID;
// if (!isColumnDimension)
// columnID = recordID;
// return columns.get(columnID).containsDataRepresentation(dataRepresentation);
public EDataType getRawDataType(Integer dimensionID, Integer recordID) {
Integer columnID = dimensionID;
if (!isColumnDimension)
columnID = recordID;
return columns.get(columnID).getRawDataType();
}
/** Returns the {@link EDataClass} associated with the value specified through dimension and record ID */
public EDataClass getDataClass(Integer dimensionID, Integer recordID) {
Integer columnID = dimensionID;
if (!isColumnDimension)
columnID = recordID;
return columns.get(columnID).getDataClass();
}
@SuppressWarnings("unchecked")
public <RAW_DATA_TYPE> RAW_DATA_TYPE getRaw(Integer dimensionID, Integer recordID) {
Integer columnID = dimensionID;
Integer rowID = recordID;
if (!isColumnDimension) {
columnID = recordID;
rowID = dimensionID;
}
if (columnID < 0 || columnID >= columns.size())
return null;
return (RAW_DATA_TYPE) columns.get(columnID).getRaw(rowID);
}
/**
* Returns the 3-component color for the given table cell. This works independent of the data type.
*
* FIXME: inhomogeneous numerical is not implemented
*
* @param dimensionID
* @param recordID
* @return
*/
public float[] getColor(Integer dimensionID, Integer recordID) {
if (isDataHomogeneous()) {
return getColorMapper().getColor(getNormalizedValue(dimensionID, recordID));
} else {
if (EDataClass.CATEGORICAL.equals(getDataClass(dimensionID, recordID))) {
CategoricalClassDescription<?> specific = (CategoricalClassDescription<?>) getDataClassSpecificDescription(
dimensionID, recordID);
Object category = getRaw(dimensionID, recordID);
if (category == null)
return Color.NOT_A_NUMBER_COLOR.getRGBA();
CategoryProperty<?> p = specific.getCategoryProperty(category);
if (p == null)
return Color.NOT_A_NUMBER_COLOR.getRGBA();
return specific.getCategoryProperty(category).getColor().getRGBA();
} else {
// simple implementation just gray scale
Float v = getNormalizedValue(dimensionID, recordID);
if (v == null || v.isNaN())
return Color.NOT_A_NUMBER_COLOR.getRGBA();
return new Color(v.floatValue()).getRGBA();
// not implemented
}
}
}
/**
* <p>
* Returns the ColorMapper for this dataset. Warning: this only works properly for homogeneous numerical datasets.
* </p>
* <p>
* Use {@link Table#getColor(Integer, Integer)} instead if you want access to a cell's color - which works for all
* data types.
* </p>
* TODO: move this to Table and provide separate interfaces for homogeneous and inhomogeneous datasets.
*
* @return the colorMapper, see {@link #colorMapper}
*/
public ColorMapper getColorMapper() {
if (colorMapper == null) {
if (this instanceof NumericalTable && ((NumericalTable) this).getDataCenter() != null) {
colorMapper = ColorMapper.createDefaultThreeColorMapper();
} else if (this instanceof CategoricalTable<?>) {
colorMapper = ((CategoricalTable<?>) this).createColorMapper();
} else {
colorMapper = ColorMapper.createDefaultTwoColorMapper();
}
}
// FIXME this is a hack due to a bug in colorMapper
// colorMapper.update();
return colorMapper;
}
/**
* @param colorMapper
* setter, see {@link #colorMapper}
*/
public void setColorMapper(ColorMapper colorMapper) {
this.colorMapper = colorMapper;
}
/**
* @return Returns a clone of a list of all dimension ids in the order they were initialized.
*/
@SuppressWarnings("unchecked")
public List<Integer> getColumnIDList() {
return (List<Integer>) defaultColumnIDs.clone();
}
/**
* @return Returns a new list of all record IDs in the order they were initialized
*/
public List<Integer> getRowIDList() {
int rowCount = getNrRows();
ArrayList<Integer> list = new ArrayList<Integer>(rowCount);
for (int i = 0; i < rowCount; i++) {
list.add(i);
}
return list;
}
/**
* @param sampled
* Determines whether the full or the sampled default record perspective is requested
* @return the defaultRecordPerspective, see {@link #defaultRecordPerspective}
*/
public Perspective getDefaultRecordPerspective(boolean sampled) {
if (sampled && sampledRecordPerspective != null)
return sampledRecordPerspective;
return defaultRecordPerspective;
}
/**
* Returns a {@link Perspective} object for the specified ID. The {@link Perspective} provides access to all mutable
* data on how to access the Table, e.g., {@link VirtualArray}, {@link ClusterTree}, {@link GroupList}, etc.
*
* @param recordPerspectiveID
* @return the associated {@link Perspective} object, or null if no such object is registered.
*/
public Perspective getRecordPerspective(String recordPerspectiveID) {
if (recordPerspectiveID == null)
throw new IllegalArgumentException("perspectiveID was null");
Perspective recordData = hashRecordPerspectives.get(recordPerspectiveID);
return recordData;
}
/**
* @param recordPerspectiveID
* @return True, if a {@link Perspective} with the specified ID is registered, false otherwise.
*/
public boolean containsRecordPerspective(String recordPerspectiveID) {
return hashRecordPerspectives.containsKey(recordPerspectiveID);
}
/**
* @param dimensionPerspectiveID
* @return True, if a {@link DimensionPerspective} with the specified ID is registered, false otherwise.
*/
public boolean containsDimensionPerspective(String dimensionPerspectiveID) {
return hashDimensionPerspectives.containsKey(dimensionPerspectiveID);
}
/**
* Register a new {@link Perspective} with this Table and trigger datadomain update.
*
* @param recordPerspective
*/
public void registerRecordPerspective(Perspective recordPerspective) {
registerRecordPerspective(recordPerspective, true);
}
/**
* Register a new {@link Perspective} with this Table
*
* @param recordPerspective
* @param flat
* determines whether a datadomain update event is triggered
*/
public void registerRecordPerspective(Perspective recordPerspective, boolean triggerUpdate) {
if (recordPerspective.getPerspectiveID() == null)
throw new IllegalStateException("Record perspective not correctly initiaklized: " + recordPerspective);
if (!recordPerspective.getIdType().equals(dataDomain.getRecordIDType()))
throw new IllegalStateException("Invalid reocrd id type for this datadomain: "
+ recordPerspective.getIdType());
hashRecordPerspectives.put(recordPerspective.getPerspectiveID(), recordPerspective);
if (recordPerspective.isDefault()) {
if (defaultRecordPerspective != null)
throw new IllegalStateException(
"The default record perspective is already set. It is not possible to have multiple defaults.");
defaultRecordPerspective = recordPerspective;
}
if (triggerUpdate) {
triggerUpdateEvent();
}
}
/**
* @param sampled
* Determines whether the full or the sampled default dimension perspective is requested
* @return the defaultDimensionPerspective, see {@link #defaultDimensionPerspective}
*/
public Perspective getDefaultDimensionPerspective(boolean sampled) {
if (sampled && sampledDimensionPerspective != null)
return sampledDimensionPerspective;
return defaultDimensionPerspective;
}
/**
* Returns a {@link DimensionPerspective} object for the specified ID. The {@link DimensionPerspective} provides
* access to all mutable data on how to access the Table, e.g., {@link VirtualArray}, {@link ClusterTree},
* {@link GroupList}, etc.
*
* @param dimensionPerspectiveID
* @return the associated {@link DimensionPerspective} object, or null if no such object is registered.
*/
public Perspective getDimensionPerspective(String dimensionPerspectiveID) {
if (dimensionPerspectiveID == null)
throw new IllegalArgumentException("perspectiveID was null");
Perspective dimensionPerspective = hashDimensionPerspectives.get(dimensionPerspectiveID);
return dimensionPerspective;
}
/**
* Register a new {@link DimensionPerspective} with this Table and trigger data domain update.
*
* @param dimensionPerspective
*/
public void registerDimensionPerspective(Perspective dimensionPerspective) {
registerDimensionPerspective(dimensionPerspective, true);
}
/**
* Register a new {@link DimensionPerspective} with this Table
*
* @param dimensionPerspective
* @param flat
* determines whether a datadomain update event is triggered
*/
public void registerDimensionPerspective(Perspective dimensionPerspective, boolean triggerUpdate) {
if (dimensionPerspective.getPerspectiveID() == null)
throw new IllegalStateException("Dimension perspective not correctly initiaklized: " + dimensionPerspective);
hashDimensionPerspectives.put(dimensionPerspective.getPerspectiveID(), dimensionPerspective);
if (dimensionPerspective.isDefault()) {
if (defaultDimensionPerspective != null)
throw new IllegalStateException(
"The default dimension perspective is already set. It is not possible to have multiple defaults.");
defaultDimensionPerspective = dimensionPerspective;
}
if (triggerUpdate) {
triggerUpdateEvent();
}
}
/**
* Return a list of content VA types that have registered {@link Perspective}.
*
* @return
*/
public Set<String> getRecordPerspectiveIDs() {
return hashRecordPerspectives.keySet();
}
/**
* Return a list of dimension VA types that have registered {@link DimensionPerspective}
*
* @return
*/
public Set<String> getDimensionPerspectiveIDs() {
return hashDimensionPerspectives.keySet();
}
/**
* Removes all data related to the set (Dimensions, Virtual Arrays and Sets) from the managers so that the garbage
* collector can handle it.
*/
public void destroy() {
}
@Override
public void finalize() throws Throwable {
Logger.log(new Status(IStatus.INFO, this.toString(), "Data table " + this + "destroyed"));
super.finalize();
}
@Override
public String toString() {
String message = "Inhomogeneous ";
if (this instanceof NumericalTable)
message = "Numerical ";
else if (this instanceof CategoricalTable)
message = "Categorical ";
return message + "table for " + dataSetDescription.getDataSetName() + "(" + size() + "," + depth() + ")";
}
/**
* Add a column to the table. An id is assigned to the column.
*
* @param column
* the column
* @return the ID assigned to the column
*/
public int addColumn(AColumn<?, ?> column) {
int id = columns.size();
column.setID(id);
columns.add(column);
defaultColumnIDs.add(column.getID());
return id;
}
/**
* Returns a description of the meta data of the element. Examples are {@link NumericalProperties} for numerical
* data and {@link CategoricalClassDescription} for categorical data.
*
* @param dimensionID
* @param recordID
* @return
*/
public Object getDataClassSpecificDescription(Integer dimensionID, Integer recordID) {
Integer columnID = recordID;
if (isColumnDimension)
columnID = dimensionID;
return columns.get(columnID).getDataClassSpecificDescription();
}
public Object getDataClassSpecificDescription(Integer dimensionID) {
return columns.get(dimensionID).getDataClassSpecificDescription();
}
/**
* @param defaultDataTransformation
* setter, see {@link defaultDataTransformation}
*/
public void setDefaultDataTransformation(String defaultDataTransformation) {
this.defaultDataTransformation = defaultDataTransformation;
}
/**
* @return the defaultDataTransformation, see {@link #defaultDataTransformation}
*/
public String getDefaultDataTransformation() {
return defaultDataTransformation;
}
// END OF PUBLIC INTERFACE
// Set creation is achieved by employing methods of SetUtils which utilizes
// package private methods in the
// table.
void createDefaultRecordPerspectives() {
List<Integer> recordIDs;
List<Integer> sampleIDs;
Integer nrRecordsInSample = null;
if (isColumnDimension) {
if (dataSetDescription.getDataProcessingDescription() != null) {
nrRecordsInSample = dataSetDescription.getDataProcessingDescription().getNrRowsInSample();
}
recordIDs = getRowIDList();
sampleIDs = getColumnIDList();
} else {
if (dataSetDescription.getDataProcessingDescription() != null) {
nrRecordsInSample = dataSetDescription.getDataProcessingDescription().getNrColumnsInSample();
}
recordIDs = getColumnIDList();
sampleIDs = getRowIDList();
}
defaultRecordPerspective = createDefaultRecordPerspective(false, recordIDs);
if (nrRecordsInSample != null) {
// recordIDs = sampleMostVariableRecords(nrRecordsInSample, recordIDs, sampleIDs);
// sampledRecordPerspective = createDefaultRecordPerspective(true, recordIDs);
throw new NotImplementedException();
}
triggerUpdateEvent();
}
private Perspective createDefaultRecordPerspective(boolean sampled, List<Integer> recordIDs) {
Perspective recordPerspective = new Perspective(dataDomain, dataDomain.getRecordIDType());
recordPerspective.setDefault(!sampled);
String label = sampled ? "Ungrouped Sampled" : "Ungrouped";
recordPerspective.setLabel(label, true);
PerspectiveInitializationData data = new PerspectiveInitializationData();
data.setData(recordIDs);
recordPerspective.init(data);
hashRecordPerspectives.put(recordPerspective.getPerspectiveID(), recordPerspective);
return recordPerspective;
}
private List<Integer> sampleMostVariableDimensions(int sampleSize, List<Integer> recordIDs,
List<Integer> dimensionIDs) {
if (dimensionIDs.size() <= sampleSize)
return dimensionIDs;
List<Pair<Double, Integer>> allDimVar = new ArrayList<Pair<Double, Integer>>();
for (Integer dimID : dimensionIDs) {
double[] allDimsPerRecordArray = new double[recordIDs.size()];
for (int i = 0; i < recordIDs.size(); i++) {
// allDimsPerRecordArray[i] = dataDomain.getNormalizedValue(dataDomain.getDimensionIDType(), dimID,
// dataDomain.getRecordIDType(), recordIDs.get(i));
allDimsPerRecordArray[i] = (Float) getRaw(dimID, recordIDs.get(i));
}
AdvancedDoubleStatistics stats = AdvancedDoubleStatistics.of(allDimsPerRecordArray);
// throwing out all values with more than 80% NAN
if (stats.getNaNs() < stats.getN() * NAN_THRESHOLD) {
allDimVar.add(new Pair<Double, Integer>(stats.getMedianAbsoluteDeviation(), dimID));
}
}
Collections.sort(allDimVar, Collections.reverseOrder(Pair.<Double> compareFirst()));
allDimVar = allDimVar.subList(0, sampleSize);
List<Integer> sampledDimensionIDs = new ArrayList<>();
for (Pair<Double, Integer> recordVar : allDimVar) {
sampledDimensionIDs.add(recordVar.getSecond());
}
return sampledDimensionIDs;
}
void createDefaultDimensionPerspectives() {
List<Integer> dimensionIDs;
List<Integer> recordIDs;
Integer nrDimensionsInSample = null;
if (isColumnDimension) {
if (dataSetDescription.getDataProcessingDescription() != null) {
nrDimensionsInSample = dataSetDescription.getDataProcessingDescription().getNrColumnsInSample();
}
dimensionIDs = getColumnIDList();
recordIDs = getRowIDList();
} else {
if (dataSetDescription.getDataProcessingDescription() != null) {
nrDimensionsInSample = dataSetDescription.getDataProcessingDescription().getNrRowsInSample();
}
dimensionIDs = getRowIDList();
recordIDs = getColumnIDList();
}
defaultDimensionPerspective = createDefaultDimensionPerspective(false, dimensionIDs);
if (nrDimensionsInSample != null) {
dimensionIDs = sampleMostVariableDimensions(nrDimensionsInSample, recordIDs, dimensionIDs);
sampledDimensionPerspective = createDefaultDimensionPerspective(true, dimensionIDs);
}
triggerUpdateEvent();
}
private Perspective createDefaultDimensionPerspective(boolean sampled, List<Integer> dimensionIDs) {
Perspective dimensionPerspective = new Perspective(dataDomain, dataDomain.getDimensionIDType());
dimensionPerspective.setDefault(!sampled);
String label = sampled ? "Ungrouped Sampled" : "Ungrouped";
dimensionPerspective.setLabel(label, true);
PerspectiveInitializationData data = new PerspectiveInitializationData();
data.setData(dimensionIDs);
dimensionPerspective.init(data);
hashDimensionPerspectives.put(dimensionPerspective.getPerspectiveID(), dimensionPerspective);
return dimensionPerspective;
}
private void triggerUpdateEvent() {
DataDomainUpdateEvent event = new DataDomainUpdateEvent(dataDomain);
event.setSender(this);
GeneralManager.get().getEventPublisher().triggerEvent(event);
}
/**
* Normalize all dimensions in the set, based solely on the values within each dimension. Operates with the raw data
* as basis by default, however when a logarithmized representation is in the dimension this is used.
*/
protected void normalize() {
for (AColumn<?, ?> dimension : columns) {
dimension.normalize();
}
}
/** Get the number of columns in the table */
protected int getNrColumns() {
return columns.size();
}
/** Get the number of rows in the table */
protected int getNrRows() {
return columns.iterator().next().size();
}
}
|
package cz.metacentrum.perun.openapi;
import cz.metacentrum.perun.openapi.invoker.ApiClient;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* Main Perun RPC client class. Uses ApiClient and model generated from OpenAPI description of Perun RPC API.
* The ApiClient pools HTTP connections and keeps cookies.
* Use it like this:
* <pre>
* PerunRPC perunRPC = new PerunRPC(PerunRPC.PERUN_URL_CESNET, user, password);
* try {
* Group group = perunRPC.getGroupsManager().getGroupById(1);
* } catch (HttpClientErrorException ex) {
* throw PerunException.to(ex);
* } catch (RestClientException ex) {
* log.error("connection problem",ex);
* }
* </pre>
* @author Martin Kuba makub@ics.muni.cz
*/
public class PerunRPC {
public static final String PERUN_URL_CESNET = "https://perun.cesnet.cz/krb/rpc";
public static final String PERUN_URL_ELIXIR = "https://perun.elixir-czech.cz/krb/rpc";
public static final String PERUN_URL_MUNI = "https://idm.ics.muni.cz/krb/rpc";
final private ApiClient apiClient;
final private AttributesManagerApi attributesManager;
final private AuthzResolverApi authzResolver;
final private DatabaseManagerApi databaseManager;
final private ExtSourcesManagerApi extSourcesManager;
final private FacilitiesManagerApi facilitiesManager;
final private GroupsManagerApi groupsManager;
final private MembersManagerApi membersManager;
final private OwnersManagerApi ownersManager;
final private RegistrarManagerApi registrarManager;
final private ResourcesManagerApi resourcesManager;
final private UsersManagerApi usersManager;
final private UtilsApi utils;
final private VosManagerApi vosManager;
final private ServicesManagerApi servicesManager;
public PerunRPC(RestTemplate restTemplate) {
if(restTemplate==null) {
restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
// set converters from HTTP response to Java objects
restTemplate.setMessageConverters(
List.of(
// register JSON response converter to find modules including JsonNullableModule
new MappingJackson2HttpMessageConverter(
Jackson2ObjectMapperBuilder.json().findModulesViaServiceLoader(true).build()),
// register String response converter
new StringHttpMessageConverter()
)
);
apiClient = new ApiClient(restTemplate);
apiClient.setUserAgent("Perun OpenAPI Java client");
//all the managers share the ApiClient and thus the connection pool and cookies
attributesManager = new AttributesManagerApi(apiClient);
authzResolver = new AuthzResolverApi(apiClient);
databaseManager = new DatabaseManagerApi(apiClient);
extSourcesManager = new ExtSourcesManagerApi(apiClient);
facilitiesManager = new FacilitiesManagerApi(apiClient);
groupsManager = new GroupsManagerApi(apiClient);
membersManager = new MembersManagerApi(apiClient);
ownersManager = new OwnersManagerApi(apiClient);
registrarManager = new RegistrarManagerApi(apiClient);
resourcesManager = new ResourcesManagerApi(apiClient);
usersManager = new UsersManagerApi(apiClient);
utils = new UtilsApi(apiClient);
vosManager = new VosManagerApi(apiClient);
servicesManager = new ServicesManagerApi(apiClient);
}
public PerunRPC() {
this(null);
}
public PerunRPC(String perunURL, String username, String password, RestTemplate restTemplate) {
this(restTemplate);
apiClient.setBasePath(perunURL);
apiClient.setUsername(username);
apiClient.setPassword(password);
}
public PerunRPC(String perunURL, String username, String password) {
this(perunURL, username, password, null);
}
public ApiClient getApiClient() {
return apiClient;
}
public AttributesManagerApi getAttributesManager() {
return attributesManager;
}
public AuthzResolverApi getAuthzResolver() {
return authzResolver;
}
public DatabaseManagerApi getDatabaseManager() {
return databaseManager;
}
public ExtSourcesManagerApi getExtSourcesManager() {
return extSourcesManager;
}
public FacilitiesManagerApi getFacilitiesManager() {
return facilitiesManager;
}
public GroupsManagerApi getGroupsManager() {
return groupsManager;
}
public MembersManagerApi getMembersManager() {
return membersManager;
}
public OwnersManagerApi getOwnersManager() {
return ownersManager;
}
public RegistrarManagerApi getRegistrarManager() {
return registrarManager;
}
public ResourcesManagerApi getResourcesManager() {
return resourcesManager;
}
public UsersManagerApi getUsersManager() {
return usersManager;
}
public UtilsApi getUtils() {
return utils;
}
public VosManagerApi getVosManager() {
return vosManager;
}
public ServicesManagerApi getServicesManager() {
return servicesManager;
}
}
|
package pipe.gui.widget;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GenerateResultsForm {
/**
* Maximum number of threads allowed
*/
private static final int MAX_THREADS = 100;
/**
* Error message if processing threads is incorrect
*/
private static final String THREADS_ERROR_MESSAGE =
"Error! Please enter a valid number of threads between 1-" + MAX_THREADS;
/**
* Action to perform when the go button is pressed
*/
private final GoAction goAction;
/**
* Panel containing number of threads and go button
*/
private JPanel generatePanel;
/**
* Number of threads text
*/
private JTextField numberOfThreadsText;
/**
* Load results button
*/
private JButton goButton;
/**
* Main panel containing the generate Panel
*/
private JPanel mainPanel;
public GenerateResultsForm(GoAction goAction) {
this.goAction = goAction;
goButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
go();
}
});
}
/**
* Attempts to start the specified procedure by gathering the number
* of threads to use. If it is not between 1 and MAX_THREADS then we display
* and error and do not perform the action
*/
private void go() {
try {
int threads = Integer.valueOf(numberOfThreadsText.getText());
if (threads < 1 || threads > MAX_THREADS) {
displayThreadErrorMessage();
return;
}
goAction.go(threads);
} catch (NumberFormatException e) {
displayThreadErrorMessage();
}
}
/**
* Displays an error message depicting that the number of threads
* entered does not conform to the expected values
*/
private void displayThreadErrorMessage() {
JOptionPane.showMessageDialog(mainPanel, THREADS_ERROR_MESSAGE, "GSPN Analysis Error",
JOptionPane.ERROR_MESSAGE);
}
/**
* @return panel to add to other GUI's
*/
public JPanel getPanel() {
return mainPanel;
}
/**
* Interface used to programmatically decide what happens when the generate
* button is pressed
*/
public interface GoAction {
void go(int threads);
}
}
|
package com.pkmmte.pkrss.downloader;
import android.content.Context;
import android.net.Uri;
import android.net.http.HttpResponseCache;
import android.util.Log;
import com.pkmmte.pkrss.Request;
import com.pkmmte.pkrss.Utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* The Default Downloader object used for general purposes.
* <p>
* This Downloader class uses Android's built-in HttpUrlConnection for
* networking. It is recommended to use the OkHttpDownloader instead as
* it is more stable and potentially performs better.
*/
public class DefaultDownloader extends Downloader {
// OkHttpClient & configuration
private final File cacheDir;
private final int cacheSize = 1024 * 1024;
private final int cacheMaxAge = 2 * 60 * 60;
private final long connectTimeout = 15000;
private final long readTimeout = 45000;
public DefaultDownloader(Context context) {
cacheDir = new File(context.getCacheDir(), "http");
try {
HttpResponseCache.install(cacheDir, cacheSize);
}
catch (IOException e) {
Log.i(TAG, "HTTP response cache installation failed:" + e);
}
}
@Override
public boolean clearCache() {
return Utils.deleteDir(cacheDir);
}
@Override
public String execute(Request request) throws IllegalArgumentException, IOException {
// Invalid URLs are a big no no
if (request.url == null || request.url.isEmpty()) {
throw new IllegalArgumentException("Invalid URL!");
}
// Start tracking download time
long time = System.currentTimeMillis();
// Empty response string placeholder
String responseStr;
// Handle cache
int maxCacheAge = request.skipCache ? 0 : cacheMaxAge;
// Build proper URL
String requestUrl = toUrl(request);
URL url = new URL(requestUrl);
// Open a connection and configure timeouts/cache
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cache-Control", "public, max-age=" + maxCacheAge);
connection.setConnectTimeout((int) connectTimeout);
connection.setReadTimeout((int) readTimeout);
// Execute the request and log its data
log("Making a request to " + requestUrl + (request.skipCache ? " [SKIP-CACHE]" : " [MAX-AGE " + maxCacheAge + "]"));
connection.connect();
// Read stream
InputStreamReader streamReader = null;
BufferedReader bufferedReader = null;
try {
streamReader = new InputStreamReader(url.openStream(), "UTF-8");
bufferedReader = new BufferedReader(streamReader);
StringBuilder sb = new StringBuilder();
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
sb.append(readLine);
}
responseStr = sb.toString();
log(TAG, "Request download took " + (System.currentTimeMillis() - time) + "ms", Log.INFO);
} catch (Exception e) {
log("Error executing/reading http request!", Log.ERROR);
e.printStackTrace();
throw new IOException(e.getMessage());
} finally {
if (bufferedReader != null)
bufferedReader.close();
if (streamReader != null)
streamReader.close();
connection.disconnect();
}
return responseStr;
}
@Override
public String toSafeUrl(Request request) {
// Copy base url
String url = request.url;
if (request.individual) {
// Append feed URL if individual article
url += "feed/?withoutcomments=1";
}
else if (request.search != null) {
// Append search query if available and not individual
url += "?s=" + Uri.encode(request.search);
}
// Return safe url
return url;
}
@Override
public String toUrl(Request request) {
// Copy base url
String url = request.url;
if (request.individual) {
// Handle individual urls differently
url += "feed/?withoutcomments=1";
}
else {
if (request.search != null)
url += "?s=" + Uri.encode(request.search);
if (request.page > 1)
url += (request.search == null ? "?paged=" : "&paged=") + String.valueOf(request.page);
}
// Return safe url
return url;
}
}
|
package com.intellij.find.actions;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.find.FindBundle;
import com.intellij.find.FindManager;
import com.intellij.find.FindSettings;
import com.intellij.find.findUsages.*;
import com.intellij.find.impl.FindManagerImpl;
import com.intellij.find.usages.SearchTarget;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.gotoByName.ModelDiff;
import com.intellij.internal.statistic.service.fus.collectors.UIEventId;
import com.intellij.internal.statistic.service.fus.collectors.UIEventLogger;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorLocation;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.impl.text.AsyncEditorLoader;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.IntRef;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.ui.*;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.AbstractPopup;
import com.intellij.ui.popup.PopupUpdateProcessor;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewBundle;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.usages.*;
import com.intellij.usages.impl.*;
import com.intellij.usages.rules.UsageFilteringRuleProvider;
import com.intellij.util.ArrayUtil;
import com.intellij.util.BitUtil;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.EdtScheduledExecutorService;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.AsyncProcessIcon;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static com.intellij.find.actions.ResolverKt.findShowUsages;
import static com.intellij.find.actions.ResolverKt.handlePsiOrSymbol;
import static com.intellij.find.actions.ShowUsagesActionHandler.getSecondInvocationTitle;
import static com.intellij.find.findUsages.FindUsagesHandlerFactory.OperationMode.USAGES_WITH_DEFAULT_OPTIONS;
public class ShowUsagesAction extends AnAction implements PopupAction, HintManagerImpl.ActionToIgnore {
public static final String ID = "ShowUsages";
public ShowUsagesAction() {
setInjectedContext(true);
}
private static final class UsageNodeComparator implements Comparator<UsageNode> {
private final ShowUsagesTable myTable;
private UsageNodeComparator(@NotNull ShowUsagesTable table) {
this.myTable = table;
}
@Override
public int compare(UsageNode c1, UsageNode c2) {
if (c1 instanceof StringNode || c2 instanceof StringNode) {
if (c1 instanceof StringNode && c2 instanceof StringNode) {
return Comparing.compare(c1.toString(), c2.toString());
}
return c1 instanceof StringNode ? 1 : -1;
}
Usage o1 = c1.getUsage();
Usage o2 = c2.getUsage();
int weight1 = o1 == myTable.USAGES_FILTERED_OUT_SEPARATOR ? 3 : o1 == myTable.USAGES_OUTSIDE_SCOPE_SEPARATOR ? 2 : o1 == myTable.MORE_USAGES_SEPARATOR ? 1 : 0;
int weight2 = o2 == myTable.USAGES_FILTERED_OUT_SEPARATOR ? 3 : o2 == myTable.USAGES_OUTSIDE_SCOPE_SEPARATOR ? 2 : o2 == myTable.MORE_USAGES_SEPARATOR ? 1 : 0;
if (weight1 != weight2) return weight1 - weight2;
if (o1 instanceof Comparable && o2 instanceof Comparable) {
//noinspection unchecked,rawtypes
return ((Comparable)o1).compareTo(o2);
}
VirtualFile v1 = UsageListCellRenderer.getVirtualFile(o1);
VirtualFile v2 = UsageListCellRenderer.getVirtualFile(o2);
String name1 = v1 == null ? null : v1.getName();
String name2 = v2 == null ? null : v2.getName();
int i = Comparing.compare(name1, name2);
if (i != 0) return i;
if (Comparing.equal(v1, v2)) {
FileEditorLocation loc1 = o1.getLocation();
FileEditorLocation loc2 = o2.getLocation();
return Comparing.compare(loc1, loc2);
}
else {
String path1 = v1 == null ? null : v1.getPath();
String path2 = v2 == null ? null : v2.getPath();
return Comparing.compare(path1, path2);
}
}
}
public static int getUsagesPageSize() {
return Math.max(1, Registry.intValue("ide.usages.page.size", 100));
}
@Override
public void update(@NotNull AnActionEvent e) {
FindUsagesInFileAction.updateFindUsagesAction(e);
if (e.getPresentation().isEnabled()) {
UsageTarget[] usageTargets = e.getData(UsageView.USAGE_TARGETS_KEY);
if (usageTargets != null && !(ArrayUtil.getFirstElement(usageTargets) instanceof PsiElementUsageTarget)) {
e.getPresentation().setEnabled(false);
}
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
ShowUsagesActionState state = getState(project);
Runnable continuation = state.continuation;
if (continuation != null) {
state.continuation = null;
hideHints(); // This action is invoked when the hint is showing because it implements HintManagerImpl.ActionToIgnore
continuation.run();
return;
}
RelativePoint popupPosition = JBPopupFactory.getInstance().guessBestPopupLocation(e.getDataContext());
PsiDocumentManager.getInstance(project).commitAllDocuments();
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.goto.usages");
if (Registry.is("ide.symbol.find.usages")) {
showSymbolUsages(project, e.getDataContext());
}
else {
showPsiUsages(project, e, popupPosition);
}
}
private static void showSymbolUsages(@NotNull Project project, @NotNull DataContext dataContext) {
Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
RelativePoint popupPosition = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext);
SearchScope searchScope = FindUsagesOptions.findScopeByName(project, dataContext, FindSettings.getInstance().getDefaultScopeName());
findShowUsages(
project, dataContext, FindBundle.message("show.usages.ambiguous.title"),
createVariantHandler(project, editor, popupPosition, searchScope)
);
}
@NotNull
private static UsageVariantHandler createVariantHandler(@NotNull Project project,
@Nullable Editor editor,
@NotNull RelativePoint popupPosition,
@NotNull SearchScope searchScope) {
return new UsageVariantHandler() {
@Override
public void handleTarget(@NotNull SearchTarget target) {
ShowTargetUsagesActionHandler.showUsages(
project, searchScope, target,
ShowUsagesParameters.initial(project, editor, popupPosition)
);
}
@Override
public void handlePsi(@NotNull PsiElement element) {
startFindUsages(element, popupPosition, editor);
}
};
}
/**
* Shows Usage popup for a single search target without disambiguation via Choose Target popup.
*/
@ApiStatus.Internal
public static void showUsages(@NotNull Project project, @NotNull DataContext dataContext, @NotNull SearchTarget target) {
RelativePoint popupPosition = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext);
showUsages(project, dataContext, popupPosition, target);
}
/**
* Shows Usage popup for a single search target without disambiguation via Choose Target popup.
*/
@ApiStatus.Internal
public static void showUsages(@NotNull Project project,
@NotNull DataContext dataContext,
@NotNull RelativePoint popupPosition,
@NotNull SearchTarget target) {
Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
SearchScope searchScope = FindUsagesOptions.findScopeByName(project, dataContext, FindSettings.getInstance().getDefaultScopeName());
UsageVariantHandler variantHandler = createVariantHandler(project, editor, popupPosition, searchScope);
handlePsiOrSymbol(variantHandler, target);
}
private static void showPsiUsages(@NotNull Project project, @NotNull AnActionEvent e, @NotNull RelativePoint popupPosition) {
UsageTarget[] usageTargets = e.getData(UsageView.USAGE_TARGETS_KEY);
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (usageTargets == null) {
FindUsagesAction.chooseAmbiguousTargetAndPerform(project, editor, element -> {
startFindUsages(element, popupPosition, editor);
return false;
});
}
else if (ArrayUtil.getFirstElement(usageTargets) instanceof PsiElementUsageTarget) {
PsiElement element = ((PsiElementUsageTarget)usageTargets[0]).getElement();
if (element != null) {
startFindUsages(element, popupPosition, editor);
}
}
}
private static void hideHints() {
HintManager.getInstance().hideHints(HintManager.HIDE_BY_ANY_KEY, false, false);
}
public static void startFindUsages(@NotNull PsiElement element, @NotNull RelativePoint popupPosition, @Nullable Editor editor) {
Project project = element.getProject();
FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
FindUsagesHandlerBase handler = findUsagesManager.getFindUsagesHandler(element, USAGES_WITH_DEFAULT_OPTIONS);
if (handler == null) return;
//noinspection deprecation
FindUsagesOptions options = handler.getFindUsagesOptions(DataManager.getInstance().getDataContext());
showElementUsages(ShowUsagesParameters.initial(project, editor, popupPosition), createActionHandler(handler, options));
}
private static void rulesChanged(@NotNull UsageViewImpl usageView, @NotNull PingEDT pingEDT, JBPopup popup) {
// later to make sure UsageViewImpl.rulesChanged was invoked
ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().executeOnPooledThread(() -> {
if ((popup == null || !popup.isDisposed()) && !usageView.isDisposed()) {
usageView.waitForUpdateRequestsCompletion();
if ((popup == null || !popup.isDisposed()) && !usageView.isDisposed()) {
pingEDT.ping();
}
}
}));
}
@NotNull
private static ShowUsagesActionHandler createActionHandler(@NotNull FindUsagesHandlerBase handler, @NotNull FindUsagesOptions options) {
// show super method warning dialogs before starting finding usages
PsiElement[] primaryElements = handler.getPrimaryElements();
PsiElement[] secondaryElements = handler.getSecondaryElements();
String searchString = FindBundle.message(
"find.usages.of.element.tab.name",
options.generateUsagesString(), UsageViewUtil.getLongName(handler.getPsiElement())
);
return new ShowUsagesActionHandler() {
@Override
public boolean isValid() {
return handler.getPsiElement().isValid();
}
@Override
public @NotNull UsageSearchPresentation getPresentation() {
return () -> searchString;
}
@Override
public @NotNull UsageSearcher createUsageSearcher() {
return FindUsagesManager.createUsageSearcher(handler, primaryElements, secondaryElements, options);
}
@Override
public @NotNull SearchScope getSelectedScope() {
return options.searchScope;
}
@Override
public @NotNull GlobalSearchScope getMaximalScope() {
return FindUsagesManager.getMaximalScope(handler);
}
@Override
public ShowUsagesActionHandler showDialog() {
FindUsagesOptions newOptions = ShowUsagesAction.showDialog(handler);
if (newOptions == null) {
return null;
}
else {
return createActionHandler(handler, newOptions);
}
}
@Override
public void findUsages() {
Project project = handler.getProject();
FindUsagesManager findUsagesManager = ((FindManagerImpl)FindManager.getInstance(project)).getFindUsagesManager();
findUsagesManager.findUsages(
handler.getPrimaryElements(), handler.getSecondaryElements(),
handler, options,
FindSettings.getInstance().isSkipResultsWithOneUsage()
);
}
@Override
public @NotNull ShowUsagesActionHandler withScope(@NotNull SearchScope searchScope) {
FindUsagesOptions newOptions = options.clone();
newOptions.searchScope = searchScope;
return createActionHandler(handler, newOptions);
}
};
}
static void showElementUsages(@NotNull ShowUsagesParameters parameters, @NotNull ShowUsagesActionHandler actionHandler) {
ApplicationManager.getApplication().assertIsDispatchThread();
Project project = parameters.project;
Editor editor = parameters.editor;
UsageViewImpl usageView = createUsageView(project);
if (editor != null) {
PsiReference reference = TargetElementUtil.findReference(editor);
if (reference != null) {
UsageInfo2UsageAdapter origin = new UsageInfo2UsageAdapter(new UsageInfo(reference));
usageView.setOriginUsage(origin);
}
}
final SearchScope searchScope = actionHandler.getSelectedScope();
final AtomicInteger outOfScopeUsages = new AtomicInteger();
ShowUsagesTable table = new ShowUsagesTable(new ShowUsagesTableCellRenderer(usageView, outOfScopeUsages, searchScope), usageView);
AsyncProcessIcon processIcon = new AsyncProcessIcon("xxx");
TitlePanel statusPanel = new TitlePanel();
statusPanel.add(processIcon, BorderLayout.EAST);
addUsageNodes(usageView.getRoot(), usageView, new ArrayList<>());
List<Usage> usages = new ArrayList<>();
Set<Usage> visibleUsages = new LinkedHashSet<>();
table.setTableModel(new SmartList<>(createStringNode(UsageViewBundle.message("progress.searching"))));
Runnable itemChosenCallback = table.prepareTable(
showMoreUsagesRunnable(parameters, actionHandler),
showUsagesInMaximalScopeRunnable(parameters, actionHandler)
);
JBPopup popup = createUsagePopup(
usageView, table, itemChosenCallback, statusPanel,
parameters, actionHandler
);
ProgressIndicator indicator = new ProgressIndicatorBase();
if (!popup.isDisposed()) {
Disposer.register(popup, usageView);
Disposer.register(popup, indicator::cancel);
// show popup only if find usages takes more than 300ms, otherwise it would flicker needlessly
EdtScheduledExecutorService.getInstance().schedule(() -> {
if (!usageView.isDisposed()) {
showPopupIfNeedTo(popup, parameters.popupPosition);
}
}, 300, TimeUnit.MILLISECONDS);
}
UsageNode USAGES_OUTSIDE_SCOPE_NODE = new UsageNode(null, table.USAGES_OUTSIDE_SCOPE_SEPARATOR);
UsageNode MORE_USAGES_SEPARATOR_NODE = new UsageNode(null, table.MORE_USAGES_SEPARATOR);
PingEDT pingEDT = new PingEDT("Rebuild popup in EDT", () -> popup.isDisposed(), 100, () -> {
if (popup.isDisposed()) return;
List<UsageNode> nodes = new ArrayList<>(usages.size());
List<Usage> copy;
synchronized (usages) {
// open up popup as soon as the first usage has been found
if (!popup.isVisible() && (usages.isEmpty() || !showPopupIfNeedTo(popup, parameters.popupPosition))) {
return;
}
addUsageNodes(usageView.getRoot(), usageView, nodes);
copy = new ArrayList<>(usages);
}
boolean shouldShowMoreSeparator = copy.contains(table.MORE_USAGES_SEPARATOR);
if (shouldShowMoreSeparator) {
nodes.add(MORE_USAGES_SEPARATOR_NODE);
}
boolean hasOutsideScopeUsages = copy.contains(table.USAGES_OUTSIDE_SCOPE_SEPARATOR);
if (hasOutsideScopeUsages && !shouldShowMoreSeparator) {
nodes.add(USAGES_OUTSIDE_SCOPE_NODE);
}
List<UsageNode> data = new ArrayList<>(nodes);
int filteredOutCount = getFilteredOutNodeCount(copy, usageView);
if (filteredOutCount != 0) {
DefaultActionGroup filteringActions = popup.getUserData(DefaultActionGroup.class);
if (filteringActions == null) return;
List<ToggleAction> unselectedActions = Arrays.stream(filteringActions.getChildren(null))
.filter(action -> action instanceof ToggleAction)
.map(action -> (ToggleAction)action)
.filter(ta -> !ta.isSelected(fakeEvent(ta)))
.filter(ta -> !StringUtil.isEmpty(ta.getTemplatePresentation().getText()))
.collect(Collectors.toList());
data.add(new FilteredOutUsagesNode(table.USAGES_FILTERED_OUT_SEPARATOR,
UsageViewBundle.message("usages.were.filtered.out", filteredOutCount),
UsageViewBundle.message("usages.were.filtered.out.tooltip")) {
@Override
public void onSelected() {
// toggle back unselected toggle actions
toggleFilters(unselectedActions);
// and restart show usages in hope it will show filtered out items now
showElementUsages(parameters, actionHandler);
}
});
}
data.sort(new UsageNodeComparator(table));
boolean hasMore = shouldShowMoreSeparator || hasOutsideScopeUsages;
int totalCount = copy.size();
int visibleCount = totalCount - filteredOutCount;
statusPanel.setText(getStatusString(!processIcon.isDisposed(), hasMore, visibleCount, totalCount));
rebuildTable(usageView, data, table, popup, parameters.popupPosition, parameters.minWidth);
});
MessageBusConnection messageBusConnection = project.getMessageBus().connect(usageView);
messageBusConnection.subscribe(UsageFilteringRuleProvider.RULES_CHANGED, () -> rulesChanged(usageView, pingEDT, popup));
Processor<Usage> collect = usage -> {
if (!UsageViewManagerImpl.isInScope(usage, searchScope)) {
if (outOfScopeUsages.getAndIncrement() == 0) {
visibleUsages.add(USAGES_OUTSIDE_SCOPE_NODE.getUsage());
usages.add(table.USAGES_OUTSIDE_SCOPE_SEPARATOR);
}
return true;
}
synchronized (usages) {
if (visibleUsages.size() >= parameters.maxUsages) return false;
UsageNode nodes = ReadAction.compute(() -> usageView.doAppendUsage(usage));
usages.add(usage);
if (nodes != null) {
visibleUsages.add(nodes.getUsage());
boolean continueSearch = true;
if (visibleUsages.size() == parameters.maxUsages) {
visibleUsages.add(MORE_USAGES_SEPARATOR_NODE.getUsage());
usages.add(table.MORE_USAGES_SEPARATOR);
continueSearch = false;
}
pingEDT.ping();
return continueSearch;
}
}
return true;
};
UsageSearcher usageSearcher = actionHandler.createUsageSearcher();
FindUsagesManager.startProcessUsages(indicator, project, usageSearcher, collect, () -> ApplicationManager.getApplication().invokeLater(
() -> {
Disposer.dispose(processIcon);
Container parent = processIcon.getParent();
if (parent != null) {
parent.remove(processIcon);
parent.repaint();
}
pingEDT.ping(); // repaint status
synchronized (usages) {
if (visibleUsages.isEmpty()) {
if (usages.isEmpty()) {
String hint = UsageViewBundle.message("no.usages.found.in", searchScope.getDisplayName());
hint(false, hint, parameters, actionHandler);
cancel(popup);
}
// else all usages filtered out
}
else if (visibleUsages.size() == 1) {
if (usages.size() == 1) {
//the only usage
Usage usage = visibleUsages.iterator().next();
if (usage == table.USAGES_OUTSIDE_SCOPE_SEPARATOR) {
String hint = UsageViewManagerImpl.outOfScopeMessage(outOfScopeUsages.get(), searchScope);
hint(true, hint, parameters, actionHandler);
}
else {
String hint = UsageViewBundle.message("show.usages.only.usage", searchScope.getDisplayName());
navigateAndHint(usage, hint, parameters, actionHandler);
}
cancel(popup);
}
else {
assert usages.size() > 1 : usages;
// usage view can filter usages down to one
Usage visibleUsage = visibleUsages.iterator().next();
if (areAllUsagesInOneLine(visibleUsage, usages)) {
String hint = UsageViewBundle.message("all.usages.are.in.this.line", usages.size(), searchScope.getDisplayName());
navigateAndHint(visibleUsage, hint, parameters, actionHandler);
cancel(popup);
}
}
}
}
},
project.getDisposed()
));
}
private static void toggleFilters(@NotNull List<? extends ToggleAction> unselectedActions) {
for (ToggleAction action : unselectedActions) {
action.actionPerformed(fakeEvent(action));
}
}
private static @NotNull AnActionEvent fakeEvent(@NotNull ToggleAction action) {
return new AnActionEvent(
null, DataContext.EMPTY_CONTEXT, "",
action.getTemplatePresentation(), ActionManager.getInstance(), 0
);
}
@NotNull
private static UsageViewImpl createUsageView(@NotNull Project project) {
UsageViewPresentation usageViewPresentation = new UsageViewPresentation();
usageViewPresentation.setDetachedMode(true);
return new UsageViewImpl(project, usageViewPresentation, UsageTarget.EMPTY_ARRAY, null) {
@Override
public @NotNull UsageViewSettings getUsageViewSettings() {
return ShowUsagesSettings.getInstance().getState();
}
};
}
@NotNull
static UsageNode createStringNode(@NotNull Object string) {
return new StringNode(string);
}
private static boolean showPopupIfNeedTo(@NotNull JBPopup popup, @NotNull RelativePoint popupPosition) {
if (!popup.isDisposed() && !popup.isVisible()) {
popup.show(popupPosition);
return true;
}
return false;
}
@NotNull
private static JComponent createHintComponent(@NotNull String secondInvocationTitle, boolean isWarning, @NotNull JComponent button) {
JComponent label = HintUtil.createInformationLabel(secondInvocationTitle);
if (isWarning) {
label.setBackground(MessageType.WARNING.getPopupBackground());
}
JPanel panel = new JPanel(new BorderLayout());
button.setBackground(label.getBackground());
panel.setBackground(label.getBackground());
label.setOpaque(false);
label.setBorder(null);
panel.setBorder(HintUtil.createHintBorder());
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.EAST);
return panel;
}
@NotNull
private static InplaceButton createSettingsButton(@NotNull Project project,
@NotNull Runnable cancelAction,
@NotNull Runnable showDialogAndFindUsagesRunnable) {
String shortcutText = "";
KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut();
if (shortcut != null) {
shortcutText = "(" + KeymapUtil.getShortcutText(shortcut) + ")";
}
return new InplaceButton("Settings..." + shortcutText, AllIcons.General.Settings, __ -> {
ApplicationManager.getApplication().invokeLater(showDialogAndFindUsagesRunnable, project.getDisposed());
cancelAction.run();
});
}
private static @Nullable FindUsagesOptions showDialog(@NotNull FindUsagesHandlerBase handler) {
UIEventLogger.logUIEvent(UIEventId.ShowUsagesPopupShowSettings);
AbstractFindUsagesDialog dialog;
if (handler instanceof FindUsagesHandlerUi) {
dialog = ((FindUsagesHandlerUi)handler).getFindUsagesDialog(false, false, false);
}
else {
dialog = FindUsagesHandler.createDefaultFindUsagesDialog(false, false, false, handler);
}
if (dialog.showAndGet()) {
dialog.calcFindUsagesOptions();
//noinspection deprecation
return handler.getFindUsagesOptions(DataManager.getInstance().getDataContext());
}
else {
return null;
}
}
@NotNull
private static JBPopup createUsagePopup(@NotNull UsageViewImpl usageView,
@NotNull JTable table,
@NotNull Runnable itemChoseCallback,
@NotNull TitlePanel statusPanel,
@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
ApplicationManager.getApplication().assertIsDispatchThread();
Project project = parameters.project;
PopupChooserBuilder<?> builder = JBPopupFactory.getInstance().createPopupChooserBuilder(table);
String title = UsageViewBundle.message(
"search.title.0.in.1",
actionHandler.getPresentation().getSearchString(),
actionHandler.getSelectedScope().getDisplayName()
);
builder.setTitle(XmlStringUtil.wrapInHtml("<body><nobr>" + StringUtil.escapeXmlEntities(title) + "</nobr></body>"));
builder.setAdText(getSecondInvocationTitle(actionHandler));
builder.setMovable(true).setResizable(true);
builder.setItemChoosenCallback(itemChoseCallback);
JBPopup[] popup = new JBPopup[1];
KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut();
if (shortcut != null) {
new DumbAwareAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
cancel(popup[0]);
showDialogAndRestart(parameters, actionHandler);
}
}.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
}
shortcut = getShowUsagesShortcut();
if (shortcut != null) {
new DumbAwareAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
cancel(popup[0]);
showUsagesInMaximalScope(parameters, actionHandler);
}
}.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
}
InplaceButton settingsButton = createSettingsButton(
project, () -> cancel(popup[0]),
showDialogAndRestartRunnable(parameters, actionHandler)
);
ActiveComponent statusComponent = new ActiveComponent() {
@Override
public void setActive(boolean active) {
statusPanel.setActive(active);
}
@NotNull
@Override
public JComponent getComponent() {
return statusPanel;
}
};
DefaultActionGroup pinGroup = new DefaultActionGroup();
ActiveComponent pin = createPinButton(project, popup, pinGroup, actionHandler::findUsages);
builder.setCommandButton(new CompositeActiveComponent(statusComponent, settingsButton, pin));
DefaultActionGroup toolbar = new DefaultActionGroup();
usageView.addFilteringActions(toolbar);
toolbar.add(UsageGroupingRuleProviderImpl.createGroupByFileStructureAction(usageView));
ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, toolbar, true);
actionToolbar.setTargetComponent(table);
actionToolbar.setReservePlaceAutoPopupIcon(false);
JComponent toolBar = actionToolbar.getComponent();
toolBar.setOpaque(false);
builder.setSettingButton(toolBar);
builder.setCancelKeyEnabled(false);
PopupUpdateProcessor processor = new PopupUpdateProcessor(usageView.getProject()) {
@Override
public void updatePopup(Object lookupItemObject) {/*not used*/}
};
builder.addListener(processor);
popup[0] = builder.createPopup();
JComponent content = popup[0].getContent();
String fullTitle = title + getStatusString(true, false, 0, 0);
int approxWidth = (int)(toolBar.getPreferredSize().getWidth()
+ new JLabel(fullTitle).getPreferredSize().getWidth()
+ settingsButton.getPreferredSize().getWidth());
IntRef minWidth = parameters.minWidth;
minWidth.set(Math.max(minWidth.get(), approxWidth));
for (AnAction action : toolbar.getChildren(null)) {
action.unregisterCustomShortcutSet(usageView.getComponent());
action.registerCustomShortcutSet(action.getShortcutSet(), content);
}
for (AnAction action : pinGroup.getChildren(null)) {
action.unregisterCustomShortcutSet(usageView.getComponent());
action.registerCustomShortcutSet(action.getShortcutSet(), content);
}
/* save toolbar actions for using later, in automatic filter toggling in {@link #restartShowUsagesWithFiltersToggled(List} */
popup[0].setUserData(Collections.singletonList(toolbar));
return popup[0];
}
@NotNull
private static ActiveComponent createPinButton(@NotNull Project project,
JBPopup @NotNull [] popup,
@NotNull DefaultActionGroup pinGroup,
@NotNull Runnable findUsagesRunnable) {
Icon icon = ToolWindowManager.getInstance(project).getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab);
AnAction pinAction =
new AnAction(IdeBundle.messagePointer("show.in.find.window.button.name"),
IdeBundle.messagePointer("show.in.find.window.button.pin.description"), icon) {
{
AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_USAGES);
setShortcutSet(action.getShortcutSet());
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
hideHints();
cancel(popup[0]);
findUsagesRunnable.run();
}
};
pinGroup.add(pinAction);
ActionToolbar pinToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, pinGroup, true);
pinToolbar.setReservePlaceAutoPopupIcon(false);
JComponent pinToolBar = pinToolbar.getComponent();
pinToolBar.setBorder(null);
pinToolBar.setOpaque(false);
return new ActiveComponent.Adapter() {
@NotNull
@Override
public JComponent getComponent() {
return pinToolBar;
}
};
}
private static void cancel(@Nullable JBPopup popup) {
if (popup != null) {
popup.cancel();
}
}
private static @NotNull String getStatusString(boolean findUsagesInProgress, boolean hasMore, int visibleCount, int totalCount) {
if (findUsagesInProgress || hasMore) {
return UsageViewBundle.message("showing.0.usages", visibleCount - (hasMore ? 1 : 0));
}
else if (visibleCount != totalCount) {
return UsageViewBundle.message("showing.0.of.1.usages", visibleCount, totalCount);
}
else {
return UsageViewBundle.message("found.0.usages", totalCount);
}
}
@NotNull
private static String suggestSecondInvocation(@NotNull String text, @Nullable String title) {
if (title != null) {
text += "<br><small>" + title + "</small>";
}
return XmlStringUtil.wrapInHtml(UIUtil.convertSpace2Nbsp(text));
}
@Nullable
static KeyboardShortcut getShowUsagesShortcut() {
return ActionManager.getInstance().getKeyboardShortcut(ID);
}
private static int getFilteredOutNodeCount(@NotNull List<? extends Usage> usages, @NotNull UsageViewImpl usageView) {
return (int)usages.stream().filter(usage -> !usageView.isVisible(usage)).count();
}
private static int getUsageOffset(@NotNull Usage usage) {
if (!(usage instanceof UsageInfo2UsageAdapter)) return -1;
PsiElement element = ((UsageInfo2UsageAdapter)usage).getElement();
if (element == null) return -1;
return element.getTextRange().getStartOffset();
}
private static boolean areAllUsagesInOneLine(@NotNull Usage visibleUsage, @NotNull List<? extends Usage> usages) {
Editor editor = getEditorFor(visibleUsage);
if (editor == null) return false;
int offset = getUsageOffset(visibleUsage);
if (offset == -1) return false;
int lineNumber = editor.getDocument().getLineNumber(offset);
for (Usage other : usages) {
Editor otherEditor = getEditorFor(other);
if (otherEditor != editor) return false;
int otherOffset = getUsageOffset(other);
if (otherOffset == -1) return false;
int otherLine = otherEditor.getDocument().getLineNumber(otherOffset);
if (otherLine != lineNumber) return false;
}
return true;
}
private static int calcMaxWidth(@NotNull JTable table) {
int colsNum = table.getColumnModel().getColumnCount();
int totalWidth = 0;
for (int col = 0; col < colsNum - 1; col++) {
TableColumn column = table.getColumnModel().getColumn(col);
int preferred = column.getPreferredWidth();
int width = Math.max(preferred, columnMaxWidth(table, col));
totalWidth += width;
column.setMinWidth(width);
column.setMaxWidth(width);
column.setWidth(width);
column.setPreferredWidth(width);
}
totalWidth += columnMaxWidth(table, colsNum - 1);
return totalWidth;
}
private static int columnMaxWidth(@NotNull JTable table, int col) {
TableColumn column = table.getColumnModel().getColumn(col);
int width = 0;
for (int row = 0; row < table.getRowCount(); row++) {
Component component = table.prepareRenderer(column.getCellRenderer(), row, col);
int rendererWidth = component.getPreferredSize().width;
width = Math.max(width, rendererWidth + table.getIntercellSpacing().width);
}
return width;
}
private static void rebuildTable(@NotNull UsageViewImpl usageView,
@NotNull List<UsageNode> data,
@NotNull ShowUsagesTable table,
@Nullable JBPopup popup,
@NotNull RelativePoint popupPosition,
@NotNull IntRef minWidth) {
ApplicationManager.getApplication().assertIsDispatchThread();
ShowUsagesTable.MyModel tableModel = table.setTableModel(data);
List<UsageNode> existingData = tableModel.getItems();
int row = table.getSelectedRow();
int newSelection = updateModel(tableModel, existingData, data, row == -1 ? 0 : row);
if (newSelection < 0 || newSelection >= tableModel.getRowCount()) {
ScrollingUtil.ensureSelectionExists(table);
newSelection = table.getSelectedRow();
}
else {
// do not pre-select the usage under caret by default
if (newSelection == 0 && table.getModel().getRowCount() > 1) {
Object valueInTopRow = table.getModel().getValueAt(0, 0);
if (valueInTopRow instanceof UsageNode && usageView.isOriginUsage(((UsageNode)valueInTopRow).getUsage())) {
newSelection++;
}
}
table.getSelectionModel().setSelectionInterval(newSelection, newSelection);
}
ScrollingUtil.ensureIndexIsVisible(table, newSelection, 0);
if (popup != null) {
setSizeAndDimensions(table, popup, popupPosition, minWidth, data);
}
}
// returns new selection
private static int updateModel(@NotNull ShowUsagesTable.MyModel tableModel,
@NotNull List<? extends UsageNode> listOld,
@NotNull List<? extends UsageNode> listNew,
int oldSelection) {
UsageNode[] oa = listOld.toArray(new UsageNode[0]);
UsageNode[] na = listNew.toArray(new UsageNode[0]);
List<ModelDiff.Cmd> cmds = ModelDiff.createDiffCmds(tableModel, oa, na);
int selection = oldSelection;
if (cmds != null) {
for (ModelDiff.Cmd cmd : cmds) {
selection = cmd.translateSelection(selection);
cmd.apply();
}
}
return selection;
}
private static void setSizeAndDimensions(@NotNull JTable table,
@NotNull JBPopup popup,
@NotNull RelativePoint popupPosition,
@NotNull IntRef minWidth,
@NotNull List<? extends UsageNode> data) {
if (isCodeWithMeClientInstance(popup)) return;
JComponent content = popup.getContent();
Window window = SwingUtilities.windowForComponent(content);
Dimension d = window.getSize();
int width = calcMaxWidth(table);
width = (int)Math.max(d.getWidth(), width);
Dimension headerSize = ((AbstractPopup)popup).getHeaderPreferredSize();
width = Math.max((int)headerSize.getWidth(), width);
width = Math.max(minWidth.get(), width);
int delta = minWidth.get() == -1 ? 0 : width - minWidth.get();
int newWidth = Math.max(width, d.width + delta);
minWidth.set(newWidth);
Dimension footerSize = ((AbstractPopup)popup).getFooterPreferredSize();
int footer = footerSize.height;
int footerBorder = footer == 0 ? 0 : 1;
Insets insets = ((AbstractPopup)popup).getPopupBorder().getBorderInsets(content);
int minHeight = headerSize.height + footer + footerBorder + insets.top + insets.bottom;
Rectangle rectangle = getPreferredBounds(table, popupPosition.getScreenPoint(), newWidth, minHeight, data.size());
table.setSize(rectangle.width, rectangle.height - minHeight);
if (!data.isEmpty()) ScrollingUtil.ensureSelectionExists(table);
Dimension newDim = rectangle.getSize();
window.setBounds(rectangle);
window.setMinimumSize(newDim);
window.setMaximumSize(newDim);
window.validate();
window.repaint();
}
private static boolean isCodeWithMeClientInstance(@NotNull JBPopup popup) {
JComponent content = popup.getContent();
return content.getClientProperty("THIN_CLIENT") != null;
}
@NotNull
private static Rectangle getPreferredBounds(@NotNull JTable table, @NotNull Point point, int width, int minHeight, int modelRows) {
boolean addExtraSpace = Registry.is("ide.preferred.scrollable.viewport.extra.space");
int visibleRows = Math.min(30, modelRows);
int rowHeight = table.getRowHeight();
int space = addExtraSpace && visibleRows < modelRows ? rowHeight / 2 : 0;
int height = visibleRows * rowHeight + minHeight + space;
Rectangle bounds = new Rectangle(point.x, point.y, width, height);
ScreenUtil.fitToScreen(bounds);
if (bounds.height != height) {
minHeight += addExtraSpace && space == 0 ? rowHeight / 2 : space;
bounds.height = Math.max(1, (bounds.height - minHeight) / rowHeight) * rowHeight + minHeight;
}
return bounds;
}
private static void addUsageNodes(@NotNull GroupNode root, @NotNull UsageViewImpl usageView, @NotNull List<? super UsageNode> outNodes) {
for (UsageNode node : root.getUsageNodes()) {
Usage usage = node.getUsage();
if (usageView.isVisible(usage)) {
node.setParent(root);
outNodes.add(node);
}
}
for (GroupNode groupNode : root.getSubGroups()) {
groupNode.setParent(root);
addUsageNodes(groupNode, usageView, outNodes);
}
}
private static void navigateAndHint(@NotNull Usage usage,
@NotNull String hint,
@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
usage.navigate(true);
Editor newEditor = getEditorFor(usage);
if (newEditor == null) return;
hint(false, hint, parameters.withEditor(newEditor), actionHandler);
}
private static void hint(boolean isWarning,
@NotNull String hint,
@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
Project project = parameters.project;
Editor editor = parameters.editor;
Runnable runnable = () -> {
if (!actionHandler.isValid()) {
return;
}
JComponent label = createHintComponent(
suggestSecondInvocation(hint, getSecondInvocationTitle(actionHandler)),
isWarning,
createSettingsButton(
project,
ShowUsagesAction::hideHints,
showDialogAndRestartRunnable(parameters, actionHandler)
)
);
ShowUsagesActionState state = getState(project);
state.continuation = showUsagesInMaximalScopeRunnable(parameters, actionHandler);
runWhenHidden(label, () -> state.continuation = null);
if (editor == null || editor.isDisposed() || !editor.getComponent().isShowing()) {
int flags = HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING;
HintManager.getInstance().showHint(label, parameters.popupPosition, flags, 0);
}
else {
HintManager.getInstance().showInformationHint(editor, label);
}
};
if (editor == null) {
//opening editor is performing in invokeLater
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(() -> {
// after new editor created, some editor resizing events are still bubbling. To prevent hiding hint, invokeLater this
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(runnable);
});
}
else {
//opening editor is performing in invokeLater
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(
() -> editor.getScrollingModel().runActionOnScrollingFinished(
() -> {
// after new editor created, some editor resizing events are still bubbling. To prevent hiding hint, invokeLater this
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(
() -> AsyncEditorLoader.performWhenLoaded(editor, runnable)
);
})
);
}
}
@Nullable
private static Editor getEditorFor(@NotNull Usage usage) {
FileEditorLocation location = usage.getLocation();
FileEditor newFileEditor = location == null ? null : location.getEditor();
return newFileEditor instanceof TextEditor ? ((TextEditor)newFileEditor).getEditor() : null;
}
static final class StringNode extends UsageNode {
@NotNull private final Object myString;
private StringNode(@NotNull Object string) {
super(null, NullUsage.INSTANCE);
myString = string;
}
@Override
public String toString() {
return myString.toString();
}
}
static abstract class FilteredOutUsagesNode extends UsageNode {
@NotNull private final String myString;
private final String myToolTip;
private FilteredOutUsagesNode(@NotNull Usage fakeUsage, @NotNull String string, @NotNull String toolTip) {
super(null, fakeUsage);
myString = string;
myToolTip = toolTip;
}
@Override
public String toString() {
return myString;
}
@NotNull
public String getTooltip() {
return myToolTip;
}
public abstract void onSelected();
}
private static @NotNull Runnable showMoreUsagesRunnable(@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
return () -> showElementUsages(parameters.moreUsages(), actionHandler);
}
private static @NotNull Runnable showUsagesInMaximalScopeRunnable(@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
return () -> showUsagesInMaximalScope(parameters, actionHandler);
}
private static void showUsagesInMaximalScope(@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
showElementUsages(parameters, actionHandler.withScope(actionHandler.getMaximalScope()));
}
private static @NotNull Runnable showDialogAndRestartRunnable(@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
return () -> showDialogAndRestart(parameters, actionHandler);
}
private static void showDialogAndRestart(@NotNull ShowUsagesParameters parameters,
@NotNull ShowUsagesActionHandler actionHandler) {
ShowUsagesActionHandler newActionHandler = actionHandler.showDialog();
if (newActionHandler != null) {
showElementUsages(parameters, newActionHandler);
}
}
@Service
private static final class ShowUsagesActionState {
Runnable continuation;
}
@NotNull
private static ShowUsagesActionState getState(@NotNull Project project) {
return ServiceManager.getService(project, ShowUsagesActionState.class);
}
private static void runWhenHidden(@NotNull Component c, @NotNull Runnable r) {
c.addHierarchyListener(runWhenHidden(r));
}
@NotNull
private static HierarchyListener runWhenHidden(@NotNull Runnable r) {
return new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if (!BitUtil.isSet(e.getChangeFlags(), HierarchyEvent.DISPLAYABILITY_CHANGED)) {
return;
}
Component component = e.getComponent();
if (component.isDisplayable()) {
return;
}
r.run();
component.removeHierarchyListener(this);
}
};
}
/**
* @deprecated please use {@link #startFindUsages(PsiElement, RelativePoint, Editor)} overload
*/
@Deprecated
@ScheduledForRemoval(inVersion = "2020.3")
public void startFindUsages(@NotNull PsiElement element,
@NotNull RelativePoint popupPosition,
@Nullable Editor editor,
int maxUsages) {
startFindUsages(element, popupPosition, editor);
}
}
|
package com.intellij.ui.javafx;
import com.intellij.util.FieldAccessor;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.sun.javafx.embed.EmbeddedSceneInterface;
import com.sun.javafx.tk.TKScene;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import java.awt.*;
public class JFXPanelWrapper extends JFXPanel {
private static final FieldAccessor<JFXPanel, Integer> myScaleFactorAccessor = new FieldAccessor<>(JFXPanel.class, "scaleFactor");
public JFXPanelWrapper() {
Platform.setImplicitExit(false);
}
/**
* This override fixes the situation of using multiple JFXPanels
* with jbtabs/splitters when some of them are not showing.
* On getMinimumSize there is no layout manager nor peer so
* the result could be #size() which is incorrect.
* @return zero size
*/
@Override
public Dimension getMinimumSize() {
return new Dimension(0, 0);
}
@Override
public void addNotify() {
// todo: remove it when IDEA finally switches to JFX10
if (myScaleFactorAccessor.isAvailable()) {
if (UIUtil.isJreHiDPIEnabled()) {
// JFXPanel is scaled asynchronously after first repaint, what may lead
// to showing unscaled content. To work it around, set "scaleFactor" ahead.
int scale = Math.round(JBUI.sysScale(this));
myScaleFactorAccessor.set(this, scale);
Scene scene = getScene();
// If scene is null then it will be set later and super.setEmbeddedScene(..) will init its scale properly,
// otherwise explicitly set scene scale to match JFXPanel.scaleFactor.
if (scene != null) {
TKScene tks = scene.impl_getPeer();
if (tks instanceof EmbeddedSceneInterface) {
((EmbeddedSceneInterface)tks).setPixelScaleFactor(scale);
}
}
}
}
// change scale factor before component will be resized in super
super.addNotify();
}
}
|
package org.bouncycastle.tls;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import org.bouncycastle.tls.crypto.TlsCrypto;
import org.bouncycastle.tls.crypto.TlsHash;
import org.bouncycastle.tls.crypto.TlsSecret;
import org.bouncycastle.tls.crypto.TlsStreamSigner;
import org.bouncycastle.tls.crypto.TlsStreamVerifier;
import org.bouncycastle.tls.crypto.TlsVerifier;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.io.Streams;
/**
* Some helper functions for the TLS API.
*/
public class TlsUtils
{
public static final byte[] EMPTY_BYTES = new byte[0];
public static final short[] EMPTY_SHORTS = new short[0];
public static final int[] EMPTY_INTS = new int[0];
public static final long[] EMPTY_LONGS = new long[0];
public static final Integer EXT_signature_algorithms = Integers.valueOf(ExtensionType.signature_algorithms);
protected static short MINIMUM_HASH_STRICT = HashAlgorithm.sha1;
protected static short MINIMUM_HASH_PREFERRED = HashAlgorithm.sha256;
public static void checkUint8(short i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint8(int i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint8(long i) throws IOException
{
if (!isValidUint8(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint16(int i) throws IOException
{
if (!isValidUint16(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint16(long i) throws IOException
{
if (!isValidUint16(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint24(int i) throws IOException
{
if (!isValidUint24(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint24(long i) throws IOException
{
if (!isValidUint24(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint32(long i) throws IOException
{
if (!isValidUint32(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint48(long i) throws IOException
{
if (!isValidUint48(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static void checkUint64(long i) throws IOException
{
if (!isValidUint64(i))
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
public static boolean isValidUint8(short i)
{
return (i & 0xFF) == i;
}
public static boolean isValidUint8(int i)
{
return (i & 0xFF) == i;
}
public static boolean isValidUint8(long i)
{
return (i & 0xFFL) == i;
}
public static boolean isValidUint16(int i)
{
return (i & 0xFFFF) == i;
}
public static boolean isValidUint16(long i)
{
return (i & 0xFFFFL) == i;
}
public static boolean isValidUint24(int i)
{
return (i & 0xFFFFFF) == i;
}
public static boolean isValidUint24(long i)
{
return (i & 0xFFFFFFL) == i;
}
public static boolean isValidUint32(long i)
{
return (i & 0xFFFFFFFFL) == i;
}
public static boolean isValidUint48(long i)
{
return (i & 0xFFFFFFFFFFFFL) == i;
}
public static boolean isValidUint64(long i)
{
return true;
}
public static boolean isSSL(TlsContext context)
{
return context.getServerVersion().isSSL();
}
public static boolean isTLSv11(ProtocolVersion version)
{
return ProtocolVersion.TLSv11.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv11(TlsContext context)
{
return isTLSv11(context.getServerVersion());
}
public static boolean isTLSv12(ProtocolVersion version)
{
return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(version.getEquivalentTLSVersion());
}
public static boolean isTLSv12(TlsContext context)
{
return isTLSv12(context.getServerVersion());
}
public static void writeUint8(short i, OutputStream output)
throws IOException
{
output.write(i);
}
public static void writeUint8(int i, OutputStream output)
throws IOException
{
output.write(i);
}
public static void writeUint8(short i, byte[] buf, int offset)
{
buf[offset] = (byte)i;
}
public static void writeUint8(int i, byte[] buf, int offset)
{
buf[offset] = (byte)i;
}
public static void writeUint16(int i, OutputStream output)
throws IOException
{
output.write(i >>> 8);
output.write(i);
}
public static void writeUint16(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 8);
buf[offset + 1] = (byte)i;
}
public static void writeUint24(int i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint24(int i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 16);
buf[offset + 1] = (byte)(i >>> 8);
buf[offset + 2] = (byte)i;
}
public static void writeUint32(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint32(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 24);
buf[offset + 1] = (byte)(i >>> 16);
buf[offset + 2] = (byte)(i >>> 8);
buf[offset + 3] = (byte)i;
}
public static void writeUint48(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 40));
output.write((byte)(i >>> 32));
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint48(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 40);
buf[offset + 1] = (byte)(i >>> 32);
buf[offset + 2] = (byte)(i >>> 24);
buf[offset + 3] = (byte)(i >>> 16);
buf[offset + 4] = (byte)(i >>> 8);
buf[offset + 5] = (byte)i;
}
public static void writeUint64(long i, OutputStream output)
throws IOException
{
output.write((byte)(i >>> 56));
output.write((byte)(i >>> 48));
output.write((byte)(i >>> 40));
output.write((byte)(i >>> 32));
output.write((byte)(i >>> 24));
output.write((byte)(i >>> 16));
output.write((byte)(i >>> 8));
output.write((byte)i);
}
public static void writeUint64(long i, byte[] buf, int offset)
{
buf[offset] = (byte)(i >>> 56);
buf[offset + 1] = (byte)(i >>> 48);
buf[offset + 2] = (byte)(i >>> 40);
buf[offset + 3] = (byte)(i >>> 32);
buf[offset + 4] = (byte)(i >>> 24);
buf[offset + 5] = (byte)(i >>> 16);
buf[offset + 6] = (byte)(i >>> 8);
buf[offset + 7] = (byte)i;
}
public static void writeOpaque8(byte[] buf, OutputStream output)
throws IOException
{
checkUint8(buf.length);
writeUint8(buf.length, output);
output.write(buf);
}
public static void writeOpaque16(byte[] buf, OutputStream output)
throws IOException
{
checkUint16(buf.length);
writeUint16(buf.length, output);
output.write(buf);
}
public static void writeOpaque24(byte[] buf, OutputStream output)
throws IOException
{
checkUint24(buf.length);
writeUint24(buf.length, output);
output.write(buf);
}
public static void writeUint8Array(short[] uints, OutputStream output)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint8(uints[i], output);
}
}
public static void writeUint8Array(short[] uints, byte[] buf, int offset)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint8(uints[i], buf, offset);
++offset;
}
}
public static void writeUint8ArrayWithUint8Length(short[] uints, OutputStream output)
throws IOException
{
checkUint8(uints.length);
writeUint8(uints.length, output);
writeUint8Array(uints, output);
}
public static void writeUint8ArrayWithUint8Length(short[] uints, byte[] buf, int offset)
throws IOException
{
checkUint8(uints.length);
writeUint8(uints.length, buf, offset);
writeUint8Array(uints, buf, offset + 1);
}
public static void writeUint16Array(int[] uints, OutputStream output)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint16(uints[i], output);
}
}
public static void writeUint16Array(int[] uints, byte[] buf, int offset)
throws IOException
{
for (int i = 0; i < uints.length; ++i)
{
writeUint16(uints[i], buf, offset);
offset += 2;
}
}
public static void writeUint16ArrayWithUint16Length(int[] uints, OutputStream output)
throws IOException
{
int length = 2 * uints.length;
checkUint16(length);
writeUint16(length, output);
writeUint16Array(uints, output);
}
public static void writeUint16ArrayWithUint16Length(int[] uints, byte[] buf, int offset)
throws IOException
{
int length = 2 * uints.length;
checkUint16(length);
writeUint16(length, buf, offset);
writeUint16Array(uints, buf, offset + 2);
}
public static byte[] encodeOpaque8(byte[] buf)
throws IOException
{
checkUint8(buf.length);
return Arrays.prepend(buf, (byte)buf.length);
}
public static byte[] encodeUint8ArrayWithUint8Length(short[] uints) throws IOException
{
byte[] result = new byte[1 + uints.length];
writeUint8ArrayWithUint8Length(uints, result, 0);
return result;
}
public static byte[] encodeUint16ArrayWithUint16Length(int[] uints) throws IOException
{
int length = 2 * uints.length;
byte[] result = new byte[2 + length];
writeUint16ArrayWithUint16Length(uints, result, 0);
return result;
}
public static short readUint8(InputStream input)
throws IOException
{
int i = input.read();
if (i < 0)
{
throw new EOFException();
}
return (short)i;
}
public static short readUint8(byte[] buf, int offset)
{
return (short)(buf[offset] & 0xff);
}
public static int readUint16(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
if (i2 < 0)
{
throw new EOFException();
}
return (i1 << 8) | i2;
}
public static int readUint16(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n;
}
public static int readUint24(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
int i3 = input.read();
if (i3 < 0)
{
throw new EOFException();
}
return (i1 << 16) | (i2 << 8) | i3;
}
public static int readUint24(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 16;
n |= (buf[++offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n;
}
public static long readUint32(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
int i3 = input.read();
int i4 = input.read();
if (i4 < 0)
{
throw new EOFException();
}
return ((i1 << 24) | (i2 << 16) | (i3 << 8) | i4) & 0xFFFFFFFFL;
}
public static long readUint32(byte[] buf, int offset)
{
int n = (buf[offset] & 0xff) << 24;
n |= (buf[++offset] & 0xff) << 16;
n |= (buf[++offset] & 0xff) << 8;
n |= (buf[++offset] & 0xff);
return n & 0xFFFFFFFFL;
}
public static long readUint48(InputStream input)
throws IOException
{
int hi = readUint24(input);
int lo = readUint24(input);
return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL);
}
public static long readUint48(byte[] buf, int offset)
{
int hi = readUint24(buf, offset);
int lo = readUint24(buf, offset + 3);
return ((long)(hi & 0xffffffffL) << 24) | (long)(lo & 0xffffffffL);
}
public static byte[] readAllOrNothing(int length, InputStream input)
throws IOException
{
if (length < 1)
{
return EMPTY_BYTES;
}
byte[] buf = new byte[length];
int read = Streams.readFully(input, buf);
if (read == 0)
{
return null;
}
if (read != length)
{
throw new EOFException();
}
return buf;
}
public static byte[] readFully(int length, InputStream input)
throws IOException
{
if (length < 1)
{
return EMPTY_BYTES;
}
byte[] buf = new byte[length];
if (length != Streams.readFully(input, buf))
{
throw new EOFException();
}
return buf;
}
public static void readFully(byte[] buf, InputStream input)
throws IOException
{
int length = buf.length;
if (length > 0 && length != Streams.readFully(input, buf))
{
throw new EOFException();
}
}
public static byte[] readOpaque8(InputStream input)
throws IOException
{
short length = readUint8(input);
return readFully(length, input);
}
public static byte[] readOpaque16(InputStream input)
throws IOException
{
int length = readUint16(input);
return readFully(length, input);
}
public static byte[] readOpaque24(InputStream input)
throws IOException
{
int length = readUint24(input);
return readFully(length, input);
}
public static short[] readUint8Array(int count, InputStream input)
throws IOException
{
short[] uints = new short[count];
for (int i = 0; i < count; ++i)
{
uints[i] = readUint8(input);
}
return uints;
}
public static int[] readUint16Array(int count, InputStream input)
throws IOException
{
int[] uints = new int[count];
for (int i = 0; i < count; ++i)
{
uints[i] = readUint16(input);
}
return uints;
}
public static ProtocolVersion readVersion(byte[] buf, int offset)
throws IOException
{
return ProtocolVersion.get(buf[offset] & 0xFF, buf[offset + 1] & 0xFF);
}
public static ProtocolVersion readVersion(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
if (i2 < 0)
{
throw new EOFException();
}
return ProtocolVersion.get(i1, i2);
}
public static int readVersionRaw(byte[] buf, int offset)
throws IOException
{
return (buf[offset] << 8) | buf[offset + 1];
}
public static int readVersionRaw(InputStream input)
throws IOException
{
int i1 = input.read();
int i2 = input.read();
if (i2 < 0)
{
throw new EOFException();
}
return (i1 << 8) | i2;
}
public static ASN1Primitive readASN1Object(byte[] encoding) throws IOException
{
ASN1InputStream asn1 = new ASN1InputStream(encoding);
ASN1Primitive result = asn1.readObject();
if (null == result)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
if (null != asn1.readObject())
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return result;
}
public static ASN1Primitive readDERObject(byte[] encoding) throws IOException
{
/*
* NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is
* canonical, we can check it by re-encoding the result and comparing to the original.
*/
ASN1Primitive result = readASN1Object(encoding);
byte[] check = result.getEncoded(ASN1Encoding.DER);
if (!Arrays.areEqual(check, encoding))
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
return result;
}
public static void writeGMTUnixTime(byte[] buf, int offset)
{
int t = (int)(System.currentTimeMillis() / 1000L);
buf[offset] = (byte)(t >>> 24);
buf[offset + 1] = (byte)(t >>> 16);
buf[offset + 2] = (byte)(t >>> 8);
buf[offset + 3] = (byte)t;
}
public static void writeVersion(ProtocolVersion version, OutputStream output)
throws IOException
{
output.write(version.getMajorVersion());
output.write(version.getMinorVersion());
}
public static void writeVersion(ProtocolVersion version, byte[] buf, int offset)
{
buf[offset] = (byte)version.getMajorVersion();
buf[offset + 1] = (byte)version.getMinorVersion();
}
public static Vector getDefaultDSSSignatureAlgorithms()
{
return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.dsa));
}
public static Vector getDefaultECDSASignatureAlgorithms()
{
return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa));
}
public static Vector getDefaultRSASignatureAlgorithms()
{
return vectorOfOne(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa));
}
public static Vector getDefaultSignatureAlgorithms(int signatureAlgorithm)
{
switch (signatureAlgorithm)
{
case SignatureAlgorithm.dsa:
return getDefaultDSSSignatureAlgorithms();
case SignatureAlgorithm.ecdsa:
return getDefaultECDSASignatureAlgorithms();
case SignatureAlgorithm.rsa:
return getDefaultRSASignatureAlgorithms();
default:
throw new IllegalArgumentException("unknown SignatureAlgorithm");
}
}
public static Vector getDefaultSupportedSignatureAlgorithms(TlsContext context)
{
TlsCrypto crypto = context.getCrypto();
short[] hashAlgorithms = new short[]{ HashAlgorithm.sha1, HashAlgorithm.sha224, HashAlgorithm.sha256,
HashAlgorithm.sha384, HashAlgorithm.sha512 };
short[] signatureAlgorithms = new short[]{ SignatureAlgorithm.rsa, SignatureAlgorithm.dsa,
SignatureAlgorithm.ecdsa };
Vector result = new Vector();
for (int i = 0; i < signatureAlgorithms.length; ++i)
{
for (int j = 0; j < hashAlgorithms.length; ++j)
{
SignatureAndHashAlgorithm alg = new SignatureAndHashAlgorithm(hashAlgorithms[j], signatureAlgorithms[i]);
if (crypto.hasSignatureAndHashAlgorithm(alg))
{
result.addElement(alg);
}
}
}
return result;
}
public static SignatureAndHashAlgorithm getSignatureAndHashAlgorithm(TlsContext context,
TlsCredentialedSigner signerCredentials)
throws IOException
{
SignatureAndHashAlgorithm signatureAndHashAlgorithm = null;
if (isTLSv12(context))
{
signatureAndHashAlgorithm = signerCredentials.getSignatureAndHashAlgorithm();
if (signatureAndHashAlgorithm == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
}
return signatureAndHashAlgorithm;
}
public static byte[] getExtensionData(Hashtable extensions, Integer extensionType)
{
return extensions == null ? null : (byte[])extensions.get(extensionType);
}
public static boolean hasExpectedEmptyExtensionData(Hashtable extensions, Integer extensionType,
short alertDescription) throws IOException
{
byte[] extension_data = getExtensionData(extensions, extensionType);
if (extension_data == null)
{
return false;
}
if (extension_data.length != 0)
{
throw new TlsFatalAlert(alertDescription);
}
return true;
}
public static TlsSession importSession(byte[] sessionID, SessionParameters sessionParameters)
{
return new TlsSessionImpl(sessionID, sessionParameters);
}
public static boolean isSignatureAlgorithmsExtensionAllowed(ProtocolVersion clientVersion)
{
return ProtocolVersion.TLSv12.isEqualOrEarlierVersionOf(clientVersion.getEquivalentTLSVersion());
}
/**
* Add a 'signature_algorithms' extension to existing extensions.
*
* @param extensions A {@link Hashtable} to add the extension to.
* @param supportedSignatureAlgorithms {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}.
* @throws IOException
*/
public static void addSignatureAlgorithmsExtension(Hashtable extensions, Vector supportedSignatureAlgorithms)
throws IOException
{
extensions.put(EXT_signature_algorithms, createSignatureAlgorithmsExtension(supportedSignatureAlgorithms));
}
public static short getSignatureAlgorithm(int keyExchangeAlgorithm)
{
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.DH_DSS:
case KeyExchangeAlgorithm.DH_DSS_EXPORT:
case KeyExchangeAlgorithm.DHE_DSS:
case KeyExchangeAlgorithm.DHE_DSS_EXPORT:
case KeyExchangeAlgorithm.SRP_DSS:
return SignatureAlgorithm.dsa;
case KeyExchangeAlgorithm.ECDH_ECDSA:
case KeyExchangeAlgorithm.ECDHE_ECDSA:
return SignatureAlgorithm.ecdsa;
case KeyExchangeAlgorithm.DH_RSA:
case KeyExchangeAlgorithm.DH_RSA_EXPORT:
case KeyExchangeAlgorithm.DHE_RSA:
case KeyExchangeAlgorithm.DHE_RSA_EXPORT:
case KeyExchangeAlgorithm.ECDH_RSA:
case KeyExchangeAlgorithm.ECDHE_RSA:
case KeyExchangeAlgorithm.SRP_RSA:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
public static short getSignatureAlgorithmClient(short clientCertificateType)
{
switch (clientCertificateType)
{
case ClientCertificateType.dss_sign:
return SignatureAlgorithm.dsa;
case ClientCertificateType.ecdsa_sign:
return SignatureAlgorithm.ecdsa;
case ClientCertificateType.rsa_sign:
return SignatureAlgorithm.rsa;
default:
return -1;
}
}
/**
* Get a 'signature_algorithms' extension from extensions.
*
* @param extensions A {@link Hashtable} to get the extension from, if it is present.
* @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}, or null.
* @throws IOException
*/
public static Vector getSignatureAlgorithmsExtension(Hashtable extensions)
throws IOException
{
byte[] extensionData = getExtensionData(extensions, EXT_signature_algorithms);
return extensionData == null ? null : readSignatureAlgorithmsExtension(extensionData);
}
/**
* Create a 'signature_algorithms' extension value.
*
* @param supportedSignatureAlgorithms A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}.
* @return A byte array suitable for use as an extension value.
* @throws IOException
*/
public static byte[] createSignatureAlgorithmsExtension(Vector supportedSignatureAlgorithms)
throws IOException
{
ByteArrayOutputStream buf = new ByteArrayOutputStream();
// supported_signature_algorithms
encodeSupportedSignatureAlgorithms(supportedSignatureAlgorithms, false, buf);
return buf.toByteArray();
}
/**
* Read 'signature_algorithms' extension data.
*
* @param extensionData The extension data.
* @return A {@link Vector} containing at least 1 {@link SignatureAndHashAlgorithm}.
* @throws IOException
*/
public static Vector readSignatureAlgorithmsExtension(byte[] extensionData)
throws IOException
{
if (extensionData == null)
{
throw new IllegalArgumentException("'extensionData' cannot be null");
}
ByteArrayInputStream buf = new ByteArrayInputStream(extensionData);
// supported_signature_algorithms
Vector supported_signature_algorithms = parseSupportedSignatureAlgorithms(false, buf);
TlsProtocol.assertEmpty(buf);
return supported_signature_algorithms;
}
public static void encodeSupportedSignatureAlgorithms(Vector supportedSignatureAlgorithms, boolean allowAnonymous,
OutputStream output) throws IOException
{
if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1
|| supportedSignatureAlgorithms.size() >= (1 << 15))
{
throw new IllegalArgumentException(
"'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)");
}
// supported_signature_algorithms
int length = 2 * supportedSignatureAlgorithms.size();
checkUint16(length);
writeUint16(length, output);
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i);
if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous)
{
/*
* RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used
* in Section 7.4.3. It MUST NOT appear in this extension.
*/
throw new IllegalArgumentException(
"SignatureAlgorithm.anonymous MUST NOT appear in the signature_algorithms extension");
}
entry.encode(output);
}
}
public static Vector parseSupportedSignatureAlgorithms(boolean allowAnonymous, InputStream input)
throws IOException
{
// supported_signature_algorithms
int length = readUint16(input);
if (length < 2 || (length & 1) != 0)
{
throw new TlsFatalAlert(AlertDescription.decode_error);
}
int count = length / 2;
Vector supportedSignatureAlgorithms = new Vector(count);
for (int i = 0; i < count; ++i)
{
SignatureAndHashAlgorithm entry = SignatureAndHashAlgorithm.parse(input);
if (!allowAnonymous && entry.getSignature() == SignatureAlgorithm.anonymous)
{
/*
* RFC 5246 7.4.1.4.1 The "anonymous" value is meaningless in this context but used
* in Section 7.4.3. It MUST NOT appear in this extension.
*/
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
supportedSignatureAlgorithms.addElement(entry);
}
return supportedSignatureAlgorithms;
}
public static void verifySupportedSignatureAlgorithm(Vector supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm)
throws IOException
{
if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.size() < 1
|| supportedSignatureAlgorithms.size() >= (1 << 15))
{
throw new IllegalArgumentException(
"'supportedSignatureAlgorithms' must have length from 1 to (2^15 - 1)");
}
if (signatureAlgorithm == null)
{
throw new IllegalArgumentException("'signatureAlgorithm' cannot be null");
}
if (signatureAlgorithm.getSignature() != SignatureAlgorithm.anonymous)
{
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm entry = (SignatureAndHashAlgorithm)supportedSignatureAlgorithms.elementAt(i);
if (entry.getHash() == signatureAlgorithm.getHash() && entry.getSignature() == signatureAlgorithm.getSignature())
{
return;
}
}
}
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
public static TlsSecret PRF(TlsContext context, TlsSecret secret, String asciiLabel, byte[] seed, int length)
{
ProtocolVersion version = context.getServerVersion();
if (version.isSSL())
{
throw new IllegalStateException("No PRF available for SSLv3 session");
}
byte[] label = Strings.toByteArray(asciiLabel);
byte[] labelSeed = concat(label, seed);
int prfAlgorithm = context.getSecurityParameters().getPrfAlgorithm();
return secret.deriveUsingPRF(prfAlgorithm, labelSeed, length);
}
static byte[] concat(byte[] a, byte[] b)
{
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static TlsSecret calculateMasterSecret(TlsContext context, TlsSecret preMasterSecret)
{
SecurityParameters securityParameters = context.getSecurityParameters();
byte[] seed;
if (securityParameters.isExtendedMasterSecret())
{
seed = securityParameters.getSessionHash();
}
else
{
seed = concat(securityParameters.getClientRandom(), securityParameters.getServerRandom());
}
if (isSSL(context))
{
return preMasterSecret.deriveSSLMasterSecret(seed);
}
String asciiLabel = securityParameters.isExtendedMasterSecret()
? ExporterLabel.extended_master_secret
: ExporterLabel.master_secret;
return PRF(context, preMasterSecret, asciiLabel, seed, 48);
}
static byte[] calculateVerifyData(TlsContext context, String asciiLabel, byte[] handshakeHash)
{
if (isSSL(context))
{
return handshakeHash;
}
SecurityParameters securityParameters = context.getSecurityParameters();
TlsSecret master_secret = securityParameters.getMasterSecret();
int verify_data_length = securityParameters.getVerifyDataLength();
return PRF(context, master_secret, asciiLabel, handshakeHash, verify_data_length).extract();
}
public static short getHashAlgorithmForPRFAlgorithm(int prfAlgorithm)
{
switch (prfAlgorithm)
{
case PRFAlgorithm.tls_prf_legacy:
throw new IllegalArgumentException("legacy PRF not a valid algorithm");
case PRFAlgorithm.tls_prf_sha256:
return HashAlgorithm.sha256;
case PRFAlgorithm.tls_prf_sha384:
return HashAlgorithm.sha384;
default:
throw new IllegalArgumentException("unknown PRFAlgorithm");
}
}
public static ASN1ObjectIdentifier getOIDForHashAlgorithm(short hashAlgorithm)
{
switch (hashAlgorithm)
{
case HashAlgorithm.md5:
return PKCSObjectIdentifiers.md5;
case HashAlgorithm.sha1:
return X509ObjectIdentifiers.id_SHA1;
case HashAlgorithm.sha224:
return NISTObjectIdentifiers.id_sha224;
case HashAlgorithm.sha256:
return NISTObjectIdentifiers.id_sha256;
case HashAlgorithm.sha384:
return NISTObjectIdentifiers.id_sha384;
case HashAlgorithm.sha512:
return NISTObjectIdentifiers.id_sha512;
default:
throw new IllegalArgumentException("unknown HashAlgorithm");
}
}
static byte[] calculateSignatureHash(TlsContext context, SignatureAndHashAlgorithm algorithm, DigestInputBuffer buf)
{
TlsHash h = context.getCrypto().createHash(algorithm);
SecurityParameters securityParameters = context.getSecurityParameters();
h.update(securityParameters.clientRandom, 0, securityParameters.clientRandom.length);
h.update(securityParameters.serverRandom, 0, securityParameters.serverRandom.length);
buf.updateDigest(h);
return h.calculateHash();
}
static void sendSignatureInput(TlsContext context, DigestInputBuffer buf, OutputStream output)
throws IOException
{
SecurityParameters securityParameters = context.getSecurityParameters();
// NOTE: The implicit copy here is intended (and important)
output.write(Arrays.concatenate(securityParameters.clientRandom, securityParameters.serverRandom));
buf.copyTo(output);
output.close();
}
static DigitallySigned generateCertificateVerify(TlsContext context, TlsCredentialedSigner credentialedSigner,
TlsStreamSigner streamSigner, TlsHandshakeHash handshakeHash) throws IOException
{
/*
* RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
*/
SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtils.getSignatureAndHashAlgorithm(
context, credentialedSigner);
byte[] signature;
if (streamSigner != null)
{
handshakeHash.copyBufferTo(streamSigner.getOutputStream());
signature = streamSigner.getSignature();
}
else
{
byte[] hash;
if (signatureAndHashAlgorithm == null)
{
hash = context.getSecurityParameters().getSessionHash();
}
else
{
hash = handshakeHash.getFinalHash(signatureAndHashAlgorithm.getHash());
}
signature = credentialedSigner.generateRawSignature(hash);
}
return new DigitallySigned(signatureAndHashAlgorithm, signature);
}
static DigitallySigned generateServerKeyExchangeSignature(TlsContext context, TlsCredentialedSigner credentials,
DigestInputBuffer buf) throws IOException
{
/*
* RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
*/
SignatureAndHashAlgorithm algorithm = TlsUtils.getSignatureAndHashAlgorithm(context, credentials);
TlsStreamSigner streamSigner = credentials.getStreamSigner();
byte[] signature;
if (streamSigner != null)
{
sendSignatureInput(context, buf, streamSigner.getOutputStream());
signature = streamSigner.getSignature();
}
else
{
byte[] hash = TlsUtils.calculateSignatureHash(context, algorithm, buf);
signature = credentials.generateRawSignature(hash);
}
return new DigitallySigned(algorithm, signature);
}
static void verifyServerKeyExchangeSignature(TlsContext context, TlsVerifier tlsVerifier, DigestInputBuffer buf,
DigitallySigned signedParams) throws IOException
{
TlsStreamVerifier streamVerifier = tlsVerifier.getStreamVerifier(signedParams);
boolean verified;
if (streamVerifier != null)
{
sendSignatureInput(context, buf, streamVerifier.getOutputStream());
verified = streamVerifier.isVerified();
}
else
{
byte[] hash = TlsUtils.calculateSignatureHash(context, signedParams.getAlgorithm(), buf);
verified = tlsVerifier.verifyRawSignature(signedParams, hash);
}
if (!verified)
{
throw new TlsFatalAlert(AlertDescription.decrypt_error);
}
}
static short getClientCertificateType(TlsContext context, Certificate clientCertificate, Certificate serverCertificate)
throws IOException
{
if (clientCertificate.isEmpty())
{
return -1;
}
return clientCertificate.getCertificateAt(0).getClientCertificateType();
}
static void trackHashAlgorithms(TlsHandshakeHash handshakeHash, Vector supportedSignatureAlgorithms)
{
if (supportedSignatureAlgorithms != null)
{
for (int i = 0; i < supportedSignatureAlgorithms.size(); ++i)
{
SignatureAndHashAlgorithm signatureAndHashAlgorithm = (SignatureAndHashAlgorithm)
supportedSignatureAlgorithms.elementAt(i);
short hashAlgorithm = signatureAndHashAlgorithm.getHash();
// TODO Support values in the "Reserved for Private Use" range
if (!HashAlgorithm.isPrivate(hashAlgorithm))
{
handshakeHash.trackHashAlgorithm(hashAlgorithm);
}
}
}
}
public static boolean hasSigningCapability(short clientCertificateType)
{
switch (clientCertificateType)
{
case ClientCertificateType.dss_sign:
case ClientCertificateType.ecdsa_sign:
case ClientCertificateType.rsa_sign:
return true;
default:
return false;
}
}
static final byte[] SSL_CLIENT = {0x43, 0x4C, 0x4E, 0x54};
static final byte[] SSL_SERVER = {0x53, 0x52, 0x56, 0x52};
private static Vector vectorOfOne(Object obj)
{
Vector v = new Vector(1);
v.addElement(obj);
return v;
}
public static int getCipherType(int cipherSuite)
{
switch (getEncryptionAlgorithm(cipherSuite))
{
case EncryptionAlgorithm.AES_128_CCM:
case EncryptionAlgorithm.AES_128_CCM_8:
case EncryptionAlgorithm.AES_128_GCM:
case EncryptionAlgorithm.AES_128_OCB_TAGLEN96:
case EncryptionAlgorithm.AES_256_CCM:
case EncryptionAlgorithm.AES_256_CCM_8:
case EncryptionAlgorithm.AES_256_GCM:
case EncryptionAlgorithm.ARIA_128_GCM:
case EncryptionAlgorithm.ARIA_256_GCM:
case EncryptionAlgorithm.AES_256_OCB_TAGLEN96:
case EncryptionAlgorithm.CAMELLIA_128_GCM:
case EncryptionAlgorithm.CAMELLIA_256_GCM:
case EncryptionAlgorithm.CHACHA20_POLY1305:
return CipherType.aead;
case EncryptionAlgorithm.RC2_CBC_40:
case EncryptionAlgorithm.IDEA_CBC:
case EncryptionAlgorithm.DES40_CBC:
case EncryptionAlgorithm.DES_CBC:
case EncryptionAlgorithm._3DES_EDE_CBC:
case EncryptionAlgorithm.AES_128_CBC:
case EncryptionAlgorithm.AES_256_CBC:
case EncryptionAlgorithm.ARIA_128_CBC:
case EncryptionAlgorithm.ARIA_256_CBC:
case EncryptionAlgorithm.CAMELLIA_128_CBC:
case EncryptionAlgorithm.CAMELLIA_256_CBC:
case EncryptionAlgorithm.SEED_CBC:
return CipherType.block;
case EncryptionAlgorithm.NULL:
case EncryptionAlgorithm.RC4_40:
case EncryptionAlgorithm.RC4_128:
return CipherType.stream;
default:
return -1;
}
}
public static int getEncryptionAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
return EncryptionAlgorithm._3DES_EDE_CBC;
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
return EncryptionAlgorithm.AES_128_CBC;
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
return EncryptionAlgorithm.AES_128_CCM;
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
return EncryptionAlgorithm.AES_128_CCM_8;
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_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_PSK_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.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
return EncryptionAlgorithm.AES_128_GCM;
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB:
return EncryptionAlgorithm.AES_128_OCB_TAGLEN96;
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return EncryptionAlgorithm.AES_256_CBC;
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
return EncryptionAlgorithm.AES_256_CCM;
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_8_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
return EncryptionAlgorithm.AES_256_CCM_8;
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_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_PSK_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.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
return EncryptionAlgorithm.AES_256_GCM;
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB:
return EncryptionAlgorithm.AES_256_OCB_TAGLEN96;
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
return EncryptionAlgorithm.ARIA_128_CBC;
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
return EncryptionAlgorithm.ARIA_128_GCM;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
return EncryptionAlgorithm.ARIA_256_CBC;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
return EncryptionAlgorithm.ARIA_256_GCM;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
return EncryptionAlgorithm.CAMELLIA_128_CBC;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
return EncryptionAlgorithm.CAMELLIA_128_GCM;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
return EncryptionAlgorithm.CAMELLIA_256_CBC;
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
return EncryptionAlgorithm.CAMELLIA_256_GCM;
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
return EncryptionAlgorithm.CHACHA20_POLY1305;
case CipherSuite.TLS_RSA_WITH_NULL_MD5:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
return EncryptionAlgorithm.NULL;
case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5:
case CipherSuite.TLS_RSA_WITH_RC4_128_MD5:
return EncryptionAlgorithm.RC4_128;
case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA:
return EncryptionAlgorithm.RC4_128;
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
return EncryptionAlgorithm.SEED_CBC;
default:
return -1;
}
}
public static int getKeyExchangeAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5:
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_anon;
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_DSS;
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DH_RSA;
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DHE_DSS;
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
return KeyExchangeAlgorithm.DHE_PSK;
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.DHE_RSA;
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDH_anon;
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDH_ECDSA;
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDH_RSA;
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDHE_ECDSA;
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDHE_PSK;
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.ECDHE_RSA;
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_PSK_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.PSK;
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_NULL_MD5:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_RC4_128_MD5:
case CipherSuite.TLS_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
return KeyExchangeAlgorithm.RSA;
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA:
return KeyExchangeAlgorithm.RSA_PSK;
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP;
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP_DSS;
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
return KeyExchangeAlgorithm.SRP_RSA;
default:
return -1;
}
}
public static int getMACAlgorithm(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
return MACAlgorithm._null;
case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5:
case CipherSuite.TLS_RSA_WITH_NULL_MD5:
case CipherSuite.TLS_RSA_WITH_RC4_128_MD5:
return MACAlgorithm.hmac_md5;
case CipherSuite.TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_anon_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DH_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_DSS_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_DHE_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA:
case CipherSuite.TLS_RSA_WITH_NULL_SHA:
case CipherSuite.TLS_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_WITH_SEED_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA:
case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA:
return MACAlgorithm.hmac_sha1;
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return MACAlgorithm.hmac_sha256;
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
return MACAlgorithm.hmac_sha384;
default:
return -1;
}
}
public static ProtocolVersion getMinimumVersion(int cipherSuite)
{
switch (cipherSuite)
{
case CipherSuite.TLS_DH_anon_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_anon_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_DHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_ECDSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_CCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_128_OCB:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_8_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_CCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_128_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_ECDHE_RSA_WITH_AES_256_OCB:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM:
case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_128_OCB:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM:
case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8:
case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.DRAFT_TLS_PSK_WITH_AES_256_OCB:
case CipherSuite.TLS_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM:
case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM:
case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8:
case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_ARIA_256_CBC_SHA384:
case CipherSuite.TLS_RSA_WITH_ARIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256:
case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384:
case CipherSuite.TLS_RSA_WITH_NULL_SHA256:
return ProtocolVersion.TLSv12;
default:
return ProtocolVersion.SSLv3;
}
}
public static boolean isAEADCipherSuite(int cipherSuite) throws IOException
{
return CipherType.aead == getCipherType(cipherSuite);
}
public static boolean isBlockCipherSuite(int cipherSuite) throws IOException
{
return CipherType.block == getCipherType(cipherSuite);
}
public static boolean isStreamCipherSuite(int cipherSuite) throws IOException
{
return CipherType.stream == getCipherType(cipherSuite);
}
public static boolean isValidCipherSuiteForVersion(int cipherSuite, ProtocolVersion serverVersion)
{
return getMinimumVersion(cipherSuite).isEqualOrEarlierVersionOf(serverVersion.getEquivalentTLSVersion());
}
public static SignatureAndHashAlgorithm chooseSignatureAndHashAlgorithm(TlsContext context, Vector algs, int signatureAlgorithm)
throws IOException
{
if (!TlsUtils.isTLSv12(context))
{
return null;
}
if (algs == null)
{
algs = TlsUtils.getDefaultSignatureAlgorithms(signatureAlgorithm);
}
SignatureAndHashAlgorithm result = null;
for (int i = 0; i < algs.size(); ++i)
{
SignatureAndHashAlgorithm alg = (SignatureAndHashAlgorithm)algs.elementAt(i);
if (alg.getSignature() == signatureAlgorithm)
{
short hash = alg.getHash();
if (hash < MINIMUM_HASH_STRICT)
{
continue;
}
if (result == null)
{
result = alg;
continue;
}
short current = result.getHash();
if (current < MINIMUM_HASH_PREFERRED)
{
if (hash > current)
{
result = alg;
}
}
else
{
if (hash < current)
{
result = alg;
}
}
}
}
if (result == null)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
return result;
}
public static int[] getSupportedCipherSuites(TlsCrypto crypto, int[] baseCipherSuiteList)
{
List<Integer> supported = new ArrayList<Integer>();
for (int i = 0; i != baseCipherSuiteList.length; i++)
{
if (isSupportedCipherSuite(crypto, baseCipherSuiteList[i]))
{
supported.add(baseCipherSuiteList[i]);
}
}
int[] rv = new int[supported.size()];
for (int i = 0; i != rv.length; i++)
{
rv[i] = supported.get(i);
}
return rv;
}
public static boolean isSupportedCipherSuite(TlsCrypto crypto, int cipherSuite)
{
int keyExchangeAlgorithm = TlsUtils.getKeyExchangeAlgorithm(cipherSuite);
// TODO Probably want TlsCrypto.hasKeyExchangeAlgorithm
switch (keyExchangeAlgorithm)
{
case KeyExchangeAlgorithm.RSA:
case KeyExchangeAlgorithm.RSA_EXPORT:
case KeyExchangeAlgorithm.RSA_PSK:
{
if (!crypto.hasRSAEncryption())
{
return false;
}
break;
}
}
int encryptionAlgorithm = TlsUtils.getEncryptionAlgorithm(cipherSuite);
int macAlgorithm = TlsUtils.getMACAlgorithm(cipherSuite);
return crypto.hasEncryptionAlgorithm(encryptionAlgorithm) && crypto.hasMacAlgorithm(macAlgorithm);
}
static void sealHandshakeHash(TlsContext context, TlsHandshakeHash handshakeHash, boolean forceBuffering)
{
if (forceBuffering || !context.getCrypto().hasAllRawSignatureAlgorithms())
{
handshakeHash.forceBuffering();
}
handshakeHash.sealHashAlgorithms();
}
}
|
package ca.corefacility.bioinformatics.irida.service.impl.sample;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.exceptions.SequenceFileAnalysisException;
import ca.corefacility.bioinformatics.irida.model.joins.Join;
import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectSampleJoin;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.project.ReferenceFile;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.model.sample.SampleSequenceFileJoin;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisFastQC;
import ca.corefacility.bioinformatics.irida.repositories.analysis.AnalysisRepository;
import ca.corefacility.bioinformatics.irida.repositories.joins.project.ProjectSampleJoinRepository;
import ca.corefacility.bioinformatics.irida.repositories.joins.sample.SampleSequenceFileJoinRepository;
import ca.corefacility.bioinformatics.irida.repositories.sample.SampleRepository;
import ca.corefacility.bioinformatics.irida.repositories.specification.ProjectSampleJoinSpecification;
import ca.corefacility.bioinformatics.irida.service.impl.CRUDServiceImpl;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
/**
* Service class for managing {@link Sample}.
*
*/
@Service
public class SampleServiceImpl extends CRUDServiceImpl<Long, Sample> implements SampleService {
private static final Logger logger = LoggerFactory.getLogger(SampleServiceImpl.class);
/**
* Reference to {@link SampleRepository} for managing {@link Sample}.
*/
private SampleRepository sampleRepository;
/**
* Reference to {@link ProjectSampleJoinRepository} for managing
* {@link ProjectSampleJoin}.
*/
private ProjectSampleJoinRepository psjRepository;
/**
* Reference to {@link SampleSequenceFileJoinRepository} for managing
* {@link SampleSequenceFileJoin}.
*/
private SampleSequenceFileJoinRepository ssfRepository;
/**
* Reference to {@link AnalysisRepository}.
*/
private final AnalysisRepository analysisRepository;
/**
* Constructor.
*
* @param sampleRepository
* the sample repository.
* @param validator
* validator.
* @param psjRepository
* the project sample join repository.
* @param ssfRepository
* the sample sequence file join repository.
* @param analysisRepository
* the analysis repository.
*/
@Autowired
public SampleServiceImpl(SampleRepository sampleRepository, ProjectSampleJoinRepository psjRepository,
SampleSequenceFileJoinRepository ssfRepository, final AnalysisRepository analysisRepository,
Validator validator) {
super(sampleRepository, validator, Sample.class);
this.sampleRepository = sampleRepository;
this.psjRepository = psjRepository;
this.ssfRepository = ssfRepository;
this.analysisRepository = analysisRepository;
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public Sample getSampleForProject(Project project, Long identifier) throws EntityNotFoundException {
Optional<Sample> sample = psjRepository.getSamplesForProject(project).stream().map(j -> j.getObject())
.filter(s -> s.getId().equals(identifier)).findFirst();
if (sample.isPresent()) {
return sample.get();
} else {
throw new EntityNotFoundException("Join between the project and this identifier doesn't exist");
}
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public Sample getSampleBySequencerSampleId(Project project, String sampleId) {
Sample s = sampleRepository.getSampleBySequencerSampleId(project, sampleId);
if (s != null) {
return s;
} else {
throw new EntityNotFoundException("No sample with external id [" + sampleId + "] in project ["
+ project.getId() + "]");
}
}
/**
* {@inheritDoc}
*/
@Override
@Transactional
public void removeSequenceFileFromSample(Sample sample, SequenceFile sequenceFile) {
SampleSequenceFileJoin joinForSampleAndFile = ssfRepository.getJoinForSampleAndFile(sample, sequenceFile);
ssfRepository.delete(joinForSampleAndFile);
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = true)
public List<Join<Project, Sample>> getSamplesForProject(Project project) {
logger.debug("Getting samples for project [" + project.getId() + "]");
return psjRepository.getSamplesForProject(project);
}
/**
* {@inheritDoc}
*/
@Transactional
public Sample mergeSamples(Project project, Sample mergeInto, Sample... toMerge) {
// confirm that all samples are part of the same project:
confirmProjectSampleJoin(project, mergeInto);
for (Sample s : toMerge) {
confirmProjectSampleJoin(project, s);
List<Join<Sample, SequenceFile>> sequenceFiles = ssfRepository.getFilesForSample(s);
for (Join<Sample, SequenceFile> sequenceFile : sequenceFiles) {
removeSequenceFileFromSample(s, sequenceFile.getObject());
addSequenceFileToSample(mergeInto, sequenceFile.getObject());
}
// have to remove the sample to be deleted from its project:
psjRepository.removeSampleFromProject(project, s);
sampleRepository.delete(s.getId());
}
return mergeInto;
}
private void confirmProjectSampleJoin(Project project, Sample sample) {
Set<Project> projects = new HashSet<>();
List<Join<Project, Sample>> sampleProjects = psjRepository.getProjectForSample(sample);
for (Join<Project, Sample> p : sampleProjects) {
projects.add(p.getSubject());
}
if (!projects.contains(project)) {
throw new IllegalArgumentException("Cannot merge sample [" + sample.getId()
+ "] with other samples; the sample does not belong to project [" + project.getId() + "]");
}
}
/**
* {@inheritDoc}
*/
@Override
public Sample read(Long id) {
return super.read(id);
}
/**
* {@inheritDoc}
*/
@Override
public Page<ProjectSampleJoin> getSamplesForProjectWithName(Project project, String name, int page, int size,
Direction order, String... sortProperties) {
sortProperties = verifySortProperties(sortProperties);
return psjRepository.findAll(ProjectSampleJoinSpecification.searchSampleWithNameInProject(name, project),
new PageRequest(page, size, order, sortProperties));
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public Long getTotalBasesForSample(Sample sample) throws SequenceFileAnalysisException {
checkNotNull(sample, "sample is null");
long totalBases = 0;
List<Join<Sample, SequenceFile>> sequenceFiles = ssfRepository.getFilesForSample(sample);
for (Join<Sample, SequenceFile> sequenceFileJoin : sequenceFiles) {
SequenceFile sequenceFile = sequenceFileJoin.getObject();
final AnalysisFastQC sequenceFileFastQC = analysisRepository.findFastqcAnalysisForSequenceFile(sequenceFile);
if (sequenceFileFastQC == null || sequenceFileFastQC.getTotalBases() == null) {
throw new SequenceFileAnalysisException("Missing FastQC analysis for SequenceFile ["
+ sequenceFile.getId() + "]");
}
totalBases += sequenceFileFastQC.getTotalBases();
}
return totalBases;
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public Double estimateCoverageForSample(Sample sample, long referenceFileLength)
throws SequenceFileAnalysisException {
checkNotNull(sample, "sample is null");
checkArgument(referenceFileLength > 0, "referenceFileLength (" + referenceFileLength + ") must be positive");
return getTotalBasesForSample(sample) / (double) referenceFileLength;
}
/**
* {@inheritDoc}
*/
@Override
@Transactional(readOnly = true)
public Double estimateCoverageForSample(Sample sample, ReferenceFile referenceFile)
throws SequenceFileAnalysisException {
checkNotNull(sample, "sample is null");
checkNotNull(referenceFile, "referenceFile is null");
return estimateCoverageForSample(sample, referenceFile.getFileLength());
}
public Page<ProjectSampleJoin> searchProjectSamples(Specification<ProjectSampleJoin> specification, int page,
int size, Direction order, String... sortProperties) {
sortProperties = verifySortProperties(sortProperties);
return psjRepository.findAll(specification, new PageRequest(page, size, order, sortProperties));
}
/**
* {@inheritDoc}
*/
@Transactional
private SampleSequenceFileJoin addSequenceFileToSample(Sample sample, SequenceFile sampleFile) {
// call the relationship repository to create the relationship between
// the two entities.
SampleSequenceFileJoin join = new SampleSequenceFileJoin(sample, sampleFile);
return ssfRepository.save(join);
}
/**
* Verify that the given sort properties array is not null or empty. If it
* is, give a default sort property.
*
* @param sortProperties
* The given sort properites
* @return The corrected sort properties
*/
private String[] verifySortProperties(String[] sortProperties) {
// if the sort properties are null, empty, or are an empty string, use
// CREATED_DATE
if (sortProperties == null || sortProperties.length == 0
|| (sortProperties.length == 1 && sortProperties[0].equals(""))) {
sortProperties = new String[] { CREATED_DATE_SORT_PROPERTY };
}
return sortProperties;
}
}
|
package com.rizki.mufrizal.aplikasi.inventory.repository.impl;
import com.rizki.mufrizal.aplikasi.inventory.domain.Barang;
import com.rizki.mufrizal.aplikasi.inventory.repository.BarangRepository;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
*
* @Author Rizki Mufrizal <mufrizalrizki@gmail.com>
* @Since Mar 18, 2016
* @Time 10:54:00 PM
* @Encoding UTF-8
* @Project Aplikasi-Inventory
* @Package com.rizki.mufrizal.aplikasi.inventory.repository.impl
*
*/
@Repository
public class BarangRepositoryImpl implements BarangRepository {
@Autowired
private SessionFactory sessionFactory;
@Override
public void simpanBarang(Barang barang) {
sessionFactory.getCurrentSession().save(barang);
}
@Override
public void editBarang(Barang barang) {
sessionFactory.getCurrentSession().update(barang);
}
@Override
public void hapusBarang(Barang barang) {
sessionFactory.getCurrentSession().delete(barang);
}
@Override
public Integer jumlahBarang() {
return sessionFactory.getCurrentSession().createCriteria(Barang.class).list().size();
}
@Override
public List<Barang> ambilBarangs(Integer pageNumber, Integer rowsPerPage) {
return sessionFactory
.getCurrentSession()
.createCriteria(Barang.class)
.setFirstResult(rowsPerPage * (pageNumber - 1))
.setMaxResults(rowsPerPage)
.list();
}
@Override
public Barang getBarang(String idBarang) {
return sessionFactory.getCurrentSession().get(Barang.class, idBarang);
}
}
|
package com.amee.domain.item;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import com.amee.domain.AMEEEntity;
import com.amee.domain.data.DataCategory;
import com.amee.domain.data.ItemDefinition;
import com.amee.domain.path.Pathable;
@MappedSuperclass
public abstract class BaseItem extends AMEEEntity implements Pathable {
public final static int NAME_MAX_SIZE = 255;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "ITEM_DEFINITION_ID")
private ItemDefinition itemDefinition;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "DATA_CATEGORY_ID")
private DataCategory dataCategory;
@Column(name = "NAME", length = NAME_MAX_SIZE, nullable = false)
private String name = "";
@Transient
private transient String fullPath;
@Transient
private Date effectiveStartDate;
@Transient
private Date effectiveEndDate;
public BaseItem() {
super();
}
public BaseItem(DataCategory dataCategory, ItemDefinition itemDefinition) {
this();
setDataCategory(dataCategory);
setItemDefinition(itemDefinition);
}
/**
* Copy values from this instance to the supplied instance.
* <p/>
* Does not copy ItemValues.
*
* @param o Object to copy values to
*/
protected void copyTo(BaseItem o) {
super.copyTo(o);
o.itemDefinition = itemDefinition;
o.dataCategory = dataCategory;
o.name = name;
o.effectiveStartDate = (effectiveStartDate != null) ? (Date) effectiveStartDate.clone() : null;
o.effectiveEndDate = (effectiveEndDate != null) ? (Date) effectiveEndDate.clone() : null;
}
/**
* Get the full path of this Item.
*
* @return the full path
*/
@Override
public String getFullPath() {
// Need to build the fullPath?
if (fullPath == null) {
// Is there a parent.
if (getDataCategory() != null) {
// There is a parent.
fullPath = getDataCategory().getFullPath() + "/" + getDisplayPath();
} else {
// There must be a parent.
throw new RuntimeException("Item has no parent.");
}
}
return fullPath;
}
public ItemDefinition getItemDefinition() {
return itemDefinition;
}
public void setItemDefinition(ItemDefinition itemDefinition) {
if (itemDefinition != null) {
this.itemDefinition = itemDefinition;
}
}
public DataCategory getDataCategory() {
return dataCategory;
}
public void setDataCategory(DataCategory dataCategory) {
if (dataCategory != null) {
this.dataCategory = dataCategory;
}
}
@Override
public String getName() {
return name;
}
@Override
public String getDisplayName() {
if (!getName().isEmpty()) {
return getName();
} else {
return getDisplayPath();
}
}
@Override
public String getDisplayPath() {
if (!getPath().isEmpty()) {
return getPath();
} else {
return getUid();
}
}
public void setName(String name) {
if (name == null) {
name = "";
}
this.name = name;
}
/**
* @return returns true if this Item supports CO2 amounts, otherwise false.
*/
public boolean supportsCalculation() {
return !getItemDefinition().getAlgorithms().isEmpty();
}
/**
* Set the effective start date.
*
* @param effectiveStartDate
*/
public void setEffectiveStartDate(Date effectiveStartDate) {
this.effectiveStartDate = effectiveStartDate;
}
/**
* Get the effective start date.
*
* @return the effective start date.
*/
public Date getEffectiveStartDate() {
return effectiveStartDate;
}
/**
* Set the effective end date.
*
* @param effectiveEndDate
*/
public void setEffectiveEndDate(Date effectiveEndDate) {
this.effectiveEndDate = effectiveEndDate;
}
/**
* Get the effective end date.
*
* @return the effective end date.
*/
public Date getEffectiveEndDate() {
return effectiveEndDate;
}
}
|
package com.intellij.vcs.log.impl;
import com.intellij.ide.caches.CachesInvalidator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.Topic;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.VcsLogProvider;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.ui.VcsLogUiImpl;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.jetbrains.annotations.*;
import java.util.Arrays;
import java.util.Map;
import static com.intellij.vcs.log.util.PersistentUtil.LOG_CACHE;
public class VcsProjectLog implements Disposable {
private static final Logger LOG = Logger.getInstance(VcsProjectLog.class);
public static final Topic<ProjectLogListener> VCS_PROJECT_LOG_CHANGED =
Topic.create("Project Vcs Log Created or Disposed", ProjectLogListener.class);
private static final int RECREATE_LOG_TRIES = 5;
@NotNull private final Project myProject;
@NotNull private final MessageBus myMessageBus;
@NotNull private final VcsLogTabsProperties myUiProperties;
@NotNull private final VcsLogTabsManager myTabsManager;
@NotNull private final LazyVcsLogManager myLogManager = new LazyVcsLogManager();
@NotNull private final Disposable myMappingChangesDisposable = Disposer.newDisposable();
private int myRecreatedLogCount = 0;
public VcsProjectLog(@NotNull Project project,
@NotNull MessageBus messageBus,
@NotNull VcsLogProjectTabsProperties uiProperties) {
myProject = project;
myMessageBus = messageBus;
myUiProperties = uiProperties;
myTabsManager = new VcsLogTabsManager(project, messageBus, uiProperties, this);
Disposer.register(this, myMappingChangesDisposable);
}
private void subscribeToMappingsChanges() {
myMessageBus.connect(myMappingChangesDisposable).subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, this::recreateLog);
}
@Nullable
public VcsLogData getDataManager() {
VcsLogManager cached = myLogManager.getCached();
if (cached == null) return null;
return cached.getDataManager();
}
/**
* The instance of the {@link VcsLogUiImpl} or null if the log was not initialized yet.
*/
@Nullable
public VcsLogUiImpl getMainLogUi() {
VcsLogContentProvider logContentProvider = VcsLogContentProvider.getInstance(myProject);
if (logContentProvider == null) return null;
return logContentProvider.getUi();
}
@Nullable
public VcsLogManager getLogManager() {
return myLogManager.getCached();
}
@NotNull
public VcsLogTabsManager getTabsManager() {
return myTabsManager;
}
@CalledInAny
private void recreateLog() {
UIUtil.invokeLaterIfNeeded(() -> myLogManager.drop(() -> {
if (myProject.isDisposed()) return;
createLog(false);
}));
}
@CalledInAwt
private void recreateOnError(@NotNull Throwable t) {
if ((++myRecreatedLogCount) % RECREATE_LOG_TRIES == 0) {
String message = String.format("VCS Log was recreated %d times due to data corruption\n" +
"Delete %s directory and restart %s if this happens often.\n%s",
myRecreatedLogCount, LOG_CACHE, ApplicationNamesInfo.getInstance().getFullProductName(),
t.getMessage());
LOG.error(message, t);
VcsLogManager manager = getLogManager();
if (manager != null && manager.isLogVisible()) {
VcsBalloonProblemNotifier.showOverChangesView(myProject, message, MessageType.ERROR);
}
}
else {
LOG.debug("Recreating VCS Log after storage corruption", t);
}
recreateLog();
}
@Nullable
@CalledInBackground
VcsLogManager createLog(boolean forceInit) {
Map<VirtualFile, VcsLogProvider> logProviders = getLogProviders();
if (!logProviders.isEmpty()) {
VcsLogManager logManager = myLogManager.getValue(logProviders);
initialize(logManager, forceInit);
return logManager;
}
return null;
}
@CalledInBackground
private static void initialize(@NotNull VcsLogManager logManager, boolean force) {
if (force) {
logManager.scheduleInitialization();
return;
}
if (PostponableLogRefresher.keepUpToDate()) {
VcsLogCachesInvalidator invalidator = CachesInvalidator.EP_NAME.findExtension(VcsLogCachesInvalidator.class);
if (invalidator.isValid()) {
HeavyAwareExecutor.executeOutOfHeavyProcessLater(logManager::scheduleInitialization, 5000);
return;
}
}
ApplicationManager.getApplication().invokeLater(() -> {
if (logManager.isLogVisible()) {
logManager.scheduleInitialization();
}
});
}
@NotNull
private Map<VirtualFile, VcsLogProvider> getLogProviders() {
return VcsLogManager.findLogProviders(Arrays.asList(ProjectLevelVcsManager.getInstance(myProject).getAllVcsRoots()), myProject);
}
public static VcsProjectLog getInstance(@NotNull Project project) {
return ServiceManager.getService(project, VcsProjectLog.class);
}
public void addProjectLogListener(@NotNull ProjectLogListener listener, @NotNull Disposable disposable) {
UIUtil.invokeLaterIfNeeded(() -> {
synchronized (myLogManager) {
VcsLogManager cached = myLogManager.getCached();
myMessageBus.connect(disposable).subscribe(VCS_PROJECT_LOG_CHANGED, listener);
if (cached != null) {
listener.logCreated(cached);
}
}
});
}
@Override
public void dispose() {
myLogManager.drop(null);
}
private class LazyVcsLogManager {
@Nullable private VcsLogManager myValue;
@NotNull
@CalledInBackground
public synchronized VcsLogManager getValue(@NotNull Map<VirtualFile, VcsLogProvider> logProviders) {
if (myValue == null) {
LOG.debug("Creating Vcs Log for " + VcsLogUtil.getProvidersMapText(logProviders));
VcsLogManager value = compute(logProviders);
myValue = value;
ApplicationManager.getApplication().invokeLater(() -> {
if (!myProject.isDisposed()) myMessageBus.syncPublisher(VCS_PROJECT_LOG_CHANGED).logCreated(value);
});
}
return myValue;
}
@NotNull
@CalledInBackground
protected VcsLogManager compute(@NotNull Map<VirtualFile, VcsLogProvider> logProviders) {
return new VcsLogManager(myProject, myUiProperties, logProviders, false,
VcsProjectLog.this::recreateOnError);
}
@CalledInAwt
public synchronized void drop(@Nullable Runnable callback) {
LOG.assertTrue(ApplicationManager.getApplication().isDispatchThread());
if (myValue != null) {
LOG.debug("Disposing Vcs Log for " + VcsLogUtil.getProvidersMapText(myValue.getDataManager().getLogProviders()));
myMessageBus.syncPublisher(VCS_PROJECT_LOG_CHANGED).logDisposed(myValue);
myValue.dispose(callback);
myValue = null;
}
else if (callback != null) {
ApplicationManager.getApplication().executeOnPooledThread(callback);
}
}
@Nullable
public synchronized VcsLogManager getCached() {
return myValue;
}
}
public static class InitLogStartupActivity implements StartupActivity {
@Override
public void runActivity(@NotNull Project project) {
if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment()) return;
VcsProjectLog projectLog = getInstance(project);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
projectLog.subscribeToMappingsChanges();
projectLog.createLog(false);
});
}
}
public interface ProjectLogListener {
@CalledInAwt
void logCreated(@NotNull VcsLogManager manager);
@CalledInAwt
default void logDisposed(@NotNull VcsLogManager manager) {
}
}
}
|
package net.sf.esfinge.metadata.container.reading;
import static org.apache.commons.beanutils.PropertyUtils.setProperty;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.esfinge.metadata.AnnotationReadingException;
import net.sf.esfinge.metadata.AnnotationValidationException;
import net.sf.esfinge.metadata.annotation.container.InitProcessor;
import net.sf.esfinge.metadata.annotation.container.MethodProcessors;
import net.sf.esfinge.metadata.annotation.container.Processors;
import net.sf.esfinge.metadata.container.AnnotationReadingProcessor;
import net.sf.esfinge.metadata.container.ContainerTarget;
public class MethodProcessorsReadingProcessor implements AnnotationReadingProcessor {
private Field fieldAnnoted;
private Map<Object,Object> map;
private MethodProcessors processors;
private Class<? extends Annotation> processorsAnnotationClass;
ParameterizedType fieldGenericType;
@Override
public void initAnnotation(Annotation an, Field field) throws AnnotationValidationException {
// TODO Auto-generated method stub
fieldAnnoted = field;
processors = (MethodProcessors)an;
processorsAnnotationClass = processors.value();
fieldGenericType = (ParameterizedType) fieldAnnoted.getGenericType();
map = new HashMap<>();
}
@Override
public void read(AnnotatedElement elementWithMetadata, Object container, ContainerTarget target)
throws AnnotationReadingException {
// TODO Auto-generated method stub
try {
if(elementWithMetadata instanceof Class)
{
Class clazz = (Class) elementWithMetadata;
for(Method methodOfClazz : clazz.getDeclaredMethods())
{
for(Annotation annotation:methodOfClazz.getDeclaredAnnotations())
{
Annotation processorAnnotation = annotation.annotationType().getAnnotation(processorsAnnotationClass);
//pega o class do value dessa anotation
Class<?> valueClass = (Class<?>) processorAnnotation.getClass().getDeclaredMethod("value").invoke(processorAnnotation);
//cria um objeto dessa classe e invoca o @InitProcessor
Object objectToInvoke = valueClass.newInstance();
findDeclaredAnnotationOnInterface(elementWithMetadata, container, annotation, valueClass,
objectToInvoke);
map.put(methodOfClazz, objectToInvoke);
}
}
}
setProperty(container,fieldAnnoted.getName(),map);
} catch (Exception e) {
// TODO: handle exception
throw new AnnotationReadingException("==========="+e);
}
}
private void findDeclaredAnnotationOnInterface(AnnotatedElement elementWithMetadata, Object container,
Annotation annotation, Class<?> valueClass, Object objectToInvoke)
throws IllegalAccessException, InvocationTargetException {
for(Method methodToInvoke: valueClass.getInterfaces()[0].getDeclaredMethods())
{
if(methodToInvoke.isAnnotationPresent(InitProcessor.class)){
executeParameters(elementWithMetadata, container, annotation, objectToInvoke, methodToInvoke);
}
}
}
private void executeParameters(AnnotatedElement elementWithMetadata, Object container, Annotation annotation,
Object objectToInvoke, Method methodToInvoke) throws IllegalAccessException, InvocationTargetException {
Object[] args = new Object[methodToInvoke.getParameters().length];
int cont = 0;
for(Parameter p1 : methodToInvoke.getParameters()){
if(p1.getType().equals(Annotation.class))
{
args[cont] = annotation;
}
else if(p1.getType().equals(AnnotatedElement.class))
{
args[cont] = elementWithMetadata;
}
else if(p1.getType().equals(container.getClass()))
{
args[cont] = container;
}
cont++;
}
methodToInvoke.invoke(objectToInvoke, args);
}
}
|
package com.amee.domain.unit;
import com.amee.base.utils.ThreadBeanHolder;
import com.amee.domain.AMEEEntity;
import com.amee.domain.IAMEEEntityReference;
import com.amee.domain.IDataService;
import com.amee.domain.ObjectType;
import com.amee.domain.path.Pathable;
import com.amee.platform.science.AmountUnit;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.measure.unit.Unit;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "UNIT")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AMEEUnit extends AMEEEntity implements Pathable {
public final static int NAME_MAX_SIZE = 255;
public final static int SYMBOL_MAX_SIZE = 255;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "UNIT_TYPE_ID")
private AMEEUnitType unitType;
@Column(name = "NAME", nullable = false, length = NAME_MAX_SIZE)
private String name = "";
@Column(name = "INTERNAL_SYMBOL", nullable = false, length = SYMBOL_MAX_SIZE)
private String internalSymbol = "";
@Column(name = "EXTERNAL_SYMBOL", nullable = false, length = SYMBOL_MAX_SIZE)
private String externalSymbol = "";
public AMEEUnit() {
super();
}
public AMEEUnit(AMEEUnitType unitType) {
super();
setUnitType(unitType);
}
public AMEEUnit(String name) {
this();
setName(name);
}
public AMEEUnit(String name, String internalSymbol) {
this(name);
setInternalSymbol(internalSymbol);
}
public AMEEUnit(String name, String internalSymbol, String externalSymbol) {
this(name, internalSymbol);
setExternalSymbol(externalSymbol);
}
@Override
@Transient
public String getPath() {
return getUid();
}
@Override
@Transient
public String getDisplayName() {
return getName();
}
@Override
@Transient
public String getDisplayPath() {
return getPath();
}
@Override
@Transient
public String getFullPath() {
return getPath();
}
@Override
@Transient
public ObjectType getObjectType() {
return ObjectType.UN;
}
@Override
@Transient
public List<IAMEEEntityReference> getHierarchy() {
List<IAMEEEntityReference> entities = new ArrayList<IAMEEEntityReference>();
entities.add(getDataService().getRootDataCategory());
entities.add(getUnitType());
entities.add(this);
return entities;
}
@Override
@Transient
public boolean isTrash() {
return super.isTrash() || getUnitType().isTrash();
}
@Transient
public boolean hasExternalSymbol() {
return !getExternalSymbol().isEmpty();
}
@Transient
public String getSymbol() {
if (getExternalSymbol().isEmpty()) {
return getInternalSymbol();
} else {
return getExternalSymbol();
}
}
@Transient
public AmountUnit getAmountUnit() {
return AmountUnit.valueOf(getInternalSymbol());
}
@Transient
public Unit getInternalUnit() {
return getAmountUnit().toUnit();
}
public AMEEUnitType getUnitType() {
return unitType;
}
public void setUnitType(AMEEUnitType unitType) {
this.unitType = unitType;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
if (name == null) {
name = "";
}
this.name = name;
}
public String getInternalSymbol() {
return internalSymbol;
}
public void setInternalSymbol(String internalSymbol) {
if (internalSymbol == null) {
internalSymbol = "";
}
this.internalSymbol = internalSymbol;
}
public String getExternalSymbol() {
return externalSymbol;
}
public void setExternalSymbol(String externalSymbol) {
if (externalSymbol == null) {
externalSymbol = "";
}
this.externalSymbol = externalSymbol;
}
@Transient
public IDataService getDataService() {
return ThreadBeanHolder.get(IDataService.class);
}
}
|
package org.jenkinsci.plugins.credentialsbinding.impl;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.credentialsbinding.MultiBinding;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.kohsuke.stapler.DataBoundSetter;
public class UsernamePasswordMultiBinding extends MultiBinding<StandardUsernamePasswordCredentials> {
private final String usernameVariable;
private final String passwordVariable;
private boolean showUsername;
@DataBoundConstructor public UsernamePasswordMultiBinding(String usernameVariable, String passwordVariable, String credentialsId) {
super(credentialsId);
this.usernameVariable = usernameVariable;
this.passwordVariable = passwordVariable;
}
public String getUsernameVariable() {
return usernameVariable;
}
public String getPasswordVariable() {
return passwordVariable;
}
public boolean isShowUsername() {
return showUsername;
}
@DataBoundSetter public void setShowUsername(boolean showUsername) {
this.showUsername = showUsername;
}
@Override protected Class<StandardUsernamePasswordCredentials> type() {
return StandardUsernamePasswordCredentials.class;
}
@Override public MultiEnvironment bind(@Nonnull Run<?, ?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@Nonnull TaskListener listener) throws IOException, InterruptedException {
StandardUsernamePasswordCredentials credentials = getCredentials(build);
Map<String, String> secretValues = new LinkedHashMap<>();
Map<String, String> publicValues = new LinkedHashMap<>();
(showUsername ? publicValues : secretValues).put(usernameVariable, credentials.getUsername());
secretValues.put(passwordVariable, credentials.getPassword().getPlainText());
return new MultiEnvironment(secretValues, publicValues);
}
@Override public Set<String> variables() {
Set<String> vars = new LinkedHashSet<>();
if (!showUsername) {
vars.add(usernameVariable);
}
vars.add(passwordVariable);
return vars;
}
@Symbol("usernamePassword")
@Extension public static class DescriptorImpl extends BindingDescriptor<StandardUsernamePasswordCredentials> {
@Override protected Class<StandardUsernamePasswordCredentials> type() {
return StandardUsernamePasswordCredentials.class;
}
@Override public String getDisplayName() {
return Messages.UsernamePasswordMultiBinding_username_and_password();
}
@Override public boolean requiresWorkspace() {
return false;
}
}
}
|
package org.springframework.data.jpa.datatables.repository;
import java.util.Arrays;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.parameter.ColumnParameter;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
/**
* {@link Specification} converting {@link DataTablesInput} to proper SQL query
*
* @author Damien Arrachequesne
*/
public class DataTablesSpecification<T> implements Specification<T> {
private final static String OR_SEPARATOR = "+";
private final static String ATTRIBUTE_SEPARATOR = ".";
private final DataTablesInput input;
public DataTablesSpecification(DataTablesInput input) {
this.input = input;
}
/**
* Creates a WHERE clause for the given {@link DataTablesInput}.
*
* @return a {@link Predicate}, must not be {@literal null}.
*/
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder) {
Predicate predicate = criteriaBuilder.conjunction();
// check for each searchable column whether a filter value exists
for (ColumnParameter column : input.getColumns()) {
String filterValue = column.getSearch().getValue();
if (column.getSearchable() && StringUtils.hasText(filterValue)) {
Expression<String> expression = getExpression(root,
column.getData());
if (filterValue.contains(OR_SEPARATOR)) {
// the filter contains multiple values, add a 'WHERE .. IN'
// clause
// Note: "\\" is added to escape special character '+'
String[] values = filterValue.split("\\" + OR_SEPARATOR);
predicate = criteriaBuilder.and(predicate,
expression.in(Arrays.asList(values)));
} else {
// the filter contains only one value, add a 'WHERE .. ='
// clause
predicate = criteriaBuilder.and(predicate,
criteriaBuilder.equal(expression, filterValue));
}
}
}
// check whether a global filter value exists
String globalFilterValue = input.getSearch().getValue();
if (StringUtils.hasText(globalFilterValue)) {
Predicate matchOneColumnPredicate = criteriaBuilder.disjunction();
// add a 'WHERE .. LIKE' clause on each searchable column
for (ColumnParameter column : input.getColumns()) {
if (column.getSearchable()) {
Expression<String> expression = getExpression(root,
column.getData());
matchOneColumnPredicate = criteriaBuilder.or(
matchOneColumnPredicate,
criteriaBuilder.like(expression, "%"
+ globalFilterValue + "%"));
}
}
predicate = criteriaBuilder.and(predicate, matchOneColumnPredicate);
}
return predicate;
}
private Expression<String> getExpression(Root<T> root, String columnData) {
if (columnData.contains(ATTRIBUTE_SEPARATOR)) {
// columnData is like "joinedEntity.attribute" so add a join clause
String[] values = columnData.split("\\" + ATTRIBUTE_SEPARATOR);
return root.join(values[0], JoinType.LEFT).get(values[1])
.as(String.class);
} else {
// columnData is like "attribute" so nothing particular to do
return root.get(columnData).as(String.class);
}
}
}
|
package com.balancedpayments;
import com.balancedpayments.core.Client;
public class Balanced {
private static final Balanced _instance = new Balanced();
private static final String VERSION = "1.3";
private static final String API_REVISION = "1.1";
private static final String API_URL = "https://api.balancedpayments.com";
private static final String AGENT = "balanced-java";
private String KEY;
private Client client = new Client(API_URL, null);
private Balanced() {}
public static synchronized Balanced getInstance() {
return _instance;
}
public void configureClient(String key) {
KEY=key;
client = new Client(API_URL, key);
}
public static void configure(String key) {
getInstance().configureClient(key);
}
public Client getClient() { return client; }
public String getAPIVersion() {
return API_REVISION;
}
public String getAPIURL() {
return API_URL;
}
public String getAgent() { return AGENT; }
public String getApiRevision() { return API_REVISION; }
public String getVersion() { return VERSION; }
}
|
//FILE: AcquisitionPanel.java
//PROJECT: Micro-Manager
//SUBSYSTEM: ASIdiSPIM plugin
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.asidispim;
import org.micromanager.asidispim.Data.AcquisitionModes;
import org.micromanager.asidispim.Data.CameraModes;
import org.micromanager.asidispim.Data.Cameras;
import org.micromanager.asidispim.Data.Devices;
import org.micromanager.asidispim.Data.MultichannelModes;
import org.micromanager.asidispim.Data.MyStrings;
import org.micromanager.asidispim.Data.Positions;
import org.micromanager.asidispim.Data.Prefs;
import org.micromanager.asidispim.Data.Properties;
import org.micromanager.asidispim.Utils.DevicesListenerInterface;
import org.micromanager.asidispim.Utils.ListeningJPanel;
import org.micromanager.asidispim.Utils.MyDialogUtils;
import org.micromanager.asidispim.Utils.MyNumberUtils;
import org.micromanager.asidispim.Utils.PanelUtils;
import org.micromanager.asidispim.Utils.SliceTiming;
import org.micromanager.asidispim.Utils.StagePositionUpdater;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.ParseException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.DefaultFormatter;
import net.miginfocom.swing.MigLayout;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import mmcorej.CMMCore;
import mmcorej.StrVector;
import mmcorej.TaggedImage;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.StagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.ScriptInterface;
import org.micromanager.api.ImageCache;
import org.micromanager.api.MMTags;
import org.micromanager.MMStudio;
import org.micromanager.acquisition.ComponentTitledBorder;
import org.micromanager.acquisition.DefaultTaggedImageSink;
import org.micromanager.acquisition.MMAcquisition;
import org.micromanager.acquisition.TaggedImageQueue;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.acquisition.TaggedImageStorageMultipageTiff;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMFrame;
import org.micromanager.utils.MMScriptException;
import org.micromanager.utils.ReportingUtils;
import com.swtdesigner.SwingResourceManager;
import ij.IJ;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import org.micromanager.asidispim.Data.AcquisitionSettings;
import org.micromanager.asidispim.Data.ChannelSpec;
import org.micromanager.asidispim.Data.Devices.Sides;
import org.micromanager.asidispim.Data.Joystick.Directions;
import org.micromanager.asidispim.Utils.ControllerUtils;
import org.micromanager.asidispim.Utils.AutofocusUtils;
import org.micromanager.asidispim.api.ASIdiSPIMException;
/**
*
* @author nico
* @author Jon
*/
@SuppressWarnings("serial")
public class AcquisitionPanel extends ListeningJPanel implements DevicesListenerInterface {
private final Devices devices_;
private final Properties props_;
private final Cameras cameras_;
private final Prefs prefs_;
private final ControllerUtils controller_;
private final AutofocusUtils autofocus_;
private final Positions positions_;
private final CMMCore core_;
private final ScriptInterface gui_;
private final JCheckBox advancedSliceTimingCB_;
private final JSpinner numSlices_;
private final JComboBox numSides_;
private final JComboBox firstSide_;
private final JSpinner numScansPerSlice_;
private final JSpinner lineScanDuration_;
private final JSpinner delayScan_;
private final JSpinner delayLaser_;
private final JSpinner delayCamera_;
private final JSpinner durationCamera_; // NB: not the same as camera exposure
private final JSpinner exposureCamera_; // NB: only used in advanced timing mode
private JCheckBox alternateBeamScanCB_;
private final JSpinner durationLaser_;
private final JSpinner delaySide_;
private final JLabel actualSlicePeriodLabel_;
private final JLabel actualVolumeDurationLabel_;
private final JLabel actualTimeLapseDurationLabel_;
private final JSpinner numTimepoints_;
private final JSpinner acquisitionInterval_;
private final JToggleButton buttonStart_;
private final JButton buttonTestAcq_;
private final JPanel volPanel_;
private final JPanel sliceAdvancedPanel_;
private final JPanel timepointPanel_;
private final JPanel savePanel_;
private final JPanel durationPanel_;
private final JFormattedTextField rootField_;
private final JFormattedTextField prefixField_;
private final JLabel acquisitionStatusLabel_;
private int numTimePointsDone_;
private final AtomicBoolean cancelAcquisition_ = new AtomicBoolean(false); // true if we should stop acquisition
private final AtomicBoolean acquisitionRequested_ = new AtomicBoolean(false); // true if acquisition has been requested to start or is underway
private final AtomicBoolean acquisitionRunning_ = new AtomicBoolean(false); // true if the acquisition is actually underway
private final StagePositionUpdater posUpdater_;
private final JSpinner stepSize_;
private final JLabel desiredSlicePeriodLabel_;
private final JSpinner desiredSlicePeriod_;
private final JLabel desiredLightExposureLabel_;
private final JSpinner desiredLightExposure_;
private final JCheckBox minSlicePeriodCB_;
private final JCheckBox separateTimePointsCB_;
private final JCheckBox saveCB_;
private final JComboBox spimMode_;
private final JCheckBox navigationJoysticksCB_;
private final JCheckBox usePositionsCB_;
private final JSpinner positionDelay_;
private final JCheckBox useTimepointsCB_;
private final JCheckBox useAutofocusCB_;
private final JPanel leftColumnPanel_;
private final JPanel centerColumnPanel_;
private final JPanel rightColumnPanel_;
private final MMFrame sliceFrameAdvanced_;
private SliceTiming sliceTiming_;
private final MultiChannelSubPanel multiChannelPanel_;
private final Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA,
Color.PINK, Color.CYAN, Color.YELLOW, Color.ORANGE};
private String lastAcquisitionPath_;
private String lastAcquisitionName_;
private MMAcquisition acq_;
private String[] channelNames_;
private int nrRepeats_; // how many separate acquisitions to perform
private final AcquisitionPanel acquisitionPanel_;
private final JComponent[] simpleTimingComponents_;
private final JPanel slicePanel_;
private final JPanel slicePanelContainer_;
private final JPanel lightSheetPanel_;
private final JPanel normalPanel_;
public AcquisitionPanel(ScriptInterface gui,
Devices devices,
Properties props,
Cameras cameras,
Prefs prefs,
StagePositionUpdater posUpdater,
Positions positions,
ControllerUtils controller,
AutofocusUtils autofocus) {
super(MyStrings.PanelNames.ACQUSITION.toString(),
new MigLayout(
"",
"[center]0[center]0[center]",
"0[top]0"));
gui_ = gui;
devices_ = devices;
props_ = props;
cameras_ = cameras;
prefs_ = prefs;
posUpdater_ = posUpdater;
positions_ = positions;
controller_ = controller;
autofocus_ = autofocus;
core_ = gui_.getMMCore();
numTimePointsDone_ = 0;
sliceTiming_ = new SliceTiming();
lastAcquisitionPath_ = "";
lastAcquisitionName_ = "";
acq_ = null;
channelNames_ = null;
acquisitionPanel_ = this;
PanelUtils pu = new PanelUtils(prefs_, props_, devices_);
// added to spinner controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ChangeListener recalculateTimingDisplayCL = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (advancedSliceTimingCB_.isSelected()) {
// need to update sliceTiming_ from property values
sliceTiming_ = getTimingFromAdvancedSettings();
}
updateDurationLabels();
}
};
// added to combobox controls where we should re-calculate the displayed
// slice period, volume duration, and time lapse duration
ActionListener recalculateTimingDisplayAL = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateDurationLabels();
}
};
// start volume sub-panel
volPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"4[]8[]"));
volPanel_.setBorder(PanelUtils.makeTitledBorder("Volume Settings"));
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, "1");
}
volPanel_.add(new JLabel("Number of sides:"));
String [] str12 = {"1", "2"};
numSides_ = pu.makeDropDownBox(str12, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SIDES, str12[1]);
numSides_.addActionListener(recalculateTimingDisplayAL);
if (!ASIdiSPIM.oSPIM) {
} else {
numSides_.setEnabled(false);
}
volPanel_.add(numSides_, "wrap");
volPanel_.add(new JLabel("First side:"));
String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()};
if (!ASIdiSPIM.oSPIM) {
} else {
props_.setPropValue(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
}
firstSide_ = pu.makeDropDownBox(ab, Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString());
firstSide_.addActionListener(recalculateTimingDisplayAL);
if (!ASIdiSPIM.oSPIM) {
} else {
firstSide_.setEnabled(false);
}
volPanel_.add(firstSide_, "wrap");
volPanel_.add(new JLabel("Delay before side [ms]:"));
// used to read/write directly to galvo/micro-mirror firmware, but want different stage scan behavior
delaySide_ = pu.makeSpinnerFloat(0, 10000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DELAY_BEFORE_SIDE, 50);
pu.addListenerLast(delaySide_, recalculateTimingDisplayCL);
volPanel_.add(delaySide_, "wrap");
volPanel_.add(new JLabel("Slices per side:"));
numSlices_ = pu.makeSpinnerInteger(1, 65000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_SLICES, 20);
pu.addListenerLast(numSlices_, recalculateTimingDisplayCL);
volPanel_.add(numSlices_, "wrap");
volPanel_.add(new JLabel("Slice step size [\u00B5m]:"));
stepSize_ = pu.makeSpinnerFloat(0, 100, 0.1,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_SLICE_STEP_SIZE,
1.0);
pu.addListenerLast(stepSize_, recalculateTimingDisplayCL); // needed only for stage scanning b/c acceleration time related to speed
volPanel_.add(stepSize_, "wrap");
// end volume sub-panel
// start slice timing controls, have 2 options with advanced timing checkbox shared
slicePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"0[]0[]"));
slicePanel_.setBorder(PanelUtils.makeTitledBorder("Slice Settings"));
// start light sheet controls
lightSheetPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"4[]8"));
lightSheetPanel_.add(new JLabel("Scan reset time [ms]:"));
JSpinner lsScanReset = pu.makeSpinnerFloat(1, 100, 0.25, // practical lower limit of 1ms
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_RESET, 3);
lsScanReset.addChangeListener(PanelUtils.coerceToQuarterIntegers(lsScanReset));
pu.addListenerLast(lsScanReset, recalculateTimingDisplayCL);
lightSheetPanel_.add(lsScanReset, "wrap");
lightSheetPanel_.add(new JLabel("Scan settle time [ms]:"));
JSpinner lsScanSettle = pu.makeSpinnerFloat(0.25, 100, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_SETTLE, 1);
lsScanSettle.addChangeListener(PanelUtils.coerceToQuarterIntegers(lsScanSettle));
pu.addListenerLast(lsScanSettle, recalculateTimingDisplayCL);
lightSheetPanel_.add(lsScanSettle, "wrap");
lightSheetPanel_.add(new JLabel("Shutter width [\u00B5m]:"));
JSpinner lsShutterWidth = pu.makeSpinnerFloat(0.1, 100, 1,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_WIDTH, 5);
pu.addListenerLast(lsShutterWidth, recalculateTimingDisplayCL);
lightSheetPanel_.add(lsShutterWidth);
// lightSheetPanel_.add(new JLabel("1 / (shutter speed):"));
// JSpinner lsShutterSpeed = pu.makeSpinnerInteger(1, 10,
// Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_SPEED, 1);
// lightSheetPanel_.add(lsShutterSpeed, "wrap");
// end light sheet controls
// start "normal" (not light sheet) controls
normalPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"4[]8"));
// out of order so we can reference it
desiredSlicePeriod_ = pu.makeSpinnerFloat(1, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_SLICE_PERIOD, 30);
minSlicePeriodCB_ = pu.makeCheckBox("Minimize slice period",
Properties.Keys.PREFS_MINIMIZE_SLICE_PERIOD, panelName_, false);
minSlicePeriodCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean doMin = minSlicePeriodCB_.isSelected();
desiredSlicePeriod_.setEnabled(!doMin);
desiredSlicePeriodLabel_.setEnabled(!doMin);
recalculateSliceTiming(false);
}
});
normalPanel_.add(minSlicePeriodCB_, "span 2, wrap");
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredSlicePeriodLabel_ = new JLabel("Slice period [ms]:");
normalPanel_.add(desiredSlicePeriodLabel_);
normalPanel_.add(desiredSlicePeriod_, "wrap");
desiredSlicePeriod_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredSlicePeriod_));
desiredSlicePeriod_.addChangeListener(recalculateTimingDisplayCL);
// special field that is enabled/disabled depending on whether advanced timing is enabled
desiredLightExposureLabel_ = new JLabel("Sample exposure [ms]:");
normalPanel_.add(desiredLightExposureLabel_);
desiredLightExposure_ = pu.makeSpinnerFloat(1.0, 1000, 0.25,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_EXPOSURE, 8.5);
desiredLightExposure_.addChangeListener(PanelUtils.coerceToQuarterIntegers(desiredLightExposure_));
desiredLightExposure_.addChangeListener(recalculateTimingDisplayCL);
normalPanel_.add(desiredLightExposure_);
// end normal simple slice timing controls
slicePanelContainer_ = new JPanel(new MigLayout("", "0[center]0", "0[]0"));
slicePanelContainer_.add(getSPIMCameraMode() == CameraModes.Keys.LIGHT_SHEET ?
lightSheetPanel_ : normalPanel_, "growx");
slicePanel_.add(slicePanelContainer_, "span 2, center, wrap");
// special checkbox to use the advanced timing settings
// action handler added below after defining components it enables/disables
advancedSliceTimingCB_ = pu.makeCheckBox("Use advanced timing settings",
Properties.Keys.PREFS_ADVANCED_SLICE_TIMING, panelName_, false);
slicePanel_.add(advancedSliceTimingCB_, "span 2, left");
// end slice sub-panel
// start advanced slice timing frame
// visibility of this frame is controlled from advancedTiming checkbox
// this frame is separate from main plugin window
sliceFrameAdvanced_ = new MMFrame();
sliceFrameAdvanced_.setTitle("Advanced timing");
sliceFrameAdvanced_.loadPosition(100, 100);
sliceAdvancedPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
sliceFrameAdvanced_.add(sliceAdvancedPanel_);
class SliceFrameAdapter extends WindowAdapter {
@Override
public void windowClosing(WindowEvent e) {
advancedSliceTimingCB_.setSelected(false);
sliceFrameAdvanced_.savePosition();
}
}
sliceFrameAdvanced_.addWindowListener(new SliceFrameAdapter());
JLabel scanDelayLabel = new JLabel("Delay before scan [ms]:");
sliceAdvancedPanel_.add(scanDelayLabel);
delayScan_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_SCAN, 0);
delayScan_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayScan_));
delayScan_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(delayScan_, "wrap");
JLabel lineScanLabel = new JLabel("Lines scans per slice:");
sliceAdvancedPanel_.add(lineScanLabel);
numScansPerSlice_ = pu.makeSpinnerInteger(1, 1000,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_NUM_SCANSPERSLICE, 1);
numScansPerSlice_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(numScansPerSlice_, "wrap");
JLabel lineScanPeriodLabel = new JLabel("Line scan duration [ms]:");
sliceAdvancedPanel_.add(lineScanPeriodLabel);
lineScanDuration_ = pu.makeSpinnerFloat(1, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_SCAN, 10);
lineScanDuration_.addChangeListener(PanelUtils.coerceToQuarterIntegers(lineScanDuration_));
lineScanDuration_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(lineScanDuration_, "wrap");
JLabel delayLaserLabel = new JLabel("Delay before laser [ms]:");
sliceAdvancedPanel_.add(delayLaserLabel);
delayLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_LASER, 0);
delayLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayLaser_));
delayLaser_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(delayLaser_, "wrap");
JLabel durationLabel = new JLabel("Laser trig duration [ms]:");
sliceAdvancedPanel_.add(durationLabel);
durationLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_LASER, 1);
durationLaser_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationLaser_));
durationLaser_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(durationLaser_, "span 2, wrap");
JLabel delayLabel = new JLabel("Delay before camera [ms]:");
sliceAdvancedPanel_.add(delayLabel);
delayCamera_ = pu.makeSpinnerFloat(0, 10000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DELAY_CAMERA, 0);
delayCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(delayCamera_));
delayCamera_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(delayCamera_, "wrap");
JLabel cameraLabel = new JLabel("Camera trig duration [ms]:");
sliceAdvancedPanel_.add(cameraLabel);
durationCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB},
Properties.Keys.SPIM_DURATION_CAMERA, 0);
durationCamera_.addChangeListener(PanelUtils.coerceToQuarterIntegers(durationCamera_));
durationCamera_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(durationCamera_, "wrap");
JLabel exposureLabel = new JLabel("Camera exposure [ms]:");
sliceAdvancedPanel_.add(exposureLabel);
exposureCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ADVANCED_CAMERA_EXPOSURE, 10f);
exposureCamera_.addChangeListener(recalculateTimingDisplayCL);
sliceAdvancedPanel_.add(exposureCamera_, "wrap");
alternateBeamScanCB_ = pu.makeCheckBox("Alternate scan direction",
Properties.Keys.PREFS_SCAN_OPPOSITE_DIRECTIONS, panelName_, false);
sliceAdvancedPanel_.add(alternateBeamScanCB_, "center, span 2, wrap");
simpleTimingComponents_ = new JComponent[]{ desiredLightExposure_,
minSlicePeriodCB_, desiredSlicePeriodLabel_,
desiredLightExposureLabel_};
final JComponent[] advancedTimingComponents = {
delayScan_, numScansPerSlice_, lineScanDuration_,
delayLaser_, durationLaser_, delayCamera_,
durationCamera_, exposureCamera_, alternateBeamScanCB_};
PanelUtils.componentsSetEnabled(advancedTimingComponents, advancedSliceTimingCB_.isSelected());
PanelUtils.componentsSetEnabled(simpleTimingComponents_, !advancedSliceTimingCB_.isSelected());
// this action listener takes care of enabling/disabling inputs
// of the advanced slice timing window
// we call this to get GUI looking right
ItemListener sliceTimingDisableGUIInputs = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
// set other components in this advanced timing frame
PanelUtils.componentsSetEnabled(advancedTimingComponents, enabled);
// also control some components in main volume settings sub-panel
PanelUtils.componentsSetEnabled(simpleTimingComponents_, !enabled);
desiredSlicePeriod_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
desiredSlicePeriodLabel_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected());
updateDurationLabels();
}
};
// this action listener shows/hides the advanced timing frame
ActionListener showAdvancedTimingFrame = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean enabled = advancedSliceTimingCB_.isSelected();
if (enabled) {
sliceFrameAdvanced_.setVisible(enabled);
}
}
};
sliceFrameAdvanced_.pack();
sliceFrameAdvanced_.setResizable(false);
// end slice Frame
// start repeat (time lapse) sub-panel
timepointPanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]",
"[]8[]"));
useTimepointsCB_ = pu.makeCheckBox("Time points",
Properties.Keys.PREFS_USE_TIMEPOINTS, panelName_, false);
useTimepointsCB_.setToolTipText("Perform a time-lapse acquisition");
useTimepointsCB_.setEnabled(true);
useTimepointsCB_.setFocusPainted(false);
ComponentTitledBorder componentBorder =
new ComponentTitledBorder(useTimepointsCB_, timepointPanel_,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
timepointPanel_.setBorder(componentBorder);
ChangeListener recalculateTimeLapseDisplay = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateActualTimeLapseDurationLabel();
}
};
useTimepointsCB_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(new JLabel("Number:"));
numTimepoints_ = pu.makeSpinnerInteger(1, 100000,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_NUM_ACQUISITIONS, 1);
numTimepoints_.addChangeListener(recalculateTimeLapseDisplay);
numTimepoints_.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
// update nrRepeats_ variable so the acquisition can be extended or shortened
// as long as we have separate timepoints
if (acquisitionRunning_.get() && getSavingSeparateFile()) {
nrRepeats_ = getNumTimepoints();
}
}
});
timepointPanel_.add(numTimepoints_, "wrap");
timepointPanel_.add(new JLabel("Interval [s]:"));
acquisitionInterval_ = pu.makeSpinnerFloat(0.1, 32000, 0.1,
Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_ACQUISITION_INTERVAL, 60);
acquisitionInterval_.addChangeListener(recalculateTimeLapseDisplay);
timepointPanel_.add(acquisitionInterval_, "wrap");
// enable/disable panel elements depending on checkbox state
useTimepointsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); // initialize
// end repeat sub-panel
// start savePanel
// TODO for now these settings aren't part of acquisition settings
// TODO consider whether that should be changed
final int textFieldWidth = 16;
savePanel_ = new JPanel(new MigLayout(
"",
"[right]10[center]8[left]",
"[]4[]"));
savePanel_.setBorder(PanelUtils.makeTitledBorder("Data Saving Settings"));
separateTimePointsCB_ = pu.makeCheckBox("Separate viewer / file for each time point",
Properties.Keys.PREFS_SEPARATE_VIEWERS_FOR_TIMEPOINTS, panelName_, false);
saveCB_ = pu.makeCheckBox("Save while acquiring",
Properties.Keys.PREFS_SAVE_WHILE_ACQUIRING, panelName_, false);
// make sure that when separate viewer is enabled then saving gets enabled too
separateTimePointsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (separateTimePointsCB_.isSelected() && !saveCB_.isSelected()) {
saveCB_.doClick(); // setSelected() won't work because need to call its listener
}
}
});
savePanel_.add(separateTimePointsCB_, "span 3, left, wrap");
savePanel_.add(saveCB_, "skip 1, span 2, center, wrap");
JLabel dirRootLabel = new JLabel ("Directory root:");
savePanel_.add(dirRootLabel);
DefaultFormatter formatter = new DefaultFormatter();
rootField_ = new JFormattedTextField(formatter);
rootField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_DIRECTORY_ROOT, "") );
rootField_.addPropertyChangeListener(new PropertyChangeListener() {
// will respond to commitEdit() as well as GUI edit on commit
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
rootField_.setColumns(textFieldWidth);
savePanel_.add(rootField_, "span 2");
JButton browseRootButton = new JButton();
browseRootButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
setRootDirectory(rootField_);
prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT,
rootField_.getText());
}
});
browseRootButton.setMargin(new Insets(2, 5, 2, 5));
browseRootButton.setText("...");
savePanel_.add(browseRootButton, "wrap");
JLabel namePrefixLabel = new JLabel();
namePrefixLabel.setText("Name prefix:");
savePanel_.add(namePrefixLabel);
prefixField_ = new JFormattedTextField(formatter);
prefixField_.setText( prefs_.getString(panelName_,
Properties.Keys.PLUGIN_NAME_PREFIX, "acq"));
prefixField_.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
prefs_.putString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX,
prefixField_.getText());
}
});
prefixField_.setColumns(textFieldWidth);
savePanel_.add(prefixField_, "span 2, wrap");
// since we use the name field even for acquisitions in RAM,
// we only need to gray out the directory-related components
final JComponent[] saveComponents = { browseRootButton, rootField_,
dirRootLabel };
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
saveCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(saveComponents, saveCB_.isSelected());
}
});
// end save panel
// start duration report panel
durationPanel_ = new JPanel(new MigLayout(
"",
"[right]6[left, 40%!]",
"[]5[]"));
durationPanel_.setBorder(PanelUtils.makeTitledBorder("Durations"));
durationPanel_.setPreferredSize(new Dimension(125, 0)); // fix width so it doesn't constantly change depending on text
durationPanel_.add(new JLabel("Slice:"));
actualSlicePeriodLabel_ = new JLabel();
durationPanel_.add(actualSlicePeriodLabel_, "wrap");
durationPanel_.add(new JLabel("Volume:"));
actualVolumeDurationLabel_ = new JLabel();
durationPanel_.add(actualVolumeDurationLabel_, "wrap");
durationPanel_.add(new JLabel("Total:"));
actualTimeLapseDurationLabel_ = new JLabel();
durationPanel_.add(actualTimeLapseDurationLabel_, "wrap");
// end duration report panel
buttonTestAcq_ = new JButton("Test Acquisition");
buttonTestAcq_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
runTestAcquisition(Devices.Sides.NONE);
}
});
buttonStart_ = new JToggleButton();
buttonStart_.setIconTextGap(6);
buttonStart_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isAcquisitionRequested()) {
stopAcquisition();
} else {
runAcquisition();
}
}
});
updateStartButton(); // call once to initialize, isSelected() will be false
// make the size of the test button match the start button (easier on the eye)
Dimension sizeStart = buttonStart_.getPreferredSize();
Dimension sizeTest = buttonTestAcq_.getPreferredSize();
sizeTest.height = sizeStart.height;
buttonTestAcq_.setPreferredSize(sizeTest);
acquisitionStatusLabel_ = new JLabel("");
acquisitionStatusLabel_.setBackground(prefixField_.getBackground());
acquisitionStatusLabel_.setOpaque(true);
updateAcquisitionStatus(AcquisitionStatus.NONE);
// Channel Panel (separate file for code)
multiChannelPanel_ = new MultiChannelSubPanel(gui, devices_, props_, prefs_);
multiChannelPanel_.addDurationLabelListener(this);
// Position Panel
final JPanel positionPanel = new JPanel();
positionPanel.setLayout(new MigLayout("flowx, fillx","[right]10[left][10][]","[]8[]"));
usePositionsCB_ = pu.makeCheckBox("Multiple positions (XY)",
Properties.Keys.PREFS_USE_MULTIPOSITION, panelName_, false);
usePositionsCB_.setToolTipText("Acquire datasest at multiple postions");
usePositionsCB_.setEnabled(true);
usePositionsCB_.setFocusPainted(false);
componentBorder =
new ComponentTitledBorder(usePositionsCB_, positionPanel,
BorderFactory.createLineBorder(ASIdiSPIM.borderColor));
positionPanel.setBorder(componentBorder);
usePositionsCB_.addChangeListener(recalculateTimingDisplayCL);
final JButton editPositionListButton = new JButton("Edit position list...");
editPositionListButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gui_.showXYPositionList();
}
});
positionPanel.add(editPositionListButton, "span 2, center");
// add empty fill space on right side of panel
positionPanel.add(new JLabel(""), "wrap, growx");
positionPanel.add(new JLabel("Post-move delay [ms]:"));
positionDelay_ = pu.makeSpinnerFloat(0.0, 10000.0, 100.0,
Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_POSITION_DELAY,
0.0);
positionPanel.add(positionDelay_, "wrap");
// enable/disable panel elements depending on checkbox state
usePositionsCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected());
}
});
PanelUtils.componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); // initialize
// end of Position panel
// checkbox to use navigation joystick settings or not
// an "orphan" UI element
navigationJoysticksCB_ = new JCheckBox("Use Navigation joystick settings");
navigationJoysticksCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, false));
navigationJoysticksCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateJoysticks();
prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS,
navigationJoysticksCB_.isSelected());
}
});
// checkbox to signal that autofocus should be used during acquisition
// another orphan UI element
useAutofocusCB_ = new JCheckBox("Autofocus during acquisition");
useAutofocusCB_.setSelected(prefs_.getBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, false));
useAutofocusCB_.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
prefs_.putBoolean(panelName_,
Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS,
useAutofocusCB_.isSelected());
}
});
// set up tabbed panels for GUI
// make 3 columns as own JPanels to get vertical space right
// in each column without dependencies on other columns
leftColumnPanel_ = new JPanel(new MigLayout(
"",
"[]",
"[]6[]10[]10[]"));
leftColumnPanel_.add(durationPanel_, "split 2");
leftColumnPanel_.add(timepointPanel_, "wrap, growx");
leftColumnPanel_.add(savePanel_, "wrap");
leftColumnPanel_.add(new JLabel("Acquisition mode: "), "split 2, right");
AcquisitionModes acqModes = new AcquisitionModes(devices_, prefs_);
spimMode_ = acqModes.getComboBox();
spimMode_.addActionListener(recalculateTimingDisplayAL);
leftColumnPanel_.add(spimMode_, "left, wrap");
leftColumnPanel_.add(buttonStart_, "split 3, left");
leftColumnPanel_.add(new JLabel(" "));
leftColumnPanel_.add(buttonTestAcq_, "wrap");
leftColumnPanel_.add(new JLabel("Status:"), "split 2, left");
leftColumnPanel_.add(acquisitionStatusLabel_);
centerColumnPanel_ = new JPanel(new MigLayout("", "[]", "[]"));
centerColumnPanel_.add(positionPanel, "growx, wrap");
centerColumnPanel_.add(multiChannelPanel_, "wrap");
centerColumnPanel_.add(navigationJoysticksCB_, "wrap");
centerColumnPanel_.add(useAutofocusCB_);
rightColumnPanel_ = new JPanel(new MigLayout("", "[center]0", "[]0[]"));
rightColumnPanel_.add(volPanel_, "growx, wrap");
rightColumnPanel_.add(slicePanel_, "growx");
// add the column panels to the main panel
this.add(leftColumnPanel_);
this.add(centerColumnPanel_);
this.add(rightColumnPanel_);
// properly initialize the advanced slice timing
advancedSliceTimingCB_.addItemListener(sliceTimingDisableGUIInputs);
sliceTimingDisableGUIInputs.itemStateChanged(null);
advancedSliceTimingCB_.addActionListener(showAdvancedTimingFrame);
// included is calculating slice timing
updateDurationLabels();
}//end constructor
private void updateJoysticks() {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().
doJoystickSettings(navigationJoysticksCB_.isSelected());
}
}
public final void updateDurationLabels() {
updateActualSlicePeriodLabel();
updateActualVolumeDurationLabel();
updateActualTimeLapseDurationLabel();
}
private void updateCalibrationOffset(final Sides side,
final AutofocusUtils.FocusResult score) {
if (score.getFocusSuccess()) {
double offsetDelta = score.getOffsetDelta();
double maxDelta = props_.getPropValueFloat(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_MAXOFFSETCHANGE);
if (Math.abs(offsetDelta) <= maxDelta) {
ASIdiSPIM.getFrame().getSetupPanel(side).updateCalibrationOffset(score);
} else {
ReportingUtils.logMessage("autofocus successful for side " + side + " but offset change too much to automatically update");
}
}
}
public SliceTiming getSliceTiming() {
return sliceTiming_;
}
/**
* Sets the acquisition name prefix programmatically.
* Added so that name prefix can be changed from a script.
* @param acqName
*/
public void setAcquisitionNamePrefix(String acqName) {
prefixField_.setText(acqName);
}
private void updateStartButton() {
boolean started = isAcquisitionRequested();
buttonStart_.setSelected(started);
buttonStart_.setText(started ? "Stop Acquisition!" : "Start Acquisition!");
buttonStart_.setBackground(started ? Color.red : Color.green);
buttonStart_.setIcon(started ?
SwingResourceManager.
getIcon(MMStudio.class,
"/org/micromanager/icons/cancel.png")
: SwingResourceManager.getIcon(MMStudio.class,
"/org/micromanager/icons/arrow_right.png"));
buttonTestAcq_.setEnabled(!started);
}
/**
* @return CameraModes.Keys value from Camera panel
* (internal, edge, overlap, pseudo-overlap, light sheet)
*/
private CameraModes.Keys getSPIMCameraMode() {
CameraModes.Keys val = null;
try {
val = ASIdiSPIM.getFrame().getSPIMCameraMode();
} catch (Exception ex) {
val = CameraModes.getKeyFromPrefCode(prefs_.getInt(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_MODE, 0));
}
return val;
}
/**
* convenience method to avoid having to regenerate acquisition settings
*/
private int getNumTimepoints() {
if (useTimepointsCB_.isSelected()) {
return (Integer) numTimepoints_.getValue();
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public int getNumSides() {
if (numSides_.getSelectedIndex() == 1) {
return 2;
} else {
return 1;
}
}
/**
* convenience method to avoid having to regenerate acquisition settings
* public for API use
*/
public boolean isFirstSideA() {
return ((String) firstSide_.getSelectedItem()).equals("A");
}
/**
* convenience method to avoid having to regenerate acquisition settings.
* public for API use
*/
public double getTimepointInterval() {
return PanelUtils.getSpinnerFloatValue(acquisitionInterval_);
}
/**
* Gathers all current acquisition settings into dedicated POD object
* @return
*/
public AcquisitionSettings getCurrentAcquisitionSettings() {
AcquisitionSettings acqSettings = new AcquisitionSettings();
acqSettings.spimMode = getAcquisitionMode();
acqSettings.isStageScanning = (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN
|| acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED
|| acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_UNIDIRECTIONAL);
acqSettings.useTimepoints = useTimepointsCB_.isSelected();
acqSettings.numTimepoints = getNumTimepoints();
acqSettings.timepointInterval = getTimepointInterval();
acqSettings.useMultiPositions = usePositionsCB_.isSelected();
acqSettings.useChannels = multiChannelPanel_.isMultiChannel();
acqSettings.channelMode = multiChannelPanel_.getChannelMode();
acqSettings.numChannels = multiChannelPanel_.getNumChannels();
acqSettings.channels = multiChannelPanel_.getUsedChannels();
acqSettings.channelGroup = multiChannelPanel_.getChannelGroup();
acqSettings.useAutofocus = useAutofocusCB_.isSelected();
acqSettings.numSides = getNumSides();
acqSettings.firstSideIsA = isFirstSideA();
acqSettings.delayBeforeSide = PanelUtils.getSpinnerFloatValue(delaySide_);
acqSettings.numSlices = (Integer) numSlices_.getValue();
acqSettings.stepSizeUm = PanelUtils.getSpinnerFloatValue(stepSize_);
acqSettings.minimizeSlicePeriod = minSlicePeriodCB_.isSelected();
acqSettings.desiredSlicePeriod = PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
acqSettings.desiredLightExposure = PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
acqSettings.centerAtCurrentZ = false;
acqSettings.sliceTiming = sliceTiming_;
acqSettings.cameraMode = getSPIMCameraMode();
acqSettings.hardwareTimepoints = false; // when running acquisition we check this and set to true if needed
acqSettings.separateTimepoints = getSavingSeparateFile();
return acqSettings;
}
/**
* gets the correct value for the slice timing's sliceDuration field
* based on other values of slice timing
* @param s
* @return
*/
private float getSliceDuration(final SliceTiming s) {
// slice duration is the max out of the scan time, laser time, and camera time
return Math.max(Math.max(
s.scanDelay +
(s.scanPeriod * s.scanNum), // scan time
s.laserDelay + s.laserDuration // laser time
),
s.cameraDelay + s.cameraDuration // camera time
);
}
/**
* gets the slice timing from advanced settings
* (normally these advanced settings are read-only and we populate them
* ourselves depending on the user's requests and our algorithm below)
* @return
*/
private SliceTiming getTimingFromAdvancedSettings() {
SliceTiming s = new SliceTiming();
s.scanDelay = PanelUtils.getSpinnerFloatValue(delayScan_);
s.scanNum = (Integer) numScansPerSlice_.getValue();
s.scanPeriod = PanelUtils.getSpinnerFloatValue(lineScanDuration_);
s.laserDelay = PanelUtils.getSpinnerFloatValue(delayLaser_);
s.laserDuration = PanelUtils.getSpinnerFloatValue(durationLaser_);
s.cameraDelay = PanelUtils.getSpinnerFloatValue(delayCamera_);
s.cameraDuration = PanelUtils.getSpinnerFloatValue(durationCamera_);
s.cameraExposure = PanelUtils.getSpinnerFloatValue(exposureCamera_);
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
* @param showWarnings true to warn user about needing to change slice period
* @return
*/
private SliceTiming getTimingFromPeriodAndLightExposure(boolean showWarnings) {
// uses algorithm Jon worked out in Octave code; each slice period goes like this:
// 1. camera readout time (none if in overlap mode, 0.25ms in PCO pseudo-overlap)
// 2. any extra delay time
// 3. camera reset time
// 4. start scan 0.25ms before camera global exposure and shifted up in time to account for delay introduced by Bessel filter
// 5. turn on laser as soon as camera global exposure, leave laser on for desired light exposure time
// 7. end camera exposure in final 0.25ms, post-filter scan waveform also ends now
final float scanLaserBufferTime = MyNumberUtils.roundToQuarterMs(0.25f); // below assumed to be multiple of 0.25ms
final Color foregroundColorOK = Color.BLACK;
final Color foregroundColorError = Color.RED;
final Component elementToColor = desiredSlicePeriod_.getEditor().getComponent(0);
SliceTiming s = new SliceTiming();
final float cameraResetTime = computeCameraResetTime(); // recalculate for safety, 0 for light sheet
final float cameraReadoutTime = computeCameraReadoutTime(); // recalculate for safety, 0 for overlap
// can we use acquisition settings directly? because they may be in flux
final AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final float cameraReadout_max = MyNumberUtils.ceilToQuarterMs(cameraReadoutTime);
final float cameraReset_max = MyNumberUtils.ceilToQuarterMs(cameraResetTime);
// we will wait cameraReadout_max before triggering camera, then wait another cameraReset_max for global exposure
// this will also be in 0.25ms increment
final float globalExposureDelay_max = cameraReadout_max + cameraReset_max;
final float laserDuration = MyNumberUtils.roundToQuarterMs(acqSettings.desiredLightExposure);
final float scanDuration = laserDuration + 2*scanLaserBufferTime;
// scan will be longer than laser by 0.25ms at both start and end
// account for delay in scan position due to Bessel filter by starting the scan slightly earlier
// than we otherwise would (Bessel filter selected b/c stretches out pulse without any ripples)
// delay to start is (empirically) 0.07ms + 0.25/(freq in kHz)
// delay to midpoint is empirically 0.38/(freq in kHz)
// group delay for 5th-order bessel filter ~0.39/freq from theory and ~0.4/freq from IC datasheet
final float scanFilterFreq = Math.max(props_.getPropValueFloat(Devices.Keys.GALVOA, Properties.Keys.SCANNER_FILTER_X),
props_.getPropValueFloat(Devices.Keys.GALVOB, Properties.Keys.SCANNER_FILTER_X));
float scanDelayFilter = 0;
if (scanFilterFreq != 0) {
scanDelayFilter = MyNumberUtils.roundToQuarterMs(0.39f/scanFilterFreq);
}
// If the PLogic card is used, account for 0.25ms delay it introduces to
// the camera and laser trigger signals => subtract 0.25ms from the scanner delay
// (start scanner 0.25ms later than it would be otherwise)
// this time-shift opposes the Bessel filter delay
// scanDelayFilter won't be negative unless scanFilterFreq is more than 3kHz which shouldn't happen
if (devices_.isValidMMDevice(Devices.Keys.PLOGIC)) {
scanDelayFilter -= 0.25f;
}
s.scanDelay = globalExposureDelay_max - scanLaserBufferTime // start scan 0.25ms before camera's global exposure
- scanDelayFilter; // start galvo moving early due to card's Bessel filter and delay of TTL signals via PLC
s.scanNum = 1;
s.scanPeriod = scanDuration;
s.laserDelay = globalExposureDelay_max; // turn on laser as soon as camera's global exposure is reached
s.laserDuration = laserDuration;
s.cameraDelay = cameraReadout_max; // camera must readout last frame before triggering again
// figure out desired time for camera to be exposing (including reset time)
// because both camera trigger and laser on occur on 0.25ms intervals (i.e. we may not
// trigger the laser until 0.24ms after global exposure) use cameraReset_max
final float cameraExposure = cameraReset_max + laserDuration;
switch (acqSettings.cameraMode) {
case EDGE:
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = cameraExposure + 0.1f; // add 0.1ms as safety margin, may require adding an additional 0.25ms to slice
// slight delay between trigger and actual exposure start
// is included in exposure time for Hamamatsu and negligible for Andor and PCO cameras
// ensure not to miss triggers by not being done with readout in time for next trigger, add 0.25ms if needed
if (getSliceDuration(s) < (s.cameraExposure + cameraReadoutTime)) {
ReportingUtils.logDebugMessage("Added 0.25ms in edge-trigger mode to make sure camera exposure long enough without dropping frames");
s.cameraDelay += 0.25f;
s.laserDelay += 0.25f;
s.scanDelay += 0.25f;
}
break;
case LEVEL: // AKA "bulb mode", TTL rising starts exposure, TTL falling ends it
s.cameraDuration = MyNumberUtils.ceilToQuarterMs(cameraExposure);
s.cameraExposure = 1; // doesn't really matter, controlled by TTL
break;
case OVERLAP: // only Hamamatsu or Andor
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = 1; // doesn't really matter, controlled by interval between triggers
break;
case PSEUDO_OVERLAP: // only PCO, enforce 0.25ms between end exposure and start of next exposure by triggering camera 0.25ms into the slice
s.cameraDuration = 1; // doesn't really matter, 1ms should be plenty fast yet easy to see for debugging
s.cameraExposure = getSliceDuration(s) - s.cameraDelay; // s.cameraDelay should be 0.25ms
if (!MyNumberUtils.floatsEqual(s.cameraDelay, 0.25f)) {
MyDialogUtils.showError("Camera delay should be 0.25ms for pseudo-overlap mode.");
}
break;
case LIGHT_SHEET:
// each slice period goes like this:
// 1. scan reset time (use to add any extra settling time to the start of each slice)
// 2. start scan, wait scan settle time
// 3. trigger camera/laser when scan settle time elapses
// 4. scan for total of exposure time plus readout time (total time some row is exposing) plus settle time plus extra 0.25ms to prevent artifacts
// 5. laser turns on 0.25ms before camera trigger and stays on until exposure is ending
// TODO revisit this after further experimentation
s.cameraDuration = 1; // only need to trigger camera
final float shutterWidth = props_.getPropValueFloat(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_WIDTH);
final int shutterSpeed = 1; // props_.getPropValueInteger(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SHUTTER_SPEED);
float pixelSize = (float) core_.getPixelSizeUm();
if (pixelSize < 1e-6) { // can't compare equality directly with floating point values so call < 1e-9 is zero or negative
pixelSize = 0.1625f; // default to pixel size of 40x with sCMOS = 6.5um/40
}
final double rowReadoutTime = getRowReadoutTime();
s.cameraExposure = (float) (rowReadoutTime * shutterWidth / pixelSize * shutterSpeed);
final float totalExposure_max = MyNumberUtils.ceilToQuarterMs(cameraReadoutTime + s.cameraExposure + 0.05f); // 50-300us extra cushion time
final float scanSettle = props_.getPropValueFloat(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_SETTLE);
final float scanReset = props_.getPropValueFloat(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_LS_SCAN_RESET);
s.scanDelay = scanReset - scanDelayFilter;
s.scanPeriod = scanSettle + totalExposure_max + scanLaserBufferTime;
s.cameraDelay = scanReset + scanSettle;
s.laserDelay = s.cameraDelay - scanLaserBufferTime; // trigger laser just before camera to make sure it's on already
s.laserDuration = totalExposure_max + scanLaserBufferTime; // laser will turn off as exposure is ending
break;
case INTERNAL:
default:
if (showWarnings) {
MyDialogUtils.showError("Invalid camera mode");
}
s.valid = false;
break;
}
// fix corner case of negative calculated scanDelay
if (s.scanDelay < 0) {
s.cameraDelay -= s.scanDelay;
s.laserDelay -= s.scanDelay;
s.scanDelay = 0; // same as (-= s.scanDelay)
}
// if a specific slice period was requested, add corresponding delay to scan/laser/camera
elementToColor.setForeground(foregroundColorOK);
if (!acqSettings.minimizeSlicePeriod) {
float globalDelay = acqSettings.desiredSlicePeriod - getSliceDuration(s); // both should be in 0.25ms increments // TODO fix;
if (acqSettings.cameraMode == CameraModes.Keys.LIGHT_SHEET) {
globalDelay = 0;
}
if (globalDelay < 0) {
globalDelay = 0;
if (showWarnings) { // only true when user has specified period that is unattainable
MyDialogUtils.showError(
"Increasing slice period to meet laser exposure constraint\n"
+ "(time required for camera readout; readout time depends on ROI).");
elementToColor.setForeground(foregroundColorError);
}
}
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// // Add 0.25ms to globalDelay if it is 0 and we are on overlap mode and scan has been shifted forward
// // basically the last 0.25ms of scan time that would have determined the slice period isn't
// // there any more because the scan time is moved up => add in the 0.25ms at the start of the slice
// // in edge or level trigger mode the camera trig falling edge marks the end of the slice period
// // not sure if PCO pseudo-overlap needs this, probably not because adding 0.25ms overhead in that case
// if (MyNumberUtils.floatsEqual(cameraReadout_max, 0f) // true iff overlap being used
// && (scanDelayFilter > 0.01f)) {
// globalDelay += 0.25f;
// fix corner case of (exposure time + readout time) being greater than the slice duration
// most of the time the slice duration is already larger
float globalDelay = MyNumberUtils.ceilToQuarterMs((s.cameraExposure + cameraReadoutTime) - getSliceDuration(s));
if (globalDelay > 0) {
s.scanDelay += globalDelay;
s.cameraDelay += globalDelay;
s.laserDelay += globalDelay;
}
// update the slice duration based on our new values
s.sliceDuration = getSliceDuration(s);
return s;
}
/**
* Re-calculate the controller's timing settings for "easy timing" mode.
* Changes panel variable sliceTiming_.
* The controller's properties will be set as needed
* @param showWarnings will show warning if the user-specified slice period too short
* or if cameras aren't assigned
*/
private void recalculateSliceTiming(boolean showWarnings) {
if(!checkCamerasAssigned(showWarnings)) {
return;
}
// if user is providing his own slice timing don't change it
if (advancedSliceTimingCB_.isSelected()) {
return;
}
sliceTiming_ = getTimingFromPeriodAndLightExposure(showWarnings);
PanelUtils.setSpinnerFloatValue(delayScan_, sliceTiming_.scanDelay);
numScansPerSlice_.setValue(sliceTiming_.scanNum);
PanelUtils.setSpinnerFloatValue(lineScanDuration_, sliceTiming_.scanPeriod);
PanelUtils.setSpinnerFloatValue(delayLaser_, sliceTiming_.laserDelay);
PanelUtils.setSpinnerFloatValue(durationLaser_, sliceTiming_.laserDuration);
PanelUtils.setSpinnerFloatValue(delayCamera_, sliceTiming_.cameraDelay);
PanelUtils.setSpinnerFloatValue(durationCamera_, sliceTiming_.cameraDuration );
PanelUtils.setSpinnerFloatValue(exposureCamera_, sliceTiming_.cameraExposure );
}
/**
* Update the displayed slice period.
*/
private void updateActualSlicePeriodLabel() {
recalculateSliceTiming(false);
actualSlicePeriodLabel_.setText(
NumberUtils.doubleToDisplayString(
sliceTiming_.sliceDuration) +
" ms");
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels. However, does not include for multiple positions.
* @return duration in ms
*/
public double computeActualVolumeDuration(AcquisitionSettings acqSettings) {
final MultichannelModes.Keys channelMode = acqSettings.channelMode;
final int numChannels = acqSettings.numChannels;
final int numSides = acqSettings.numSides;
final float delayBeforeSide = acqSettings.delayBeforeSide;
int numCameraTriggers = acqSettings.numSlices;
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
numCameraTriggers += 1;
}
// stackDuration is per-side, per-channel, per-position
final double stackDuration = numCameraTriggers * acqSettings.sliceTiming.sliceDuration;
if (acqSettings.isStageScanning) {
final double accelerationX = controller_.computeScanAcceleration(
controller_.computeScanSpeed(acqSettings)) + 1; // extra 1 for rounding up that often happens in controller
final double rampDuration = delayBeforeSide + accelerationX;
final double retraceSpeed = 0.67f*props_.getPropValueFloat(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MAX_MOTOR_SPEED); // retrace speed set to 67% of max speed in firmware
final double speedFactor = ASIdiSPIM.oSPIM ? (2 / Math.sqrt(3.)) : Math.sqrt(2.);
final double scanDistance = acqSettings.numSlices * acqSettings.stepSizeUm * speedFactor;
final double retraceTime = scanDistance/retraceSpeed/1000;
// TODO double-check these calculations below, at least they are better than before ;-)
if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN) {
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return retraceTime + (numSides * ((rampDuration * 2) + (stackDuration * numChannels)));
} else { // "normal" stage scan with volume channel switching
if (numSides == 1) {
// single-view so will retrace at beginning of each channel
return ((rampDuration * 2) + stackDuration + retraceTime) * numChannels;
} else {
// will only retrace at very start/end
return retraceTime + (numSides * ((rampDuration * 2) + stackDuration) * numChannels);
}
}
} else if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_UNIDIRECTIONAL) {
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return ((rampDuration * 2) + (stackDuration * numChannels) + retraceTime) * numSides;
} else { // "normal" stage scan with volume channel switching
return ((rampDuration * 2) + stackDuration + retraceTime) * numChannels * numSides;
}
} else { // interleaved mode => one-way pass collecting both sides
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
// single pass with all sides and channels
return retraceTime + (rampDuration * 2 + stackDuration * numSides * numChannels);
} else { // one-way pass collecting both sides, then rewind for next channel
return ((rampDuration * 2) + (stackDuration * numSides) + retraceTime) * numChannels;
}
}
} else { // piezo scan
double channelSwitchDelay = 0;
if (channelMode == MultichannelModes.Keys.VOLUME) {
channelSwitchDelay = 500; // estimate channel switching overhead time as 0.5s
// actual value will be hardware-dependent
}
if (channelMode == MultichannelModes.Keys.SLICE_HW) {
return numSides * (delayBeforeSide + stackDuration * numChannels); // channelSwitchDelay = 0
} else {
return numSides * numChannels
* (delayBeforeSide + stackDuration)
+ (numChannels - 1) * channelSwitchDelay;
}
}
}
/**
* Compute the timepoint duration in ms. Only difference from computeActualVolumeDuration()
* is that it also takes into account the multiple positions, if any.
* @return duration in ms
*/
private double computeTimepointDuration() {
AcquisitionSettings acqSettings = getCurrentAcquisitionSettings();
final double volumeDuration = computeActualVolumeDuration(acqSettings);
if (acqSettings.useMultiPositions) {
try {
// use 1.5 seconds motor move between positions
// (could be wildly off but was estimated using actual system
// and then slightly padded to be conservative to avoid errors
// where positions aren't completed in time for next position)
// could estimate the actual time by analyzing the position's relative locations
// and using the motor speed and acceleration time
return gui_.getPositionList().getNumberOfPositions() *
(volumeDuration + 1500 + PanelUtils.getSpinnerFloatValue(positionDelay_));
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
}
return volumeDuration;
}
/**
* Compute the volume duration in ms based on controller's timing settings.
* Includes time for multiple channels.
* @return duration in ms
*/
private double computeActualVolumeDuration() {
return computeActualVolumeDuration(getCurrentAcquisitionSettings());
}
/**
* Update the displayed volume duration.
*/
private void updateActualVolumeDurationLabel() {
double duration = computeActualVolumeDuration();
if (duration > 1000) {
actualVolumeDurationLabel_.setText(
NumberUtils.doubleToDisplayString(duration/1000d) +
" s"); // round to ms
} else {
actualVolumeDurationLabel_.setText(
NumberUtils.doubleToDisplayString(Math.round(10*duration)/10d) +
" ms"); // round to tenth of ms
}
}
/**
* Compute the time lapse duration
* @return duration in s
*/
private double computeActualTimeLapseDuration() {
double duration = (getNumTimepoints() - 1) * getTimepointInterval()
+ computeTimepointDuration()/1000;
return duration;
}
/**
* Update the displayed time lapse duration.
*/
private void updateActualTimeLapseDurationLabel() {
String s = "";
double duration = computeActualTimeLapseDuration();
if (duration < 60) { // less than 1 min
s += NumberUtils.doubleToDisplayString(duration) + " s";
} else if (duration < 60*60) { // between 1 min and 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/60)) + " min ";
s += NumberUtils.doubleToDisplayString(Math.round(duration % 60)) + " s";
} else { // longer than 1 hour
s += NumberUtils.doubleToDisplayString(Math.floor(duration/(60*60))) + " hr ";
s += NumberUtils.doubleToDisplayString(Math.round((duration % (60*60))/60)) + " min";
}
actualTimeLapseDurationLabel_.setText(s);
}
/**
* Computes the per-row readout time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing camera exposure in light sheet mode
* @return
*/
private double getRowReadoutTime() {
if (getNumSides() > 1) {
return Math.max(cameras_.getRowReadoutTime(Devices.Keys.CAMERAA),
cameras_.getRowReadoutTime(Devices.Keys.CAMERAB));
} else {
if (isFirstSideA()) {
return cameras_.getRowReadoutTime(Devices.Keys.CAMERAA);
} else {
return cameras_.getRowReadoutTime(Devices.Keys.CAMERAB);
}
}
}
/**
* Computes the reset time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraResetTime() {
CameraModes.Keys camMode = getSPIMCameraMode();
if (getNumSides() > 1) {
return Math.max(cameras_.computeCameraResetTime(Devices.Keys.CAMERAA, camMode),
cameras_.computeCameraResetTime(Devices.Keys.CAMERAB, camMode));
} else {
if (isFirstSideA()) {
return cameras_.computeCameraResetTime(Devices.Keys.CAMERAA, camMode);
} else {
return cameras_.computeCameraResetTime(Devices.Keys.CAMERAB, camMode);
}
}
}
/**
* Computes the readout time of the SPIM cameras set on Devices panel.
* Handles single-side operation.
* Needed for computing (semi-)optimized slice timing in "easy timing" mode.
* @return
*/
private float computeCameraReadoutTime() {
CameraModes.Keys camMode = getSPIMCameraMode();
if (getNumSides() > 1) {
return Math.max(cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode),
cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode));
} else {
if (isFirstSideA()) {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, camMode);
} else {
return cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, camMode);
}
}
}
/**
* Makes sure that cameras are assigned to the desired sides and display error message
* if not (e.g. if single-sided with side B first, then only checks camera for side B)
* @return true if cameras assigned, false if not
*/
private boolean checkCamerasAssigned(boolean showWarnings) {
String firstCamera, secondCamera;
final boolean firstSideA = isFirstSideA();
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
}
if (firstCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the first side (Imaging Path " +
(firstSideA ? "A" : "B") + ") on the Devices Panel");
}
return false;
}
if (getNumSides()> 1 && secondCamera == null) {
if (showWarnings) {
MyDialogUtils.showError("Please select a valid camera for the second side (Imaging Path " +
(firstSideA ? "B" : "A") + ") on the Devices Panel.");
}
return false;
}
return true;
}
/**
* used for updateAcquisitionStatus() calls
*/
private static enum AcquisitionStatus {
NONE,
ACQUIRING,
WAITING,
DONE,
}
private void updateAcquisitionStatus(AcquisitionStatus phase) {
updateAcquisitionStatus(phase, 0);
}
private void updateAcquisitionStatus(AcquisitionStatus phase, int secsToNextAcquisition) {
String text = "";
switch(phase) {
case NONE:
text = "No acquisition in progress.";
break;
case ACQUIRING:
text = "Acquiring time point "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints());
// TODO make sure the number of timepoints can't change during an acquisition
// (or maybe we make a hidden feature where the acquisition can be terminated by changing)
break;
case WAITING:
text = "Next timepoint ("
+ NumberUtils.intToDisplayString(numTimePointsDone_+1)
+ " of "
+ NumberUtils.intToDisplayString(getNumTimepoints())
+ ") in "
+ NumberUtils.intToDisplayString(secsToNextAcquisition)
+ " s.";
break;
case DONE:
text = "Acquisition finished with "
+ NumberUtils.intToDisplayString(numTimePointsDone_)
+ " time points.";
break;
default:
break;
}
acquisitionStatusLabel_.setText(text);
}
private boolean requiresPiezos(AcquisitionModes.Keys mode) {
switch (mode) {
case STAGE_SCAN:
case NONE:
case SLICE_SCAN_ONLY:
case STAGE_SCAN_INTERLEAVED:
case STAGE_SCAN_UNIDIRECTIONAL:
case NO_SCAN:
return false;
case PIEZO_SCAN_ONLY:
case PIEZO_SLICE_SCAN:
return true;
default:
MyDialogUtils.showError("Unspecified acquisition mode " + mode.toString());
return true;
}
}
/**
* runs a test acquisition with the following features:
* - not saved to disk
* - window can be closed without prompting to save
* - timepoints disabled
* - autofocus disabled
* @param side Devices.Sides.NONE to run as specified in acquisition tab,
* Devices.Side.A or B to run only that side
*/
public void runTestAcquisition(Devices.Sides side) {
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
updateStartButton();
boolean success = runAcquisitionPrivate(true, side);
if (!success) {
ReportingUtils.logError("Fatal error running test diSPIM acquisition.");
}
acquisitionRequested_.set(false);
acquisitionRunning_.set(false);
updateStartButton();
// deskew automatically if we were supposed to
AcquisitionModes.Keys spimMode = getAcquisitionMode();
if (spimMode == AcquisitionModes.Keys.STAGE_SCAN || spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED
|| spimMode == AcquisitionModes.Keys.STAGE_SCAN_UNIDIRECTIONAL) {
if (prefs_.getBoolean(MyStrings.PanelNames.DATAANALYSIS.toString(),
Properties.Keys.PLUGIN_DESKEW_AUTO_TEST, false)) {
ASIdiSPIM.getFrame().getDataAnalysisPanel().runDeskew(acquisitionPanel_);
}
}
}
/**
* Implementation of acquisition that orchestrates image
* acquisition itself rather than using the acquisition engine.
*
* This methods is public so that the ScriptInterface can call it
* Please do not access this yourself directly, instead use the API, e.g.
* import org.micromanager.asidispim.api.*;
* ASIdiSPIMInterface diSPIM = new ASIdiSPIMImplementation();
* diSPIM.runAcquisition();
*/
public void runAcquisition() {
class acqThread extends Thread {
acqThread(String threadName) {
super(threadName);
}
@Override
public void run() {
ReportingUtils.logDebugMessage("User requested start of diSPIM acquisition.");
if (isAcquisitionRequested()) { // don't allow acquisition to be requested again, just return
ReportingUtils.logError("another acquisition already running");
return;
}
cancelAcquisition_.set(false);
acquisitionRequested_.set(true);
ASIdiSPIM.getFrame().tabsSetEnabled(false);
updateStartButton();
boolean success = runAcquisitionPrivate(false, Devices.Sides.NONE);
if (!success) {
ReportingUtils.logError("Fatal error running diSPIM acquisition.");
}
acquisitionRequested_.set(false);
updateStartButton();
ASIdiSPIM.getFrame().tabsSetEnabled(true);
}
}
acqThread acqt = new acqThread("diSPIM Acquisition");
acqt.start();
}
private Color getChannelColor(int channelIndex) {
return (colors[channelIndex % colors.length]);
}
/**
* Actually runs the acquisition; does the dirty work of setting
* up the controller, the circular buffer, starting the cameras,
* grabbing the images and putting them into the acquisition, etc.
* @param testAcq true if running test acquisition only (see runTestAcquisition() javadoc)
* @param testAcqSide only applies to test acquisition, passthrough from runTestAcquisition()
* @return true if ran without any fatal errors.
*/
private boolean runAcquisitionPrivate(boolean testAcq, Devices.Sides testAcqSide) {
// sanity check, shouldn't call this unless we aren't running an acquisition
if (gui_.isAcquisitionRunning()) {
MyDialogUtils.showError("An acquisition is already running");
return false;
}
if (ASIdiSPIM.getFrame().getHardwareInUse()) {
MyDialogUtils.showError("Hardware is being used by something else (maybe autofocus?)");
return false;
}
boolean liveModeOriginally = gui_.isLiveModeOn();
if (liveModeOriginally) {
gui_.enableLiveMode(false);
}
// make sure slice timings are up to date
// do this automatically; we used to prompt user if they were out of date
// do this before getting snapshot of sliceTiming_ in acqSettings
recalculateSliceTiming(!minSlicePeriodCB_.isSelected());
if (!sliceTiming_.valid) {
MyDialogUtils.showError("Error in calculating the slice timing; is the camera mode set correctly?");
return false;
}
AcquisitionSettings acqSettingsOrig = getCurrentAcquisitionSettings();
if (acqSettingsOrig.cameraMode == CameraModes.Keys.LIGHT_SHEET
&& core_.getPixelSizeUm() < 1e-6) { // can't compare equality directly with floating point values so call < 1e-9 is zero or negative
ReportingUtils.showError("Need to configure pixel size in Micro-Manager to use light sheet mode.");
return false;
}
// if a test acquisition then only run single timpoint, no autofocus
// allow multi-positions for test acquisition for now, though perhaps this is not desirable
if (testAcq) {
acqSettingsOrig.useTimepoints = false;
acqSettingsOrig.numTimepoints = 1;
acqSettingsOrig.useAutofocus = false;
acqSettingsOrig.separateTimepoints = false;
// if called from the setup panels then the side will be specified
// so we can do an appropriate single-sided acquisition
// if called from the acquisition panel then NONE will be specified
// and run according to existing settings
if (testAcqSide != Devices.Sides.NONE) {
acqSettingsOrig.numSides = 1;
acqSettingsOrig.firstSideIsA = (testAcqSide == Devices.Sides.A);
}
// work around limitation of not being able to use PLogic per-volume switching with single side
// => do per-volume switching instead (only difference should be extra time to switch)
if (acqSettingsOrig.useChannels && acqSettingsOrig.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettingsOrig.numSides < 2) {
acqSettingsOrig.channelMode = MultichannelModes.Keys.VOLUME;
}
}
double volumeDuration = computeActualVolumeDuration(acqSettingsOrig);
double timepointDuration = computeTimepointDuration();
long timepointIntervalMs = Math.round(acqSettingsOrig.timepointInterval*1000);
// use hardware timing if < 1 second between timepoints
// experimentally need ~0.5 sec to set up acquisition, this gives a bit of cushion
// cannot do this in getCurrentAcquisitionSettings because of mutually recursive
// call with computeActualVolumeDuration()
if ( acqSettingsOrig.numTimepoints > 1
&& timepointIntervalMs < (timepointDuration + 750)
&& !acqSettingsOrig.isStageScanning) {
acqSettingsOrig.hardwareTimepoints = true;
}
if (acqSettingsOrig.useMultiPositions) {
if (acqSettingsOrig.hardwareTimepoints
|| ((acqSettingsOrig.numTimepoints > 1)
&& (timepointIntervalMs < timepointDuration*1.2))) {
// change to not hardwareTimepoints and warn user
// but allow acquisition to continue
acqSettingsOrig.hardwareTimepoints = false;
MyDialogUtils.showError("Timepoint interval may not be sufficient "
+ "depending on actual time required to change positions. "
+ "Proceed at your own risk.");
}
}
// now acqSettings should be read-only
final AcquisitionSettings acqSettings = acqSettingsOrig;
// generate string for log file
Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String acqSettingsJSON = gson.toJson(acqSettings);
// get MM device names for first/second cameras to acquire
String firstCamera, secondCamera;
Devices.Keys firstCameraKey, secondCameraKey;
boolean firstSideA = acqSettings.firstSideIsA;
if (firstSideA) {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
firstCameraKey = Devices.Keys.CAMERAA;
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
secondCameraKey = Devices.Keys.CAMERAB;
} else {
firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB);
firstCameraKey = Devices.Keys.CAMERAB;
secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA);
secondCameraKey = Devices.Keys.CAMERAA;
}
boolean sideActiveA, sideActiveB;
final boolean twoSided = acqSettings.numSides > 1;
if (twoSided) {
sideActiveA = true;
sideActiveB = true;
} else {
secondCamera = null;
if (firstSideA) {
sideActiveA = true;
sideActiveB = false;
} else {
sideActiveA = false;
sideActiveB = true;
}
}
if (sideActiveA) {
if (!devices_.isValidMMDevice(Devices.Keys.CAMERAA)) {
MyDialogUtils.showError("Using side A but no camera specified for that side.");
return false;
}
if (!CameraModes.getValidModeKeys(devices_.getMMDeviceLibrary(Devices.Keys.CAMERAA)).contains(getSPIMCameraMode())) {
MyDialogUtils.showError("Camera trigger mode set to " + getSPIMCameraMode().toString() + " but camera A doesn't support it.");
return false;
}
if (!devices_.isValidMMDevice(Devices.Keys.GALVOA)) {
MyDialogUtils.showError("Using side A but no scanner specified for that side.");
return false;
}
if (requiresPiezos(acqSettings.spimMode) && !devices_.isValidMMDevice(Devices.Keys.PIEZOA)) {
MyDialogUtils.showError("Using side A and acquisition mode requires piezos but no piezo specified for that side.");
return false;
}
}
if (sideActiveB) {
if (!devices_.isValidMMDevice(Devices.Keys.CAMERAB)) {
MyDialogUtils.showError("Using side B but no camera specified for that side.");
return false;
}
if (!CameraModes.getValidModeKeys(devices_.getMMDeviceLibrary(Devices.Keys.CAMERAB)).contains(getSPIMCameraMode())) {
MyDialogUtils.showError("Camera trigger mode set to " + getSPIMCameraMode().toString() + " but camera B doesn't support it.");
return false;
}
if (!devices_.isValidMMDevice(Devices.Keys.GALVOB)) {
MyDialogUtils.showError("Using side B but no scanner specified for that side.");
return false;
}
if (requiresPiezos(acqSettings.spimMode) && !devices_.isValidMMDevice(Devices.Keys.PIEZOB)) {
MyDialogUtils.showError("Using side B and acquisition mode requires piezos but no piezo specified for that side.");
return false;
}
}
boolean usingDemoCam = (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAA).equals(Devices.Libraries.DEMOCAM) && sideActiveA)
|| (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAB).equals(Devices.Libraries.DEMOCAM) && sideActiveB);
// set up channels
int nrChannelsSoftware = acqSettings.numChannels; // how many times we trigger the controller per stack
int nrSlicesSoftware = acqSettings.numSlices;
String originalChannelConfig = "";
boolean changeChannelPerVolumeSoftware = false;
if (acqSettings.useChannels) {
if (acqSettings.numChannels < 1) {
MyDialogUtils.showError("\"Channels\" is checked, but no channels are selected");
return false;
}
// get current channel so that we can restore it, then set channel appropriately
originalChannelConfig = multiChannelPanel_.getCurrentConfig();
switch (acqSettings.channelMode) {
case VOLUME:
changeChannelPerVolumeSoftware = true;
multiChannelPanel_.initializeChannelCycle();
break;
case VOLUME_HW:
case SLICE_HW:
if (acqSettings.numChannels == 1) { // only 1 channel selected so don't have to really use hardware switching
multiChannelPanel_.initializeChannelCycle();
multiChannelPanel_.selectNextChannel();
} else { // we have at least 2 channels
boolean success = controller_.setupHardwareChannelSwitching(acqSettings);
if (!success) {
MyDialogUtils.showError("Couldn't set up slice hardware channel switching.");
return false;
}
nrChannelsSoftware = 1;
nrSlicesSoftware = acqSettings.numSlices * acqSettings.numChannels;
}
break;
default:
MyDialogUtils.showError("Unsupported multichannel mode \"" + acqSettings.channelMode.toString() + "\"");
return false;
}
}
if (acqSettings.hardwareTimepoints) {
// in hardwareTimepoints case we trigger controller once for all timepoints => need to
// adjust number of frames we expect back from the camera during MM's SequenceAcquisition
if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) {
// For overlap mode we are send one extra trigger per channel per side for volume-switching (both PLogic and not)
// This holds for all multi-channel modes, just the order in which the extra trigger comes varies
// Very last trigger won't ever return a frame so subtract 1.
nrSlicesSoftware = ((acqSettings.numSlices + 1) * acqSettings.numChannels * acqSettings.numTimepoints) - 1;
} else {
// we get back one image per trigger for all trigger modes other than OVERLAP
// and we have already computed how many images that is (nrSlicesSoftware)
nrSlicesSoftware *= acqSettings.numTimepoints;
}
}
// set up XY positions
int nrPositions = 1;
PositionList positionList = new PositionList();
if (acqSettings.useMultiPositions) {
try {
positionList = gui_.getPositionList();
nrPositions = positionList.getNumberOfPositions();
} catch (MMScriptException ex) {
MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions");
}
if (nrPositions < 1) {
MyDialogUtils.showError("\"Positions\" is checked, but no positions are in position list");
return false;
}
}
// make sure we have cameras selected
if (!checkCamerasAssigned(true)) {
return false;
}
final float cameraReadoutTime = computeCameraReadoutTime();
final double exposureTime = acqSettings.sliceTiming.cameraExposure;
final boolean save = saveCB_.isSelected() && !testAcq;
final String rootDir = rootField_.getText();
// make sure we have a valid directory to save in
final File dir = new File(rootDir);
if (save) {
try {
if (!dir.exists()) {
if (!dir.mkdir()) {
throw new Exception();
}
}
} catch (Exception ex) {
MyDialogUtils.showError("Could not create directory for saving acquisition data.");
return false;
}
}
if (acqSettings.separateTimepoints) {
// because separate timepoints closes windows when done, force the user to save data to disk to avoid confusion
if (!save) {
MyDialogUtils.showError("For separate timepoints, \"Save while acquiring\" must be enabled.");
return false;
}
// for separate timepoints, make sure the directory is empty to make sure naming pattern is "clean"
// this is an arbitrary choice to avoid confusion later on when looking at file names
if (dir != null && (dir.list().length > 0)) {
MyDialogUtils.showError("For separate timepoints the saving directory must be empty.");
return false;
}
}
int nrFrames; // how many Micro-manager "frames" = time points to take
if (acqSettings.separateTimepoints) {
nrFrames = 1;
nrRepeats_ = acqSettings.numTimepoints;
} else {
nrFrames = acqSettings.numTimepoints;
nrRepeats_ = 1;
}
AcquisitionModes.Keys spimMode = acqSettings.spimMode;
boolean autoShutter = core_.getAutoShutter();
boolean shutterOpen = false; // will read later
String originalCamera = core_.getCameraDevice();
// more sanity checks
// TODO move these checks earlier, before we set up channels and XY positions
// make sure stage scan is supported if selected
if (acqSettings.isStageScanning) {
if (!devices_.isTigerDevice(Devices.Keys.XYSTAGE)
|| !props_.hasProperty(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_NUMLINES)) {
MyDialogUtils.showError("Must have stage with scan-enabled firmware for stage scanning.");
return false;
}
if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED
&& acqSettings.numSides < 2) {
MyDialogUtils.showError("Interleaved mode requires two sides.");
return false;
}
}
double sliceDuration = acqSettings.sliceTiming.sliceDuration;
if (exposureTime + cameraReadoutTime > sliceDuration) {
// should only only possible to mess this up using advanced timing settings
// or if there are errors in our own calculations
MyDialogUtils.showError("Exposure time of " + exposureTime +
" is longer than time needed for a line scan with" +
" readout time of " + cameraReadoutTime + "\n" +
"This will result in dropped frames. " +
"Please change input");
return false;
}
// if we want to do hardware timepoints make sure there's not a problem
// lots of different situations where hardware timepoints can't be used...
if (acqSettings.hardwareTimepoints) {
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW) {
// both hardware time points and volume channel switching use SPIMNumRepeats property
// TODO this seems a severe limitation, maybe this could be changed in the future via firmware change
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with hardware channel switching volume-by-volume.");
return false;
}
if (acqSettings.isStageScanning) {
// stage scanning needs to be triggered for each time point
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with stage scanning.");
return false;
}
if (acqSettings.separateTimepoints) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with separate viewers/file for each time point.");
return false;
}
if (acqSettings.useAutofocus) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with autofocus during acquisition.");
return false;
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME) {
MyDialogUtils.showError("Cannot use hardware time points (small time point interval)"
+ " with software channels (need to use PLogic channel switching).");
return false;
}
if (spimMode == AcquisitionModes.Keys.NO_SCAN) {
MyDialogUtils.showError("Cannot do hardware time points when no scan mode is used."
+ " Use the number of slices to set the number of images to acquire.");
return false;
}
}
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW
&& acqSettings.numSides < 2) {
MyDialogUtils.showError("Cannot do PLogic channel switching of volume when only one"
+ " side is selected. Pester the developers if you need this.");
return false;
}
// make sure we aren't trying to collect timepoints faster than we can
if (!acqSettings.useMultiPositions && acqSettings.numTimepoints > 1) {
if (timepointIntervalMs < volumeDuration) {
MyDialogUtils.showError("Time point interval shorter than" +
" the time to collect a single volume.\n");
return false;
}
}
// Autofocus settings; only used if acqSettings.useAutofocus is true
boolean autofocusAtT0 = false;
int autofocusEachNFrames = 10;
String autofocusChannel = "";
if (acqSettings.useAutofocus) {
autofocusAtT0 = prefs_.getBoolean(MyStrings.PanelNames.AUTOFOCUS.toString(),
Properties.Keys.PLUGIN_AUTOFOCUS_ACQBEFORESTART, false);
autofocusEachNFrames = props_.getPropValueInteger(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_EACHNIMAGES);
autofocusChannel = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_AUTOFOCUS_CHANNEL);
// double-check that selected channel is valid if we are doing multi-channel
if (acqSettings.useChannels) {
String channelGroup = props_.getPropValueString(Devices.Keys.PLUGIN,
Properties.Keys.PLUGIN_MULTICHANNEL_GROUP);
StrVector channels = gui_.getMMCore().getAvailableConfigs(channelGroup);
boolean found = false;
for (String channel : channels) {
if (channel.equals(autofocusChannel)) {
found = true;
break;
}
}
if (!found) {
MyDialogUtils.showError("Invalid autofocus channel selected on autofocus tab.");
return false;
}
}
}
// it appears the circular buffer, which is used by both cameras, can only have one
// image size setting => we require same image height and width for second camera if two-sided
if (twoSided) {
try {
Rectangle roi_1 = core_.getROI(firstCamera);
Rectangle roi_2 = core_.getROI(secondCamera);
if (roi_1.width != roi_2.width || roi_1.height != roi_2.height) {
MyDialogUtils.showError("Camera ROI height and width must be equal because of Micro-Manager's circular buffer");
return false;
}
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Problem getting camera ROIs");
}
}
cameras_.setCameraForAcquisition(firstCameraKey, true);
if (twoSided) {
cameras_.setCameraForAcquisition(secondCameraKey, true);
}
// save exposure time, will restore at end of acquisition
try {
prefs_.putFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE_FIRST.toString(),
(float)core_.getExposure(devices_.getMMDevice(firstCameraKey)));
if (twoSided) {
prefs_.putFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE_SECOND.toString(),
(float)core_.getExposure(devices_.getMMDevice(secondCameraKey)));
}
} catch (Exception ex) {
MyDialogUtils.showError(ex, "could not cache exposure");
}
try {
core_.setExposure(firstCamera, exposureTime);
if (twoSided) {
core_.setExposure(secondCamera, exposureTime);
}
gui_.refreshGUIFromCache();
} catch (Exception ex) {
MyDialogUtils.showError(ex, "could not set exposure");
}
// seems to have a problem if the core's camera has been set to some other
// camera before we start doing things, so set to a SPIM camera
try {
core_.setCameraDevice(firstCamera);
} catch (Exception ex) {
MyDialogUtils.showError(ex, "could not set camera");
}
// empty out circular buffer
try {
core_.clearCircularBuffer();
} catch (Exception ex) {
MyDialogUtils.showError(ex, "Error emptying out the circular buffer");
return false;
}
// stop the serial traffic for position updates during acquisition
// if we return from this function (including aborting) we need to unpause
posUpdater_.pauseUpdates(true);
// initialize stage scanning so we can restore state
Point2D.Double xyPosUm = new Point2D.Double();
float origXSpeed = 1f; // don't want 0 in case something goes wrong
float origXAccel = 1f; // don't want 0 in case something goes wrong
if (acqSettings.isStageScanning) {
try {
xyPosUm = core_.getXYStagePosition(devices_.getMMDevice(Devices.Keys.XYSTAGE));
origXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
origXAccel = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL);
} catch (Exception ex) {
MyDialogUtils.showError("Could not get XY stage position, speed, or acceleration for stage scan initialization");
posUpdater_.pauseUpdates(false);
return false;
}
}
numTimePointsDone_ = 0;
// force saving as image stacks, not individual files
// implementation assumes just two options, either
// TaggedImageStorageDiskDefault.class or TaggedImageStorageMultipageTiff.class
boolean separateImageFilesOriginally =
ImageUtils.getImageStorageClass().equals(TaggedImageStorageDiskDefault.class);
ImageUtils.setImageStorageClass(TaggedImageStorageMultipageTiff.class);
// Set up controller SPIM parameters (including from Setup panel settings)
// want to do this, even with demo cameras, so we can test everything else
if (!controller_.prepareControllerForAquisition(acqSettings)) {
posUpdater_.pauseUpdates(false);
return false;
}
boolean nonfatalError = false;
long acqButtonStart = System.currentTimeMillis();
String acqName = "";
acq_ = null;
// do not want to return from within this loop => throw exception instead
// loop is executed once per acquisition (i.e. once if separate viewers isn't selected
// or once per timepoint if separate viewers is selected)
long repeatStart = System.currentTimeMillis();
for (int acqNum = 0; !cancelAcquisition_.get() && acqNum < nrRepeats_; acqNum++) {
// handle intervals between (software-timed) repeats
// only applies when doing separate viewers for each timepoint
// and have multiple timepoints
long repeatNow = System.currentTimeMillis();
long repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
while (repeatdelay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (repeatdelay / 1000));
long sleepTime = Math.min(1000, repeatdelay);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
ReportingUtils.showError(e);
}
repeatNow = System.currentTimeMillis();
repeatdelay = repeatStart + acqNum * timepointIntervalMs - repeatNow;
}
BlockingQueue<TaggedImage> bq = new LinkedBlockingQueue<TaggedImage>(10);
// try to close last acquisition viewer if there could be one open (only in single acquisition per timepoint mode)
if (acqSettings.separateTimepoints && (acq_!=null) && !cancelAcquisition_.get()) {
try {
// following line needed due to some arcane internal reason, otherwise
// call to closeAcquisitionWindow() fails silently.
acq_.promptToSave(false);
gui_.closeAcquisitionWindow(acqName);
} catch (Exception ex) {
// do nothing if unsuccessful
}
}
if (acqSettings.separateTimepoints) {
// call to getUniqueAcquisitionName is extra safety net, we have checked that directory is empty before starting
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText() + "_" + acqNum);
} else {
acqName = gui_.getUniqueAcquisitionName(prefixField_.getText());
}
long extraStageScanTimeout = 0;
if (acqSettings.isStageScanning) {
// approximately compute the extra time to wait for stack to begin by getting the per-channel volume duration
// and subtracting the acquisition duration and then dividing by two
extraStageScanTimeout = (long) Math.ceil(computeActualVolumeDuration(acqSettings)/acqSettings.numChannels
- (acqSettings.numSlices * acqSettings.sliceTiming.sliceDuration)) / 2;
}
long extraMultiXYTimeout = 0;
if (acqSettings.useMultiPositions) {
// give 10 extra seconds to arrive at intended XY position instead of trying to get fancy about computing actual move time
extraMultiXYTimeout = 10000;
}
VirtualAcquisitionDisplay vad = null;
WindowListener wl_acq = null;
WindowListener[] wls_orig = null;
try {
// check for stop button before each acquisition
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// flag that we are actually running acquisition now
acquisitionRunning_.set(true);
ReportingUtils.logMessage("diSPIM plugin starting acquisition " + acqName + " with following settings: " + acqSettingsJSON);
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// swap nrFrames and numSlices
gui_.openAcquisition(acqName, rootDir, acqSettings.numSlices, acqSettings.numSides * acqSettings.numChannels,
nrFrames, nrPositions, true, save);
} else {
gui_.openAcquisition(acqName, rootDir, nrFrames, acqSettings.numSides * acqSettings.numChannels,
acqSettings.numSlices, nrPositions, true, save);
}
channelNames_ = new String[acqSettings.numSides * acqSettings.numChannels];
// generate channel names and colors
// also builds viewString for MultiViewRegistration metadata
String viewString = "";
final String SEPARATOR = "_";
// set up channels (side A/B is treated as channel too)
if (acqSettings.useChannels) {
ChannelSpec[] channels = multiChannelPanel_.getUsedChannels();
for (int i = 0; i < channels.length; i++) {
String chName = "-" + channels[i].config_;
// same algorithm for channel index vs. specified channel and side as below
int channelIndex = i;
if (twoSided) {
channelIndex *= 2;
}
channelNames_[channelIndex] = firstCamera + chName;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[channelIndex+1] = secondCamera + chName;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
} else {
channelNames_[0] = firstCamera;
viewString += NumberUtils.intToDisplayString(0) + SEPARATOR;
if (twoSided) {
channelNames_[1] = secondCamera;
viewString += NumberUtils.intToDisplayString(90) + SEPARATOR;
}
}
// strip last separator of viewString (for Multiview Reconstruction)
viewString = viewString.substring(0, viewString.length() - 1);
// assign channel names and colors
for (int i = 0; i < acqSettings.numSides * acqSettings.numChannels; i++) {
gui_.setChannelName(acqName, i, channelNames_[i]);
gui_.setChannelColor(acqName, i, getChannelColor(i));
}
// initialize acquisition
gui_.initializeAcquisition(acqName, (int) core_.getImageWidth(),
(int) core_.getImageHeight(), (int) core_.getBytesPerPixel(),
(int) core_.getImageBitDepth());
gui_.promptToSaveAcquisition(acqName, !testAcq);
// These metadata have to added after initialization, otherwise they will not be shown?!
gui_.setAcquisitionProperty(acqName, "NumberOfSides",
NumberUtils.doubleToDisplayString(acqSettings.numSides));
gui_.setAcquisitionProperty(acqName, "FirstSide", acqSettings.firstSideIsA ? "A" : "B");
gui_.setAcquisitionProperty(acqName, "SlicePeriod_ms",
actualSlicePeriodLabel_.getText());
gui_.setAcquisitionProperty(acqName, "LaserExposure_ms",
NumberUtils.doubleToDisplayString(acqSettings.desiredLightExposure));
gui_.setAcquisitionProperty(acqName, "VolumeDuration",
actualVolumeDurationLabel_.getText());
gui_.setAcquisitionProperty(acqName, "SPIMmode", spimMode.toString());
// Multi-page TIFF saving code wants this one (cameras are all 16-bits, so not much reason for anything else)
gui_.setAcquisitionProperty(acqName, "PixelType", "GRAY16");
gui_.setAcquisitionProperty(acqName, "UseAutofocus",
acqSettings.useAutofocus ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "HardwareTimepoints",
acqSettings.hardwareTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "SeparateTimepoints",
acqSettings.separateTimepoints ? Boolean.TRUE.toString() : Boolean.FALSE.toString());
gui_.setAcquisitionProperty(acqName, "CameraMode", acqSettings.cameraMode.toString());
gui_.setAcquisitionProperty(acqName, "z-step_um",
NumberUtils.doubleToDisplayString(acqSettings.stepSizeUm));
// Properties for use by MultiViewRegistration plugin
// Format is: x_y_z, set to 1 if we should rotate around this axis.
gui_.setAcquisitionProperty(acqName, "MVRotationAxis", "0_1_0");
gui_.setAcquisitionProperty(acqName, "MVRotations", viewString);
// save XY and SPIM head position in metadata
// update positions first at expense of two extra serial transactions
positions_.getUpdatedPosition(Devices.Keys.XYSTAGE, Directions.X); // / will update cache for Y too
gui_.setAcquisitionProperty(acqName, "Position_X",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.X));
gui_.setAcquisitionProperty(acqName, "Position_Y",
positions_.getPositionString(Devices.Keys.XYSTAGE, Directions.Y));
positions_.getUpdatedPosition(Devices.Keys.UPPERZDRIVE);
gui_.setAcquisitionProperty(acqName, "Position_SPIM_Head",
positions_.getPositionString(Devices.Keys.UPPERZDRIVE));
gui_.setAcquisitionProperty(acqName, "SPIMAcqSettings", acqSettingsJSON);
gui_.setAcquisitionProperty(acqName, "SPIMtype", ASIdiSPIM.oSPIM ? "oSPIM" : "diSPIM");
gui_.setAcquisitionProperty(acqName, "AcquisitionName", acqName);
// get circular buffer ready
// do once here but not per-trigger; need to ensure ROI changes registered
core_.initializeCircularBuffer();
// TODO: use new acquisition interface that goes through the pipeline
//gui_.setAcquisitionAddImageAsynchronous(acqName);
acq_ = gui_.getAcquisition(acqName);
// Dive into MM internals since script interface does not support pipelines
ImageCache imageCache = acq_.getImageCache();
vad = acq_.getAcquisitionWindow();
imageCache.addImageCacheListener(vad);
// Start pumping images into the ImageCache
DefaultTaggedImageSink sink = new DefaultTaggedImageSink(bq, imageCache);
sink.start();
// remove usual window listener(s) and replace it with our own
// that will prompt before closing and cancel acquisition if confirmed
// this should be considered a hack, it may not work perfectly
// I have confirmed that there is only one windowListener and it seems to
// also be related to window closing
// Note that ImageJ's acquisition window is AWT instead of Swing
wls_orig = vad.getImagePlus().getWindow().getWindowListeners();
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().removeWindowListener(l);
}
wl_acq = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
// if running acquisition only close if user confirms
if (acquisitionRunning_.get()) {
boolean stop = MyDialogUtils.getConfirmDialogResult(
"Do you really want to abort the acquisition?",
JOptionPane.YES_NO_OPTION);
if (stop) {
cancelAcquisition_.set(true);
}
}
}
};
vad.getImagePlus().getWindow().addWindowListener(wl_acq);
// patterned after implementation in MMStudio.java
// will be null if not saving to disk
lastAcquisitionPath_ = acq_.getImageCache().getDiskLocation();
lastAcquisitionName_ = acqName;
// make sure all devices have arrived, e.g. a stage isn't still moving
try {
core_.waitForSystem();
} catch (Exception e) {
ReportingUtils.logError("error waiting for system");
}
// Loop over all the times we trigger the controller's acquisition
// (although if multi-channel with volume switching is selected there
// is inner loop to trigger once per channel)
// remember acquisition start time for software-timed timepoints
// For hardware-timed timepoints we only trigger the controller once
long acqStart = System.currentTimeMillis();
for (int trigNum = 0; trigNum < nrFrames; trigNum++) {
// handle intervals between (software-timed) time points
// when we are within the same acquisition
// (if separate viewer is selected then nothing bad happens here
// but waiting during interval handled elsewhere)
long acqNow = System.currentTimeMillis();
long delay = acqStart + trigNum * timepointIntervalMs - acqNow;
while (delay > 0 && !cancelAcquisition_.get()) {
updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (delay / 1000));
long sleepTime = Math.min(1000, delay);
Thread.sleep(sleepTime);
acqNow = System.currentTimeMillis();
delay = acqStart + trigNum * timepointIntervalMs - acqNow;
}
// check for stop button before each time point
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
int timePoint = acqSettings.separateTimepoints ? acqNum : trigNum ;
// this is where we autofocus if requested
if (acqSettings.useAutofocus) {
// Note that we will not autofocus as expected when using hardware
// timing. Seems OK, since hardware timing will result in short
// acquisition times that do not need autofocus. We have already
// ensured that we aren't doing both
if ( (autofocusAtT0 && timePoint == 0) || ( (timePoint > 0) &&
(timePoint % autofocusEachNFrames == 0 ) ) ) {
if (acqSettings.useChannels) {
multiChannelPanel_.selectChannel(autofocusChannel);
}
if (sideActiveA) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.A, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.A, score);
}
if (sideActiveB) {
AutofocusUtils.FocusResult score = autofocus_.runFocus(
this, Devices.Sides.B, false,
sliceTiming_, false);
updateCalibrationOffset(Devices.Sides.B, score);
}
// Restore settings of the controller
controller_.prepareControllerForAquisition(acqSettings);
if (acqSettings.useChannels && acqSettings.channelMode != MultichannelModes.Keys.VOLUME) {
controller_.setupHardwareChannelSwitching(acqSettings);
}
}
}
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
// loop over all positions
for (int positionNum = 0; positionNum < nrPositions; positionNum++) {
if (acqSettings.useMultiPositions) {
// make sure user didn't stop things
if (cancelAcquisition_.get()) {
throw new IllegalMonitorStateException("User stopped the acquisition");
}
// want to move between positions move stage fast, so we
// will clobber stage scanning setting so need to restore it
float scanXSpeed = 1f;
float scanXAccel = 1f;
if (acqSettings.isStageScanning) {
scanXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
scanXAccel = props_.getPropValueFloat(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL, origXAccel);
}
// blocking call; will wait for stages to move
MultiStagePosition.goToPosition(positionList.getPosition(positionNum), core_);
// restore speed for stage scanning
if (acqSettings.isStageScanning) {
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, scanXSpeed);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL, scanXAccel);
}
// setup stage scan at this position
// non-multi-position situation is handled in prepareControllerForAquisition instead
if (acqSettings.useMultiPositions) {
StagePosition pos = positionList.getPosition(positionNum).get(devices_.getMMDevice(Devices.Keys.XYSTAGE));
controller_.prepareStageScanForAcquisition(pos.x, pos.y);
}
// wait any extra time the user requests
Thread.sleep(Math.round(PanelUtils.getSpinnerFloatValue(positionDelay_)));
}
// loop over all the times we trigger the controller
// usually just once, but will be the number of channels if we have
// multiple channels and aren't using PLogic to change between them
for (int channelNum = 0; channelNum < nrChannelsSoftware; channelNum++) {
try {
// flag that we are using the cameras/controller
ASIdiSPIM.getFrame().setHardwareInUse(true);
// deal with shutter before starting acquisition
shutterOpen = core_.getShutterOpen();
if (autoShutter) {
core_.setAutoShutter(false);
if (!shutterOpen) {
core_.setShutterOpen(true);
}
}
// start the cameras
core_.startSequenceAcquisition(firstCamera, nrSlicesSoftware, 0, true);
if (twoSided) {
core_.startSequenceAcquisition(secondCamera, nrSlicesSoftware, 0, true);
}
// deal with channel if needed (hardware channel switching doesn't happen here)
if (changeChannelPerVolumeSoftware) {
multiChannelPanel_.selectNextChannel();
}
// trigger the state machine on the controller
// do this even with demo cameras to test everything else
boolean success = controller_.triggerControllerStartAcquisition(spimMode, firstSideA);
if (!success) {
throw new Exception("Controller triggering not successful");
}
ReportingUtils.logDebugMessage("Starting time point " + (timePoint+1) + " of " + nrFrames
+ " with (software) channel number " + channelNum);
// Wait for first image to create ImageWindow, so that we can be sure about image size
// Do not actually grab first image here, just make sure it is there
long start = System.currentTimeMillis();
long now = start;
final long timeout = Math.max(3000, Math.round(10*sliceDuration + 2*acqSettings.delayBeforeSide))
+ extraStageScanTimeout + extraMultiXYTimeout;
while (core_.getRemainingImageCount() == 0 && (now - start < timeout)
&& !cancelAcquisition_.get()) {
now = System.currentTimeMillis();
Thread.sleep(5);
}
if (now - start >= timeout) {
String msg = "Camera did not send first image within a reasonable time.\n";
if (acqSettings.isStageScanning) {
msg += "Make sure jumpers are correct on XY card and also micro-micromirror card.";
} else {
msg += "Make sure camera trigger cables are connected properly.";
}
throw new Exception(msg);
}
// grab all the images from the cameras, put them into the acquisition
int[] frNumber = new int[2*acqSettings.numChannels]; // keep track of how many frames we have received for each "channel" (MM channel is our channel * 2 for the 2 cameras)
int[] cameraFrNumber = new int[2]; // keep track of how many frames we have received from the camera
int[] tpNumber = new int[2*acqSettings.numChannels]; // keep track of which timepoint we are on for hardware timepoints
int imagesToSkip = 0; // hardware timepoints have to drop spurious images with overlap mode
final boolean checkForSkips = acqSettings.hardwareTimepoints && (acqSettings.cameraMode == CameraModes.Keys.OVERLAP);
boolean done = false;
final long timeout2 = Math.max(1000, Math.round(5*sliceDuration));
start = System.currentTimeMillis();
long last = start;
try {
while ((core_.getRemainingImageCount() > 0
|| core_.isSequenceRunning(firstCamera)
|| (twoSided && core_.isSequenceRunning(secondCamera)))
&& !done) {
now = System.currentTimeMillis();
if (core_.getRemainingImageCount() > 0) { // we have an image to grab
TaggedImage timg = core_.popNextTaggedImage();
if (checkForSkips && imagesToSkip != 0) {
imagesToSkip
continue; // goes to next iteration of this loop without doing anything else
}
// figure out which channel index this frame belongs to
// "channel index" is channel of MM acquisition
// channel indexes will go from 0 to (numSides * numChannels - 1)
// if double-sided then second camera gets odd channel indexes (1, 3, etc.)
// and adjacent pairs will be same color (e.g. 0 and 1 will be from first color, 2 and 3 from second, etc.)
String camera = (String) timg.tags.get("Camera");
int cameraIndex = camera.equals(firstCamera) ? 0: 1;
int channelIndex_tmp;
switch (acqSettings.channelMode) {
case NONE:
case VOLUME:
channelIndex_tmp = channelNum;
break;
case VOLUME_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] / acqSettings.numSlices; // want quotient only
break;
case SLICE_HW:
channelIndex_tmp = cameraFrNumber[cameraIndex] % acqSettings.numChannels; // want modulo arithmetic
break;
default:
// should never get here
throw new Exception("Undefined channel mode");
}
if (twoSided) {
channelIndex_tmp *= 2;
}
final int channelIndex = channelIndex_tmp + cameraIndex;
int actualTimePoint = timePoint;
if (acqSettings.hardwareTimepoints) {
actualTimePoint = tpNumber[channelIndex];
}
if (acqSettings.separateTimepoints) {
// if we are doing separate timepoints then frame is always 0
actualTimePoint = 0;
}
// note that hardwareTimepoints and separateTimepoints can never both be true
// add image to acquisition
if (spimMode == AcquisitionModes.Keys.NO_SCAN && !acqSettings.separateTimepoints) {
// create time series for no scan
addImageToAcquisition(acq_,
frNumber[channelIndex], channelIndex, actualTimePoint,
positionNum, now - acqStart, timg, bq);
} else { // standard, create Z-stacks
addImageToAcquisition(acq_, actualTimePoint, channelIndex,
frNumber[channelIndex], positionNum,
now - acqStart, timg, bq);
}
// update our counters to be ready for next image
frNumber[channelIndex]++;
cameraFrNumber[cameraIndex]++;
// if hardware timepoints then we only send one trigger and
// manually keep track of which channel/timepoint comes next
if (acqSettings.hardwareTimepoints
&& frNumber[channelIndex] >= acqSettings.numSlices) { // only do this if we are done with the slices in this MM channel
// we just finished filling one MM channel with all its slices so go to next timepoint for this channel
frNumber[channelIndex] = 0;
tpNumber[channelIndex]++;
// see if we are supposed to skip next image
if (checkForSkips) {
// one extra image per MM channel, this includes case of only 1 color (either multi-channel disabled or else only 1 channel selected)
// if we are interleaving by slice then next nrChannel images will be from extra slice position
// any other configuration we will just drop the next image
if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.SLICE_HW) {
imagesToSkip = acqSettings.numChannels;
} else {
imagesToSkip = 1;
}
}
// update acquisition status message for hardware acquisition
// (for non-hardware acquisition message is updated elsewhere)
// Arbitrarily choose one possible channel to do this on.
if (channelIndex == 0 && (numTimePointsDone_ < acqSettings.numTimepoints)) {
numTimePointsDone_++;
updateAcquisitionStatus(AcquisitionStatus.ACQUIRING);
}
}
last = now; // keep track of last image timestamp
} else { // no image ready yet
done = cancelAcquisition_.get();
Thread.sleep(1);
if (now - last >= timeout2) {
ReportingUtils.logError("Camera did not send all expected images within" +
" a reasonable period for timepoint " + numTimePointsDone_ + ". Continuing anyway.");
nonfatalError = true;
done = true;
}
}
}
// update count if we stopped in the middle
if (cancelAcquisition_.get()) {
numTimePointsDone_
}
// if we are using demo camera then add some extra time to let controller finish
// since we got images without waiting for controller to actually send triggers
if (usingDemoCam) {
Thread.sleep(200); // for serial communication overhead
Thread.sleep((long)volumeDuration/nrChannelsSoftware); // estimate the time per channel, not ideal in case of software channel switching
}
} catch (InterruptedException iex) {
MyDialogUtils.showError(iex);
}
if (acqSettings.hardwareTimepoints) {
break; // only trigger controller once
}
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally {
// cleanup at the end of each time we trigger the controller
ASIdiSPIM.getFrame().setHardwareInUse(false);
// put shutter back to original state
core_.setShutterOpen(shutterOpen);
core_.setAutoShutter(autoShutter);
// make sure cameras aren't running anymore
if (core_.isSequenceRunning(firstCamera)) {
core_.stopSequenceAcquisition(firstCamera);
}
if (twoSided && core_.isSequenceRunning(secondCamera)) {
core_.stopSequenceAcquisition(secondCamera);
}
}
}
}
if (acqSettings.hardwareTimepoints) {
break;
}
}
} catch (IllegalMonitorStateException ex) {
// do nothing, the acquisition was simply halted during its operation
// will log error message during finally clause
} catch (MMScriptException mex) {
MyDialogUtils.showError(mex);
} catch (Exception ex) {
MyDialogUtils.showError(ex);
} finally { // end of this acquisition (could be about to restart if separate viewers)
try {
// restore original window listeners
try {
vad.getImagePlus().getWindow().removeWindowListener(wl_acq);
for (WindowListener l : wls_orig) {
vad.getImagePlus().getWindow().addWindowListener(l);
}
} catch (Exception ex) {
// do nothing, window is probably gone
}
if (cancelAcquisition_.get()) {
ReportingUtils.logMessage("User stopped the acquisition");
}
bq.put(TaggedImageQueue.POISON);
// TODO: evaluate closeAcquisition call
// at the moment, the Micro-Manager api has a bug that causes
// a closed acquisition not be really closed, causing problems
// when the user closes a window of the previous acquisition
// changed r14705 (2014-11-24)
// gui_.closeAcquisition(acqName);
ReportingUtils.logMessage("diSPIM plugin acquisition " + acqName +
" took: " + (System.currentTimeMillis() - acqButtonStart) + "ms");
// flag that we are done with acquisition
acquisitionRunning_.set(false);
} catch (Exception ex) {
// exception while stopping sequence acquisition, not sure what to do...
MyDialogUtils.showError(ex, "Problem while finishing acquisition");
}
}
}// for loop over acquisitions
// cleanup after end of all acquisitions
// TODO be more careful and always do these if we actually started acquisition,
// even if exception happened
cameras_.setCameraForAcquisition(firstCameraKey, false);
if (twoSided) {
cameras_.setCameraForAcquisition(secondCameraKey, false);
}
// restore exposure times of SPIM cameras
try {
core_.setExposure(firstCamera, prefs_.getFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE_FIRST.toString(), 10f));
if (twoSided) {
core_.setExposure(secondCamera, prefs_.getFloat(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_CAMERA_LIVE_EXPOSURE_SECOND.toString(), 10f));
}
gui_.refreshGUIFromCache();
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore exposure after acquisition");
}
// reset channel to original if we clobbered it
if (acqSettings.useChannels) {
multiChannelPanel_.setConfig(originalChannelConfig);
}
// clean up controller settings after acquisition
// want to do this, even with demo cameras, so we can test everything else
// TODO figure out if we really want to return piezos to 0 position (maybe center position,
// maybe not at all since we move when we switch to setup tab, something else??)
controller_.cleanUpControllerAfterAcquisition(acqSettings.numSides, acqSettings.firstSideIsA, true);
// if we did stage scanning restore its position and speed
if (acqSettings.isStageScanning) {
try {
// make sure stage scanning state machine is stopped, otherwise setting speed/position won't take
props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_STATE,
Properties.Values.SPIM_IDLE);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed);
props_.setPropValue(Devices.Keys.XYSTAGE,
Properties.Keys.STAGESCAN_MOTOR_ACCEL, origXAccel);
core_.setXYPosition(devices_.getMMDevice(Devices.Keys.XYSTAGE),
xyPosUm.x, xyPosUm.y);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore XY stage position after acquisition");
}
}
updateAcquisitionStatus(AcquisitionStatus.DONE);
posUpdater_.pauseUpdates(false);
if (testAcq && prefs_.getBoolean(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_SAVE, false)) {
String path = "";
try {
path = prefs_.getString(MyStrings.PanelNames.SETTINGS.toString(),
Properties.Keys.PLUGIN_TESTACQ_PATH, "");
IJ.saveAs(acq_.getAcquisitionWindow().getImagePlus(), "raw", path);
// TODO consider generating a short metadata file to assist in interpretation
} catch (Exception ex) {
MyDialogUtils.showError("Could not save raw data from test acquisition to path " + path);
}
}
if (separateImageFilesOriginally) {
ImageUtils.setImageStorageClass(TaggedImageStorageDiskDefault.class);
}
// restore camera
try {
core_.setCameraDevice(originalCamera);
} catch (Exception ex) {
MyDialogUtils.showError("Could not restore camera after acquisition");
}
if (liveModeOriginally) {
gui_.enableLiveMode(true);
}
if (nonfatalError) {
MyDialogUtils.showError("Missed some images during acquisition, see core log for details");
}
return true;
}
@Override
public void saveSettings() {
// save controller settings
props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
props_.setPropValue(Devices.Keys.PLOGIC, Properties.Keys.SAVE_CARD_SETTINGS,
Properties.Values.DO_SSZ, true);
}
/**
* Gets called when this tab gets focus. Refreshes values from properties.
*/
@Override
public void gotSelected() {
posUpdater_.pauseUpdates(true);
props_.callListeners();
// old joystick associations were cleared when leaving
// last tab so only do it if joystick settings need to be applied
if (navigationJoysticksCB_.isSelected()) {
updateJoysticks();
}
sliceFrameAdvanced_.setVisible(advancedSliceTimingCB_.isSelected());
posUpdater_.pauseUpdates(false);
}
/**
* called when tab looses focus.
*/
@Override
public void gotDeSelected() {
// if we have been using navigation panel's joysticks need to unset them
if (navigationJoysticksCB_.isSelected()) {
if (ASIdiSPIM.getFrame() != null) {
ASIdiSPIM.getFrame().getNavigationPanel().doJoystickSettings(false);
}
}
sliceFrameAdvanced_.setVisible(false);
}
@Override
public void devicesChangedAlert() {
devices_.callListeners();
}
/**
* Gets called when enclosing window closes
*/
@Override
public void windowClosing() {
if (acquisitionRequested_.get()) {
cancelAcquisition_.set(true);
while (acquisitionRunning_.get()) {
// spin wheels until we are done
}
}
sliceFrameAdvanced_.savePosition();
sliceFrameAdvanced_.dispose();
}
@Override
public void refreshDisplay() {
updateDurationLabels();
}
@Override
// Used to re-layout portion of window depending when camera mode changes, in
// particular light sheet mode needs different set of controls.
public void cameraModeChange() {
CameraModes.Keys key = getSPIMCameraMode();
slicePanelContainer_.removeAll();
slicePanelContainer_.add((key == CameraModes.Keys.LIGHT_SHEET) ?
lightSheetPanel_ : normalPanel_, "growx");
slicePanelContainer_.revalidate();
slicePanelContainer_.repaint();
}
private void setRootDirectory(JTextField rootField) {
File result = FileDialogs.openDir(null,
"Please choose a directory root for image data",
MMStudio.MM_DATA_SET);
if (result != null) {
rootField.setText(result.getAbsolutePath());
}
}
/**
* The basic method for adding images to an existing data set. If the
* acquisition was not previously initialized, it will attempt to initialize
* it from the available image data. This version uses a blocking queue and is
* much faster than the one currently implemented in the ScriptInterface
* Eventually, this function should be replaced by the ScriptInterface version
* of the same.
* @param acq - MMAcquisition object to use (old way used acquisition name and then
* had to call deprecated function on every call, now just pass acquisition object
* @param frame - frame nr at which to insert the image
* @param channel - channel at which to insert image
* @param slice - (z) slice at which to insert image
* @param position - position at which to insert image
* @param ms - Time stamp to be added to the image metadata
* @param taggedImg - image + metadata to be added
* @param bq - Blocking queue to which the image should be added. This queue
* should be hooked up to the ImageCache belonging to this acquisitions
* @throws java.lang.InterruptedException
* @throws org.micromanager.utils.MMScriptException
*/
private void addImageToAcquisition(MMAcquisition acq,
int frame,
int channel,
int slice,
int position,
long ms,
TaggedImage taggedImg,
BlockingQueue<TaggedImage> bq) throws MMScriptException, InterruptedException {
// verify position number is allowed
if (acq.getPositions() <= position) {
throw new MMScriptException("The position number must not exceed declared"
+ " number of positions (" + acq.getPositions() + ")");
}
// verify that channel number is allowed
if (acq.getChannels() <= channel) {
throw new MMScriptException("The channel number must not exceed declared"
+ " number of channels (" + + acq.getChannels() + ")");
}
JSONObject tags = taggedImg.tags;
if (!acq.isInitialized()) {
throw new MMScriptException("Error in the ASIdiSPIM logic. Acquisition should have been initialized");
}
// create required coordinate tags
try {
MDUtils.setFrameIndex(tags, frame);
tags.put(MMTags.Image.FRAME, frame);
MDUtils.setChannelIndex(tags, channel);
MDUtils.setChannelName(tags, channelNames_[channel]);
MDUtils.setSliceIndex(tags, slice);
MDUtils.setPositionIndex(tags, position);
MDUtils.setElapsedTimeMs(tags, ms);
MDUtils.setImageTime(tags, MDUtils.getCurrentTime());
MDUtils.setZStepUm(tags, PanelUtils.getSpinnerFloatValue(stepSize_));
if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {
// add default setting
tags.put(MMTags.Summary.SLICES_FIRST, true);
tags.put(MMTags.Summary.TIME_FIRST, false);
}
if (acq.getPositions() > 1) {
// if no position name is defined we need to insert a default one
if (tags.has(MMTags.Image.POS_NAME)) {
tags.put(MMTags.Image.POS_NAME, "Pos" + position);
}
}
// update frames if necessary
if (acq.getFrames() <= frame) {
acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));
}
} catch (JSONException e) {
throw new MMScriptException(e);
}
bq.put(taggedImg);
}
/**
* @return true if an acquisition is currently underway
* (e.g. all checks passed, controller set up, MM acquisition object created, etc.)
*/
public boolean isAcquisitionRunning() {
return acquisitionRunning_.get();
}
/**
* @return true if an acquisition has been requested by user. Will
* also return true if acquisition is running.
*/
public boolean isAcquisitionRequested() {
return acquisitionRequested_.get();
}
/**
* Stops the acquisition by setting an Atomic boolean indicating that we should
* halt. Does nothing if an acquisition isn't running.
*/
public void stopAcquisition() {
if (isAcquisitionRequested()) {
cancelAcquisition_.set(true);
}
}
/**
* @return pathname on filesystem to last completed acquisition
* (even if it was stopped pre-maturely). Null if not saved to disk.
*/
public String getLastAcquisitionPath() {
return lastAcquisitionPath_;
}
public String getLastAcquisitionName() {
return lastAcquisitionName_;
}
public ij.ImagePlus getLastAcquisitionImagePlus() throws ASIdiSPIMException {
try {
return gui_.getAcquisition(lastAcquisitionName_).getAcquisitionWindow().getImagePlus();
} catch (MMScriptException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingDirectoryRoot() {
return rootField_.getText();
}
public void setSavingDirectoryRoot(String directory) throws ASIdiSPIMException {
rootField_.setText(directory);
try {
rootField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public String getSavingNamePrefix() {
return prefixField_.getText();
}
public void setSavingNamePrefix(String acqPrefix) throws ASIdiSPIMException {
prefixField_.setText(acqPrefix);
try {
prefixField_.commitEdit();
} catch (ParseException e) {
throw new ASIdiSPIMException(e);
}
}
public boolean getSavingSeparateFile() {
return separateTimePointsCB_.isSelected();
}
public void setSavingSeparateFile(boolean separate) {
separateTimePointsCB_.setSelected(separate);
}
public boolean getSavingSaveWhileAcquiring() {
return saveCB_.isSelected();
}
public void setSavingSaveWhileAcquiring(boolean save) {
saveCB_.setSelected(save);
}
public org.micromanager.asidispim.Data.AcquisitionModes.Keys getAcquisitionMode() {
return (org.micromanager.asidispim.Data.AcquisitionModes.Keys) spimMode_.getSelectedItem();
}
public void setAcquisitionMode(org.micromanager.asidispim.Data.AcquisitionModes.Keys mode) {
spimMode_.setSelectedItem(mode);
}
public boolean getTimepointsEnabled() {
return useTimepointsCB_.isSelected();
}
public void setTimepointsEnabled(boolean enabled) {
useTimepointsCB_.setSelected(enabled);
}
public int getNumberOfTimepoints() {
return (Integer) numTimepoints_.getValue();
}
public void setNumberOfTimepoints(int numTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(numTimepoints, 1, 100000)) {
throw new ASIdiSPIMException("illegal value for number of time points");
}
numTimepoints_.setValue(numTimepoints);
}
// getTimepointInterval already existed
public void setTimepointInterval(double intervalTimepoints) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(intervalTimepoints, 0.1, 32000)) {
throw new ASIdiSPIMException("illegal value for time point interval");
}
acquisitionInterval_.setValue(intervalTimepoints);
}
public boolean getMultiplePositionsEnabled() {
return usePositionsCB_.isSelected();
}
public void setMultiplePositionsEnabled(boolean enabled) {
usePositionsCB_.setSelected(enabled);
}
public double getMultiplePositionsPostMoveDelay() {
return PanelUtils.getSpinnerFloatValue(positionDelay_);
}
public void setMultiplePositionsDelay(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for post move delay");
}
positionDelay_.setValue(delayMs);
}
public boolean getChannelsEnabled() {
return multiChannelPanel_.isMultiChannel();
}
public void setChannelsEnabled(boolean enabled) {
multiChannelPanel_.setPanelEnabled(enabled);
}
public String[] getAvailableChannelGroups() {
return multiChannelPanel_.getAvailableGroups();
}
public String getChannelGroup() {
return multiChannelPanel_.getChannelGroup();
}
public void setChannelGroup(String channelGroup) {
String[] availableGroups = getAvailableChannelGroups();
for (String group : availableGroups) {
if (group.equals(channelGroup)) {
multiChannelPanel_.setChannelGroup(channelGroup);
}
}
}
public String[] getAvailableChannels() {
return multiChannelPanel_.getAvailableChannels();
}
public boolean getChannelEnabled(String channel) {
ChannelSpec[] usedChannels = multiChannelPanel_.getUsedChannels();
for (ChannelSpec spec : usedChannels) {
if (spec.config_.equals(channel)) {
return true;
}
}
return false;
}
public void setChannelEnabled(String channel, boolean enabled) {
multiChannelPanel_.setChannelEnabled(channel, enabled);
}
// getNumSides() already existed
public void setVolumeNumberOfSides(int numSides) {
if (numSides == 2) {
numSides_.setSelectedIndex(1);
} else {
numSides_.setSelectedIndex(0);
}
}
public void setFirstSideIsA(boolean firstSideIsA) {
if (firstSideIsA) {
firstSide_.setSelectedIndex(0);
} else {
firstSide_.setSelectedIndex(1);
}
}
public double getVolumeDelayBeforeSide() {
return PanelUtils.getSpinnerFloatValue(delaySide_);
}
public void setVolumeDelayBeforeSide(double delayMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(delayMs, 0d, 10000d)) {
throw new ASIdiSPIMException("illegal value for delay before side");
}
delaySide_.setValue(delayMs);
}
public int getVolumeSlicesPerVolume() {
return (Integer) numSlices_.getValue();
}
public void setVolumeSlicesPerVolume(int slices) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(slices, 1, 65000)) {
throw new ASIdiSPIMException("illegal value for number of slices");
}
numSlices_.setValue(slices);
}
public double getVolumeSliceStepSize() {
return PanelUtils.getSpinnerFloatValue(stepSize_);
}
public void setVolumeSliceStepSize(double stepSizeUm) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(stepSizeUm, 0d, 100d)) {
throw new ASIdiSPIMException("illegal value for slice step size");
}
stepSize_.setValue(stepSizeUm);
}
public boolean getVolumeMinimizeSlicePeriod() {
return minSlicePeriodCB_.isSelected();
}
public void setVolumeMinimizeSlicePeriod(boolean minimize) {
minSlicePeriodCB_.setSelected(minimize);
}
public double getVolumeSlicePeriod() {
return PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_);
}
public void setVolumeSlicePeriod(double periodMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(periodMs, 1d, 1000d)) {
throw new ASIdiSPIMException("illegal value for slice period");
}
desiredSlicePeriod_.setValue(periodMs);
}
public double getVolumeSampleExposure() {
return PanelUtils.getSpinnerFloatValue(desiredLightExposure_);
}
public void setVolumeSampleExposure(double exposureMs) throws ASIdiSPIMException {
if (MyNumberUtils.outsideRange(exposureMs, 1.0, 1000.0)) {
throw new ASIdiSPIMException("illegal value for sample exposure");
}
desiredLightExposure_.setValue(exposureMs);
}
public boolean getAutofocusDuringAcquisition() {
return useAutofocusCB_.isSelected();
}
public void setAutofocusDuringAcquisition(boolean enable) {
useAutofocusCB_.setSelected(enable);
}
public double getEstimatedSliceDuration() {
return sliceTiming_.sliceDuration;
}
public double getEstimatedVolumeDuration() {
return computeActualVolumeDuration();
}
public double getEstimatedAcquisitionDuration() {
return computeActualTimeLapseDuration();
}
}
|
package net.java.sip.communicator.impl.protocol.sip;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.Message;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
/**
* A straightforward implementation of the basic instant messaging operation
* set.
*
* @author Benoit Pradelle
*/
public class OperationSetBasicInstantMessagingSipImpl
implements OperationSetBasicInstantMessaging
{
private static final Logger logger =
Logger.getLogger(OperationSetBasicInstantMessagingSipImpl.class);
/**
* A list of listeners registered for message events.
*/
private Vector messageListeners = new Vector();
/**
* A list of processors registered for incoming sip messages.
*/
private Vector messageProcessors = new Vector();
/**
* The provider that created us.
*/
private ProtocolProviderServiceSipImpl sipProvider = null;
/**
* A reference to the persistent presence operation set that we use
* to match incoming messages to <tt>Contact</tt>s and vice versa.
*/
private OperationSetPresenceSipImpl opSetPersPresence = null;
/**
* Hashtable containing the CSeq of each discussion
*/
private long seqN = hashCode();
/**
* Hashtable containing the message sent
*/
private Hashtable sentMsg = null;
/**
* It can be implemented in some servers.
*/
private boolean offlineMessageSupported = false;
/**
* Gives access to presence states for the Sip protocol.
*/
private SipStatusEnum sipStatusEnum;
/**
* Creates an instance of this operation set.
* @param provider a ref to the <tt>ProtocolProviderServiceImpl</tt>
* that created us and that we'll use for retrieving the underlying aim
* connection.
*/
OperationSetBasicInstantMessagingSipImpl(
ProtocolProviderServiceSipImpl provider)
{
this.sipProvider = provider;
this.sentMsg = new Hashtable(3);
provider.addRegistrationStateChangeListener(new
RegistrationStateListener());
Object isOffMsgsSupported = provider.getAccountID().
getAccountProperties().get("OFFLINE_MSG_SUPPORTED");
if(isOffMsgsSupported != null &&
Boolean.valueOf((String)isOffMsgsSupported).booleanValue())
offlineMessageSupported = true;
sipProvider.registerMethodProcessor(Request.MESSAGE,
new SipMessageListener());
this.sipStatusEnum = sipProvider.getSipStatusEnum();
}
/**
* Registers a MessageListener with this operation set so that it gets
* notifications of successful message delivery, failure or reception of
* incoming messages..
*
* @param listener the <tt>MessageListener</tt> to register.
*/
public void addMessageListener(MessageListener listener)
{
synchronized (this.messageListeners)
{
if (!this.messageListeners.contains(listener))
{
this.messageListeners.add(listener);
}
}
}
/**
* Unregisters <tt>listener</tt> so that it won't receive any further
* notifications upon successful message delivery, failure or reception of
* incoming messages..
*
* @param listener the <tt>MessageListener</tt> to unregister.
*/
public void removeMessageListener(MessageListener listener)
{
synchronized (this.messageListeners)
{
this.messageListeners.remove(listener);
}
}
/**
* Registers a SipMessageListener with this operation set so that it gets
* notifications of successful message delivery, failure or reception of
* incoming messages..
*
* @param listener the <tt>SipMessageListener</tt> to register.
*/
void addMessageProcessor(SipMessageProcessor processor)
{
synchronized (this.messageProcessors)
{
if (!this.messageProcessors.contains(processor))
{
this.messageProcessors.add(processor);
}
}
}
/**
* Unregisters <tt>listener</tt> so that it won't receive any further
* notifications upon successful message delivery, failure or reception of
* incoming messages..
*
* @param listener the <tt>SipMessageListener</tt> to unregister.
*/
void removeMessageProcessor(SipMessageProcessor processor)
{
synchronized (this.messageProcessors)
{
this.messageProcessors.remove(processor);
}
}
/**
* Create a Message instance for sending arbitrary MIME-encoding content.
*
* @param content content value
* @param contentType the MIME-type for <tt>content</tt>
* @param contentEncoding encoding used for <tt>content</tt>
* @param subject a <tt>String</tt> subject or <tt>null</tt> for now subject.
* @return the newly created message.
*/
public Message createMessage(byte[] content, String contentType,
String contentEncoding, String subject)
{
return new MessageSipImpl(new String(content), contentType
, contentEncoding, subject);
}
/**
* Create a Message instance for sending a simple text messages with
* default (text/plain) content type and encoding.
*
* @param messageText the string content of the message.
* @return Message the newly created message
*/
public Message createMessage(String messageText)
{
return new MessageSipImpl(messageText, DEFAULT_MIME_TYPE
, DEFAULT_MIME_ENCODING, null);
}
/**
* Determines whether the protocol provider (or the protocol itself) support
* sending and receiving offline messages. Most often this method would
* return true for protocols that support offline messages and false for
* those that don't. It is however possible for a protocol to support these
* messages and yet have a particular account that does not (i.e. feature
* not enabled on the protocol server). In cases like this it is possible
* for this method to return true even when offline messaging is not
* supported, and then have the sendMessage method throw an
* OperationFailedException with code - OFFLINE_MESSAGES_NOT_SUPPORTED.
*
* @return <tt>true</tt> if the protocol supports offline messages and
* <tt>false</tt> otherwise.
*/
public boolean isOfflineMessagingSupported()
{
return offlineMessageSupported;
}
/**
* Determines whether the protocol supports the supplied content type
*
* @param contentType the type we want to check
* @return <tt>true</tt> if the protocol supports it and
* <tt>false</tt> otherwise.
*/
public boolean isContentTypeSupported(String contentType)
{
if(contentType.equals(DEFAULT_MIME_TYPE))
return true;
else
return false;
}
public void sendInstantMessage(Contact to, Message message)
throws IllegalStateException, IllegalArgumentException
{
if (! (to instanceof ContactSipImpl))
throw new IllegalArgumentException(
"The specified contact is not a Sip contact."
+ to);
assertConnected();
// offline message
if (to.getPresenceStatus().equals(
sipStatusEnum.getStatus(SipStatusEnum.OFFLINE))
&& !offlineMessageSupported)
{
logger.debug("trying to send a message to an offline contact");
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
message,
to,
MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED,
new Date());
fireMessageEvent(evt);
return;
}
// create the message
Request mes;
try
{
mes = createMessage(to, message);
}
catch (OperationFailedException ex)
{
logger.error(
"Failed to create the message."
, ex);
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
message,
to,
MessageDeliveryFailedEvent.INTERNAL_ERROR,
new Date());
fireMessageEvent(evt);
return;
}
sendRequestMessage(mes, to, message);
}
void sendRequestMessage(Request mes, Contact to, Message message)
{
//check whether there's a cached authorization header for this
//call id and if so - attach it to the request.
// add authorization header
CallIdHeader call = (CallIdHeader)mes.getHeader(CallIdHeader.NAME);
String callid = call.getCallId();
AuthorizationHeader authorization = sipProvider
.getSipSecurityManager()
.getCachedAuthorizationHeader(callid);
if(authorization != null)
mes.addHeader(authorization);
//Transaction
ClientTransaction messageTransaction;
SipProvider jainSipProvider
= this.sipProvider.getDefaultJainSipProvider();
try
{
messageTransaction = jainSipProvider.getNewClientTransaction(mes);
}
catch (TransactionUnavailableException ex)
{
logger.error(
"Failed to create messageTransaction.\n"
+ "This is most probably a network connection error."
, ex);
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
message,
to,
MessageDeliveryFailedEvent.NETWORK_FAILURE,
new Date());
fireMessageEvent(evt);
return;
}
// send the message
try
{
messageTransaction.sendRequest();
}
catch (SipException ex)
{
logger.error(
"Failed to send the message."
, ex);
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
message,
to,
MessageDeliveryFailedEvent.INTERNAL_ERROR,
new Date());
fireMessageEvent(evt);
return;
}
// we register the reference to this message to retrieve it when
// we'll receive the response message
String key = ((CallIdHeader)mes.getHeader(CallIdHeader.NAME))
.getCallId();
this.sentMsg.put(key, message);
}
/**
* Construct a Request which represent a new message
*
* @param to the <tt>Contact</tt> to send <tt>message</tt> to
* @param message the <tt>Message</tt> to send.
* @return a Message Request destinated to the contact
* @throws OperationFailedException if an error occurred during
* the creation of the request
*/
Request createMessage(Contact to, Message message)
throws OperationFailedException
{
// Address
InetAddress destinationInetAddress = null;
Address toAddress = null;
try
{
toAddress = parseAddressStr(to.getAddress());
destinationInetAddress = InetAddress.getByName(
( (SipURI) toAddress.getURI()).getHost());
}
catch (UnknownHostException ex)
{
throw new IllegalArgumentException(
( (SipURI) toAddress.getURI()).getHost()
+ " is not a valid internet address " + ex.getMessage());
}
catch (ParseException exc)
{
//Shouldn't happen
logger.error(
"An unexpected error occurred while"
+ "constructing the address", exc);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the address"
, OperationFailedException.INTERNAL_ERROR
, exc);
}
// Call ID
CallIdHeader callIdHeader = this.sipProvider
.getDefaultJainSipProvider().getNewCallId();
//CSeq
CSeqHeader cSeqHeader = null;
try
{
cSeqHeader = this.sipProvider.getHeaderFactory()
.createCSeqHeader(seqN++, Request.MESSAGE);
}
catch (InvalidArgumentException ex)
{
//Shouldn't happen
logger.error(
"An unexpected error occurred while"
+ "constructing the CSeqHeadder", ex);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the CSeqHeadder"
, OperationFailedException.INTERNAL_ERROR
, ex);
}
catch (ParseException exc)
{
//shouldn't happen
logger.error(
"An unexpected error occurred while"
+ "constructing the CSeqHeadder", exc);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the CSeqHeadder"
, OperationFailedException.INTERNAL_ERROR
, exc);
}
//FromHeader and ToHeader
String localTag = ProtocolProviderServiceSipImpl.generateLocalTag();
FromHeader fromHeader = null;
ToHeader toHeader = null;
try
{
//FromHeader
fromHeader = this.sipProvider.getHeaderFactory()
.createFromHeader(this.sipProvider.getOurSipAddress()
, localTag);
//ToHeader
toHeader = this.sipProvider.getHeaderFactory()
.createToHeader(toAddress, null);
}
catch (ParseException ex)
{
//these two should never happen.
logger.error(
"An unexpected error occurred while"
+ "constructing the FromHeader or ToHeader", ex);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the FromHeader or ToHeader"
, OperationFailedException.INTERNAL_ERROR
, ex);
}
//ViaHeaders
ArrayList viaHeaders = this.sipProvider.getLocalViaHeaders(
destinationInetAddress
, this.sipProvider.getDefaultListeningPoint());
//MaxForwards
MaxForwardsHeader maxForwards = this.sipProvider
.getMaxForwardsHeader();
// Content params
ContentTypeHeader contTypeHeader;
ContentLengthHeader contLengthHeader;
try
{
contTypeHeader = this.sipProvider.getHeaderFactory()
.createContentTypeHeader(getType(message),
getSubType(message));
if (! DEFAULT_MIME_ENCODING.equalsIgnoreCase(message.getEncoding()))
contTypeHeader.setParameter("charset", message.getEncoding());
contLengthHeader = this.sipProvider.getHeaderFactory()
.createContentLengthHeader(message.getSize());
}
catch (ParseException ex)
{
//these two should never happen.
logger.error(
"An unexpected error occurred while"
+ "constructing the content headers", ex);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the content headers"
, OperationFailedException.INTERNAL_ERROR
, ex);
}
catch (InvalidArgumentException exc)
{
//these two should never happen.
logger.error(
"An unexpected error occurred while"
+ "constructing the content length header", exc);
throw new OperationFailedException(
"An unexpected error occurred while"
+ "constructing the content length header"
, OperationFailedException.INTERNAL_ERROR
, exc);
}
Request req;
try
{
req = this.sipProvider.getMessageFactory().createRequest(
toHeader.getAddress().getURI(),
Request.MESSAGE,
callIdHeader,
cSeqHeader,
fromHeader,
toHeader,
viaHeaders,
maxForwards,
contTypeHeader,
message.getRawData());
}
catch (ParseException ex)
{
//shouldn't happen
logger.error(
"Failed to create message Request!", ex);
throw new OperationFailedException(
"Failed to create message Request!"
, OperationFailedException.INTERNAL_ERROR
, ex);
}
req.addHeader(contLengthHeader);
return req;
}
/**
* Parses the the <tt>uriStr</tt> string and returns a JAIN SIP URI.
*
* @param uriStr a <tt>String</tt> containing the uri to parse.
*
* @return a URI object corresponding to the <tt>uriStr</tt> string.
* @throws ParseException if uriStr is not properly formatted.
*/
private Address parseAddressStr(String uriStr)
throws ParseException
{
uriStr = uriStr.trim();
//Handle default domain name (i.e. transform 1234 -> 1234@sip.com)
//assuming that if no domain name is specified then it should be the
//same as ours.
if (uriStr.indexOf('@') == -1
&& !uriStr.trim().startsWith("tel:"))
{
uriStr = uriStr + "@"
+ ( (SipURI)this.sipProvider.getOurSipAddress().getURI())
.getHost();
}
//Let's be uri fault tolerant and add the sip: scheme if there is none.
if (uriStr.toLowerCase().indexOf("sip:") == -1 //no sip scheme
&& uriStr.indexOf('@') != -1) //most probably a sip uri
{
uriStr = "sip:" + uriStr;
}
//Request URI
Address uri
= this.sipProvider.getAddressFactory().createAddress(uriStr);
return uri;
}
/**
* Parses the content type of a message and return the type
*
* @param msg the Message to scan
* @return the type of the message
*/
private String getType(Message msg)
{
String type = msg.getContentType();
return type.substring(0, type.indexOf('/'));
}
/**
* Parses the content type of a message and return the subtype
*
* @param msg the Message to scan
* @return the subtype of the message
*/
private String getSubType(Message msg)
{
String subtype = msg.getContentType();
return subtype.substring(subtype.indexOf('/') + 1);
}
private void assertConnected()
throws IllegalStateException
{
if (this.sipProvider == null)
throw new IllegalStateException(
"The provider must be non-null and signed on the "
+ "service before being able to communicate.");
if (!this.sipProvider.isRegistered())
throw new IllegalStateException(
"The provider must be signed on the service before "
+ "being able to communicate.");
}
/**
* Our listener that will tell us when we're registered to
*/
private class RegistrationStateListener
implements RegistrationStateChangeListener
{
/**
* The method is called by a ProtocolProvider implementation whenever
* a change in the registration state of the corresponding provider had
* occurred.
* @param evt ProviderStatusChangeEvent the event describing the status
* change.
*/
public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
logger.debug("The provider changed state from: "
+ evt.getOldState()
+ " to: " + evt.getNewState());
if (evt.getNewState() == RegistrationState.REGISTERED)
{
opSetPersPresence = (OperationSetPresenceSipImpl)
sipProvider.getSupportedOperationSets()
.get(OperationSetPersistentPresence.class.getName());
}
}
}
/**
* Delivers the specified event to all registered message listeners.
* @param evt the <tt>EventObject</tt> that we'd like delivered to all
* registered message listeners.
*/
private void fireMessageEvent(EventObject evt)
{
Iterator listeners = null;
synchronized (this.messageListeners)
{
listeners = new ArrayList(this.messageListeners).iterator();
}
logger.debug("Dispatching Message Listeners="
+ messageListeners.size()
+ " evt=" + evt);
while (listeners.hasNext())
{
MessageListener listener
= (MessageListener) listeners.next();
if (evt instanceof MessageDeliveredEvent)
{
listener.messageDelivered( (MessageDeliveredEvent) evt);
}
else if (evt instanceof MessageReceivedEvent)
{
listener.messageReceived( (MessageReceivedEvent) evt);
}
else if (evt instanceof MessageDeliveryFailedEvent)
{
listener.messageDeliveryFailed(
(MessageDeliveryFailedEvent) evt);
}
}
}
/**
* Class for listening incoming packets.
*/
private class SipMessageListener
implements SipListener
{
public void processDialogTerminated(
DialogTerminatedEvent dialogTerminatedEvent)
{
// never fired
}
public void processIOException(IOExceptionEvent exceptionEvent)
{
// never fired
}
public void processTransactionTerminated(
TransactionTerminatedEvent transactionTerminatedEvent)
{
// nothing to do
}
/**
*
* @param timeoutEvent TimeoutEvent
*/
public void processTimeout(TimeoutEvent timeoutEvent)
{
// this is normaly handled by the SIP stack
logger.error("Timeout event thrown : " + timeoutEvent.toString());
if (timeoutEvent.isServerTransaction()) {
logger.warn("The sender has probably not received our OK");
return;
}
Request req = timeoutEvent.getClientTransaction().getRequest();
// get the content
String content = null;
try
{
content = new String(req.getRawContent(), getCharset(req));
}
catch (UnsupportedEncodingException ex)
{
logger.warn("failed to convert the message charset", ex);
content = new String(req.getRawContent());
}
// to who this request has been sent ?
ToHeader toHeader = (ToHeader) req.getHeader(ToHeader.NAME);
if (toHeader == null)
{
logger.error("received a request without a to header");
return;
}
Contact to = resolveContact(
toHeader.getAddress().getURI().toString());
Message failedMessage = null;
if (to == null) {
logger.error(
"timeout on a message sent to an unknown contact : "
+ toHeader.getAddress().getURI().toString());
//we don't know what message it concerns, so create a new
//one
failedMessage = createMessage(content);
}
else
{
// try to retrieve the original message
String key = ((CallIdHeader)req.getHeader(CallIdHeader.NAME))
.getCallId();
failedMessage = (Message) sentMsg.get(key);
if (failedMessage == null)
{
// should never happen
logger.error("Couldn't find the sent message.");
// we don't know what the message is so create a new one
//based on the content of the failed request.
failedMessage = createMessage(content);
}
}
// error for delivering the message
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
// we don't know what message it concerns
failedMessage,
to,
MessageDeliveryFailedEvent.INTERNAL_ERROR,
new Date());
fireMessageEvent(evt);
}
/**
* Process a request from a distant contact
*
* @param requestEvent the <tt>RequestEvent</tt> containing the newly
* received request.
*/
public void processRequest(RequestEvent requestEvent)
{
synchronized (messageProcessors)
{
Iterator iter = messageProcessors.iterator();
while (iter.hasNext())
{
SipMessageProcessor listener
= (SipMessageProcessor)iter.next();
if(!listener.processMessage(requestEvent))
return;
}
}
// get the content
String content = null;
try
{
Request req = requestEvent.getRequest();
content = new String(req.getRawContent(), getCharset(req));
}
catch (UnsupportedEncodingException ex)
{
logger.debug("failed to convert the message charset");
content = new String(requestEvent.getRequest().getRawContent());
}
// who sent this request ?
FromHeader fromHeader = (FromHeader)
requestEvent.getRequest().getHeader(FromHeader.NAME);
if (fromHeader == null)
{
logger.error("received a request without a from header");
return;
}
Contact from = resolveContact(
fromHeader.getAddress().getURI().toString());
Message newMessage = createMessage(content);
if (from == null) {
logger.debug("received a message from an unknown contact: "
+ fromHeader.getAddress().getURI().toString());
//create the volatile contact
from = opSetPersPresence
.createVolatileContact(fromHeader.getAddress().getURI()
.toString().substring(4));
}
// answer ok
try
{
Response ok = sipProvider.getMessageFactory()
.createResponse(Response.OK, requestEvent.getRequest());
SipProvider jainSipProvider = (SipProvider) requestEvent.
getSource();
jainSipProvider.getNewServerTransaction(
requestEvent.getRequest()).sendResponse(ok);
}
catch (ParseException exc)
{
logger.error("failed to build the response", exc);
}
catch (SipException exc)
{
logger.error("failed to send the response : "
+ exc.getMessage(),
exc);
}
catch (InvalidArgumentException exc)
{
logger.debug("Invalid argument for createResponse : "
+ exc.getMessage(),
exc);
}
// fire an event
MessageReceivedEvent msgReceivedEvt
= new MessageReceivedEvent(
newMessage, from, new Date());
fireMessageEvent(msgReceivedEvt);
}
/**
* Process a response from a distant contact.
*
* @param responseEvent the <tt>ResponseEvent</tt> containing the newly
* received SIP response.
*/
public void processResponse(ResponseEvent responseEvent)
{
Request req = responseEvent.getClientTransaction().getRequest();
int status = responseEvent.getResponse().getStatusCode();
// content of the response
String content = null;
try
{
content = new String(req.getRawContent(), getCharset(req));
}
catch (UnsupportedEncodingException exc)
{
logger.debug("failed to convert the message charset", exc);
content = new String(req.getRawContent());
}
// to who did we send the original message ?
ToHeader toHeader = (ToHeader)
req.getHeader(ToHeader.NAME);
if (toHeader == null)
{
// should never happen
logger.error("send a request without a to header");
return;
}
Contact to = resolveContact(toHeader.getAddress()
.getURI().toString());
if (to == null) {
logger.error(
"Error received a response from an unknown contact : "
+ toHeader.getAddress().getURI().toString() + " : "
+ responseEvent.getResponse().getReasonPhrase());
// error for delivering the message
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
// we don't know what message it concerns
createMessage(content),
to,
MessageDeliveryFailedEvent.INTERNAL_ERROR,
new Date());
fireMessageEvent(evt);
return;
}
// we retrieve the original message
String key = ((CallIdHeader)req.getHeader(CallIdHeader.NAME))
.getCallId();
Message newMessage = (Message) sentMsg.get(key);
if (newMessage == null) {
// should never happen
logger.error("Couldn't find the message sent");
// error for delivering the message
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
// we don't know what message it is
createMessage(content),
to,
MessageDeliveryFailedEvent.INTERNAL_ERROR,
new Date());
fireMessageEvent(evt);
return;
}
// status 401/407 = proxy authentification
if (status >= 400 && status != 401 && status != 407)
{
logger.info(
"Error received from the network : "
+ responseEvent.getResponse().getReasonPhrase());
// error for delivering the message
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
newMessage,
to,
MessageDeliveryFailedEvent.NETWORK_FAILURE,
new Date(),
responseEvent.getResponse().getReasonPhrase());
fireMessageEvent(evt);
sentMsg.remove(key);
}
else if (status == 401 || status == 407)
{
// proxy ask for authentification
logger.debug(
"proxy asks authentication : "
+ responseEvent.getResponse().getReasonPhrase());
ClientTransaction clientTransaction = responseEvent
.getClientTransaction();
SipProvider sourceProvider = (SipProvider)
responseEvent.getSource();
try
{
processAuthenticationChallenge(clientTransaction,
responseEvent.getResponse(),
sourceProvider);
}
catch (OperationFailedException ex)
{
logger.error("can't solve the challenge", ex);
// error for delivering the message
MessageDeliveryFailedEvent evt =
new MessageDeliveryFailedEvent(
newMessage,
to,
MessageDeliveryFailedEvent.NETWORK_FAILURE,
new Date(),
ex.getMessage());
fireMessageEvent(evt);
sentMsg.remove(key);
}
}
else if (status >= 200)
{
logger.debug(
"Ack received from the network : "
+ responseEvent.getResponse().getReasonPhrase());
// we delivered the message
MessageDeliveredEvent msgDeliveredEvt
= new MessageDeliveredEvent(
newMessage, to, new Date());
fireMessageEvent(msgDeliveredEvt);
// we don't need this message anymore
sentMsg.remove(key);
}
}
/**
* Try to find a charset in a MESSAGE request for the
* text content. If no charset is defined, the default charset
* for text messages is returned.
*
* @param req the MESSAGE request in which to look for a charset
* @return defined charset in the request or DEFAULT_MIME_ENCODING
* if no charset is specified
*/
private String getCharset(Request req)
{
String charset = null;
Header contentTypeHeader = req.getHeader(ContentTypeHeader.NAME);
if (contentTypeHeader instanceof ContentTypeHeader)
charset = ((ContentTypeHeader) contentTypeHeader)
.getParameter("charset");
if (charset == null)
charset = DEFAULT_MIME_ENCODING;
return charset;
}
/**
* Try to find a contact registered using a string to identify him.
*
* @param contactID A string with which the contact may have
* been registered
* @return A valid contact if it has been found, null otherwise
*/
private Contact resolveContact(String contactID) {
Contact res = opSetPersPresence.findContactByID(contactID);
if (res == null) {
// we try to resolve the conflict by removing "sip:" from the id
if (contactID.startsWith("sip:")) {
res = opSetPersPresence.findContactByID(
contactID.substring(4));
}
if (res == null) {
// we try to remove the part after the '@'
if (contactID.indexOf('@') > -1) {
res = opSetPersPresence.findContactByID(
contactID.substring(0,
contactID.indexOf('@')));
if (res == null) {
// try the same thing without sip:
if (contactID.startsWith("sip:")) {
res = opSetPersPresence.findContactByID(
contactID.substring(4,
contactID.indexOf('@')));
}
}
}
}
}
return res;
}
/**
* Attempts to re-generate the corresponding request with the proper
* credentials.
*
* @param clientTransaction the corresponding transaction
* @param response the challenge
* @param jainSipProvider the provider that received the challenge
*
* @throws OperationFailedException if processing the authentication
* challenge fails.
*/
private void processAuthenticationChallenge(
ClientTransaction clientTransaction,
Response response,
SipProvider jainSipProvider)
throws OperationFailedException
{
try
{
logger.debug("Authenticating a message request.");
ClientTransaction retryTran
= sipProvider.getSipSecurityManager().handleChallenge(
response
, clientTransaction
, jainSipProvider);
if(retryTran == null)
{
logger.trace("No password supplied or error occured!");
return;
}
retryTran.sendRequest();
return;
}
catch (Exception exc)
{
logger.error("We failed to authenticate a message request.",
exc);
throw new OperationFailedException("Failed to authenticate"
+ "a message request"
, OperationFailedException.INTERNAL_ERROR
, exc);
}
}
}
}
|
package com.cube.storm.ui.model;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import lombok.Getter;
/**
* Base model class for all Storm objects
*
* @author Callum Taylor
* @project StormUI
*/
public abstract class Model implements Serializable, Parcelable
{
@SerializedName("class") @Getter protected String className;
}
|
//@author A0111875E
package com.epictodo.engine;
import com.epictodo.controller.nlp.SentenceAnalysis;
import com.epictodo.controller.nlp.SentenceStructure;
import com.epictodo.model.Response;
import com.epictodo.util.DateValidator;
import com.epictodo.util.TimeValidator;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.ParseException;
import java.util.*;
public class NLPEngine {
protected static StanfordCoreNLP _pipeline;
private static NLPEngine instance = null;
private NLPLoadEngine load_engine = NLPLoadEngine.getInstance();
private TimeValidator time_validator = TimeValidator.getInstance();
private DateValidator date_validator = DateValidator.getInstance();
private SentenceAnalysis sentence_analysis = new SentenceAnalysis();
private SentenceStructure sentence_struct = new SentenceStructure();
private Response _response = new Response();
private PrintStream _err = System.err;
public NLPEngine() {
_pipeline = load_engine._pipeline;
}
/**
* This method ensures that there will only be one running instance
*
* @return
*/
public static NLPEngine getInstance() {
if (instance == null) {
instance = new NLPEngine();
}
return instance;
}
/**
* This method mutes NLP API Error Messages temporarily
* This works for all console messages
* <p/>
* Usage:
* <p/>
* mute();
*/
public void mute() {
System.setErr(new PrintStream(new OutputStream() {
public void write(int b) {
}
}));
}
/**
* This method restores NLP API Error Messages to be displayed
* This method works for all console messages.
* <p/>
* Usage:
* <p/>
* restore();
*/
public void restore() {
System.setErr(_err);
}
public Response flexiAdd(String _sentence) throws ParseException {
boolean is_date_set = false;
boolean is_time_set = false;
boolean is_priority_set = false;
boolean to_check = false;
String tomorrow_date;
String date_value;
String time_value;
String _priority;
String start_time;
String end_time;
double _duration;
int num_days;
List<String> analyzed_results = new ArrayList<>();
List<String> task_name = new ArrayList<>();
List<String> task_desc = new ArrayList<>();
List<String> task_date = new ArrayList<>();
List<String> task_time = new ArrayList<>();
// Initialize Sentence Structure & Sentence Analysis to Map
Map<String, String> sentence_struct_map = sentence_struct.sentenceDependencies(_sentence);
Map<String, String> date_time_map = sentence_analysis.dateTimeAnalyzer(_sentence);
Map<String, String> sentence_token_map = sentence_analysis.sentenceAnalyzer(_sentence);
LinkedHashMap<String, LinkedHashSet<String>> entities_map = sentence_analysis.nerEntitiesExtractor(_sentence);
/**
* Name Entity Recognition (NER) map
* For loop to traverse key:value of NER map to retrieve keywords to be processed
*
* Example: root, nn, dobj, nsubj, aux, xcomp, prep, num, etc.
*
*/
for (Map.Entry<String, LinkedHashSet<String>> map_result : entities_map.entrySet()) {
String _key = map_result.getKey();
LinkedHashSet<String> _value = map_result.getValue();
}
/**
* Sentence analyzer to analyze the text for keywords
* For loop to traverse the following:
*
* 1. (TIME) - stores TIME's (value) key to check if it's a single or multiple TIME value
* 1.1. Checks if key is valid time before storing.
* 1.2. "at" maybe classified as a valid TIME but we do not want to register this
*
* 2. (PERSON) - stores PERSON name to be processed in Task Description
* 2.1. PERSON does not accept 'Prof' as an actual person, rather an entity
*
* 3. (LOCATION) - stores LOCATION name if it exists.
* 3.1. TOKYO, SINGAPORE are actual LOCATION
* 3.2. COM1, LT15, SR1 are not an actual LOCATION stored in our model (can be implemented using Classifier in future)
*
*/
for (Map.Entry<String, String> map_result : sentence_token_map.entrySet()) {
String _key = map_result.getKey();
String _value = map_result.getValue();
if (_value.equalsIgnoreCase("TIME")) {
if (time_validator.validate(_key)) {
task_time.add(_key);
}
}
if (_value.equalsIgnoreCase("NUMBER")) {
if (date_validator.validateDateExpression(_key)) {
date_value = date_validator.fixShortDate(_key);
task_date.add(date_value);
num_days = date_validator.compareDate(date_value);
// Checks if date distance is >= 0 or <= 1 of 1 day
if (num_days >= 0 && num_days <= 1) {
_priority = date_validator.determinePriority(date_value);
date_value = date_validator.genericDateFormat(date_value);
_response.setTaskDate(date_value);
_response.setPriority(Integer.parseInt(_priority));
is_priority_set = true;
} else { // Check if TaskDate has been set previously, prevent override
_priority = date_validator.determinePriority(date_value);
date_value = date_validator.genericDateFormat(date_value);
_response.setTaskDate(date_value);
_response.setPriority(Integer.parseInt(_priority));
is_priority_set = true;
}
is_date_set = true;
}
}
if (_value.equalsIgnoreCase("PERSON")) {
if (!_key.equalsIgnoreCase("Prof")) {
task_desc.add(_key);
analyzed_results.add(_key);
} else {
task_desc.add(_key);
analyzed_results.add(_key);
}
} else if (_value.equalsIgnoreCase("LOCATION")) {
task_desc.add(_key);
analyzed_results.add(_key);
} else if (_value.equalsIgnoreCase("ORGANIZATION")) {
task_desc.add(_key);
analyzed_results.add(_key);
}
}
/**
* This algorithm checks if the time values stored are more than or equals to 2
* There can be instances where users input 3 or more time variables, but the first 2 will be registered
*
* This algorithm will getTimeDuration before storing start_time, end_time & _duration to _response
*/
if (task_time.size() != 0 && task_time.size() >= 2) {
start_time = task_time.get(0);
end_time = task_time.get(1);
_duration = time_validator.getTimeDuration(start_time, end_time);
_response.setStartTime(start_time);
_response.setEndTime(end_time);
_response.setTaskDuration(_duration);
is_time_set = true;
} else if (task_time.size() != 0 && task_time.size() < 2) {
_response.setTaskTime(task_time.get(0));
is_time_set = true;
}
/**
* Date time analyzer map to analyze date time values to be stored
* This algorithm will check for TOMORROW date & time distance.
*
* If that case happens, the result will be parsed to getDateInFormat & getTimeInFormat to handle such cases
* Otherwise, the result will be parsed to validateDate & validateTime to handle the more generic cases
*/
for (Map.Entry<String, String> map_result : date_time_map.entrySet()) {
String _key = map_result.getKey();
String _value = map_result.getValue();
tomorrow_date = date_validator.convertDateFormat(_value);
num_days = date_validator.compareDate(tomorrow_date);
// Checks if date distance is >= 0 or <= 1 of 1 day
if (num_days >= 0 && num_days <= 1) {
_priority = date_validator.determinePriority(tomorrow_date);
date_value = date_validator.genericDateFormat(tomorrow_date);
time_value = date_validator.getTimeInFormat(_value);
if (!is_date_set) { // Check if TaskDate has been set previously, prevent override
_response.setTaskDate(date_value);
is_date_set = true;
}
if (!is_time_set) {
_response.setTaskTime(time_value);
is_time_set = true;
}
if (!is_priority_set) {
_response.setPriority(Integer.parseInt(_priority));
is_priority_set = true;
}
// _response.setTaskDate(date_value);
// _response.setTaskTime(time_value);
// _response.setPriority(Integer.parseInt(_priority));
task_desc.add(_key);
analyzed_results.add(_key);
analyzed_results.add(date_value);
analyzed_results.add(time_value);
analyzed_results.add(_priority);
} else { // Check if TaskDate has been set previously, prevent override
_priority = date_validator.determinePriority(_value);
date_value = date_validator.genericDateFormat(tomorrow_date);
time_value = date_validator.validateTime(_value);
if (!is_date_set) {
_response.setTaskDate(date_value);
is_date_set = true;
}
if (!is_time_set) {
_response.setTaskTime(time_value);
is_time_set = true;
}
if (!is_priority_set) {
_response.setPriority(Integer.parseInt(_priority));
is_priority_set = true;
}
// _response.setTaskDate(date_value);
// _response.setTaskTime(time_value);
// _response.setPriority(Integer.parseInt(_priority));
task_desc.add(_key);
analyzed_results.add(_key);
analyzed_results.add(date_value);
analyzed_results.add(time_value);
analyzed_results.add(_priority);
}
}
/**
* Sentence Dependencies map to analyze and return the dependencies of the sentence structure
* This algorithm checks the dependencies relationship in the tree structure, and returns the results
*/
for (Map.Entry<String, String> map_result : sentence_struct_map.entrySet()) {
String _key = map_result.getKey();
String _value = map_result.getValue();
if ((_key.equalsIgnoreCase("root") || _key.equalsIgnoreCase("dep") || _key.equalsIgnoreCase("dobj") ||
_key.equalsIgnoreCase("prep_on") || _key.equalsIgnoreCase("prep_for") || _key.equalsIgnoreCase("nn") ||
_key.equalsIgnoreCase("xcomp")) &&
(!_value.equalsIgnoreCase("to") || _value.equalsIgnoreCase("aux"))) {
task_name.add(_value);
analyzed_results.add(_value);
}
}
_response.setTaskName(task_name);
_response.setTaskDesc(task_desc);
return _response;
}
}
|
package org.wyona.yanel.impl.resources.login;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yanel.core.util.MailUtil;
import org.wyona.yanel.servlet.YanelServlet;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.http.HttpServletResponse;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.BasicHttpParams;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import java.util.Date;
/**
* Handle OAuth 2.0 callback
*/
public class OAuth2CallbackResource extends Resource implements ViewableV2 {
private static Logger log = LogManager.getLogger(OAuth2CallbackResource.class);
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return true;
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getSize()
*/
public long getSize() throws Exception {
return -1;
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getView(String)
*/
public View getView(String viewId) throws Exception {
View view = new View();
view.setResponse(false); // this resource writes the response itself
HttpServletResponse response = getEnvironment().getResponse();
try {
String state = getEnvironment().getRequest().getParameter("state");
log.warn("TODO: Check state '" + state + "' ...");
if (false) {
throw new Exception("Checking 'state' parameter failed!");
}
String token_endpoint = getDiscoveryDocument();
String code = getEnvironment().getRequest().getParameter("code");
String id_token = getAccessAndIdToken(token_endpoint, code);
if (id_token == null) {
throw new Exception("Getting 'id_token' failed!");
}
Payload userInfo = getPayload(id_token);
log.warn("DEBUG: Expiry date: " + userInfo.getExpiryDate());
String email = userInfo.getEmail();
User user = null;
if (getRealm().getIdentityManager().getUserManager().existsAlias(email)) {
String trueId = realm.getIdentityManager().getUserManager().getTrueId(userInfo.getEmail());
user = realm.getIdentityManager().getUserManager().getUser(trueId, true);
} else {
log.warn("User '" + email + "' does not exist yet, hence create account and login user ...");
user = getRealm().getIdentityManager().getUserManager().createUser(userInfo.getId(), "TODO:gmail", email, null);
getRealm().getIdentityManager().getUserManager().createAlias(email, user.getID());
addUserToGroups(user);
if (getResourceConfigProperty("administrator-email") != null) {
notifyAdmin(user);
}
}
YanelServlet.setIdentity(new Identity(user, email), getEnvironment().getRequest().getSession(true), realm);
response.setHeader("Location", getResourceConfigProperty("redirect-landing-page-url"));
response.setStatus(307);
} catch(Exception e) {
log.error(e.getMessage());
response.setStatus(500);
}
return view;
}
/**
* Notify administrator, that user has been registered
*/
private void notifyAdmin(User user) throws Exception {
String email = getResourceConfigProperty("administrator-email");
StringBuilder body = new StringBuilder("User account with email address '" + user.getEmail() + "' has been created.");
MailUtil.send(getYanel().getAdministratorEmail(), email, "[" + getRealm().getName() + "] User account has been created", body.toString());
}
/**
* Add registered user to particular groups by default
* @param user User to be added to groups
*/
private void addUserToGroups(User user) throws Exception {
// TODO: See src/resources/registration/src/java/org/wyona/yanel/resources/registration/UserRegistrationResource.java#addUserToGroups(User)
String groupsCSV = getResourceConfigProperty("groups");
if (groupsCSV != null) {
String[] groupIDs = null;
if (groupsCSV.indexOf(",") >= 0) {
groupIDs = groupsCSV.split(",");
} else {
groupIDs = new String[1];
groupIDs[0] = groupsCSV;
}
for (int i = 0; i < groupIDs.length; i++) {
if (getRealm().getIdentityManager().getGroupManager().existsGroup(groupIDs[i])) {
log.debug("Add user '" + user.getEmail() + "' to group: " + groupIDs[i]);
getRealm().getIdentityManager().getGroupManager().getGroup(groupIDs[i]).addMember(user);
} else {
log.warn("No such group: " + groupIDs[i]);
}
}
}
}
/**
* @return URL of token endpoint
*/
private String getDiscoveryDocument() {
log.warn("TODO: Get token endpoint URL from discovery document!");
return "https:
}
private String getAccessAndIdToken(String token_endpoint, String code) {
int connectionTimeout = 2000;
int socketTimeout = 25000;
try {
StringBuilder qs = new StringBuilder("?");
qs.append("code=" + code);
qs.append("&");
qs.append("client_id=" + getResourceConfigProperty("client_id"));
qs.append("&");
qs.append("client_secret=" + getResourceConfigProperty("client_secret"));
qs.append("&");
qs.append("redirect_uri=" + getResourceConfigProperty("redirect_uri"));
qs.append("&");
qs.append("grant_type=authorization_code");
java.net.URL url = new java.net.URL(token_endpoint);
//log.debug("Get Access and Id Token from '" + url + qs + "' ...");
DefaultHttpClient httpClient = getHttpClient(url, null, null, connectionTimeout, socketTimeout);
HttpPost httpPost = new HttpPost(url.toString() + qs);
//httpPost.setEntity(new StringEntity("{\"code\":\"" + code + "\",\"client_id\":\"" + getResourceConfigProperty("client_id") + "\"}", "utf-8"));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
ObjectMapper jsonPojoMapper = new ObjectMapper();
java.io.InputStream in = response.getEntity().getContent();
JsonNode rootNode = jsonPojoMapper.readTree(in);
in.close();
log.warn("DEBUG: Response code 200 ...");
return getIdTokenFromJson(rootNode);
} else {
log.error("Response code '" + response.getStatusLine().getStatusCode() + "'");
return null;
}
} catch(Exception e) {
log.error(e, e);
return null;
}
}
/**
* Get value of 'id_token' from JSON
*/
private String getIdTokenFromJson(JsonNode rootNode) {
java.util.Iterator<String> it = rootNode.getFieldNames();
while (it.hasNext()) {
log.debug("Field name: " + it.next());
}
return rootNode.path("id_token").getTextValue();
}
/**
* Get http client using SSL if necessary and basic authentication set
* @param username Username for basic authentication
* @param password Password for basic authentication
* @param connectionTimeout Value of CONNECTION_TIMEOUT
* @param socketTimeout Value of SO_TIMEOUT
* @return http client
* TODO: Re-use org.wyona.yanel.core.source.HttpResolver#getHttpClient(...)
*/
private DefaultHttpClient getHttpClient(java.net.URL url, String username, String password, int connectionTimeout, int socketTimeout) throws Exception {
HttpParams httpParams = new BasicHttpParams();
if (connectionTimeout >= 0) {
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
} else {
log.warn("No connection timeout set, hence use default value: " + HttpConnectionParams.getConnectionTimeout(httpParams));
}
if (socketTimeout >= 0) {
HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
} else {
log.warn("No socket timeout set, hence use default value: " + HttpConnectionParams.getSoTimeout(httpParams));
}
String yanelVersion = org.wyona.yanel.core.Yanel.getInstance().getVersion();
HttpProtocolParams.setUserAgent(httpParams, "Yanel/" + yanelVersion + " HttpResolver");
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
if (url.getProtocol().equals("https")) {
httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", 443, getSSLFactory()));
} else {
log.warn("Unsecure connection: " + url); }
if (username != null && password != null) {
log.debug("Set BASIC AUTH for username '" + username + "'...");
httpClient.getCredentialsProvider().setCredentials(new org.apache.http.auth.AuthScope(url.getHost(), url.getPort()), new org.apache.http.
auth.UsernamePasswordCredentials(username, password));
} else {
log.debug("No BASIC AUTH credentials set.");
}
return httpClient;
}
/**
* Get SSL factory
* TODO: Re-use org.wyona.yanel.core.source.HttpResolver#getSSLFactory()
*/
private org.apache.http.conn.ssl.SSLSocketFactory getSSLFactory() throws Exception {
// TODO: Make SSLSocketFactory configurable...
// INFO: Just trust the certificate without checking/comparing a list of trusted certificates
org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(new org.apache.http.conn.ssl.TrustStrategy() {
public boolean isTrusted(final java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
return true;
}
}, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
//org.apache.http.conn.ssl.SSLSocketFactory factory = new org.apache.http.conn.ssl.SSLSocketFactory(getSSLContext(), new org.apache.http.conn.ssl.StrictHostnameVerifier());
return factory;
}
/**
* Get user information
*/
private Payload getPayload(String id_token) throws Exception {
// INFO: Analyze JWT, e.g. get unique user Id and user email and ... see https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo
//log.debug("Decode id_token '" + id_token + "' ....");
String jwtBodyJSon = decodeJWT(id_token);
log.warn("DEBUG: Decoded JWT: " + jwtBodyJSon);
Payload payload = new Payload(jwtBodyJSon);
return payload;
}
/**
* Decode JWT
* @return decoded JWT as JSON
*/
private String decodeJWT(String jwt) {
String[] splittedJWT = jwt.split("\\.");
String base64EncodedHeader = splittedJWT[0];
String base64EncodedBody = splittedJWT[1];
String base64EncodedSignature = splittedJWT[2];
Base64 base64Url = new Base64(true);
return new String(base64Url.decode(base64EncodedBody));
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getViewDescriptors()
*/
public ViewDescriptor[] getViewDescriptors() {
log.warn("Not implemented!");
return null;
}
}
class Payload {
private String sub;
private String email;
private Date expiryDate;
/**
* @param decodedJWT Decoded JWT as JSON
*/
public Payload(String decodedJWT) throws Exception {
ObjectMapper jsonPojoMapper = new ObjectMapper();
JsonNode rootNode = jsonPojoMapper.readTree(decodedJWT);
this.sub = rootNode.path("sub").getTextValue();
this.email = rootNode.path("email").getTextValue();
this.expiryDate = new Date(rootNode.path("exp").getLongValue());
}
public String getEmail() {
return email;
}
public String getId() {
return sub;
}
public Date getExpiryDate() {
return expiryDate;
}
}
|
package com.heroku.config;
import com.heroku.shiro.MyShiroRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Value("${spring.redis.url}")
private String url;
@Value("${spring.redis.timeout}")
private int timeout;
/**
* ShiroFilterFactoryBean w
* ShiroFilterFactoryBean
* ShiroFilterFactoryBeanSecurityManager
*
* Filter Chain 1URLFilter 2
* 3permsroles
*
*/
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// Web"/login.jsp"
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
/**
* shiro redisManager
* shiro-redis
* @return
*/
public RedisManager redisManager() throws URISyntaxException {
RedisManager redisManager = new RedisManager();
URI uri = new URI(url);
redisManager.setHost(uri.getHost());
redisManager.setPort(uri.getPort());
redisManager.setExpire(1800);
redisManager.setTimeout(timeout);
// password = null?
String userInfo = uri.getUserInfo();
if(userInfo != null)
{
String[] info = userInfo.split(":");
if(info.length > 1)
{
redisManager.setPassword(info[1]);
}
}
return redisManager;
}
/**
* RedisSessionDAO shiro sessionDao redis
* shiro-redis
*/
@Bean
public RedisSessionDAO redisSessionDAO() throws URISyntaxException {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
}
/**
* Session Manager
* shiro-redis
*/
@Bean
public DefaultWebSessionManager sessionManager() throws URISyntaxException {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* realm; ()
*
* @return
*/
@Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
return myShiroRealm;
}
}
|
package org.jetbrains.idea.devkit.inspections;
import com.intellij.ExtensionPoints;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ui.ListTable;
import com.intellij.codeInspection.ui.ListWrappingTableModel;
import com.intellij.diagnostic.ITNReporter;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.plugins.PluginManagerMain;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceDescriptor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.LoadingOrder;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.panel.ComponentPanelBuilder;
import com.intellij.openapi.ui.panel.PanelGridBuilder;
import com.intellij.openapi.util.AtomicClearableLazyValue;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.NavigatableAdapter;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightMethodBuilder;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import com.intellij.util.ui.UI;
import com.intellij.util.xml.*;
import com.intellij.util.xml.highlighting.*;
import com.intellij.util.xml.reflect.DomAttributeChildDescription;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.XCollection;
import com.intellij.xml.CommonXmlStrings;
import com.siyeh.ig.ui.ExternalizableStringSet;
import com.siyeh.ig.ui.UiUtils;
import org.jdom.Element;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.DevKitBundle;
import org.jetbrains.idea.devkit.dom.Action;
import org.jetbrains.idea.devkit.dom.*;
import org.jetbrains.idea.devkit.dom.impl.PluginPsiClassConverter;
import org.jetbrains.idea.devkit.inspections.quickfix.AddWithTagFix;
import org.jetbrains.idea.devkit.module.PluginModuleType;
import org.jetbrains.idea.devkit.util.PsiUtil;
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class PluginXmlDomInspection extends BasicDomElementsInspection<IdeaPlugin> {
private static final Logger LOG = Logger.getInstance(PluginXmlDomInspection.class);
@NonNls
private static final String PLUGIN_ICON_SVG_FILENAME = "pluginIcon.svg";
public List<String> myRegistrationCheckIgnoreClassList = new ExternalizableStringSet();
@XCollection
public List<PluginModuleSet> PLUGINS_MODULES = new ArrayList<>();
private final AtomicClearableLazyValue<Map<String, PluginModuleSet>> myPluginModuleSetByModuleName = AtomicClearableLazyValue.create(() -> {
Map<String, PluginModuleSet> result = new HashMap<>();
for (PluginModuleSet modulesSet : PLUGINS_MODULES) {
for (String module : modulesSet.modules) {
result.put(module, modulesSet);
}
}
return result;
});
public PluginXmlDomInspection() {
super(IdeaPlugin.class);
}
@Nullable
@Override
public JComponent createOptionsPanel() {
ListTable table = new ListTable(new ListWrappingTableModel(myRegistrationCheckIgnoreClassList, ""));
JPanel panel = UiUtils.createAddRemoveTreeClassChooserPanel(table, DevKitBundle.message("inspections.plugin.xml.add.ignored.class.title"));
PanelGridBuilder grid = UI.PanelFactory.grid();
grid.resize().add(
UI.PanelFactory.panel(panel)
.withLabel(DevKitBundle.message("inspections.plugin.xml.ignore.classes.title"))
.moveLabelOnTop()
.resizeY(true)
);
if (ApplicationManager.getApplication().isInternal()) {
JBTextArea component = new JBTextArea(5, 80);
component.setText(PLUGINS_MODULES.stream().map(it -> String.join(",", it.modules)).collect(Collectors.joining("\n")));
component.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
PLUGINS_MODULES.clear();
for (String line : StringUtil.splitByLines(component.getText())) {
PluginModuleSet set = new PluginModuleSet();
set.modules = new LinkedHashSet<>(StringUtil.split(line, ","));
PLUGINS_MODULES.add(set);
}
myPluginModuleSetByModuleName.drop();
}
});
ComponentPanelBuilder pluginModulesPanel =
UI.PanelFactory.panel(new JBScrollPane(component))
.withLabel(DevKitBundle.message("inspections.plugin.xml.plugin.modules.label"))
.moveLabelOnTop()
.withComment(DevKitBundle.message("inspections.plugin.xml.plugin.modules.description"))
.resizeY(true);
grid.add(pluginModulesPanel);
}
return grid.createPanel();
}
@Override
public void readSettings(@NotNull Element node) {
super.readSettings(node);
myPluginModuleSetByModuleName.drop();
}
@Override
@NotNull
public String getShortName() {
return "PluginXmlValidity";
}
@Override
protected void checkDomElement(DomElement element, DomElementAnnotationHolder holder, DomHighlightingHelper helper) {
super.checkDomElement(element, holder, helper);
if (element instanceof IdeaPlugin) {
Module module = element.getModule();
if (module != null) {
annotateIdeaPlugin((IdeaPlugin)element, holder, module);
checkJetBrainsPlugin((IdeaPlugin)element, holder, module);
checkPluginIcon((IdeaPlugin)element, holder, module);
}
}
else {
ComponentModuleRegistrationChecker componentModuleRegistrationChecker = new ComponentModuleRegistrationChecker(myPluginModuleSetByModuleName,
myRegistrationCheckIgnoreClassList,
holder);
if (element instanceof Extension) {
annotateExtension((Extension)element, holder, componentModuleRegistrationChecker);
}
else if (element instanceof ExtensionPoint) {
annotateExtensionPoint((ExtensionPoint)element, holder, componentModuleRegistrationChecker);
}
else if (element instanceof Vendor) {
annotateVendor((Vendor)element, holder);
}
else if (element instanceof ProductDescriptor) {
annotateProductDescriptor((ProductDescriptor)element, holder);
}
else if (element instanceof IdeaVersion) {
annotateIdeaVersion((IdeaVersion)element, holder);
}
else if (element instanceof Extensions) {
annotateExtensions((Extensions)element, holder);
}
else if (element instanceof AddToGroup) {
annotateAddToGroup((AddToGroup)element, holder);
}
else if (element instanceof Action) {
annotateAction((Action)element, holder, componentModuleRegistrationChecker);
}
else if (element instanceof Group) {
annotateGroup((Group)element, holder);
}
else if (element instanceof Component) {
annotateComponent((Component)element, holder, componentModuleRegistrationChecker);
if (element instanceof Component.Project) {
annotateProjectComponent((Component.Project)element, holder);
}
}
}
if (element instanceof GenericDomValue) {
final GenericDomValue domValue = (GenericDomValue)element;
if (domValue.getConverter() instanceof PluginPsiClassConverter) {
annotatePsiClassValue(domValue, holder);
}
}
}
private static void annotatePsiClassValue(GenericDomValue domValue, DomElementAnnotationHolder holder) {
final Object value = domValue.getValue();
if (value instanceof PsiClass) {
PsiClass psiClass = (PsiClass)value;
if (psiClass.getContainingClass() != null &&
!StringUtil.containsChar(StringUtil.notNullize(domValue.getRawText()), '$')) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.inner.class.must.be.separated.with.dollar"));
}
}
}
private static boolean isUnderProductionSources(DomElement domElement, @NotNull Module module) {
VirtualFile virtualFile = DomUtil.getFile(domElement).getVirtualFile();
return virtualFile != null &&
ModuleRootManager.getInstance(module).getFileIndex().isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.PRODUCTION);
}
private static void annotateIdeaPlugin(IdeaPlugin ideaPlugin, DomElementAnnotationHolder holder, @NotNull Module module) {
//noinspection deprecation
highlightAttributeNotUsedAnymore(ideaPlugin.getIdeaPluginVersion(), holder);
//noinspection deprecation
if (DomUtil.hasXml(ideaPlugin.getUseIdeaClassloader())) {
//noinspection deprecation
highlightDeprecated(ideaPlugin.getUseIdeaClassloader(), "Deprecated", holder, true, true);
}
checkMaxLength(ideaPlugin.getUrl(), 255, holder);
checkMaxLength(ideaPlugin.getId(), 255, holder);
checkTemplateText(ideaPlugin.getName(), "Plugin display name here", holder);
checkTemplateTextContainsWord(ideaPlugin.getName(), "plugin", holder);
checkMaxLength(ideaPlugin.getName(), 255, holder);
checkMaxLength(ideaPlugin.getDescription(), 65535, holder);
checkHasRealText(ideaPlugin.getDescription(), 40, holder);
checkTemplateTextContains(ideaPlugin.getDescription(), "Enter short description for your plugin here.", holder);
checkTemplateTextContains(ideaPlugin.getDescription(), "most HTML tags may be used", holder);
checkMaxLength(ideaPlugin.getChangeNotes(), 65535, holder);
checkHasRealText(ideaPlugin.getChangeNotes(), 40, holder);
checkTemplateTextContains(ideaPlugin.getChangeNotes(), "Add change notes here", holder);
checkTemplateTextContains(ideaPlugin.getChangeNotes(), "most HTML tags may be used", holder);
if (!hasRealPluginId(ideaPlugin)) return;
boolean isNotIdeaProject = !PsiUtil.isIdeaProject(module.getProject());
if (isNotIdeaProject &&
!DomUtil.hasXml(ideaPlugin.getVersion()) &&
PluginModuleType.isOfType(module)) {
holder.createProblem(ideaPlugin, DevKitBundle.message("inspections.plugin.xml.version.must.be.specified"),
new AddMissingMainTag("Add <version>", ideaPlugin.getVersion(), ""));
}
checkMaxLength(ideaPlugin.getVersion(), 64, holder);
if (isNotIdeaProject && !DomUtil.hasXml(ideaPlugin.getVendor())) {
holder.createProblem(ideaPlugin, DevKitBundle.message("inspections.plugin.xml.vendor.must.be.specified"),
new AddMissingMainTag("Add <vendor>", ideaPlugin.getVendor(), ""));
}
}
private static void checkJetBrainsPlugin(IdeaPlugin ideaPlugin, DomElementAnnotationHolder holder, @NotNull Module module) {
if (!PsiUtil.isIdeaProject(module.getProject())) return;
if (DomUtil.hasXml(ideaPlugin.getUrl())) {
String url = ideaPlugin.getUrl().getStringValue();
if ("https:
highlightRedundant(ideaPlugin.getUrl(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.no.generic.plugin.url"), holder);
}
}
if (!hasRealPluginId(ideaPlugin)) return;
String id = ideaPlugin.getId().getStringValue();
if (id != null &&
(StringUtil.startsWith(id, "com.android.") ||
id.equals("org.jetbrains.android"))) {
return;
}
if (!isUnderProductionSources(ideaPlugin, module)) return;
final Vendor vendor = ideaPlugin.getVendor();
if (!DomUtil.hasXml(vendor)) {
holder.createProblem(DomUtil.getFileElement(ideaPlugin),
DevKitBundle.message("inspections.plugin.xml.plugin.should.have.jetbrains.vendor"),
new AddMissingMainTag("Specify JetBrains as vendor", vendor, PluginManagerMain.JETBRAINS_VENDOR));
}
else if (!PluginManagerMain.isDevelopedByJetBrains(vendor.getValue())) {
holder.createProblem(vendor, DevKitBundle.message("inspections.plugin.xml.plugin.should.include.jetbrains.vendor"));
}
else {
final String url = vendor.getUrl().getStringValue();
if (url != null && StringUtil.endsWith(url, "jetbrains.com")) {
highlightRedundant(vendor.getUrl(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.vendor.no.url", url), holder);
}
}
if (DomUtil.hasXml(vendor.getEmail())) {
highlightRedundant(vendor.getEmail(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.vendor.no.email"), holder);
}
if (DomUtil.hasXml(ideaPlugin.getChangeNotes())) {
highlightRedundant(ideaPlugin.getChangeNotes(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.no.change.notes"), holder);
}
if (DomUtil.hasXml(ideaPlugin.getVersion())) {
highlightRedundant(ideaPlugin.getVersion(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.no.version"), holder);
}
if (DomUtil.hasXml(ideaPlugin.getIdeaVersion())) {
highlightRedundant(ideaPlugin.getIdeaVersion(),
DevKitBundle.message("inspections.plugin.xml.plugin.jetbrains.no.idea.version"), holder);
}
}
private static void checkPluginIcon(IdeaPlugin ideaPlugin, DomElementAnnotationHolder holder, Module module) {
if (!hasRealPluginId(ideaPlugin)) return;
if (!isUnderProductionSources(ideaPlugin, module)) return;
Collection<VirtualFile> pluginIconFiles =
FilenameIndex.getVirtualFilesByName(module.getProject(), PLUGIN_ICON_SVG_FILENAME, GlobalSearchScope.moduleScope(module));
if (pluginIconFiles.isEmpty()) {
holder.createProblem(ideaPlugin, ProblemHighlightType.WEAK_WARNING,
DevKitBundle.message("inspections.plugin.xml.no.plugin.icon.svg.file", PLUGIN_ICON_SVG_FILENAME),
null);
}
}
private static boolean hasRealPluginId(IdeaPlugin ideaPlugin) {
String pluginId = ideaPlugin.getPluginId();
return pluginId != null && !pluginId.equals(PluginManagerCore.CORE_PLUGIN_ID);
}
private void annotateExtensionPoint(ExtensionPoint extensionPoint,
DomElementAnnotationHolder holder,
ComponentModuleRegistrationChecker componentModuleRegistrationChecker) {
if (extensionPoint.getWithElements().isEmpty() &&
!extensionPoint.collectMissingWithTags().isEmpty()) {
holder.createProblem(extensionPoint, DevKitBundle.message("inspections.plugin.xml.ep.doesnt.have.with"), new AddWithTagFix());
}
checkEpBeanClassAndInterface(extensionPoint, holder);
checkEpNameAndQualifiedName(extensionPoint, holder);
Module module = extensionPoint.getModule();
if (componentModuleRegistrationChecker.isIdeaPlatformModule(module)) {
componentModuleRegistrationChecker.checkProperModule(extensionPoint);
}
}
private static void checkEpBeanClassAndInterface(ExtensionPoint extensionPoint, DomElementAnnotationHolder holder) {
boolean hasBeanClass = DomUtil.hasXml(extensionPoint.getBeanClass());
boolean hasInterface = DomUtil.hasXml(extensionPoint.getInterface());
if (hasBeanClass && hasInterface) {
holder.createProblem(extensionPoint, ProblemHighlightType.GENERIC_ERROR,
DevKitBundle.message("inspections.plugin.xml.ep.both.beanClass.and.interface"), null);
}
else if (!hasBeanClass && !hasInterface) {
holder.createProblem(extensionPoint, ProblemHighlightType.GENERIC_ERROR,
DevKitBundle.message("inspections.plugin.xml.ep.missing.beanClass.and.interface"), null);
}
}
private static void checkEpNameAndQualifiedName(ExtensionPoint extensionPoint, DomElementAnnotationHolder holder) {
GenericAttributeValue<String> name = extensionPoint.getName();
GenericAttributeValue<String> qualifiedName = extensionPoint.getQualifiedName();
boolean hasName = DomUtil.hasXml(name);
boolean hasQualifiedName = DomUtil.hasXml(qualifiedName);
if (hasName && hasQualifiedName) {
holder.createProblem(extensionPoint, ProblemHighlightType.GENERIC_ERROR,
DevKitBundle.message("inspections.plugin.xml.ep.both.name.and.qualifiedName"), null);
}
else if (!hasName && !hasQualifiedName) {
holder.createProblem(extensionPoint, ProblemHighlightType.GENERIC_ERROR,
DevKitBundle.message("inspections.plugin.xml.ep.missing.name.and.qualifiedName"), null);
}
if (hasQualifiedName) {
if (!isValidEpName(qualifiedName)) {
String message = DevKitBundle.message("inspections.plugin.xml.invalid.ep.name.description",
DevKitBundle.message("inspections.plugin.xml.invalid.ep.qualifiedName"),
qualifiedName.getValue());
holder.createProblem(qualifiedName, ProblemHighlightType.WEAK_WARNING, message, null);
}
return;
}
if (hasName && !isValidEpName(name)) {
String message = DevKitBundle.message("inspections.plugin.xml.invalid.ep.name.description",
DevKitBundle.message("inspections.plugin.xml.invalid.ep.name"),
name.getValue());
holder.createProblem(name, ProblemHighlightType.WEAK_WARNING, message, null);
}
}
private static boolean isValidEpName(GenericAttributeValue<String> nameAttrValue) {
if (!nameAttrValue.exists()) {
return true;
}
@NonNls String name = nameAttrValue.getValue();
if (name != null && StringUtil.startsWith(name, "Pythonid.") &&
PsiUtil.isIdeaProject(nameAttrValue.getManager().getProject())) {
return true;
}
if (StringUtil.isEmpty(name) ||
!Character.isLowerCase(name.charAt(0)) || // also checks that name doesn't start with dot
name.toUpperCase().equals(name) || // not all uppercase
!StringUtil.isLatinAlphanumeric(name.replace(".", "")) ||
name.charAt(name.length() - 1) == '.') {
return false;
}
List<String> fragments = StringUtil.split(name, ".");
if (fragments.stream().anyMatch(f -> Character.isUpperCase(f.charAt(0)))) {
return false;
}
String epName = fragments.get(fragments.size() - 1);
fragments.remove(fragments.size() - 1);
List<String> words = StringUtil.getWordsIn(epName);
return words.stream().noneMatch(w -> fragments.stream().anyMatch(f -> StringUtil.equalsIgnoreCase(w, f)));
}
private static void annotateExtensions(Extensions extensions, DomElementAnnotationHolder holder) {
//noinspection deprecation
final GenericAttributeValue<IdeaPlugin> xmlnsAttribute = extensions.getXmlns();
if (DomUtil.hasXml(xmlnsAttribute)) {
highlightDeprecated(xmlnsAttribute, DevKitBundle.message("inspections.plugin.xml.use.defaultExtensionNs"), holder, false, true);
return;
}
if (!DomUtil.hasXml(extensions.getDefaultExtensionNs())) {
holder.createProblem(
extensions,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
DevKitBundle.message("inspections.plugin.xml.specify.defaultExtensionNs.explicitly", Extensions.DEFAULT_PREFIX),
null,
new AddDomElementQuickFix<GenericAttributeValue>(extensions.getDefaultExtensionNs()) {
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
super.applyFix(project, descriptor);
myElement.setStringValue(Extensions.DEFAULT_PREFIX);
}
});
}
}
private static void annotateIdeaVersion(IdeaVersion ideaVersion, DomElementAnnotationHolder holder) {
//noinspection deprecation
highlightAttributeNotUsedAnymore(ideaVersion.getMin(), holder);
//noinspection deprecation
highlightAttributeNotUsedAnymore(ideaVersion.getMax(), holder);
highlightUntilBuild(ideaVersion, holder);
GenericAttributeValue<String> sinceBuild = ideaVersion.getSinceBuild();
GenericAttributeValue<String> untilBuild = ideaVersion.getUntilBuild();
if (!DomUtil.hasXml(sinceBuild) ||
!DomUtil.hasXml(untilBuild)) {
return;
}
BuildNumber sinceBuildNumber = parseBuildNumber(sinceBuild, holder);
BuildNumber untilBuildNumber = parseBuildNumber(untilBuild, holder);
if (sinceBuildNumber == null || untilBuildNumber == null) return;
int compare = Comparing.compare(sinceBuildNumber, untilBuildNumber);
if (compare > 0) {
holder.createProblem(untilBuild, DevKitBundle.message("inspections.plugin.xml.until.build.must.be.greater.than.since.build"));
}
}
@Nullable
private static BuildNumber parseBuildNumber(GenericAttributeValue<String> build,
DomElementAnnotationHolder holder) {
try {
return BuildNumber.fromString(build.getStringValue());
}
catch (RuntimeException e) {
holder.createProblem(build, DevKitBundle.message("inspections.plugin.xml.until.since.build.invalid"));
return null;
}
}
private static void highlightUntilBuild(IdeaVersion ideaVersion, DomElementAnnotationHolder holder) {
String untilBuild = ideaVersion.getUntilBuild().getStringValue();
if (untilBuild != null && isStarSupported(ideaVersion.getSinceBuild().getStringValue())) {
Matcher matcher = IdeaPluginDescriptorImpl.EXPLICIT_BIG_NUMBER_PATTERN.matcher(untilBuild);
if (matcher.matches()) {
holder.createProblem(
ideaVersion.getUntilBuild(),
DevKitBundle.message("inspections.plugin.xml.until.build.use.asterisk.instead.of.big.number", matcher.group(2)),
new CorrectUntilBuildAttributeFix(
IdeaPluginDescriptorImpl.convertExplicitBigNumberInUntilBuildToStar(untilBuild)));
}
if (untilBuild.matches("\\d+")) {
int branch = Integer.parseInt(untilBuild);
String corrected = (branch - 1) + ".*";
holder.createProblem(ideaVersion.getUntilBuild(),
DevKitBundle.message("inspections.plugin.xml.until.build.misleading.plain.number", untilBuild, corrected),
new CorrectUntilBuildAttributeFix(corrected));
}
}
}
private static final Pattern BASE_LINE_EXTRACTOR = Pattern.compile("(?:\\p{javaLetter}+-)?(\\d+)(?:\\..*)?");
private static final int FIRST_BRANCH_SUPPORTING_STAR = 131;
private static boolean isStarSupported(String buildNumber) {
if (buildNumber == null) return false;
Matcher matcher = BASE_LINE_EXTRACTOR.matcher(buildNumber);
if (matcher.matches()) {
int branch = Integer.parseInt(matcher.group(1));
return branch >= FIRST_BRANCH_SUPPORTING_STAR;
}
return false;
}
private void annotateExtension(Extension extension,
DomElementAnnotationHolder holder, ComponentModuleRegistrationChecker componentModuleRegistrationChecker) {
final ExtensionPoint extensionPoint = extension.getExtensionPoint();
if (extensionPoint == null) return;
final GenericAttributeValue<PsiClass> interfaceAttribute = extensionPoint.getInterface();
if (DomUtil.hasXml(interfaceAttribute)) {
final PsiClass value = interfaceAttribute.getValue();
if (value != null && value.isDeprecated()) {
highlightDeprecated(
extension, DevKitBundle.message("inspections.plugin.xml.deprecated.ep", extensionPoint.getEffectiveQualifiedName()),
holder, false, false);
return;
}
}
if (ExtensionPoints.ERROR_HANDLER.equals(extensionPoint.getEffectiveQualifiedName()) && extension.exists()) {
String implementation = extension.getXmlTag().getAttributeValue("implementation");
if (ITNReporter.class.getName().equals(implementation)) {
IdeaPlugin plugin = extension.getParentOfType(IdeaPlugin.class, true);
if (plugin != null) {
Vendor vendor = plugin.getVendor();
if (DomUtil.hasXml(vendor) && PluginManagerMain.isDevelopedByJetBrains(vendor.getValue())) {
highlightRedundant(extension,
DevKitBundle.message("inspections.plugin.xml.no.need.to.specify.itnReporter"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL, holder);
}
else {
Module module = plugin.getModule();
boolean inPlatformCode = module != null && module.getName().startsWith("intellij.platform.");
if (!inPlatformCode) {
highlightRedundant(extension,
DevKitBundle.message("inspections.plugin.xml.third.party.plugins.must.not.use.itnReporter"),
holder);
}
}
}
}
}
if (ServiceDescriptor.class.getName().equals(extensionPoint.getBeanClass().getStringValue())) {
GenericAttributeValue serviceInterface = getAttribute(extension, "serviceInterface");
GenericAttributeValue serviceImplementation = getAttribute(extension, "serviceImplementation");
if (serviceInterface != null && serviceImplementation != null &&
StringUtil.equals(serviceInterface.getStringValue(), serviceImplementation.getStringValue())) {
highlightRedundant(serviceInterface,
DevKitBundle.message("inspections.plugin.xml.service.interface.class.redundant"),
ProblemHighlightType.WARNING, holder);
}
}
final List<? extends DomAttributeChildDescription> descriptions = extension.getGenericInfo().getAttributeChildrenDescriptions();
for (DomAttributeChildDescription attributeDescription : descriptions) {
final GenericAttributeValue attributeValue = attributeDescription.getDomAttributeValue(extension);
if (attributeValue == null || !DomUtil.hasXml(attributeValue)) continue;
// IconsReferencesContributor
if ("icon".equals(attributeDescription.getXmlElementName())) {
annotateResolveProblems(holder, attributeValue);
}
else if ("order".equals(attributeDescription.getXmlElementName())) {
annotateOrderAttributeProblems(holder, attributeValue);
}
final PsiElement declaration = attributeDescription.getDeclaration(extension.getManager().getProject());
if (declaration instanceof PsiField) {
PsiField psiField = (PsiField)declaration;
if (psiField.isDeprecated()) {
highlightDeprecated(
attributeValue, DevKitBundle.message("inspections.plugin.xml.deprecated.attribute", attributeDescription.getName()),
holder, false, true);
}
}
}
Module module = extension.getModule();
if (componentModuleRegistrationChecker.isIdeaPlatformModule(module)) {
componentModuleRegistrationChecker.checkProperXmlFileForExtension(extension);
}
}
@Nullable
private static GenericAttributeValue getAttribute(DomElement domElement, String attributeName) {
final DomAttributeChildDescription attributeDescription = domElement.getGenericInfo().getAttributeChildDescription(attributeName);
if (attributeDescription == null) {
return null;
}
return attributeDescription.getDomAttributeValue(domElement);
}
private void annotateComponent(Component component,
DomElementAnnotationHolder holder, ComponentModuleRegistrationChecker componentModuleRegistrationChecker) {
Module module = component.getModule();
if (componentModuleRegistrationChecker.isIdeaPlatformModule(module)) {
componentModuleRegistrationChecker.checkProperXmlFileForClass(
component, component.getImplementationClass().getValue());
}
GenericDomValue<PsiClass> interfaceClassElement = component.getInterfaceClass();
PsiClass interfaceClass = interfaceClassElement.getValue();
if (interfaceClass != null && interfaceClass.equals(component.getImplementationClass().getValue())) {
highlightRedundant(interfaceClassElement,
DevKitBundle.message("inspections.plugin.xml.component.interface.class.redundant"),
ProblemHighlightType.WARNING, holder);
}
}
private static void annotateVendor(Vendor vendor, DomElementAnnotationHolder holder) {
//noinspection deprecation
highlightAttributeNotUsedAnymore(vendor.getLogo(), holder);
checkTemplateText(vendor, "YourCompany", holder);
checkMaxLength(vendor, 255, holder);
checkTemplateText(vendor.getUrl(), "http:
checkMaxLength(vendor.getUrl(), 255, holder);
checkTemplateText(vendor.getEmail(), "support@yourcompany.com", holder);
checkMaxLength(vendor.getEmail(), 255, holder);
}
private static void annotateProductDescriptor(ProductDescriptor productDescriptor, DomElementAnnotationHolder holder) {
checkMaxLength(productDescriptor.getCode(), 15, holder);
String releaseDate = productDescriptor.getReleaseDate().getValue();
if (releaseDate == null) return;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.US);
dateFormat.setLenient(false);
dateFormat.parse(releaseDate);
}
catch (ParseException e) {
holder.createProblem(productDescriptor.getReleaseDate(),
DevKitBundle.message("inspections.plugin.xml.product.descriptor.invalid.date"));
}
}
private static void annotateAddToGroup(AddToGroup addToGroup, DomElementAnnotationHolder holder) {
if (!DomUtil.hasXml(addToGroup.getRelativeToAction())) return;
if (!DomUtil.hasXml(addToGroup.getAnchor())) {
holder.createProblem(addToGroup, DevKitBundle.message("inspections.plugin.xml.anchor.must.have.relative-to-action"),
new AddDomElementQuickFix<GenericAttributeValue>(addToGroup.getAnchor()));
return;
}
final Anchor value = addToGroup.getAnchor().getValue();
if (value == Anchor.after || value == Anchor.before) {
return;
}
holder.createProblem(
addToGroup.getAnchor(),
DevKitBundle.message("inspections.plugin.xml.must.use.after.before.with.relative-to-action", Anchor.after, Anchor.before));
}
private static void annotateGroup(Group group, DomElementAnnotationHolder holder) {
final GenericAttributeValue<String> iconAttribute = group.getIcon();
if (DomUtil.hasXml(iconAttribute)) {
annotateResolveProblems(holder, iconAttribute);
}
GenericAttributeValue<ActionOrGroup> useShortcutOfAttribute = group.getUseShortcutOf();
if (!DomUtil.hasXml(useShortcutOfAttribute)) return;
GenericAttributeValue<PsiClass> clazz = group.getClazz();
if (!DomUtil.hasXml(clazz)) {
holder.createProblem(group, "'class' must be specified with 'use-shortcut-of'",
new AddDomElementQuickFix<GenericAttributeValue>(group.getClazz()));
return;
}
PsiClass actionGroupClass = clazz.getValue();
if (actionGroupClass == null) return;
PsiMethod canBePerformedMethod = new LightMethodBuilder(actionGroupClass.getManager(), "canBePerformed")
.setContainingClass(JavaPsiFacade.getInstance(actionGroupClass.getProject()).findClass(ActionGroup.class.getName(),
actionGroupClass.getResolveScope()))
.setModifiers(PsiModifier.PUBLIC)
.setMethodReturnType(PsiType.BOOLEAN)
.addParameter("context", DataContext.class.getName());
PsiMethod overriddenCanBePerformedMethod = actionGroupClass.findMethodBySignature(canBePerformedMethod, false);
if (overriddenCanBePerformedMethod == null) {
String methodPresentation = PsiFormatUtil.formatMethod(canBePerformedMethod, PsiSubstitutor.EMPTY,
PsiFormatUtilBase.SHOW_NAME |
PsiFormatUtilBase.SHOW_PARAMETERS |
PsiFormatUtilBase.SHOW_CONTAINING_CLASS,
PsiFormatUtilBase.SHOW_TYPE);
holder.createProblem(clazz, "Must override " + methodPresentation + " with 'use-shortcut-of'");
}
}
private static void annotateAction(Action action,
DomElementAnnotationHolder holder,
ComponentModuleRegistrationChecker componentModuleRegistrationChecker) {
final GenericAttributeValue<String> iconAttribute = action.getIcon();
if (DomUtil.hasXml(iconAttribute)) {
annotateResolveProblems(holder, iconAttribute);
}
Module module = action.getModule();
if (componentModuleRegistrationChecker.isIdeaPlatformModule(module)) {
componentModuleRegistrationChecker.checkProperXmlFileForClass(action, action.getClazz().getValue());
}
}
private static void annotateProjectComponent(Component.Project projectComponent, DomElementAnnotationHolder holder) {
//noinspection deprecation
GenericDomValue<Boolean> skipForDefault = projectComponent.getSkipForDefaultProject();
if (skipForDefault.exists()) {
highlightDeprecated(skipForDefault, DevKitBundle.message("inspections.plugin.xml.skipForDefaultProject.deprecated"),
holder, true, true);
}
}
private static void annotateOrderAttributeProblems(DomElementAnnotationHolder holder, GenericAttributeValue attributeValue) {
String orderValue = attributeValue.getStringValue();
if (StringUtil.isEmpty(orderValue)) {
return;
}
try {
LoadingOrder.readOrder(orderValue);
}
catch (AssertionError ignore) {
holder.createProblem(attributeValue, HighlightSeverity.ERROR, DevKitBundle.message("inspections.plugin.xml.invalid.order.attribute"));
return; // no need to resolve references for invalid attribute value
}
annotateResolveProblems(holder, attributeValue);
}
private static void annotateResolveProblems(DomElementAnnotationHolder holder, GenericAttributeValue attributeValue) {
final XmlAttributeValue value = attributeValue.getXmlAttributeValue();
if (value != null) {
for (PsiReference reference : value.getReferences()) {
if (reference.resolve() == null) {
holder.createResolveProblem(attributeValue, reference);
}
}
}
}
private static void highlightRedundant(DomElement element, String message, DomElementAnnotationHolder holder) {
highlightRedundant(element, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, holder);
}
private static void highlightRedundant(DomElement element,
String message,
ProblemHighlightType highlightType,
DomElementAnnotationHolder holder) {
holder.createProblem(element, highlightType, message, null, new RemoveDomElementQuickFix(element)).highlightWholeElement();
}
private static void highlightAttributeNotUsedAnymore(GenericAttributeValue attributeValue,
DomElementAnnotationHolder holder) {
if (!DomUtil.hasXml(attributeValue)) return;
highlightDeprecated(
attributeValue, DevKitBundle.message("inspections.plugin.xml.attribute.not.used.anymore", attributeValue.getXmlElementName()),
holder, true, true);
}
private static void highlightDeprecated(DomElement element, String message, DomElementAnnotationHolder holder,
boolean useRemoveQuickfix, boolean highlightWholeElement) {
DomElementProblemDescriptor problem;
if (!useRemoveQuickfix) {
problem = holder.createProblem(element, ProblemHighlightType.LIKE_DEPRECATED, message, null);
}
else {
problem = holder.createProblem(element, ProblemHighlightType.LIKE_DEPRECATED, message, null, new RemoveDomElementQuickFix(element));
}
if (highlightWholeElement) {
problem.highlightWholeElement();
}
}
private static void checkTemplateText(GenericDomValue<String> domValue,
String templateText,
DomElementAnnotationHolder holder) {
if (templateText.equals(domValue.getValue())) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.do.not.use.template.text", templateText));
}
}
private static void checkTemplateTextContains(GenericDomValue<String> domValue,
String containsText,
DomElementAnnotationHolder holder) {
String text = domValue.getStringValue();
if (text != null && StringUtil.containsIgnoreCase(text, containsText)) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.must.not.contain.template.text", containsText));
}
}
private static void checkTemplateTextContainsWord(GenericDomValue<String> domValue,
String templateWord,
DomElementAnnotationHolder holder) {
String text = domValue.getStringValue();
if (text == null) return;
for (String word : StringUtil.getWordsIn(text)) {
if (StringUtil.equalsIgnoreCase(word, templateWord)) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.must.not.contain.template.text", templateWord));
}
}
}
private static void checkMaxLength(GenericDomValue<String> domValue,
int maxLength,
DomElementAnnotationHolder holder) {
String value = domValue.getStringValue();
if (value != null && value.length() > maxLength) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.value.exceeds.max.length", maxLength));
}
}
private static void checkHasRealText(GenericDomValue<String> domValue,
int minimumLength,
DomElementAnnotationHolder holder) {
if (!DomUtil.hasXml(domValue)) return;
String value = StringUtil.removeHtmlTags(StringUtil.notNullize(domValue.getStringValue()));
value = StringUtil.replace(value, CommonXmlStrings.CDATA_START, "");
value = StringUtil.replace(value, CommonXmlStrings.CDATA_END, "");
if (StringUtil.isEmptyOrSpaces(value) || value.length() < minimumLength) {
holder.createProblem(domValue, DevKitBundle.message("inspections.plugin.xml.value.must.have.minimum.length", minimumLength));
}
}
private static class CorrectUntilBuildAttributeFix implements LocalQuickFix {
private final String myCorrectValue;
CorrectUntilBuildAttributeFix(String correctValue) {
myCorrectValue = correctValue;
}
@Nls
@NotNull
@Override
public String getName() {
return "Change 'until-build' to '" + myCorrectValue + "'";
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return "Correct 'until-build' attribute";
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final XmlAttribute attribute = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), XmlAttribute.class, false);
//noinspection unchecked
final GenericAttributeValue<String> domElement = DomManager.getDomManager(project).getDomElement(attribute);
LOG.assertTrue(domElement != null);
domElement.setStringValue(myCorrectValue);
}
}
private static class AddMissingMainTag implements LocalQuickFix {
@NotNull
private final String myFamilyName;
@NotNull
private final String myTagName;
@Nullable
private final String myTagValue;
private AddMissingMainTag(@NotNull String familyName, @NotNull GenericDomValue domValue, @Nullable String tagValue) {
myFamilyName = familyName;
myTagName = domValue.getXmlElementName();
myTagValue = tagValue;
}
@Nls
@NotNull
@Override
public String getFamilyName() {
return myFamilyName;
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
PsiFile file = descriptor.getPsiElement().getContainingFile();
DomFileElement<IdeaPlugin> fileElement = DomManager.getDomManager(project).getFileElement((XmlFile)file, IdeaPlugin.class);
if (fileElement != null) {
IdeaPlugin root = fileElement.getRootElement();
XmlTag after = getLastSubTag(root, root.getId(), root.getDescription(), root.getVersion(), root.getName());
XmlTag rootTag = root.getXmlTag();
XmlTag missingTag = rootTag.createChildTag(myTagName, rootTag.getNamespace(), myTagValue, false);
XmlTag addedTag;
if (after == null) {
addedTag = rootTag.addSubTag(missingTag, true);
}
else {
addedTag = (XmlTag)rootTag.addAfter(missingTag, after);
}
if (StringUtil.isEmpty(myTagValue)) {
int valueStartOffset = addedTag.getValue().getTextRange().getStartOffset();
NavigatableAdapter.navigate(project, file.getVirtualFile(), valueStartOffset, true);
}
}
}
private static XmlTag getLastSubTag(IdeaPlugin root, DomElement... children) {
Set<XmlTag> childrenTags = new HashSet<>();
for (DomElement child : children) {
if (child != null) {
childrenTags.add(child.getXmlTag());
}
}
XmlTag[] subTags = root.getXmlTag().getSubTags();
for (int i = subTags.length - 1; i >= 0; i
if (childrenTags.contains(subTags[i])) {
return subTags[i];
}
}
return null;
}
}
@Tag("modules-set")
public static class PluginModuleSet {
@XCollection(elementName = "module", valueAttributeName = "name")
@Property(surroundWithTag = false)
public Set<String> modules = new LinkedHashSet<>();
}
}
|
package com.java.blick.dates;
import java.sql.Timestamp;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.Month;
import java.time.MonthDay;
import java.time.Year;
import java.time.YearMonth;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import com.java.blick.dates.factories.LocalDateFactory;
import com.java.blick.dates.factories.LocalDateTimeFactory;
import com.java.blick.dates.factories.LocalTimeFactory;
import com.java.blick.dates.factories.ZonedDateTimeFactory;
public class Instants {
public static Date toDate(Instant instant) {
Objects.requireNonNull(instant);
return Date.from(instant);
}
public static Timestamp toTimestamp(Instant instant) {
Objects.requireNonNull(instant);
return new Timestamp(toMillis(instant));
}
public static LocalDateTimeFactory toLocalDateTime(Instant instant) {
Objects.requireNonNull(instant);
return new LocalDateTimeFactory(toMillis(instant));
}
public static LocalDateFactory toLocalDate(Instant instant) {
Objects.requireNonNull(instant);
return new LocalDateFactory(toMillis(instant));
}
public static LocalTimeFactory toLocalTime(Instant instant) {
Objects.requireNonNull(instant);
return new LocalTimeFactory(toMillis(instant));
}
public static Month toMonth(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toMonth(toMillis(instant));
}
public static MonthDay toMonthDay(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toMonthDay(toMillis(instant));
}
public static Year toYear(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toYear(toMillis(instant));
}
public static YearMonth toYearMonth(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toYearMonth(toMillis(instant));
}
public static DayOfWeek toDayOfWeek(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toDayOfWeek(toMillis(instant));
}
public static Calendar toCalendar(Instant instant) {
Objects.requireNonNull(instant);
return Millis.toCalendar(toMillis(instant));
}
public static ZonedDateTimeFactory toZonedDateTime(Instant instant) {
Objects.requireNonNull(instant);
return new ZonedDateTimeFactory(toMillis(instant));
}
public static long toMillis(Instant instant) {
return instant.toEpochMilli();
}
}
|
package com.jed.actor;
import org.lwjgl.opengl.GL11;
import com.jed.util.Vector;
/**
*
* @author jlinde, Peter Colapietro
*
*/
public class PolygonBoundary extends Boundary {
private double rightBound = 0;
private double leftBound = 0;
private double upperBound = 0;
private double lowerBound = 0;
/**
*
* @param position position vector
* @param verticies array of vertices
*/
public PolygonBoundary(final Vector position, final Vector[] verticies) {
super(position, verticies);
//Find Max Bounds for quad tree
for (Vector each : verticies) {
if (each.x > rightBound)
rightBound = each.x;
if (each.x < leftBound)
leftBound = each.x;
if (each.y < upperBound)
upperBound = each.y;
if (each.y > lowerBound)
lowerBound = each.y;
}
}
@Override
public double getRightBound() {
return owner.position.x + position.x + rightBound;
}
@Override
public double getLeftBound() {
return owner.position.x + position.x + leftBound;
}
@Override
public double getUpperBound() {
return owner.position.y + position.y + upperBound;
}
@Override
public double getLowerBound() {
return owner.position.y + position.y + lowerBound;
}
@Override
public int getWidth() {
return (int) (rightBound - leftBound);
}
@Override
public int getHeight() {
return (int) (lowerBound - upperBound);
}
@Override
public void draw() {
//Bounding Box
GL11.glColor3f(1f, 0, 0);
GL11.glBegin(GL11.GL_LINE_LOOP);
for (Vector each : verticies) {
owner.drawChildVertex2f(position.x + each.x, position.y + each.y);
}
GL11.glEnd();
}
}
|
package com.order.bolt;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Tuple;
import com.jcraft.jsch.Session;
import com.order.constant.Constant;
import com.order.databean.SessionInfo;
import com.order.databean.TimeCacheStructures.Pair;
import com.order.databean.TimeCacheStructures.RealTimeCacheList;
import com.order.databean.UserInfo;
import com.order.util.FName;
import com.order.util.StreamId;
import com.order.util.TimeParaser;
import org.apache.log4j.Logger;
public class StatisticsBolt extends BaseBasicBolt {
private static Logger log =Logger.getLogger(StatisticsBolt.class);
private RealTimeCacheList<Pair<String, UserInfo>> userInfos =
new RealTimeCacheList<Pair<String, UserInfo>>(Constant.ONE_DAY);
private RealTimeCacheList<Pair<String, SessionInfo>> sessionInfos =
new RealTimeCacheList<Pair<String, SessionInfo>>(Constant.ONE_DAY);
private void constructInfoFromBrowseData(Tuple input) throws Exception{
String remoteIp = input.getStringByField(FName.REMOTEIP.name());
Long recordTime = TimeParaser.splitTime(input.getStringByField(FName.RECORDTIME.name()));
String sessionId = input.getStringByField(FName.SESSIONID.name());
String userAgent = input.getStringByField(FName.USERAGENT.name());
String pageType = input.getStringByField(FName.PAGETYPE.name());
String msisdn = input.getStringByField(FName.MSISDN.name());
int channelCode = input.getIntegerByField(FName.CHANNELCODE.name());
String bookId = input.getStringByField(FName.BOOKID.name());
String chapterId = input.getStringByField(FName.CHAPTERID.name());
if (sessionId == null || !sessionId.trim().equals("") ) {
return ;
}
//SessionInfos
Pair<String, SessionInfo> sessionPair = new Pair<String, SessionInfo>(sessionId, null);
if (sessionInfos.contains(sessionPair)) {
SessionInfo currentSessionInfo = (SessionInfo) sessionInfos.get(sessionPair).getValue();
currentSessionInfo.upDateSeesionInfo(bookId, null, null, recordTime, -1, 0, channelCode, -1);
} else {
SessionInfo currentSessionInfo = new SessionInfo(sessionId, msisdn, bookId, null, null, recordTime, -1, 0, channelCode, -1);
sessionInfos.put(new Pair<String, SessionInfo>(sessionId, currentSessionInfo));
}
//UserInfos
Pair<String, UserInfo> userPair = new Pair<String, UserInfo>(msisdn, null);
if (userInfos.contains(userPair)) {
UserInfo currentUserInfo = (UserInfo) userInfos.get(userPair).getValue();
currentUserInfo.upDateUserInfo(recordTime, sessionId, remoteIp, userAgent);
} else {
UserInfo currentUserInfo = new UserInfo(msisdn, recordTime, sessionId, remoteIp, userAgent);
userInfos.put(new Pair<String, UserInfo>(msisdn, currentUserInfo));
}
}
private void constructInfoFromOrderData(Tuple input) throws Exception {
String msisdn = input.getStringByField(FName.MSISDN.name());
Long recordTime = TimeParaser.splitTime(input.getStringByField(FName.RECORDTIME.name()));
String userAgent = input.getStringByField(FName.USERAGENT.name());
int orderType = input.getIntegerByField(FName.ORDERTYPE.name());
String productId = input.getStringByField(FName.PRODUCTID.name());
String bookId = input.getStringByField(FName.BOOKID.name());
String chapterId = input.getStringByField(FName.CHAPTERID.name());
int channelCode = input.getIntegerByField(FName.CHANNELCODE.name());
int realInfoFee = input.getIntegerByField(FName.REALINFORFEE.name());
String wapIp = input.getStringByField(FName.WAPIP.name());
String sessionId = input.getStringByField(FName.SESSIONID.name());
int promotionId = input.getIntegerByField(FName.PROMOTIONID.name());
if (sessionId == null || sessionId.trim().equals("")) {
return;
}
//TODO
//SessionInfos
Pair<String, SessionInfo> sessionInfoPair = new Pair<String, SessionInfo>(sessionId, null);
if (sessionInfos.contains(sessionInfoPair)) {
SessionInfo currentSessionInfo = (SessionInfo) sessionInfos.get(sessionInfoPair).getValue();
currentSessionInfo.upDateSeesionInfo(null, bookId, chapterId, recordTime, orderType,
realInfoFee, channelCode, promotionId);
} else {
SessionInfo currentSessionInfo = new SessionInfo(sessionId, msisdn, null, bookId,
chapterId, recordTime, orderType, realInfoFee, channelCode, promotionId);
sessionInfos.put(new Pair<String, SessionInfo>(sessionId, currentSessionInfo));
}
//UserInfos
Pair<String, UserInfo> userInfoPair = new Pair<String, UserInfo>(msisdn, null);
if (userInfos.contains(userInfoPair)) {
UserInfo userInfo = (UserInfo) userInfos.get(userInfoPair).getValue();
userInfo.upDateUserInfo(recordTime, sessionId, wapIp, userAgent);
} else {
UserInfo currentUserInfo = new UserInfo(msisdn, recordTime, sessionId, wapIp, userAgent);
userInfos.put(new Pair<String, UserInfo>(msisdn, currentUserInfo));
}
}
@Override
public void execute(Tuple input, BasicOutputCollector collector) {
if (input.getSourceStreamId().equals(StreamId.BROWSEDATA)) {
try {
this.constructInfoFromBrowseData(input);
} catch (Exception e) {
log.error("");
}
}else if (input.getSourceStreamId().equals(StreamId.ORDERDATA)) {
try {
this.constructInfoFromOrderData(input);
} catch (Exception e) {
log.error("");
}
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
}
|
package com.xiaoleilu.hutool;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
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.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.xiaoleilu.hutool.exceptions.UtilException;
/**
*
* @author xiaoleilu
*
*/
public class FileUtil {
/** The Unix separator character. */
private static final char UNIX_SEPARATOR = '/';
/** The Windows separator character. */
private static final char WINDOWS_SEPARATOR = '\\';
/** Class */
public static final String CLASS_EXT = ".class";
/** Jar */
public static final String JAR_FILE_EXT = ".jar";
/** Jarjar */
public static final String JAR_PATH_EXT = ".jar!";
/** Path, path */
public static final String PATH_FILE_PRE = "file:";
/**
* <br>
*
* @param path
* @return
*/
public static File[] ls(String path) {
if(path == null) {
return null;
}
path = getAbsolutePath(path);
File file = new File(path);
if(file.isDirectory()) {
return file.listFiles();
}
throw new UtilException(StrUtil.format("Path [{}] is not directory!", path));
}
/**
* <br>
*
* @param path ClassPath
* @return jar.jar!/xxx/xxx
* @throws IOException
*/
public static List<String> listFileNames(String path) {
if(path == null) {
return null;
}
path = getAbsolutePath(path);
if(path.endsWith(String.valueOf(UNIX_SEPARATOR)) == false) {
path = path + UNIX_SEPARATOR;
}
List<String> paths = new ArrayList<String>();
int index = path.lastIndexOf(FileUtil.JAR_PATH_EXT);
try {
if(index == -1) {
File[] files = ls(path);
for (File file : files) {
if(file.isFile()) {
paths.add(file.getName());
}
}
}else {
//jar
index = index + FileUtil.JAR_FILE_EXT.length();
final String jarPath = path.substring(0, index);
final String subPath = path.substring(index + 2);
for (JarEntry entry : Collections.list(new JarFile(jarPath).entries())) {
final String name = entry.getName();
if(name.startsWith(subPath)) {
String nameSuffix = StrUtil.removePrefix(name, subPath);
if(nameSuffix.contains(String.valueOf(UNIX_SEPARATOR)) == false) {
paths.add(nameSuffix);
}
}
}
}
} catch (Exception e) {
throw new UtilException(StrUtil.format("Can not read file path of [{}]", path), e);
}
return paths;
}
/**
*
* @param fullFilePath POSIX
* @return nullnull
* @throws IOException
*/
public static File touch(String fullFilePath) throws IOException {
if(fullFilePath == null) {
return null;
}
File file = new File(fullFilePath);
file.getParentFile().mkdirs();
if(!file.exists()) file.createNewFile();
return file;
}
/**
*
* @param fullFileOrDirPath
* @return
* @throws IOException
*/
public static boolean del(String fullFileOrDirPath) throws IOException {
return del(new File(fullFileOrDirPath));
}
/**
*
* @param file
* @return
* @throws IOException
*/
public static boolean del(File file) throws IOException {
if(file == null || file.exists() == false) {
return true;
}
if(file.isDirectory()) {
File[] files = file.listFiles();
for (File childFile : files) {
boolean isOk = del(childFile);
if(isOk == false) {
return false;
}
}
}
return file.delete();
}
/**
*
* @param dirPath POSIX
* @return
*/
public static File mkdir(String dirPath){
if(dirPath == null) {
return null;
}
File dir = new File(dirPath);
dir.mkdirs();
return dir;
}
/**
* <br>
* prefix[Randon].suffix
* From com.jodd.io.FileUtil
* @param prefix 3
* @param suffix null.tmp
* @param dir
* @param isReCreat
* @return
* @throws IOException
*/
public static File createTempFile(String prefix, String suffix, File dir, boolean isReCreat) throws IOException {
int exceptionsCount = 0;
while (true) {
try {
File file = File.createTempFile(prefix, suffix, dir).getCanonicalFile();
if(isReCreat) {
file.delete();
file.createNewFile();
}
return file;
} catch (IOException ioex) { // fixes java.io.WinNTFileSystem.createFileExclusively access denied
if (++exceptionsCount >= 50) {
throw ioex;
}
}
}
}
/**
* <br>
*
* @param src
* @param dest
* @param isOverride
* @throws IOException
*/
public static void copy(File src, File dest, boolean isOverride) throws IOException {
//check
if (! src.exists()) {
throw new FileNotFoundException("File not exist: " + src);
}
if (! src.isFile()) {
throw new IOException("Not a file:" + src);
}
if (equals(src, dest)) {
throw new IOException("Files '" + src + "' and '" + dest + "' are equal");
}
if (dest.exists()) {
if (dest.isDirectory()) {
dest = new File(dest, src.getName());
}
if (dest.exists() && ! isOverride) {
throw new IOException("File already exist: " + dest);
}
}
// do copy file
FileInputStream input = new FileInputStream(src);
FileOutputStream output = new FileOutputStream(dest);
try {
IoUtil.copy(input, output);
} finally {
close(output);
close(input);
}
if (src.length() != dest.length()) {
throw new IOException("Copy file failed of '" + src + "' to '" + dest + "' due to different sizes");
}
}
/**
*
* @param src
* @param dest
* @param isOverride
* @throws IOException
*/
public static void move(File src, File dest, boolean isOverride) throws IOException {
//check
if (! src.exists()) {
throw new FileNotFoundException("File already exist: " + src);
}
if (dest.exists()) {
if (! isOverride) {
throw new IOException("File already exist: " + dest);
}
dest.delete();
}
if(src.isDirectory() && dest.isFile()) {
throw new IOException(StrUtil.format("Can not move directory [{}] to file [{}]", src, dest));
}
if(src.isFile() && dest.isDirectory()) {
dest = new File(dest, src.getName());
}
if (src.renameTo(dest) == false) {
//renameTocopy
try {
copy(src, dest, isOverride);
src.delete();
} catch (Exception e) {
throw new IOException(StrUtil.format("Move [{}] to [{}] failed!", src, dest), e);
}
}
}
/**
* <br/>
*
* @param path
* @param baseClass
* @return
*/
public static String getAbsolutePath(String path, Class<?> baseClass){
if(path == null) {
path = StrUtil.EMPTY;
}
if(baseClass == null) {
return getAbsolutePath(path);
}
// return baseClass.getResource(path).getPath();
return StrUtil.removePrefix(PATH_FILE_PRE, baseClass.getResource(path).getPath());
}
/**
* classes<br>
* \/
* @param path
* @return
*/
public static String getAbsolutePath(String path){
if(path == null) {
path = StrUtil.EMPTY;
}else {
path = path.replaceAll("[/\\\\]{1,}", "/");
if(path.startsWith("/") || path.matches("^[a-zA-Z]:/.*")){
return path;
}
}
ClassLoader classLoader = ClassUtil.getClassLoader();
URL url = classLoader.getResource(path);
String reultPath= url != null ? url.getPath() : classLoader.getResource(StrUtil.EMPTY).getPath() + path;
return StrUtil.removePrefix(reultPath, PATH_FILE_PRE);
}
/**
*
* @param path
* @return
*/
public static boolean isExist(String path){
return new File(path).exists();
}
/**
*
* @param closeable
*/
public static void close(Closeable closeable){
if(closeable == null) return;
try {
closeable.close();
} catch (IOException e) {
}
}
/**
*
* @param file1 1
* @param file2 2
* @return
*/
public static boolean equals(File file1, File file2) {
try {
file1 = file1.getCanonicalFile();
file2 = file2.getCanonicalFile();
} catch (IOException ignore) {
return false;
}
return file1.equals(file2);
}
/**
*
* @param path
* @param charset
* @param isAppend
* @return BufferedReader
* @throws IOException
*/
public static BufferedWriter getBufferedWriter(String path, String charset, boolean isAppend) throws IOException {
return new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(touch(path), isAppend), charset
)
);
}
/**
* print
* @param path
* @param charset
* @param isAppend
* @return
* @throws IOException
*/
public static PrintWriter getPrintWriter(String path, String charset, boolean isAppend) throws IOException {
return new PrintWriter(getBufferedWriter(path, charset, isAppend));
}
/**
*
* @param path
* @return
* @throws IOException
*/
public static OutputStream getOutputStream(String path) throws IOException {
return new FileOutputStream(touch(path));
}
/**
*
* @param path
* @param charset
* @return BufferedReader
* @throws IOException
*/
public static BufferedReader getReader(String path, String charset) throws IOException{
if(StrUtil.isBlank(charset)) {
return new BufferedReader(new InputStreamReader(new FileInputStream(path)));
}else {
return new BufferedReader(new InputStreamReader(new FileInputStream(path), charset));
}
}
/**
*
* @param path
* @param charset
* @param collection
* @return
* @throws IOException
*/
public static <T extends Collection<String>> T readLines(String path, String charset, T collection) throws IOException{
BufferedReader reader = null;
try {
reader = getReader(path, charset);
String line;
while(true){
line = reader.readLine();
if(line == null) break;
collection.add(line);
}
return collection;
}finally {
close(reader);
}
}
/**
*
* @param url URL
* @param charset
* @param collection
* @return
* @throws IOException
*/
public static <T extends Collection<String>> T readLines(URL url, String charset, T collection) throws IOException{
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(url.openStream()));
while(true){
String line = reader.readLine();
if(line == null) break;
collection.add(line);
}
return collection;
} finally {
close(reader);
}
}
/**
*
* @param url URL
* @param charset
* @return List
* @throws IOException
*/
public static List<String> readLines(URL url, String charset) throws IOException {
return readLines(url, charset, new ArrayList<String>());
}
/**
*
* @param path
* @param charset
* @return List
* @throws IOException
*/
public static List<String> readLines(String path, String charset) throws IOException {
return readLines(path, charset, new ArrayList<String>());
}
/**
* readerHandler
* @param readerHandler Reader
* @param path
* @param charset
* @return load
* @throws IOException
*/
public static <T> T load(ReaderHandler<T> readerHandler, String path, String charset) throws IOException {
BufferedReader reader = null;
T result = null;
try {
reader = getReader(path, charset);
result = readerHandler.handle(reader);
} catch (IOException e) {
throw new IOException(e);
}finally {
close(reader);
}
return result;
}
/**
*
* @param fileName
* @return
*/
public static String getExtension(String fileName) {
if (fileName == null) {
return null;
}
int index = fileName.lastIndexOf(StrUtil.DOT);
if (index == -1) {
return StrUtil.EMPTY;
} else {
String ext = fileName.substring(index + 1);
return (ext.contains(String.valueOf(UNIX_SEPARATOR)) || ext.contains(String.valueOf(WINDOWS_SEPARATOR))) ? StrUtil.EMPTY : ext;
}
}
/**
*
* @param filePath
* @return
*/
public static int indexOfLastSeparator(String filePath) {
if (filePath == null) {
return -1;
}
int lastUnixPos = filePath.lastIndexOf(UNIX_SEPARATOR);
int lastWindowsPos = filePath.lastIndexOf(WINDOWS_SEPARATOR);
return (lastUnixPos >= lastWindowsPos) ? lastUnixPos : lastWindowsPos;
}
/**
* String
* @param content
* @param path
* @param charset
* @throws IOException
*/
public static void writeString(String content, String path, String charset) throws IOException {
PrintWriter writer = null;
try {
writer = getPrintWriter(path, charset, false);
writer.print(content);
}finally {
close(writer);
}
}
/**
* String
* @param content
* @param path
* @param charset
* @throws IOException
*/
public static void appendString(String content, String path, String charset) throws IOException {
PrintWriter writer = null;
try {
writer = getPrintWriter(path, charset, true);
writer.print(content);
}finally {
close(writer);
}
}
/**
*
* @param path
* @param charset
* @return
* @throws IOException
*/
public static String readString(String path, String charset) throws IOException {
return new String(readBytes(new File(path)), charset);
}
/**
*
* @param list
* @param path
* @param charset
* @throws IOException
*/
public static <T> void writeLines(Collection<T> list, String path, String charset) throws IOException {
writeLines(list, path, charset, false);
}
/**
*
* @param list
* @param path
* @param charset
* @throws IOException
*/
public static <T> void appendLines(Collection<T> list, String path, String charset) throws IOException {
writeLines(list, path, charset, true);
}
/**
*
* @param list
* @param path
* @param charset
* @param isAppend
* @throws IOException
*/
public static <T> void writeLines(Collection<T> list, String path, String charset, boolean isAppend) throws IOException {
PrintWriter writer = null;
try {
writer = getPrintWriter(path, charset, isAppend);
for (T t : list) {
if(t != null) {
writer.println(t.toString());
}
}
}finally {
close(writer);
}
}
/**
*
* @param data
* @param path
* @throws IOException
*/
public static void writeBytes(byte[] data, String path) throws IOException {
writeBytes(touch(path), data);
}
/**
*
* @param dest
* @param data
* @throws IOException
*/
public static void writeBytes(File dest, byte[] data) throws IOException {
writeBytes(dest, data, 0, data.length, false);
}
/**
*
* @param dest
* @param data
* @param off
* @param len
* @param append
* @throws IOException
*/
public static void writeBytes(File dest, byte[] data, int off, int len, boolean append) throws IOException {
if (dest.exists() == true) {
if (dest.isFile() == false) {
throw new IOException("Not a file: " + dest);
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(dest, append);
out.write(data, off, len);
} finally {
close(out);
}
}
/**
* <br>
* Integer.MAX_VALUE
* @param file
* @return
* @throws IOException
*/
public static byte[] readBytes(File file) throws IOException {
//check
if (! file.exists()) {
throw new FileNotFoundException("File not exist: " + file);
}
if (! file.isFile()) {
throw new IOException("Not a file:" + file);
}
long len = file.length();
if (len >= Integer.MAX_VALUE) {
throw new IOException("File is larger then max array size");
}
byte[] bytes = new byte[(int) len];
FileInputStream in = null;
try {
in = new FileInputStream(file);
in.read(bytes);
}finally {
close(in);
}
return bytes;
}
/**
* <br>
* @param dest
* @param in
* @throws IOException
*/
public static void writeStream(File dest, InputStream in) throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(dest);
IoUtil.copy(in, out);
} finally {
close(out);
}
}
/**
* <br>
* @param fullFilePath
* @param in
* @throws IOException
*/
public static void writeStream(String fullFilePath, InputStream in) throws IOException {
writeStream(touch(fullFilePath), in);
}
/**
* <br>
* null
* @param file
* @param lastModifyTime
* @return
*/
public static boolean isModifed(File file, long lastModifyTime) {
if(null == file || false == file.exists()) {
return true;
}
return file.lastModified() != lastModifyTime;
}
/**
* Reader
* @author Luxiaolei
*
* @param <T>
*/
public interface ReaderHandler<T> {
public T handle(BufferedReader reader) throws IOException;
}
}
|
package edu.ntnu.idi.goldfish;
import edu.ntnu.idi.goldfish.mahout.DBModel;
import edu.ntnu.idi.goldfish.mahout.SMDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericBooleanPrefDataModel;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import java.io.File;
public enum DataSet {
yowSMImplicit, yowImplicit, yowBaseline, claypool2k, Netflix100M, Movielens1M, Movielens50k, Movielens1Mbinary, Movielens50kbinary, MovielensSynthesized1M, MovielensSynthesized200k, MovielensSynthesized50k, MovielensMock1M,MovielensMock100K,MovielensMock500K, VTT36k, food;
public DataModel getModel() throws Exception {
DataModel model;
switch (this) {
// yow userstudy
case yowBaseline:
return new FileDataModel(new File("datasets/yow-userstudy/python/yow-smart-sample-explicit-3.csv"));
// yow userstudy
case yowImplicit:
return new DBModel(new File("datasets/yow-userstudy/python/yow-smart-sample-implicit-3.csv"));
case yowSMImplicit:
return new SMDataModel(new File("datasets/yow-userstudy/python/yow-smart-sample-implicit-3.csv"));
// claypool userstudy
case claypool2k:
return new SMDataModel(new File("datasets/claypool/claypool-sample-exdupes-exinvalid-rating.csv"));
// netflix
case Netflix100M:
return new FileDataModel(new File("datasets/netflix-100m/ratings.tsv.gz"));
// movielens
case Movielens1M:
return new FileDataModel(new File("datasets/movielens-1m/ratings.tsv.gz"));
case Movielens50k:
return new FileDataModel(new File("datasets/movielens-1m/ratings-50k.tsv.gz"));
// synthesized models (initialized with SMDataModel
case MovielensSynthesized1M:
return new SMDataModel(new File("datasets/movielens-synthesized/ratings-synthesized.tsv"));
case MovielensSynthesized200k:
return new SMDataModel(new File("datasets/movielens-synthesized/ratings-200k.tsv"));
case MovielensSynthesized50k:
return new SMDataModel(new File("datasets/movielens-synthesized/ratings-50k.tsv"));
case MovielensMock1M:
return new DBModel(new File("datasets/movielens-mock/mock1m-nodupes.csv"));
case MovielensMock500K:
return new DBModel(new File("datasets/movielens-mock/mock500k-nodupes.csv"));
case MovielensMock100K:
return new DBModel(new File("datasets/movielens-mock/mock100k-nodupes.csv"));
case food:
return new SMDataModel(new File("datasets/FOOD_Dataset/food-ettellerannet.csv"));
// binary models
case VTT36k:
model = new FileDataModel(new File("datasets/vtt-36k/VTT_I_data.csv"));
return new GenericBooleanPrefDataModel(GenericBooleanPrefDataModel.toDataMap(model));
case Movielens1Mbinary:
model = new FileDataModel(new File("datasets/movielens-1m/ratings-binary.csv"));
return new GenericBooleanPrefDataModel(GenericBooleanPrefDataModel.toDataMap(model));
case Movielens50kbinary:
model = new FileDataModel(new File("datasets/movielens-1m/ratings-binary-50k.csv"));
return new GenericBooleanPrefDataModel(GenericBooleanPrefDataModel.toDataMap(model));
}
return null;
}
}
|
package gavilan.jacop.endview;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Arrays.asList;
import static java.util.Collections.reverse;
import java.util.List;
import org.jacop.constraints.Alldifferent;
import org.jacop.constraints.And;
import org.jacop.constraints.In;
import org.jacop.constraints.Or;
import org.jacop.constraints.PrimitiveConstraint;
import org.jacop.constraints.XeqC;
import org.jacop.constraints.XeqY;
import org.jacop.core.IntDomain;
import org.jacop.core.IntVar;
import org.jacop.core.IntervalDomain;
import org.jacop.core.Store;
import org.jacop.search.DepthFirstSearch;
import org.jacop.search.IndomainMin;
import org.jacop.search.InputOrderSelect;
import org.jacop.search.Search;
import org.jacop.search.SelectChoicePoint;
public class EndView {
Store store = new Store();
ArrayList<IntVar> getRow(IntVar[][] grid, int n) {
return new ArrayList(Arrays.asList(grid[n]));
}
ArrayList<IntVar> getColumn(IntVar[][] grid, int n) {
ArrayList<IntVar> results = new ArrayList<>();
for (int i = 0; i < grid.length; ++i) {
results.add(grid[i][n]);
}
return results;
}
String display(int rowCount, int n) {
if (n <= (rowCount - 4)) {
return "X";
}
else {
return "" + (char) ('A' + (n - (rowCount - 3)));
}
}
public void drawGrid(IntVar[][] grid) {
int rowCount = grid.length;
for (int i = 0; i < rowCount; ++i) {
for (int j = 0; j < rowCount; ++j) {
Arrays.stream(grid[i][j].dom().toIntArray())
.mapToObj(n -> display(rowCount, n))
.forEach(System.out::print);
}
System.out.println();
}
}
private void constrain(int constraint, ArrayList<IntVar> vars) {
if (constraint > 0) {
int kind = vars.size();
IntDomain blank = new IntervalDomain(1, vars.size() - 4);
IntVar target = new IntVar(store, constraint, constraint);
if (5 == kind) {
store.impose(new Or(
new XeqC(vars.get(0), constraint),
new And(new In(vars.get(0), blank),
new XeqC(vars.get(1), constraint))
));
}
else if (6 == kind) {
store.impose(new Or(
new PrimitiveConstraint[]{
new XeqY(target, vars.get(0)),
new And(new In(vars.get(0), blank),
new XeqC(vars.get(1), constraint)),
new And(
new PrimitiveConstraint[]{
new In(vars.get(0), blank),
new In(vars.get(1), blank),
new XeqC(vars.get(2), constraint)
})
}));
}
}
}
int toDom(int rowCount, char c) {
return c - 'A' + rowCount - 3;
}
public void solve(List<String> gridPic) {
List<IntVar> vars = new ArrayList<>();
int rowCount = gridPic.size() - 2;
IntVar[][] grid = new IntVar[rowCount][rowCount];
for (int i = 0; i < rowCount; ++i) {
for (int j = 0; j < rowCount; ++j) {
IntVar v = new IntVar(store, 1, rowCount);
vars.add(v);
grid[i][j] = v;
}
}
String topRow = gridPic.get(0);
String bottomRow = gridPic.get(gridPic.size() - 1);
for (int i = 0; i < rowCount; ++i) {
ArrayList<IntVar> row = getRow(grid, i);
ArrayList<IntVar> column = getColumn(grid, i);
store.impose(new Alldifferent(row));
store.impose(new Alldifferent(column));
int topConstraint = toDom(rowCount, topRow.charAt(i + 1));
constrain(topConstraint, column);
reverse(column);
int bottomConstraint = toDom(rowCount, bottomRow.charAt(i + 1));
constrain(bottomConstraint, column);
int leftConstraint = toDom(rowCount, gridPic.get(i + 1).charAt(0));
constrain(leftConstraint, row);
int rightContraint = toDom(rowCount, gridPic.get(i + 1).charAt(gridPic.get(i + 1).length() - 1));
reverse(row);
constrain(rightContraint, row);
}
boolean ok = store.consistency();
if (ok) {
Search<IntVar> search = new DepthFirstSearch<>();
SelectChoicePoint<IntVar> select = new InputOrderSelect<>(store, vars.toArray(new IntVar[1]), new IndomainMin<>());
boolean result = search.labeling(store, select);
drawGrid(grid);
}
}
public static void main(String[] args) {
List<String> gridPic = asList(
" DCA ",
" ..... ",
"B.....D",
" ..... ",
" .....D",
" .....A",
" A "
);
new EndView().solve(gridPic);
List<String> gridPic2 = asList(
" AD D ",
"D...... ",
" ...... ",
" ......C",
" ...... ",
" ......B",
" ...... ",
" C CC "
);
new EndView().solve(gridPic2);
}
}
|
package gui.centerarea;
import control.CountUtilities;
import static gui.centerarea.TimetableBlock.DraggingTypes.Move;
import gui.misc.TweakingHelper;
import gui.root.RootCenterArea;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import lombok.Getter;
/**
* Class that resembles a draggable, resizable block inside the timetable,
* whose sole purpose is to display information.
* Highly volatile. Do not poke the dragging-dragon too much.
*/
public abstract class TimetableBlock extends Pane {
public enum DraggingTypes { Move, Resize_Top, Resize_Right, Resize_Bottom, Resize_Left }
/**
* Styling variables.
* For tweaking the styling.
*/
private double verticalBorderSize = 6.0;
private double margin = 5.0;
private double blurRadius = 20.0;
/**
* Content variables.
* Directly displaying block content, such as the name.
*/
@Getter
private Label titleNormalLabel;
@Getter
private Label titleDraggedLabel;
@Getter
private Label countNormalLabel;
@Getter
private Label countDraggedLabel;
@Getter
private Label descriptionNormalLabel;
@Getter
private Label descriptionDraggedLabel;
/**
* Misc variables.
* For dragging, panes etc
*/
@Getter
private TimetableBlock thisBlock;
@Getter
private Pane draggedPane; // rootCenterArea shown when dragging
@Getter
private Pane feedbackPane; // rootCenterArea shown when snapping
@Getter
private VBox contentPane; // content of this rootCenterArea
@Getter
private VBox draggedContentPane; // content of rootCenterArea shown when dragging
// for feedbackPane
private WritableImage feedbackImage; // content of feedbackPane (is just an image, sneaky!)
private GaussianBlur gaussianBlur;
private ColorAdjust darken;
private ImageView image;
@Getter
private double dragXOffset;
@Getter
private double dragYOffset;
@Getter
private RootCenterArea rootCenterArea;
@Getter
private boolean dragging;
@Getter
private DraggingTypes draggingType;
@Getter
private ShotBlock parentBlock;
@Getter
private double startingY;
/**
* Constructor for TimetableBlock class.
* @param pane - the parent rootCenterArea.
* @param parent - the parent node
*/
TimetableBlock(RootCenterArea pane, ShotBlock parent) {
this.dragging = false;
this.thisBlock = this;
this.parentBlock = parent;
this.rootCenterArea = pane;
}
/**
* Inits the necessary eventhandlers for this block.
* @param horizontalAllowed - specifies if horizontal dragging (between timelines)
* is allowed
*/
void addMouseEventHandlers(boolean horizontalAllowed) {
// mouse event handlers
setOnMousePressed(getOnPressedHandler(horizontalAllowed));
setOnMouseDragged(getOnDraggedHandler(horizontalAllowed));
setOnMouseReleased(getOnreleaseHandler(horizontalAllowed));
setOnMouseMoved(getOnMouseMovedHandler());
}
/**
* Helper function to initialize normal (visible) blocks.
*/
void initNormalPane() {
setBlendMode(BlendMode.MULTIPLY);
// content rootCenterArea for our
// actual rootCenterArea, which holds content (text and stuff)
contentPane = new VBox();
contentPane.minWidthProperty().bind(widthProperty());
contentPane.maxWidthProperty().bind(widthProperty());
contentPane.minHeightProperty().bind(heightProperty());
contentPane.maxHeightProperty().bind(heightProperty());
// add some labels etc
titleNormalLabel = initTitleLabel(contentPane);
countNormalLabel = initCountLabel(contentPane);
descriptionNormalLabel = initDescriptionLabel(contentPane);
descriptionNormalLabel.setWrapText(true);
addWithClipRegion(contentPane, this);
this.getStyleClass().add("block_Background");
this.getContentPane().getStyleClass().add("block_Foreground");
this.setStyle("-fx-background-color: "
+ TweakingHelper.STRING_PRIMARY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_SECONDARY + ";");
this.getContentPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_QUADRATORY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_TERTIARY + ";");
}
/**
* Helper function to initialize dragged (visible when dragging) blocks.
* @param anchorPane the AnchorPane drag on
*/
void initDraggedPane(AnchorPane anchorPane) {
// draggedPane itself
draggedPane = new Pane();
draggedPane.setVisible(false);
// dragged content rootCenterArea which mirrors
// our content rootCenterArea, shown when dragging.
draggedContentPane = new VBox() ;
draggedContentPane.minWidthProperty().bind(draggedPane.widthProperty());
draggedContentPane.maxWidthProperty().bind(draggedPane.widthProperty());
draggedContentPane.minHeightProperty().bind(draggedPane.heightProperty());
draggedContentPane.maxHeightProperty().bind(draggedPane.heightProperty());
// add some labels etc
titleDraggedLabel = initTitleLabel(draggedContentPane);
countDraggedLabel = initCountLabel(draggedContentPane);
descriptionDraggedLabel = initCountLabel(draggedContentPane);
descriptionDraggedLabel.setWrapText(true);
// dropshadow shown underneath dragged rootCenterArea
DropShadow ds = new DropShadow(15.0, 5.0, 5.0, Color.GRAY);
this.getDraggedPane().setEffect(ds);
addWithClipRegion(draggedContentPane, draggedPane);
anchorPane.getChildren().add(draggedPane);
this.getDraggedPane().getStyleClass().add("block_Background");
this.getDraggedContentPane().getStyleClass().add("block_Foreground");
this.getDraggedPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_PRIMARY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_SECONDARY + ";");
this.getDraggedContentPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_QUADRATORY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_TERTIARY + ";");
}
/**
* Helper function to initialize feedback (the snapping) blocks.
* @param gridPane the gridpane to have the feedback on
*/
public void initFeedbackPane(GridPane gridPane) {
feedbackPane = new Pane();
feedbackPane.setVisible(false);
gaussianBlur = new GaussianBlur(15.0);
darken = new ColorAdjust(0, -0.4, -0.2, 0.2);
image = new ImageView();
image.fitHeightProperty().bind(feedbackPane.heightProperty());
darken.setInput(gaussianBlur);
image.setEffect(darken);
feedbackPane.getChildren().add(image);
gridPane.add(feedbackPane, 0, 0);
}
/**
* Add content to rootCenterArea, but with a clipping region bound to the rootCenterArea's size.
* @param content the Pane in which content is located.
* @param pane the Pane in which the vbox is located.
*/
private void addWithClipRegion(Node content, Pane pane) {
Rectangle clipRegion = new Rectangle(); // clip region to restrict content
clipRegion.widthProperty().bind(pane.widthProperty());
clipRegion.heightProperty().bind(pane.heightProperty().subtract(verticalBorderSize));
content.setClip(clipRegion);
pane.getChildren().add(content);
}
/**
* Helper function to add title labels to panes.
* @param vbox rootCenterArea to add this label to
* @return the label in question.
*/
private Label initTitleLabel(VBox vbox) {
Label res = new Label(parentBlock.getName());
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Title");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_SECONDARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Helper function to add the description label to panes.
* @param vbox - rootCenterArea to add this label to
* @return - the label in question
*/
private Label initDescriptionLabel(VBox vbox) {
Label res = new Label(parentBlock.getDescription());
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Normal");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_TERTIARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Helper function to add count labels to panes.
* @param vbox rootCenterArea to add this label to
* @return the label in question.
*/
private Label initCountLabel(VBox vbox) {
String labelText = parentBlock.getBeginCount() + " - " + parentBlock.getEndCount();
Label res = new Label(labelText);
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Normal");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_TERTIARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Get handler for on mouse moved (handling cursors).
* @return - the handler
*/
private EventHandler<MouseEvent> getOnMouseMovedHandler() {
return e -> {
DraggingTypes dragType = findEdgeZone(e);
Cursor newCursor = null;
switch (dragType) {
case Move:
newCursor = Cursor.CLOSED_HAND;
break;
case Resize_Bottom:
case Resize_Top:
newCursor = Cursor.N_RESIZE;
break;
case Resize_Left:
case Resize_Right:
newCursor = Cursor.E_RESIZE;
break;
default:
newCursor = Cursor.DEFAULT;
}
if (getCursor() != newCursor) {
setCursor(newCursor);
}
};
}
/**
* Event handler for on mouse pressed.
* @param isCameraTimeline true when action is on the CameraTimeline
* @return - the eventhandler
*/
private EventHandler<MouseEvent> getOnPressedHandler(boolean isCameraTimeline) {
return e -> {
onPressedHandlerHelper(e);
GridPane gridPane;
if (isCameraTimeline) {
gridPane = getRootCenterArea().getMainTimeLineGridPane();
TimelinesGridPane.setColumnIndex(
feedbackPane, TimelinesGridPane.getColumnIndex(thisBlock));
TimelinesGridPane.setRowIndex(
feedbackPane, TimelinesGridPane.getRowIndex(thisBlock));
TimelinesGridPane.setRowSpan(
feedbackPane, TimelinesGridPane.getRowSpan(thisBlock));
} else {
gridPane = getRootCenterArea().getDirectorGridPane();
DirectorGridPane.setColumnIndex(
feedbackPane, DirectorGridPane.getColumnIndex(thisBlock));
DirectorGridPane.setRowIndex(
feedbackPane, DirectorGridPane.getRowIndex(thisBlock));
DirectorGridPane.setRowSpan(
feedbackPane, DirectorGridPane.getRowSpan(thisBlock));
}
// Set startingY if dragging
double blockY = gridPane.localToScene(thisBlock.getLayoutX(),
thisBlock.getLayoutY()).getY();
if (draggingType == DraggingTypes.Resize_Top) {
startingY = blockY + thisBlock.getHeight();
} else if (draggingType == DraggingTypes.Resize_Bottom) {
startingY = blockY;
}
};
}
/**
* Helper method for on Mouse Pressed.
* @param e the MouseEvent.
*/
private void onPressedHandlerHelper(MouseEvent e) {
// init correct object ordering
feedbackPane.toBack();
draggedPane.toFront();
this.toFront();
// init draggingpane
draggingType = findEdgeZone(e);
draggedPane.setLayoutX(getLayoutX());
draggedPane.setLayoutY(getLayoutY());
// Init feedbackpane
image.setImage(null);
feedbackImage = null;
feedbackImage = this.snapshot(new SnapshotParameters(), null);
image.setImage(feedbackImage);
feedbackPane.setVisible(true);
}
/**
* Event handler for on mouse dragged.
* @param isCameraTimeline - specifies if horizontal dragging
* (between timelines) is allowed
* @return - the eventhandler
*/
private EventHandler<MouseEvent> getOnDraggedHandler(boolean isCameraTimeline) {
return e -> {
if (!dragging) {
dragXOffset = e.getX();
dragYOffset = e.getY();
dragging = true;
draggedPane.setVisible(true);
draggedPane.setPrefHeight(getHeight());
draggedPane.setMinHeight(getHeight());
draggedPane.setMaxHeight(getHeight());
draggedPane.setPrefWidth(getWidth());
thisBlock.setVisible(false);
}
onMouseDraggedHelper(e, isCameraTimeline);
e.consume();
};
}
/**
* Event handler for on mouse release.
* @param isCameraTimeline true if the action is on a CameraTimeline
* @return - the event handler
*/
private EventHandler<MouseEvent> getOnreleaseHandler(boolean isCameraTimeline) {
return e -> {
draggedPane.setVisible(false);
thisBlock.setVisible(true);
if (dragging) {
snapPane(thisBlock, feedbackPane, e.getSceneY(), draggingType, isCameraTimeline);
}
feedbackPane.setVisible(false);
dragging = false;
// Update ShotBlock
if (isCameraTimeline) {
double newBeginCount = TimelinesGridPane.getRowIndex(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT;
parentBlock.setBeginCount(newBeginCount, false);
parentBlock.setEndCount(newBeginCount + TimelinesGridPane.getRowSpan(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT, false);
} else {
double newBeginCount = DirectorGridPane.getRowIndex(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT;
parentBlock.setBeginCount(newBeginCount, false);
parentBlock.setEndCount(newBeginCount + DirectorGridPane.getRowSpan(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT, false);
}
this.fireEvent(parentBlock.getShotBlockUpdatedEvent());
};
}
/**
* Helper function for MouseDragged event. Normal (actual dragging) part.
* @param event the mousedrag event in question.
* @param isCameraTimeline - specifies if horizontal dragging
* (between timelines) is allowed
*/
private void onMouseDraggedHelper(MouseEvent event, boolean isCameraTimeline) {
double x = event.getSceneX();
double y = event.getSceneY();
// Fix dragging out of grid
if (draggingType == DraggingTypes.Resize_Bottom
|| draggingType == DraggingTypes.Resize_Top) {
GridPane gridPane;
if (isCameraTimeline) {
gridPane = getRootCenterArea().getMainTimeLineGridPane();
} else {
gridPane = getRootCenterArea().getDirectorGridPane();
}
Bounds sceneBounds = gridPane.localToScene(gridPane.getLayoutBounds());
if (y < sceneBounds.getMinY()) {
y = sceneBounds.getMinY();
}
}
// determine what kind of dragging we're going to do, and handle it.
if (draggingType == DraggingTypes.Resize_Bottom || draggingType == DraggingTypes.Resize_Top
|| (draggingType == DraggingTypes.Move && !isCameraTimeline)) {
onMouseDraggedHelperVertical(x, y, isCameraTimeline);
} else if (draggingType == Move) {
onMouseDraggedHelperNormal(x, y, isCameraTimeline);
}
// set feedbackpane
snapPane(feedbackPane, draggedPane, y, draggingType, isCameraTimeline);
}
/**
* Snap the targetregion to a grid using the model provided by the mappingPane.
* @param targetRegion - the target region to snap
* @param mappingPane - the model mappingPane to follow while snapping
* @param y - the Y coordinate of the mouse during this snap
* @param dragType - The type of drag used while snapping (move, resize)
* @param isCameraTimeline true if the action is on the CameraTimeline
*/
private void snapPane(Region targetRegion, Region mappingPane,
double y, DraggingTypes dragType, boolean isCameraTimeline) {
// set feedback rootCenterArea
double yCoordinate;
double xCoordinate;
if (dragType == Move) {
yCoordinate = y - dragYOffset;
} else {
yCoordinate = y;
}
xCoordinate = mappingPane.localToScene(mappingPane.getBoundsInLocal()).getMinX()
+ mappingPane.getWidth() / 2;
ScrollableGridPane gridPane;
if (isCameraTimeline) {
gridPane = rootCenterArea.getMainTimeLineGridPane();
} else {
gridPane = rootCenterArea.getDirectorGridPane();
}
SnappingPane myPane = gridPane.getMyPane(xCoordinate, yCoordinate);
if (myPane != null) {
int numCounts = (int) Math.round(mappingPane.getHeight()
/ gridPane.getVerticalElementSize());
if (myPane.isBottomHalf() && dragType == DraggingTypes.Resize_Top) {
numCounts = (int) Math.round((mappingPane.getHeight() - 5)
/ gridPane.getVerticalElementSize());
}
if (myPane.isBottomHalf() && (dragType == DraggingTypes.Resize_Top
|| dragType == Move)) {
GridPane.setRowIndex(targetRegion, myPane.getRow() + 1);
} else if (dragType == Move || dragType == DraggingTypes.Resize_Top) {
GridPane.setRowIndex(targetRegion, myPane.getRow());
}
GridPane.setColumnIndex(targetRegion, myPane.getColumn());
GridPane.setRowSpan(targetRegion, Math.max(numCounts, 1));
}
}
/**
* Helper function for MouseDragged event. Normal (actual dragging) part.
* @param x - the x coordinate needed to process the vertical dragging
* @param y - the y coordinate needed to process the vertical dragging
* @param isCameraTimeline true if the action is in the CameraTimeline
*/
private void onMouseDraggedHelperNormal(double x, double y, boolean isCameraTimeline) {
AnchorPane parentPane;
if (isCameraTimeline) {
parentPane = rootCenterArea.getMainTimeLineAnchorPane();
} else {
parentPane = rootCenterArea.getDirectorAnchorPane();
}
Bounds parentBounds = parentPane.localToScene(parentPane.getBoundsInLocal());
draggedPane.setLayoutX(x - parentBounds.getMinX() - dragXOffset);
draggedPane.setLayoutY(y - parentBounds.getMinY() - dragYOffset);
}
/**
* Helper function for MouseDragged event. Vertical part.
* @param x - the x coordinate needed to process the vertical dragging
* @param y - the y coordinate needed to process the vertical dragging
* @param isCameraTimeline true if the action is in the CameraTimeline
*/
private void onMouseDraggedHelperVertical(double x, double y, boolean isCameraTimeline) {
double newLayoutY = 0;
double newPrefHeight = 0;
AnchorPane anchorPane;
ScrollableGridPane gridPane;
if (isCameraTimeline) {
anchorPane = rootCenterArea.getMainTimeLineAnchorPane();
gridPane = rootCenterArea.getMainTimeLineGridPane();
} else {
anchorPane = rootCenterArea.getDirectorAnchorPane();
gridPane = rootCenterArea.getDirectorGridPane();
}
Point2D bounds = anchorPane.sceneToLocal(x, y);
if (thisBlock.draggingType == DraggingTypes.Resize_Top) {
newPrefHeight = startingY - y;
newLayoutY = bounds.getY();
} else if (thisBlock.draggingType == DraggingTypes.Resize_Bottom) {
newLayoutY = anchorPane.sceneToLocal(0, startingY).getY();
newPrefHeight = bounds.getY() - newLayoutY;
} else if (thisBlock.draggingType == DraggingTypes.Move && !isCameraTimeline) {
Bounds parentBounds = anchorPane.localToScene(anchorPane.getBoundsInLocal());
newLayoutY = y - parentBounds.getMinY() - dragYOffset;
newPrefHeight = getHeight();
}
if (newPrefHeight < gridPane.getVerticalElementSize()) {
newPrefHeight = gridPane.getVerticalElementSize();
if (draggingType == DraggingTypes.Resize_Top) {
newLayoutY = gridPane.sceneToLocal(0,
startingY).getY() - newPrefHeight;
}
}
draggedPane.setLayoutY(newLayoutY);
draggedPane.setPrefHeight(newPrefHeight);
draggedPane.setMinHeight(newPrefHeight);
draggedPane.setMaxHeight(newPrefHeight);
}
/**
Find out in what area of a block (0,1,2,3,4) the mouse is pressed.
0 is the center, 1 is top, 2 is right, 3 is bottom, 4 is left.
Changing margin size (see top of file) makes the side areas thicker.
@param event The MouseEvent to read for this.
@return int to what area of a block mouse is pressed in.
*/
private DraggingTypes findEdgeZone(MouseEvent event) {
if (event.getY() < margin) {
return DraggingTypes.Resize_Top;
} else if (event.getX() > getWidth() - margin) {
// Horizontal resizing disabled for now.
// return DraggingTypes.Resize_Right;
return Move;
} else if (event.getY() > getHeight() - margin) {
return DraggingTypes.Resize_Bottom;
} else if (event.getX() < margin) {
// Horizontal resizing disabled for now.
// return DraggingTypes.Resize_Left;
return Move;
} else {
return Move;
}
}
}
|
package hex.deeplearning;
import com.amazonaws.services.cloudfront.model.InvalidArgumentException;
import hex.*;
import water.*;
import water.util.*;
import static water.util.MRUtils.sampleFrame;
import static water.util.MRUtils.sampleFrameStratified;
import hex.FrameTask.DataInfo;
import water.api.*;
import water.fvec.Frame;
import water.fvec.RebalanceDataSet;
import water.fvec.Vec;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Random;
/**
* Deep Learning Neural Net implementation based on MRTask2
*/
public class DeepLearning extends Job.ValidatedJob {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
public static DocGen.FieldDoc[] DOC_FIELDS;
public static final String DOC_GET = "Deep Learning";
/**
* A model key associated with a previously trained Deep Learning
* model. This option allows users to build a new model as a
* continuation of a previously generated model (e.g., by a grid search).
*/
@API(help = "Model checkpoint to resume training with", filter= Default.class, json = true)
public Key checkpoint;
/**
* If enabled, store the best model under the destination key of this model at the end of training.
* Only applicable if training is not cancelled.
*/
@API(help = "If enabled, override the final model with the best model found during training", filter= Default.class, json = true)
public boolean override_with_best_model = true;
/**
* Unlock expert mode parameters than can affect model building speed,
* predictive accuracy and scoring. Leaving expert mode parameters at default
* values is fine for many problems, but best results on complex datasets are often
* only attainable via expert mode options.
*/
@API(help = "Enable expert mode (to access all options from GUI)", filter = Default.class, json = true)
public boolean expert_mode = false;
@API(help = "Auto-Encoder (Experimental)", filter= Default.class, json = true)
public boolean autoencoder = false;
@API(help="Use all factor levels of categorical variables. Otherwise, the first factor level is omitted (without loss of accuracy). Useful for variable importances and auto-enabled for autoencoder.",filter=Default.class, json=true, importance = ParamImportance.SECONDARY)
public boolean use_all_factor_levels = true;
/*Neural Net Topology*/
/**
* The activation function (non-linearity) to be used the neurons in the hidden layers.
* Tanh: Hyperbolic tangent function (same as scaled and shifted sigmoid).
* Rectifier: Chooses the maximum of (0, x) where x is the input value.
* Maxout: Choose the maximum coordinate of the input vector.
* With Dropout: Zero out a random user-given fraction of the
* incoming weights to each hidden layer during training, for each
* training row. This effectively trains exponentially many models at
* once, and can improve generalization.
*/
@API(help = "Activation function", filter = Default.class, json = true, importance = ParamImportance.CRITICAL)
public Activation activation = Activation.Rectifier;
/**
* The number and size of each hidden layer in the model.
* For example, if a user specifies "100,200,100" a model with 3 hidden
* layers will be produced, and the middle hidden layer will have 200
* neurons.To specify a grid search, add parentheses around each
* model's specification: "(100,100), (50,50,50), (20,20,20,20)".
*/
@API(help = "Hidden layer sizes (e.g. 100,100). Grid search: (10,10), (20,20,20)", filter = Default.class, json = true, importance = ParamImportance.CRITICAL)
public int[] hidden = new int[] { 200, 200 };
/**
* The number of passes over the training dataset to be carried out.
* It is recommended to start with lower values for initial grid searches.
* This value can be modified during checkpoint restarts and allows continuation
* of selected models.
*/
@API(help = "How many times the dataset should be iterated (streamed), can be fractional", filter = Default.class, dmin = 1e-3, json = true, importance = ParamImportance.CRITICAL)
public double epochs = 10;
/**
* The number of training data rows to be processed per iteration. Note that
* independent of this parameter, each row is used immediately to update the model
* with (online) stochastic gradient descent. This parameter controls the
* synchronization period between nodes in a distributed environment and the
* frequency at which scoring and model cancellation can happen. For example, if
* it is set to 10,000 on H2O running on 4 nodes, then each node will
* process 2,500 rows per iteration, sampling randomly from their local data.
* Then, model averaging between the nodes takes place, and scoring can happen
* (dependent on scoring interval and duty factor). Special values are 0 for
* one epoch per iteration, -1 for processing the maximum amount of data
* per iteration (if **replicate training data** is enabled, N epochs
* will be trained per iteration on N nodes, otherwise one epoch). Special value
* of -2 turns on automatic mode (auto-tuning).
*/
@API(help = "Number of training samples (globally) per MapReduce iteration. Special values are 0: one epoch, -1: all available data (e.g., replicated training data), -2: automatic", filter = Default.class, lmin = -2, json = true, importance = ParamImportance.SECONDARY)
public long train_samples_per_iteration = -2;
// @API(help = "Target ratio of communication overhead to computation. Only for multi-node operation and train_samples_per_iteration=-2 (auto-tuning)", filter = Default.class, dmin = 1e-3, dmax=0.999, json = true, importance = ParamImportance.SECONDARY)
public double target_ratio_comm_to_comp = 0.02;
/**
* The random seed controls sampling and initialization. Reproducible
* results are only expected with single-threaded operation (i.e.,
* when running on one node, turning off load balancing and providing
* a small dataset that fits in one chunk). In general, the
* multi-threaded asynchronous updates to the model parameters will
* result in (intentional) race conditions and non-reproducible
* results. Note that deterministic sampling and initialization might
* still lead to some weak sense of determinism in the model.
*/
@API(help = "Seed for random numbers (affects sampling) - Note: only reproducible when running single threaded", filter = Default.class, json = true)
public long seed = new Random().nextLong();
/*Adaptive Learning Rate*/
/**
* The implemented adaptive learning rate algorithm (ADADELTA) automatically
* combines the benefits of learning rate annealing and momentum
* training to avoid slow convergence. Specification of only two
* parameters (rho and epsilon) simplifies hyper parameter search.
* In some cases, manually controlled (non-adaptive) learning rate and
* momentum specifications can lead to better results, but require the
* specification (and hyper parameter search) of up to 7 parameters.
* If the model is built on a topology with many local minima or
* long plateaus, it is possible for a constant learning rate to produce
* sub-optimal results. Learning rate annealing allows digging deeper into
* local minima, while rate decay allows specification of different
* learning rates per layer. When the gradient is being estimated in
* a long valley in the optimization landscape, a large learning rate
* can cause the gradient to oscillate and move in the wrong
* direction. When the gradient is computed on a relatively flat
* surface with small learning rates, the model can converge far
* slower than necessary.
*/
@API(help = "Adaptive learning rate (ADADELTA)", filter = Default.class, json = true, importance = ParamImportance.SECONDARY)
public boolean adaptive_rate = true;
/**
* The first of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to momentum and relates to the memory to prior weight updates.
* Typical values are between 0.9 and 0.999.
* This parameter is only active if adaptive learning rate is enabled.
*/
@API(help = "Adaptive learning rate time decay factor (similarity to prior updates)", filter = Default.class, dmin = 0.01, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double rho = 0.99;
/**
* The second of two hyper parameters for adaptive learning rate (ADADELTA).
* It is similar to learning rate annealing during initial training
* and momentum at later stages where it allows forward progress.
* Typical values are between 1e-10 and 1e-4.
* This parameter is only active if adaptive learning rate is enabled.
*/
@API(help = "Adaptive learning rate smoothing factor (to avoid divisions by zero and allow progress)", filter = Default.class, dmin = 1e-15, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double epsilon = 1e-8;
/*Learning Rate*/
/**
* When adaptive learning rate is disabled, the magnitude of the weight
* updates are determined by the user specified learning rate
* (potentially annealed), and are a function of the difference
* between the predicted value and the target value. That difference,
* generally called delta, is only available at the output layer. To
* correct the output at each hidden layer, back propagation is
* used. Momentum modifies back propagation by allowing prior
* iterations to influence the current update. Using the momentum
* parameter can aid in avoiding local minima and the associated
* instability. Too much momentum can lead to instabilities, that's
* why the momentum is best ramped up slowly.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Learning rate (higher => less stable, lower => slower convergence)", filter = Default.class, dmin = 1e-10, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double rate = .005;
/**
* Learning rate annealing reduces the learning rate to "freeze" into
* local minima in the optimization landscape. The annealing rate is the
* inverse of the number of training samples it takes to cut the learning rate in half
* (e.g., 1e-6 means that it takes 1e6 training samples to halve the learning rate).
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Learning rate annealing: rate / (1 + rate_annealing * samples)", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double rate_annealing = 1e-6;
/**
* The learning rate decay parameter controls the change of learning rate across layers.
* For example, assume the rate parameter is set to 0.01, and the rate_decay parameter is set to 0.5.
* Then the learning rate for the weights connecting the input and first hidden layer will be 0.01,
* the learning rate for the weights connecting the first and the second hidden layer will be 0.005,
* and the learning rate for the weights connecting the second and third hidden layer will be 0.0025, etc.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Learning rate decay factor between layers (N-th layer: rate*alpha^(N-1))", filter = Default.class, dmin = 0, json = true, importance = ParamImportance.EXPERT)
public double rate_decay = 1.0;
/*Momentum*/
/**
* The momentum_start parameter controls the amount of momentum at the beginning of training.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Initial momentum at the beginning of training (try 0.5)", filter = Default.class, dmin = 0, dmax = 0.9999999999, json = true, importance = ParamImportance.SECONDARY)
public double momentum_start = 0;
/**
* The momentum_ramp parameter controls the amount of learning for which momentum increases
* (assuming momentum_stable is larger than momentum_start). The ramp is measured in the number
* of training samples.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Number of training samples for which momentum increases", filter = Default.class, dmin = 1, json = true, importance = ParamImportance.SECONDARY)
public double momentum_ramp = 1e6;
/**
* The momentum_stable parameter controls the final momentum value reached after momentum_ramp training samples.
* The momentum used for training will remain the same for training beyond reaching that point.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Final momentum after the ramp is over (try 0.99)", filter = Default.class, dmin = 0, dmax = 0.9999999999, json = true, importance = ParamImportance.SECONDARY)
public double momentum_stable = 0;
/**
* The Nesterov accelerated gradient descent method is a modification to
* traditional gradient descent for convex functions. The method relies on
* gradient information at various points to build a polynomial approximation that
* minimizes the residuals in fewer iterations of the descent.
* This parameter is only active if adaptive learning rate is disabled.
*/
@API(help = "Use Nesterov accelerated gradient (recommended)", filter = Default.class, json = true, importance = ParamImportance.SECONDARY)
public boolean nesterov_accelerated_gradient = true;
/*Regularization*/
/**
* A fraction of the features for each training row to be omitted from training in order
* to improve generalization (dimension sampling).
*/
@API(help = "Input layer dropout ratio (can improve generalization, try 0.1 or 0.2)", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double input_dropout_ratio = 0.0;
/**
* A fraction of the inputs for each hidden layer to be omitted from training in order
* to improve generalization. Defaults to 0.5 for each hidden layer if omitted.
*/
@API(help = "Hidden layer dropout ratios (can improve generalization), specify one value per hidden layer, defaults to 0.5", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double[] hidden_dropout_ratios;
/**
* A regularization method that constrains the absolute value of the weights and
* has the net effect of dropping some weights (setting them to zero) from a model
* to reduce complexity and avoid overfitting.
*/
@API(help = "L1 regularization (can add stability and improve generalization, causes many weights to become 0)", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double l1 = 0.0;
/**
* A regularization method that constrdains the sum of the squared
* weights. This method introduces bias into parameter estimates, but
* frequently produces substantial gains in modeling as estimate variance is
* reduced.
*/
@API(help = "L2 regularization (can add stability and improve generalization, causes many weights to be small", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.SECONDARY)
public double l2 = 0.0;
/**
* A maximum on the sum of the squared incoming weights into
* any one neuron. This tuning parameter is especially useful for unbound
* activation functions such as Maxout or Rectifier.
*/
@API(help = "Constraint for squared sum of incoming weights per unit (e.g. for Rectifier)", filter = Default.class, dmin = 1e-10, json = true, importance = ParamImportance.EXPERT)
public float max_w2 = Float.POSITIVE_INFINITY;
/*Initialization*/
/**
* The distribution from which initial weights are to be drawn. The default
* option is an optimized initialization that considers the size of the network.
* The "uniform" option uses a uniform distribution with a mean of 0 and a given
* interval. The "normal" option draws weights from the standard normal
* distribution with a mean of 0 and given standard deviation.
*/
@API(help = "Initial Weight Distribution", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public InitialWeightDistribution initial_weight_distribution = InitialWeightDistribution.UniformAdaptive;
/**
* The scale of the distribution function for Uniform or Normal distributions.
* For Uniform, the values are drawn uniformly from -initial_weight_scale...initial_weight_scale.
* For Normal, the values are drawn from a Normal distribution with a standard deviation of initial_weight_scale.
*/
@API(help = "Uniform: -value...value, Normal: stddev)", filter = Default.class, dmin = 0, json = true, importance = ParamImportance.EXPERT)
public double initial_weight_scale = 1.0;
/**
* The loss (error) function to be minimized by the model.
* Cross Entropy loss is used when the model output consists of independent
* hypotheses, and the outputs can be interpreted as the probability that each
* hypothesis is true. Cross entropy is the recommended loss function when the
* target values are class labels, and especially for imbalanced data.
* It strongly penalizes error in the prediction of the actual class label.
* Mean Square loss is used when the model output are continuous real values, but can
* be used for classification as well (where it emphasizes the error on all
* output classes, not just for the actual class).
*/
@API(help = "Loss function", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public Loss loss = Loss.Automatic;
/*Scoring*/
/**
* The minimum time (in seconds) to elapse between model scoring. The actual
* interval is determined by the number of training samples per iteration and the scoring duty cycle.
*/
@API(help = "Shortest time interval (in secs) between model scoring", filter = Default.class, dmin = 0, json = true, importance = ParamImportance.SECONDARY)
public double score_interval = 5;
/**
* The number of training dataset points to be used for scoring. Will be
* randomly sampled. Use 0 for selecting the entire training dataset.
*/
@API(help = "Number of training set samples for scoring (0 for all)", filter = Default.class, lmin = 0, json = true, importance = ParamImportance.EXPERT)
public long score_training_samples = 10000l;
/**
* The number of validation dataset points to be used for scoring. Can be
* randomly sampled or stratified (if "balance classes" is set and "score
* validation sampling" is set to stratify). Use 0 for selecting the entire
* training dataset.
*/
@API(help = "Number of validation set samples for scoring (0 for all)", filter = Default.class, lmin = 0, json = true, importance = ParamImportance.EXPERT)
public long score_validation_samples = 0l;
/**
* Maximum fraction of wall clock time spent on model scoring on training and validation samples,
* and on diagnostics such as computation of feature importances (i.e., not on training).
*/
@API(help = "Maximum duty cycle fraction for scoring (lower: more training, higher: more scoring).", filter = Default.class, dmin = 0, dmax = 1, json = true, importance = ParamImportance.EXPERT)
public double score_duty_cycle = 0.1;
/**
* The stopping criteria in terms of classification error (1-accuracy) on the
* training data scoring dataset. When the error is at or below this threshold,
* training stops.
*/
@API(help = "Stopping criterion for classification error fraction on training data (-1 to disable)", filter = Default.class, dmin=-1, dmax=1, json = true, importance = ParamImportance.EXPERT)
public double classification_stop = 0;
/**
* The stopping criteria in terms of regression error (MSE) on the training
* data scoring dataset. When the error is at or below this threshold, training
* stops.
*/
@API(help = "Stopping criterion for regression error (MSE) on training data (-1 to disable)", filter = Default.class, dmin=-1, json = true, importance = ParamImportance.EXPERT)
public double regression_stop = 1e-6;
/**
* Enable quiet mode for less output to standard output.
*/
@API(help = "Enable quiet mode for less output to standard output", filter = Default.class, json = true)
public boolean quiet_mode = false;
/**
* For classification models, the maximum size (in terms of classes) of the
* confusion matrix for it to be printed. This option is meant to avoid printing
* extremely large confusion matrices.
*/
@API(help = "Max. size (number of classes) for confusion matrices to be shown", filter = Default.class, json = true)
public int max_confusion_matrix_size = 20;
/**
* The maximum number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable)
*/
@API(help = "Max. number (top K) of predictions to use for hit ratio computation (for multi-class only, 0 to disable)", filter = Default.class, lmin=0, json = true, importance = ParamImportance.EXPERT)
public int max_hit_ratio_k = 10;
/*Imbalanced Classes*/
/**
* For imbalanced data, balance training data class counts via
* over/under-sampling. This can result in improved predictive accuracy.
*/
@API(help = "Balance training data class counts via over/under-sampling (for imbalanced data)", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean balance_classes = false;
/**
* Desired relative class ratios of the training data after over/under-sampling. Only when balance_classes is enabled. Default is 1/N for each class, where N is the number of classes.
*/
@API(help = "Desired relative class ratios of the training data after over/under-sampling.", filter = Default.class, dmin = 1, json = true, importance = ParamImportance.SECONDARY)
public float[] balance_class_model_distribution;
/**
* When classes are balanced, limit the resulting dataset size to the
* specified multiple of the original dataset size.
*/
@API(help = "Maximum relative size of the training data after balancing class counts (can be less than 1.0)", filter = Default.class, json = true, dmin=1e-3, importance = ParamImportance.EXPERT)
public float max_after_balance_size = 5.0f;
/**
* Method used to sample the validation dataset for scoring, see Score Validation Samples above.
*/
@API(help = "Method used to sample validation dataset for scoring", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public ClassSamplingMethod score_validation_sampling = ClassSamplingMethod.Uniform;
/*Misc*/
/**
* Gather diagnostics for hidden layers, such as mean and RMS values of learning
* rate, momentum, weights and biases.
*/
@API(help = "Enable diagnostics for hidden layers", filter = Default.class, json = true)
public boolean diagnostics = true;
/**
* Whether to compute variable importances for input features.
* The implemented method (by Gedeon) considers the weights connecting the
* input features to the first two hidden layers.
*/
@API(help = "Compute variable importances for input features (Gedeon method) - can be slow for large networks", filter = Default.class, json = true)
public boolean variable_importances = false;
/**
* Enable fast mode (minor approximation in back-propagation), should not affect results significantly.
*/
@API(help = "Enable fast mode (minor approximation in back-propagation)", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean fast_mode = true;
/**
* Ignore constant training columns (no information can be gained anyway).
*/
@API(help = "Ignore constant training columns (no information can be gained anyway)", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean ignore_const_cols = true;
/**
* Increase training speed on small datasets by splitting it into many chunks
* to allow utilization of all cores.
*/
@API(help = "Force extra load balancing to increase training speed for small datasets (to keep all cores busy)", filter = Default.class, json = true)
public boolean force_load_balance = true;
/**
* Replicate the entire training dataset onto every node for faster training on small datasets.
*/
@API(help = "Replicate the entire training dataset onto every node for faster training on small datasets", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean replicate_training_data = true;
/**
* Run on a single node for fine-tuning of model parameters. Can be useful for
* checkpoint resumes after training on multiple nodes for fast initial
* convergence.
*/
@API(help = "Run on a single node for fine-tuning of model parameters", filter = Default.class, json = true)
public boolean single_node_mode = false;
/**
* Enable shuffling of training data (on each node). This option is
* recommended if training data is replicated on N nodes, and the number of training samples per iteration
* is close to N times the dataset size, where all nodes train will (almost) all
* the data. It is automatically enabled if the number of training samples per iteration is set to -1 (or to N
* times the dataset size or larger).
*/
@API(help = "Enable shuffling of training data (recommended if training data is replicated and train_samples_per_iteration is close to #nodes x #rows)", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean shuffle_training_data = false;
// @API(help = "Handling of missing values. Either Skip or MeanImputation.", filter= Default.class, json = true)
public MissingValuesHandling missing_values_handling = MissingValuesHandling.MeanImputation;
@API(help = "Sparse data handling (Experimental).", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean sparse = false;
@API(help = "Use a column major weight matrix for input layer. Can speed up forward propagation, but might slow down backpropagation (Experimental).", filter = Default.class, json = true, importance = ParamImportance.EXPERT)
public boolean col_major = false;
@API(help = "Average activation for sparse auto-encoder (Experimental)", filter= Default.class, json = true)
public double average_activation = 0;
@API(help = "Sparsity regularization (Experimental)", filter= Default.class, json = true)
public double sparsity_beta = 0;
public enum MissingValuesHandling {
Skip, MeanImputation
}
public enum ClassSamplingMethod {
Uniform, Stratified
}
public enum InitialWeightDistribution {
UniformAdaptive, Uniform, Normal
}
/**
* Activation functions
*/
public enum Activation {
Tanh, TanhWithDropout, Rectifier, RectifierWithDropout, Maxout, MaxoutWithDropout
}
/**
* Loss functions
* CrossEntropy is recommended
*/
public enum Loss {
Automatic, MeanSquare, CrossEntropy
}
// the following parameters can only be specified in expert mode
transient final String [] expert_options = new String[] {
"use_all_factor_levels",
"loss",
"max_w2",
"score_training_samples",
"score_validation_samples",
"initial_weight_distribution",
"initial_weight_scale",
"diagnostics",
"rate_decay",
"score_duty_cycle",
"variable_importances",
"fast_mode",
"score_validation_sampling",
"ignore_const_cols",
"force_load_balance",
"replicate_training_data",
"shuffle_training_data",
"nesterov_accelerated_gradient",
"classification_stop",
"regression_stop",
"quiet_mode",
"max_confusion_matrix_size",
"max_hit_ratio_k",
"hidden_dropout_ratios",
"single_node_mode",
"sparse",
"col_major",
"autoencoder",
"average_activation",
"sparsity_beta",
};
// the following parameters can be modified when restarting from a checkpoint
transient final String [] cp_modifiable = new String[] {
"expert_mode",
"seed",
"epochs",
"score_interval",
"train_samples_per_iteration",
"target_ratio_comm_to_comp",
"score_duty_cycle",
"classification_stop",
"regression_stop",
"quiet_mode",
"max_confusion_matrix_size",
"max_hit_ratio_k",
"diagnostics",
"variable_importances",
"force_load_balance",
"replicate_training_data",
"shuffle_training_data",
"single_node_mode",
"sparse",
"col_major",
};
/**
* Helper to specify which arguments trigger a refresh on change
* @param ver
*/
@Override
protected void registered(RequestServer.API_VERSION ver) {
super.registered(ver);
for (Argument arg : _arguments) {
if ( arg._name.equals("activation") || arg._name.equals("initial_weight_distribution")
|| arg._name.equals("expert_mode") || arg._name.equals("adaptive_rate")
|| arg._name.equals("replicate_training_data")
|| arg._name.equals("balance_classes")
|| arg._name.equals("n_folds")
|| arg._name.equals("checkpoint")) {
arg.setRefreshOnChange();
}
}
}
/**
* Helper to handle arguments based on existing input values
* @param arg
* @param inputArgs
*/
@Override protected void queryArgumentValueSet(Argument arg, java.util.Properties inputArgs) {
super.queryArgumentValueSet(arg, inputArgs);
if (!arg._name.equals("checkpoint") && !Utils.contains(cp_modifiable, arg._name)) {
if (checkpoint != null) {
arg.disable("Taken from model checkpoint.");
final DeepLearningModel cp_model = UKV.get(checkpoint);
if (cp_model == null) {
throw new IllegalArgumentException("Checkpointed model was not found.");
}
if (cp_model.model_info().unstable()) {
throw new IllegalArgumentException("Checkpointed model was unstable. Not restarting.");
}
return;
}
}
if(arg._name.equals("initial_weight_scale") &&
(initial_weight_distribution == InitialWeightDistribution.UniformAdaptive)
) {
arg.disable("Using sqrt(6 / (# units + # units of previous layer)) for Uniform distribution.", inputArgs);
}
if (classification) {
if(arg._name.equals("regression_stop")) {
arg.disable("Only for regression.", inputArgs);
}
if(arg._name.equals("max_after_balance_size") && !balance_classes) {
arg.disable("Requires balance_classes.", inputArgs);
}
}
else {
if(arg._name.equals("classification_stop")
|| arg._name.equals("max_confusion_matrix_size")
|| arg._name.equals("max_hit_ratio_k")
|| arg._name.equals("max_after_balance_size")
|| arg._name.equals("balance_classes")) {
arg.disable("Only for classification.", inputArgs);
}
if (validation != null && arg._name.equals("score_validation_sampling")) {
score_validation_sampling = ClassSamplingMethod.Uniform;
arg.disable("Using uniform sampling for validation scoring dataset.", inputArgs);
}
}
if ((arg._name.equals("score_validation_samples") || arg._name.equals("score_validation_sampling")) && validation == null) {
arg.disable("Requires a validation data set.", inputArgs);
}
if (Utils.contains(expert_options, arg._name) && !expert_mode) {
arg.disable("Only in expert mode.", inputArgs);
}
if (!adaptive_rate) {
if (arg._name.equals("rho") || arg._name.equals("epsilon")) {
arg.disable("Only for adaptive learning rate.", inputArgs);
rho = 0;
epsilon = 0;
}
} else {
if (arg._name.equals("rate") || arg._name.equals("rate_annealing") || arg._name.equals("rate_decay") || arg._name.equals("nesterov_accelerated_gradient")
|| arg._name.equals("momentum_start") || arg._name.equals("momentum_ramp") || arg._name.equals("momentum_stable") ) {
arg.disable("Only for non-adaptive learning rate.", inputArgs);
momentum_start = 0;
momentum_stable = 0;
}
}
if (arg._name.equals("hidden_dropout_ratios")) {
if (activation != Activation.TanhWithDropout && activation != Activation.MaxoutWithDropout && activation != Activation.RectifierWithDropout) {
arg.disable("Only for activation functions with dropout.", inputArgs);
}
}
if (arg._name.equals("replicate_training_data") && (H2O.CLOUD.size() == 1)) {
arg.disable("Only for multi-node operation.");
replicate_training_data = false;
}
if (arg._name.equals("single_node_mode") && (H2O.CLOUD.size() == 1 || !replicate_training_data)) {
arg.disable("Only for multi-node operation with replication.");
single_node_mode = false;
}
if (arg._name.equals("use_all_factor_levels") && autoencoder ) {
arg.disable("Automatically enabled for auto-encoders.");
use_all_factor_levels = true;
}
if(arg._name.equals("override_with_best_model") && n_folds != 0) {
arg.disable("Only without n-fold cross-validation.", inputArgs);
override_with_best_model = false;
}
}
/** Print model parameters as JSON */
@Override public boolean toHTML(StringBuilder sb) {
try {
return makeJsonBox(sb);
} catch (Throwable t) {
return false;
}
}
/**
* Return a query link to this page
* @param k Model Key
* @param content Link text
* @return HTML Link
*/
public static String link(Key k, String content) {
return link(k, content, null, null, null);
}
/**
* Return a query link to this page
* @param k Model Key
* @param content Link text
* @param cp Key to checkpoint to continue training with (optional)
* @param response Response
* @param val Validation data set key
* @return HTML Link
*/
public static String link(Key k, String content, Key cp, String response, Key val) {
DeepLearning req = new DeepLearning();
RString rs = new RString("<a href='" + req.href() + ".query?source=%$key" +
(cp == null ? "" : "&checkpoint=%$cp") +
(response == null ? "" : "&response=%$resp") +
(val == null ? "" : "&validation=%$valkey") +
"'>%content</a>");
rs.replace("key", k.toString());
rs.replace("content", content);
if (cp != null) rs.replace("cp", cp.toString());
if (response != null) rs.replace("resp", response);
if (val != null) rs.replace("valkey", val);
return rs.toString();
}
/**
* Report the relative progress of building a Deep Learning model (measured by how many epochs are done)
* @return floating point number between 0 and 1
*/
@Override public float progress(){
if(UKV.get(dest()) == null)return 0;
DeepLearningModel m = UKV.get(dest());
if (m != null && m.model_info()!=null ) {
final float p = (float) Math.min(1, (m.epoch_counter / m.model_info().get_params().epochs));
return cv_progress(p);
}
return 0;
}
@Override
protected final void execImpl() {
try {
buildModel();
if (n_folds > 0) CrossValUtils.crossValidate(this);
} finally {
delete();
state = UKV.<Job>get(self()).state;
new TAtomic<DeepLearningModel>() {
@Override
public DeepLearningModel atomic(DeepLearningModel m) {
if (m != null) m.get_params().state = state;
return m;
}
}.invoke(dest());
}
}
/**
* Train a Deep Learning model, assumes that all members are populated
* If checkpoint == null, then start training a new model, otherwise continue from a checkpoint
*/
private void buildModel() {
DeepLearningModel cp = null;
if (checkpoint == null) {
cp = initModel();
cp.start_training(null);
} else {
final DeepLearningModel previous = UKV.get(checkpoint);
if (previous == null) throw new IllegalArgumentException("Checkpoint not found.");
Log.info("Resuming from checkpoint.");
if (n_folds != 0) {
throw new UnsupportedOperationException("n_folds must be 0: Cross-validation is not supported during checkpoint restarts.");
}
else {
((ValidatedJob)previous.job()).xval_models = null; //remove existing cross-validation keys after checkpoint restart
}
if (source == null || (previous.model_info().get_params().source != null && !Arrays.equals(source._key._kb, previous.model_info().get_params().source._key._kb))) {
throw new IllegalArgumentException("source must be the same as for the checkpointed model.");
}
autoencoder = previous.model_info().get_params().autoencoder;
if (!autoencoder && (response == null || !source.names()[source.find(response)].equals(previous.responseName()))) {
throw new IllegalArgumentException("response must be the same as for the checkpointed model.");
}
// if (!autoencoder && (response == null || !Arrays.equals(response._key._kb, previous.model_info().get_params().response._key._kb))) {
if (Utils.difference(ignored_cols, previous.model_info().get_params().ignored_cols).length != 0
|| Utils.difference(previous.model_info().get_params().ignored_cols, ignored_cols).length != 0) {
ignored_cols = previous.model_info().get_params().ignored_cols;
Log.warn("Automatically re-using ignored_cols from the checkpointed model.");
}
if ((validation == null) == (previous._validationKey != null)
|| (validation != null && validation._key != null && previous._validationKey != null
&& !Arrays.equals(validation._key._kb, previous._validationKey._kb))) {
throw new IllegalArgumentException("validation must be the same as for the checkpointed model.");
}
if (classification != previous.model_info().get_params().classification) {
Log.warn("Automatically switching to " + ((classification=!classification) ? "classification" : "regression") + " (same as the checkpointed model).");
}
epochs += previous.epoch_counter; //add new epochs to existing model
Log.info("Adding " + String.format("%.3f", previous.epoch_counter) + " epochs from the checkpointed model.");
try {
final DataInfo dataInfo = prepareDataInfo();
cp = new DeepLearningModel(previous, destination_key, job_key, dataInfo);
cp.write_lock(self());
cp.start_training(previous);
assert(state==JobState.RUNNING);
final DeepLearning A = cp.model_info().get_params();
Object B = this;
for (Field fA : A.getClass().getDeclaredFields()) {
if (Utils.contains(cp_modifiable, fA.getName())) {
if (!expert_mode && Utils.contains(expert_options, fA.getName())) continue;
for (Field fB : B.getClass().getDeclaredFields()) {
if (fA.equals(fB)) {
try {
if (fB.get(B) == null || fA.get(A) == null || !fA.get(A).toString().equals(fB.get(B).toString())) { // if either of the two parameters is null, skip the toString()
if (fA.get(A) == null && fB.get(B) == null) continue; //if both parameters are null, we don't need to do anything
Log.info("Applying user-requested modification of '" + fA.getName() + "': " + fA.get(A) + " -> " + fB.get(B));
fA.set(A, fB.get(B));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
if (A.n_folds != 0) {
Log.warn("Disabling cross-validation: Not supported when resuming training from a checkpoint.");
A.n_folds = 0;
}
cp.update(self());
} finally {
if (cp != null) cp.unlock(self());
}
}
trainModel(cp);
cp.stop_training();
}
/**
* Redirect to the model page for that model that is trained by this job
* @return Response
*/
@Override protected Response redirect() {
return DeepLearningProgressPage.redirect(this, self(), dest());
}
private boolean _fakejob;
//Sanity check for Deep Learning job parameters
private void checkParams() {
if (source.numCols() <= 1)
throw new IllegalArgumentException("Training data must have at least 2 features (incl. response).");
if (hidden == null) throw new IllegalArgumentException("There must be at least one hidden layer.");
for (int i=0;i<hidden.length;++i) {
if (hidden[i]==0)
throw new IllegalArgumentException("Hidden layer size must be >0.");
}
//Auto-fill defaults
if (hidden_dropout_ratios == null) {
if (activation == Activation.TanhWithDropout || activation == Activation.MaxoutWithDropout || activation == Activation.RectifierWithDropout) {
hidden_dropout_ratios = new double[hidden.length];
if (!quiet_mode) Log.info("Automatically setting all hidden dropout ratios to 0.5.");
Arrays.fill(hidden_dropout_ratios, 0.5);
}
}
else if (hidden_dropout_ratios.length != hidden.length) throw new IllegalArgumentException("Must have " + hidden.length + " hidden layer dropout ratios.");
else if (activation != Activation.TanhWithDropout && activation != Activation.MaxoutWithDropout && activation != Activation.RectifierWithDropout) {
if (!quiet_mode) Log.info("Ignoring hidden_dropout_ratios because a non-Dropout activation function was specified.");
}
if (input_dropout_ratio < 0 || input_dropout_ratio >= 1) {
throw new IllegalArgumentException("Input dropout must be in [0,1).");
}
if (!quiet_mode) {
if (adaptive_rate) {
Log.info("Using automatic learning rate. Ignoring the following input parameters:");
Log.info(" rate, rate_decay, rate_annealing, momentum_start, momentum_ramp, momentum_stable, nesterov_accelerated_gradient.");
} else {
Log.info("Using manual learning rate. Ignoring the following input parameters:");
Log.info(" rho, epsilon.");
}
if (initial_weight_distribution == InitialWeightDistribution.UniformAdaptive) {
Log.info("Ignoring initial_weight_scale for UniformAdaptive weight distribution.");
}
if (n_folds != 0) {
if (override_with_best_model) {
Log.info("Automatically setting override_with_best_model to false, since the final model is the only scored model with n-fold cross-validation.");
override_with_best_model = false;
}
}
}
if(loss == Loss.Automatic) {
if (!classification) {
if (!quiet_mode) Log.info("Automatically setting loss to MeanSquare for regression.");
loss = Loss.MeanSquare;
}
else if (autoencoder) {
if (!quiet_mode) Log.info("Automatically setting loss to MeanSquare for auto-encoder.");
loss = Loss.MeanSquare;
}
else {
if (!quiet_mode) Log.info("Automatically setting loss to Cross-Entropy for classification.");
loss = Loss.CrossEntropy;
}
}
if(autoencoder && sparsity_beta > 0) {
if (activation == Activation.Tanh || activation == Activation.TanhWithDropout) {
if (average_activation >= 1 || average_activation <= -1)
throw new IllegalArgumentException("Tanh average activation must be in (-1,1).");
}
else if (activation == Activation.Rectifier || activation == Activation.RectifierWithDropout) {
if (average_activation <= 0)
throw new IllegalArgumentException("Rectifier average activation must be positive.");
}
}
if (!classification && loss == Loss.CrossEntropy) throw new IllegalArgumentException("Cannot use CrossEntropy loss function for regression.");
if (autoencoder && loss != Loss.MeanSquare) throw new IllegalArgumentException("Must use MeanSquare loss function for auto-encoder.");
if (autoencoder && classification) { classification = false; Log.info("Using regression mode for auto-encoder.");}
// reason for the error message below is that validation might not have the same horizontalized features as the training data (or different order)
if (autoencoder && validation != null) throw new UnsupportedOperationException("Cannot specify a validation dataset for auto-encoder.");
if (autoencoder && activation == Activation.Maxout) throw new UnsupportedOperationException("Maxout activation is not supported for auto-encoder.");
// make default job_key and destination_key in case they are missing
if (dest() == null) {
destination_key = Key.make();
}
if (self() == null) {
job_key = Key.make();
}
if (UKV.get(self()) == null) {
start_time = System.currentTimeMillis();
state = JobState.RUNNING;
UKV.put(self(), this);
_fakejob = true;
}
if (!sparse && col_major) {
if (!quiet_mode) throw new IllegalArgumentException("Cannot use column major storage for non-sparse data handling.");
}
}
/**
* Helper to create a DataInfo object from the source and response
* @return DataInfo object
*/
private DataInfo prepareDataInfo() {
final boolean del_enum_resp = classification && !response.isEnum();
final Frame train = FrameTask.DataInfo.prepareFrame(source, autoencoder ? null : response, ignored_cols, classification, ignore_const_cols, true /*drop >20% NA cols*/);
final DataInfo dinfo = new FrameTask.DataInfo(train, autoencoder ? 0 : 1, autoencoder || use_all_factor_levels, //use all FactorLevels for auto-encoder
autoencoder ? DataInfo.TransformType.NORMALIZE : DataInfo.TransformType.STANDARDIZE, //transform predictors
classification ? DataInfo.TransformType.NONE : DataInfo.TransformType.STANDARDIZE); //transform response
if (!autoencoder) {
final Vec resp = dinfo._adaptedFrame.lastVec(); //convention from DataInfo: response is the last Vec
assert (!classification ^ resp.isEnum()) : "Must have enum response for classification!"; //either regression or enum response
if (del_enum_resp) ltrash(resp);
}
return dinfo;
}
/**
* Create an initial Deep Learning model, typically to be trained by trainModel(model)
* @return Randomly initialized model
*/
public final DeepLearningModel initModel() {
try {
lock_data();
checkParams();
final DataInfo dinfo = prepareDataInfo();
final Vec resp = dinfo._adaptedFrame.lastVec(); //convention from DataInfo: response is the last Vec
float[] priorDist = classification ? new MRUtils.ClassDist(resp).doAll(resp).rel_dist() : null;
final DeepLearningModel model = new DeepLearningModel(dest(), self(), source._key, dinfo, (DeepLearning)this.clone(), priorDist);
model.model_info().initializeMembers();
return model;
}
finally {
unlock_data();
}
}
/**
* Helper to update a Frame and adding it to the local trash at the same time
* @param target Frame referece, to be overwritten
* @param src Newly made frame, to be deleted via local trash
* @return src
*/
Frame updateFrame(Frame target, Frame src) {
if (src != target) ltrash(src);
return src;
}
/**
* Train a Deep Learning neural net model
* @param model Input model (e.g., from initModel(), or from a previous training run)
* @return Trained model
*/
public final DeepLearningModel trainModel(DeepLearningModel model) {
Frame validScoreFrame = null;
Frame train, trainScoreFrame;
try {
lock_data();
if (checkpoint == null && !quiet_mode) logStart(); //if checkpoint is given, some Job's params might be uninitialized (but the restarted model's parameters are correct)
if (model == null) {
model = UKV.get(dest());
}
model.write_lock(self());
final DeepLearning mp = model.model_info().get_params(); //use the model's parameters for everything below - NOT the job's parameters (can be different after checkpoint restart)
prepareValidationWithModel(model);
final long model_size = model.model_info().size();
if (!quiet_mode) Log.info("Number of model parameters (weights/biases): " + String.format("%,d", model_size));
train = model.model_info().data_info()._adaptedFrame;
if (mp.force_load_balance) train = updateFrame(train, reBalance(train, mp.replicate_training_data /*rebalance into only 4*cores per node*/));
if (mp.classification && mp.balance_classes) {
float[] trainSamplingFactors = new float[train.lastVec().domain().length]; //leave initialized to 0 -> will be filled up below
if (balance_class_model_distribution != null) {
if (balance_class_model_distribution.length != train.lastVec().domain().length)
throw new IllegalArgumentException("balance_class_model_distribution must have " + train.lastVec().domain().length + " elements");
trainSamplingFactors = balance_class_model_distribution;
}
train = updateFrame(train, sampleFrameStratified(
train, train.lastVec(), trainSamplingFactors, (long)(mp.max_after_balance_size*train.numRows()), mp.seed, true, false));
model.setModelClassDistribution(new MRUtils.ClassDist(train.lastVec()).doAll(train.lastVec()).rel_dist());
}
model.training_rows = train.numRows();
trainScoreFrame = updateFrame(train, sampleFrame(train, mp.score_training_samples, mp.seed)); //training scoring dataset is always sampled uniformly from the training dataset
if (!quiet_mode) Log.info("Number of chunks of the training data: " + train.anyVec().nChunks());
if (validation != null) {
model.validation_rows = validation.numRows();
Frame adaptedValid = getValidation();
if (getValidAdaptor().needsAdaptation2CM()) {
adaptedValid.add(getValidAdaptor().adaptedValidationResponse(_responseName), getValidAdaptor().getAdaptedValidationResponse2CM());
}
// validation scoring dataset can be sampled in multiple ways from the given validation dataset
if (mp.classification && mp.balance_classes && mp.score_validation_sampling == ClassSamplingMethod.Stratified) {
validScoreFrame = updateFrame(adaptedValid, sampleFrameStratified(adaptedValid, adaptedValid.lastVec(), null,
mp.score_validation_samples > 0 ? mp.score_validation_samples : adaptedValid.numRows(), mp.seed+1, false /* no oversampling */, false));
} else {
validScoreFrame = updateFrame(adaptedValid, sampleFrame(adaptedValid, mp.score_validation_samples, mp.seed+1));
}
if (mp.force_load_balance) validScoreFrame = updateFrame(validScoreFrame, reBalance(validScoreFrame, false /*always split up globally since scoring should be distributed*/));
if (!quiet_mode) Log.info("Number of chunks of the validation data: " + validScoreFrame.anyVec().nChunks());
}
// Set train_samples_per_iteration size (cannot be done earlier since this depends on whether stratified sampling is done)
model.actual_train_samples_per_iteration = computeTrainSamplesPerIteration(mp, train.numRows(), model);
// Determine whether shuffling is enforced
if(mp.replicate_training_data && (model.actual_train_samples_per_iteration == train.numRows()*(mp.single_node_mode?1:H2O.CLOUD.size())) && !mp.shuffle_training_data && H2O.CLOUD.size() > 1) {
Log.warn("Enabling training data shuffling, because all nodes train on the full dataset (replicated training data).");
mp.shuffle_training_data = true;
}
model._timeLastScoreEnter = System.currentTimeMillis(); //to keep track of time per iteration, must be called before first call to doScoring
if (!mp.quiet_mode) Log.info("Initial model:\n" + model.model_info());
if (autoencoder) model.doScoring(train, trainScoreFrame, validScoreFrame, self(), getValidAdaptor()); //get the null model reconstruction error
// put the initial version of the model into DKV
model.update(self());
Log.info("Starting to train the Deep Learning model.");
if (n_folds == 0 || xval_models == null)
//main loop
do model.set_model_info(H2O.CLOUD.size() > 1 && mp.replicate_training_data ? ( mp.single_node_mode ?
new DeepLearningTask2(train, model.model_info(), rowFraction(train, mp, model)).invoke(Key.make()).model_info() : //replicated data + single node mode
new DeepLearningTask2(train, model.model_info(), rowFraction(train, mp, model)).invokeOnAllNodes().model_info() ) : //replicated data + multi-node mode
new DeepLearningTask(model.model_info(), rowFraction(train, mp, model)).doAll(train).model_info()); //distributed data (always in multi-node mode)
while (model.doScoring(train, trainScoreFrame, validScoreFrame, self(), getValidAdaptor()));
// replace the model with the best model so far (if it's better)
if (!isCancelledOrCrashed() && override_with_best_model && model.actual_best_model_key != null && n_folds == 0) {
DeepLearningModel best_model = UKV.get(model.actual_best_model_key);
if (best_model != null && best_model.error() < model.error() && Arrays.equals(best_model.model_info().units, model.model_info().units)) {
Log.info("Setting the model to be the best model so far (based on scoring history).");
DeepLearningModel.DeepLearningModelInfo mi = best_model.model_info().deep_clone();
// Don't cheat - count full amount of training samples, since that's the amount of training it took to train (without finding anything better)
mi.set_processed_global(model.model_info().get_processed_global());
mi.set_processed_local(model.model_info().get_processed_local());
model.set_model_info(mi);
model.update(self());
model.doScoring(train, trainScoreFrame, validScoreFrame, self(), getValidAdaptor());
assert(best_model.error() == model.error());
}
}
Log.info(model);
Log.info("Finished training the Deep Learning model.");
return model;
}
catch(JobCancelledException ex) {
model = UKV.get(dest());
state = JobState.CANCELLED; //for JSON REST response
model.get_params().state = state; //for parameter JSON on the HTML page
Log.info("Deep Learning model building was cancelled.");
return model;
}
finally {
if (model != null) model.unlock(self());
unlock_data();
}
}
/**
* Lock the input datasets against deletes
*/
private void lock_data() {
source.read_lock(self());
if( validation != null && source._key != null && validation._key !=null && !source._key.equals(validation._key) )
validation.read_lock(self());
}
/**
* Release the lock for the input datasets
*/
private void unlock_data() {
source.unlock(self());
if( validation != null && source._key != null && validation._key != null && !source._key.equals(validation._key) )
validation.unlock(self());
}
/**
* Delete job related keys
*/
public void delete() {
cleanup();
if (_fakejob) UKV.remove(job_key);
remove();
}
/**
* Rebalance a frame for load balancing
* @param fr Input frame
* @param local whether to only create enough chunks to max out all cores on one node only
* @return Frame that has potentially more chunks
*/
private Frame reBalance(final Frame fr, boolean local) {
final int chunks = (int)Math.min( 4 * H2O.NUMCPUS * (local ? 1 : H2O.CLOUD.size()), fr.numRows());
if (fr.anyVec().nChunks() > chunks) {
Log.info("Dataset already contains " + fr.anyVec().nChunks() + " chunks. No need to rebalance.");
return fr;
}
if (!quiet_mode) Log.info("ReBalancing dataset into (at least) " + chunks + " chunks.");
// return MRUtils.shuffleAndBalance(fr, chunks, seed, local, shuffle_training_data);
String snewKey = fr._key != null ? (fr._key.toString() + ".balanced") : Key.rand();
Key newKey = Key.makeSystem(snewKey);
RebalanceDataSet rb = new RebalanceDataSet(fr, newKey, chunks);
H2O.submitTask(rb);
rb.join();
return UKV.get(newKey);
}
/**
* Compute the actual train_samples_per_iteration size from the user-given parameter
* @param mp Model parameter (DeepLearning object)
* @param numRows number of training rows
* @param model DL Model
* @return The total number of training rows to be processed per iteration (summed over on all nodes)
*/
private static long computeTrainSamplesPerIteration(final DeepLearning mp, final long numRows, DeepLearningModel model) {
long tspi = mp.train_samples_per_iteration;
assert(tspi == 0 || tspi == -1 || tspi == -2 || tspi >= 1);
if (tspi == 0 || (!mp.replicate_training_data && tspi == -1) ) {
tspi = numRows;
if (!mp.quiet_mode) Log.info("Setting train_samples_per_iteration (" + mp.train_samples_per_iteration + ") to one epoch: #rows (" + tspi + ").");
}
else if (tspi == -1) {
tspi = (mp.single_node_mode ? 1 : H2O.CLOUD.size()) * numRows;
if (!mp.quiet_mode) Log.info("Setting train_samples_per_iteration (" + mp.train_samples_per_iteration + ") to #nodes x #rows (" + tspi + ").");
} else if (tspi == -2) {
// automatic tuning based on CPU speed, network speed and model size
// measure cpu speed
double total_gflops = 0;
for (H2ONode h2o : H2O.CLOUD._memary) {
HeartBeat hb = h2o._heartbeat;
total_gflops += hb._gflops;
}
if (mp.single_node_mode) total_gflops /= H2O.CLOUD.size();
if (total_gflops == 0) {
total_gflops = Linpack.run(H2O.SELF._heartbeat._cpus_allowed) * (mp.single_node_mode ? 1 : H2O.CLOUD.size());
}
final long model_size = model.model_info().size();
int[] msg_sizes = new int[]{ (int)(model_size*4) == (model_size*4) ? (int)(model_size*4) : Integer.MAX_VALUE };
double[] microseconds_collective = new double[msg_sizes.length];
NetworkTest.NetworkTester nt = new NetworkTest.NetworkTester(msg_sizes,null,microseconds_collective,model_size>1e6 ? 1 : 5 /*repeats*/,false,true /*only collectives*/);
nt.compute2();
//length of the network traffic queue based on log-tree rollup (2 log(nodes))
int network_queue_length = mp.single_node_mode || H2O.CLOUD.size() == 1? 1 : 2*(int)Math.floor(Math.log(H2O.CLOUD.size())/Math.log(2));
// heuristics
double flops_overhead_per_row = 30;
if (mp.activation == Activation.Maxout || mp.activation == Activation.MaxoutWithDropout) {
flops_overhead_per_row *= 8;
} else if (mp.activation == Activation.Tanh || mp.activation == Activation.TanhWithDropout) {
flops_overhead_per_row *= 5;
}
// target fraction of comm vs cpu time: 5%
double fraction = mp.single_node_mode || H2O.CLOUD.size() == 1 ? 1e-3 : 0.05; //one single node mode, there's no model averaging effect, so less need to shorten the M/R iteration
// estimate the time for communication (network) and training (compute)
model.time_for_communication_us = (H2O.CLOUD.size() == 1 ? 1e4 /* add 10ms for single-node */ : 0) + network_queue_length * microseconds_collective[0];
double time_per_row_us = flops_overhead_per_row * model_size / (total_gflops * 1e9) / H2O.SELF._heartbeat._cpus_allowed * 1e6;
// compute the optimal number of training rows per iteration
// fraction := time_comm_us / (time_comm_us + tspi * time_per_row_us) ==> tspi = (time_comm_us/fraction - time_comm_us)/time_per_row_us
tspi = (long)((model.time_for_communication_us / fraction - model.time_for_communication_us)/ time_per_row_us);
tspi = Math.min(tspi, (mp.single_node_mode ? 1 : H2O.CLOUD.size()) * numRows * 10); //not more than 10x of what train_samples_per_iteration=-1 would do
// If the number is close to a multiple of epochs, use that -> prettier scoring
if (tspi > numRows && Math.abs(tspi % numRows)/(double)numRows < 0.2) tspi = tspi - tspi % numRows;
tspi = Math.min(tspi, (long)(mp.epochs * numRows / 10)); //limit to number of epochs desired, but at least 10 iterations total
tspi = Math.max(1, tspi); //at least 1 point
if (!mp.quiet_mode) {
Log.info("Auto-tuning parameter 'train_samples_per_iteration':");
Log.info("Estimated compute power : " + (int)total_gflops + " GFlops");
Log.info("Estimated time for comm : " + PrettyPrint.usecs((long)model.time_for_communication_us));
Log.info("Estimated time per row : " + ((long)time_per_row_us > 0 ? PrettyPrint.usecs((long)time_per_row_us) : time_per_row_us + " usecs"));
Log.info("Estimated training speed: " + (int)(1e6/time_per_row_us) + " rows/sec");
Log.info("Setting train_samples_per_iteration (" + mp.train_samples_per_iteration + ") to auto-tuned value: " + tspi);
}
} else {
// limit user-given value to number of epochs desired
tspi = Math.min(tspi, (long)(mp.epochs * numRows));
}
assert(tspi != 0 && tspi != -1 && tspi != -2 && tspi >= 1);
return tspi;
}
/**
* Compute the fraction of rows that need to be used for training during one iteration
* @param numRows number of training rows
* @param train_samples_per_iteration number of training rows to be processed per iteration
* @param replicate_training_data whether of not the training data is replicated on each node
* @return fraction of rows to be used for training during one iteration
*/
private static float computeRowUsageFraction(final long numRows, final long train_samples_per_iteration, final boolean replicate_training_data) {
float rowUsageFraction = (float)train_samples_per_iteration / numRows;
if (replicate_training_data) rowUsageFraction /= H2O.CLOUD.size();
assert(rowUsageFraction > 0);
return rowUsageFraction;
}
private static float rowFraction(Frame train, DeepLearning p, DeepLearningModel m) {
return computeRowUsageFraction(train.numRows(), m.actual_train_samples_per_iteration, p.replicate_training_data);
}
/**
* Cross-Validate a DeepLearning model by building new models on N train/test holdout splits
* @param splits Frames containing train/test splits
* @param cv_preds Array of Frames to store the predictions for each cross-validation run
* @param offsets Array to store the offsets of starting row indices for each cross-validation run
* @param i Which fold of cross-validation to perform
*/
@Override public void crossValidate(Frame[] splits, Frame[] cv_preds, long[] offsets, int i) {
// Train a clone with slightly modified parameters (to account for cross-validation)
final DeepLearning cv = (DeepLearning) this.clone();
cv.genericCrossValidation(splits, offsets, i);
cv_preds[i] = ((DeepLearningModel) UKV.get(cv.dest())).score(cv.validation);
new TAtomic<DeepLearningModel>() {
@Override public DeepLearningModel atomic(DeepLearningModel m) {
if (!keep_cross_validation_splits && /*paranoid*/cv.dest().toString().contains("xval")) {
m.get_params().source = null;
m.get_params().validation=null;
m.get_params().response=null;
}
return m;
}
}.invoke(cv.dest());
}
}
|
package javaewah;
import java.util.*;
import java.io.*;
public final class EWAHCompressedBitmap implements Cloneable, Externalizable,
Iterable<Integer> {
/**
* Creates an empty bitmap (no bit set to true).
*/
public EWAHCompressedBitmap() {
this.buffer = new long[defaultbuffersize];
this.rlw = new RunningLengthWord(this.buffer, 0);
}
/**
* Sets explicitly the buffer size (in 64-bit words). The initial memory usage
* will be "buffersize * 64". For large poorly compressible bitmaps, using
* large values may improve performance.
*
* @param buffersize number of 64-bit words reserved when the object is created)
*/
public EWAHCompressedBitmap(final int buffersize) {
this.buffer = new long[buffersize];
this.rlw = new RunningLengthWord(this.buffer, 0);
}
/**
* Gets an EWAHIterator over the data. This is a customized
* iterator which iterates over run length word. For experts only.
*
* @return the EWAHIterator
*/
private EWAHIterator getEWAHIterator() {
return new EWAHIterator(this.buffer, this.actualsizeinwords);
}
/**
* Returns a new compressed bitmap containing the bitwise XOR values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap xor(final EWAHCompressedBitmap a) {
final EWAHCompressedBitmap container = new EWAHCompressedBitmap();
container.reserve(this.actualsizeinwords + a.actualsizeinwords);
final EWAHIterator i = a.getEWAHIterator();
final EWAHIterator j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.sizeinbits = sizeInBits();
return container;
}
// at this point, this is safe:
BufferedRunningLengthWord rlwi = new BufferedRunningLengthWord(i.next());
BufferedRunningLengthWord rlwj = new BufferedRunningLengthWord(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final long dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
} else {
// we have a stream of 1x11
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container.addStreamOfEmptyWords(!predator.getRunningBit(),
tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
final long[] buf = i_is_prey ? j.buffer() : i.buffer();
for (int k = 0; k < preyrl - tobediscarded; ++k)
container.add(~buf[k + dw_predator]);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
}
final long predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final long dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
} else {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
final long[] buf = i_is_prey ? i.buffer() : j.buffer();
for (int k = 0; k < tobediscarded; ++k)
container.add(~buf[k + dw_prey]);
}
}
// all that is left to do now is to AND the dirty words
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
^ j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
^ j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
discharge(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.sizeinbits = Math.max(sizeInBits(), a.sizeInBits());
return container;
}
/**
* Returns a new compressed bitmap containing the bitwise AND values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap and(final EWAHCompressedBitmap a) {
final EWAHCompressedBitmap container = new EWAHCompressedBitmap();
container
.reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords
: a.actualsizeinwords);
final EWAHIterator i = a.getEWAHIterator();
final EWAHIterator j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.sizeinbits = sizeInBits();
return container;
}
// at this point, this is safe:
BufferedRunningLengthWord rlwi = new BufferedRunningLengthWord(i.next());
BufferedRunningLengthWord rlwj = new BufferedRunningLengthWord(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
container.addStreamOfEmptyWords(false, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.RunningLength = 0;
}
final long predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfEmptyWords(false, tobediscarded);
} else {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to AND the dirty words
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
& j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
& j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
dischargeAsEmpty(rlwi, i, container);
if (rlwj != null)
dischargeAsEmpty(rlwj, j, container);
container.sizeinbits = Math.max(sizeInBits(), a.sizeInBits());
return container;
}
/**
* Return true if the two EWAHCompressedBitmap have both at least one
* true bit in the same position. Equivalently, you could call "and"
* and check whether there is a set bit, but intersects will run faster
* if you don't need the result of the "and" operation.
*
* @param a the other bitmap
* @return whether they intersect
*/
public boolean intersects(final EWAHCompressedBitmap a) {
final EWAHIterator i = a.getEWAHIterator();
final EWAHIterator j = getEWAHIterator();
if ((! i.hasNext()) || (! j.hasNext())) {
return false;
}
BufferedRunningLengthWord rlwi = new BufferedRunningLengthWord(i.next());
BufferedRunningLengthWord rlwj = new BufferedRunningLengthWord(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
if(predator.getRunningBit()) return true;
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
if(preyrl > tobediscarded) return true;
predator.discardFirstWords(preyrl);
prey.RunningLength = 0;
}
final long predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
} else {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
if(tobediscarded>0) return true;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
if( ( i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
& j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k] ) !=0)
return true;
else
if( ( i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
& j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k] ) != 0)
return true;
}
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
return false;
}
/**
* Returns a new compressed bitmap containing the bitwise AND NOT values of
* the current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap andNot(final EWAHCompressedBitmap a) {
final EWAHCompressedBitmap container = new EWAHCompressedBitmap();
container
.reserve(this.actualsizeinwords > a.actualsizeinwords ? this.actualsizeinwords
: a.actualsizeinwords);
final EWAHIterator i = a.getEWAHIterator();
final EWAHIterator j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.sizeinbits = sizeInBits();
return container;
}
// at this point, this is safe:
BufferedRunningLengthWord rlwi = new BufferedRunningLengthWord(i.next());
rlwi.setRunningBit(!rlwi.getRunningBit());
BufferedRunningLengthWord rlwj = new BufferedRunningLengthWord(j.next());
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
container.addStreamOfEmptyWords(false, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final int dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
if (i_is_prey)
container.addStreamOfDirtyWords(j.buffer(), dw_predator, preyrl
- tobediscarded);
else
container.addStreamOfNegatedDirtyWords(i.buffer(), dw_predator,
preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.RunningLength = 0;
}
final long predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfEmptyWords(false, tobediscarded);
} else {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final int dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
if (i_is_prey)
container.addStreamOfNegatedDirtyWords(i.buffer(), dw_prey,
tobediscarded);
else
container.addStreamOfDirtyWords(j.buffer(), dw_prey, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to AND the dirty words
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add((~i.buffer()[prey.dirtywordoffset + i.dirtyWords()
+ k])
& j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add((~i.buffer()[predator.dirtywordoffset
+ i.dirtyWords() + k])
& j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());
rlwi.setRunningBit(!rlwi.getRunningBit());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());
}
}
if (rlwi != null)
dischargeAsEmpty(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.sizeinbits = Math.max(sizeInBits(), a.sizeInBits());
return container;
}
/**
* Negate (bitwise) the current bitmap. To get a negated copy, do
* ((EWAHCompressedBitmap) mybitmap.clone()).not();
*
* The running time is proportional to the compressed size (as reported by
* sizeInBytes()).
*
*/
public void not() {
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
if(! i.hasNext()) return;
while (true) {
final RunningLengthWord rlw1 = i.next();
rlw1.setRunningBit(!rlw1.getRunningBit());
for (int j = 0; j < rlw1.getNumberOfLiteralWords(); ++j) {
i.buffer()[i.dirtyWords() + j] = ~i.buffer()[i.dirtyWords() + j];
}
if(!i.hasNext()) {// must potentially adjust the last dirty word
if(rlw1.getNumberOfLiteralWords()==0) return;
int usedbitsinlast = this.sizeinbits % wordinbits;
if(usedbitsinlast==0) return;
i.buffer()[i.dirtyWords() + rlw1.getNumberOfLiteralWords() - 1] &= ( (~0l) >>> (wordinbits - usedbitsinlast));
return;
}
}
}
/**
* Returns a new compressed bitmap containing the bitwise OR values of the
* current bitmap with some other bitmap.
*
* The running time is proportional to the sum of the compressed sizes (as
* reported by sizeInBytes()).
*
* @param a the other bitmap
* @return the EWAH compressed bitmap
*/
public EWAHCompressedBitmap or(final EWAHCompressedBitmap a) {
final EWAHCompressedBitmap container = new EWAHCompressedBitmap();
container.reserve(this.actualsizeinwords + a.actualsizeinwords);
final EWAHIterator i = a.getEWAHIterator();
final EWAHIterator j = getEWAHIterator();
if (!(i.hasNext() && j.hasNext())) {// this never happens...
container.sizeinbits = sizeInBits();
return container;
}
// at this point, this is safe:
BufferedRunningLengthWord rlwi = new BufferedRunningLengthWord(i.next());
BufferedRunningLengthWord rlwj = new BufferedRunningLengthWord(j.next());
// RunningLength;
while (true) {
final boolean i_is_prey = rlwi.size() < rlwj.size();
final BufferedRunningLengthWord prey = i_is_prey ? rlwi : rlwj;
final BufferedRunningLengthWord predator = i_is_prey ? rlwj : rlwi;
if (prey.getRunningBit() == false) {
final long predatorrl = predator.getRunningLength();
final long preyrl = prey.getRunningLength();
final long tobediscarded = (predatorrl >= preyrl) ? preyrl : predatorrl;
container
.addStreamOfEmptyWords(predator.getRunningBit(), tobediscarded);
final long dw_predator = predator.dirtywordoffset
+ (i_is_prey ? j.dirtyWords() : i.dirtyWords());
container.addStreamOfDirtyWords(i_is_prey ? j.buffer() : i.buffer(),
dw_predator, preyrl - tobediscarded);
predator.discardFirstWords(preyrl);
prey.discardFirstWords(preyrl);
prey.RunningLength = 0;
} else {
// we have a stream of 1x11
container.addStreamOfEmptyWords(true, prey.RunningLength);
predator.discardFirstWords(prey.RunningLength);
prey.RunningLength = 0;
}
long predatorrl = predator.getRunningLength();
if (predatorrl > 0) {
if (predator.getRunningBit() == false) {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
final long dw_prey = prey.dirtywordoffset
+ (i_is_prey ? i.dirtyWords() : j.dirtyWords());
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
container.addStreamOfDirtyWords(i_is_prey ? i.buffer() : j.buffer(),
dw_prey, tobediscarded);
} else {
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
final long tobediscarded = (predatorrl >= nbre_dirty_prey) ? nbre_dirty_prey
: predatorrl;
container.addStreamOfEmptyWords(true, tobediscarded);
predator.discardFirstWords(tobediscarded);
prey.discardFirstWords(tobediscarded);
}
}
// all that is left to do now is to OR the dirty words
final long nbre_dirty_prey = prey.getNumberOfLiteralWords();
if (nbre_dirty_prey > 0) {
for (int k = 0; k < nbre_dirty_prey; ++k) {
if (i_is_prey)
container.add(i.buffer()[prey.dirtywordoffset + i.dirtyWords() + k]
| j.buffer()[predator.dirtywordoffset + j.dirtyWords() + k]);
else
container.add(i.buffer()[predator.dirtywordoffset + i.dirtyWords()
+ k]
| j.buffer()[prey.dirtywordoffset + j.dirtyWords() + k]);
}
predator.discardFirstWords(nbre_dirty_prey);
}
if (i_is_prey) {
if (!i.hasNext()) {
rlwi = null;
break;
}
rlwi.reset(i.next());// = new
// BufferedRunningLengthWord(i.next());
} else {
if (!j.hasNext()) {
rlwj = null;
break;
}
rlwj.reset(j.next());// = new
// BufferedRunningLengthWord(
// j.next());
}
}
if (rlwi != null)
discharge(rlwi, i, container);
if (rlwj != null)
discharge(rlwj, j, container);
container.sizeinbits = Math.max(sizeInBits(), a.sizeInBits());
return container;
}
/**
* For internal use.
*
* @param initialWord the initial word
* @param iterator the iterator
* @param container the container
*/
private static void discharge(final BufferedRunningLengthWord initialWord,
final EWAHIterator iterator, final EWAHCompressedBitmap container) {
BufferedRunningLengthWord runningLengthWord = initialWord;
for (;;) {
final long runningLength = runningLengthWord.getRunningLength();
container.addStreamOfEmptyWords(runningLengthWord.getRunningBit(),
runningLength);
container.addStreamOfDirtyWords(iterator.buffer(), iterator.dirtyWords()
+ runningLengthWord.dirtywordoffset,
runningLengthWord.getNumberOfLiteralWords());
if (!iterator.hasNext())
break;
runningLengthWord = new BufferedRunningLengthWord(iterator.next());
}
}
/**
* For internal use.
*
* @param initialWord the initial word
* @param iterator the iterator
* @param container the container
*/
private static void dischargeAsEmpty(final BufferedRunningLengthWord initialWord,
final EWAHIterator iterator, final EWAHCompressedBitmap container) {
BufferedRunningLengthWord runningLengthWord = initialWord;
for (;;) {
final long runningLength = runningLengthWord.getRunningLength();
container.addStreamOfEmptyWords(false,
runningLength + runningLengthWord.getNumberOfLiteralWords());
if (!iterator.hasNext())
break;
runningLengthWord = new BufferedRunningLengthWord(iterator.next());
}
}
/**
* set the bit at position i to true, the bits must be set in increasing
* order. For example, set(15) and then set(7) will fail. You must do set(7)
* and then set(15).
*
* @param i the index
* @return true if the value was set (always true when i>= sizeInBits()).
*/
public boolean set(final int i) {
if (i < this.sizeinbits)
return false;
// must I complete a word?
if ((this.sizeinbits % 64) != 0) {
final int possiblesizeinbits = (this.sizeinbits / 64) * 64 + 64;
if (possiblesizeinbits < i + 1) {
this.sizeinbits = possiblesizeinbits;
}
}
addStreamOfEmptyWords(false, (i / 64) - this.sizeinbits / 64);
final int bittoflip = i - (this.sizeinbits / 64 * 64);
// next, we set the bit
if ((this.rlw.getNumberOfLiteralWords() == 0)
|| ((this.sizeinbits - 1) / 64 < i / 64)) {
final long newdata = 1l << bittoflip;
addLiteralWord(newdata);
} else {
this.buffer[this.actualsizeinwords - 1] |= 1l << bittoflip;
// check if we just completed a stream of 1s
if (this.buffer[this.actualsizeinwords - 1] == ~0l) {
// we remove the last dirty word
this.buffer[this.actualsizeinwords - 1] = 0;
--this.actualsizeinwords;
this.rlw
.setNumberOfLiteralWords(this.rlw.getNumberOfLiteralWords() - 1);
// next we add one clean word
addEmptyWord(true);
}
}
this.sizeinbits = i + 1;
return true;
}
/**
* Adding words directly to the bitmap (for expert use).
*
* This is normally how you add data to the array. So you add bits in streams
* of 8*8 bits.
*
* @param newdata the word
* @return the number of words added to the buffer
*/
public int add(final long newdata) {
return add(newdata, wordinbits);
}
/**
* For experts: You want to add many
* zeroes or ones? This is the method you use.
*
* @param v the boolean value
* @param number the number
* @return the number of words added to the buffer
*/
public int addStreamOfEmptyWords(final boolean v, final long number) {
if (number == 0)
return 0;
final boolean noliteralword = (this.rlw.getNumberOfLiteralWords() == 0);
final long runlen = this.rlw.getRunningLength();
if ((noliteralword) && (runlen == 0)) {
this.rlw.setRunningBit(v);
}
int wordsadded = 0;
if ((noliteralword) && (this.rlw.getRunningBit() == v)
&& (runlen < RunningLengthWord.largestrunninglengthcount)) {
long whatwecanadd = number < RunningLengthWord.largestrunninglengthcount
- runlen ? number : RunningLengthWord.largestrunninglengthcount
- runlen;
this.rlw.setRunningLength(runlen + whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
if (number - whatwecanadd > 0)
wordsadded += addStreamOfEmptyWords(v, number - whatwecanadd);
} else {
push_back(0);
++wordsadded;
this.rlw.position = this.actualsizeinwords - 1;
final long whatwecanadd = number < RunningLengthWord.largestrunninglengthcount ? number
: RunningLengthWord.largestrunninglengthcount;
this.rlw.setRunningBit(v);
this.rlw.setRunningLength(whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
if (number - whatwecanadd > 0)
wordsadded += addStreamOfEmptyWords(v, number - whatwecanadd);
}
return wordsadded;
}
/**
* Same as addStreamOfDirtyWords, but the words are negated.
*
* @param data the dirty words
* @param start the starting point in the array
* @param number the number of dirty words to add
* @return how many (compressed) words were added to the bitmap
*/
private long addStreamOfNegatedDirtyWords(final long[] data,
final long start, final long number) {
if (number == 0)
return 0;
final long NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords();
final long whatwecanadd = number < RunningLengthWord.largestliteralcount
- NumberOfLiteralWords ? number : RunningLengthWord.largestliteralcount
- NumberOfLiteralWords;
this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd);
final long leftovernumber = number - whatwecanadd;
negative_push_back(data, (int) start, (int) whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
long wordsadded = whatwecanadd;
if (leftovernumber > 0) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
++wordsadded;
wordsadded += addStreamOfDirtyWords(data, start + whatwecanadd,
leftovernumber);
}
return wordsadded;
}
/**
* if you have several dirty words to copy over, this might be faster.
*
*
* @param data the dirty words
* @param start the starting point in the array
* @param number the number of dirty words to add
* @return how many (compressed) words were added to the bitmap
*/
private long addStreamOfDirtyWords(final long[] data, final long start,
final long number) {
if (number == 0)
return 0;
final long NumberOfLiteralWords = this.rlw.getNumberOfLiteralWords();
final long whatwecanadd = number < RunningLengthWord.largestliteralcount
- NumberOfLiteralWords ? number : RunningLengthWord.largestliteralcount
- NumberOfLiteralWords;
this.rlw.setNumberOfLiteralWords(NumberOfLiteralWords + whatwecanadd);
final long leftovernumber = number - whatwecanadd;
push_back(data, (int) start, (int) whatwecanadd);
this.sizeinbits += whatwecanadd * wordinbits;
long wordsadded = whatwecanadd;
if (leftovernumber > 0) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
++wordsadded;
wordsadded += addStreamOfDirtyWords(data, start + whatwecanadd,
leftovernumber);
}
return wordsadded;
}
/**
* Adding words directly to the bitmap (for expert use).
*
* @param newdata the word
* @param bitsthatmatter the number of significant bits (by default it should be 64)
* @return the number of words added to the buffer
*/
public int add(final long newdata, final int bitsthatmatter) {
this.sizeinbits += bitsthatmatter;
if (newdata == 0) {
return addEmptyWord(false);
} else if (newdata == ~0l) {
return addEmptyWord(true);
} else {
return addLiteralWord(newdata);
}
}
/**
* Returns the size in bits of the *uncompressed* bitmap represented by this
* compressed bitmap. Initially, the sizeInBits is zero. It is extended
* automatically when you set bits to true.
*
* @return the size in bits
*/
public int sizeInBits() {
return this.sizeinbits;
}
/**
* Change the reported size in bits of the *uncompressed* bitmap represented
* by this compressed bitmap. It is not possible to reduce the sizeInBits, but
* it can be extended. The new bits are set to false or true depending on the
* value of defaultvalue.
*
* @param size the size in bits
* @param defaultvalue the default boolean value
* @return true if the update was possible
*/
public boolean setSizeInBits(final int size, final boolean defaultvalue) {
if (size < this.sizeinbits)
return false;
// next loop could be optimized further
if (defaultvalue)
while (((this.sizeinbits % 64) != 0) && (this.sizeinbits < size)) {
this.set(this.sizeinbits);
}
final int leftover = size % 64;
if (defaultvalue == false)
this.addStreamOfEmptyWords(defaultvalue, (size / 64) - this.sizeinbits
/ 64 + (leftover != 0 ? 1 : 0));
else {
this.addStreamOfEmptyWords(defaultvalue, (size / 64) - this.sizeinbits
/ 64);
final long newdata = (1l << leftover) + ((1l << leftover) - 1);
this.addLiteralWord(newdata);
}
this.sizeinbits = size;
return true;
}
/**
* Report the *compressed* size of the bitmap (equivalent to memory usage,
* after accounting for some overhead).
*
* @return the size in bytes
*/
public int sizeInBytes() {
return this.actualsizeinwords * 8;
}
/**
* For internal use (trading off memory for speed).
*
* @param size the number of words to allocate
* @return True if the operation was a success.
*/
private boolean reserve(final int size) {
if (size > this.buffer.length) {
final long oldbuffer[] = this.buffer;
this.buffer = new long[size];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
return true;
}
return false;
}
/**
* For internal use.
*
* @param data the word to be added
*/
private void push_back(final long data) {
if (this.actualsizeinwords == this.buffer.length) {
final long oldbuffer[] = this.buffer;
this.buffer = new long[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
this.buffer[this.actualsizeinwords++] = data;
}
/**
* For internal use.
*
* @param data the array of words to be added
* @param start the starting point
* @param number the number of words to add
*/
private void push_back(final long[] data, final int start, final int number) {
while (this.actualsizeinwords + number >= this.buffer.length) {
final long oldbuffer[] = this.buffer;
this.buffer = new long[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
System.arraycopy(data, start, this.buffer, this.actualsizeinwords, number);
this.actualsizeinwords += number;
}
/**
* For internal use.
*
* @param data the array of words to be added
* @param start the starting point
* @param number the number of words to add
*/
private void negative_push_back(final long[] data, final int start,
final int number) {
while (this.actualsizeinwords + number >= this.buffer.length) {
final long oldbuffer[] = this.buffer;
this.buffer = new long[oldbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.buffer, 0, oldbuffer.length);
this.rlw.array = this.buffer;
}
for (int k = 0; k < number; ++k)
this.buffer[this.actualsizeinwords + k] = ~data[start + k];
this.actualsizeinwords += number;
}
/**
* For internal use.
*
* @param v the boolean value
* @return the storage cost of the addition
*/
private int addEmptyWord(final boolean v) {
final boolean noliteralword = (this.rlw.getNumberOfLiteralWords() == 0);
final long runlen = this.rlw.getRunningLength();
if ((noliteralword) && (runlen == 0)) {
this.rlw.setRunningBit(v);
}
if ((noliteralword) && (this.rlw.getRunningBit() == v)
&& (runlen < RunningLengthWord.largestrunninglengthcount)) {
this.rlw.setRunningLength(runlen + 1);
return 0;
}
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
this.rlw.setRunningBit(v);
this.rlw.setRunningLength(1);
return 1;
}
/**
* For internal use.
*
* @param newdata the dirty word
* @return the storage cost of the addition
*/
private int addLiteralWord(final long newdata) {
final long numbersofar = this.rlw.getNumberOfLiteralWords();
if (numbersofar >= RunningLengthWord.largestliteralcount) {
push_back(0);
this.rlw.position = this.actualsizeinwords - 1;
this.rlw.setNumberOfLiteralWords(1);
push_back(newdata);
return 2;
}
this.rlw.setNumberOfLiteralWords(numbersofar + 1);
push_back(newdata);
return 1;
}
/**
* reports the number of bits set to true. Running time is proportional to
* compressed size (as reported by sizeInBytes).
*
* @return the number of bits set to true
*/
public int cardinality() {
int counter = 0;
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord localrlw = i.next();
if (localrlw.getRunningBit()) {
counter += wordinbits * localrlw.getRunningLength();
}
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
long data = i.buffer()[i.dirtyWords() + j];
for (int c = 0; c < wordinbits; ++c)
if ((data & (1l << c)) != 0)
++counter;
}
}
return counter;
}
/**
* A string describing the bitmap.
*
* @return the string
*/
@Override
public String toString() {
String ans = " EWAHCompressedBitmap, size in bits = " + this.sizeinbits
+ " size in words = " + this.actualsizeinwords + "\n";
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord localrlw = i.next();
if (localrlw.getRunningBit()) {
ans += localrlw.getRunningLength() + " 1x11\n";
} else {
ans += localrlw.getRunningLength() + " 0x00\n";
}
ans += localrlw.getNumberOfLiteralWords() + " dirties\n";
}
return ans;
}
/**
* A more detailed string describing the bitmap (useful for debugging).
*
* @return the string
*/
public String toDebugString() {
String ans = " EWAHCompressedBitmap, size in bits = " + this.sizeinbits
+ " size in words = " + this.actualsizeinwords + "\n";
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
while (i.hasNext()) {
RunningLengthWord localrlw = i.next();
if (localrlw.getRunningBit()) {
ans += localrlw.getRunningLength() + " 1x11\n";
} else {
ans += localrlw.getRunningLength() + " 0x00\n";
}
ans += localrlw.getNumberOfLiteralWords() + " dirties\n";
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
long data = i.buffer()[i.dirtyWords() + j];
ans += "\t" + data + "\n";
}
}
return ans;
}
/**
* Iterator over the set bits (this is what most people will want to use to
* browse the content). The location of the set bits is returned, in
* increasing order.
*
* @return the int iterator
*/
public IntIterator intIterator() {
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
return new IntIterator() {
int pos = 0;
RunningLengthWord localrlw = null;
final static int initcapacity = 512;
int[] localbuffer = new int[initcapacity];
int localbuffersize = 0;
int bufferpos = 0;
public boolean hasNext() {
while (this.localbuffersize == 0) {
if (!loadNextRLE())
return false;
loadBuffer();
}
return true;
}
private boolean loadNextRLE() {
while (i.hasNext()) {
this.localrlw = i.next();
return true;
}
return false;
}
private void add(final int val) {
++this.localbuffersize;
while (this.localbuffersize > this.localbuffer.length) {
int[] oldbuffer = this.localbuffer;
this.localbuffer = new int[this.localbuffer.length * 2];
System.arraycopy(oldbuffer, 0, this.localbuffer, 0, oldbuffer.length);
}
this.localbuffer[this.localbuffersize - 1] = val;
}
private void loadBuffer() {
this.bufferpos = 0;
this.localbuffersize = 0;
if (this.localrlw.getRunningBit()) {
for (int j = 0; j < this.localrlw.getRunningLength(); ++j) {
for (int c = 0; c < wordinbits; ++c) {
add(this.pos++);
}
}
} else {
this.pos += wordinbits * this.localrlw.getRunningLength();
}
for (int j = 0; j < this.localrlw.getNumberOfLiteralWords(); ++j) {
final long data = i.buffer()[i.dirtyWords() + j];
for (long c = 0; c < wordinbits; ++c) {
if (((1l << c) & data) != 0) {
add(this.pos);
}
++this.pos;
}
}
}
public int next() {
final int answer = this.localbuffer[this.bufferpos++];
if (this.localbuffersize == this.bufferpos) {
this.localbuffersize = 0;
}
return answer;
}
};
}
/**
* iterate over the positions of the true values.
* This is similar to intIterator(), but it uses
* Java generics.
*
* @return the iterator
*/
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
final private IntIterator under = intIterator();
public Integer next() {
return new Integer(this.under.next());
}
public boolean hasNext() {
return this.under.hasNext();
}
public void remove() {
throw new UnsupportedOperationException("bitsets do not support remove");
}
};
}
/**
* get the locations of the true values as one vector. (may use more memory
* than iterator())
*
* @return the positions
*/
public List<Integer> getPositions() {
final ArrayList<Integer> v = new ArrayList<Integer>();
final EWAHIterator i = new EWAHIterator(this.buffer, this.actualsizeinwords);
int pos = 0;
while (i.hasNext()) {
RunningLengthWord localrlw = i.next();
if (localrlw.getRunningBit()) {
for (int j = 0; j < localrlw.getRunningLength(); ++j) {
for (int c = 0; c < wordinbits; ++c)
v.add(new Integer(pos++));
}
} else {
pos += wordinbits * localrlw.getRunningLength();
}
for (int j = 0; j < localrlw.getNumberOfLiteralWords(); ++j) {
final long data = i.buffer()[i.dirtyWords() + j];
for (long c = 0; c < wordinbits; ++c) {
if (((1l << c) & data) != 0) {
v.add(new Integer(pos));
}
++pos;
}
}
}
while ((v.size() > 0)
&& (v.get(v.size() - 1).intValue() >= this.sizeinbits))
v.remove(v.size() - 1);
return v;
}
/**
* Check to see whether the two compressed bitmaps contain the same data.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o instanceof EWAHCompressedBitmap) {
EWAHCompressedBitmap other = (EWAHCompressedBitmap) o;
if( sizeinbits == other.sizeinbits
&& actualsizeinwords == other.actualsizeinwords
&& rlw.position == other.rlw.position) {
for(int k = 0; k<actualsizeinwords; ++k)
if(buffer[k]!= other.buffer[k])
return false;
return true;
}
}
return false;
}
/**
* Returns a customized hash code (based on Karp-Rabin).
* Naturally, if the bitmaps are equal, they will hash to the same value.
*
*/
@Override
public int hashCode() {
int karprabin = 0;
final int B = 31;
for(int k = 0; k<actualsizeinwords; ++k) {
karprabin += B*karprabin+(buffer[k]& ((1l<<32) - 1));
karprabin += B*karprabin+(buffer[k]>>> 32);
}
return sizeinbits ^ karprabin;
}
/*
* @see java.lang.Object#clone()
*/
@Override
public Object clone() throws java.lang.CloneNotSupportedException {
final EWAHCompressedBitmap clone = (EWAHCompressedBitmap) super.clone();
clone.buffer = this.buffer.clone();
clone.actualsizeinwords = this.actualsizeinwords;
clone.sizeinbits = this.sizeinbits;
return clone;
}
/*
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
public void readExternal(ObjectInput in) throws IOException {
deserialize(in);
}
/**
* Deserialize.
*
* @param in the DataInput stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public void deserialize(DataInput in) throws IOException {
this.sizeinbits = in.readInt();
this.actualsizeinwords = in.readInt();
int bufferSize = in.readInt();
if (this.buffer.length < bufferSize) {
this.buffer = new long[bufferSize];
}
for (int k = 0; k < this.actualsizeinwords; ++k)
this.buffer[k] = in.readLong();
this.rlw = new RunningLengthWord(this.buffer, in.readInt());
}
/*
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
public void writeExternal(ObjectOutput out) throws IOException {
serialize(out);
}
/**
* Serialize.
*
* @param out the DataOutput stream
* @throws IOException Signals that an I/O exception has occurred.
*/
public void serialize(DataOutput out) throws IOException {
out.writeInt(this.sizeinbits);
out.writeInt(this.actualsizeinwords);
out.writeInt(this.buffer.length);
for (int k = 0; k < this.actualsizeinwords; ++k)
out.writeLong(this.buffer[k]);
out.writeInt(this.rlw.position);
}
/**
* Clear any set bits and set size in bits back to 0
*/
public void clear() {
sizeinbits = 0;
actualsizeinwords = 1;
rlw.position = 0;
// buffer is not fully cleared but any new set operations should overwrite stale data
buffer[0] = 0;
}
/** The Constant defaultbuffersize: default memory allocation when the object is constructed. */
static final int defaultbuffersize = 4;
/** The buffer (array of 64-bit words) */
long buffer[] = null;
/** The actual size in words. */
int actualsizeinwords = 1;
/** sizeinbits: number of bits in the (uncompressed) bitmap. */
int sizeinbits = 0;
/** The current (last) running length word. */
RunningLengthWord rlw = null;
/** The Constant wordinbits represents the number of bits in a long. */
public static final int wordinbits = 64;
}
|
package model;
import javax.swing.JOptionPane;
import java.sql.*;
public class InvertedIndexOperations {
private PreparedStatement stAddTerm;
protected InvertedIndexOperations(Connection connection) throws SQLException{
stAddTerm = connection.prepareStatement("INSERT INTO SPATIA.INVERTEDINDEX(idDoc,term,tf) VALUES(?,?,?)");
}
/**
* Add a term to the database
* @param idDoc The id of the document containing the term
* @param term The term to be added
* @param tf The Term Frequency (TF) of the term in the document
*/
public void addTerm(int idDoc, String term, int tf){
try{
stAddTerm.clearParameters();
stAddTerm.setInt(1, idDoc);
stAddTerm.setString(2, term);
stAddTerm.setInt(3, tf);
stAddTerm.executeUpdate();
} catch(SQLException e){
//The insertion fails due to duplicate key
if(e.getErrorCode()==23505){
JOptionPane.showMessageDialog(null, "There is already the term \"" + term + "\" for document id: " + idDoc);
}
//The insertion fails due to foreign key constraint failure
else if(e.getErrorCode()==23506){
JOptionPane.showMessageDialog(null, "There is no document with id: " + idDoc);
}
//Unhandled error
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.toString(), "Error adding Term", JOptionPane.ERROR_MESSAGE);
}
}
}
|
package net.clgd.ccemux.init;
import static org.apache.commons.cli.Option.builder;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.SplashScreen;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Optional;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import dan200.computercraft.ComputerCraft;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import net.clgd.ccemux.OperatingSystem;
import net.clgd.ccemux.emulation.CCEmuX;
import net.clgd.ccemux.plugins.PluginManager;
import net.clgd.ccemux.rendering.RendererFactory;
import net.clgd.ccemux.rendering.TerminalFont;
@Slf4j
public class Launcher {
private static final Options opts = new Options();
// initialize cli options
static {
opts.addOption(builder("h").longOpt("help").desc("Shows this help information").build());
opts.addOption(builder("d").longOpt("data-dir")
.desc("Sets the data directory where plugins, configs, and other data are stored.").hasArg()
.argName("path").build());
opts.addOption(builder("r").longOpt("renderer")
.desc("Sets the renderer to use. Run without a value to list all available renderers.").hasArg()
.optionalArg(true).argName("renderer").build());
opts.addOption(builder().longOpt("plugin").desc(
"Used to load additional plugins not present in the default plugin directory. Value should be a path to a .jar file.")
.hasArg().argName("file").build());
}
private static void printHelp() {
new HelpFormatter().printHelp("ccemux [args]", opts);
}
public static void main(String args[]) {
if (System.getProperty("ccemux.forceDirectLaunch") != null) {
log.info("Skipping custom classloader, some features may be unavailable");
new Launcher(args).launch();
} else {
try (final CCEmuXClassloader loader = new CCEmuXClassloader(
((URLClassLoader) Launcher.class.getClassLoader()).getURLs())) {
@SuppressWarnings("unchecked")
final Class<Launcher> klass = (Class<Launcher>) loader.findClass(Launcher.class.getName());
final Constructor<Launcher> constructor = klass.getDeclaredConstructor(String[].class);
constructor.setAccessible(true);
final Method launch = klass.getDeclaredMethod("launch");
launch.setAccessible(true);
launch.invoke(constructor.newInstance(new Object[] { args }));
} catch (Exception e) {
log.warn("Failed to setup rewriting classloader - some features may be unavailable", e);
new Launcher(args).launch();
}
}
System.exit(0);
}
private final CommandLine cli;
private final Path dataDir;
private Launcher(String args[]) {
// parse cli options
CommandLine _cli = null;
try {
_cli = new DefaultParser().parse(opts, args);
} catch (org.apache.commons.cli.ParseException e) {
System.err.println(e.getLocalizedMessage());
printHelp();
System.exit(1);
}
cli = _cli;
if (cli.hasOption('h')) {
printHelp();
System.exit(0);
}
log.info("Starting CCEmuX");
log.debug("ClassLoader in use: {}", this.getClass().getClassLoader().getClass().getName());
// set data dir
if (cli.hasOption('d')) {
dataDir = Paths.get(cli.getOptionValue('d'));
} else {
dataDir = OperatingSystem.get().getAppDataDir().resolve("ccemux");
}
log.info("Data directory is {}", dataDir.toString());
}
private void crashMessage(Throwable e) {
CrashReport report = new CrashReport(e);
log.error("Unexpected exception occurred!", e);
log.error("CCEmuX has crashed!");
if (!GraphicsEnvironment.isHeadless()) {
JTextArea textArea = new JTextArea(12, 60);
textArea.setEditable(false);
textArea.setText(report.toString());
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setMaximumSize(new Dimension(600, 400));
int result = JOptionPane.showConfirmDialog(null,
new Object[] { "CCEmuX has crashed!", scrollPane,
"Would you like to create a bug report on GitHub?" },
"CCEmuX Crash", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
try {
report.createIssue();
} catch (URISyntaxException | IOException e1) {
log.error("Failed to open GitHub to create issue", e1);
}
}
}
}
private void setSystemLAF() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
log.warn("Failed to set system look and feel", e);
}
}
private Config loadConfig() {
log.debug("Loading config data");
Config cfg = Config.loadConfig(dataDir);
for (Field f : Config.class.getDeclaredFields()) {
try {
f.setAccessible(true);
if (!(Modifier.isTransient(f.getModifiers()) || Modifier.isStatic(f.getModifiers())))
log.trace(" {} -> {}", f.getName(), f.get(cfg));
} catch (Exception e) {}
}
log.info("Config loaded");
return cfg;
}
private PluginManager loadPlugins(Config cfg) throws ReflectiveOperationException {
if (!(getClass().getClassLoader() instanceof URLClassLoader)) {
throw new RuntimeException("Classloader in use is not a URLClassLoader");
}
URLClassLoader loader = (URLClassLoader) getClass().getClassLoader();
File pd = dataDir.resolve("plugins").toFile();
if (pd.isFile()) pd.delete();
if (!pd.exists()) pd.mkdirs();
HashSet<URL> urls = new HashSet<>();
for (File f : pd.listFiles()) {
if (f.isFile()) {
log.debug("Adding plugin source '{}'", f.getName());
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException e) {
log.warn("Failed to add plugin source", e);
}
}
}
if (cli.hasOption("plugin")) {
for (String s : cli.getOptionValues("plugin")) {
File f = Paths.get(s).toFile();
log.debug("Adding external plugin source '{}'", f.getName());
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException e) {
log.warn("Failed to add plugin source '{}'", f.getName());
}
}
}
Method m = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
m.setAccessible(true);
for (URL u : urls) {
m.invoke(loader, u);
}
return new PluginManager(loader, cfg);
}
private File getCCSource() throws URISyntaxException {
URI source = Optional.ofNullable(ComputerCraft.class.getProtectionDomain().getCodeSource())
.orElseThrow(() -> new IllegalStateException("Cannot locate CC")).getLocation().toURI();
log.debug("CC is loaded from {}", source);
if (!source.getScheme().equals("file"))
throw new IllegalStateException("Incompatible CC location: " + source.toString());
return new File(source);
}
private void launch() {
try {
setSystemLAF();
File dd = dataDir.toFile();
if (dd.isFile()) dd.delete();
if (!dd.exists()) dd.mkdirs();
Config cfg = loadConfig();
if (cfg.getTermScale() != (int) cfg.getTermScale())
log.warn("Terminal scale is not an integer - stuff might look bad! Don't blame us!");
PluginManager pluginMgr = loadPlugins(cfg);
pluginMgr.loadConfigs();
pluginMgr.loaderSetup(getClass().getClassLoader());
if (getClass().getClassLoader() instanceof CCEmuXClassloader) {
val loader = (CCEmuXClassloader) getClass().getClassLoader();
loader.chain.finalise();
log.warn("ClassLoader chain finalized");
loader.allowCC();
log.debug("CC access now allowed");
} else {
log.warn("Incompatible classloader type: {}", getClass().getClassLoader().getClass());
}
pluginMgr.setup();
if (cli.hasOption('r') && cli.getOptionValue('r') == null) {
log.info("Available rendering methods:");
RendererFactory.implementations.keySet().stream().forEach(k -> log.info(" {}", k));
System.exit(0);
} else if (cli.hasOption('r')) {
cfg.setRenderer(cli.getOptionValue('r'));
log.info("Overriding renderer ({} selected)", cfg.getRenderer());
}
if (!RendererFactory.implementations.containsKey(cfg.getRenderer())) {
log.error("Specified renderer '{}' does not exist - are you missing a plugin?", cfg.getRenderer());
if (!GraphicsEnvironment.isHeadless()) {
JOptionPane.showMessageDialog(null,
"Specified renderer '" + cfg.getRenderer() + "' does not exist.\n"
+ "Please double check your config file and plugin list.",
"Configuration Error", JOptionPane.ERROR_MESSAGE);
}
}
pluginMgr.onInitializationCompleted();
TerminalFont.loadImplicitFonts();
log.info("Setting up emulation environment");
if (!GraphicsEnvironment.isHeadless())
Optional.ofNullable(SplashScreen.getSplashScreen()).ifPresent(SplashScreen::close);
CCEmuX emu = new CCEmuX(cfg, pluginMgr, getCCSource());
emu.createComputer();
emu.run();
pluginMgr.onClosing(emu);
log.info("Emulation complete, goodbye!");
} catch (Throwable e) {
crashMessage(e);
}
}
}
|
package net.kerupani129.sjgl.map;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.tiled.Layer;
import org.newdawn.slick.tiled.TileSet;
import org.newdawn.slick.tiled.TiledMap;
import net.kerupani129.sjgl.SContainer;
import net.kerupani129.sjgl.SGame;
import net.kerupani129.sjgl.map.layer.TLayer;
import net.kerupani129.sjgl.map.layer.TLayerObject;
import net.kerupani129.sjgl.map.layer.TLayerTile;
import net.kerupani129.sjgl.map.object.TObject;
// TODO: ()
public class TMap extends TiledMap {
private float maxMapX = 0, maxMapY = 0;
private Rectangle viewport = new Rectangle(0, 0, 0, 0);
private List<TLayer> layerList = new ArrayList<TLayer>();
public final TMapManager manager;
/**
* TiledMap
*/
public TMap(TMapManager manager, String path, TObjectMap objectMap) throws SlickException {
super(path, getParent(path));
this.manager = manager;
@SuppressWarnings("unchecked")
ListIterator<Layer> i = this.layers.listIterator();
while (i.hasNext()) {
int index = i.nextIndex();
Layer layer = i.next();
String isObjectLayer = getLayerProperty(index, "type", "tile");
switch (isObjectLayer) {
case "image":
// TODO:
break;
case "object":
// case "event":
// case "item":
layerList.add(new TLayerObject(this, layer, objectMap));
break;
case "tile":
default:
layerList.add(new TLayerTile(this, layer));
break;
}
}
}
private static String getParent(String path) {
Path opath = Paths.get(path);
String parent = opath.getParent().toString();
parent = parent.replace('\\', '/');
return parent;
}
public void translateViewport(float x, float y) {
this.setViewportLocation(viewport.getX() + x, viewport.getY() + y);
}
public void setViewportSize(float viewportWidth, float viewportHeight) {
viewport.setSize(viewportWidth, viewportHeight);
maxMapX = this.getTileWidth() * this.getWidth() - viewport.getWidth();
maxMapY = this.getTileHeight() * this.getHeight() - viewport.getHeight();
if (maxMapX < 0) maxMapX = 0;
if (maxMapY < 0) maxMapY = 0;
}
public void setViewportLocation(float viewportX, float viewportY) {
if (viewportX < 0) viewportX = 0;
if (viewportY < 0) viewportY = 0;
if (viewportX > maxMapX) viewportX = maxMapX;
if (viewportY > maxMapY) viewportY = maxMapY;
viewport.setLocation(viewportX, viewportY);
}
public Rectangle getViewport() {
return new Rectangle(viewport.getX(), viewport.getY(), viewport.getWidth(), viewport.getHeight());
}
public void render(SContainer container, SGame game, Graphics g) throws SlickException {
g.translate(-viewport.getX(), -viewport.getY());
g.setWorldClip(viewport);
super.render(0, 0);
g.translate(viewport.getX(), viewport.getY());
g.clearWorldClip();
}
public void update(SContainer container, SGame game, int delta) throws SlickException {
for (TLayer layer : layerList) {
layer.update(container, game, delta);
}
}
public String getTilePropertyInTiles(int x, int y, int layerIndex, String propertyName, String def) {
String prop = def;
int id = getTileId(x, y, layerIndex);
if ( id != 0 ) {
prop = getTileProperty(id, propertyName, prop);
}
return prop;
}
public String getTilePropertyInTiles(int x, int y, String propertyName, String def) {
String prop = def;
for (int l = 0; l < getLayerCount(); l++) {
prop = getTilePropertyInTiles(x, y, l, propertyName, prop);
}
return prop;
}
public int getOrientation() {
return this.orientation;
}
@Override
public void renderIsometricMap(int x, int y, int sx, int sy, int width, int height, Layer layer,
boolean lineByLine) {
super.renderIsometricMap(x, y, sx, sy, tileWidth, height, layer, lineByLine);
}
@Override
public void render(int x, int y, int sx, int sy, int width, int height, int l, boolean lineByLine) {
TLayer layer = layerList.get(l);
layer.render(x, y, sx, sy, width, height, lineByLine);
}
@Override
public void render(int x, int y, int sx, int sy, int width, int height, boolean lineByLine) {
for (TLayer layer : layerList) {
layer.render(x, y, sx, sy, width, height, lineByLine);
}
}
public int getTileSetIndex(String name) {
for (int i = 0; i < this.tileSets.size(); ++i) {
TileSet tileset = (TileSet) this.tileSets.get(i);
if (tileset.name.equals(name)) {
return i;
}
}
return -1;
}
public TileSet getTileSet(String name) {
return (TileSet) this.tileSets.get(getTileSetIndex(name));
}
public List<TObject> getObjects() {
List<TObject> list = new ArrayList<TObject>();
for (TLayer layer : layerList) {
if (layer instanceof TLayerObject)
list.addAll(((TLayerObject) layer).getObjects());
}
return list;
}
public List<TObject> getObjects(String type) {
List<TObject> list = new ArrayList<TObject>();
for (TLayer layer : layerList) {
if (layer instanceof TLayerObject)
list.addAll(((TLayerObject) layer).getObjects(type));
}
return list;
}
public List<TObject> getPlayers() {
return getObjects(getMapProperty("player", null));
}
}
|
package org.cactoos.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Stream that copies input to output.
* <b>WARNING:</b>
* This class closes {@link TeeInputStream#output}
* after {@link TeeInputStream#close()}.
*
* <p>There is no thread-safety guarantee.
*
* @since 0.1
*/
public final class TeeInputStream extends InputStream {
/**
* Input.
*/
private final InputStream input;
/**
* Output.
*/
private final OutputStream output;
/**
* Ctor.
* @param src Source of data
* @param tgt Destination of data
*/
public TeeInputStream(final InputStream src, final OutputStream tgt) {
super();
this.input = src;
this.output = tgt;
}
@Override
public int read() throws IOException {
final int data = this.input.read();
if (data >= 0) {
this.output.write(data);
}
return data;
}
@Override
public int read(final byte[] buf) throws IOException {
return this.read(buf, 0, buf.length);
}
@Override
public int read(final byte[] buf, final int offset,
final int len) throws IOException {
final int max = this.input.read(buf, offset, len);
if (max > 0) {
this.output.write(buf, offset, max);
}
return max;
}
@Override
public long skip(final long num) throws IOException {
return this.input.skip(num);
}
@Override
public int available() throws IOException {
return this.input.available();
}
@Override
public void close() throws IOException {
this.input.close();
this.output.close();
}
@Override
public void mark(final int limit) {
this.input.mark(limit);
}
@Override
public void reset() throws IOException {
this.input.reset();
}
@Override
public boolean markSupported() {
return this.input.markSupported();
}
}
|
package org.jtrfp.trcl.gpu;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.media.opengl.GL3;
import org.jtrfp.trcl.ObjectListWindow;
import org.jtrfp.trcl.VerboseExecutorService;
import org.jtrfp.trcl.coll.CollectionActionDispatcher;
import org.jtrfp.trcl.coll.CollectionActionUnpacker;
import org.jtrfp.trcl.coll.CollectionThreadDecoupler;
import org.jtrfp.trcl.coll.DecoupledCollectionActionDispatcher;
import org.jtrfp.trcl.coll.ImplicitBiDiAdapter;
import org.jtrfp.trcl.coll.ListActionTelemetry;
import org.jtrfp.trcl.coll.PartitionedList;
import org.jtrfp.trcl.core.NotReadyException;
import org.jtrfp.trcl.core.TRFuture;
import org.jtrfp.trcl.core.ThreadManager;
import org.jtrfp.trcl.gui.Reporter;
import org.jtrfp.trcl.mem.IntArrayVariableList;
import org.jtrfp.trcl.mem.PagedByteBuffer;
import org.jtrfp.trcl.mem.VEC4Address;
import org.jtrfp.trcl.obj.PositionedRenderable;
import org.jtrfp.trcl.obj.WorldObject;
import org.jtrfp.trcl.pool.IndexList;
import com.ochafik.util.Adapter;
import com.ochafik.util.CollectionAdapter;
public class RenderList {
public static final int NUM_SUBPASSES = 4;
public static final int NUM_BLOCKS_PER_SUBPASS = 1024 * 4;
public static final int NUM_BLOCKS_PER_PASS = NUM_BLOCKS_PER_SUBPASS
* NUM_SUBPASSES;
public static final int NUM_RENDER_PASSES = 2;// Opaque + transparent //TODO: This is no longer the case
private int[] hostRenderListPageTable;
private int dummyBufferID;
private int numOpaqueBlocks,
numTransparentBlocks,
numUnoccludedTBlocks;
private final int renderListIdx;
private long rootBufferReadFinishedSync;
private final GPU gpu;
private final Renderer renderer;
private final RendererFactory rFactory;
private final ObjectListWindow objectListWindow;
private final ThreadManager threadManager;
private final Reporter reporter;
//private final ArrayList<WorldObject> nearbyWorldObjects = new ArrayList<WorldObject>();
private final IntBuffer previousViewport;
private final IntArrayVariableList renderList;
private final ListActionTelemetry<VEC4Address> renderListTelemetry
= new ListActionTelemetry<VEC4Address>();
public static final ExecutorService RENDER_LIST_EXECUTOR = new VerboseExecutorService(Executors.newSingleThreadExecutor());
//private final PartitionedIndexPool<VEC4Address>renderListPool;
/*private final PartitionedIndexPool.Partition<VEC4Address>
opaquePartition,
transparentPartition,
unoccludedTPartition;*/
private final IndexList<VEC4Address> opaqueIL, transIL, unoccludedIL;
private final DecoupledCollectionActionDispatcher<PositionedRenderable>
relevantPositionedRenderables = new DecoupledCollectionActionDispatcher<PositionedRenderable>(new HashSet<PositionedRenderable>(), RENDER_LIST_EXECUTOR);
private final PartitionedList<VEC4Address>
renderListPoolNEW = new PartitionedList<VEC4Address>(renderListTelemetry);
private final CollectionAdapter<CollectionActionDispatcher<VEC4Address>,PositionedRenderable>
opaqueODAddrsColl = new CollectionAdapter<CollectionActionDispatcher<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(new CollectionThreadDecoupler(opaqueIL = new IndexList<VEC4Address>(renderListPoolNEW.newSubList()),RENDER_LIST_EXECUTOR)),opaqueODAdapter),
transODAddrsColl = new CollectionAdapter<CollectionActionDispatcher<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(new CollectionThreadDecoupler(transIL = new IndexList<VEC4Address>(renderListPoolNEW.newSubList()),RENDER_LIST_EXECUTOR)),transODAdapter ),
unoccludedODAddrsColl= new CollectionAdapter<CollectionActionDispatcher<VEC4Address>,PositionedRenderable>(new CollectionActionUnpacker<VEC4Address>(new CollectionThreadDecoupler(unoccludedIL = new IndexList<VEC4Address>(renderListPoolNEW.newSubList()),RENDER_LIST_EXECUTOR)),unoccludedODAddrAdapter);
public RenderList(final GPU gpu, final Renderer renderer, final ObjectListWindow objectListWindow, ThreadManager threadManager, Reporter reporter) {
// Build VAO
final IntBuffer ib = IntBuffer.allocate(1);
this.reporter = reporter;
this.threadManager = threadManager;
this.gpu = gpu;
this.objectListWindow=objectListWindow;
this.renderer = renderer;
this.rFactory = renderer.getRendererFactory();
this.previousViewport =ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asIntBuffer();
this.renderListIdx =objectListWindow.create();
this.renderList = new IntArrayVariableList(objectListWindow.opaqueIDs,renderListIdx);
//this.renderListPool = new PartitionedIndexPoolImpl<VEC4Address>();
//this.opaquePartition = renderListPool.newPartition();
//this.transparentPartition = renderListPool.newPartition();
//this.unoccludedTPartition = renderListPool.newPartition();
//this.renderingIndices = new ListActionAdapter<PartitionedIndexPool.Entry<VEC4Address>,VEC4Address>(new PartitionedIndexPool.EntryAdapter<VEC4Address>(VEC4Address.ZERO));
//renderListPool.getFlatEntries().addTarget(renderingIndices, true);//Convert entries to Integers
//((ListActionDispatcher)renderingIndices.getOutput()).addTarget(renderListTelemetry, true);//Pipe Integers to renderList
relevantPositionedRenderables.addTarget(opaqueODAddrsColl, true);
relevantPositionedRenderables.addTarget(transODAddrsColl, true);
relevantPositionedRenderables.addTarget(unoccludedODAddrsColl, true);
final TRFuture<Void> task0 = gpu.submitToGL(new Callable<Void>(){
@Override
public Void call() throws Exception {
final GL3 gl = gpu.getGl();
gl.glGenBuffers(1, ib);
ib.clear();
dummyBufferID = ib.get();
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, dummyBufferID);
gl.glBufferData(GL3.GL_ARRAY_BUFFER, 1, null, GL3.GL_STATIC_DRAW);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 1, GL3.GL_BYTE, false, 0, 0);
gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0);
return null;
}
});//end task0
hostRenderListPageTable = new int[((ObjectListWindow.OBJECT_LIST_SIZE_BYTES_PER_PASS
* RenderList.NUM_RENDER_PASSES)
/ PagedByteBuffer.PAGE_SIZE_BYTES)*3];
task0.get();
}// end constructor
private void sendRenderListPageTable(){
//final Renderer renderer = tr.mainRenderer.get();
final int size = Math.min(objectListWindow.numPages(),hostRenderListPageTable.length);
//////// Workaround for AMD bug where element zero always returns zero in frag. Shift up one.
for (int i = 0; i < size-1; i++) {
hostRenderListPageTable[i+1] = objectListWindow.logicalPage2PhysicalPage(i);
}// end for(hostRenderListPageTable.length)
rFactory.getObjectProcessingStage().sendRenderListPageTable(hostRenderListPageTable);
//final GLProgram objectProgram = rFactory.getObjectProgram();
final GLProgram depthQueueProgram = rFactory.getDepthQueueProgram();
depthQueueProgram.use();
final GLProgram primaryProgram = rFactory.getOpaqueProgram();
primaryProgram.use();
final GLProgram vertexProgram = rFactory.getVertexProcessingStage().getVertexProgram();
vertexProgram.use();
vertexProgram.getUniform("renderListPageTable").setArrayui(hostRenderListPageTable);
gpu.defaultProgram();
sentPageTable=true;
}
private static int frameCounter = 0;
private void updateStatesToGPU() {
synchronized(threadManager.gameStateLock){
synchronized(relevantPositionedRenderables){
for (PositionedRenderable renderable:relevantPositionedRenderables)
try{renderable.updateStateToGPU(renderer);}
catch(NotReadyException e){}//Simply not ready
renderer.getCamera().getCompleteMatrixAsFlatArray(renderer.cameraMatrixAsFlatArray);//TODO
renderer.getCamera().getProjectionRotationMatrixAsFlatArray(renderer.camRotationProjectionMatrix);//TODO
}}
}//end updateStatesToGPU
private final CyclicBarrier renderListExecutorBarrier = new CyclicBarrier(2);
private void updateRenderListToGPU(){
if(renderListTelemetry.isModified()){
RENDER_LIST_EXECUTOR.execute(new Runnable(){
@Override
public void run() {
//Defragment
opaqueIL .defragment();
transIL .defragment();
unoccludedIL.defragment();
numOpaqueBlocks = opaqueIL .delegateSize();
numTransparentBlocks= transIL .delegateSize();
numUnoccludedTBlocks= unoccludedIL.delegateSize();
renderList.rewind();
renderListTelemetry.drainListStateTo(renderList);
try{renderListExecutorBarrier.await();}catch(Exception e){e.printStackTrace();}//TODO: Remove barrier, use go()
}});
try{renderListExecutorBarrier.await();}catch(Exception e){e.printStackTrace();}
}//end if(modified)
}//end updateRenderingListToGPU()
public void sendToGPU(GL3 gl) {
frameCounter++;
frameCounter %= 100;
updateStatesToGPU();
updateRenderListToGPU();
}//end sendToGPU
private boolean sentPageTable=false;
private void saveWindowViewportState(GL3 gl){
gl.glGetIntegerv(GL3.GL_VIEWPORT, previousViewport);
}
private void revertViewportToWindow(GL3 gl){
gl.glViewport(
previousViewport.get(0),
previousViewport.get(1),
previousViewport.get(2),
previousViewport.get(3));
}//end revertViewportToWindow()
public void render(final GL3 gl) throws NotReadyException {
if(!sentPageTable)sendRenderListPageTable();
final int renderListLogicalVec4Offset = ((objectListWindow.getObjectSizeInBytes()*renderListIdx)/16);
final int primsPerBlock = GPU.GPU_VERTICES_PER_BLOCK/3;
final int numPrimitives = (numTransparentBlocks+numOpaqueBlocks+numUnoccludedTBlocks)*primsPerBlock;
saveWindowViewportState(gl);
// OBJECT STAGE
rFactory.getObjectProcessingStage().process(gl,renderer.getCameraMatrixAsFlatArray(),
renderListLogicalVec4Offset, numTransparentBlocks, numOpaqueBlocks, numUnoccludedTBlocks);
//// VERTEX STAGE
VertexProcessingStage vps = rFactory.getVertexProcessingStage();
vps.process(gl, renderListLogicalVec4Offset, numPrimitives);
///// PRIMITIVE STAGE
//Almost like a geometry shader, except writing lookup textures for each primitive.
rFactory.getPrimitiveProgram().use();
rFactory.getPrimitiveFrameBuffer().bindToDraw();
vps.getVertexXYTexture().bindToTextureUnit(0, gl);
vps.getVertexWTexture().bindToTextureUnit(1, gl);
vps.getVertexZTexture().bindToTextureUnit(2, gl);
vps.getVertexUVTexture().bindToTextureUnit(3, gl);
vps.getVertexNormXYTexture().bindToTextureUnit(4, gl);
vps.getVertexNormZTexture().bindToTextureUnit(5, gl);
gl.glDisable(GL3.GL_PROGRAM_POINT_SIZE);//Asserts that point size is set only from CPU
gl.glPointSize(2*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING);//2x2 frags
gl.glViewport(0, 0,
RendererFactory.PRIMITIVE_BUFFER_WIDTH*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING,
RendererFactory.PRIMITIVE_BUFFER_HEIGHT*RendererFactory.PRIMITIVE_BUFFER_OVERSAMPLING);
gl.glDepthMask(false);
gl.glDisable(GL3.GL_BLEND);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_CULL_FACE);
//Everything
gl.glDrawArrays(GL3.GL_POINTS, 0, (numTransparentBlocks+numOpaqueBlocks+numUnoccludedTBlocks)*primsPerBlock);
//Cleanup
gl.glEnable(GL3.GL_PROGRAM_POINT_SIZE);
gl.glPointSize(1);
revertViewportToWindow(gl);
gl.glDepthMask(true);
// OPAQUE.DRAW STAGE
final GLProgram primaryProgram = rFactory.getOpaqueProgram();
primaryProgram.use();
vps.getVertexXYTexture().bindToTextureUnit(1, gl);
vps.getVertexUVTexture().bindToTextureUnit(2, gl);
vps.getVertexTextureIDTexture().bindToTextureUnit(3, gl);
vps.getVertexZTexture().bindToTextureUnit(4, gl);
vps.getVertexWTexture().bindToTextureUnit(5, gl);
vps.getVertexNormXYTexture().bindToTextureUnit(6, gl);
vps.getVertexNormZTexture().bindToTextureUnit(7, gl);
rFactory.getOpaqueFrameBuffer().bindToDraw();
final int numOpaqueVertices = numOpaqueBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
final int numTransparentVertices = numTransparentBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
final int numUnoccludedVertices = numUnoccludedTBlocks
* GPU.GPU_VERTICES_PER_BLOCK;
// Turn on depth write, turn off transparency
gl.glDisable(GL3.GL_BLEND);
gl.glDepthFunc(GL3.GL_LESS);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glEnable(GL3.GL_DEPTH_CLAMP);
//gl.glDepthRange((BriefingScreen.MAX_Z_DEPTH+1)/2, 1);
if(rFactory.isBackfaceCulling())gl.glEnable(GL3.GL_CULL_FACE);
if (frameCounter == 0) {
reporter.report(
"org.jtrfp.trcl.core."+renderer.getDebugName()+".RenderList.numOpaqueBlocks",
"" + opaqueIL.size());
reporter.report(
"org.jtrfp.trcl.core."+renderer.getDebugName()+".RenderList.numTransparentBlocks",
"" + transIL.size());
reporter.report(
"org.jtrfp.trcl.core."+renderer.getDebugName()+".RenderList.numUnoccludedTransparentBlocks",
"" + unoccludedIL.size());
reporter.report(
"org.jtrfp.trcl.core."+renderer.getDebugName()+".RenderList.approxNumSceneTriangles",
"" + ((opaqueIL.size()+transIL.size()+unoccludedIL.size())*GPU.GPU_VERTICES_PER_BLOCK)/3);
}
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, numOpaqueVertices);
// Cleanup
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// DEPTH QUEUE DRAW
// DRAW
final GLProgram depthQueueProgram = rFactory.getDepthQueueProgram();
depthQueueProgram.use();
rFactory.getDepthQueueFrameBuffer().bindToDraw();
gl.glDepthMask(false);
gl.glDisable(GL3.GL_CULL_FACE);
gl.glEnable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_DEPTH_CLAMP);
gl.glDepthRange(0, 1);
gl.glDepthFunc(GL3.GL_LEQUAL);
//Set up float shift queue blending
gl.glEnable(GL3.GL_BLEND);
gl.glBlendFunc(GL3.GL_ONE, GL3.GL_CONSTANT_COLOR);
gl.glBlendEquation(GL3.GL_FUNC_ADD);
gl.glBlendColor(4f, 4f, 4f, 4f);// upshift 2 bits
//object, root, depth, xy
rFactory.getOpaqueDepthTexture().bindToTextureUnit(1,gl);
vps.getVertexXYTexture().bindToTextureUnit(2, gl);
//renderer.getVertexUVTexture().bindToTextureUnit(3, gl);
vps.getVertexTextureIDTexture().bindToTextureUnit(4, gl);
vps.getVertexZTexture().bindToTextureUnit(5, gl);
vps.getVertexWTexture().bindToTextureUnit(6, gl);
vps.getVertexNormXYTexture().bindToTextureUnit(7, gl);
vps.getVertexNormZTexture().bindToTextureUnit(8, gl);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices, numTransparentVertices);
//UNOCCLUDED TRANSPARENT
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDrawArrays(GL3.GL_TRIANGLES, numOpaqueVertices+numTransparentVertices, numUnoccludedVertices);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
gpu.defaultProgram();
gpu.defaultFrameBuffers();
gpu.defaultTIU();
gpu.defaultTexture();
// DEFERRED STAGE
if(rFactory.isBackfaceCulling())gl.glDisable(GL3.GL_CULL_FACE);
final GLProgram deferredProgram = rFactory.getDeferredProgram();
deferredProgram.use();
gl.glDepthMask(false);
gl.glDisable(GL3.GL_DEPTH_TEST);
gl.glDisable(GL3.GL_BLEND);
final GLFrameBuffer renderTarget = renderer.getRenderingTarget();
if(renderTarget!=null)
renderTarget.bindToDraw();
else gpu.defaultFrameBuffers();
gpu.memoryManager.get().bindToUniform(0, deferredProgram,
deferredProgram.getUniform("rootBuffer"));
renderer.getSkyCube().getSkyCubeTexture().bindToTextureUnit(1,gl);
renderer.getRendererFactory().getPortalTexture().bindToTextureUnit(2,gl);
gpu.textureManager.get().vqCodebookManager.get().getESTuTvTexture().bindToTextureUnit(3,gl);
gpu.textureManager.get().vqCodebookManager.get().getRGBATexture().bindToTextureUnit(4,gl);
rFactory.getOpaquePrimitiveIDTexture().bindToTextureUnit(5,gl);
rFactory.getLayerAccumulatorTexture0().bindToTextureUnit(6,gl);
vps.getVertexTextureIDTexture ().bindToTextureUnit(7,gl);
rFactory.getPrimitiveUVZWTexture().bindToTextureUnit(8,gl);
rFactory.getPrimitiveNormTexture().bindToTextureUnit(9, gl);
rFactory.getLayerAccumulatorTexture1().bindToTextureUnit(10,gl);
deferredProgram.getUniform("bypassAlpha").setui(!renderer.getCamera().isFogEnabled()?1:0);
deferredProgram.getUniform("projectionRotationMatrix")
.set4x4Matrix(renderer.getCamRotationProjectionMatrix(), true);
//Execute the draw to a screen quad
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 36);
//Cleanup
gl.glDisable(GL3.GL_BLEND);
// DEPTH QUEUE ERASE
rFactory.getDepthQueueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_COLOR_BUFFER_BIT);
gpu.defaultFrameBuffers();
//Cleanup
gl.glDepthMask(true);
gpu.defaultProgram();
gpu.defaultTIU();
gpu.defaultFrameBuffers();
//INTERMEDIATE ERASE
rFactory.getOpaqueFrameBuffer().bindToDraw();
gl.glClear(GL3.GL_DEPTH_BUFFER_BIT|GL3.GL_COLOR_BUFFER_BIT);
}// end render()
public void reset() {
synchronized(relevantPositionedRenderables){
relevantPositionedRenderables.clear();
}//end sync(relevantObjects)
}//end reset()
public void repopulate(List<PositionedRenderable> renderables){
synchronized(relevantPositionedRenderables){
relevantPositionedRenderables.clear();
relevantPositionedRenderables.addAll(renderables);
}//end sync(relevantObjects)
}
public CollectionActionDispatcher<PositionedRenderable> getVisibleWorldObjectList(){
return relevantPositionedRenderables;
}
public int getAttribDummyID() {
return dummyBufferID;
}
static final Adapter<CollectionActionDispatcher<VEC4Address>, PositionedRenderable> opaqueODAdapter =
new ImplicitBiDiAdapter<CollectionActionDispatcher<VEC4Address>,PositionedRenderable>(null,new com.ochafik.util.listenable.Adapter<PositionedRenderable,CollectionActionDispatcher<VEC4Address>>(){
@Override
public CollectionActionDispatcher<VEC4Address> adapt(
PositionedRenderable value) {
if(value instanceof WorldObject && ((WorldObject)value).isImmuneToOpaqueDepthTest())
return new CollectionActionDispatcher<VEC4Address>(new HashSet<VEC4Address>());
else {return value.getOpaqueObjectDefinitionAddresses();}
}
});
static final Adapter<CollectionActionDispatcher<VEC4Address>, PositionedRenderable> transODAdapter =
new ImplicitBiDiAdapter<CollectionActionDispatcher<VEC4Address>, PositionedRenderable>(null,new com.ochafik.util.listenable.Adapter<PositionedRenderable,CollectionActionDispatcher<VEC4Address>>(){
@Override
public CollectionActionDispatcher<VEC4Address> adapt(
PositionedRenderable value) {
if(value instanceof WorldObject && ((WorldObject)value).isImmuneToOpaqueDepthTest())
return new CollectionActionDispatcher<VEC4Address>(new HashSet<VEC4Address>());
else {return value.getTransparentObjectDefinitionAddresses();}
}
});
static final Adapter<CollectionActionDispatcher<VEC4Address>, PositionedRenderable> unoccludedODAddrAdapter =
new ImplicitBiDiAdapter<CollectionActionDispatcher<VEC4Address>, PositionedRenderable>(null,new com.ochafik.util.listenable.Adapter<PositionedRenderable,CollectionActionDispatcher<VEC4Address>>(){
@Override
public CollectionActionDispatcher<VEC4Address> adapt(
PositionedRenderable value) {
final CollectionActionDispatcher<VEC4Address> result = new CollectionActionDispatcher<VEC4Address>(new HashSet<VEC4Address>());
if(value instanceof WorldObject && ((WorldObject)value).isImmuneToOpaqueDepthTest()){
value.getOpaqueObjectDefinitionAddresses().addTarget(result, true);
value.getTransparentObjectDefinitionAddresses().addTarget(result, true);
}//end if(unoccluded)
return result;
}
});
}// end RenderList
|
package org.lightmare.rest;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Resource;
import org.lightmare.cache.RestContainer;
import org.lightmare.rest.providers.JacksonFXmlFeature;
import org.lightmare.rest.providers.ObjectMapperProvider;
import org.lightmare.rest.providers.ResourceBuilder;
import org.lightmare.rest.providers.RestReloader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Dynamically manage REST resources, implementation of {@link ResourceConfig}
* class to add and remove {@link Resource}'s and reload at runtime
*
* @author levan
*
*/
public class RestConfig extends ResourceConfig {
// Collection of resources before registration
private Set<Resource> preResources;
// Reloader instance (implementation of ContainerLifecycleListener class)
private RestReloader reloader = RestReloader.get();
private static final Lock LOCK = new ReentrantLock();
public RestConfig(boolean changeCache) {
super();
RestConfig config = RestContainer.getRestConfig();
register(ObjectMapperProvider.class);
register(JacksonFXmlFeature.class);
LOCK.lock();
try {
if (reloader == null) {
reloader = new RestReloader();
}
this.registerInstances(reloader);
if (ObjectUtils.notNull(config)) {
// Adds resources to pre-resources from existing cached
// configuration
this.addPreResources(config);
Map<String, Object> properties = config.getProperties();
if (CollectionUtils.available(properties)) {
addProperties(properties);
}
}
if (changeCache) {
RestContainer.setRestConfig(this);
}
} finally {
LOCK.unlock();
}
}
public RestConfig() {
this(Boolean.TRUE);
}
public void cache() {
RestConfig config = RestContainer.getRestConfig();
if (ObjectUtils.notEquals(this, config)) {
RestContainer.setRestConfig(this);
}
}
private void clearResources() {
Set<Resource> resources = getResources();
if (CollectionUtils.available(resources)) {
getResources().clear();
}
}
/**
* Registers {@link Resource}s from passed {@link RestConfig} as
* {@link RestConfig#preResources} cache
*
* @param oldConfig
*/
public void registerAll(RestConfig oldConfig) {
clearResources();
Set<Resource> newResources;
newResources = new HashSet<Resource>();
if (ObjectUtils.notNull(oldConfig)) {
Set<Resource> olds = oldConfig.getResources();
if (CollectionUtils.available(olds)) {
newResources.addAll(olds);
}
}
registerResources(newResources);
}
public void addPreResource(Resource resource) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.add(resource);
}
public void addPreResources(Collection<Resource> preResources) {
if (CollectionUtils.available(preResources)) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.addAll(preResources);
}
}
public void addPreResources(RestConfig oldConfig) {
if (ObjectUtils.notNull(oldConfig)) {
addPreResources(oldConfig.getResources());
addPreResources(oldConfig.preResources);
}
}
private void removePreResource(Resource resource) {
if (ObjectUtils.available(this.preResources)) {
this.preResources.remove(resource);
}
}
/**
* Caches {@link Resource} created from passed {@link Class} for further
* registration
*
* @param resourceClass
* @param oldConfig
* @throws IOException
*/
public void registerClass(Class<?> resourceClass, RestConfig oldConfig)
throws IOException {
Resource.Builder builder = Resource.builder(resourceClass);
Resource preResource = builder.build();
Resource resource = ResourceBuilder.rebuildResource(preResource);
addPreResource(resource);
}
/**
* Removes {@link Resource} created from passed {@link Class} from
* pre-resources cache
*
* @param resourceClass
*/
public void unregister(Class<?> resourceClass) {
Resource resource = RestContainer.getResource(resourceClass);
removePreResource(resource);
}
public void registerPreResources() {
if (ObjectUtils.available(preResources)) {
RestContainer.putResources(preResources);
registerResources(preResources);
}
}
}
|
package org.minimalj.security;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.minimalj.frontend.Frontend;
import org.minimalj.transaction.PersistenceTransaction;
import org.minimalj.transaction.Role;
import org.minimalj.transaction.Transaction;
public class Subject implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Serializable token;
private final List<String> roles = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Serializable getToken() {
return token;
}
public void setToken(Serializable token) {
this.token = token;
}
public List<String> getRoles() {
return roles;
}
public boolean isValid() {
return token != null;
}
public static boolean hasRoleFor(Transaction<?> transaction) {
Role role = getRole(transaction);
boolean noRoleNeeded = role == null;
return noRoleNeeded || hasRole(role.value());
}
public static boolean hasRole(String... roleNames) {
Subject subject = getSubject();
if (subject != null) {
for (String roleName : roleNames) {
if (subject.roles.contains(roleName)) {
return true;
}
}
}
return false;
}
public static Role getRole(Transaction<?> transaction) {
boolean isPersistenceTransaction = transaction instanceof PersistenceTransaction;
if (isPersistenceTransaction) {
PersistenceTransaction<?> persistenceTransaction = (PersistenceTransaction<?>) transaction;
Role role = findRoleByType(transaction.getClass(), persistenceTransaction.getClass());
if (role == null) {
role = findRoleByType(persistenceTransaction.getEntityClazz(), persistenceTransaction.getClass());
}
return role;
} else {
return findRoleByType(transaction.getClass(), Transaction.class);
}
}
private static Role findRoleByType(Class<?> clazz, @SuppressWarnings("rawtypes") Class<? extends Transaction> transactionClass) {
Role[] roles = clazz.getAnnotationsByType(Role.class);
Role role = findRoleByType(roles, transactionClass);
if (role != null) {
return role;
}
roles = clazz.getPackage().getAnnotationsByType(Role.class);
role = findRoleByType(roles, transactionClass);
return role;
}
private static Role findRoleByType(Role[] roles, @SuppressWarnings("rawtypes") Class<? extends Transaction> transactionClass) {
for (Role role : roles) {
if (role.transaction() == transactionClass) {
return role;
}
}
// TODO respect class hierachy when retrieving needed role for a transaction
// the following lines only go by order of the roles not by the hierachy
// for (Role role : roles) {
// if (role.transactionClass().isAssignableFrom(transactionClass)) {
// return role;
// check for the Transaction.class as this is the default in the annotation
for (Role role : roles) {
if (role.transaction() == Transaction.class) {
return role;
}
}
return null;
}
public static Subject getSubject() {
if (Frontend.isAvailable()) {
return Frontend.getInstance().getSubject();
} else {
return Authorization.getInstance().getSubject();
}
}
}
|
package org.robolectric.res;
import java.util.LinkedHashMap;
import java.util.Map;
public class StyleData implements Style {
private final String packageName;
private final String name;
private final String parent;
private final Map<ResName, Attribute> items = new LinkedHashMap<ResName, Attribute>();
public StyleData(String packageName, String name, String parent) {
this.packageName = packageName;
this.name = name;
this.parent = parent;
}
public String getName() {
return name;
}
public String getParent() {
return parent;
}
public void add(ResName attrName, Attribute attribute) {
attrName.mustBe("attr");
items.put(attrName, attribute);
}
@Override public Attribute getAttrValue(ResName resName) {
resName.mustBe("attr");
Attribute attribute = items.get(resName);
// yuck. hack to work around library package remapping
if (attribute == null) {
attribute = items.get(resName.withPackageName(packageName));
if (attribute != null && (!"android".equals(attribute.contextPackageName))) {
attribute = new Attribute(resName, attribute.value, resName.packageName);
}
}
return attribute;
}
@Override public String toString() {
return "StyleData{" +
"name='" + name + '\'' +
", parent='" + parent + '\'' +
'}';
}
public String getPackageName() {
return packageName;
}
}
|
package org.scijava.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptException;
import org.scijava.Context;
import org.scijava.Contextual;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.NullContextException;
import org.scijava.command.Command;
import org.scijava.convert.ConvertService;
import org.scijava.log.LogService;
import org.scijava.module.AbstractModuleInfo;
import org.scijava.module.DefaultMutableModuleItem;
import org.scijava.module.ModuleException;
import org.scijava.plugin.Parameter;
import org.scijava.util.DigestUtils;
import org.scijava.util.FileUtils;
/**
* Metadata about a script.
* <p>
* This class is responsible for parsing the script for parameters. See
* {@link #parseParameters()} for details.
* </p>
*
* @author Curtis Rueden
* @author Johannes Schindelin
*/
public class ScriptInfo extends AbstractModuleInfo implements Contextual {
private static final int PARAM_CHAR_MAX = 640 * 1024; // should be enough ;-)
private final String path;
private final BufferedReader reader;
@Parameter
private Context context;
@Parameter
private LogService log;
@Parameter
private ScriptService scriptService;
@Parameter
private ConvertService conversionService;
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The SciJava application context to use when populating
* service inputs.
* @param file The script file.
*/
public ScriptInfo(final Context context, final File file) {
this(context, file.getPath());
}
/**
* Creates a script metadata object which describes the given script file.
*
* @param context The SciJava application context to use when populating
* service inputs.
* @param path Path to the script file.
*/
public ScriptInfo(final Context context, final String path) {
this(context, path, null);
}
/**
* Creates a script metadata object which describes a script provided by the
* given {@link Reader}.
*
* @param context The SciJava application context to use when populating
* service inputs.
* @param path Pseudo-path to the script file. This file does not actually
* need to exist, but rather provides a name for the script with file
* extension.
* @param reader Reader which provides the script itself (i.e., its contents).
*/
public ScriptInfo(final Context context, final String path,
final Reader reader)
{
setContext(context);
this.path = path;
this.reader =
reader == null ? null : new BufferedReader(reader, PARAM_CHAR_MAX);
}
// -- ScriptInfo methods --
/**
* Gets the path to the script on disk.
* <p>
* If the path doesn't actually exist on disk, then this is a pseudo-path
* merely for the purpose of naming the script with a file extension, and the
* actual script content is delivered by the {@link BufferedReader} given by
* {@link #getReader()}.
* </p>
*/
public String getPath() {
return path;
}
/**
* Gets the reader which delivers the script's content.
* <p>
* This might be null, in which case the content is stored in a file on disk
* given by {@link #getPath()}.
* </p>
*/
public BufferedReader getReader() {
return reader;
}
/**
* Parses the script's input and output parameters from the script header.
* <p>
* This method is called automatically the first time any parameter accessor
* method is called ({@link #getInput}, {@link #getOutput}, {@link #inputs()},
* {@link #outputs()}, etc.). Subsequent calls will reparse the parameters.
* <p>
* SciJava's scripting framework supports specifying @{@link Parameter}-style
* inputs and outputs in a preamble. The format is a simplified version of the
* Java @{@link Parameter} annotation syntax. The following syntaxes are
* supported:
* </p>
* <ul>
* <li>{@code // @<type> <varName>}</li>
* <li>{@code // @<type>(<attr1>=<value1>, ..., <attrN>=<valueN>) <varName>}</li>
* <li>{@code // @<IOType> <type> <varName>}</li>
* <li>
* {@code // @<IOType>(<attr1>=<value1>, ..., <attrN>=<valueN>) <type> <varName>}
* </li>
* </ul>
* <p>
* Where:
* </p>
* <ul>
* <li>{@code //} = the comment style of the scripting language, so that the
* parameter line is ignored by the script engine itself.</li>
* <li>{@code <IOType>} = one of {@code INPUT}, {@code OUTPUT}, or
* {@code BOTH}.</li>
* <li>{@code <varName>} = the name of the input or output variable.</li>
* <li>{@code <type>} = the Java {@link Class} of the variable.</li>
* <li>{@code <attr*>} = an attribute key.</li>
* <li>{@code <value*>} = an attribute value.</li>
* </ul>
* <p>
* See the @{@link Parameter} annotation for a list of valid attributes.
* </p>
* <p>
* Here are a few examples:
* </p>
* <ul>
* <li>{@code // @Dataset dataset}</li>
* <li>{@code // @double(type=OUTPUT) result}</li>
* <li>{@code // @BOTH ImageDisplay display}</li>
* <li>{@code // @INPUT(persist=false, visibility=INVISIBLE) boolean verbose}</li>
* parameters will be parsed and filled just like @{@link Parameter}
* -annotated fields in {@link Command}s.
* </ul>
*/
// NB: Widened visibility from AbstractModuleInfo.
@Override
public void parseParameters() {
clearParameters();
try {
final BufferedReader in;
if (reader == null) {
in = new BufferedReader(new FileReader(getPath()));
}
else {
in = reader;
in.mark(PARAM_CHAR_MAX);
}
while (true) {
final String line = in.readLine();
if (line == null) break;
// NB: Scan for lines containing an '@' with no prior alphameric
// characters. This assumes that only non-alphanumeric characters can
// be used as comment line markers.
if (line.matches("^[^\\w]*@.*")) {
final int at = line.indexOf('@');
parseParam(line.substring(at + 1));
}
else if (line.matches(".*\\w.*")) break;
}
if (reader == null) in.close();
else in.reset();
addReturnValue();
}
catch (final IOException exc) {
log.error("Error reading script: " + path, exc);
}
catch (final ScriptException exc) {
log.error("Invalid parameter syntax for script: " + path, exc);
}
}
// -- ModuleInfo methods --
@Override
public String getDelegateClassName() {
return ScriptModule.class.getName();
}
@Override
public Class<?> loadDelegateClass() {
return ScriptModule.class;
}
@Override
public ScriptModule createModule() throws ModuleException {
return new ScriptModule(this);
}
// -- Contextual methods --
@Override
public Context context() {
if (context == null) throw new NullContextException();
return context;
}
@Override
public Context getContext() {
return context;
}
@Override
public void setContext(final Context context) {
context.inject(this);
}
// -- Identifiable methods --
@Override
public String getIdentifier() {
return "script:" + path;
}
// -- Locatable methods --
@Override
public String getLocation() {
return new File(path).toURI().normalize().toString();
}
@Override
public String getVersion() {
final File file = new File(path);
if (!file.exists()) return null; // no version for non-existent script
final Date lastModified = FileUtils.getModifiedTime(file);
final String datestamp =
new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(lastModified);
try {
final String hash = DigestUtils.bestHex(FileUtils.readFile(file));
return datestamp + "-" + hash;
}
catch (final IOException exc) {
log.error(exc);
}
return datestamp;
}
// -- Helper methods --
private void parseParam(final String param) throws ScriptException {
final int lParen = param.indexOf("(");
final int rParen = param.lastIndexOf(")");
if (rParen < lParen) {
throw new ScriptException("Invalid parameter: " + param);
}
if (lParen < 0) parseParam(param, parseAttrs(""));
else {
final String cutParam =
param.substring(0, lParen) + param.substring(rParen + 1);
final String attrs = param.substring(lParen + 1, rParen);
parseParam(cutParam, parseAttrs(attrs));
}
}
private void parseParam(final String param,
final HashMap<String, String> attrs) throws ScriptException
{
final String[] tokens = param.trim().split("[ \t\n]+");
checkValid(tokens.length >= 1, param);
final String typeName, varName;
if (isIOType(tokens[0])) {
// assume syntax: <IOType> <type> <varName>
checkValid(tokens.length >= 3, param);
attrs.put("type", tokens[0]);
typeName = tokens[1];
varName = tokens[2];
}
else {
// assume syntax: <type> <varName>
checkValid(tokens.length >= 2, param);
typeName = tokens[0];
varName = tokens[1];
}
final Class<?> type = scriptService.lookupClass(typeName);
addItem(varName, type, attrs);
}
/** Parses a comma-delimited list of {@code key=value} pairs into a map. */
private HashMap<String, String> parseAttrs(final String attrs)
throws ScriptException
{
// TODO: We probably want to use a real CSV parser.
final HashMap<String, String> attrsMap = new HashMap<String, String>();
for (final String token : attrs.split(",")) {
if (token.isEmpty()) continue;
final int equals = token.indexOf("=");
if (equals < 0) throw new ScriptException("Invalid attribute: " + token);
final String key = token.substring(0, equals).trim();
String value = token.substring(equals + 1).trim();
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
attrsMap.put(key, value);
}
return attrsMap;
}
private boolean isIOType(final String token) {
return conversionService.convert(token, ItemIO.class) != null;
}
private void checkValid(final boolean valid, final String param)
throws ScriptException
{
if (!valid) throw new ScriptException("Invalid parameter: " + param);
}
/** Adds an output for the value returned by the script itself. */
private void addReturnValue() throws ScriptException {
final HashMap<String, String> attrs = new HashMap<String, String>();
attrs.put("type", "OUTPUT");
addItem(ScriptModule.RETURN_VALUE, Object.class, attrs);
}
private <T> void addItem(final String name, final Class<T> type,
final Map<String, String> attrs) throws ScriptException
{
final DefaultMutableModuleItem<T> item =
new DefaultMutableModuleItem<T>(this, name, type);
for (final String key : attrs.keySet()) {
final String value = attrs.get(key);
assignAttribute(item, key, value);
}
if (item.isInput()) registerInput(item);
if (item.isOutput()) registerOutput(item);
}
private <T> void assignAttribute(final DefaultMutableModuleItem<T> item,
final String key, final String value) throws ScriptException
{
// CTR: There must be an easier way to do this.
// Just compile the thing using javac? Or parse via javascript, maybe?
if ("callback".equalsIgnoreCase(key)) {
item.setCallback(value);
}
else if ("choices".equalsIgnoreCase(key)) {
// FIXME: Regex above won't handle {a,b,c} syntax.
// item.setChoices(choices);
}
else if ("columns".equalsIgnoreCase(key)) {
item.setColumnCount(conversionService.convert(value, int.class));
}
else if ("description".equalsIgnoreCase(key)) {
item.setDescription(value);
}
else if ("initializer".equalsIgnoreCase(key)) {
item.setInitializer(value);
}
else if ("type".equalsIgnoreCase(key)) {
item.setIOType(conversionService.convert(value, ItemIO.class));
}
else if ("label".equalsIgnoreCase(key)) {
item.setLabel(value);
}
else if ("max".equalsIgnoreCase(key)) {
item.setMaximumValue(conversionService.convert(value, item.getType()));
}
else if ("min".equalsIgnoreCase(key)) {
item.setMinimumValue(conversionService.convert(value, item.getType()));
}
else if ("name".equalsIgnoreCase(key)) {
item.setName(value);
}
else if ("persist".equalsIgnoreCase(key)) {
item.setPersisted(conversionService.convert(value, boolean.class));
}
else if ("persistKey".equalsIgnoreCase(key)) {
item.setPersistKey(value);
}
else if ("required".equalsIgnoreCase(key)) {
item.setRequired(conversionService.convert(value, boolean.class));
}
else if ("softMax".equalsIgnoreCase(key)) {
item.setSoftMaximum(conversionService.convert(value, item.getType()));
}
else if ("softMin".equalsIgnoreCase(key)) {
item.setSoftMinimum(conversionService.convert(value, item.getType()));
}
else if ("stepSize".equalsIgnoreCase(key)) {
// FIXME
item.setStepSize(conversionService.convert(value, Number.class));
}
else if ("style".equalsIgnoreCase(key)) {
item.setWidgetStyle(value);
}
else if ("visibility".equalsIgnoreCase(key)) {
item.setVisibility(conversionService.convert(value, ItemVisibility.class));
}
else if ("value".equalsIgnoreCase(key)) {
item.setWidgetStyle(value);
}
else {
throw new ScriptException("Invalid attribute name: " + key);
}
}
}
|
package org.sd.atn;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sd.io.FileUtil;
import org.sd.atn.ResourceManager;
import org.sd.token.Feature;
import org.sd.token.Normalizer;
import org.sd.token.Token;
import org.sd.token.TokenClassifierHelper;
import org.sd.util.Usage;
import org.sd.xml.DomElement;
import org.sd.xml.DomNamedNodeMap;
import org.sd.xml.DomNode;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Classifier that takes a list of terms in the defining xml or reads a flat
* file with terms.
* <p>
* Flat file names are specified under 'textfile caseSensitive="true|false"
* _keyFeature="..." classFeature="..."' nodes and have contents of the form:
* <p>
* term \t key=val \t key=val \t ...
* <p>
* Xml terms are specified under 'terms caseSensitive="true|false" nodes and
* have child nodes of the form 'term att=val ...' with each term's text.
* <p>
* The '_keyFeature' designates the feature name used in the file that should
* be changed to mirror the current classifier's name instead of that value
* used in the file. This is needed to avoid shadowing rules of the same
* name as the feature in the file, when the rote list is used in a classifier
* with a different name.
* <p>
* If classFeature is non-empty, then all terms will receive a feature with
* "class" as the the key and the classifer's name as the value.
*
* @author Spence Koehler
*/
@Usage(notes =
"This is an org.sd.atn.AbstractAtnStateTokenClassifier used as a Classifier\n" +
"within an org.sd.atn.AtnGrammar based on matching terms by dictionary or\n" +
"regular expression matching.\n" +
"\n" +
"Terms are loaded from in-line lists (terms), text files (textfile), or regular\n" +
"expressions (regexes). Stopword terms can also be specified and are applied\n" +
"before term matches. Supplements can mask base terms using stopwords and/or add\n" +
"terms to the classifier. Stopwords can also be triggered based on other classifier\n" +
"classifications. The XML format for specifying the terms is:\n" +
"\n" +
"<roteListType name='optionalName' caseSensitive='defaultCaseSensitivity' classFeature='...'>\n" +
" <jclass>org.sd.atn.RoteListClassifier</jclass>\n" +
" <terms caseSensitive='...' classFeature='...' ...collective term attributes...>\n" +
" <term ...single term attributes...>...</term>\n" +
" ...\n" +
" </terms>\n" +
" ...\n" +
" <textfile caseSensitive='...' classFeature='...' _keyFeature='...' ...collective term attributes...>\n" +
" ...\n" +
" <regexes ...> see RegexData\n" +
" <regex ...>...</regex>\n" +
" ...\n" +
" </regexes>\n" +
" ...\n" +
" <stopwords>\n" +
" <terms.../>\n" +
" ...\n" +
" <textfile.../>\n" +
" ...\n" +
" <regexes.../>\n" +
" ...\n" +
" <classifiers>\n" +
" <classifier>...</classifier>\n" +
" ...\n" +
" <feature name='...' type='interp|parse|string|classpath' when='exists|equals|matches-prev|matches-next'>text-to-equal|feature-name</feature>\n" +
" </classifiers>\n" +
" </stopwords>\n" +
"</roteListType>"
)
public class RoteListClassifier extends AbstractAtnStateTokenClassifier {
private static final Map<String, String> EMPTY_ATTRIBUTES = new HashMap<String, String>();
// <roteListType name='optionalName' caseSensitive='defaultCaseSensitivity' classFeature='...'>
// <jclass>org.sd.atn.RoteListClassifier</jclass>
// <terms caseSensitive='...' classFeature='...' pluralize='true|false' genitivize='true|false' ...collective term attributes...>
// <term ...single term attributes...>...</term>
// </terms>
// <textfile caseSensitive='...' classFeature='...' _keyFeature='...' pluralize='true|false' genitivize='true|false' ...collective term attributes...>
// <regexes ...> // see RegexData
// <regex ...>...</regex>
// </regexes>
// <stopwords>
// <terms.../>
// <textfile.../>
// <regexes.../>
// <classifiers>
// <classifier>...</classifier>
// <feature ...>...</feature>
// </classifiers>
// <predelim>...</predelim>
// <postdelim>...</postdelim>
// <test>...</test>
// </stopwords>
// </roteListType>
// ADDITIONAL NOTES:
// - if a term within a "case-insensitive" set of terms needs to be case-sensitive,
// - then add an attribute/value pair: _literal=<TERM> to the term, where <TERM>
// is the case-sensitive version of the term that must be matched.
private String roteListType;
private TermsWithStopwords termsAndStopwords;
private boolean defaultCaseSensitivity;
private String classFeature;
private ResourceManager resourceManager;
private boolean trace;
public RoteListClassifier(DomElement classifierIdElement, ResourceManager resourceManager, Map<String, Normalizer> id2Normalizer) {
super(classifierIdElement, id2Normalizer);
init(classifierIdElement, resourceManager);
}
/**
* Construct a simple instance with the given text file.
*/
public RoteListClassifier(File textfile, boolean caseSensitive) {
super();
this.resourceManager = new ResourceManager();
this.roteListType = textfile.getName();
this.termsAndStopwords = null;
this.defaultCaseSensitivity = caseSensitive;
this.classFeature = null;
this.trace = false;
if (textfile != null && textfile.exists()) {
this.termsAndStopwords = new TermsWithStopwords();
final TermsBundle termsBundle = new TermsBundle(false, super.getTokenClassifierHelper());
termsBundle.loadTextFile(textfile, caseSensitive);
this.termsAndStopwords.setTerms(termsBundle);
}
}
private final void init(DomElement classifierIdElement, ResourceManager resourceManager) {
this.resourceManager = resourceManager;
this.roteListType = classifierIdElement.getLocalName();
this.termsAndStopwords = null;
this.defaultCaseSensitivity = true;
this.classFeature = null;
doSupplement(classifierIdElement);
}
protected final void doSupplement(DomNode classifierIdElement) {
this.defaultCaseSensitivity = classifierIdElement.getAttributeBoolean("caseSensitive", this.defaultCaseSensitivity);
this.classFeature = classifierIdElement.getAttributeValue("classFeature", this.classFeature);
this.trace = classifierIdElement.getAttributeBoolean("trace", false);
this.termsAndStopwords = loadTermsAndStopwords(this.termsAndStopwords, classifierIdElement, false, getClassifiersNode(classifierIdElement));
}
/**
* Scan up the DOM tree to find the (shallowest) "classifiers" node.
*/
private final DomNode getClassifiersNode(DomNode refElement) {
DomNode result = null;
for (DomNode parentNode = (DomNode)refElement.getParentNode();
parentNode != null;
parentNode = (DomNode)parentNode.getParentNode()) {
final String nodeName = parentNode.getLocalName();
if ("classifiers".equals(nodeName)) {
result = parentNode;
//NOTE: don't break so we can find shallowest!
}
}
return result;
}
private final TermsWithStopwords loadTermsAndStopwords(TermsWithStopwords termsWithStopwords, DomNode classifierIdElement, boolean isStopwords, DomNode allClassifiersParentNode) {
TermsWithStopwords result = termsWithStopwords == null ? new TermsWithStopwords() : termsWithStopwords;
final boolean reset = classifierIdElement.getAttributeBoolean("reset", false);
if (reset) result.reset();
final boolean pluralize = classifierIdElement.getAttributeBoolean("pluralize", false);
if (pluralize) result.pluralize();
final boolean genitivize = classifierIdElement.getAttributeBoolean("genitivize", false);
if (genitivize) result.genitivize();
final NodeList childNodes = classifierIdElement.getChildNodes();
final int numChildNodes = childNodes.getLength();
for (int childNodeNum = 0; childNodeNum < numChildNodes; ++childNodeNum) {
final Node childNode = childNodes.item(childNodeNum);
if (childNode.getNodeType() != Node.ELEMENT_NODE) continue;
final DomElement childElement = (DomElement)childNode;
final String childNodeName = childNode.getLocalName();
if ("terms".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadTerms(result.getTerms(), childElement, isStopwords));
}
else if ("textfile".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadTextFile(result.getTerms(), childElement, isStopwords, classifierIdElement.getLocalName()));
}
else if ("regexes".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadRegexes(result.getTerms(), childElement, isStopwords));
}
else if ("classifiers".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadClassifiers(result.getTerms(), childElement, isStopwords, allClassifiersParentNode));
}
else if ("classifier".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadClassifier(result.getTerms(), childElement, isStopwords));
}
else if ("feature".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadFeature(result.getTerms(), childElement, isStopwords));
}
else if ("predelim".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadStepTest(result.getTerms(), childElement, isStopwords));
}
else if ("postdelim".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadStepTest(result.getTerms(), childElement, isStopwords));
}
else if ("test".equalsIgnoreCase(childNodeName)) {
result.setTerms(loadStepTest(result.getTerms(), childElement, isStopwords));
}
else if ("stopwords".equalsIgnoreCase(childNodeName)) {
result.setStopwords(loadTermsAndStopwords(result.getStopwords(), childElement, true, allClassifiersParentNode));
}
}
if (result.getTerms() != null) {
// adjust user-defined down to finite observed if warranted
final int maxWordCount = result.getTerms().getMaxWordCount();
final int curMaxWordCount = super.getMaxWordCount();
getTokenClassifierHelper().setMaxWordCount(adjustMaxWordCount(maxWordCount, curMaxWordCount));
}
return result;
}
public String getRoteListType() {
return roteListType;
}
public boolean isEmpty() {
return termsAndStopwords == null || termsAndStopwords.isEmpty();
}
/**
* Supplement this classifier with the given dom node.
*/
public void supplement(DomNode supplementNode) {
doSupplement(supplementNode);
}
/**
* Determine whether the token is a stopword.
*/
public boolean doClassifyStopword(Token token, AtnState atnState) {
return termsAndStopwords == null ? false : termsAndStopwords.doClassifyStopword(token, atnState);
}
/**
* Determine whether the text is a stopword.
*/
public Map<String, String> doClassifyStopword(String text) {
return termsAndStopwords == null ? null : termsAndStopwords.doClassifyStopword(text);
}
/**
* Determine whether the token is a term.
*/
public boolean doClassifyTerm(Token token, AtnState atnState) {
return termsAndStopwords == null ? false : termsAndStopwords.doClassifyTerm(token, atnState);
}
/**
* Determine whether the text is a term.
*/
public Map<String, String> doClassifyTerm(String text) {
return termsAndStopwords == null ? null : termsAndStopwords.doClassifyTerm(text);
}
/**
* Determine whether the token is a valid term, and not a stopword.
*/
public boolean doClassify(Token token, AtnState atnState) {
if (trace) {
System.out.println("RoteListClassifier(" + getName() + ").classify(" + token + "," + atnState + ")...");
}
final boolean result = termsAndStopwords.doClassify(token, atnState);
if (trace) {
System.out.println("\tRoteListClassifier(" + getName() + ").classify(" + token + ").result=" + result);
}
return result;
}
/**
* Determine whether the text is a valid term, and not a stopword.
*/
public Map<String, String> doClassify(String text) {
if (trace) {
System.out.println("RoteListClassifier(" + getName() + ").classify(" + text + ")...");
}
final Map<String, String> result = termsAndStopwords.doClassify(text);
if (trace) {
System.out.println("RoteListClassifier(" + getName() + ").classify(" + text + ").result=" + result);
}
return result;
}
protected boolean getDefaultCaseSensitivity() {
return defaultCaseSensitivity;
}
protected String getClassFeature() {
return classFeature;
}
protected TermsWithStopwords getTermsWithStopwords() {
return termsAndStopwords;
}
protected final TermsBundle loadTerms(TermsBundle termsBundle, DomElement termsElement, boolean isStopwords) {
if (termsElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadTerms(termsElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature);
return termsBundle;
}
protected final TermsBundle loadTextFile(TermsBundle termsBundle, DomElement textfileElement, boolean isStopwords, String classifierName) {
if (textfileElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadTextFile(textfileElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature, resourceManager, classifierName);
return termsBundle;
}
protected final TermsBundle loadRegexes(TermsBundle termsBundle, DomElement regexesElement, boolean isStopwords) {
if (regexesElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadRegexes(regexesElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature);
return termsBundle;
}
protected final TermsBundle loadClassifiers(TermsBundle termsBundle, DomElement classifiersElement, boolean isStopwords, DomNode classifiersParentNode) {
if (classifiersElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadClassifiers(classifiersElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature, resourceManager, classifiersParentNode);
return termsBundle;
}
protected final TermsBundle loadClassifier(TermsBundle termsBundle, DomElement classifierElement, boolean isStopwords) {
if (classifierElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadClassifier(classifierElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature, resourceManager);
return termsBundle;
}
protected final TermsBundle loadFeature(TermsBundle termsBundle, DomElement featureElement, boolean isStopwords) {
if (featureElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadFeature(featureElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature, resourceManager);
return termsBundle;
}
protected final TermsBundle loadStepTest(TermsBundle termsBundle, DomElement stepTestElement, boolean isStopwords) {
if (stepTestElement == null) return termsBundle;
if (termsBundle == null) termsBundle = new TermsBundle(isStopwords, super.getTokenClassifierHelper());
termsBundle.loadStepTest(stepTestElement, this.defaultCaseSensitivity, isStopwords ? null : this.classFeature, resourceManager);
return termsBundle;
}
public static final int adjustMaxWordCount(int localMaxWordCount, int globalMaxWordCount) {
int result = globalMaxWordCount;
if (localMaxWordCount > 0) {
// bring max down to finite observed if warranted
if (result == 0 || result > localMaxWordCount) {
result = localMaxWordCount;
}
}
return result;
}
/**
* Container for a set of case sensitive or case insensitive terms
* with attributes.
*/
protected static final class Terms {
private boolean caseSensitive;
private String classFeature;
private boolean isStopwords;
private int userDefinedMaxWordCount;
private int maxWordCount;
private Map<String, Map<String, String>> term2attributes;
private RegexDataContainer regexes;
private List<ClassifierContainer> classifiers;
private Map<String, FeatureContainer> features;
private StepTestContainer testContainer;
private boolean trace;
private TokenClassifierHelper tokenClassifierHelper;
private boolean hasOnlyTests;
private boolean pluralize;
private boolean genitivize;
public Terms(boolean caseSensitive, String classFeature, boolean isStopwords, int userDefinedMaxWordCount, TokenClassifierHelper tokenClassifierHelper) {
this.caseSensitive = caseSensitive;
this.classFeature = "".equals(classFeature) ? null : classFeature;
this.isStopwords = isStopwords;
this.userDefinedMaxWordCount = userDefinedMaxWordCount;
this.maxWordCount = 0;
this.term2attributes = new HashMap<String, Map<String, String>>();
this.regexes = null;
this.classifiers = null;
this.features = null;
this.testContainer = null;
this.trace = false;
this.tokenClassifierHelper = tokenClassifierHelper;
this.hasOnlyTests = true;
this.pluralize = false;
this.genitivize = false;
}
public void pluralize() {
this.pluralize = true;
}
public void genitivize() {
this.genitivize = true;
}
public void setMaxWordCount(int maxWordCount) {
this.maxWordCount = maxWordCount;
}
public int getMaxWordCount() {
// adjust user-defined down to finite observed if warranted
return adjustMaxWordCount(maxWordCount, userDefinedMaxWordCount);
}
void setTrace(boolean trace) {
this.trace = trace;
if (classifiers != null) {
for (ClassifierContainer classifier : classifiers) {
classifier.setTrace(trace);
}
}
}
public void reset() {
if (term2attributes != null) term2attributes.clear();
this.regexes = null;
this.classifiers = null;
this.features = null;
this.testContainer = null;
this.hasOnlyTests = true;
}
public boolean isEmpty() {
return
(term2attributes == null || term2attributes.size() == 0) &&
(this.regexes == null || this.regexes.size() == 0) &&
(this.classifiers == null || this.classifiers.size() == 0) &&
(this.features == null || this.features.size() == 0) &&
(this.testContainer == null || this.testContainer.isEmpty());
}
public Map<String, Map<String, String>> getTerm2Attributes() {
return term2attributes;
}
public RegexDataContainer getRegexes() {
return regexes;
}
public List<ClassifierContainer> getClassifiers() {
return classifiers;
}
public Map<String, FeatureContainer> getFeatures() {
return features;
}
public StepTestContainer getTestContainer() {
return testContainer;
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public String getClassFeature() {
return classFeature;
}
public boolean isStopwords() {
return isStopwords;
}
public boolean doClassify(Token token, AtnState atnState) {
boolean result = false;
boolean exceedsMaxWordCount = false;
if (maxWordCount > 0 && token.getWordCount() > maxWordCount) {
// local maxWordCount may be stricter than global
exceedsMaxWordCount = true;
}
boolean hasClassAttribute = false;
final String actualKey = tokenClassifierHelper.getNormalizedText(token);
String key = actualKey;
if (!exceedsMaxWordCount) {
if (!caseSensitive) {
key = key.toLowerCase();
}
if (term2attributes.containsKey(key)) {
result = true;
if (!caseSensitive) {
// check for override to case insensitivity ("_literal" attribute)
// note that "_literal" will not work with pluralize and genitivize flags
final Map<String, String> attributes = term2attributes.get(key);
if (attributes != null) {
final String literal = attributes.get("_literal");
if (literal != null && !"".equals(literal)) {
result = literal.equals(actualKey);
}
}
}
}
if (!result && pluralize) {
final String dkey = depluralize(key);
if (dkey != null && term2attributes.containsKey(dkey)) {
key = dkey;
result = true;
token.setFeature("pluralized", "true", this);
}
}
if (!result && genitivize) {
final String dkey = degenitivize(key);
if (dkey != null && term2attributes.containsKey(dkey)) {
key = dkey;
result = true;
token.setFeature("genitivized", "true", this);
}
}
if (result) {
if (trace) {
System.out.println("\tfound '" + key + "' in term2attributes");
}
// only add token attributes for non stopwords
if (!isStopwords) {
final Map<String, String> attributes = term2attributes.get(key);
if (attributes != null) {
hasClassAttribute = attributes.containsKey("class");
for (Map.Entry<String, String> kvPair : attributes.entrySet()) {
token.setFeature(kvPair.getKey(), kvPair.getValue(), this);
}
}
}
}
if (!result && regexes != null) {
if (regexes.matches(key, token, !isStopwords)) {
if (trace) {
System.out.println("\tfound '" + key + "' in regexData");
}
result = true;
}
}
if ((classifiers != null) && (!isStopwords || !result)) {
for (ClassifierContainer classifier : classifiers) {
final boolean curResult = classifier.doClassify(token, atnState);
if (curResult) {
if (trace) {
System.out.println("\tfound '" + key + "' in classifier '" + classifier.getName() + "'");
}
result = true;
// keep going to add features from further matches
}
}
}
if (!result && features != null) {
for (Map.Entry<String, FeatureContainer> featureEntry : features.entrySet()) {
final FeatureContainer featureContainer = featureEntry.getValue();
result = featureContainer.doClassify(token);
if (result) {
if (trace) {
final String feature = featureContainer.getFeatureName();
System.out.println("\tfound feature '" + feature +
"' (value=" + token.getFeatureValue(
featureContainer.getFeatureName(),
null,
featureContainer.getType()) +
") on token '" + token + "'");
}
break;
}
}
}
// NOTE: token tests (predelim/postdelim/test) are only applied to verify (or reverse) a match
if ((result || hasOnlyTests) && testContainer != null && !testContainer.isEmpty()) {
result = testContainer.verify(token, atnState).accept();
if (trace) {
System.out.println("\ttokenTests.verify(" + token + "," + atnState + ")=" + result);
}
}
if (result && classFeature != null && !hasClassAttribute) {
token.setFeature("class", classFeature, this);
}
if (trace && !result) {
System.out.println("\tdidn't find '" + key + "'");
}
}
return result;
}
public Map<String, String> doClassify(String text) {
Map<String, String> result = null;
String key = text;
if (!caseSensitive) {
key = key.toLowerCase();
}
boolean matched = false;
// go ahead and get attributes for both terms and stopwords
if (term2attributes.containsKey(key)) {
matched = true;
result = term2attributes.get(key);
}
if (!matched && pluralize) {
final String dkey = depluralize(key);
if (dkey != null && term2attributes.containsKey(dkey)) {
matched = true;
key = dkey;
result = new HashMap<String, String>(term2attributes.get(dkey));
result.put("pluralized", "true");
}
}
if (!matched && genitivize) {
final String dkey = degenitivize(key);
if (dkey != null && term2attributes.containsKey(dkey)) {
matched = true;
key = dkey;
result = new HashMap<String, String>(term2attributes.get(dkey));
result.put("genitivized", "true");
}
}
if (!matched && regexes != null) {
result = regexes.matches(key);
if (result != null) {
matched = true;
}
}
//NOTE: matching raw text against classifiers can fail
if ((classifiers != null) && (!isStopwords || !matched)) {
for (ClassifierContainer classifier : classifiers) {
final Map<String, String> curResult = classifier.doClassify(key);
if (curResult != null) {
if (result == null) result = new HashMap<String, String>();
result.putAll(curResult);
matched = true;
//keep going to add features from further matches
}
}
}
//NOTE: unable to match raw text against features
//NOTE: unable to match raw text against testContainer
//TODO: remove this (and related) text matching method by fixing infrastructure for free-text matching cases
if (matched && classFeature != null) {
boolean hasClassAttribute = false;
if (result != null) {
hasClassAttribute = result.containsKey("class");
}
if (!hasClassAttribute) {
if (result == null) result = new HashMap<String, String>();
result.put("class", classFeature);
}
}
if (matched && result == null) {
result = EMPTY_ATTRIBUTES;
}
return result;
}
private final String depluralize(String key) {
String result = null;
final int keylen = key.length();
if (keylen > 0) {
final char lastchar = key.charAt(keylen - 1);
if ((lastchar == 's' || lastchar == 'S') && keylen > 1) {
final char penultimatechar = key.charAt(keylen - 2);
if (penultimatechar != '\'') {
result = key.substring(0, keylen - 1);
}
}
}
return result;
}
private final String degenitivize(String key) {
String result = null;
final int keylen = key.length();
if (keylen > 2) {
final char lastchar = key.charAt(keylen - 1);
final char penultimatechar = key.charAt(keylen - 2);
if ((lastchar == 's' || lastchar == 'S') && (penultimatechar == '\'')) {
result = key.substring(0, keylen - 2);
}
}
return result;
}
protected final void loadTerms(DomElement termsElement) {
// get global attributes to apply to each term (ignoring 'caseSensitive', 'pluralize', 'genitivize' attributes)
Map<String, String> globalAttributes = null;
if (termsElement.hasAttributes()) {
final Map<String, String> termsElementAttributes = termsElement.getDomAttributes().getAttributes();
int minAttrCount = 1;
if (termsElementAttributes.containsKey("caseSensitive")) ++minAttrCount;
if (termsElementAttributes.containsKey("pluralize")) ++minAttrCount;
if (termsElementAttributes.containsKey("genitivize")) ++minAttrCount;
if (termsElementAttributes.size() >= minAttrCount) {
globalAttributes = new HashMap<String, String>(termsElementAttributes);
// ignore caseSensitive, pluralize, genitivize attributes
globalAttributes.remove("caseSensitive");
globalAttributes.remove("pluralize");
globalAttributes.remove("genitivize");
}
}
// load each "term" under "terms"
Map<String, String> termAttributes = null;
final NodeList termNodes = termsElement.selectNodes("term");
for (int i = 0; i < termNodes.getLength(); ++i) {
final Node curNode = termNodes.item(i);
if (curNode.getNodeType() != Node.ELEMENT_NODE) continue;
final DomElement termElement = (DomElement)curNode;
final String termText = termElement.getTextContent();
final String term = caseSensitive ? termText : termText.toLowerCase();
// only load attributes for non-stopwords
if (!isStopwords) {
if (termElement.hasAttributes()) {
final DomNamedNodeMap domNodeMap = termElement.getDomAttributes();
// apply global attributes, but don't clobber term-level overrides
if (globalAttributes != null) {
for (Map.Entry<String, String> entry : globalAttributes.entrySet()) {
if (!termAttributes.containsKey(entry.getKey())) {
domNodeMap.setAttribute(entry.getKey(), entry.getValue());
}
}
}
termAttributes = domNodeMap.getAttributes();
}
else if (globalAttributes != null) {
termAttributes = new HashMap<String, String>(globalAttributes);
}
else {
termAttributes = null;
}
}
addTermAttributes(term, termAttributes);
}
if (term2attributes != null && term2attributes.size() > 0) {
hasOnlyTests = false;
}
}
protected final void loadTextFile(DomElement textfileElement, ResourceManager resourceManager, String classifierName) {
final int minChars = textfileElement.getAttributeInt("minChars", 1);
final String keyFeature = textfileElement.getAttributeValue("_keyFeature", null);
final File textfile = resourceManager.getWorkingFile(textfileElement);
loadTextFile(textfile, minChars, keyFeature, classifierName);
if (term2attributes != null && term2attributes.size() > 0) {
hasOnlyTests = false;
}
}
protected final void loadTextFile(File textfile, int minChars, String keyFeature, String classifierName) {
try {
final BufferedReader reader = FileUtil.getReader(textfile);
String line = null;
while ((line = reader.readLine()) != null) {
if (!"".equals(line) && line.charAt(0) == '#') continue;
final String[] lineFields = line.trim().split("\t");
final String term = caseSensitive ? lineFields[0] : lineFields[0].toLowerCase();
if (term.length() >= minChars) {
Map<String, String> termAttributes = null;
if (lineFields.length > 1) {
termAttributes = new HashMap<String, String>();
for (int fieldNum = 1; fieldNum < lineFields.length; ++fieldNum) {
final String[] attVal = lineFields[fieldNum].split("=");
if (attVal.length == 2) {
String key = attVal[0];
final String value = attVal[1];
// change the keyFeature to match the classifier name
if (keyFeature != null && classifierName != null && keyFeature.equals(key)) {
key = classifierName;
}
termAttributes.put(key, value);
}
}
}
addTermAttributes(term, termAttributes);
}
}
reader.close();
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
protected final void loadRegexes(DomElement regexesElement) {
this.regexes = new RegexDataContainer(regexesElement);
if (regexes.size() > 0) {
hasOnlyTests = false;
}
}
protected final void loadClassifiers(DomElement classifiersElement, ResourceManager resourceManager, DomNode classifiersParentNode) {
final NodeList classifierNodes = classifiersElement.getChildNodes();
for (int i = 0; i < classifierNodes.getLength(); ++i) {
final Node curNode = classifierNodes.item(i);
if (curNode.getNodeType() != Node.ELEMENT_NODE) continue;
final String nodeName = curNode.getNodeName();
final String classifierName = curNode.getTextContent().trim();
if ("classifier".equals(nodeName)) {
loadClassifier((DomNode)curNode, resourceManager);
}
else if ("feature".equals(nodeName)) {
loadFeature((DomNode)curNode);
}
else if ("allNamedClassifiers".equals(nodeName)) {
// look at each classifiersParentNode child elts w/"name" attribute
final NodeList childNodes = classifiersParentNode.getChildNodes();
final int numChildNodes = childNodes.getLength();
for (int childNodeNum = 0; childNodeNum < numChildNodes; ++childNodeNum) {
final Node childNode = childNodes.item(childNodeNum);
if (childNode == classifiersElement ||
childNode.getNodeType() != Node.ELEMENT_NODE ||
!childNode.hasAttributes())
continue;
final DomElement childElement = (DomElement)childNode;
final boolean verbose = childElement.getAttributeBoolean("verbose", false);
final boolean trace = childElement.getAttributeBoolean("trace", verbose);
final String cName = childElement.getAttributeValue("name", null);
retrieveClassifier(cName, resourceManager, trace);
}
}
else {
if (GlobalConfig.verboseLoad()) {
System.out.println(new Date() + ": WARNING : Unrecognized 'classifiers' sub-element '" +
nodeName + "'. Expecting 'classifier' or 'feature'.");
}
}
}
}
protected final void loadClassifier(DomNode classifierElement, ResourceManager resourceManager) {
String classifierName = classifierElement.hasAttributes() ? classifierElement.getAttributeValue("cat", null) : null;
if (classifierName == null) {
classifierName = classifierElement.getTextContent().trim();
}
final boolean verbose = classifierElement.getAttributeBoolean("verbose", false);
final boolean trace = classifierElement.getAttributeBoolean("trace", verbose);
retrieveClassifier(classifierName, resourceManager, trace);
if (classifiers != null && classifiers.size() > 0) {
hasOnlyTests = false;
}
}
private final void retrieveClassifier(String classifierName, ResourceManager resourceManager, boolean trace) {
if (this.classifiers == null) this.classifiers = new ArrayList<ClassifierContainer>();
final ClassifierContainer classifier = new ClassifierContainer(classifierName, resourceManager);
if (trace) classifier.setTrace(trace);
this.classifiers.add(classifier);
}
protected final void loadFeature(DomNode featureElement) {
final FeatureContainer featureContainer = new FeatureContainer(featureElement);
final String featureKey = featureContainer.getFeatureKey();
if (featureKey != null) {
if (this.features == null) this.features = new HashMap<String, FeatureContainer>();
this.features.put(featureKey, featureContainer);
}
if (features != null && features.size() > 0) {
hasOnlyTests = false;
}
}
protected final void loadStepTest(DomElement stepTestElement, ResourceManager resourceManager) {
if (testContainer == null) testContainer = new StepTestContainer();
final StepTestWrapper testWrapper = new StepTestWrapper(stepTestElement, resourceManager);
testContainer.addTestWrapper(testWrapper);
}
private final void addTermAttributes(String term, Map<String, String> attributes) {
Map<String, String> curAttributes = term2attributes.get(term);
if (curAttributes == null) {
term2attributes.put(term, attributes);
}
else {
if (attributes != null) {
curAttributes.putAll(attributes);
}
}
// update max word count
final int curWordCount = computeWordCount(term);
if (curWordCount > maxWordCount) {
maxWordCount = curWordCount;
}
}
private final int computeWordCount(String term) {
//NOTE: we don't have a tokenizer to use for this here, so we're just counting spaces.
int result = 1;
for (int spos = term.indexOf(' '); spos >= 0; spos = term.indexOf(' ', spos + 1)) {
++result;
}
return result;
}
}
/**
* Container for bundling case sensitive and insensitive terms.
*/
protected static final class TermsBundle {
private boolean isStopwords;
private Terms caseSensitiveTerms;
private Terms caseInsensitiveTerms;
private int maxWordCount;
private TokenClassifierHelper tokenClassifierHelper;
private boolean pluralize;
private boolean genitivize;
public TermsBundle(boolean isStopwords, TokenClassifierHelper tokenClassifierHelper) {
this.isStopwords = isStopwords;
this.caseSensitiveTerms = null;
this.caseInsensitiveTerms = null;
this.maxWordCount = 0;
this.tokenClassifierHelper = tokenClassifierHelper;
this.pluralize = false;
this.genitivize = false;
}
void setTrace(boolean trace) {
if (caseSensitiveTerms != null) caseSensitiveTerms.setTrace(trace);
if (caseInsensitiveTerms != null) caseInsensitiveTerms.setTrace(trace);
}
public void pluralize() {
this.pluralize = true;
if (caseSensitiveTerms != null) caseSensitiveTerms.pluralize();
if (caseInsensitiveTerms != null) caseInsensitiveTerms.pluralize();
}
public void genitivize() {
this.genitivize = true;
if (caseSensitiveTerms != null) caseSensitiveTerms.genitivize();
if (caseInsensitiveTerms != null) caseInsensitiveTerms.genitivize();
}
public int getMaxWordCount() {
return maxWordCount;
}
public void reset() {
if (caseSensitiveTerms != null) caseSensitiveTerms.reset();
if (caseInsensitiveTerms != null) caseInsensitiveTerms.reset();
}
public boolean isStopwords() {
return isStopwords;
}
public Terms getCaseSensitiveTerms() {
return caseSensitiveTerms;
}
public Terms getCaseInsensitiveTerms() {
return caseInsensitiveTerms;
}
public boolean isEmpty() {
return
(caseSensitiveTerms == null || caseSensitiveTerms.isEmpty()) &&
(caseInsensitiveTerms == null || caseInsensitiveTerms.isEmpty());
}
public boolean doClassify(Token token, AtnState atnState) {
boolean result = false;
if (caseSensitiveTerms != null) {
result = caseSensitiveTerms.doClassify(token, atnState);
}
if ((caseInsensitiveTerms != null) && (!isStopwords || !result)) {
// even if prior result succeeded, try again here to get any new token features (unless stopwords)
result |= caseInsensitiveTerms.doClassify(token, atnState);
}
return result;
}
public Map<String, String> doClassify(String text) {
Map<String, String> result = null;
if (caseSensitiveTerms != null) {
result = caseSensitiveTerms.doClassify(text);
}
if ((caseInsensitiveTerms != null) && (!isStopwords || result == null)) {
// even if prior result succeeded, try again here to get any new token features (unless stopwords)
final Map<String, String> ciResult = caseInsensitiveTerms.doClassify(text);
if (result == null) {
result = ciResult;
}
else {
if (ciResult != null) {
result.putAll(ciResult);
}
}
}
return result;
}
protected final void loadTerms(DomElement termsElement, boolean defaultCaseSensitivity, String classFeature) {
final Terms theTerms = getTheTerms(termsElement, defaultCaseSensitivity, classFeature);
theTerms.loadTerms(termsElement);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadTextFile(DomElement textfileElement, boolean defaultCaseSensitivity, String classFeature, ResourceManager resourceManager, String classifierName) {
final Terms theTerms = getTheTerms(textfileElement, defaultCaseSensitivity, classFeature);
theTerms.loadTextFile(textfileElement, resourceManager, classifierName);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadTextFile(File textfile, boolean caseSensitive) {
Terms theTerms = null;
if (caseSensitive) {
if (this.caseSensitiveTerms == null) this.caseSensitiveTerms = new Terms(true, null, false, 0, tokenClassifierHelper);
theTerms = this.caseSensitiveTerms;
}
else {
if (this.caseInsensitiveTerms == null) this.caseInsensitiveTerms = new Terms(false, null, false, 0, tokenClassifierHelper);
theTerms = this.caseInsensitiveTerms;
}
theTerms.loadTextFile(textfile, 1, null, null);
}
protected final void loadRegexes(DomElement regexesElement, boolean defaultCaseSensitivity, String classFeature) {
final Terms theTerms = getTheTerms(regexesElement, defaultCaseSensitivity, classFeature);
theTerms.loadRegexes(regexesElement);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadClassifiers(DomElement classifiersElement, boolean defaultCaseSensitivity, String classFeature, ResourceManager resourceManager, DomNode classifiersParentNode) {
final Terms theTerms = getTheTerms(classifiersElement, defaultCaseSensitivity, classFeature);
theTerms.loadClassifiers(classifiersElement, resourceManager, classifiersParentNode);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadClassifier(DomElement classifierElement, boolean defaultCaseSensitivity, String classFeature, ResourceManager resourceManager) {
final Terms theTerms = getTheTerms(classifierElement, defaultCaseSensitivity, classFeature);
theTerms.loadClassifier(classifierElement, resourceManager);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadFeature(DomElement featureElement, boolean defaultCaseSensitivity, String classFeature, ResourceManager resourceManager) {
final Terms theTerms = getTheTerms(featureElement, defaultCaseSensitivity, classFeature);
theTerms.loadFeature(featureElement);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
protected final void loadStepTest(DomElement stepTestElement, boolean defaultCaseSensitivity, String classFeature, ResourceManager resourceManager) {
final Terms theTerms = getTheTerms(stepTestElement, defaultCaseSensitivity, classFeature);
theTerms.loadStepTest(stepTestElement, resourceManager);
adjustMaxWordCount(theTerms.getMaxWordCount());
}
private final void adjustMaxWordCount(int termsMaxWordCount) {
// for a bundle, we want to preserve the "largest" maxWordCount
if (termsMaxWordCount > 0 && termsMaxWordCount > this.maxWordCount) {
this.maxWordCount = termsMaxWordCount;
}
}
/** Get the correct (case -sensitive or -insensitive) terms */
private final Terms getTheTerms(DomElement theElement, boolean defaultCaseSensitivity, String defaultClassFeature) {
Terms theTerms = null;
final boolean caseSensitive = theElement.getAttributeBoolean("caseSensitive", defaultCaseSensitivity);
final String classFeature = theElement.getAttributeValue("classFeature", defaultClassFeature);
final int maxWordCount = theElement.getAttributeInt("maxWordCount", 0);
// Get a handle on theTerms based on case sensitivity
if (caseSensitive) {
if (this.caseSensitiveTerms == null) this.caseSensitiveTerms = new Terms(true, classFeature, isStopwords, maxWordCount, tokenClassifierHelper);
theTerms = this.caseSensitiveTerms;
}
else {
if (this.caseInsensitiveTerms == null) this.caseInsensitiveTerms = new Terms(false, classFeature, isStopwords, maxWordCount, tokenClassifierHelper);
theTerms = this.caseInsensitiveTerms;
}
if (pluralize) {
theTerms.pluralize();
}
else {
this.pluralize = theElement.getAttributeBoolean("pluralize", false);
if (pluralize) theTerms.pluralize();
}
if (genitivize) {
theTerms.genitivize();
}
else {
this.genitivize = theElement.getAttributeBoolean("genitivize", false);
if (genitivize) theTerms.genitivize();
}
return theTerms;
}
}
protected static final class TermsWithStopwords {
private TermsBundle terms;
private TermsWithStopwords stopwords;
private boolean pluralize;
private boolean genitivize;
public TermsWithStopwords() {
this.terms = null;
this.stopwords = null;
this.pluralize = false;
this.genitivize = false;
}
public void reset() {
if (terms != null) terms.reset();
if (stopwords != null) stopwords.reset();
}
public void pluralize() {
this.pluralize = true;
if (terms != null) terms.pluralize();
if (stopwords != null) stopwords.pluralize();
}
public void genitivize() {
this.genitivize = true;
if (terms != null) terms.genitivize();
if (stopwords != null) stopwords.genitivize();
}
public void setTrace(boolean trace) {
if (terms != null) {
terms.setTrace(trace);
}
if (stopwords != null) {
stopwords.setTrace(trace);
}
}
public TermsBundle getTerms() {
return terms;
}
public void setTerms(TermsBundle terms) {
this.terms = terms;
if (pluralize && terms != null) {
terms.pluralize();
}
if (genitivize && terms != null) {
terms.genitivize();
}
}
public TermsWithStopwords getStopwords() {
return stopwords;
}
public void setStopwords(TermsWithStopwords stopwords) {
this.stopwords = stopwords;
if (pluralize && stopwords != null) {
stopwords.pluralize();
}
if (genitivize && stopwords != null) {
stopwords.genitivize();
}
}
public boolean hasStopwords() {
return stopwords != null && !stopwords.isEmpty();
}
public boolean isEmpty() {
return (terms == null || terms.isEmpty()) && (stopwords == null || stopwords.isEmpty());
}
public boolean doClassify(Token token, AtnState atnState) {
boolean result = false;
if ((stopwords == null || (stopwords != null && !stopwords.doClassify(token, atnState))) &&
(terms != null)) {
result = terms.doClassify(token, atnState);
}
return result;
}
public Map<String, String> doClassify(String text) {
Map<String, String> result = null;
if ((stopwords == null || (stopwords != null && stopwords.doClassify(text) == null)) &&
(terms != null)) {
result = terms.doClassify(text);
}
return result;
}
public boolean doClassifyTerm(Token token, AtnState atnState) {
boolean result = false;
if (terms != null && token != null) {
result = terms.doClassify(token, atnState);
}
return result;
}
public Map<String, String> doClassifyTerm(String text) {
Map<String, String> result = null;
if (terms != null && text != null) {
result = terms.doClassify(text);
}
return result;
}
public boolean doClassifyStopword(Token token, AtnState atnState) {
boolean result = false;
if (stopwords != null && token != null) {
result = stopwords.doClassify(token, atnState);
}
return result;
}
public Map<String, String> doClassifyStopword(String text) {
Map<String, String> result = null;
if (stopwords != null && text != null) {
result = stopwords.doClassify(text);
}
return result;
}
}
protected static final class ClassifierContainer {
private String classifierName;
private AtnStateTokenClassifier namedResource; // temp storage
private List<AtnStateTokenClassifier> _classifiers; // delayed load
private boolean literalMatch; // delayed load
private boolean ruleMatch; // delayed load
private boolean trace;
private Object classifiersMutex = new Object();
public ClassifierContainer(String classifierName, ResourceManager resourceManager) {
this.classifierName = classifierName;
this.namedResource = findClassifierResource(classifierName, resourceManager);
this._classifiers = null;
this.literalMatch = false;
this.ruleMatch = false;
}
public boolean getTrace() {
return trace;
}
public void setTrace(boolean trace) {
this.trace = trace;
}
public String getName() {
return classifierName;
}
private final AtnStateTokenClassifier findClassifierResource(String classifierName, ResourceManager resourceManager) {
AtnStateTokenClassifier result = null;
final Object classifierObject = classifierName != null && !"".equals(classifierName) ? resourceManager.getResource(classifierName) : null;
if (classifierObject == null) {
if (GlobalConfig.verboseLoad()) {
System.out.println(new Date() + ": WARNING : RoteListClassifier unknown classifier '" + classifierName + "'");
}
}
else {
if (classifierObject instanceof AtnStateTokenClassifier) {
//TODO: adjust maxWordCount in containing Terms instance?
result = (AtnStateTokenClassifier)classifierObject;
}
else {
if (GlobalConfig.verboseLoad()) {
System.out.println(new Date() + ": WARNING : classifier '" +
classifierName + "' is *NOT* an AtnStateTokenClassifier (" +
classifierObject.getClass().getName() + ")");
}
}
}
return result;
}
public boolean doClassify(Token token, AtnState atnState) {
final List<AtnStateTokenClassifier> classifiers = getClassifiers(atnState);
boolean result = false;
// classify by resource and grammar classifiers
for (AtnStateTokenClassifier classifier : classifiers) {
result = classifier.classify(token, atnState).matched();
if (result) {
if (trace) {
System.out.println("\tclassifier(" + classifierName + ").classify(" + token + "," + atnState + ")=true");
}
break;
}
}
// check for literal token match
if (!result && literalMatch) {
result = classifierName != null && classifierName.equals(token.getText());
if (result && trace) {
System.out.println("\tliteralMatch(" + classifierName + ")=true");
}
}
// check for rule match
if (!result && ruleMatch) {
result = atnState.getRuleStep().getLabel().equals(classifierName);
for (AtnState theState = atnState.getPushState(); !result && theState != null; theState = theState.getPushState()) {
final AtnRule rule = theState.getRule();
final String ruleName = rule.getRuleName();
final String ruleId = rule.getRuleId();
result = ruleName.equals(classifierName);
if (!result && ruleId != null) {
result = ruleId.equals(classifierName);
}
}
}
// check for a token feature that matches the category
if (!result) {
final Feature feature = token.getFeature(classifierName, null, true); //todo: parameterize "broaden"?
result = (feature != null);
if (result && trace) {
System.out.println("\ttokenFeature(" + classifierName + ")=" + feature);
}
}
return result;
}
private final List<AtnStateTokenClassifier> getClassifiers(AtnState atnState) {
List<AtnStateTokenClassifier> result = null;
synchronized (classifiersMutex) {
if (_classifiers == null) {
loadClassifiers(atnState);
}
result = _classifiers;
}
return result;
}
public Map<String, String> doClassify(String text) {
Map<String, String> result = null;
if (this._classifiers == null) {
if (trace) {
System.out.println("\tWARNING: ClassifierContainer(" + classifierName + ") not fully initialized for doClassify(" + text + ")");
}
if (namedResource != null) {
final Map<String, String> curResult = namedResource.classify(text);
if (curResult != null) {
if (result == null) new HashMap<String, String>();
result.putAll(curResult);
if (trace) {
System.out.println("\tclassifier(" + classifierName + ").classify(" + text + ")=" + curResult);
}
}
}
}
else {
// classify by resource and grammar classifiers
for (AtnStateTokenClassifier classifier : _classifiers) {
final Map<String, String> curResult = classifier.classify(text);
if (curResult != null) {
if (result == null) new HashMap<String, String>();
result.putAll(curResult);
if (trace) {
System.out.println("\tclassifier(" + classifierName + ").classify(" + text + ")=" + curResult);
}
}
}
}
return result;
}
private final synchronized void loadClassifiers(AtnState atnState) {
this._classifiers = new ArrayList<AtnStateTokenClassifier>();
if (namedResource != null) {
this._classifiers.add(namedResource);
}
final AtnGrammar grammar = atnState.getRule().getGrammar();
final List<AtnStateTokenClassifier> tokenClassifiers = grammar.getClassifiers(classifierName);
if (tokenClassifiers != null) {
//TODO: adjust maxWordCount in containing Terms instance?
this._classifiers.addAll(tokenClassifiers);
}
else {
if (grammar.getCat2Rules().containsKey(classifierName)) {
ruleMatch = true;
}
else {
literalMatch = true;
}
}
}
}
}
|
package org.struckture.base;
import org.struckture.base.annotations.StruckField;
import org.struckture.base.annotations.Struckture;
import org.struckture.base.annotations.StrucktureAnnotation;
import org.struckture.base.exceptions.FieldConfigurationException;
import org.struckture.base.exceptions.StrucktureReadException;
import org.struckture.base.exceptions.StructureConfigurationException;
import org.struckture.handlers.BooleanArrayHandler;
import org.struckture.handlers.BooleanHandler;
import org.struckture.handlers.ByteArrayHandler;
import org.struckture.handlers.ByteHandler;
import org.struckture.handlers.DoubleHandler;
import org.struckture.handlers.FloatHandler;
import org.struckture.handlers.IntHandler;
import org.struckture.handlers.LongHandler;
import org.struckture.handlers.ShortHandler;
import org.struckture.handlers.StringHandler;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Implementation of Struck.<br/>
*
* Usage:
* <br/>
* <pre>
* {@code
* Strucktor<SomeStruckture> struck = Strucktor.forClass(SomeStruckture.class)
* SomeStruckture structure = struck.read(stream);
* }
* </pre>
*
* @param <T> Structure type to read.
*/
public class Strucktor<T> implements Struck<T> {
private final Class<T> type;
private final Map<Field, Handler<?>> handlers = new HashMap<>();
private final int dataLength;
private static final Map<Type, Class<? extends Handler>> HANDLER_TYPES;
static {
HANDLER_TYPES = new HashMap<>();
HANDLER_TYPES.put(Byte.TYPE, ByteHandler.class);
HANDLER_TYPES.put(Byte.class, ByteHandler.class);
HANDLER_TYPES.put(Short.TYPE, ShortHandler.class);
HANDLER_TYPES.put(Short.class, ShortHandler.class);
HANDLER_TYPES.put(Integer.TYPE, IntHandler.class);
HANDLER_TYPES.put(Integer.class, IntHandler.class);
HANDLER_TYPES.put(Long.TYPE, LongHandler.class);
HANDLER_TYPES.put(Long.class, LongHandler.class);
HANDLER_TYPES.put(Float.TYPE, FloatHandler.class);
HANDLER_TYPES.put(Float.class, FloatHandler.class);
HANDLER_TYPES.put(Double.TYPE, DoubleHandler.class);
HANDLER_TYPES.put(Double.class, DoubleHandler.class);
HANDLER_TYPES.put(Boolean.TYPE, BooleanHandler.class);
HANDLER_TYPES.put(Boolean.class, BooleanHandler.class);
HANDLER_TYPES.put(byte[].class, ByteArrayHandler.class);
HANDLER_TYPES.put(boolean[].class, BooleanArrayHandler.class);
HANDLER_TYPES.put(String.class, StringHandler.class);
}
/**
* Gets a {@link Struck} instance.
* @param type the type
* @param <Q> the type
* @return Struck instance which knows to read Struckture for type type(Q)
*/
public static <Q> Struck<Q> forClass(Class<Q> type) {
return new Strucktor<>(type);
}
private String format(String message, Object... args) {
return MessageFormat.format(message, args);
}
private boolean hasNoArgConstructor(Class<?> klass) {
for (Constructor c : klass.getDeclaredConstructors()) {
if (c.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
private Strucktor(Class<T> type) {
this.type = type;
if (!hasNoArgConstructor(type)) {
throw new StructureConfigurationException(
format("Struck ''{0}'' doesn't have no args constructor.", type));
}
Struckture strucktureAnnotation = type.getAnnotation(Struckture.class);
if (strucktureAnnotation == null) {
throw new StructureConfigurationException(
format("Struck ''{0}'' is not annotated with ''{1}''.", type, Struckture.class));
}
dataLength = strucktureAnnotation.length();
if (dataLength < 1) {
throw new StructureConfigurationException(
format("Length of structure ''{0}'' is not positive. length = ''{1}''.", type, dataLength));
}
for (Field field : type.getDeclaredFields()) {
StruckField struckFieldAnnotation = field.getAnnotation(StruckField.class);
if (struckFieldAnnotation != null) {
Handler<?> handler = getValidHandler(field, dataLength);
field.setAccessible(true);
handlers.put(field, handler);
}
}
boolean overlapAllowed = strucktureAnnotation.allowOverlapping();
if (!overlapAllowed) {
checkOverlapping(handlers);
}
}
private void checkOverlapping(Map<Field, Handler<?>> handlers) {
Map<Interval, Field> checked = new HashMap<>();
for (Map.Entry<Field, Handler<?>> entry : handlers.entrySet()) {
Handler<?> handler = entry.getValue();
Interval newInterval = new Interval(handler.getOffset(), handler.getOffset() + handler.getSize());
for (Map.Entry<Interval, Field> c : checked.entrySet()) {
Interval checkedInterval = c.getKey();
if (checkedInterval.overlaps(newInterval)) {
String message = format("Fields ''{0}'' and ''{1}'' are overlapping. "
+ "You can allow overlapping on the structure on the ''{3}'' annotation.",
c.getValue(), entry.getKey(), Struckture.class);
throw new StructureConfigurationException(message);
}
}
checked.put(newInterval, entry.getKey());
}
}
private static class Interval {
private final int from;
private final int to;
Interval(int from, int to) {
this.from = from;
this.to = to;
}
private boolean overlaps(Interval other) {
boolean isOtherLeft = other.from <= from && other.to <= from;
boolean isOtherRight = other.from >= to && other.to >= to;
return !isOtherLeft && !isOtherRight;
}
}
private Handler<?> getValidHandler(Field field, int dataLength) {
try {
Class<? extends Handler> handlerType = HANDLER_TYPES.get(field.getType());
if (handlerType == null) {
throw new FieldConfigurationException(
format("Handler for type ''{0}'' is not supported.", field.getType()));
}
Set<Annotation> annotations = getStruckAnnotations(field);
Handler<?> handler = handlerType.newInstance();
handler.init(annotations);
if (handler.getOffset() < 0) {
throw new FieldConfigurationException(
format("Offset for ''{0}'' negative. Should be non-negative.", field));
}
if (handler.getOffset() + handler.getSize() > dataLength) {
throw new FieldConfigurationException(
format("Upper bound for ''{0}'' outside the structure size ''{1}''.", field, dataLength));
}
return handler;
} catch (IllegalAccessException | InstantiationException e) {
throw new FieldConfigurationException(format("Error while configuring field ''{0}''.", field), e);
}
}
private Set<Annotation> getStruckAnnotations(Field field) {
Set<Annotation> annotations = new HashSet<>();
for (Annotation annotation : field.getDeclaredAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(StrucktureAnnotation.class)) {
annotations.add(annotation);
}
}
return annotations;
}
@Override
public T read(InputStream stream) throws StrucktureReadException {
try {
byte[] bytes = new byte[dataLength];
int read = stream.read(bytes);
if (read == -1) {
return null;
}
if (read < dataLength) {
throw new StrucktureReadException(
format("Couldn't read structure. Only ''{0}'' bytes are available", read));
}
Constructor<T> declaredConstructor = type.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
T result = declaredConstructor.newInstance();
for (Field field : handlers.keySet()) {
Handler handler = handlers.get(field);
if (handler != null) {
Object value = handler.getValue(bytes);
field.set(result, value);
}
}
return result;
} catch (Exception e) {
throw new StrucktureReadException("Could not read structure.", e);
}
}
}
|
package org.znerd.util.text;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.znerd.util.Preconditions;
/**
* Text string utility functions.
*/
public class TextUtils {
private static final String NULL_STRING = "(null)";
/**
* Puts quote characters around the string representation of an object, escaping all backslash and quote characters inside the string. Returns <code>"(null)"</code> if the object is
* <code>null</code> or if the object's <code>toString()</code> method returns <code>null</code>.
*/
public static final String quote(Object o) {
if (o == null) {
return NULL_STRING;
}
String s = o.toString();
if (s == null) {
return NULL_STRING;
}
s = s.replaceAll("\\\\", Matcher.quoteReplacement("\\\\"));
s = s.replaceAll("\"", Matcher.quoteReplacement("\\\""));
return '"' + s + '"';
}
/**
* Checks if the specified string is either <code>null</code> or empty or contains only whitespace.
*/
public static final boolean isEmpty(String s) {
return s == null || "".equals(s.trim());
}
/**
* Checks if the specified string matches the specified regular expression.
* <p>
* This method differs from {@link String#matches(String)} in that this method also supports partial matches. To give an example:
*
* <pre>
* "bla bla".match("bla$"); // returns false
* TextUtils.matches("bla bla", "bla$"); // returns true
* </pre>
*/
public static final boolean matches(String s, String regex) {
Preconditions.checkArgument(s == null, "s == null");
Preconditions.checkArgument(regex == null, "regex == null");
return Pattern.compile(regex).matcher(s).find();
}
private TextUtils() {
}
}
|
package redis.clients.jedis;
import java.net.URI;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.JedisURIHelper;
import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> {
private String clientNameOnReturn = null;
public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final String host) {
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) {
database = dbIndex.intValue();
}
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(h, port,
Protocol.DEFAULT_TIMEOUT, password, database, null), new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host,
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
}
}
public JedisPool(final URI uri) {
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig(), uri, timeout);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database) {
this(poolConfig, host, port, timeout, password, database, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password, database, clientName));
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(), timeout,
JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper.getDBIndex(uri) : 0, null));
}
public String getClientNameOnReturn() {
return clientNameOnReturn;
}
public void setClientNameOnReturn(String s) {
clientNameOnReturn = s;
}
@Override
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final Jedis resource) {
if (resource != null) {
try {
if (clientNameOnReturn != null) {
resource.clientSetname(clientNameOnReturn);
}
resource.resetState();
returnResourceObject(resource);
} catch (Exception e) {
returnBrokenResource(resource);
throw new JedisException("Could not return the resource to the pool", e);
}
}
}
public int getNumActive() {
if (this.internalPool == null || this.internalPool.isClosed()) {
return -1;
}
return this.internalPool.getNumActive();
}
}
|
package sourceafis;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
import sourceafis.scalars.*;
public class FingerprintMatcher {
static final int maxDistanceError = 13;
static final double maxAngleError = Math.toRadians(10);
final FingerprintTemplate template;
Map<Integer, List<IndexedEdge>> edgeHash = new HashMap<>();
FingerprintTemplate candidate;
PriorityQueue<EdgePair> pairQueue = new PriorityQueue<>();
PairInfo[] pairsByCandidate;
PairInfo[] pairsByProbe;
PairInfo[] pairList;
int pairCount;
public FingerprintMatcher(FingerprintTemplate template) {
this.template = template;
buildEdgeHash();
pairsByProbe = new PairInfo[template.minutiae.size()];
pairList = new PairInfo[template.minutiae.size()];
for (int i = 0; i < pairList.length; ++i)
pairList[i] = new PairInfo();
}
static class IndexedEdge {
final EdgeShape shape;
final int reference;
final int neighbor;
IndexedEdge(EdgeShape shape, int reference, int neighbor) {
this.shape = shape;
this.reference = reference;
this.neighbor = neighbor;
}
}
void buildEdgeHash() {
for (int referenceMinutia = 0; referenceMinutia < template.minutiae.size(); ++referenceMinutia)
for (int neighborMinutia = 0; neighborMinutia < template.minutiae.size(); ++neighborMinutia)
if (referenceMinutia != neighborMinutia) {
IndexedEdge edge = new IndexedEdge(new EdgeShape(template, referenceMinutia, neighborMinutia), referenceMinutia, neighborMinutia);
for (int hash : shapeCoverage(edge.shape)) {
List<IndexedEdge> list = edgeHash.get(hash);
if (list == null)
edgeHash.put(hash, list = new ArrayList<>());
list.add(edge);
}
}
}
static List<Integer> shapeCoverage(EdgeShape edge) {
int minLengthBin = (edge.length - maxDistanceError) / maxDistanceError;
int maxLengthBin = (edge.length + maxDistanceError) / maxDistanceError;
int angleBins = (int)Math.ceil(2 * Math.PI / maxAngleError);
int minReferenceBin = (int)(Angle.difference(edge.referenceAngle, maxAngleError) / maxAngleError);
int maxReferenceBin = (int)(Angle.add(edge.referenceAngle, maxAngleError) / maxAngleError);
int endReferenceBin = (maxReferenceBin + 1) % angleBins;
int minNeighborBin = (int)(Angle.difference(edge.neighborAngle, maxAngleError) / maxAngleError);
int maxNeighborBin = (int)(Angle.add(edge.neighborAngle, maxAngleError) / maxAngleError);
int endNeighborBin = (maxNeighborBin + 1) % angleBins;
List<Integer> coverage = new ArrayList<>();
for (int lengthBin = minLengthBin; lengthBin <= maxLengthBin; ++lengthBin)
for (int referenceBin = minReferenceBin; referenceBin != endReferenceBin; referenceBin = (referenceBin + 1) % angleBins)
for (int neighborBin = minNeighborBin; neighborBin != endNeighborBin; neighborBin = (neighborBin + 1) % angleBins)
coverage.add((referenceBin << 24) + (neighborBin << 16) + lengthBin);
return coverage;
}
public double match(FingerprintTemplate candidate) {
final int maxTriedRoots = 70;
final int maxTriedTriangles = 7538;
this.candidate = candidate;
int rootIndex = 0;
int triangleIndex = 0;
double bestScore = 0;
for (MinutiaPair root : (Iterable<MinutiaPair>)roots()::iterator) {
double score = tryRoot(root);
if (score > bestScore)
bestScore = score;
++rootIndex;
if (rootIndex >= maxTriedRoots)
break;
if (pairCount >= 3) {
++triangleIndex;
if (triangleIndex >= maxTriedTriangles)
break;
}
}
return bestScore;
}
interface ShapeFilter extends Predicate<EdgeShape> {
}
Stream<MinutiaPair> roots() {
final int minEdgeLength = 58;
final int maxEdgeLookups = 1633;
ShapeFilter[] filters = new ShapeFilter[] {
shape -> shape.length >= minEdgeLength,
shape -> shape.length < minEdgeLength
};
class EdgeLookup {
EdgeShape candidateEdge;
int candidateReference;
}
Stream<EdgeLookup> lookups = Arrays.stream(filters)
.flatMap(shapeFilter -> IntStream.range(1, candidate.minutiae.size()).boxed()
.flatMap(step -> IntStream.range(0, step + 1).boxed()
.flatMap(pass -> {
List<Integer> candidateReferences = new ArrayList<>();
for (int candidateReference = pass; candidateReference < candidate.minutiae.size(); candidateReference += step + 1)
candidateReferences.add(candidateReference);
return candidateReferences.stream();
})
.flatMap(candidateReference -> {
int candidateNeighbor = (candidateReference + step) % candidate.minutiae.size();
EdgeShape candidateEdge = new EdgeShape(candidate, candidateReference, candidateNeighbor);
if (shapeFilter.test(candidateEdge)) {
EdgeLookup lookup = new EdgeLookup();
lookup.candidateEdge = candidateEdge;
lookup.candidateReference = candidateReference;
return Stream.of(lookup);
}
return null;
})));
return lookups.limit(maxEdgeLookups)
.flatMap(lookup -> {
List<IndexedEdge> matches = edgeHash.get(hashShape(lookup.candidateEdge));
if (matches != null) {
return matches.stream()
.filter(match -> matchingShapes(match.shape, lookup.candidateEdge))
.map(match -> new MinutiaPair(match.reference, lookup.candidateReference));
}
return null;
});
}
static int hashShape(EdgeShape edge) {
int lengthBin = edge.length / maxDistanceError;
int referenceAngleBin = (int)(edge.referenceAngle / maxAngleError);
int neighborAngleBin = (int)(edge.neighborAngle / maxAngleError);
return (referenceAngleBin << 24) + (neighborAngleBin << 16) + lengthBin;
}
static boolean matchingShapes(EdgeShape probe, EdgeShape candidate) {
int lengthDelta = probe.length - candidate.length;
if (lengthDelta >= -maxDistanceError && lengthDelta <= maxDistanceError) {
double complementaryAngleError = Angle.complementary(maxAngleError);
double referenceDelta = Angle.difference(probe.referenceAngle, candidate.referenceAngle);
if (referenceDelta <= maxAngleError || referenceDelta >= complementaryAngleError) {
double neighborDelta = Angle.difference(probe.neighborAngle, candidate.neighborAngle);
if (neighborDelta <= maxAngleError || neighborDelta >= complementaryAngleError)
return true;
}
}
return false;
}
double tryRoot(MinutiaPair root) {
createRootPairing(root);
buildPairing();
}
void createRootPairing(MinutiaPair root) {
if (pairsByCandidate == null || pairsByCandidate.length < candidate.minutiae.size())
pairsByCandidate = new PairInfo[candidate.minutiae.size()];
for (int i = 0; i < pairCount; ++i) {
pairList[i].supportingEdges = 0;
pairsByProbe[pairList[i].pair.probe] = null;
pairsByCandidate[pairList[i].pair.candidate] = null;
}
pairsByCandidate[root.candidate] = pairsByProbe[root.probe] = pairList[0];
pairList[0].pair = root;
pairCount = 1;
}
void buildPairing() {
while (true) {
collectEdges();
skipPaired();
if (pairQueue.isEmpty())
break;
addPair(pairQueue.remove());
}
}
PairInfo lastPair() {
return pairList[pairCount - 1];
}
void collectEdges() {
MinutiaPair reference = lastPair().pair;
NeighborEdge[] probeNeighbors = template.edgeTable[reference.probe];
NeighborEdge[] candidateNeigbors = candidate.edgeTable[reference.candidate];
List<MatchingPair> matches = findMatchingPairs(probeNeighbors, candidateNeigbors);
for (MatchingPair match : matches) {
MinutiaPair neighbor = match.pair;
if (pairsByCandidate[neighbor.candidate] == null && pairsByProbe[neighbor.probe] == null)
pairQueue.add(new EdgePair(reference, neighbor, match.distance));
else if (pairsByProbe[neighbor.probe] != null && pairsByProbe[neighbor.probe].pair.candidate == neighbor.candidate) {
++pairsByProbe[reference.probe].supportingEdges;
++pairsByProbe[neighbor.probe].supportingEdges;
}
}
}
static class MatchingPair {
MinutiaPair pair;
int distance;
MatchingPair(MinutiaPair pair, int distance) {
this.pair = pair;
this.distance = distance;
}
}
static List<MatchingPair> findMatchingPairs(NeighborEdge[] probeStar, NeighborEdge[] candidateStar) {
double complementaryAngleError = Angle.complementary(maxAngleError);
List<MatchingPair> results = new ArrayList<>();
int start = 0;
int end = 0;
for (int candidateIndex = 0; candidateIndex < candidateStar.length; ++candidateIndex) {
NeighborEdge candidateEdge = candidateStar[candidateIndex];
while (start < probeStar.length && probeStar[start].edge.length < candidateEdge.edge.length - maxDistanceError)
++start;
if (end < start)
end = start;
while (end < probeStar.length && probeStar[end].edge.length <= candidateEdge.edge.length + maxDistanceError)
++end;
for (int probeIndex = start; probeIndex < end; ++probeIndex) {
NeighborEdge probeEdge = probeStar[probeIndex];
double referenceDiff = Angle.difference(probeEdge.edge.referenceAngle, candidateEdge.edge.referenceAngle);
if (referenceDiff <= maxAngleError || referenceDiff >= complementaryAngleError) {
double neighborDiff = Angle.difference(probeEdge.edge.neighborAngle, candidateEdge.edge.neighborAngle);
if (neighborDiff <= maxAngleError || neighborDiff >= complementaryAngleError)
results.add(new MatchingPair(new MinutiaPair(probeEdge.neighbor, candidateEdge.neighbor), candidateEdge.edge.length));
}
}
}
return results;
}
void skipPaired() {
while (!pairQueue.isEmpty() && (pairsByProbe[pairQueue.peek().neighbor.probe] != null || pairsByCandidate[pairQueue.peek().neighbor.candidate] != null)) {
EdgePair edge = pairQueue.remove();
if (pairsByProbe[edge.neighbor.probe] != null && pairsByProbe[edge.neighbor.probe].pair.candidate == edge.neighbor.candidate) {
++pairsByProbe[edge.reference.probe].supportingEdges;
++pairsByProbe[edge.neighbor.probe].supportingEdges;
}
}
}
void addPair(EdgePair edge) {
pairsByCandidate[edge.neighbor.candidate] = pairsByProbe[edge.neighbor.probe] = pairList[pairCount];
pairList[pairCount].pair = edge.neighbor;
pairList[pairCount].reference = edge.reference;
++pairCount;
}
static class MinutiaPair {
final int probe;
final int candidate;
MinutiaPair(int probe, int candidate) {
this.probe = probe;
this.candidate = candidate;
}
}
static class PairInfo {
MinutiaPair pair;
MinutiaPair reference;
int supportingEdges;
}
static class EdgePair implements Comparable<EdgePair> {
MinutiaPair reference;
MinutiaPair neighbor;
int distance;
EdgePair(MinutiaPair reference, MinutiaPair neighbor, int distance) {
this.reference = reference;
this.neighbor = neighbor;
this.distance = distance;
}
@Override public int compareTo(EdgePair other) {
return Integer.compare(distance, other.distance);
}
}
}
|
package uk.gov.register.core;
import uk.gov.register.store.BackingStoreDriver;
import uk.gov.register.views.ConsistencyProof;
import uk.gov.register.views.EntryProof;
import uk.gov.register.views.RegisterProof;
import javax.xml.bind.DatatypeConverter;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* An append-only log of Entries, together with proofs
*/
public class EntryLog {
private final BackingStoreDriver backingStoreDriver;
public EntryLog(BackingStoreDriver backingStoreDriver) {
this.backingStoreDriver = backingStoreDriver;
}
public void appendEntry(Entry entry) {
backingStoreDriver.insertEntry(entry);
}
public Optional<Entry> getEntry(int entryNumber) {
return backingStoreDriver.getEntry(entryNumber);
}
public Collection<Entry> getEntries(int start, int limit) {
return backingStoreDriver.getEntries(start, limit);
}
public Iterator<Entry> getIterator() {
return backingStoreDriver.getEntryIterator();
}
public Iterator<Entry> getIterator(int start, int end){
return backingStoreDriver.getEntryIterator(start, end);
}
public Collection<Entry> getAllEntries() {
return backingStoreDriver.getAllEntries();
}
public int getTotalEntries() {
return backingStoreDriver.getTotalEntries();
}
public Optional<Instant> getLastUpdatedTime() {
return backingStoreDriver.getLastUpdatedTime();
}
public RegisterProof getRegisterProof() throws NoSuchAlgorithmException {
String rootHash = backingStoreDriver.withVerifiableLog(verifiableLog ->
bytesToString(verifiableLog.currentRoot()));
return new RegisterProof(rootHash);
}
public EntryProof getEntryProof(int entryNumber, int totalEntries) {
List<String> auditProof = backingStoreDriver.withVerifiableLog(verifiableLog ->
verifiableLog.auditProof(entryNumber, totalEntries)
.stream().map(this::bytesToString).collect(Collectors.toList()));
return new EntryProof(Integer.toString(entryNumber), auditProof);
}
public ConsistencyProof getConsistencyProof(int totalEntries1, int totalEntries2) {
List<String> consistencyProof = backingStoreDriver.withVerifiableLog(verifiableLog ->
verifiableLog.consistencyProof(totalEntries1, totalEntries2))
.stream().map(this::bytesToString).collect(Collectors.toList());
return new ConsistencyProof(consistencyProof);
}
private String bytesToString(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes).toLowerCase();
}
}
|
package se.sics.cooja.plugins;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.interfaces.LED;
import se.sics.cooja.interfaces.Log;
import se.sics.cooja.interfaces.Radio;
import se.sics.cooja.interfaces.Radio.RadioEvent;
/**
* Shows events such as mote logs, LEDs, and radio transmissions, in a timeline.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Timeline")
@PluginType(PluginType.SIM_STANDARD_PLUGIN)
public class TimeLine extends VisPlugin {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(TimeLine.class);
private static Color COLOR_BACKGROUND = Color.WHITE;
public static final int EVENT_PIXEL_HEIGHT = 4;
public static final int TIME_MARKER_PIXEL_HEIGHT = 6;
public static final int FIRST_MOTE_PIXEL_OFFSET = TIME_MARKER_PIXEL_HEIGHT + EVENT_PIXEL_HEIGHT;
private int paintedMoteHeight = EVENT_PIXEL_HEIGHT;
private Simulation simulation;
private JScrollPane timelineScrollPane;
private MoteRuler timelineMoteRuler;
private JPanel timeline;
private Box eventCheckboxes;
private Observer tickObserver;
private ArrayList<MoteObservation> activeMoteObservers = new ArrayList<MoteObservation>();
private ArrayList<MoteEvents> allMoteEvents = new ArrayList<MoteEvents>();
private long startTime;
private boolean viewportTracking = true;
private Point viewportInfinite = new Point(Integer.MAX_VALUE, 0);
private Runnable updateViewport = new Runnable() {
public void run() {
if (!viewportTracking) {
return;
}
viewportInfinite.x = timeline.getWidth();
timelineScrollPane.getViewport().setViewPosition(viewportInfinite);
}
};
private boolean showRadioRXTX = true;
private boolean showRadioChannels = false;
private boolean showRadioHW = true;
private boolean showLEDs = true;
private boolean showLogOutputs = false;
private boolean showWatchpoints = false;
/**
* @param simulation Simulation
* @param gui GUI
*/
public TimeLine(final Simulation simulation, final GUI gui) {
super("Timeline (Add motes to observe by clicking +)", gui);
this.simulation = simulation;
startTime = simulation.getSimulationTime();
/* Automatically repaint every tick */
simulation.addTickObserver(tickObserver = new Observer() {
public void update(Observable obs, Object obj) {
if (timelineScrollPane == null)
return;
timeline.setPreferredSize(new Dimension(
(int) (simulation.getSimulationTime() - startTime),
(int) (FIRST_MOTE_PIXEL_OFFSET + paintedMoteHeight * allMoteEvents.size())
));
timelineMoteRuler.setPreferredSize(new Dimension(
35,
(int) (FIRST_MOTE_PIXEL_OFFSET + paintedMoteHeight * allMoteEvents.size())
));
timeline.revalidate();
timeline.repaint();
if (viewportTracking) {
SwingUtilities.invokeLater(updateViewport);
}
}
});
/* Box: events to observe */
eventCheckboxes = Box.createVerticalBox();
JCheckBox eventCheckBox;
eventCheckBox = createEventCheckbox("Radio RX/TX", "Show radio transmissions, receptions, and collisions");
eventCheckBox.setName("showRadioRXTX");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showRadioRXTX = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
eventCheckboxes.add(eventCheckBox);
eventCheckBox = createEventCheckbox("Radio channels", "Show different radio channels");
eventCheckBox.setName("showRadioChannels");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showRadioChannels = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
/*eventCheckboxes.add(eventCheckBox);*/
eventCheckBox = createEventCheckbox("Radio ON/OFF", "Show radio hardware state");
eventCheckBox.setName("showRadioHW");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showRadioHW = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
eventCheckboxes.add(eventCheckBox);
eventCheckBox = createEventCheckbox("LEDs", "Show LED state");
eventCheckBox.setName("showLEDs");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showLEDs = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
eventCheckboxes.add(eventCheckBox);
eventCheckBox = createEventCheckbox("Log output", "Show mote log output, such as by printf()'s");
eventCheckBox.setName("showLogOutput");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showLogOutputs = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
/*eventCheckboxes.add(eventCheckBox);*/
eventCheckBox = createEventCheckbox("Watchpoints", "Show code watchpoints configurable on MSPSim based motes");
eventCheckBox.setName("showWatchpoints");
eventCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showWatchpoints = ((JCheckBox) e.getSource()).isSelected();
recalculateMoteHeight();
}
});
/*eventCheckboxes.add(eventCheckBox);*/
/* Panel: timeline canvas w. scroll pane and add mote button */
timeline = new Timeline();
timelineScrollPane = new JScrollPane(
timeline,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
timelineScrollPane.getHorizontalScrollBar().addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Rectangle view = timelineScrollPane.getViewport().getViewRect();
if (view.x + view.width + 5 > simulation.getSimulationTime()) {
viewportInfinite.y = view.y;
viewportTracking = true;
} else {
viewportTracking = false;
}
timeline.revalidate();
timeline.repaint();
}
});
timelineScrollPane.getVerticalScrollBar().addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
Rectangle view = timelineScrollPane.getViewport().getViewRect();
viewportInfinite.y = view.y;
timeline.revalidate();
timeline.repaint();
}
});
timelineScrollPane.getVerticalScrollBar().setPreferredSize(
new Dimension(
35,
timelineScrollPane.getVerticalScrollBar().getPreferredSize().height));
JButton timelineAddMoteButton = new JButton(addMoteAction);
timelineAddMoteButton.setText("+");
timelineAddMoteButton.setToolTipText("Add mote");
timelineAddMoteButton.setBorderPainted(false);
timelineAddMoteButton.setFont(new Font("SansSerif", Font.PLAIN, 11));
JButton saveDataButton = new JButton(saveDataAction);
saveDataButton.setText("S");
saveDataButton.setToolTipText("Save all data to file");
saveDataButton.setBorderPainted(false);
saveDataButton.setFont(new Font("SansSerif", Font.PLAIN, 11));
timelineMoteRuler = new MoteRuler();
timelineScrollPane.setRowHeaderView(timelineMoteRuler);
timelineScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER, timelineAddMoteButton);
timelineScrollPane.setCorner(JScrollPane.LOWER_RIGHT_CORNER, saveDataButton);
timelineScrollPane.setBackground(Color.WHITE);
JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
eventCheckboxes,
timelineScrollPane
);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.0);
getContentPane().add(splitPane);
pack();
setSize(gui.getDesktopPane().getWidth(), 150);
setLocation(0, gui.getDesktopPane().getHeight() - 150);
numberMotesWasUpdated();
}
private JCheckBox createEventCheckbox(String text, String tooltip) {
JCheckBox checkBox = new JCheckBox(text, true);
checkBox.setToolTipText(tooltip);
return checkBox;
}
private Action removeMoteAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JComponent b = (JComponent) e.getSource();
Mote m = (Mote) b.getClientProperty("mote");
removeMote(m);
}
};
private Action addMoteAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JComboBox source = new JComboBox();
source.addItem("All motes");
for (Mote m: simulation.getMotes()) {
source.addItem(m);
}
Object description[] = {
source
};
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage(description);
optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
String options[] = new String[] {"Cancel", "Add"};
optionPane.setOptions(options);
optionPane.setInitialValue(options[1]);
JDialog dialog = optionPane.createDialog(GUI.getTopParentContainer(), "Add mote to timeline");
dialog.setVisible(true);
if (optionPane.getValue() == null || !optionPane.getValue().equals("Add")) {
return;
}
if (source.getSelectedItem().equals("All motes")) {
for (Mote m: simulation.getMotes()) {
addMote(m);
}
} else {
addMote((Mote) source.getSelectedItem());
}
}
};
/**
* Save logged raw data to file for post-processing.
*/
private Action saveDataAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(GUI.getTopParentContainer());
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
File saveFile = fc.getSelectedFile();
if (saveFile.exists()) {
String s1 = "Overwrite";
String s2 = "Cancel";
Object[] options = { s1, s2 };
int n = JOptionPane.showOptionDialog(
GUI.getTopParentContainer(),
"A file with the same name already exists.\nDo you want to remove it?",
"Overwrite existing file?", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, s1);
if (n != JOptionPane.YES_OPTION) {
return;
}
}
if (saveFile.exists() && !saveFile.canWrite()) {
logger.fatal("No write access to file");
return;
}
try {
BufferedWriter outStream = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
saveFile)));
/* Output all events (per mote) */
for (MoteEvents moteEvents: allMoteEvents) {
for (LEDEvent ev: moteEvents.ledEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
for (LogEvent ev: moteEvents.logEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
for (RadioChannelEvent ev: moteEvents.radioChannelEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
for (RadioHWEvent ev: moteEvents.radioHWEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
for (RadioRXTXEvent ev: moteEvents.radioRXTXEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
for (WatchpointEvent ev: moteEvents.watchpointEvents) {
outStream.write(moteEvents.mote + "\t" + ev.time + "\t" + ev.toString() + "\n");
}
}
outStream.close();
} catch (Exception ex) {
logger.fatal("Could not write to file: " + saveFile);
return;
}
}
};
private void numberMotesWasUpdated() {
/* Timeline */
timeline.setPreferredSize(new Dimension(
(int) (simulation.getSimulationTime() - startTime),
(int) (FIRST_MOTE_PIXEL_OFFSET + paintedMoteHeight * allMoteEvents.size())
));
timelineMoteRuler.setPreferredSize(new Dimension(
35,
(int) (FIRST_MOTE_PIXEL_OFFSET + paintedMoteHeight * allMoteEvents.size())
));
timelineMoteRuler.revalidate();
timelineMoteRuler.repaint();
timeline.revalidate();
timeline.repaint();
/* Plugin title */
if (allMoteEvents.isEmpty()) {
setTitle("Timeline (Add motes to observe by clicking +)");
} else {
setTitle("Timeline (" + allMoteEvents.size() + " motes)");
}
}
/* XXX Keeps track of observed mote interfaces */
class MoteObservation {
private Observer observer;
private Observable observable;
private Mote mote;
public MoteObservation(Mote mote, Observable observable, Observer observer) {
this.mote = mote;
this.observable = observable;
this.observer = observer;
}
public Mote getMote() {
return mote;
}
/**
* Disconnect observer from observable (stop observing) and clean up resources (remove pointers).
*/
public void dispose() {
observable.deleteObserver(observer);
mote = null;
observable = null;
observer = null;
}
}
private void addMoteObservers(Mote mote, final MoteEvents moteEvents) {
final LED moteLEDs = mote.getInterfaces().getLED();
final Radio moteRadio = mote.getInterfaces().getRadio();
final Log moteLog = mote.getInterfaces().getLog();
/* TODO Watchpoints? */
/* LEDs */
if (moteLEDs != null) {
LEDEvent startupEv = new LEDEvent(
simulation.getSimulationTime(),
moteLEDs.isRedOn(),
moteLEDs.isGreenOn(),
moteLEDs.isYellowOn()
);
moteEvents.addLED(startupEv);
Observer observer = new Observer() {
public void update(Observable o, Object arg) {
LEDEvent ev = new LEDEvent(
simulation.getSimulationTime(),
moteLEDs.isRedOn(),
moteLEDs.isGreenOn(),
moteLEDs.isYellowOn()
);
moteEvents.addLED(ev);
}
};
moteLEDs.addObserver(observer);
activeMoteObservers.add(new MoteObservation(mote, moteLEDs, observer));
}
/* Radio HW */
if (moteRadio != null) {
RadioHWEvent startupHW = new RadioHWEvent(
simulation.getSimulationTime(), moteRadio.isReceiverOn());
moteEvents.addRadioHW(startupHW);
RadioRXTXEvent startupRXTX = new RadioRXTXEvent(
simulation.getSimulationTime(), RadioEvent.UNKNOWN);
moteEvents.addRadioRXTX(startupRXTX);
Observer observer = new Observer() {
public void update(Observable o, Object arg) {
/* Radio HW events */
if (moteRadio.getLastEvent() == RadioEvent.HW_ON ||
moteRadio.getLastEvent() == RadioEvent.HW_OFF) {
RadioHWEvent ev = new RadioHWEvent(
simulation.getSimulationTime(), moteRadio.getLastEvent()==RadioEvent.HW_ON);
moteEvents.addRadioHW(ev);
return;
}
/* Radio RXTX events */
if (moteRadio.getLastEvent() == RadioEvent.TRANSMISSION_STARTED ||
moteRadio.getLastEvent() == RadioEvent.TRANSMISSION_FINISHED ||
moteRadio.getLastEvent() == RadioEvent.RECEPTION_STARTED ||
moteRadio.getLastEvent() == RadioEvent.RECEPTION_INTERFERED ||
moteRadio.getLastEvent() == RadioEvent.RECEPTION_FINISHED) {
RadioRXTXEvent ev = new RadioRXTXEvent(
simulation.getSimulationTime(), moteRadio.getLastEvent());
moteEvents.addRadioRXTX(ev);
return;
}
}
};
moteRadio.addObserver(observer);
activeMoteObservers.add(new MoteObservation(mote, moteRadio, observer));
}
}
private void addMote(Mote newMote) {
if (newMote != null) {
for (MoteEvents moteEvents: allMoteEvents) {
if (moteEvents.mote == newMote) {
return;
}
}
MoteEvents newMoteLog = new MoteEvents(newMote);
allMoteEvents.add(newMoteLog);
addMoteObservers(newMote, newMoteLog);
}
numberMotesWasUpdated();
}
private void removeMote(Mote mote) {
MoteEvents remove = null;
for (MoteEvents moteEvents: allMoteEvents) {
if (moteEvents.mote == mote) {
remove = moteEvents;
break;
}
}
if (remove == null) {
logger.warn("No such observed mote: " + mote);
return;
}
allMoteEvents.remove(remove);
/* Remove mote observers */
MoteObservation[] moteObservers = activeMoteObservers.toArray(new MoteObservation[0]);
for (MoteObservation o: moteObservers) {
if (o.getMote() == mote) {
o.dispose();
activeMoteObservers.remove(o);
}
}
numberMotesWasUpdated();
}
private void recalculateMoteHeight() {
int h = EVENT_PIXEL_HEIGHT;
if (showRadioRXTX) {
h += EVENT_PIXEL_HEIGHT;
}
if (showRadioChannels) {
h += EVENT_PIXEL_HEIGHT;
}
if (showRadioHW) {
h += EVENT_PIXEL_HEIGHT;
}
if (showLEDs) {
h += EVENT_PIXEL_HEIGHT;
}
if (showLogOutputs) {
h += EVENT_PIXEL_HEIGHT;
}
if (showWatchpoints) {
h += EVENT_PIXEL_HEIGHT;
}
paintedMoteHeight = h;
timelineMoteRuler.revalidate();
timelineMoteRuler.repaint();
timeline.revalidate();
timeline.repaint();
}
public void closePlugin() {
simulation.deleteTickObserver(tickObserver);
/* Remove active mote interface observers */
for (MoteObservation o: activeMoteObservers) {
o.dispose();
}
activeMoteObservers.clear();
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
/* Remember observed motes */
Mote[] allMotes = simulation.getMotes();
for (MoteEvents moteEvents: allMoteEvents) {
element = new Element("mote");
for (int i=0; i < allMotes.length; i++) {
if (allMotes[i] == moteEvents.mote) {
element.setText("" + i);
config.add(element);
break;
}
}
}
if (showRadioRXTX) {
element = new Element("showRadioRXTX");
config.add(element);
}
if (showRadioChannels) {
element = new Element("showRadioChannels");
config.add(element);
}
if (showRadioHW) {
element = new Element("showRadioHW");
config.add(element);
}
if (showLEDs) {
element = new Element("showLEDs");
config.add(element);
}
if (showLogOutputs) {
element = new Element("showLogOutput");
config.add(element);
}
if (showWatchpoints) {
element = new Element("showWatchpoints");
config.add(element);
}
return config;
}
public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) {
showRadioRXTX = false;
showRadioChannels = false;
showRadioHW = false;
showLEDs = false;
showLogOutputs = false;
showWatchpoints = false;
for (Element element : configXML) {
String name = element.getName();
if ("mote".equals(name)) {
int index = Integer.parseInt(element.getText());
addMote(simulation.getMote(index));
} else if ("showRadioRXTX".equals(name)) {
showRadioRXTX = true;
} else if ("showRadioChannels".equals(name)) {
showRadioChannels = true;
} else if ("showRadioHW".equals(name)) {
showRadioHW = true;
} else if ("showLEDs".equals(name)) {
showLEDs = true;
} else if ("showLogOutput".equals(name)) {
showLogOutputs = true;
} else if ("showWatchpoints".equals(name)) {
showWatchpoints = true;
}
}
/* XXX HACK: Update checkboxes according to config */
for (Component c: eventCheckboxes.getComponents()) {
if (c.getName() == "showRadioRXTX") {
((JCheckBox)c).setSelected(showRadioRXTX);
} else if (c.getName() == "showRadioChannels") {
((JCheckBox)c).setSelected(showRadioChannels);
} else if (c.getName() == "showRadioHW") {
((JCheckBox)c).setSelected(showRadioHW);
} else if (c.getName() == "showLEDs") {
((JCheckBox)c).setSelected(showLEDs);
} else if (c.getName() == "showLogOutput") {
((JCheckBox)c).setSelected(showLogOutputs);
} else if (c.getName() == "showWatchpoints") {
((JCheckBox)c).setSelected(showWatchpoints);
}
}
recalculateMoteHeight();
return true;
}
class Timeline extends JPanel {
private int mouseTimePositionX = -1;
private int mouseTimePositionY = -1;
private MouseAdapter mouseAdapter = new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
if (mouseTimePositionX >= 0) {
mouseTimePositionX = e.getX();
mouseTimePositionY = e.getY();
repaint();
}
}
public void mousePressed(MouseEvent e) {
if (e.getPoint().getY() < FIRST_MOTE_PIXEL_OFFSET) {
mouseTimePositionX = e.getX();
mouseTimePositionY = e.getY();
repaint();
}
}
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
mouseTimePositionX = -1;
repaint();
}
};
public Timeline() {
setToolTipText("");
setBackground(COLOR_BACKGROUND);
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
public void paintComponent(Graphics g) {
/*logger.info("Painting timeline: " + startTime + " -> " + (startTime + timeline.getWidth()));*/
Rectangle bounds = g.getClipBounds();
long intervalStart = bounds.x + startTime;
long intervalEnd = intervalStart + bounds.width;
/*logger.info("Painting interval: " + intervalStart + " -> " + intervalEnd);*/
if (bounds.x > Integer.MAX_VALUE - 1000) {
/* TODO Strange bounds */
return;
}
g.setColor(COLOR_BACKGROUND);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
drawTimeRule(g, intervalStart, intervalEnd);
/* Paint mote events */
int lineHeightOffset = FIRST_MOTE_PIXEL_OFFSET;
for (int mIndex = 0; mIndex < allMoteEvents.size(); mIndex++) {
if (showRadioRXTX) {
RadioRXTXEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).radioRXTXEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
if (showRadioChannels) {
RadioChannelEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).radioChannelEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
if (showRadioHW) {
RadioHWEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).radioHWEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
if (showLEDs) {
LEDEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).ledEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
if (showLogOutputs) {
LogEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).logEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
if (showWatchpoints) {
WatchpointEvent firstEvent = getFirstIntervalEvent(allMoteEvents.get(mIndex).watchpointEvents, intervalStart);
if (firstEvent != null) {
firstEvent.paintInterval(g, lineHeightOffset, (int) startTime, intervalEnd);
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
lineHeightOffset += EVENT_PIXEL_HEIGHT;
}
/* Draw vertical time marker (mouse dragged) */
drawMouseTime(g, intervalStart, intervalEnd);
}
private <T extends MoteEvent> T getFirstIntervalEvent(ArrayList<T> events, long time) {
/* TODO IMPLEMENT ME: Binary search */
int nrEvents = events.size();
if (nrEvents == 0) {
return null;
}
if (nrEvents == 1) {
events.get(0);
}
int ev = 0;
while (ev < nrEvents && events.get(ev).time < time) {
ev++;
}
ev
if (ev < 0) {
ev = 0;
}
if (ev >= events.size()) {
return events.get(events.size()-1);
}
return events.get(ev);
}
private void drawTimeRule(Graphics g, long start, long end) {
long millis;
/* Paint 10ms and 100 ms markers */
g.setColor(Color.GRAY);
millis = start - (start % 100);
while (millis <= end) {
if (millis % 100 == 0) {
g.drawLine(
(int)(millis - startTime), (int)0,
(int)(millis - startTime), (int)TIME_MARKER_PIXEL_HEIGHT);
} else {
g.drawLine(
(int)(millis - startTime), (int)0,
(int)(millis - startTime), (int)TIME_MARKER_PIXEL_HEIGHT/2);
}
millis += 10;
}
}
private void drawMouseTime(Graphics g, long start, long end) {
if (mouseTimePositionX >= 0) {
String str = "Time: " + (mouseTimePositionX + startTime);
int h = g.getFontMetrics().getHeight();
int w = g.getFontMetrics().stringWidth(str) + 6;
int y=mouseTimePositionY<getHeight()/2?0:getHeight()-h;
int delta = mouseTimePositionX + w > end?w:0; /* Don't write outside visible area */
/* Line */
g.setColor(Color.GRAY);
g.drawLine(
mouseTimePositionX, 0,
mouseTimePositionX, getHeight());
/* Text box */
g.setColor(Color.DARK_GRAY);
g.fillRect(
mouseTimePositionX-delta, y,
w, h);
g.setColor(Color.BLACK);
g.drawRect(
mouseTimePositionX-delta, y,
w, h);
g.setColor(Color.WHITE);
g.drawString(str,
mouseTimePositionX+3-delta,
y+h-1);
}
}
public int getWidth() {
return (int) (simulation.getSimulationTime() - startTime);
}
public String getToolTipText(MouseEvent event) {
if (event.getPoint().y <= FIRST_MOTE_PIXEL_OFFSET) {
return "<html>Click to display time</html>";
}
/* Mote */
int mote = (event.getPoint().y-FIRST_MOTE_PIXEL_OFFSET)/paintedMoteHeight;
if (mote < 0 || mote >= allMoteEvents.size()) {
return null;
}
String tooltip = "<html>Mote: " + allMoteEvents.get(mote).mote + "<br>";
/* Time */
long time = event.getPoint().x + startTime;
tooltip += "Time: " + time + "<br>";
/* Event */
ArrayList<? extends MoteEvent> events = null;
int evMatched = 0;
int evMouse = ((event.getPoint().y-FIRST_MOTE_PIXEL_OFFSET) % paintedMoteHeight) / EVENT_PIXEL_HEIGHT;
if (showRadioRXTX) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).radioRXTXEvents;
}
evMatched++;
}
if (showRadioChannels) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).radioChannelEvents;
}
evMatched++;
}
if (showRadioHW) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).radioHWEvents;
}
evMatched++;
}
if (showLEDs) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).ledEvents;
}
evMatched++;
}
if (showLogOutputs) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).logEvents;
}
evMatched++;
}
if (showWatchpoints) {
if (evMatched == evMouse) {
events = allMoteEvents.get(mote).watchpointEvents;
}
evMatched++;
}
if (events != null) {
MoteEvent ev = getFirstIntervalEvent(events, time);
if (ev != null && time >= ev.time) {
tooltip += ev + "<br>";
}
}
tooltip += "</html>";
return tooltip;
}
}
class MoteRuler extends JPanel {
public MoteRuler() {
setPreferredSize(new Dimension(35, 1));
setToolTipText("");
setBackground(COLOR_BACKGROUND);
final JPopupMenu popupMenu = new JPopupMenu();
final JMenuItem removeItem = new JMenuItem(removeMoteAction);
removeItem.setText("Remove from timeline");
popupMenu.add(removeItem);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
Mote m = getMote(e.getPoint());
if (m == null) {
return;
}
removeItem.setText("Remove from timeline: " + m);
removeItem.putClientProperty("mote", m);
popupMenu.show(MoteRuler.this, e.getX(), e.getY());
}
});
}
private Mote getMote(Point p) {
if (p.y < FIRST_MOTE_PIXEL_OFFSET) {
return null;
}
int m = (p.y-FIRST_MOTE_PIXEL_OFFSET)/paintedMoteHeight;
if (m < allMoteEvents.size()) {
return allMoteEvents.get(m).mote;
}
return null;
}
protected void paintComponent(Graphics g) {
g.setColor(COLOR_BACKGROUND);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.setFont(new Font("SansSerif", Font.PLAIN, paintedMoteHeight));
int y = FIRST_MOTE_PIXEL_OFFSET-EVENT_PIXEL_HEIGHT/2+paintedMoteHeight;
for (MoteEvents moteLog: allMoteEvents) {
String str = "??";
if (moteLog.mote.getInterfaces().getMoteID() != null) {
str = "" + moteLog.mote.getInterfaces().getMoteID().getMoteID();
}
int w = g.getFontMetrics().stringWidth(str) + 1;
/*g.drawRect(0, y, getWidth()-1, paintedMoteHeight);*/
g.drawString(str, getWidth() - w, y);
y += paintedMoteHeight;
}
}
public String getToolTipText(MouseEvent event) {
Point p = event.getPoint();
Mote m = getMote(p);
if (m == null)
return null;
return "<html>" + m + "<br>Click mote for options</html>";
}
}
/* Event classes */
abstract class MoteEvent {
long time;
public MoteEvent(long time) {
this.time = time;
}
}
class RadioRXTXEvent extends MoteEvent {
RadioRXTXEvent prev = null;
RadioRXTXEvent next = null;
RadioEvent state = null;
public RadioRXTXEvent(long time, RadioEvent ev) {
super(time);
this.state = ev;
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
RadioRXTXEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
/* ev = ev.next;
continue;*/
w = 1;
}
if (ev.state == RadioEvent.TRANSMISSION_STARTED) {
g.setColor(Color.BLUE);
} else if (ev.state == RadioEvent.RECEPTION_STARTED) {
g.setColor(Color.GREEN);
} else if (ev.state == RadioEvent.RECEPTION_INTERFERED) {
g.setColor(Color.RED);
} else {
/*g.setColor(Color.LIGHT_GRAY);*/
ev = ev.next;
continue;
}
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
public String toString() {
if (state == RadioEvent.TRANSMISSION_STARTED) {
return "Radio TX started at " + time + "<br>";
} else if (state == RadioEvent.TRANSMISSION_FINISHED) {
return "Radio TX finished at " + time + "<br>";
} else if (state == RadioEvent.RECEPTION_STARTED) {
return "Radio RX started at " + time + "<br>";
} else if (state == RadioEvent.RECEPTION_FINISHED) {
return "Radio RX finished at " + time + "<br>";
} else if (state == RadioEvent.RECEPTION_INTERFERED) {
return "Radio reception was interfered at " + time + "<br>";
}
return "Unknown event<br>";
}
}
class RadioChannelEvent extends MoteEvent {
RadioChannelEvent prev = null;
RadioChannelEvent next = null;
public RadioChannelEvent(long time) {
super(time);
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
RadioChannelEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
ev = ev.next;
continue;
}
g.setColor(Color.GRAY);
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
}
class RadioHWEvent extends MoteEvent {
RadioHWEvent prev = null;
RadioHWEvent next = null;
boolean on;
public RadioHWEvent(long time, boolean on) {
super(time);
this.on = on;
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
RadioHWEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
ev = ev.next;
continue;
}
if (!ev.on) {
ev = ev.next;
continue;
}
g.setColor(Color.GRAY);
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
public String toString() {
return "Radio HW was turned " + (on?"on":"off") + " at time " + time + "<br>";
}
}
class LEDEvent extends MoteEvent {
LEDEvent prev = null;
LEDEvent next = null;
boolean red;
boolean green;
boolean blue;
Color color;
public LEDEvent(long time, boolean red, boolean green, boolean blue) {
super(time);
this.red = red;
this.green = green;
this.blue = blue;
this.color = new Color(red?255:0, green?255:0, blue?255:0);
prev = null;
next = null;
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
LEDEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
ev = ev.next;
continue;
}
if (!ev.red && !ev.green && !ev.blue) {
g.setColor(Color.WHITE);
} else if (ev.red && ev.green && ev.blue) {
g.setColor(Color.LIGHT_GRAY);
} else {
g.setColor(ev.color);
}
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
public String toString() {
return
"LED state:<br>" +
"Red = " + (red?"ON":"OFF") + "<br>" +
"Green = " + (green?"ON":"OFF") + "<br>" +
"Blue = " + (blue?"ON":"OFF") + "<br>";
}
}
class LogEvent extends MoteEvent {
LogEvent prev = null;
LogEvent next = null;
public LogEvent(long time) {
super(time);
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
LogEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
ev = ev.next;
continue;
}
g.setColor(Color.GREEN);
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
}
class WatchpointEvent extends MoteEvent {
WatchpointEvent prev = null;
WatchpointEvent next = null;
public WatchpointEvent(long time) {
super(time);
}
public void paintInterval(Graphics g, int lineHeightOffset, int startTime, long end) {
WatchpointEvent ev = this;
while (ev != null && ev.time < end) {
int w;
/* Paint until next event or end of clip */
if (ev.next != null) {
w = (int) (ev.next.time - ev.time);
} else {
w = (int) (end - ev.time); /* No more events */
}
/* Ignore painting events with zero width */
if (w == 0) {
ev = ev.next;
continue;
}
g.setColor(Color.BLUE);
g.fillRect(
(int)(ev.time - startTime), lineHeightOffset,
w, EVENT_PIXEL_HEIGHT
);
ev = ev.next;
}
}
}
class MoteEvents {
Mote mote;
ArrayList<RadioRXTXEvent> radioRXTXEvents;
ArrayList<RadioChannelEvent> radioChannelEvents;
ArrayList<RadioHWEvent> radioHWEvents;
ArrayList<LEDEvent> ledEvents;
ArrayList<LogEvent> logEvents;
ArrayList<WatchpointEvent> watchpointEvents;
private RadioRXTXEvent lastRadioRXTXEvent = null;
private RadioChannelEvent lastRadioChannelEvent = null;
private RadioHWEvent lastRadioHWEvent = null;
private LEDEvent lastLEDEvent = null;
private LogEvent lastLogEvent = null;
private WatchpointEvent lastWatchpointEvent = null;
public MoteEvents(Mote mote) {
this.mote = mote;
this.radioRXTXEvents = new ArrayList<RadioRXTXEvent>();
this.radioChannelEvents = new ArrayList<RadioChannelEvent>();
this.radioHWEvents = new ArrayList<RadioHWEvent>();
this.ledEvents = new ArrayList<LEDEvent>();
this.logEvents = new ArrayList<LogEvent>();
this.watchpointEvents = new ArrayList<WatchpointEvent>();
}
public void addRadioRXTX(RadioRXTXEvent ev) {
/* Link with previous events */
if (lastRadioRXTXEvent != null) {
ev.prev = lastRadioRXTXEvent;
lastRadioRXTXEvent.next = ev;
}
lastRadioRXTXEvent = ev;
radioRXTXEvents.add(ev);
}
public void addRadioChannel(RadioChannelEvent ev) {
/* Link with previous events */
if (lastRadioChannelEvent != null) {
ev.prev = lastRadioChannelEvent;
lastRadioChannelEvent.next = ev;
}
lastRadioChannelEvent = ev;
/* TODO XXX Requires MSPSim changes */
radioChannelEvents.add(ev);
}
public void addRadioHW(RadioHWEvent ev) {
/* Link with previous events */
if (lastRadioHWEvent != null) {
ev.prev = lastRadioHWEvent;
lastRadioHWEvent.next = ev;
}
lastRadioHWEvent = ev;
radioHWEvents.add(ev);
}
public void addLED(LEDEvent ev) {
/* Link with previous events */
if (lastLEDEvent != null) {
ev.prev = lastLEDEvent;
lastLEDEvent.next = ev;
}
lastLEDEvent = ev;
ledEvents.add(ev);
}
public void addLog(LogEvent ev) {
/* Link with previous events */
if (lastLogEvent != null) {
ev.prev = lastLogEvent;
lastLogEvent.next = ev;
}
lastLogEvent = ev;
logEvents.add(ev);
}
public void addWatchpoint(WatchpointEvent ev) {
/* Link with previous events */
if (lastWatchpointEvent != null) {
ev.prev = lastWatchpointEvent;
lastWatchpointEvent.next = ev;
}
lastWatchpointEvent = ev;
watchpointEvents.add(ev);
}
}
}
|
package kawa.standard;
import kawa.lang.*;
/**
* The Syntax transformer that re-writes the "define" Scheme primitive.
* Currently, only handles top-level definitions.
* @author Per Bothner
*/
public class define extends Syntax implements Printable
{
public Expression rewrite (Object obj, Interpreter interp)
throws kawa.lang.WrongArguments
{
if (obj instanceof Pair)
{
Pair p1 = (Pair) obj;
if (p1.car instanceof Symbol && p1.cdr instanceof Pair)
{
Pair p2 = (Pair) p1.cdr;
if (p2.cdr == List.Empty)
{
SetExp result = new SetExp ((Symbol)p1.car,
interp.rewrite (p2.car));
result.setDefining (true);
return result;
}
}
else if (p1.car instanceof Pair)
{
Pair p2 = (Pair) p1.car;
if (p2.car instanceof Symbol)
{
Symbol name = (Symbol) p2.car;
LambdaExp lexp = new LambdaExp (p2.cdr, p1.cdr, interp);
lexp.setName (name.toString ());
SetExp result = new SetExp (name, lexp);
result.setDefining (true);
return result;
}
}
}
return interp.syntaxError ("invalid syntax for define");
}
}
|
package org.eclipse.xtext.parser;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.testlanguages.ReferenceGrammarTestLanguageStandaloneSetup;
import org.eclipse.xtext.testlanguages.SimpleExpressionsTestLanguageStandaloneSetup;
import org.eclipse.xtext.testlanguages.TreeTestLanguageStandaloneSetup;
import com.google.common.collect.Iterables;
/**
* @author Jan Khnlein - Initial contribution and API
*/
public class PartialParsingPerformanceTest extends AbstractPartialParserTest {
private static final int NUM_ELEMENTS = 100;
public void testExpression() throws Exception {
with(SimpleExpressionsTestLanguageStandaloneSetup.class);
String d = ")+d)\r\n";
String a_b = "(a+(b*\r\n";
StringBuffer modelBuffer = new StringBuffer(NUM_ELEMENTS * (a_b.length() + d.length()) + 1);
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(a_b);
}
modelBuffer.append("c");
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(d);
}
String model = modelBuffer.toString();
IParseResult parseResult = getParseResult(model);
IParseResult reparse = reparse(parseResult, model.indexOf('c'), 1, "Hugo");
assertFalse(reparse.hasSyntaxErrors());
}
public void testReference() throws Exception {
with(ReferenceGrammarTestLanguageStandaloneSetup.class);
StringBuffer modelBuffer = new StringBuffer();
modelBuffer.append("spielplatz 17 {\n");
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" kind ( Herbert");
modelBuffer.append(i);
modelBuffer.append(" 11 )\n");
}
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" erwachsener ( Hugo");
modelBuffer.append(i);
modelBuffer.append(" 111 )\n");
}
modelBuffer.append(" erwachsener ( Sven 112 )\n");
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" spielzeug ( Schaufel ROT )\n");
}
modelBuffer.append("}\n");
String model = modelBuffer.toString();
IParseResult parseResult = getParseResult(model);
IParseResult reparse = reparse(parseResult, model.indexOf("Sven"), 4, "Peter");
if(reparse.hasSyntaxErrors()) {
fail("Unexpected parse errors " + Iterables.toString(reparse.getSyntaxErrors())) ;
}
}
public void testReferenceWithErrorAtEnd() throws Exception {
with(ReferenceGrammarTestLanguageStandaloneSetup.class);
StringBuffer modelBuffer = new StringBuffer();
modelBuffer.append("spielplatz 17 {\n");
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" kind ( Herbert");
modelBuffer.append(i);
modelBuffer.append(" 11 )\n");
}
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" erwachsener ( Hugo");
modelBuffer.append(i);
modelBuffer.append(" 111 )\n");
}
modelBuffer.append(" erwachsener ( Sven 112 )\n");
for(int i=0; i<NUM_ELEMENTS; ++i) {
modelBuffer.append(" spielzeug ( Schaufel ROT )\n");
}
modelBuffer.append(" kind (Herbert " + NUM_ELEMENTS + 1 + "\n");
modelBuffer.append("}\n");
String model = modelBuffer.toString();
IParseResult parseResult = getParseResultAndExpect(model, 1);
assertEquals(1, Iterables.size(parseResult.getSyntaxErrors()));
IParseResult reparse = reparse(parseResult, model.indexOf("Sven"), 4, "Peter");
assertEquals(1, Iterables.size(reparse.getSyntaxErrors()));
assertTrue(reparse.hasSyntaxErrors());
}
public void testBug_255015() throws Exception {
with(TreeTestLanguageStandaloneSetup.class);
StringBuffer modelBuffer = new StringBuffer(NUM_ELEMENTS * 128);
for(int i = 0; i < Math.sqrt(NUM_ELEMENTS) * 2; i++) {
modelBuffer.append("parent (\"Teststring\") {\n");
for (int j = 0; j < Math.sqrt(NUM_ELEMENTS) * 2; j++) {
modelBuffer.append(" child (\"Teststring\"){};");
}
modelBuffer.append("};");
}
String model = modelBuffer.toString();
XtextResource resource = getResourceFromString(model);
assertFalse(resource.getParseResult().hasSyntaxErrors());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.