answer
stringlengths 17
10.2M
|
|---|
package es.sinjava.basico;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import es.sinjava.rest.model.Alps;
import es.sinjava.rest.model.Category;
import es.sinjava.rest.model.Descriptor;
import es.sinjava.rest.model.DinamicBean;
import es.sinjava.rest.model.HateoasRoot;
import es.sinjava.rest.model.Item;
import es.sinjava.rest.model.ModelHateoas;
public class App {
public static void main(String[] args) throws ClientHandlerException,
UniformInterfaceException, IOException {
String destiny = "http://localhost:8888/";
if (args != null && args.length > 1 && args[0] != null) {
System.out.println("Capturada la url");
destiny = args[0];
}
Client client = Client.create();
WebResource webResource = client.resource(destiny);
ObjectMapper om = new ObjectMapper();
ClientResponse response2 = webResource.accept("application/json").get(
ClientResponse.class);
if (response2.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response2.getStatus());
}
HateoasRoot hateoas = om.readValue(response2.getEntity(String.class),
HateoasRoot.class);
System.out.println(" Recibidos " + hateoas.get_links().size());
for (Entry<String, Item> item : hateoas.get_links().entrySet()) {
System.out.println("-> " + item.getKey() + " - "
+ item.getValue().getHref());
}
// REcuperamos los descriptores del profile:
URL profileURL = hateoas.get_links().get("profile").getHref();
WebResource webResource2 = client.resource(profileURL.toString());
ClientResponse profileResponse = webResource2
.accept("application/json").get(ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
HateoasRoot profiles = om.readValue(
profileResponse.getEntity(String.class), HateoasRoot.class);
System.out.println(profiles.get_links().size());
profiles.get_links().remove("self");
System.out.println(profiles.get_links().size());
Map<String, Alps> mapaModels = new HashMap<>();
for (Entry<String, Item> hateoasEntitys : profiles.get_links()
.entrySet()) {
webResource2 = client.resource(hateoasEntitys.getValue().getHref()
.toString());
profileResponse = webResource2.accept("application/json").get(
ClientResponse.class);
if (profileResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ profileResponse.getStatus());
}
ModelHateoas model = om
.readValue(profileResponse.getEntity(String.class),
ModelHateoas.class);
mapaModels.put(hateoasEntitys.getKey(), model.getAlps());
}
List<DinamicBean> dinamicBeanList = new ArrayList<>();
for (String fieldSelected : mapaModels.keySet()) {
for (Descriptor item : mapaModels.get(fieldSelected)
.getDescriptors()) {
if (item.getType() == null && item.getDescriptors() != null) {
System.out.println(item);
DinamicBean dinamicBean = dinamicBeanForDescriptor(
fieldSelected, hateoas.get_links(), item);
dinamicBeanList.add(dinamicBean);
}
}
}
System.out.println("Sacabao" + dinamicBeanList.size());
}
private static DinamicBean dinamicBeanForDescriptor(String fieldSelected,
Map<String, Item> urls, Descriptor desc) {
DinamicBean db = new DinamicBean();
db.setName(fieldSelected);
db.setUrl(urls.get(fieldSelected).getHref());
db.setProperty(new HashMap<>());
for (Descriptor property : desc.getDescriptors()) {
if (property.getDoc() == null) {
db.getProperty().put(property.getName(), Category.STRING);
} else if (property.getDoc() != null) {
db.getProperty().put(property.getName(), Category.ENUMERATED);
}
}
return db;
}
}
|
package com.foundationdb.server.service.is;
import com.foundationdb.ais.AISCloner;
import com.foundationdb.ais.model.AISBuilder;
import com.foundationdb.ais.model.AkibanInformationSchema;
import com.foundationdb.ais.model.Column;
import com.foundationdb.ais.model.DefaultNameGenerator;
import com.foundationdb.ais.model.Group;
import com.foundationdb.ais.model.Index;
import com.foundationdb.ais.model.Join;
import com.foundationdb.ais.model.NameGenerator;
import com.foundationdb.ais.model.Parameter;
import com.foundationdb.ais.model.Routine;
import com.foundationdb.ais.model.SQLJJar;
import com.foundationdb.ais.model.Sequence;
import com.foundationdb.ais.model.Table;
import com.foundationdb.ais.model.TableName;
import com.foundationdb.ais.model.View;
import com.foundationdb.ais.util.ChangedTableDescription;
import com.foundationdb.qp.memoryadapter.MemoryAdapter;
import com.foundationdb.qp.memoryadapter.MemoryTableFactory;
import com.foundationdb.qp.row.Row;
import com.foundationdb.qp.rowtype.Schema;
import com.foundationdb.server.service.security.SecurityService;
import com.foundationdb.server.service.session.Session;
import com.foundationdb.server.store.SchemaManager;
import com.foundationdb.server.store.TableChanges.ChangeSet;
import com.foundationdb.server.store.format.DummyStorageFormatRegistry;
import com.foundationdb.server.store.format.StorageFormatRegistry;
import com.foundationdb.server.types.TInstance;
import com.foundationdb.server.types.mcompat.mtypes.MNumeric;
import com.foundationdb.server.types.mcompat.mtypes.MString;
import com.foundationdb.server.types.value.ValueSource;
import org.junit.Before;
import org.junit.Test;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import static com.foundationdb.qp.memoryadapter.MemoryGroupCursor.GroupScan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class BasicInfoSchemaTablesServiceImplTest {
private static final String I_S = TableName.INFORMATION_SCHEMA;
private AkibanInformationSchema ais;
private SchemaManager schemaManager;
private NameGenerator nameGenerator;
private BasicInfoSchemaTablesServiceImpl bist;
private MemoryAdapter adapter;
@Before
public void setUp() throws Exception {
ais = BasicInfoSchemaTablesServiceImpl.createTablesToRegister();
schemaManager = new MockSchemaManager(ais);
nameGenerator = new DefaultNameGenerator();
createTables();
bist = new BasicInfoSchemaTablesServiceImpl(schemaManager, null, null);
bist.attachFactories(ais);
adapter = new MemoryAdapter(new Schema(ais), null, null);
}
private static void simpleTable(AISBuilder builder, String group, String schema, String table, String parentName, boolean withPk) {
builder.table(schema, table);
builder.column(schema, table, "id", 0, "INT", null, null, false, false, null, null);
if(parentName != null) {
builder.column(schema, table, "pid", 1, "INT", null, null, false, false, null, null);
}
if(withPk) {
builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, "id", 0, true, null);
}
if(parentName == null) {
builder.createGroup(group, schema);
} else {
String joinName = table + "/" + parentName;
builder.joinTables(joinName, schema, parentName, schema, table);
builder.joinColumns(joinName, schema, parentName, "id", schema, table, "pid");
builder.addJoinToGroup(group, joinName, 0);
}
}
private void createTables() throws Exception {
AISBuilder builder = new AISBuilder(ais, nameGenerator, schemaManager.getStorageFormatRegistry());
{
String schema = "test";
String table = "foo";
builder.table(schema, table);
builder.column(schema, table, "c1", 0, "INT", null, null, false, false, null, null);
builder.column(schema, table, "c2", 1, "DOUBLE", null, null, true, false, null, null);
builder.createGroup(table, schema);
builder.addTableToGroup(table, schema, table);
// no defined pk or indexes
}
{
String schema = "test";
String table = "bar";
builder.table(schema, table);
builder.column(schema, table, "col", 0, "BIGINT", null, null, false, false, null, null);
builder.column(schema, table, "name", 1, "INT", null, null, false, false, null, null);
builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, "col", 0, true, null);
builder.createGroup(table, schema);
schema = "test";
String childTable = table + "2";
String indexName = "foo_name";
builder.table(schema, childTable);
builder.column(schema, childTable, "foo", 0, "INT", null, null, true, false, null, null);
builder.column(schema, childTable, "pid", 1, "INT", null, null, true, false, null, null);
String joinName = childTable + "/" + table;
builder.joinTables(joinName, schema, table, schema, childTable);
builder.joinColumns(joinName, schema, table, "col", schema, childTable, "pid");
builder.addJoinToGroup(table, joinName, 0);
builder.groupIndex(table, indexName, false, Index.JoinType.RIGHT);
builder.groupIndexColumn(table, indexName, schema, childTable, "foo", 0);
builder.groupIndexColumn(table, indexName, schema, table, "name", 1);
}
{
String schema = "zap";
String table = "pow";
String indexName = "name_value";
builder.table(schema, table);
builder.column(schema, table, "name", 0, "VARCHAR", 32L, null, true, false, null, null);
builder.column(schema, table, "value", 1, "DECIMAL", 10L, 2L, true, false, null, null);
builder.index(schema, table, indexName, true, Index.UNIQUE_KEY_CONSTRAINT);
builder.indexColumn(schema, table, indexName, "name", 0, true, null);
builder.indexColumn(schema, table, indexName, "value", 1, true, null);
builder.createGroup(table, schema);
builder.addTableToGroup(table, schema, table);
// no defined pk
}
{
// Added for bug1019905: Last table only had GFK show up in constraints/key_column_usage if it had a GFK
String schema = "zzz";
String table = schema + "1";
builder.table(schema, table);
builder.column(schema, table, "id", 0, "INT", null, null, false, false, null, null);
builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, "id", 0, true, null);
builder.createGroup(table, schema);
String childTable = schema + "2";
builder.table(schema, childTable);
builder.column(schema, childTable, "id", 0, "INT", null, null, false, false, null, null);
builder.column(schema, childTable, "one_id", 1, "INT", null, null, true, false, null, null);
builder.index(schema, childTable, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, childTable, Index.PRIMARY_KEY_CONSTRAINT, "id", 0, true, null);
String joinName = childTable + "/" + table;
builder.joinTables(joinName, schema, table, schema, childTable);
builder.joinColumns(joinName, schema, table, "id", schema, childTable, "one_id");
builder.addJoinToGroup(table, joinName, 0);
}
{
// bug1024965: Grouping constraints not in depth order
/*
* r
* |-m
* | |-b
* | |-x
* |-a
* |-w
*/
String schema = "gco";
String group = "r";
simpleTable(builder, group, schema, "r", null, true);
simpleTable(builder, group, schema, "m", "r", true);
simpleTable(builder, group, schema, "b", "m", true);
simpleTable(builder, group, schema, "x", "b", false);
simpleTable(builder, group, schema, "a", "r", true);
simpleTable(builder, group, schema, "w", "a", false);
}
{
/* Sequence testing */
String schema = "test";
String sequence = "sequence";
builder.sequence(schema, sequence, 1, 1, 0, 1000, false);
sequence = sequence + "1";
builder.sequence(schema, sequence, 1000, -1, 0, 1000, false);
String table = "seq-table";
sequence = "_col_sequence";
builder.table(schema, table);
builder.column(schema, table, "col", 0, "BIGINT", null, null, false, false, null, null);
builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, "col", 0, true, null);
builder.sequence(schema, sequence, 1, 1, 0, 1000, false);
builder.columnAsIdentity(schema, table, "col", sequence, true);
builder.createGroup(table, schema);
builder.addTableToGroup(table, schema, table);
}
{
String schema = "test";
String table = "defaults";
builder.table(schema, table);
builder.column(schema, table, "col1", 0, "VARCHAR", 10L, null, false, false, null, null, "fred", null);
builder.column(schema, table, "col2", 1, "VARCHAR", 10L, null, false, false, null, null, "", null);
builder.column(schema, table, "col3", 2, "BIGINT", null, null, false, false, null, null, "0", null);
builder.column(schema, table, "col4", 3, "DATE", null, null, false, false, null, null, null, "current_date");
builder.createGroup(table, schema);
builder.addTableToGroup(table, schema, table);
}
builder.basicSchemaIsComplete();
builder.groupingIsComplete();
Map<Table, Integer> ordinalMap = new HashMap<>();
List<Table> remainingTables = new ArrayList<>();
// Add all roots
for(Table table : ais.getTables().values()) {
if(table.isRoot()) {
remainingTables.add(table);
}
}
while(!remainingTables.isEmpty()) {
Table table = remainingTables.remove(remainingTables.size()-1);
ordinalMap.put(table, 0);
for(Index index : table.getIndexesIncludingInternal()) {
index.computeFieldAssociations(ordinalMap);
}
// Add all immediate children
for(Join join : table.getChildJoins()) {
remainingTables.add(join.getChild());
}
}
for(Group group : ais.getGroups().values()) {
for(Index index : group.getIndexes()) {
index.computeFieldAssociations(ordinalMap);
}
}
{
String schema = "test";
String view = "voo";
Map<TableName,Collection<String>> refs = new HashMap<>();
refs.put(TableName.create(schema, "foo"), Arrays.asList("c1", "c2"));
builder.view(schema, view,
"CREATE VIEW voo(c1,c2) AS SELECT c2,c1 FROM foo", new Properties(),
refs);
builder.column(schema, view, "c1", 0, "DOUBLE", null, null, true, false, null, null);
builder.column(schema, view, "c2", 1, "INT", null, null, false, false, null, null);
}
builder.sqljJar("test", "ajar",
new URL("https://example.com/procs/ajar.jar"));
builder.routine("test", "proc1", "java", Routine.CallingConvention.JAVA);
builder.parameter("test", "proc1", "n1", Parameter.Direction.IN,
"bigint", null, null);
builder.parameter("test", "proc1", "s1", Parameter.Direction.IN,
"varchar", 16L, null);
builder.parameter("test", "proc1", "n2", Parameter.Direction.IN,
"decimal", 10L, 5L);
builder.parameter("test", "proc1", null, Parameter.Direction.OUT,
"varchar", 100L, null);
builder.routineExternalName("test", "proc1", "test", "ajar",
"com.foundationdb.procs.Proc1", "call");
}
private MemoryTableFactory getFactory(TableName name) {
Table table = ais.getTable(name);
assertNotNull("No such table: " + name, table);
MemoryTableFactory factory = MemoryAdapter.getMemoryTableFactory(table);
assertNotNull("No factory for table " + name, factory);
return factory;
}
/**
* Performing a full scan and compare against expected rows. This skips all I_S
* rows and returns that as a value, as double checking all those in this test
* excessive.
*
* @param expectedRows Expected, non-I_S rows.
* @param scan Scan providing actual rows.
*
* @return The number of I_S rows seen.
*/
private static int scanAndCompare(Object[][] expectedRows, GroupScan scan) {
int skippedRows = 0;
Row row;
int rowIndex = 0;
while((row = scan.next()) != null) {
if(rowIndex == expectedRows.length) {
fail("More actual rows than expected");
}
assertEquals("Expected column count, row " + rowIndex,
expectedRows[rowIndex].length, row.rowType().nFields());
for(int colIndex = 0; colIndex < expectedRows[rowIndex].length; ++colIndex) {
final String msg = "row " + rowIndex + ", col " + colIndex;
final Object expected = expectedRows[rowIndex][colIndex];
final ValueSource actual = row.value(colIndex);
if(expected == null || actual.isNull()) {
Column column = row.rowType().table().getColumn(colIndex);
if(!Boolean.TRUE.equals(column.getNullable())) {
fail(String.format("Expected (%s) or actual (%s) NULL for column (%s) declared NOT NULL",
expected, actual, column));
}
}
if(expected == null) {
assertEquals(msg + " isNull", true, actual.isNull());
} else if(expected instanceof TInstance) {
assertEquals(msg + " (type only)", expected, actual.tInstance());
} else if(expected instanceof String) {
if(colIndex == 0 && actual.getString().equals(I_S)) {
--rowIndex;
++skippedRows;
break;
}
assertEquals(msg, expected, actual.getString());
} else if(expected instanceof Integer) {
assertEquals(msg, expected, actual.getInt32());
} else if(expected instanceof Long) {
assertEquals(msg, expected, actual.getInt64());
} else if(expected instanceof Boolean) {
assertEquals(msg, (Boolean)expected ? "YES" : "NO", actual.getString());
} else if(expected instanceof Text) {
assertEquals(msg, ((Text)expected).getText(), actual.getString());
} else {
fail("Unsupported type: " + expected.getClass());
}
}
++rowIndex;
}
if(rowIndex < expectedRows.length) {
fail("More expected rows than actual");
}
scan.close();
return skippedRows;
}
static class Text {
private String text;
public Text(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
private static final TInstance LONG = MNumeric.BIGINT.instance(false);
private static final TInstance LONG_NULL = MNumeric.BIGINT.instance(true);
private static final TInstance VARCHAR = MString.VARCHAR.instance(128,true);
@Test
public void schemataScan() {
final Object[][] expected = {
{ "gco", null, null, null, null, LONG },
{ "test", null, null, null, null, LONG },
{ "zap", null, null, null, null, LONG },
{ "zzz", null, null, null, null, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.SCHEMATA).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S schemas", 1, skipped);
}
@Test
public void tablesScan() {
final Object[][] expected = {
{ "gco", "a", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "gco", "b", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "gco", "m", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "gco", "r", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "gco", "w", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "gco", "x", "TABLE", LONG_NULL, null, "gco.r", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "test", "bar", "TABLE", LONG_NULL, null, "test.bar", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "test", "bar2", "TABLE", LONG_NULL, null, "test.bar", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "test", "defaults", "TABLE", LONG_NULL, null, "test.defaults", I_S, VARCHAR, I_S, VARCHAR, LONG},
{ "test", "foo", "TABLE", LONG_NULL, null, "test.foo", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "test", "seq-table", "TABLE", LONG_NULL, null, "test.seq-table", I_S, VARCHAR, I_S, VARCHAR, LONG},
{ "zap", "pow", "TABLE", LONG_NULL, null, "zap.pow", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "zzz", "zzz1", "TABLE", LONG_NULL, null, "zzz.zzz1", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "zzz", "zzz2", "TABLE", LONG_NULL, null, "zzz.zzz1", I_S, VARCHAR, I_S, VARCHAR, LONG },
{ "test", "voo", "VIEW", null, null, null, null, null, null, null, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.TABLES).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S tables", 22, skipped);
}
@Test
public void columnsScan() {
final Object[][] expected = {
{ "gco", "a", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null, LONG},
{ "gco", "a", "pid", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null, LONG},
{ "gco", "b", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "b", "pid", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "m", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "m", "pid", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "r", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "w", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "w", "pid", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "x", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "gco", "x", "pid", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null, LONG},
{ "test", "bar", "col", 0L, "bigint", false, 8L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null, LONG},
{ "test", "bar", "name", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "bar2", "foo", 0L, "int", true, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "bar2", "pid", 1L, "int", true, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "defaults", "col1", 0L, "varchar", false, 10L, null, null, 1L, I_S, VARCHAR, I_S, VARCHAR, null, null, null, null, null, null, null, null, "fred", LONG},
{ "test", "defaults", "col2", 1L, "varchar", false, 10L, null, null, 1L, I_S, VARCHAR, I_S, VARCHAR, null, null, null, null, null, null, null, null, "", LONG},
{ "test", "defaults", "col3", 2L, "bigint", false, 8L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, "0", LONG},
{ "test", "defaults", "col4", 3L, "date", false, 3L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, "current_date()", LONG},
{ "test", "foo", "c1", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "foo", "c2", 1L, "double", true, 8L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "seq-table", "col", 0L, "bigint", false, 8L, null, null, 0L, null, null, null, null, "test", "_col_sequence", "BY DEFAULT", 1L, 1L, 0L, 1000L, "NO", null, LONG},
{ "zap", "pow", "name", 0L, "varchar", true, 32L, null, null, 1L, I_S, VARCHAR, I_S, VARCHAR, null, null, null, null, null, null, null, null, null,LONG},
{ "zap", "pow", "value", 1L, "decimal", true, 5L, 10L, 2L, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "zzz", "zzz1", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "zzz", "zzz2", "id", 0L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "zzz", "zzz2", "one_id", 1L, "int", true, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "voo", "c1", 0L, "double", true, 8L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
{ "test", "voo", "c2", 1L, "int", false, 4L, null, null, 0L, null, null, null, null, null, null, null, null, null, null, null, null, null,LONG},
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.COLUMNS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S columns", 155, skipped);
}
@Test
public void tableConstraintsScan() {
final Object[][] expected = {
{ "gco", "a", "a/r", "GROUPING", LONG },
{ "gco", "a", "PRIMARY", "PRIMARY KEY", LONG },
{ "gco", "b", "b/m", "GROUPING", LONG },
{ "gco", "b", "PRIMARY", "PRIMARY KEY", LONG },
{ "gco", "m", "m/r", "GROUPING", LONG },
{ "gco", "m", "PRIMARY", "PRIMARY KEY", LONG },
{ "gco", "r", "PRIMARY", "PRIMARY KEY", LONG },
{ "gco", "w", "w/a", "GROUPING", LONG },
{ "gco", "x", "x/b", "GROUPING", LONG },
{ "test", "bar", "PRIMARY", "PRIMARY KEY", LONG },
{ "test", "bar2", "bar2/bar", "GROUPING", LONG },
{ "test", "seq-table", "PRIMARY", "PRIMARY KEY", LONG},
{ "zap", "pow", "name_value", "UNIQUE", LONG },
{ "zzz", "zzz1", "PRIMARY", "PRIMARY KEY", LONG },
{ "zzz", "zzz2", "zzz2/zzz1", "GROUPING", LONG },
{ "zzz", "zzz2", "PRIMARY", "PRIMARY KEY", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.TABLE_CONSTRAINTS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S constraints", 0, skipped);
}
@Test
public void referentialConstraintsScan() {
final Object[][] expected = {
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.REFERENTIAL_CONSTRAINTS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S referential_constraints", 0, skipped);
}
@Test
public void groupingConstraintsScan() {
final Object[][] expected = {
{ "gco", "r", "gco", "r", "gco.r", 0L, null, null, null, null, LONG },
{ "gco", "r", "gco", "m", "gco.r/gco.m", 1L, "m/r", "gco", "r", "PRIMARY", LONG },
{ "gco", "r", "gco", "b", "gco.r/gco.m/gco.b", 2L, "b/m", "gco", "m", "PRIMARY", LONG },
{ "gco", "r", "gco", "x", "gco.r/gco.m/gco.b/gco.x", 3L, "x/b", "gco", "b", "PRIMARY", LONG },
{ "gco", "r", "gco", "a", "gco.r/gco.a", 1L, "a/r", "gco", "r", "PRIMARY", LONG },
{ "gco", "r", "gco", "w", "gco.r/gco.a/gco.w", 2L, "w/a", "gco", "a", "PRIMARY", LONG },
{ "test", "bar", "test", "bar", "test.bar", 0L, null, null, null, null, LONG },
{ "test", "bar", "test", "bar2", "test.bar/test.bar2", 1L, "bar2/bar", "test", "bar", "PRIMARY", LONG },
{ "test", "defaults", "test", "defaults", "test.defaults", 0L, null, null, null, null, LONG},
{ "test", "foo", "test", "foo", "test.foo", 0L, null, null, null, null, LONG },
{ "test", "seq-table", "test", "seq-table", "test.seq-table", 0L, null, null, null, null, LONG},
{ "zap", "pow", "zap", "pow", "zap.pow", 0L, null, null, null, null, LONG },
{ "zzz", "zzz1", "zzz", "zzz1", "zzz.zzz1", 0L, null, null, null, null, LONG },
{ "zzz", "zzz1", "zzz", "zzz2", "zzz.zzz1/zzz.zzz2", 1L, "zzz2/zzz1", "zzz", "zzz1", "PRIMARY", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.GROUPING_CONSTRAINTS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S grouping_constraints", 22, skipped);
}
@Test
public void keyColumnUsageScan() {
final Object[][] expected = {
{"gco", "a", "a/r", "pid", 0L, 0L, LONG },
{"gco", "a", "PRIMARY", "id", 0L, null, LONG },
{"gco", "b", "b/m", "pid", 0L, 0L, LONG },
{"gco", "b", "PRIMARY", "id", 0L, null, LONG },
{"gco", "m", "m/r", "pid", 0L, 0L, LONG },
{"gco", "m", "PRIMARY", "id", 0L, null, LONG },
{"gco", "r", "PRIMARY", "id", 0L, null, LONG },
{"gco", "w", "w/a", "pid", 0L, 0L, LONG },
{"gco", "x", "x/b", "pid", 0L, 0L, LONG },
{ "test", "bar", "PRIMARY", "col", 0L, null, LONG },
{ "test", "bar2", "bar2/bar", "pid", 0L, 0L, LONG },
{ "test", "seq-table", "PRIMARY", "col", 0L, null, LONG},
{ "zap", "pow", "name_value", "name", 0L, null, LONG },
{ "zap", "pow", "name_value", "value", 1L, null, LONG },
{ "zzz", "zzz1", "PRIMARY", "id", 0L, null, LONG },
{ "zzz", "zzz2", "zzz2/zzz1", "one_id", 0L, 0L, LONG },
{ "zzz", "zzz2", "PRIMARY", "id", 0L, null, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.KEY_COLUMN_USAGE).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S key_column_usage", 0, skipped);
}
@Test
public void indexesScan() {
final Object[][] expected = {
{ "gco", "a", "PRIMARY", "PRIMARY", LONG, "gco.a.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "gco", "b", "PRIMARY", "PRIMARY", LONG, "gco.b.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "gco", "m", "PRIMARY", "PRIMARY", LONG, "gco.m.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "gco", "r", "PRIMARY", "PRIMARY", LONG, "gco.r.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "test", "bar", "PRIMARY", "PRIMARY", LONG, "test.bar.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "test", "bar2", "foo_name", null, LONG, "test.bar.foo_name", "INDEX", false, "RIGHT", null, LONG },
{ "test", "seq-table", "PRIMARY", "PRIMARY", LONG, "test.seq-table.PRIMARY", "PRIMARY", true, null, null, LONG},
{ "zap", "pow", "name_value", "name_value", LONG, "zap.pow.name_value", "UNIQUE", true, null, null, LONG },
{ "zzz", "zzz1", "PRIMARY", "PRIMARY", LONG, "zzz.zzz1.PRIMARY", "PRIMARY", true, null, null, LONG },
{ "zzz", "zzz2", "PRIMARY", "PRIMARY", LONG, "zzz.zzz2.PRIMARY", "PRIMARY", true, null, null, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.INDEXES).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S indexes", 0, skipped);
}
@Test
public void indexColumnsScan() {
final Object[][] expected = {
{ "gco", "PRIMARY", "a", "gco", "a", "id", 0L, true, null, LONG },
{ "gco", "PRIMARY", "b", "gco", "b", "id", 0L, true, null, LONG },
{ "gco", "PRIMARY", "m", "gco", "m", "id", 0L, true, null, LONG },
{ "gco", "PRIMARY", "r", "gco", "r", "id", 0L, true, null, LONG },
{ "test", "PRIMARY", "bar", "test", "bar", "col", 0L, true, null, LONG },
{ "test", "foo_name", "bar2", "test", "bar2", "foo", 0L, true, null, LONG },
{ "test", "foo_name", "bar2", "test", "bar", "name", 1L, true, null, LONG },
{ "test", "PRIMARY", "seq-table", "test", "seq-table", "col", 0L, true, null, LONG},
{ "zap", "name_value", "pow", "zap", "pow", "name", 0L, true, null, LONG },
{ "zap", "name_value", "pow", "zap", "pow", "value", 1L, true, null, LONG },
{ "zzz", "PRIMARY", "zzz1", "zzz", "zzz1", "id", 0L, true, null, LONG },
{ "zzz", "PRIMARY", "zzz2", "zzz", "zzz2", "id", 0L, true, null, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.INDEX_COLUMNS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skipped I_S index_columns", 0, skipped);
}
@Test
public void sequencesScan() {
final Object[][] expected = {
{"test", "_col_sequence", "test._col_sequence", 1L, 1L, 0L, 1000L, false, LONG},
{"test", "sequence", "test.sequence", 1L, 1L, 0L, 1000L, false, LONG },
{"test", "sequence1", "test.sequence1", 1000L, -1L, 0L, 1000L, false, LONG},
};
GroupScan scan = getFactory (BasicInfoSchemaTablesServiceImpl.SEQUENCES).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S sequences", 0, skipped);
}
@Test
public void viewsScan() {
final Object[][] expected = {
{ "test", "voo", new Text("CREATE VIEW voo(c1,c2) AS SELECT c2,c1 FROM foo"), false, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.VIEWS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S views", 0, skipped);
}
@Test
public void viewTableUsageScan() {
final Object[][] expected = {
{ "test", "voo", "test", "foo", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.VIEW_TABLE_USAGE).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S views", 0, skipped);
}
@Test
public void viewColumnUsageScan() {
final Object[][] expected = {
{ "test", "voo", "test", "foo", "c1", LONG },
{ "test", "voo", "test", "foo", "c2", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.VIEW_COLUMN_USAGE).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S views", 0, skipped);
}
@Test
public void routinesScan() {
final Object[][] expected = {
{ "test", "proc1", "PROCEDURE", null, "com.foundationdb.procs.Proc1.call", "java", "JAVA", "NO", null, "YES", 0L, LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.ROUTINES).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S routines", 0, skipped);
}
@Test
public void parametersScan() {
final Object[][] expected = {
{ "test", "proc1", "n1", 1L, "bigint", null, null, null, "IN", "NO", LONG },
{ "test", "proc1", "s1", 2L, "varchar", 16L, null, null, "IN", "NO", LONG },
{ "test", "proc1", "n2", 3L, "decimal", null, 10L, 5L, "IN", "NO", LONG },
{ "test", "proc1", null, 4L, "varchar", 100L, null, null, "OUT", "NO", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.PARAMETERS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S parameters", 0, skipped);
}
@Test
public void jarsScan() {
final Object[][] expected = {
{ "test", "ajar", "https://example.com/procs/ajar.jar", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.JARS).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S jars", 0, skipped);
}
@Test
public void routineJarUsageScan() {
final Object[][] expected = {
{ "test", "proc1", "test", "ajar", LONG },
};
GroupScan scan = getFactory(BasicInfoSchemaTablesServiceImpl.ROUTINE_JAR_USAGE).getGroupScan(adapter);
int skipped = scanAndCompare(expected, scan);
assertEquals("Skip I_S routines", 0, skipped);
}
private static class MockSchemaManager implements SchemaManager {
final AkibanInformationSchema ais;
final StorageFormatRegistry storageFormatRegistry = DummyStorageFormatRegistry.create();
public MockSchemaManager(AkibanInformationSchema ais) {
this.ais = ais;
}
@Override
public AkibanInformationSchema getAis(Session session) {
return ais;
}
@Override
public StorageFormatRegistry getStorageFormatRegistry() {
return storageFormatRegistry;
}
@Override
public AISCloner getAISCloner() {
return new AISCloner(storageFormatRegistry);
}
@Override
public TableName registerStoredInformationSchemaTable(Table newTable, int version) {
throw new UnsupportedOperationException();
}
@Override
public TableName registerMemoryInformationSchemaTable(Table newTable, MemoryTableFactory factory) {
Group group = newTable.getGroup();
storageFormatRegistry.registerMemoryFactory(group.getName(), factory);
// No copying or name registry; just apply right now.
group.setStorageDescription(null);
storageFormatRegistry.finishStorageDescription(group, null);
return group.getName();
}
@Override
public void unRegisterMemoryInformationSchemaTable(TableName tableName) {
storageFormatRegistry.unregisterMemoryFactory(tableName);
}
@Override
public void startOnline(Session session) {
throw new UnsupportedOperationException();
}
@Override
public AkibanInformationSchema getOnlineAIS(Session session) {
throw new UnsupportedOperationException();
}
@Override
public void addOnlineChangeSet(Session session, ChangeSet changeSet) {
throw new UnsupportedOperationException();
}
@Override
public Collection<ChangeSet> getOnlineChangeSets(Session session) {
throw new UnsupportedOperationException();
}
@Override
public void finishOnline(Session session) {
throw new UnsupportedOperationException();
}
@Override
public void discardOnline(Session session) {
throw new UnsupportedOperationException();
}
@Override
public TableName createTableDefinition(Session session, Table newTable) {
throw new UnsupportedOperationException();
}
@Override
public void renameTable(Session session, TableName currentName, TableName newName) {
throw new UnsupportedOperationException();
}
@Override
public void createIndexes(Session session, Collection<? extends Index> indexes, boolean keepStorage) {
throw new UnsupportedOperationException();
}
@Override
public void dropIndexes(Session session, Collection<? extends Index> indexes) {
throw new UnsupportedOperationException();
}
@Override
public void dropTableDefinition(Session session, String schemaName, String tableName, DropBehavior dropBehavior) {
throw new UnsupportedOperationException();
}
@Override
public void alterTableDefinitions(Session session, Collection<ChangedTableDescription> alteredTables) {
throw new UnsupportedOperationException();
}
@Override
public void alterSequence(Session session, TableName sequenceName, Sequence newDefinition) {
throw new UnsupportedOperationException();
}
@Override
public void createView(Session session, View view) {
throw new UnsupportedOperationException();
}
@Override
public void dropView(Session session, TableName viewName) {
throw new UnsupportedOperationException();
}
@Override
public void createSequence(Session session, Sequence sequence) {
throw new UnsupportedOperationException();
}
@Override
public void dropSequence(Session session, Sequence sequence) {
throw new UnsupportedOperationException();
}
@Override
public void createRoutine(Session session, Routine routine, boolean replaceExisting) {
throw new UnsupportedOperationException();
}
@Override
public void dropRoutine(Session session, TableName routineName) {
throw new UnsupportedOperationException();
}
@Override
public void createSQLJJar(Session session, SQLJJar sqljJar) {
throw new UnsupportedOperationException();
}
@Override
public void replaceSQLJJar(Session session, SQLJJar sqljJar) {
throw new UnsupportedOperationException();
}
@Override
public void dropSQLJJar(Session session, TableName jarName) {
throw new UnsupportedOperationException();
}
@Override
public void registerSystemRoutine(Routine routine) {
throw new UnsupportedOperationException();
}
@Override
public void unRegisterSystemRoutine(TableName routineName) {
throw new UnsupportedOperationException();
}
@Override
public Set<String> getTreeNames(Session session) {
throw new UnsupportedOperationException();
}
@Override
public long getOldestActiveAISGeneration() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasTableChanged(Session session, int tableID) {
throw new UnsupportedOperationException();
}
@Override
public void setSecurityService(SecurityService securityService) {
}
}
}
|
package doublex.lib.lockableContainers;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DoubleX
* @param <C>
* @param <K>
*/
public final class UnitTestedLockableContainer<C, K> implements IContainable<C> {
private static final Logger LOG =
Logger.getLogger(UnitTestedLockableContainer.class.getName());
private final LockableContainer<C, K> mLockableContainer;
public UnitTestedLockableContainer(
final LockableContainer<C, K> lockableContainer) {
mLockableContainer = lockableContainer;
}
@Override
public void tryPutContents(final C contents) {
unitTestTryPutContents(contents);
mLockableContainer.tryPutContents(contents);
}
@Override
public C triedTakenContents() {
final C contents = mLockableContainer.triedTakenContents();
unitTestTriedTakenContents(contents);
return contents;
}
private void unitTestTryPutContents(final C contents) {
LOG.log(Level.INFO, "UnitTestedLockableContainer tryPutContents");
LOG.log(Level.INFO, "contents: {0}", contents);
}
private void unitTestTriedTakenContents(final C contents) {
LOG.log(Level.INFO, "UnitTestedLockableContainer triedTakenContents");
LOG.log(Level.INFO, "contents: {0}", contents);
}
}
|
package edu.northwestern.bioinformatics.studycalendar.web;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.UserDao;
import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.*;
import edu.northwestern.bioinformatics.studycalendar.domain.*;
import static edu.northwestern.bioinformatics.studycalendar.domain.Role.*;
import edu.northwestern.bioinformatics.studycalendar.security.AuthenticationSystemConfiguration;
import edu.northwestern.bioinformatics.studycalendar.service.UserRoleService;
import edu.northwestern.bioinformatics.studycalendar.service.UserService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.easymock.IArgumentMatcher;
import static org.easymock.classextension.EasyMock.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;
import java.util.*;
public class CreateUserCommandTest extends StudyCalendarTestCase {
private final Logger log = LoggerFactory.getLogger(getClass());
private Study study;
private Site mayo, nu;
private StudySite mayoSS, nuSS;
private UserService userService;
private SiteDao siteDao;
private UserRoleService userRoleService;
private UserDao userDao;
private Errors errors;
private AuthenticationSystemConfiguration authenticationSystemConfiguration;
@Override
protected void setUp() throws Exception {
super.setUp();
mayo = setId(1, createNamedInstance("Mayo Clinic", Site.class));
nu = setId(2, createNamedInstance("Northwestern Clinic", Site.class));
study = createNamedInstance("Study A", Study.class);
mayoSS = createStudySite(study, mayo);
nuSS = createStudySite(study, nu);
siteDao = new SiteDaoStub(Arrays.asList(mayo, nu));
userDao = registerDaoMockFor(UserDao.class);
userService = registerMockFor(UserService.class);
userRoleService = registerMockFor(UserRoleService.class);
authenticationSystemConfiguration = registerMockFor(AuthenticationSystemConfiguration.class);
expect(authenticationSystemConfiguration.isLocalAuthenticationSystem()).andReturn(true).anyTimes();
errors = new MapBindingResult(new HashMap(), "?");
}
public void testBuildRolesGrid() throws Exception {
User expectedUser = createUser(-1, "Joe", -1L, true, STUDY_ADMIN);
expectedCsmUser(expectedUser);
replayMocks();
CreateUserCommand command = createCommand(expectedUser);
verifyMocks();
Map<Site, Map<Role, CreateUserCommand.RoleCell>> rolesGrid = command.getRolesGrid();
assertEquals("Roles grid has wrong number of sites", 2, rolesGrid.size());
assertEquals("Wrong number checked for site specific Role", values().length, rolesGrid.get(mayo).size());
assertTrue("Role should be true for all sites", rolesGrid.get(mayo).get(STUDY_ADMIN).isSelected());
assertTrue("Role should be true for all sites", rolesGrid.get(nu).get(STUDY_ADMIN).isSelected());
assertFalse("Role should not be true for this site", rolesGrid.get(mayo).get(SUBJECT_COORDINATOR).isSelected());
}
private void expectedCsmUser(final User expectedUser) {
gov.nih.nci.security.authorization.domainobjects.User csmUser = new gov.nih.nci.security.authorization.domainobjects.User();
csmUser.setEmailId("user@email.com");
expect(userService.getCsmUserByCsmUserId(expectedUser.getId())).andReturn(csmUser);
}
public void testInterpretRolesGrid() throws Exception {
User expectedUser = createUser(-1, "Joe", -1L, true);
expectedCsmUser(expectedUser);
List<UserRole> expectedUserRoles = Arrays.asList(
createUserRole(expectedUser, STUDY_ADMIN),
createUserRole(expectedUser, SUBJECT_COORDINATOR, mayo, nu)
);
expectedUser.setUserRoles(new HashSet<UserRole>(expectedUserRoles));
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, mayo);
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, nu);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, mayo);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, nu);
userRoleService.assignUserRole(expectedUser, STUDY_ADMIN);
userRoleService.removeUserRoleAssignment(expectedUser, STUDY_COORDINATOR);
userRoleService.removeUserRoleAssignment(expectedUser, SYSTEM_ADMINISTRATOR);
replayMocks();
CreateUserCommand command = createCommand(expectedUser);
expectedUser.setUserRoles(Collections.<UserRole>emptySet()); // empty user roles so we can test the assign method
command.assignUserRolesFromRolesGrid();
verifyMocks();
}
public void testInterpretRolesGridRemoveRole() throws Exception {
User expectedUser = createUser(-1, "Joe", -1L, true);
List<UserRole> expectedUserRoles = Arrays.asList(
createUserRole(expectedUser, STUDY_ADMIN),
createUserRole(expectedUser, SUBJECT_COORDINATOR, mayo, nu)
);
expectedUser.setUserRoles(new HashSet<UserRole>(expectedUserRoles));
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, mayo);
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, nu);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, mayo);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, nu);
userRoleService.removeUserRoleAssignment(expectedUser, STUDY_ADMIN);
userRoleService.removeUserRoleAssignment(expectedUser, STUDY_COORDINATOR);
userRoleService.removeUserRoleAssignment(expectedUser, SYSTEM_ADMINISTRATOR);
expectedCsmUser(expectedUser);
replayMocks();
CreateUserCommand command = createCommand(expectedUser);
command.getRolesGrid().get(mayo).get(STUDY_ADMIN).setSelected(false);
command.assignUserRolesFromRolesGrid();
verifyMocks();
}
public void testInterpretRolesGridAddRole() throws Exception {
User expectedUser = createUser(-1, "Joe", -1L, true);
List<UserRole> expectedUserRoles = Arrays.asList(
createUserRole(expectedUser, SUBJECT_COORDINATOR, mayo, nu)
);
expectedUser.setUserRoles(new HashSet<UserRole>(expectedUserRoles));
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, mayo);
userRoleService.assignUserRole(expectedUser, SUBJECT_COORDINATOR, nu);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, mayo);
userRoleService.removeUserRoleAssignment(expectedUser, SITE_COORDINATOR, nu);
userRoleService.assignUserRole(expectedUser, STUDY_ADMIN);
userRoleService.removeUserRoleAssignment(expectedUser, STUDY_COORDINATOR);
userRoleService.removeUserRoleAssignment(expectedUser, SYSTEM_ADMINISTRATOR);
expectedCsmUser(expectedUser);
replayMocks();
CreateUserCommand command = createCommand(expectedUser);
command.getRolesGrid().get(mayo).get(STUDY_ADMIN).setSelected(true);
command.assignUserRolesFromRolesGrid();
verifyMocks();
}
public void testUserDefaultsToNewWhenNotSet() throws Exception {
CreateUserCommand command = createCommand(null);
assertNotNull(command.getUser());
assertNull(command.getUser().getId());
assertNull(command.getUser().getName());
}
public void testValidateRejectsRemovalOfLastSiteCoordinatorForSite() throws Exception {
User lastSiteCoord = setId(3, createUser("jimbo", SITE_COORDINATOR));
expectedCsmUser(lastSiteCoord);
replayMocks();
CreateUserCommand command = createCommand(lastSiteCoord);
resetMocks();
lastSiteCoord.getUserRole(SITE_COORDINATOR).addSite(mayo);
mayoSS.addStudySubjectAssignment(new StudySubjectAssignment());
command.getRolesGrid().get(mayo).get(SITE_COORDINATOR).setSelected(false);
expect(userDao.getSiteCoordinators(mayo)).andReturn(Arrays.asList(lastSiteCoord));
replayMocks();
command.validate(errors);
verifyMocks();
assertEquals("Wrong number of errors", 1, errors.getFieldErrorCount());
FieldError actualError = (FieldError) errors.getFieldErrors().get(0);
assertFieldError(actualError, "rolesGrid[1][SITE_COORDINATOR].selected",
"error.user.last-site-coordinator", "jimbo", "Mayo Clinic");
}
public void testValidateDoesNotRejectLastSiteCoordinatorForUnusedSite() throws Exception {
User lastSiteCoord = setId(3, createUser("jimbo", SITE_COORDINATOR));
lastSiteCoord.getUserRole(SITE_COORDINATOR).addSite(mayo);
expectedCsmUser(lastSiteCoord);
replayMocks();
CreateUserCommand command = createCommand(lastSiteCoord);
verifyMocks();
command.getRolesGrid().get(mayo).get(SITE_COORDINATOR).setSelected(false);
command.validate(errors);
verifyMocks();
assertEquals("Wrong number of errors: " + errors.getFieldErrors(), 0, errors.getFieldErrorCount());
}
public void testValidateDoesNotRequirePasswordForNonLocalAuthenticationSystem() throws Exception {
reset(authenticationSystemConfiguration);
expect(authenticationSystemConfiguration.isLocalAuthenticationSystem()).andReturn(false);
User newUser = new User();
newUser.setName("anything");
CreateUserCommand command = createCommand(newUser);
command.setEmailAddress("user@email.com");
expect(userDao.getByName(newUser.getName())).andReturn(null);
replayMocks();
command.validate(errors);
assertEquals("Wrong number of errors: " + errors.getFieldErrors(), 0, errors.getFieldErrorCount());
verifyMocks();
}
public void testValidateEmailAddressIsMandatory() throws Exception {
User newUser = new User();
newUser.setName("anything");
CreateUserCommand command = createCommand(newUser);
command.setPassword("password");
command.setRePassword("password");
expect(userDao.getByName(newUser.getName())).andReturn(null);
replayMocks();
command.validate(errors);
assertEquals("Wrong number of errors: " + errors.getFieldErrors(), 1, errors.getFieldErrorCount());
verifyMocks();
}
public void testValidateEmailAddressforInvalidFormat() throws Exception {
User newUser = new User();
newUser.setName("anything");
CreateUserCommand command = createCommand(newUser);
command.setPassword("password");
command.setRePassword("password");
command.setEmailAddress("invalid email address");
expect(userDao.getByName(newUser.getName())).andReturn(null);
replayMocks();
command.validate(errors);
assertEquals("Wrong number of errors: " + errors.getFieldErrors(), 1, errors.getFieldErrorCount());
verifyMocks();
}
public void testValidateEmailAddressforValidFormat() throws Exception {
User newUser = new User();
newUser.setName("anything");
CreateUserCommand command = createCommand(newUser);
command.setPassword("password");
command.setRePassword("password");
command.setEmailAddress("valid@email.com");
expect(userDao.getByName(newUser.getName())).andReturn(null);
replayMocks();
command.validate(errors);
assertEquals("Wrong number of errors: " + errors.getFieldErrors(), 0, errors.getFieldErrorCount());
verifyMocks();
}
public void testRandomPasswordIsGeneratedForNewUserWithNonLocalAuthenticationSystem() throws Exception {
// stub calls
userRoleService.removeUserRoleAssignment((User) notNull(), (Role) notNull(), (Site) notNull());
expectLastCall().anyTimes();
userRoleService.removeUserRoleAssignment((User) notNull(), (Role) notNull());
expectLastCall().anyTimes();
reset(authenticationSystemConfiguration);
expect(authenticationSystemConfiguration.isLocalAuthenticationSystem()).andReturn(false);
User newUser = new User();
expect(userService.saveUser(eq(newUser), randomPassword(), null)).andReturn(newUser);
CreateUserCommand command = createCommand(newUser);
replayMocks();
command.apply();
verifyMocks();
}
private String randomPassword() {
reportMatcher(new IArgumentMatcher() {
public boolean matches(Object object) {
String candidate = (String) object;
if (candidate == null) return false;
boolean lengthOkay = 16 <= candidate.length() && candidate.length() <= 32;
if (!lengthOkay) log.error("Length not in range [16, 32]");
boolean charsOkay = true;
for (int i = 0; i < candidate.length(); i++) {
boolean thisCharOkay = (' ' <= candidate.charAt(i) && candidate.charAt(i) <= '~');
if (!thisCharOkay) log.error("Character {} ({}) out of range", i, candidate.charAt(i));
charsOkay = charsOkay && thisCharOkay;
}
return lengthOkay && charsOkay;
}
public void appendTo(StringBuffer stringBuffer) {
stringBuffer.append("[random password]");
}
});
return null;
}
private static void assertGlobalError(
ObjectError actual, String expectedCode, Object... expectedArgs
) {
assertEquals("Wrong code", expectedCode, actual.getCode());
assertEquals("Wrong number of args", expectedArgs.length, actual.getArguments().length);
for (int i = 0; i < expectedArgs.length; i++) {
Object expectedParameter = expectedArgs[i];
assertEquals("Wrong parameter " + i, expectedParameter, actual.getArguments()[i]);
}
}
private static void assertFieldError(
FieldError error, String expectedField, String expectedCode, Object... expectedArgs
) {
assertEquals("Wrong field", expectedField, error.getField());
assertGlobalError(error, expectedCode, expectedArgs);
}
private CreateUserCommand createCommand(User user) {
return new CreateUserCommand(user, siteDao, userService, userDao, userRoleService, authenticationSystemConfiguration);
}
private static class SiteDaoStub extends SiteDao {
private List<Site> all;
public SiteDaoStub(List<Site> all) {
this.all = all;
}
@Override
public List<Site> getAll() {
return all;
}
public void setAll(List<Site> all) {
this.all = all;
}
@Override
public int getCount() {
return getAll().size();
}
////// UNUSED STUB METHODS
@Override
public Site getByName(final String name) {
throw new UnsupportedOperationException("getByName not implemented");
}
@Override
public Site getByAssignedIdentifier(final String assignedIdentifier) {
throw new UnsupportedOperationException("getByAssignedIdentifier not implemented");
}
@Override
public Site getByGridId(String gridId) {
throw new UnsupportedOperationException("getByGridId not implemented");
}
@Override
public Site getByGridId(Site template) {
throw new UnsupportedOperationException("getByGridId not implemented");
}
@Override
public void save(Site site) {
throw new UnsupportedOperationException("save not implemented");
}
@Override
public Site getById(int i) {
throw new UnsupportedOperationException("getById not implemented");
}
}
}
|
package codes.plus;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
public class OpenLocationCode {
private static final BigDecimal BD_0 = new BigDecimal(0);
private static final BigDecimal BD_5 = new BigDecimal(5);
private static final BigDecimal BD_4 = new BigDecimal(4);
private static final BigDecimal BD_20 = new BigDecimal(20);
private static final BigDecimal BD_90 = new BigDecimal(90);
private static final BigDecimal BD_180 = new BigDecimal(180);
private static final char[] ALPHABET = "23456789CFGHJMPQRVWX".toCharArray();
private static Map<Character, Integer> CHARACTER_TO_INDEX = new HashMap<>();
static {
int index = 0;
for (char character : ALPHABET) {
char lowerCaseCharacter = Character.toLowerCase(character);
CHARACTER_TO_INDEX.put(character, index);
CHARACTER_TO_INDEX.put(lowerCaseCharacter, index);
index++;
}
}
private static final char SEPARATOR = '+';
private static final char SEPARATOR_POSITION = 8;
private static final char SUFFIX_PADDING = '0';
/** Class providing information about area covered by Open Location Code. */
public class CodeArea {
private final BigDecimal southLatitude;
private final BigDecimal westLongitude;
private final BigDecimal northLatitude;
private final BigDecimal eastLongitude;
public CodeArea(BigDecimal southLatitude, BigDecimal westLongitude, BigDecimal northLatitude, BigDecimal eastLongitude) {
this.southLatitude = southLatitude;
this.westLongitude = westLongitude;
this.northLatitude = northLatitude;
this.eastLongitude = eastLongitude;
}
public double getSouthLatitude() {
return southLatitude.doubleValue();
}
public double getWestLongitude() {
return westLongitude.doubleValue();
}
public double getLatitudeHeight() {
return northLatitude.subtract(southLatitude).doubleValue();
}
public double getLongitudeWidth() {
return eastLongitude.subtract(westLongitude).doubleValue();
}
public double getCenterLatitude() {
return southLatitude.add(northLatitude).doubleValue() / 2;
}
public double getCenterLongitude() {
return westLongitude.add(eastLongitude).doubleValue() / 2;
}
public double getNorthLatitude() {
return northLatitude.doubleValue();
}
public double getEastLongitude() {
return eastLongitude.doubleValue();
}
}
/** The state of the OpenLocationCode. */
private final String code;
/** Creates Open Location Code for the provided code. */
public OpenLocationCode(String code) {
if (!isValidCode(code)) {
throw new IllegalArgumentException("The provided code '" + code + "' is not a valid Open Location Code.");
}
this.code = code.toUpperCase();
}
/** Creates Open Location Code from the provided latitude, longitude and desired code length. */
public OpenLocationCode(double latitude, double longitude, int codeLength) throws IllegalArgumentException {
if (codeLength < 4 || (codeLength < 10 & codeLength % 2 == 1)) {
throw new IllegalArgumentException("Illegal code length " + codeLength);
}
latitude = clipLatitude(latitude);
longitude = normalizeLongitude(longitude);
// Latitude 90 needs to be adjusted to be just less, so the returned code
// can also be decoded.
if (latitude == 90) {
latitude = latitude - 0.9 * computeLatitudePrecision(codeLength);
}
StringBuilder codeBuilder = new StringBuilder();
// Ensure the latitude and longitude are within [0, 180] and [0, 360) respectively.
/* Note: double type can't be used because of the rounding arithmetic due to floating point implementation.
* Eg. "8.95 - 8" can give result 0.9499999999999 instead of 0.95 which incorrectly classify the points on the
* border of a cell.
*/
BigDecimal remainingLongitude = new BigDecimal(longitude + 180);
BigDecimal remainingLatitude = new BigDecimal(latitude + 90);
// Create up to 10 significant digits from pairs alternating latitude and longitude.
int generatedDigits = 0;
while (generatedDigits < codeLength) {
// Always the integer part of the remaining latitude/longitude will be used for the following digit.
if (generatedDigits == 0) {
// First step World division: Map <0..400) to <0..20) for both latitude and longitude.
remainingLatitude = remainingLatitude.divide(BD_20);
remainingLongitude = remainingLongitude.divide(BD_20);
} else if (generatedDigits < 10) {
remainingLatitude = remainingLatitude.multiply(BD_20);
remainingLongitude = remainingLongitude.multiply(BD_20);
} else {
remainingLatitude = remainingLatitude.multiply(BD_5);
remainingLongitude = remainingLongitude.multiply(BD_4);
}
int latitudeDigit = remainingLatitude.intValue();
int longitudeDigit = remainingLongitude.intValue();
if (generatedDigits < 10) {
codeBuilder.append(ALPHABET[latitudeDigit]);
codeBuilder.append(ALPHABET[longitudeDigit]);
generatedDigits += 2;
} else {
codeBuilder.append(ALPHABET[4 * latitudeDigit + longitudeDigit]);
generatedDigits += 1;
}
remainingLatitude = remainingLatitude.subtract(new BigDecimal(latitudeDigit));
remainingLongitude = remainingLongitude.subtract(new BigDecimal(longitudeDigit));
if (generatedDigits == SEPARATOR_POSITION) codeBuilder.append(SEPARATOR);
}
if (generatedDigits < SEPARATOR_POSITION) {
for (;generatedDigits < SEPARATOR_POSITION; generatedDigits++) {
codeBuilder.append(SUFFIX_PADDING);
}
codeBuilder.append(SEPARATOR);
}
this.code = codeBuilder.toString();
}
/**
* Creates Open Location Code with code length 10 from the provided latitude, longitude.
*/
public OpenLocationCode(double latitude, double longitude) {
this(latitude, longitude, 10);
}
public String getCode() {
return code;
}
/**
* Encodes latitude/longitude into 10 digit Open Location Code.
* This method is equivalent to creating the OpenLocationCode object and getting the code from it.
*/
public static String encode(double latitude, double longitude) {
return new OpenLocationCode(latitude, longitude).getCode();
}
/**
* Encodes latitude/longitude into Open Location Code of the provided length.
* This method is equivalent to creating the OpenLocationCode object and getting the code from it.
*/
public static String encode(double latitude, double longitude, int codeLength) {
return new OpenLocationCode(latitude, longitude, codeLength).getCode();
}
/** Decodes {@link OpenLocationCode} object into {@link CodeArea} object encapsulating latitude/longitude bounding box. */
public CodeArea decode() {
if (!isFullCode(code)) {
throw new IllegalStateException(
"Method decode() could only be called on valid full codes, code was " + code + ".");
}
String decoded = code.replaceAll("[0+]", "");
// Decode the lat/lng pair component.
BigDecimal southLatitude = BD_0;
BigDecimal westLongitude = BD_0;
int digit = 0;
double latitudeResolution = 400, longitudeResolution = 400;
// Decode pair.
while (digit < decoded.length()) {
if (digit < 10) {
latitudeResolution /= 20;
longitudeResolution /= 20;
southLatitude = southLatitude.add(new BigDecimal(latitudeResolution * CHARACTER_TO_INDEX.get(decoded.charAt(digit))));
westLongitude = westLongitude.add(new BigDecimal(longitudeResolution * CHARACTER_TO_INDEX.get(decoded.charAt(digit + 1))));
digit += 2;
} else {
latitudeResolution /= 5;
longitudeResolution /= 4;
southLatitude = southLatitude.add(new BigDecimal(latitudeResolution * (CHARACTER_TO_INDEX.get(decoded.charAt(digit)) / 4)));
westLongitude = westLongitude.add(new BigDecimal(longitudeResolution * (CHARACTER_TO_INDEX.get(decoded.charAt(digit)) % 4)));
digit += 1;
}
}
return new CodeArea(
southLatitude.subtract(BD_90),
westLongitude.subtract(BD_180),
southLatitude.subtract(BD_90).add(new BigDecimal(latitudeResolution)),
westLongitude.subtract(BD_180).add(new BigDecimal(longitudeResolution)));
}
public static CodeArea decode(String code) throws IllegalArgumentException {
return new OpenLocationCode(code).decode();
}
/** Returns whether this {@link OpenLocationCode} is a full Open Location Code. */
public boolean isFull() {
return code.indexOf(SEPARATOR) == SEPARATOR_POSITION;
}
/** Returns whether the provided Open Location Code is a full Open Location Code. */
public static boolean isFull(String code) throws IllegalArgumentException {
return new OpenLocationCode(code).isFull();
}
/** Returns whether this {@link OpenLocationCode} is a short Open Location Code. */
public boolean isShort() {
return code.indexOf(SEPARATOR) >= 0 && code.indexOf(SEPARATOR) < SEPARATOR_POSITION;
}
/** Returns whether the provided Open Location Code is a short Open Location Code. */
public static boolean isShort(String code) throws IllegalArgumentException {
return new OpenLocationCode(code).isShort();
}
/**
* Returns whether this {@link OpenLocationCode} is a padded Open Location Code,
* meaning that it contains less than 8 valid digits.
*/
private boolean isPadded() {
return code.indexOf(SUFFIX_PADDING) >= 0;
}
/**
* Returns whether the provided Open Location Code is a padded Open Location Code,
* meaning that it contains less than 8 valid digits.
*/
public static boolean isPadded(String code) throws IllegalArgumentException {
return new OpenLocationCode(code).isPadded();
}
public OpenLocationCode shorten(double referenceLatitude, double referenceLongitude) {
if (!isFull()) {
throw new IllegalStateException("shorten() method could only be called on a full code.");
}
if (isPadded()) {
throw new IllegalStateException("shorten() method can not be called on a padded code.");
}
CodeArea codeArea = decode();
double latitudeDiff = Math.abs(referenceLatitude - codeArea.getCenterLatitude());
double longitudeDiff = Math.abs(referenceLongitude - codeArea.getCenterLongitude());
if (latitudeDiff < 0.0125 && longitudeDiff < 0.0125) {
return new OpenLocationCode(code.substring(6));
}
if (latitudeDiff < 0.25 && longitudeDiff < 0.25) {
return new OpenLocationCode(code.substring(4));
}
throw new IllegalArgumentException("Reference location is too far from the Open Location Code center.");
}
/**
* Returns an {@link OpenLocationCode} object representing a full Open Location Code from this (short)
* Open Location Code, given the reference location.
*/
public OpenLocationCode recover(double referenceLatitude, double referenceLongitude) {
if (isFull()) {
// Note: each code is either full xor short, no other option.
return this;
}
referenceLatitude = clipLatitude(referenceLatitude);
referenceLongitude = normalizeLongitude(referenceLongitude);
int digitsToRecover = 8 - code.indexOf(SEPARATOR);
// The resolution (height and width) of the padded area in degrees.
double paddedAreaSize = Math.pow(20, 2 - (digitsToRecover / 2));
// Distance from the center to an edge (in degrees).
// Round down the reference latitude and longitude to the resolution.
double roundedLatitude = Math.floor(referenceLatitude / paddedAreaSize) * paddedAreaSize;
double roundedLongitude = Math.floor(referenceLongitude / paddedAreaSize) * paddedAreaSize;
// Use the reference location to pad the supplied short code and decode it.
String recoveredPrefix = new OpenLocationCode(roundedLatitude, roundedLongitude).getCode().substring(0, digitsToRecover);
OpenLocationCode recovered = new OpenLocationCode(recoveredPrefix + code);
CodeArea recoveredCodeArea = recovered.decode();
double recoveredLatitude = recoveredCodeArea.getCenterLatitude();
double recoveredLongitude = recoveredCodeArea.getCenterLongitude();
// Move the recovered latitude by one resolution up or down if it is too far from the reference.
double latitudeDiff = recoveredLatitude - referenceLatitude;
if (latitudeDiff > paddedAreaSize / 2) {
recoveredLatitude -= paddedAreaSize;
} else if (latitudeDiff < -paddedAreaSize / 2) {
recoveredLatitude += paddedAreaSize;
}
// Move the recovered longitude by one resolution up or down if it is too far from the reference.
double longitudeDiff = recoveredCodeArea.getCenterLongitude() - referenceLongitude;
if (longitudeDiff > paddedAreaSize / 2) {
recoveredLongitude -= paddedAreaSize;
} else if (longitudeDiff < -paddedAreaSize / 2) {
recoveredLongitude += paddedAreaSize;
}
return new OpenLocationCode(recoveredLatitude, recoveredLongitude, recovered.getCode().length() - 1);
}
/** Returns whether the bounding box specified by the Open Location Code contains provided point. */
public boolean contains(double latitude, double longitude) {
CodeArea codeArea = decode();
return codeArea.getSouthLatitude() <= latitude && latitude < codeArea.getNorthLatitude()
&& codeArea.getWestLongitude() <= longitude && longitude < codeArea.getEastLongitude();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OpenLocationCode that = (OpenLocationCode) o;
return hashCode() == that.hashCode();
}
@Override
public int hashCode() {
return code != null ? code.hashCode() : 0;
}
@Override
public String toString() {
return getCode();
}
// Exposed static helper methods.
/** Returns whether the provided string is a valid Open Location code. */
public static boolean isValidCode(String code) {
if (code == null || code.length() < 2) return false;
// There must be exactly one separator.
int separatorPosition = code.indexOf(SEPARATOR);
if (separatorPosition == -1) return false;
if (separatorPosition != code.lastIndexOf(SEPARATOR)) return false;
if (separatorPosition % 2 != 0) return false;
// Check first two characters: only some values from the alphabet are permitted.
if (separatorPosition == 8) {
// First latitude character can only have first 9 values.
Integer index0 = CHARACTER_TO_INDEX.get(code.charAt(0));
if (index0 == null || index0 > 8) return false;
// First longitude character can only have first 18 values.
Integer index1 = CHARACTER_TO_INDEX.get(code.charAt(1));
if (index1 == null || index1 > 17) return false;
}
// Check the characters before the separator.
boolean paddingStarted = false;
for (int i = 0; i < separatorPosition; i++) {
if (paddingStarted) {
// Once padding starts, there must not be anything but padding.
if (code.charAt(i) != SUFFIX_PADDING) return false;
continue;
}
if (CHARACTER_TO_INDEX.keySet().contains(code.charAt(i))) continue;
if (SUFFIX_PADDING == code.charAt(i)) {
paddingStarted = true;
// Padding can start on even character: 2, 4 or 6.
if (i != 2 && i != 4 && i != 6) return false;
continue;
}
return false;
}
// Check the characters after the separator.
if (code.length() > separatorPosition + 1) {
if (paddingStarted) return false;
// Only one character after separator is forbidden.
if (code.length() == separatorPosition + 2) return false;
for (int i = separatorPosition + 1; i < code.length(); i++) {
if (!CHARACTER_TO_INDEX.keySet().contains(code.charAt(i))) return false;
}
}
return true;
}
/** Returns if the code is a valid full Open Location Code. */
public static boolean isFullCode(String code) {
try {
return new OpenLocationCode(code).isFull();
} catch (IllegalArgumentException e) {
return false;
}
}
/** Returns if the code is a valid short Open Location Code. */
public static boolean isShortCode(String code) {
try {
return new OpenLocationCode(code).isShort();
} catch (IllegalArgumentException e) {
return false;
}
}
// Private static methods.
private static double clipLatitude(double latitude) {
return Math.min(Math.max(latitude, -90), 90);
}
private static double normalizeLongitude(double longitude) {
if (longitude < -180) {
longitude = (longitude % 360) + 360;
}
if (longitude >= 180) {
longitude = (longitude % 360) - 360;
}
return longitude;
}
/**
* Compute the latitude precision value for a given code length.
* Lengths <= 10 have the same precision for latitude and longitude, but lengths > 10 have different precisions
* due to the grid method having fewer columns than rows.
* Copied from the JS implementation.
*/
private static double computeLatitudePrecision(int codeLength) {
if (codeLength <= 10) {
return Math.pow(20, Math.floor(codeLength / -2 + 2));
}
return Math.pow(20, -3) / Math.pow(5, codeLength - 10);
}
}
|
//package pt.fccn.mobile.arquivo.tests.imagesearch;
//import static org.hamcrest.CoreMatchers.containsString;
//import static org.hamcrest.MatcherAssert.assertThat;
//import org.junit.Test;
//import org.openqa.selenium.By;
//import pt.fccn.arquivo.selenium.Retry;
//import pt.fccn.arquivo.selenium.WebDriverTestBaseParalell;
///**
// *
// * @author Ivo Branco <ivo.branco@fccn.pt>
// *
// */
//public class ImageSearchQuerySuggestionTest extends WebDriverTestBaseParalell {
// public ImageSearchQuerySuggestionTest(String os, String version, String browser, String deviceName,
// String deviceOrientation) {
// super(os, version, browser, deviceName, deviceOrientation);
// @Test
// @Retry
// public void imageSearchQuerySuggestionTest() {
// run("Search with testre", () -> {
// driver.findElement(By.id("txtSearch")).clear();
// driver.findElement(By.id("txtSearch")).sendKeys("testre");
|
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FuzzySearch {
public static final String FILE_CATALOG_FILENAME = "files.txt";
public static final String FILE_CATALOG_FILE = "test/resources";
private List<String> FILE_CATALOG = new ArrayList<>();
private static final HashMap<String, String[]> LOOKUP = new HashMap<>();
public FuzzySearch() throws IOException {
populateFileCatalog();
String fileName = "java_challenges/Hanoi/src/CharacterDisplay.java";
populateSearchTree(fileName, fileName);
// for (String fileName : FILE_CATALOG) {
// populateSearchTree(fileName, fileName);
// System.out.println();
}
private void populateSearchTree(String partialName, String fileName) {
boolean found = LOOKUP.containsKey(partialName);
if (found) {
String[] fileList = LOOKUP.get(partialName);
if (!fileList[fileList.length - 1].equals(fileName)) {
System.out.println("partialName = " + partialName);
fileList[fileList.length] = fileName;
LOOKUP.put(partialName, fileList);
}
} else {
System.out.println("partialName = " + partialName);
LOOKUP.put(partialName, new String[]{fileName});
for (int i = 0; i < partialName.length(); i++) {
String front = (i == 0) ? "" : partialName.substring(0, i);
String back = (i >= partialName.length() - 1) ? "" : partialName.substring(i + 1, partialName.length());
if (partialName.length() > 1) {
populateSearchTree(front + back, fileName);
}
}
}
}
private void populateFileCatalog() throws IOException {
Path catalogFile = FileSystems.getDefault().getPath(FILE_CATALOG_FILE, FILE_CATALOG_FILENAME);
FILE_CATALOG = Files.readAllLines(catalogFile, StandardCharsets.UTF_8);
}
public String[] find(String pattern) {
String s = FILE_CATALOG.get(0);
System.out.println("s = " + s);
return new String[]{};
}
}
|
package at.hgz.dice;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.NumberPicker;
public abstract class DiceNumberDialogFragment extends DialogFragment {
private int value;
private NumberPicker diceNumberPicker;
public DiceNumberDialogFragment(int value) {
this.value = value;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setRetainInstance(true);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View view = inflater.inflate(R.layout.dialog_dice_number, null);
diceNumberPicker = (NumberPicker) view.findViewById(R.id.diceNumberPicker);
diceNumberPicker.setMinValue(1);
diceNumberPicker.setMaxValue(1000);
diceNumberPicker.setWrapSelectorWheel(false);
diceNumberPicker.setValue(value);
builder.setView(view)
// set title
.setTitle(R.string.number_of_dice)
// Add action buttons
.setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
returnValue(diceNumberPicker.getValue());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DiceNumberDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
@Override
public void onDestroyView() {
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
protected abstract void returnValue(int value);
}
|
package net.hyperic.sigar.cmd;
import net.hyperic.sigar.Sigar;
import net.hyperic.sigar.SigarProxy;
import net.hyperic.sigar.SigarException;
import net.hyperic.sigar.ProcCredName;
import net.hyperic.sigar.ProcMem;
import net.hyperic.sigar.ProcTime;
import net.hyperic.sigar.ProcState;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Show process status.
*/
public class Ps extends SigarCommandBase {
public Ps(Shell shell) {
super(shell);
}
public Ps() {
super();
}
protected boolean validateArgs(String[] args) {
return true;
}
public String getSyntaxArgs() {
return "[pid|query]";
}
public String getUsageShort() {
return "Show process status";
}
public boolean isPidCompleter() {
return true;
}
public void output(String[] args) throws SigarException {
long[] pids;
if (args.length == 0) {
pids = this.proxy.getProcList();
}
else {
pids = this.shell.findPids(args);
}
for (int i=0; i<pids.length; i++) {
long pid = pids[i];
try {
output(pid);
} catch (SigarException e) {
this.err.println("Exception getting process info for " +
pid + ": " + e.getMessage());
}
}
}
public static String join(List info) {
StringBuffer buf = new StringBuffer();
Iterator i = info.iterator();
boolean hasNext = i.hasNext();
while (hasNext) {
buf.append((String)i.next());
hasNext = i.hasNext();
if (hasNext)
buf.append("\t");
}
return buf.toString();
}
private static boolean isClassName(String name) {
int len = name.length();
for (int i=0; i<len; i++) {
char c = name.charAt(i);
if (!((c == '.') || Character.isLetter(c))) {
return false;
}
}
return true;
}
public static List getInfo(SigarProxy sigar, long pid)
throws SigarException {
ProcState state = sigar.getProcState(pid);
ProcTime time = null;
String unknown = "???";
List info = new ArrayList();
info.add(String.valueOf(pid));
try {
ProcCredName cred = sigar.getProcCredName(pid);
info.add(cred.getUser());
} catch (SigarException e) {
info.add(unknown);
}
try {
time = sigar.getProcTime(pid);
info.add(getStartTime(time.getStartTime()));
} catch (SigarException e) {
info.add(unknown);
}
try {
ProcMem mem = sigar.getProcMem(pid);
info.add(Sigar.formatSize(mem.getSize()));
info.add(Sigar.formatSize(mem.getRss()));
info.add(Sigar.formatSize(mem.getShare()));
} catch (SigarException e) {
info.add(unknown);
}
info.add(String.valueOf(state.getState()));
if (time != null) {
info.add(getCpuTime(time));
}
else {
info.add(unknown);
}
String name = state.getName();
if (name.equals("java")) {
//try to guess classname for java programs
try {
String[] args = sigar.getProcArgs(pid);
for (int i=1; i<args.length; i++) {
String arg = args[i];
if (!isClassName(arg)) {
continue;
}
//example: "java:weblogic.Server"
name += ":" + arg;
break;
}
} catch (SigarException e) {}
}
else {
try {
String[] args = sigar.getProcArgs(pid);
name = args[0];
} catch (SigarException e) {}
}
info.add(name);
return info;
}
public void output(long pid) throws SigarException {
println(join(getInfo(this.proxy, pid)));
}
private static String getCpuTime(ProcTime time) {
long t = time.getTotal();
return t/60 + ":" + t%60;
}
private static String getStartTime(long time) {
if (time == 0) {
return "00:00";
}
long timeNow = System.currentTimeMillis();
String fmt = "MMMd";
if ((timeNow - time) < ((60*60*24) * 1000)) {
fmt = "HH:mm";
}
return new SimpleDateFormat(fmt).format(new Date(time));
}
public static void main(String[] args) throws Exception {
new Ps().processCommand(args);
}
}
|
package org.hyperic.sigar.cmd;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.jmx.SigarProcess;
import org.hyperic.sigar.jmx.SigarRegistry;
public class Mx extends SigarCommandBase {
private boolean isRegistered;
public Mx(Shell shell) {
super(shell);
}
public Mx() {
super();
}
//java -Dcom.sun.management.jmxremote -jar sigar.jar
public String getUsageShort() {
return "Register MBeans for use via jconsole, etc.";
}
protected boolean validateArgs(String[] args) {
return args.length <= 1;
}
public static MBeanServer getMBeanServer()
throws SigarException {
List servers =
MBeanServerFactory.findMBeanServer(null);
if (servers.size() == 0) {
throw new SigarException("No MBeanServers available");
}
else {
return (MBeanServer)servers.get(0);
}
}
private void register(MBeanServer server) throws SigarException {
if (isRegistered) {
return;
}
SigarRegistry registry = new SigarRegistry();
try {
server.registerMBean(registry, null);
SigarProcess proc = new SigarProcess();
server.registerMBean(proc, new ObjectName(proc.getObjectName()));
isRegistered = true;
} catch (Exception e) {
throw new SigarException(e.getMessage());
}
}
private void jconsole() {
String pid = String.valueOf(this.sigar.getPid());
String[] argv = { "jconsole", pid };
println("exec(jconsole, " + pid + ")");
try {
Process p = Runtime.getRuntime().exec(argv);
p.waitFor();
println("jconsole exited");
} catch (Exception e) {
println(e.getMessage());
}
}
public void output(String[] args) throws SigarException {
MBeanServer server = getMBeanServer();
register(server);
boolean hasQuery = false;
boolean launchJconsole = false;
String query = "sigar:*";
for (int i=0; i<args.length; i++) {
String arg = args[i];
if (arg.equals("-jconsole")) {
launchJconsole = true;
}
else {
query = arg;
hasQuery = true;
}
}
try {
Set beans =
server.queryNames(new ObjectName(query), null);
println(beans.size() + " MBeans are registered...");
for (Iterator it=beans.iterator(); it.hasNext();) {
ObjectName name = (ObjectName)it.next();
if (hasQuery) {
MBeanInfo info = server.getMBeanInfo(name);
MBeanAttributeInfo[] attrs = info.getAttributes();
for (int i=0; i<attrs.length; i++) {
String attr = attrs[i].getName();
Object val = server.getAttribute(name, attr);
println(name + ":" + attr + "=" + val);
}
}
else {
println(name.toString());
}
}
} catch (Exception e) {
throw new SigarException(e.getMessage());
}
if (launchJconsole) {
jconsole();
}
}
public static void main(String[] args) throws Exception {
new Mx().processCommand(args);
}
}
|
package org.cytoscape.internal.view;
import static org.cytoscape.internal.view.util.ViewUtil.invokeOnEDT;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.events.SetCurrentNetworkEvent;
import org.cytoscape.application.events.SetCurrentNetworkListener;
import org.cytoscape.application.events.SetCurrentNetworkViewEvent;
import org.cytoscape.application.events.SetCurrentNetworkViewListener;
import org.cytoscape.application.events.SetCurrentTableEvent;
import org.cytoscape.application.events.SetCurrentTableListener;
import org.cytoscape.event.DebounceTimer;
import org.cytoscape.internal.view.util.CyToolBar;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.events.NetworkAddedEvent;
import org.cytoscape.model.events.NetworkAddedListener;
import org.cytoscape.model.events.NetworkDestroyedEvent;
import org.cytoscape.model.events.NetworkDestroyedListener;
import org.cytoscape.model.events.RowsSetEvent;
import org.cytoscape.model.events.RowsSetListener;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.events.SessionAboutToBeLoadedEvent;
import org.cytoscape.session.events.SessionAboutToBeLoadedListener;
import org.cytoscape.session.events.SessionAboutToBeSavedEvent;
import org.cytoscape.session.events.SessionAboutToBeSavedListener;
import org.cytoscape.session.events.SessionLoadedEvent;
import org.cytoscape.session.events.SessionLoadedListener;
import org.cytoscape.session.events.SessionSaveCancelledEvent;
import org.cytoscape.session.events.SessionSaveCancelledListener;
import org.cytoscape.session.events.SessionSavedEvent;
import org.cytoscape.session.events.SessionSavedListener;
import org.cytoscape.view.model.events.NetworkViewAddedEvent;
import org.cytoscape.view.model.events.NetworkViewAddedListener;
import org.cytoscape.view.model.events.NetworkViewDestroyedEvent;
import org.cytoscape.view.model.events.NetworkViewDestroyedListener;
import org.cytoscape.view.model.events.UpdateNetworkPresentationEvent;
import org.cytoscape.view.model.events.UpdateNetworkPresentationListener;
/**
* A utility class that listens for various events and then updates the enable
* state for the toolbar icons. Menus do this check every time that a menu is
* selected, but since toolbars are always visible, we need to listen for the
* actual events. This is less than ideal.
*/
public class ToolBarEnableUpdater implements SessionAboutToBeLoadedListener, SessionLoadedListener,
SessionAboutToBeSavedListener, SessionSavedListener, SessionSaveCancelledListener, NetworkAddedListener,
NetworkDestroyedListener, NetworkViewAddedListener, NetworkViewDestroyedListener, SetCurrentNetworkListener,
SetCurrentNetworkViewListener, SetCurrentTableListener, RowsSetListener, UpdateNetworkPresentationListener {
private final DebounceTimer debounceTimer = new DebounceTimer(100);
private boolean loadingSession;
private final CyToolBar toolbar;
private final CyServiceRegistrar serviceRegistrar;
public ToolBarEnableUpdater(CyToolBar toolbar, CyServiceRegistrar serviceRegistrar) {
this.toolbar = toolbar;
this.serviceRegistrar = serviceRegistrar;
}
@Override
public void handleEvent(SessionAboutToBeLoadedEvent e) {
updateToolbar();
loadingSession = true;
}
@Override
public void handleEvent(SessionLoadedEvent e) {
loadingSession = false;
updateToolbar();
}
@Override
public void handleEvent(SessionAboutToBeSavedEvent e) {
updateToolbar();
}
@Override
public void handleEvent(SessionSavedEvent e) {
updateToolbar();
}
@Override
public void handleEvent(SessionSaveCancelledEvent e) {
updateToolbar();
}
@Override
public void handleEvent(SetCurrentNetworkEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(SetCurrentNetworkViewEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(NetworkAddedEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(NetworkViewAddedEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(NetworkDestroyedEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(NetworkViewDestroyedEvent e) {
if (!loadingSession)
updateToolbar();
}
@Override
public void handleEvent(SetCurrentTableEvent e) {
if (!loadingSession)
updateToolbar();
}
/**
* This is mainly for listening to node/edge selection events.
*/
@Override
public void handleEvent(RowsSetEvent e) {
if (!loadingSession && e.containsColumn(CyNetwork.SELECTED))
updateToolbar();
}
@Override
public void handleEvent(UpdateNetworkPresentationEvent e) {
if (!loadingSession && e.getSource()
.equals(serviceRegistrar.getService(CyApplicationManager.class).getCurrentNetworkView()))
updateToolbar();
}
private void updateToolbar() {
debounceTimer.debounce(() -> {
invokeOnEDT(() -> {
for (var action : toolbar.getAllToolBarActions())
action.updateEnableState();
});
});
}
}
|
package com.yammer.telemetry.test;
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler;
import com.yammer.telemetry.instrumentation.TelemetryTransformer;
import org.junit.Before;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.fail;
public class TelemetryTestHelpers {
public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
Method[] methods = clazz.getDeclaredMethods();
Map<Method, Throwable> testFailures = new HashMap<>();
int ran = 0;
for (Method method : methods) {
if (method.isAnnotationPresent(TransformedTest.class)) {
try {
ran++;
runTransformed(clazz, method.getName(), handlers);
} catch (Exception e) {
//noinspection ThrowableResultOfMethodCallIgnored
testFailures.put(method, unwrap(e));
}
}
}
if (!testFailures.isEmpty()) {
StringWriter builder = new StringWriter();
PrintWriter writer = new PrintWriter(builder);
writer.println("Transformed tests failed:");
for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
//noinspection ThrowableResultOfMethodCallIgnored
entry.getValue().printStackTrace(writer);
writer.println();
}
fail(builder.toString());
}
if (ran == 0) {
fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
}
}
private static Throwable unwrap(Throwable e) {
if (e instanceof InvocationTargetException) {
return e.getCause();
}
return e;
}
public static void runTransformed(Class<?> clazz, String method, ClassInstrumentationHandler... handlers) throws Exception {
Set<String> befores = new HashSet<>();
for (Method beforeMethod : clazz.getDeclaredMethods()) {
if (beforeMethod.isAnnotationPresent(Before.class)) {
befores.add(beforeMethod.getName());
}
}
TelemetryTransformer transformer = new TelemetryTransformer();
for (ClassInstrumentationHandler handler : handlers) {
transformer.addHandler(handler);
}
try (TransformingClassLoader loader = new TransformingClassLoader(transformer)) {
Class<?> aClass = loader.loadClass(clazz.getName());
Object instance = aClass.newInstance();
for (String beforeMethod : befores) {
Method before = aClass.getDeclaredMethod(beforeMethod);
before.invoke(instance);
}
Method declaredMethod = aClass.getDeclaredMethod(method);
declaredMethod.invoke(instance);
}
}
}
|
package com.asksunny.codegen.java;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import com.asksunny.codegen.CodeGenConfig;
import com.asksunny.codegen.GroupFunction;
import com.asksunny.codegen.utils.ParamMapBuilder;
import com.asksunny.codegen.utils.TemplateUtil;
import com.asksunny.schema.Entity;
import com.asksunny.schema.Field;
import com.asksunny.schema.FieldDrillDownComparator;
import com.asksunny.schema.FieldGroupLevelComparator;
import com.asksunny.schema.FieldOrderComparator;
import com.asksunny.schema.parser.JdbcSqlTypeMap;
public class MyBatisXmlEntityGenerator extends CodeGenerator {
static final String INDENDENT_1 = " ";
static final String INDENDENT_2 = " ";
static final String INDENDENT_3 = " ";
static final String INDENDENT_4 = " ";
static final String NEWLINE = "\n";
private String javaEntityName = null;
private String javaEntityVarName = null;
private List<Field> primaryKeys = new ArrayList<>();
private List<Field> allFields = null;
private List<String> allFieldNames = new ArrayList<>();
private List<String> allFieldDbNames = new ArrayList<>();
private int fieldsSize = 0;
public void doCodeGen() throws IOException {
StringBuilder xmlmapper = new StringBuilder();
xmlmapper.append(genResultMap()).append(NEWLINE);
xmlmapper.append(genInsert()).append(NEWLINE);
xmlmapper.append(genSelectBasic()).append(NEWLINE);
if (entity.hasKeyField()) {
xmlmapper.append(genSelectByKey()).append(NEWLINE);
xmlmapper.append(genUpdate()).append(NEWLINE);
xmlmapper.append(genDelete()).append(NEWLINE);
}
if (entity.hasGroupByFields()) {
xmlmapper.append(genSelectByGroup()).append(NEWLINE);
}
if (entity.hasDrillDownFields()) {
xmlmapper.append(genDrilldown()).append(NEWLINE);
}
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"MyBatis.xml.tmpl")),
ParamMapBuilder
.newBuilder()
.addMapEntry("MAPPER_PACKAGE_NAME",
configuration.getMapperPackageName())
.addMapEntry("DOMAIN_PACKAGE_NAME",
configuration.getDomainPackageName())
.addMapEntry("REST_PACKAGE_NAME",
configuration.getRestPackageName())
.addMapEntry("SQLMAP", xmlmapper.toString())
.addMapEntry("ENTITY_VAR_NAME",
entity.getEntityVarName())
.addMapEntry("ENTITY_NAME",
entity.getEntityObjectName())
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
String filePath = configuration.getMapperPackageName().replaceAll(
"[\\.]", "/");
writeCode(new File(configuration.getMyBatisXmlBaseDir(), filePath),
String.format("%sMapper.xml", entity.getEntityObjectName()),
generated);
}
public String genInsert() throws IOException {
List<String> collist = new ArrayList<>();
List<String> vallist = new ArrayList<>();
for (int i = 0; i < fieldsSize; i++) {
Field fd = this.allFields.get(i);
if (!fd.isAutogen()) {
collist.add(fd.getName());
vallist.add(String.format("#{%s,jdbcType=%s}", fd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(fd.getJdbcType())));
}
}
String cols = StringUtils.join(collist, ",");
String vals = StringUtils.join(vallist, ",\n" + INDENDENT_2);
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.insert.xml.tmpl")),
ParamMapBuilder.newBuilder()
.addMapEntry("FIELD_SELECT_LIST", cols)
.addMapEntry("INSERT_VALUES_LIST", vals)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genUpdate() throws IOException {
if (!entity.hasKeyField()) {
return null;
}
List<String> keyCols = new ArrayList<>();
List<String> updateList = new ArrayList<>();
int knum = 0;
for (int i = 0; i < fieldsSize; i++) {
Field fd = this.allFields.get(i);
if (!fd.isAutogen()) {
updateList.add(String.format("%s=#{%s,jdbcType=%s}",
fd.getName(), fd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(fd.getJdbcType())));
}
if (fd.isUnique()) {
keyCols.add(String.format("%s=#{%s,jdbcType=%s}", fd.getName(),
fd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(fd.getJdbcType())));
knum++;
}
}
String keyType = knum > 1 ? javaEntityName : JdbcSqlTypeMap
.toJavaTypeName(entity.getKeyField());
String updateLists = StringUtils.join(updateList, ",\n ");
String whereClause = StringUtils.join(keyCols, "\n AND ");
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.update.xml.tmpl")),
ParamMapBuilder.newBuilder().addMapEntry("KEY_TYPE", keyType)
.addMapEntry("UPDATE_FIELD_LIST", updateLists)
.addMapEntry("WHERE_CLAUSE", whereClause)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genDelete() throws IOException {
if (!entity.hasKeyField()) {
return null;
}
List<String> keyCols = new ArrayList<>();
int knum = 0;
for (int i = 0; i < fieldsSize; i++) {
Field fd = this.allFields.get(i);
if (fd.isUnique()) {
keyCols.add(String.format("%s=#{%s,jdbcType=%s}", fd.getName(),
fd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(fd.getJdbcType())));
knum++;
}
}
String keyType = knum > 1 ? javaEntityName : JdbcSqlTypeMap
.toJavaTypeName(entity.getKeyField());
String whereClause = StringUtils.join(keyCols, "\n AND ");
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.delete.xml.tmpl")),
ParamMapBuilder.newBuilder().addMapEntry("KEY_TYPE", keyType)
.addMapEntry("WHERE_CLAUSE", whereClause)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genSelectBasic() throws IOException {
List<Field> sortFields = new ArrayList<>(this.allFields);
Collections.sort(sortFields, new FieldOrderComparator());
List<String> collist = new ArrayList<>();
for (int i = 0; i < fieldsSize; i++) {
Field fd = sortFields.get(i);
collist.add(fd.getName());
}
String orderby = entity.getOrderBy() == null ? ""
: ("ORDER BY " + entity.getOrderBy());
String cols = StringUtils.join(collist, ",");
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.select.xml.tmpl")),
ParamMapBuilder.newBuilder()
.addMapEntry("FIELD_SELECT_LIST", cols)
.addMapEntry("ORDER_BY", orderby)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genSelectByKey() throws IOException {
if (!this.entity.hasKeyField()) {
return null;
}
List<Field> sortFields = new ArrayList<>(this.allFields);
Collections.sort(sortFields, new FieldOrderComparator());
List<String> collist = new ArrayList<>();
List<Field> keyFields = new ArrayList<>();
for (int i = 0; i < fieldsSize; i++) {
Field fd = sortFields.get(i);
collist.add(fd.getName());
if (fd.isUnique()) {
keyFields.add(fd);
}
}
String keyType = keyFields.size() > 1 ? javaEntityName : JdbcSqlTypeMap
.toJavaTypeName(keyFields.get(0));
List<String> whereList = new ArrayList<>();
for (Field fd : keyFields) {
whereList.add(String.format("%s=#{%s,jdbcType=%s}", fd.getName(),
fd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(fd.getJdbcType())));
}
String whereClause = StringUtils.join(whereList, " AND\n");
String orderby = entity.getOrderBy() == null ? ""
: ("ORDER BY " + entity.getOrderBy());
String cols = StringUtils.join(collist, ",");
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.select.bykey.xml.tmpl")),
ParamMapBuilder.newBuilder()
.addMapEntry("FIELD_SELECT_LIST", cols)
.addMapEntry("KEY_TYPE", keyType)
.addMapEntry("WHERE_KEY_FIELD", whereClause)
.addMapEntry("ORDER_BY", orderby)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genSelectByGroup() throws IOException {
List<Field> sortFields = new ArrayList<>(this.allFields);
Collections.sort(sortFields, new FieldOrderComparator());
List<String> collist = new ArrayList<>();
List<Field> groupList = entity.getGroupByFields();
Field gffd = entity.getGroupFunctionField();
if (gffd != null) {
collist.add(String.format("%1$s(%2$s) as %2$s", gffd
.getGroupFunction().toString(), gffd.getName()));
}
if (groupList.size() > 0) {
Collections.sort(groupList, new FieldGroupLevelComparator());
}
int gpSize = groupList.size();
StringBuilder orderby = new StringBuilder();
StringBuilder groupBy = new StringBuilder();
StringBuilder groupByKey = new StringBuilder();
List<String> gbs = new ArrayList<>();
for (int i = 0; i < gpSize; i++) {
Field fd = groupList.get(i);
collist.add(i, fd.getName());
gbs.add(fd.getName());
groupByKey.append(fd.getObjectname());
}
orderby.append(StringUtils.join(gbs, ","));
groupBy.append(StringUtils.join(gbs, ","));
String cols = StringUtils.join(collist, ",");
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.select.groupby.xml.tmpl")), ParamMapBuilder
.newBuilder().addMapEntry("FIELD_SELECT_LIST", cols)
.addMapEntry("ORDER_BY_FIELD", orderby.toString())
.addMapEntry("GROUP_BY_KEY", groupByKey.toString())
.addMapEntry("GROUP_BY_FIELD", groupBy.toString())
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public String genDrilldown() throws IOException {
List<Field> sortFields = new ArrayList<>(this.allFields);
Collections.sort(sortFields, new FieldOrderComparator());
List<String> collist = new ArrayList<>();
List<String> plainlist = new ArrayList<>();
List<Field> groupList = entity.getDrillDownFields();
if (groupList.size() > 0) {
Collections.sort(groupList, new FieldDrillDownComparator());
}
Field gffd = entity.getGroupFunctionField();
if (gffd != null) {
collist.add(String.format("%1$s(%2$s) as %2$s", gffd
.getGroupFunction().toString(), gffd.getName()));
plainlist.add(gffd.getName());
}
int gpSize = groupList.size();
String generated = null;
if (gpSize > 0) {
StringBuilder cols = new StringBuilder();
List<String> gbs = new ArrayList<>();
Field fd = groupList.get(0);
List<String> acollist = new ArrayList<>(collist);
acollist.add(0, fd.getName());
gbs.add(fd.getName());
cols.append(StringUtils.join(acollist, ','));
generated = toGroupBySql("myBatis.select.drilldowntop.xml.tmpl",
cols.toString(), fd, null, null);
}
if (gpSize > 1) {
StringBuilder allsql = new StringBuilder();
allsql.append(generated);
List<String> innercollist = new ArrayList<>(plainlist);
innercollist.add(0, groupList.get(0).getName());
for (int i = 1; i < gpSize; i++) {
List<String> acollist = new ArrayList<>(collist);
List<String> whereClauses = new ArrayList<>();
for (int k = 0; k < i; k++) {
Field whfd = groupList.get(k);
whereClauses
.add(String.format(String.format(
"%s=#{%s,jdbcType=%s}", whfd.getName(),
whfd.getVarname(),
JdbcSqlTypeMap.getJdbcTyepName(whfd
.getJdbcType()))));
}
innercollist.add(i, groupList.get(i).getName());
acollist.add(0, groupList.get(i).getName());
generated = toGroupBySql("myBatis.select.drilldown.xml.tmpl",
StringUtils.join(acollist, ','), groupList.get(i),
StringUtils.join(innercollist, ','),
StringUtils.join(whereClauses, " AND "));
allsql.append("\n").append(generated);
}
generated = allsql.toString();
}
return generated;
}
protected String toGroupBySql(String tmpl, String selectionList,
Field gbField, String innerSQl, String whereClause)
throws IOException {
return TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(tmpl)),
ParamMapBuilder.newBuilder()
.addMapEntry("FIELD_SELECT_LIST", selectionList)
.addMapEntry("ORDER_BY_FIELD", gbField.getName())
.addMapEntry("GROUP_BY_KEY", gbField.getObjectname())
.addMapEntry("GROUP_BY_FIELD", gbField.getName())
.addMapEntry("WHERE_KEY_FIELD", whereClause)
.addMapEntry("INNER_FIELD_SELECT_LIST", innerSQl)
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
}
public String genResultMap() throws IOException {
StringBuilder fdmapping = new StringBuilder();
String primaryKey = "";
for (int i = 0; i < fieldsSize; i++) {
Field fd = this.allFields.get(i);
if (!fd.isPrimaryKey()) {
fdmapping.append(String.format(
"<result property=\"%s\" column=\"%s\" />\n%s",
fd.getVarname(), fd.getName(), INDENDENT_4));
} else {
primaryKey = String.format(
"<id property=\"%s\" column=\"%s\" />",
fd.getVarname(), fd.getName());
}
}
String generated = TemplateUtil.renderTemplate(
IOUtils.toString(getClass().getResourceAsStream(
"myBatis.resultmap.xml.templ")),
ParamMapBuilder.newBuilder()
.addMapEntry("PRIMARY_KEY_PROP", primaryKey)
.addMapEntry("FIELD_MAPPINGS", fdmapping.toString())
.addMapEntry("TABLE_NAME", entity.getName())
.addMapEntry("ENTITY_VAR_NAME", javaEntityVarName)
.addMapEntry("ENTITY_NAME", javaEntityName)
.addMapEntry("ENTITY_LABEL", entity.getLabel())
.buildMap());
return generated;
}
public MyBatisXmlEntityGenerator(CodeGenConfig configuration, Entity entity) {
super(configuration, entity);
this.javaEntityName = this.entity.getEntityObjectName();
this.javaEntityVarName = this.entity.getEntityVarName();
this.allFields = this.entity.getFields();
this.fieldsSize = this.allFields.size();
for (int i = 0; i < fieldsSize; i++) {
Field fd = this.allFields.get(i);
if (fd.isUnique()) {
this.primaryKeys.add(fd);
}
this.allFieldDbNames.add(fd.getName());
this.allFieldNames.add(fd.getObjectname());
}
}
}
|
package org.openlmis.functional;
import cucumber.api.DataTable;
import cucumber.api.java.en.And;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.LoginPage;
import org.openlmis.pageobjects.PageObjectFactory;
import org.openlmis.pageobjects.ViewOrdersPage;
import org.openlmis.pageobjects.edi.ConvertOrderPage;
import org.testng.annotations.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static java.util.Arrays.asList;
@Listeners(CaptureScreenshotOnFailureListener.class)
public class DownloadOrderFile extends TestCaseHelper {
public String program = "HIV";
public String passwordUsers = "TQskzK3iiLfbRVHeM1muvBCiiKriibfl6lh8ipo91hb74G3OvsybvkzpPI4S3KIeWTXAiiwlUU0iiSxWii4wSuS8mokSAieie";
public String userSICUserName = "storeInCharge";
public String[] csvRows = null;
@BeforeMethod(groups = "requisition")
public void setUp() throws InterruptedException, SQLException, IOException {
super.setup();
}
@DataProvider(name = "envData")
public Object[][] getEnvData() {
return new Object[][]{};
}
@And("^I configure order file:$")
public void setupOrderFileConfiguration(DataTable userTable) throws SQLException {
List<Map<String, String>> data = userTable.asMaps();
for (Map map : data)
dbWrapper.setupOrderFileConfiguration(map.get("File Prefix").toString(), map.get("Header In File").toString());
}
@And("^I configure non openlmis order file columns:$")
public void setupOrderFileNonOpenLMISColumns(DataTable userTable) throws SQLException {
dbWrapper.deleteRowFromTable("order_file_columns", "openLMISField", "false");
List<Map<String, String>> data = userTable.asMaps();
for (Map map : data)
dbWrapper.setupOrderFileNonOpenLMISColumns(map.get("Data Field Label").toString(), map.get("Include In Order File").toString(), map.get("Column Label").toString(), Integer.parseInt(map.get("Position").toString()));
}
@And("^I configure openlmis order file columns:$")
public void setupOrderFileOpenLMISColumns(DataTable userTable) throws SQLException {
List<Map<String, String>> data = userTable.asMaps();
for (Map map : data)
dbWrapper.setupOrderFileOpenLMISColumns(map.get("Data Field Label").toString(), map.get("Include In Order File").toString(), map.get("Column Label").toString(), Integer.parseInt(map.get("Position").toString()), map.get("Format").toString());
}
@And("^I download order file$")
public void downloadOrderFile() throws InterruptedException {
ViewOrdersPage viewOrdersPage = PageObjectFactory.getViewOrdersPage(testWebDriver);
viewOrdersPage.downloadCSV();
testWebDriver.sleep(5000);
}
@And("^I get order data in file prefix \"([^\"]*)\"$")
public void getOrderDataFromDownloadedFile(String filePrefix) throws InterruptedException, SQLException, IOException {
String orderId = String.valueOf(dbWrapper.getMaxRnrID());
csvRows = readCSVFile(filePrefix + orderId + ".csv");
testWebDriver.sleep(5000);
deleteFile(filePrefix + orderId + ".csv");
}
@And("^I verify order file line \"([^\"]*)\" having \"([^\"]*)\"$")
public void checkOrderFileData(int lineNumber, String data) {
testWebDriver.sleep(1000);
assertTrue("Order data incorrect in line number " + lineNumber, csvRows[lineNumber - 1].contains(data));
}
public void checkOrderFileDataForPattern(int lineNumber, String data) {
Pattern orderDataPattern = Pattern.compile(data);
testWebDriver.sleep(1000);
Matcher matcher = orderDataPattern.matcher(csvRows[lineNumber - 1]);
assertTrue("Order data incorrect in line number " + lineNumber, !matcher.find());
}
@And("^I verify order date format \"([^\"]*)\" in line \"([^\"]*)\"$")
public void checkOrderFileOrderDate(String dateFormat, int lineNumber) throws SQLException {
String createdDate = dbWrapper.getCreatedDate("orders", dateFormat);
assertTrue("Order date incorrect.", csvRows[lineNumber - 1].contains(createdDate));
}
@And("^I verify order id in line \"([^\"]*)\"$")
public void checkOrderFileOrderId(int lineNumber) throws SQLException {
String orderId = String.valueOf(dbWrapper.getMaxRnrID());
assertTrue("Order date incorrect.", csvRows[lineNumber - 1].contains(orderId));
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function")
public void testVerifyOrderFileForDefaultConfiguration(String password) throws InterruptedException, SQLException, IOException {
dbWrapper.setupOrderFileConfiguration("O", "TRUE");
setupDownloadOrderFileSetup(password);
getOrderDataFromDownloadedFile("O");
checkOrderFileData(1, "Order number,Facility code,Product code,Product name,Approved quantity,Period,Order date");
checkOrderFileData(2, ",\"F10\",\"P10\",\"antibiotic Capsule 300/200/600 mg\",\"10\",\"01/12\",");
checkOrderFileOrderDate("dd/MM/yy", 2);
checkOrderFileOrderId(2);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function")
public void testVerifyOrderFileHavingStrengthFormDossageUnitIsNull(String password) throws InterruptedException, SQLException, IOException {
dbWrapper.setupOrderFileConfiguration("O", "TRUE");
List<String> rightsList = asList("CREATE_REQUISITION", "VIEW_REQUISITION", "APPROVE_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSICUserName, "200", rightsList);
setupTestRoleRightsData("lmu", "CONVERT_TO_ORDER,VIEW_ORDER");
dbWrapper.insertUser("212", "lmu", passwordUsers, "F10", "Jake_Doe@openlmis.com");
dbWrapper.insertRoleAssignment("212", "lmu");
dbWrapper.insertFulfilmentRoleAssignment("lmu", "lmu", "F10");
dbWrapper.updateFieldValueToNull("products", "strength", "code", "P10");
dbWrapper.updateFieldValueToNull("products", "formid", "code", "P10");
dbWrapper.updateFieldValueToNull("products", "dosageunitid", "code", "P10");
LoginPage loginPage = PageObjectFactory.getLoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSICUserName, password);
homePage.navigateAndInitiateRnr(program);
homePage.clickProceed();
testWebDriver.sleep(2000);
dbWrapper.insertValuesInRequisition(false);
dbWrapper.insertValuesInRegimenLineItems("100", "200", "300", "Regimens data filled");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSICUserName, "HIV");
dbWrapper.updateRequisitionStatus("AUTHORIZED", userSICUserName, "HIV");
dbWrapper.updateFieldValue("requisition_line_items", "quantityApproved", 10);
dbWrapper.updateRequisitionStatus("APPROVED", userSICUserName, "HIV");
homePage.logout(baseUrlGlobal);
loginPage.loginAs("lmu", password);
homePage.navigateConvertToOrder();
ConvertOrderPage convertOrderPage = PageObjectFactory.getConvertOrderPage(testWebDriver);
convertOrderPage.clickConvertToOrderButton();
convertOrderPage.clickCheckBoxConvertToOrder();
convertOrderPage.clickConvertToOrderButton();
convertOrderPage.clickOk();
homePage.navigateViewOrders();
downloadOrderFile();
getOrderDataFromDownloadedFile("O");
checkOrderFileData(1, "Order number,Facility code,Product code,Product name,Approved quantity,Period,Order date");
checkOrderFileDataForPattern(2, "//d*\",\"F10\",\"P10\",\"antibiotic \",\"10\",\"01/12\",");
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function")
public void testVerifyOrderFileForDefaultConfigurationWithNoHeaders(String password) throws InterruptedException, SQLException, IOException {
dbWrapper.setupOrderFileConfiguration("O", "FALSE");
setupDownloadOrderFileSetup(password);
getOrderDataFromDownloadedFile("O");
checkOrderFileData(1, ",\"F10\",\"P10\",\"antibiotic Capsule 300/200/600 mg\",\"10\",\"01/12\",");
checkOrderFileOrderDate("dd/MM/yy", 1);
checkOrderFileOrderId(1);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function")
public void testVerifyOrderFileForSpecificConfiguration(String password) throws SQLException, IOException, InterruptedException {
dbWrapper.setupOrderFileConfiguration("Zero", "TRUE");
dbWrapper.setupOrderFileOpenLMISColumns("create.facility.code", "TRUE", "Facility code", 6, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.order.number", "TRUE", "Order number", 8, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.quantity.approved", "TRUE", "Approved quantity", 2, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.product.code", "TRUE", "Product code", 3, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.product.name", "TRUE", "Product name", 4, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.order.date", "TRUE", "Order date", 5, "MM-dd-yyyy");
dbWrapper.setupOrderFileOpenLMISColumns("label.period", "TRUE", "Period", 7, "yyyy-MM");
dbWrapper.deleteRowFromTable("order_file_columns", "openLMISField", "false");
dbWrapper.setupOrderFileNonOpenLMISColumns("Not Applicable", "TRUE", "Extra 1", 1);
dbWrapper.setupOrderFileNonOpenLMISColumns("Not Applicable", "TRUE", "", 9);
setupDownloadOrderFileSetup(password);
getOrderDataFromDownloadedFile("Zero");
checkOrderFileData(1, "Extra 1,Approved quantity,Product code,Product name,Order date,Facility code,Period,Order number,");
checkOrderFileData(2, ",\"10\",\"P10\",\"antibiotic Capsule 300/200/600 mg\"");
checkOrderFileData(2, ",\"F10\",\"2012-01\",");
checkOrderFileOrderDate("MM-dd-yyyy", 2);
checkOrderFileOrderId(2);
dbWrapper.setupOrderFileOpenLMISColumns("create.facility.code", "TRUE", "Facility code", 2, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.order.number", "TRUE", "Order number", 1, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.quantity.approved", "TRUE", "Approved quantity", 5, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.product.code", "TRUE", "Product code", 3, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.product.name", "TRUE", "Product name", 4, "");
dbWrapper.setupOrderFileOpenLMISColumns("header.order.date", "TRUE", "Order date", 7, "dd/MM/yy");
dbWrapper.setupOrderFileOpenLMISColumns("label.period", "TRUE", "Period", 6, "MM/yy");
dbWrapper.deleteRowFromTable("order_file_columns", "openLMISField", "false");
}
public void setupDownloadOrderFileSetup(String password) throws SQLException, InterruptedException {
List<String> rightsList = asList("CREATE_REQUISITION", "VIEW_REQUISITION", "APPROVE_REQUISITION");
setupTestDataToInitiateRnR(true, program, userSICUserName, "200", rightsList);
setupTestRoleRightsData("lmu", "CONVERT_TO_ORDER,VIEW_ORDER");
dbWrapper.insertUser("212", "lmu", passwordUsers, "F10", "Jake_Doe@openlmis.com");
dbWrapper.insertRoleAssignment("212", "lmu");
dbWrapper.insertFulfilmentRoleAssignment("lmu", "lmu", "F10");
LoginPage loginPage = PageObjectFactory.getLoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSICUserName, password);
homePage.navigateAndInitiateRnr(program);
homePage.clickProceed();
testWebDriver.sleep(2000);
dbWrapper.insertValuesInRequisition(false);
dbWrapper.insertValuesInRegimenLineItems("100", "200", "300", "Regimens data filled");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSICUserName, "HIV");
dbWrapper.updateRequisitionStatus("AUTHORIZED", userSICUserName, "HIV");
dbWrapper.updateFieldValue("requisition_line_items", "quantityApproved", 10);
dbWrapper.updateRequisitionStatus("APPROVED", userSICUserName, "HIV");
homePage.logout(baseUrlGlobal);
loginPage.loginAs("lmu", password);
homePage.navigateConvertToOrder();
ConvertOrderPage convertOrderPage = PageObjectFactory.getConvertOrderPage(testWebDriver);
convertOrderPage.clickConvertToOrderButton();
convertOrderPage.clickCheckBoxConvertToOrder();
convertOrderPage.clickConvertToOrderButton();
convertOrderPage.clickOk();
homePage.navigateViewOrders();
downloadOrderFile();
}
@AfterMethod(groups = "requisition")
public void tearDown() throws SQLException {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = PageObjectFactory.getHomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
}
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"Admin123"}
};
}
}
|
import junit.framework.*;
/**
* JUnits tests for the Java subversion binding helper functions
*/
public class AllTests {
public static void main( String [] args )
{
junit.textui.TestRunner.run( suite() );
}
public static Test suite( )
{
TestSuite suite = new TestSuite(
"All JUnit tests for the Java Subversion binding");
//add tests here
//example:
//suite.addTest( new StatusTest() );
suite.addTestSuite( DateTests.class );
suite.addTestSuite( EntryTests.class );
suite.addTestSuite( VectorTests.class );
suite.addTestSuite( HashtableTests.class );
return suite;
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public final class MainPanel extends JPanel {
private final String[] columnNames = {"String", "Integer", "Boolean"};
private final Object[][] data = {
{"aaa", 12, true}, {"bbb", 5, false},
{"CCC", 92, true}, {"DDD", 0, false}
};
private final DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
// ArrayIndexOutOfBoundsException: 0 >= 0
// Bug ID: JDK-6967479 JTable sorter fires even if the model is empty
//return getValueAt(0, column).getClass();
switch (column) {
case 0:
return String.class;
case 1:
return Number.class;
case 2:
return Boolean.class;
default:
return super.getColumnClass(column);
}
}
};
private final JTable table = new JTable(model);
private final JCheckBox check = new JCheckBox("viewport setOpaque");
private final JButton button = new JButton("Choose background color");
public MainPanel() {
super(new BorderLayout());
table.setAutoCreateRowSorter(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(60);
col.setMaxWidth(60);
col.setResizable(false);
JScrollPane scroll = new JScrollPane(table);
scroll.setComponentPopupMenu(new TablePopupMenu());
//scroll.getViewport().setInheritsPopupMenu(true); // 1.5.0
table.setInheritsPopupMenu(true);
//table.setFillsViewportHeight(true);
scroll.getViewport().setOpaque(true);
//scroll.getViewport().setBackground(Color.WHITE);
check.setSelected(true);
check.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
scroll.getViewport().setOpaque(true);
} else if (e.getStateChange() == ItemEvent.DESELECTED) {
scroll.getViewport().setOpaque(false);
}
scroll.repaint();
});
button.addActionListener(e -> {
Color color = JColorChooser.showDialog(getRootPane(), "background color", scroll.getViewport().getBackground());
scroll.getViewport().setBackground(color);
scroll.repaint();
});
JPanel pnl = new JPanel();
pnl.add(check);
pnl.add(button);
add(scroll);
add(pnl, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
class TestCreateAction extends AbstractAction {
protected TestCreateAction(String label) {
super(label);
}
@Override public void actionPerformed(ActionEvent e) {
model.addRow(new Object[] {"New row", model.getRowCount(), false});
Rectangle r = table.getCellRect(model.getRowCount() - 1, 0, true);
table.scrollRectToVisible(r);
}
}
class DeleteAction extends AbstractAction {
protected DeleteAction(String label) {
super(label);
}
@Override public void actionPerformed(ActionEvent e) {
int[] selection = table.getSelectedRows();
for (int i = selection.length - 1; i >= 0; i
model.removeRow(table.convertRowIndexToModel(selection[i]));
}
}
}
private class TablePopupMenu extends JPopupMenu {
private final Action deleteAction = new DeleteAction("delete");
protected TablePopupMenu() {
super();
add(new TestCreateAction("add"));
addSeparator();
add(deleteAction);
}
@Override public void show(Component c, int x, int y) {
deleteAction.setEnabled(table.getSelectedRowCount() > 0);
super.show(c, x, y);
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
public class ChatServerGUI extends javax.swing.JFrame {
/**
* Creates new form ChatServerGUI
*/
public ChatServerGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
btnConectar = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txtNomeUsuarioServer = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtPortaSever = new javax.swing.JTextField();
txtServer = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Porta");
btnConectar.setText("Conectar");
btnConectar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConectarActionPerformed(evt);
}
});
jLabel2.setText("Nome do Usuario");
txtNomeUsuarioServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNomeUsuarioServerActionPerformed(evt);
}
});
jLabel3.setText("Servidor");
txtPortaSever.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtPortaSeverActionPerformed(evt);
}
});
txtServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtServerActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtNomeUsuarioServer)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(53, 53, 53))
.addGroup(layout.createSequentialGroup()
.addComponent(txtServer)
.addGap(12, 12, 12)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(txtPortaSever, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnConectar, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtPortaSever, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConectar))
.addComponent(txtServer))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtNomeUsuarioServer, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void txtNomeUsuarioServerActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void txtPortaSeverActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void txtServerActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ChatServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatServerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatServerGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnConectar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField txtNomeUsuarioServer;
private javax.swing.JTextField txtPortaSever;
private javax.swing.JTextField txtServer;
// End of variables declaration
}
|
package jpt.app00;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpServer;
public class Main {
private static final int DEFAULT_QUEUE_SIZE = 0;
private static final int DEFAULT_PORT_NUMBER = 7666;
public static void main(String[] args) throws IOException {
int portNumber = DEFAULT_PORT_NUMBER;
int queueSize = DEFAULT_QUEUE_SIZE;
for (String arg : args) {
if (arg.startsWith("-p")) {
portNumber = Integer.parseInt(arg.replaceFirst("\\-p", ""));
} else if (arg.startsWith("-q")) {
queueSize = Integer.parseInt(arg.replaceFirst("\\-q", ""));
} else {
System.err.println("Usage: java " + Main.class.getName() + " [option...]");
System.err.println("Options: ");
System.err.println(" -p<i> change the listen port number (" + DEFAULT_PORT_NUMBER +")");
System.err.println(" -q<i> change the queue size (" + DEFAULT_QUEUE_SIZE + ")");
System.exit(1);
}
}
HttpServer server = HttpServer.create(new InetSocketAddress(portNumber), queueSize);
server.createContext("/", new Handler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port " + portNumber);
}
}
|
package com.tankformers;
import static com.tankformers.Game.newGameBoard;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.tankformers.model.Board;
public class Tankformers implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Board board;
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h / w);
batch = new SpriteBatch();
board = newGameBoard();
scheduleClock();
}
private void scheduleClock() {
Timer.schedule(new Task() {
@Override
public void run() {
if (Gdx.input.isKeyPressed(Keys.UP)) {
board.tankA.drive(1);
}
if (Gdx.input.isKeyPressed(Keys.DOWN)) {
board.tankA.drive(-0.5f);
}
if (Gdx.input.isKeyPressed(Keys.LEFT)) {
board.tankA.turn(1);
}
if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
board.tankA.turn(-1);
}
}
}, 0, 1 / 30.0f);
}
@Override
public void dispose() {
batch.dispose();
Painting.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
Painting.draw(board.tankA, batch);
Painting.draw(board.tankB, batch);
batch.end();
}
@Override
public void resize(int width, int height) {}
@Override
public void pause() {}
@Override
public void resume() {}
}
|
package com.example.icampgeofence;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
import com.google.android.gms.location.LocationClient.OnRemoveGeofencesResultListener;
import com.google.android.gms.location.LocationStatusCodes;
public class LocationMgr implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static final String TRANSITION_INTENT_ACTION = "geofence_transition";
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private final static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001;
private final Activity parentActivity;
private LocationClient locationClient = null;
// Stores the PendingIntent used to request geofence monitoring
private PendingIntent geofenceRequestIntent;
// Flag that indicates if a request is underway.
private boolean inProgress = false;
public interface OnDeleteFenceListener {
void onDeleteFence(String id);
}
public LocationMgr(Activity parent) {
parentActivity = parent;
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
locationClient = new LocationClient(parentActivity, this, this);
}
public LocationClient getClient() {
return locationClient;
}
protected void connect() {
// Connect the client.
try {
locationClient.connect();
}
catch (Exception e) {
Log.e("LocationMgr could not connect.", e.getMessage(), e);
}
}
protected void disconnect() {
// Disconnecting the client invalidates it.
locationClient.disconnect();
}
public void setMockLocation(double latitude, double longitude, float accuracy) {
LocationManager lm = (LocationManager) parentActivity.getSystemService(Context.LOCATION_SERVICE);
lm.addTestProvider(LocationManager.GPS_PROVIDER,
"requiresNetwork" == "",
"requiresSatellite" == "",
"requiresCell" == "",
"hasMonetaryCost" == "",
"supportsAltitude" == "",
"supportsSpeed" == "",
"supportsBearing" == "",
android.location.Criteria.NO_REQUIREMENT,
android.location.Criteria.ACCURACY_FINE);
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
newLocation.setLatitude(latitude);
newLocation.setLongitude(longitude);
newLocation.setAccuracy(accuracy);
lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE,
null,System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, newLocation);
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(parentActivity, "Connected", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(parentActivity, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
parentActivity,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
}
catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
}
else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
showErrorDialog(connectionResult.getErrorCode());
}
}
void showErrorDialog(int code) {
GooglePlayServicesUtil.getErrorDialog(code, parentActivity, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
}
/*
* Create a PendingIntent that triggers an IntentService in your
* app when a geofence transition occurs.
*/
private PendingIntent getTransitionPendingIntent() {
// Create an explicit Intent
Intent intent = new Intent(parentActivity, ReceiveTransitionsIntentService.class);
intent.setAction(TRANSITION_INTENT_ACTION);
/*
* Return the PendingIntent
*/
return PendingIntent.getService(
parentActivity,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
public void addGeofence(final Fence fence) {
// get pending intent for geofence transitions
geofenceRequestIntent = getTransitionPendingIntent();
// create new Geofence from Fence and add to play services
Geofence gf = fence.asGeofence();
List<Geofence> gfList = new ArrayList<Geofence>();
gfList.add(gf);
// Send a request to add the current geofences
locationClient.addGeofences(gfList, geofenceRequestIntent, new OnAddGeofencesResultListener() {
@Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
// if successful, persist the new Fence
if (LocationStatusCodes.SUCCESS == statusCode) {
FenceMgr.getDefault().add(fence);
Toast.makeText(parentActivity, "Added new geofence named " + fence.getName(), Toast.LENGTH_SHORT).show();
}
else {
// If adding the geofences failed
/*
* Report errors here.
* You can log the error using Log.e() or update
* the UI.
*/
}
// Turn off the in progress flag
inProgress = false;
// disconnect the client
//locationClient.disconnect();
}
});
}
public void removeGeofence(final Fence fence, final OnDeleteFenceListener listener) {
List<String> gfList = new ArrayList<String>();
gfList.add(fence.getId());
locationClient.removeGeofences(gfList, new OnRemoveGeofencesResultListener() {
@Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode, String[] geofenceRequestIds) {
// if successful, persist the change
if (LocationStatusCodes.SUCCESS == statusCode) {
FenceMgr.getDefault().delete(fence);
listener.onDeleteFence(fence.getId());
Toast.makeText(parentActivity, "Removed geofence named " + fence.getName(), Toast.LENGTH_SHORT).show();
}
else {
// If adding the geofences failed
/*
* Report errors here.
* You can log the error using Log.e() or update
* the UI.
*/
}
// Turn off the in progress flag
inProgress = false;
}
@Override
public void onRemoveGeofencesByPendingIntentResult(int arg0, PendingIntent arg1) {
// TODO Auto-generated method stub
}
});
}
}
|
package com.example.reader;
import ilearnrw.textadaptation.TextAnnotationModule;
import ilearnrw.textclassification.Word;
import ilearnrw.user.problems.ProblemDefinition;
import ilearnrw.user.problems.ProblemDefinitionIndex;
import ilearnrw.user.problems.ProblemDescription;
import ilearnrw.user.profile.UserProfile;
import java.io.File;
import java.util.ArrayList;
import com.example.reader.interfaces.ColorPickerListener;
import com.example.reader.interfaces.OnHttpListener;
import com.example.reader.interfaces.OnProfileFetched;
import com.example.reader.results.ProfileResult;
import com.example.reader.tasks.ProfileTask;
import com.example.reader.types.ColorPickerDialog;
import com.example.reader.types.BasicListAdapter;
import com.example.reader.utils.FileHelper;
import com.example.reader.utils.HttpHelper;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
public class PresentationModule
extends
Activity
implements
OnClickListener,
OnCheckedChangeListener,
OnHttpListener,
OnProfileFetched,
OnItemSelectedListener {
private LinearLayout colorLayout, container;
private Button btnOk, btnCancel;
private RadioGroup rulesGroup;
private RadioButton rbtnRule1, rbtnRule2, rbtnRule3, rbtnRule4;
private Spinner spCategories, spProblems;
private ImageView colorBox;
private File fileHtml = null;
private File fileJSON = null;
private String html, json;
private String name = "";
private Boolean showGUI = false;
private ArrayList<Word> trickyWords;
private SharedPreferences sp;
private String TAG;
private ProblemDefinition[] definitions;
private ProblemDescription[][] descriptions;
private ProblemDescription[] problemDescriptions;
private ArrayList<String> categories;
private ArrayList<String> problems;
private final int DEFAULT_COLOR = 0xffff0000;
private final int DEFAULT_RULE = 3;
private int currentColor;
private int currentRule;
private int currentCategoryPos;
private int currentProblemPos;
private UserProfile userProfile;
private TextAnnotationModule txModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TAG = getClass().getName();
Bundle bundle = getIntent().getExtras();
boolean loadFiles = true;
if(bundle.containsKey("loadFiles"))
loadFiles = bundle.getBoolean("loadFiles");
name = bundle.getString("title", "");
showGUI = bundle.getBoolean("showGUI", false);
trickyWords = new ArrayList<Word>();
if(loadFiles){
fileHtml = (File)bundle.get("file");
fileJSON = (File)bundle.get("json");
html = FileHelper.readFromFile(fileHtml);
json = FileHelper.readFromFile(fileJSON);
} else {
html = bundle.getString("html");
json = bundle.getString("json");
}
categories = new ArrayList<String>();
problems = new ArrayList<String>();
setContentView(R.layout.activity_presentation_module);
sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putBoolean("showGUI", showGUI).commit();
int id = sp.getInt("id",-1);
String token = sp.getString("authToken", "");
if(id==-1 || token.isEmpty()) {
finished(); // If you don't have an id something is terribly wrong
throw new IllegalArgumentException("Missing id or token");
}
init();
}
private void init(){
container = (LinearLayout) findViewById(R.id.presentation_module_container);
if(showGUI)
container.setVisibility(View.VISIBLE);
else
container.setVisibility(View.GONE);
spCategories = (Spinner) findViewById(R.id.categories);
spProblems = (Spinner) findViewById(R.id.problems);
btnOk = (Button) findViewById(R.id.pm_btn_ok);
btnCancel = (Button) findViewById(R.id.pm_btn_cancel);
rulesGroup = (RadioGroup) findViewById(R.id.pm_rules);
rbtnRule1 = (RadioButton) findViewById(R.id.pm_rule1);
rbtnRule2 = (RadioButton) findViewById(R.id.pm_rule2);
rbtnRule3 = (RadioButton) findViewById(R.id.pm_rule3);
rbtnRule4 = (RadioButton) findViewById(R.id.pm_rule4);
colorLayout = (LinearLayout) findViewById(R.id.pm_color_layout);
colorBox = (ImageView) findViewById(R.id.pm_color);
btnCancel.setOnClickListener(this);
btnOk.setOnClickListener(this);
colorLayout.setOnClickListener(this);
rulesGroup.setOnCheckedChangeListener(this);
String userId = Integer.toString(sp.getInt("id", 0));
String token = sp.getString("authToken", "");
currentCategoryPos = 0;
currentProblemPos = 0;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
spCategories.setOnItemSelectedListener(this);
spProblems.setOnItemSelectedListener(this);
new ProfileTask(this, showGUI, this, this).run(userId, token);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.pm_btn_ok:
for (int i = 0; i < categories.size(); i++)
{
for (int j = 0; j < this.problems.size(); j++)
{
int color = sp.getInt("pm_color_"+i+"_"+j, DEFAULT_COLOR);
int rule = sp.getInt("pm_rule_"+i+"_"+j, DEFAULT_RULE);
this.txModule.getPresentationRulesModule().setPresentationRule(i, j, rule);
if (rbtnRule1.isChecked() || rbtnRule2.isChecked())
{
this.txModule.getPresentationRulesModule().setTextColor(i, j, color);
}
else if (rbtnRule3.isChecked() || rbtnRule4.isChecked())
{
this.txModule.getPresentationRulesModule().setHighlightingColor(i, j, color);
}
}
}
finished();
break;
case R.id.pm_btn_cancel:
onBackPressed();
break;
case R.id.pm_color_layout:
int color = sp.getInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, DEFAULT_COLOR);
ColorPickerDialog dialog = new ColorPickerDialog(this, color, new ColorPickerListener() {
@Override
public void onOk(ColorPickerDialog dialog, int color) {
sp.edit().putInt("pm_color_" + currentCategoryPos + "_" + currentProblemPos, color).commit();
updateColor(currentCategoryPos, currentProblemPos);
}
@Override
public void onCancel(ColorPickerDialog dialog) {}
});
dialog.show();
break;
}
};
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getId()) {
case R.id.pm_rules:
switch(group.getCheckedRadioButtonId()){
case R.id.pm_rule1:
currentRule = 1;
break;
case R.id.pm_rule2:
currentRule = 2;
break;
case R.id.pm_rule3:
currentRule = 3;
break;
case R.id.pm_rule4:
currentRule = 4;
break;
}
default:
break;
}
sp.edit().putInt("pm_rule_"+currentCategoryPos+"_"+currentProblemPos, currentRule).commit();
updateRule(currentCategoryPos, currentProblemPos);
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
switch(parent.getId()){
case R.id.categories:
currentCategoryPos = pos;
updateProblems(currentCategoryPos);
updateRule(currentCategoryPos, currentProblemPos);
break;
case R.id.problems:
currentProblemPos = pos;
updateColor(currentCategoryPos, currentProblemPos);
updateRule(currentCategoryPos, currentProblemPos);
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
@Override
public void onBackPressed() {
Intent i = new Intent(this, LibraryActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
private void finished(){
try
{
String input = "text/annotate?userId=" + 1 + "&lc=EN&token=";
String result = txModule.sendPostToServer(sp.getString("authToken", ""), input);
Log.i("Result", result);
}
catch (Exception e)
{
Log.i("Exception", "I am here: " +e.toString());
}
Intent intent = new Intent(PresentationModule.this, ReaderActivity.class);
intent.putExtra("html", html);
intent.putExtra("json", json);
intent.putExtra("title", name);
intent.putExtra("trickyWords", (ArrayList<Word>) trickyWords);
startActivity(intent);
}
private void updateColor(int category, int problem){
currentColor = sp.getInt("pm_color_"+category+"_"+problem, DEFAULT_COLOR);
colorBox.setBackgroundColor(currentColor);
}
private void updateRule(int category, int problem){
currentRule = sp.getInt("pm_rule_"+category+"_"+problem, DEFAULT_RULE);
switch(currentRule){
case 1:
rbtnRule1.setChecked(true);
break;
case 2:
rbtnRule2.setChecked(true);
break;
case 3:
rbtnRule3.setChecked(true);
break;
case 4:
rbtnRule4.setChecked(true);
break;
}
}
private void updateProblems(int index){
problemDescriptions = descriptions[index];
currentProblemPos = 0;
problems.clear();
for(int i=0; i<problemDescriptions.length; i++){
String[] descriptions = problemDescriptions[i].getDescriptions();
String str = "";
for(int j=0; j<descriptions.length; j++){
if(j+1<descriptions.length)
str += descriptions[j] + " | ";
else
str += descriptions[j];
}
problems.add((i+1) + ". " + str);
}
ArrayAdapter<String> problemAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, problems, true);
problemAdapter.notifyDataSetChanged();
spProblems.setAdapter(problemAdapter);
}
@Override
public void onTokenExpired(final String... params) {
if(HttpHelper.refreshTokens(this)){
final String newToken = sp.getString("authToken", "");
runOnUiThread(new Runnable() {
@Override
public void run() {
new ProfileTask(PresentationModule.this, showGUI, PresentationModule.this, PresentationModule.this).run(params[0], newToken);
Log.d(TAG, getString(R.string.token_error_retry));
Toast.makeText(PresentationModule.this, getString(R.string.token_error_retry), Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onProfileFetched(ProfileResult profile) {
trickyWords = (ArrayList<Word>) profile.userProblems.getTrickyWords();
if(!showGUI){
finished();
return;
}
ProblemDefinitionIndex index = profile.userProblems.getProblems();
definitions = index.getProblemsIndex();
descriptions = index.getProblems();
categories.clear();
for(int i=0; i<definitions.length;i++){
categories.add((i+1) + ". " + definitions[i].getType().getUrl());
}
currentCategoryPos = 0;
updateProblems(currentCategoryPos);
ArrayAdapter<String> categoryAdapter = new BasicListAdapter(this, R.layout.textview_item_multiline, categories, true);
spCategories.setAdapter(categoryAdapter);
userProfile = new UserProfile(profile.language, profile.userProblems, profile.preferences);
txModule = new TextAnnotationModule(html, userProfile);
}
}
|
package com.hp.hpl.jena.db.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.RDFRDBException;
import com.hp.hpl.jena.util.Log;
/**
* @author hkuno based on code by Dave Reynolds
*
* Extends DriverRDB with Oracle-specific parameters.
*/
public abstract class Driver_Oracle extends DriverRDB {
public int MAX_DB_IDENTIFIER_LENGTH = 30;
public int m_tablecounter;
/**
* Constructor
*/
public Driver_Oracle() {
super();
// Oracle not supported at this time
if (true) {
throw(new RDFRDBException("Oracle is not yet supported for Jena."));
}
String myPackageName = this.getClass().getPackage().getName();
DATABASE_TYPE = "Oracle";
DRIVER_NAME = "oracle.jdbc.driver.OracleDriver";
EMPTY_LITERAL_MARKER = "EmptyLiteral";
ID_SQL_TYPE = "INTEGER";
INSERT_BY_PROCEDURE = false;
INDEX_KEY_LENGTH = 250;
LONG_OBJECT_LENGTH = 250;
SKIP_ALLOCATE_ID = false;
SKIP_DUPLICATE_CHECK = true;
EMPTY_LITERAL_MARKER = "EmptyLiteral";
SQL_FILE = "etc/oracle.sql";
m_psetClassName = myPackageName + ".PSet_TripleStore_RDB";
m_psetReifierClassName = myPackageName + ".PSet_ReifStore_RDB";
m_lsetClassName = myPackageName + ".SpecializedGraph_TripleStore_RDB";
m_lsetReifierClassName = myPackageName + ".SpecializedGraphReifier_RDB";
m_tablecounter = 1;
}
/**
* Set the database connection
*/
public void setConnection( IDBConnection dbcon ) {
m_dbcon = dbcon;
try {
Properties defaultSQL = SQLCache.loadSQLFile(DEFAULT_SQL_FILE, null, ID_SQL_TYPE);
m_sql = new SQLCache(SQL_FILE, defaultSQL, dbcon, ID_SQL_TYPE);
} catch (Exception e) {
e.printStackTrace( System.err );
Log.severe("Unable to set connection for Driver:" + e);
}
}
/**
* If the underlying database connection supports transactions,
* call commit(), then turn autocommit on.
*/
public void commit() throws RDFRDBException{
if (transactionsSupported()) {
try {
if (inTransaction) {
Connection c = m_sql.getConnection();
c.commit();
c.setAutoCommit(true);
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
inTransaction = false;
}
} catch (SQLException e) {
throw new RDFRDBException("Transaction support failed: ", e);
}
}
}
}
|
package com.hp.hpl.jena.ontology.tidy;
//import java.util.Iterator;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.reasoner.InfGraph;
import com.hp.hpl.jena.graph.compose.MultiUnion;
import com.hp.hpl.jena.ontology.tidy.impl.CheckerImpl;
import com.hp.hpl.jena.ontology.*;
/**
*
* This class implements the OWL Syntax Checker,
* and is integrated with Jena Models, OntModels, and Graphs.
* The basic mode of use, is to create a Checker
* and to add one or more Models, OntModels or Graphs.
* It tries to do the right thing, vis-a-vis
* imports, without duplicating imports processing
* already performed by an {@link OntModel};
* in particular, to use a specific
* {@link OntDocumentManager}
* create an {@link OntModel} using that document
* manager. Any imports that are processed by
* this class, a private document manager is used,
* constructed from the default profile
* (with imports processing explicitly on).
* The three methods {@link #getProblems()}
* {@link #getErrors()} and {@link #getSubLanguage()}
* can all be used repeatedly and at any point. They
* report on what has been added so far.
* When constructing a checker, you must choose whether
* to record errors and problems concerning non-OWL Lite
* constructs, or only concerning non-OWL DL constructs.
* For either choice {@link #getSubLanguage()} functions
* correctly (i.e. the grammar used is identical). However,
* if the Checker has been constructed with the liteflag as false,
* it is not possible to access a rationale for an ontology
* being in OWL DL rather than OWL Lite.
*
*
* @author <a href="mailto:Jeremy.Carroll@hp.com">Jeremy Carroll</a>
*
*/
public class Checker extends CheckerImpl implements CheckerResults {
/**
* Create a new checker - indicate whether error reports
* are wanted for non-OWL Lite constructions
* or only non-OWL DL constructions.
* @param liteFlag If true
* {@link #getErrors()} and
* {@link #getProblems()} will indicate any OWL DL or OWL Full construction.
*/
public Checker(boolean liteFlag) {
super(liteFlag);
}
/**
* Adds the graph, and definitely not its imports, to the syntax check.
* Many graphs can be checked together.
* Does not process imports,
* and does not attempt to be clever at all (e.g.
no special treatment for inferred graphs,
it just processes the inferred triples as normal).
* @param g The graph to be added.
*/
public void addRaw(Graph g) {
super.addRaw(g);
}
/**
* Include an ontology and its imports
* in the check.
* @param url Load the ontology from this URL.
*/
public void load(String url) {
super.load(url);
}
/**
* Include an ontology and its imports
* in the check.
* @param url Load the ontology from this URL.
* @param lang The language (RDF/XML, N3 or N-TRIPLE) in which the ontology is written.
*/
public void load(String url,String lang) {
super.load(url,lang);
}
public void add(Graph g) {
while (g instanceof InfGraph)
g = ((InfGraph) g).getRawGraph();
if (g instanceof MultiUnion) {
// We guess that this is imports closed already.
addRaw(g);
} else {
addGraphAndImports(g);
}
}
/**
* Adds the graph, and definitely its imports, to the syntax check.
* If g is an inferred graph, the inferred triples are added (which is
* probably not what was desired).
* @param g The Graph to be added.
*/
public void addGraphAndImports(Graph g) {
addRaw(importsClosure(g));
}
/**
* Adds the model to the syntax check.
* Only considers the base triples of an inferred model
* (if recognised as such), along with any imports.
* <p>
* If the <code>Model</code> is an
* {@link com.hp.hpl.jena.ontology.OntModel} created with the {@link ModelFactory}
then the base graph with its imports (which have already
been collected) are added. Import processing is not redone
at this stage.
<p>
The behaviour is identical to that of {@link #add(Graph)};
better control,if needed, is achieved through the use of
{@link #addGraphAndImports} and {@link #addRaw}.
* @param m The Model to be added.
*/
public void add(Model m) {
add(m.getGraph());
}
}
|
package com.opencms.workplace;
import com.opencms.file.*;
import com.opencms.core.*;
import com.opencms.util.*;
import com.opencms.template.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
public class CmsAdminSiteNew extends CmsWorkplaceDefault implements com.opencms.core.I_CmsConstants {
/**
* Gets all available categories
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @exception CmsException
*/
public Integer getCategories(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws com.opencms.core.CmsException
{
Vector categories = cms.getAllCategories();
for (int z = 0; z < categories.size(); z++)
{
names.addElement(((CmsCategory) categories.elementAt(z)).getName());
values.addElement(new String(""+((CmsCategory) categories.elementAt(z)).getId()));
}
return new Integer(0);
}
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws com.opencms.core.CmsException
{
CmsXmlTemplateFile xmlTemplateDocument = getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector);
if (parameters.get("submitform") != null)
{
if (((String) parameters.get("NAME")).equals("") || ((String) parameters.get("DOMAINNAME")).equals("") || ((String) parameters.get("DESCRIPTION")).equals(""))
{
templateSelector = "datamissing";
}
else
{
cms.newSite((String) parameters.get("NAME"), (String) parameters.get("DESCRIPTION"), Integer.parseInt((String) parameters.get("CATEGORY")), Integer.parseInt((String) parameters.get("LANGUAGE")), Integer.parseInt((String) parameters.get("DOMAIN")), (String) parameters.get("DOMAINNAME"), (String) parameters.get("MANAGERGROUP"), (String) parameters.get("GROUP"));
templateSelector = "wait";
}
}
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector);
}
/**
* Gets all available domains
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @exception CmsException
*/
public Integer getDomains(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws com.opencms.core.CmsException
{
Vector countries = cms.getAllCountries();
for (int z = 0; z < countries.size(); z++)
{
names.addElement(((CmsCountry) countries.elementAt(z)).getName());
values.addElement(new String(""+((CmsCountry) countries.elementAt(z)).getCountryId()));
}
return new Integer(0);
}
/**
* Gets all available groups
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @exception CmsException
*/
public Integer getGroups(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException
{
// get all groups
Vector groups = cms.getGroups();
int retValue = -1;
String defaultGroup = C_GROUP_USERS;
I_CmsSession session = cms.getRequestContext().getSession(true);
String enteredGroup = (String) session.getValue("new_project_group");
if (enteredGroup != null && !enteredGroup.equals(""))
{
// if an error has occurred before, take the previous entry of the user
defaultGroup = enteredGroup;
}
// fill the names and values
int n = 0;
for (int z = 0; z < groups.size(); z++)
{
if (((CmsGroup) groups.elementAt(z)).getProjectCoWorker())
{
String name = ((CmsGroup) groups.elementAt(z)).getName();
if (defaultGroup.equals(name))
{
retValue = n;
}
names.addElement(name);
values.addElement(name);
n++; // count the number of ProjectCoWorkers
}
}
return new Integer(retValue);
}
/**
* Gets all available languages
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @exception CmsException
*/
public Integer getLanguages(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws com.opencms.core.CmsException
{
Vector languages = cms.getAllLanguages();
for (int z = 0; z < languages.size(); z++)
{
names.addElement(((CmsLanguage) languages.elementAt(z)).getName());
values.addElement(new String("" + ((CmsLanguage) languages.elementAt(z)).getLanguageId()));
}
return new Integer(0);
}
/**
* Gets all available groups.
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @exception CmsException
*/
public Integer getManagerGroups(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters) throws CmsException
{
// get all groups
Vector groups = cms.getGroups();
int retValue = -1;
String defaultGroup = C_GROUP_PROJECTLEADER;
I_CmsSession session = cms.getRequestContext().getSession(true);
String enteredGroup = (String) session.getValue("new_project_managergroup");
if (enteredGroup != null && !enteredGroup.equals(""))
{
// if an error has occurred before, take the previous entry of the user
defaultGroup = enteredGroup;
}
// fill the names and values
int n = 0;
for (int z = 0; z < groups.size(); z++)
{
if (((CmsGroup) groups.elementAt(z)).getProjectmanager())
{
String name = ((CmsGroup) groups.elementAt(z)).getName();
if (defaultGroup.equals(name))
{
retValue = n;
}
names.addElement(name);
values.addElement(name);
n++; // count the number of project managers
}
}
return new Integer(retValue);
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector)
{
return false;
}
}
|
package com.robrua.orianna.store;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.robrua.orianna.type.core.OriannaObject;
import com.robrua.orianna.type.exception.OriannaException;
/**
* A very simple filesystem-based DB
*
* @author Rob Rua (robrua@alumni.cmu.edu)
*/
public class FileSystemDB extends DataStore {
/**
* Iterator for DB entries on the file system
*
* @author Rob Rua (robrua@alumni.cmu.edu)
*/
public static class FSIterator<T extends OriannaObject<?>> implements Iterator<T> {
private final Class<T> clazz;
private final Iterator<File> files;
private File lastFile = null;
/**
* @param folder
* root DB folder for type
* @param clazz
* the type
*/
private FSIterator(final File folder, final Class<T> clazz) {
files = Arrays.asList(folder.listFiles()).iterator();
this.clazz = clazz;
}
@Override
public boolean hasNext() {
return files.hasNext();
}
@Override
public T next() {
lastFile = files.next();
return read(lastFile, clazz);
}
@Override
public void remove() {
if(lastFile != null) {
lastFile.delete();
}
files.remove();
}
}
private static final String HAVE_ALL_NAME = "meta";
/**
* Reads an object from a file
*
* @param file
* the file to read from
* @param type
* the type of the object stored
* @return the object in the file
*/
@SuppressWarnings("unchecked")
private static <T extends OriannaObject<?>> T read(final File file, final Class<T> type) {
try {
return (T)type.getDeclaredConstructors()[0].newInstance(readFile(file));
}
catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
return null;
}
}
/**
* Reads an object from a file
*
* @param file
* the file to read from
* @return the object in the file
*/
private static Object readFile(final File file) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(file));
return ois.readObject();
}
catch(IOException | ClassNotFoundException e) {
throw new OriannaException("Unable to read file!");
}
finally {
if(ois != null) {
try {
ois.close();
}
catch(final IOException e) {
throw new OriannaException("Unable to close file stream!");
}
}
}
}
/**
* Writes an object to a file
*
* @param file
* the file to write to
* @param object
* the object to write
*/
private static void write(final File file, final OriannaObject<?> object) {
writeFile(file, object.getDto());
}
/**
* Writes an object to a file
*
* @param file
* the file to write to
* @param object
* the object to write
*/
private static void writeFile(final File file, final Object object) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(object);
}
catch(final IOException e) {
throw new OriannaException("Unable to write to file!");
}
finally {
if(oos != null) {
try {
oos.close();
}
catch(final IOException e) {
throw new OriannaException("Unable to close file stream!");
}
}
}
}
private final Map<Class<? extends OriannaObject<?>>, Boolean> haveAll;
private final File root;
/**
* @param root
* the root folder of the DB
*/
@SuppressWarnings("unchecked")
public FileSystemDB(final File root) {
if(root == null || root.exists() && !root.isDirectory()) {
throw new IllegalArgumentException("Root file must be a directory!");
}
this.root = root;
if(!root.exists()) {
root.mkdirs();
}
final File allFile = new File(root, HAVE_ALL_NAME);
if(!allFile.exists()) {
haveAll = new HashMap<>();
}
else {
haveAll = (HashMap<Class<? extends OriannaObject<?>>, Boolean>)readFile(allFile);
}
}
/**
* @param rootPath
* the path to the root folder of the DB
*/
public FileSystemDB(final String rootPath) {
this(new File(rootPath));
}
@Override
protected boolean allowsNullStoreKeys() {
return false;
}
@Override
protected <T extends OriannaObject<?>> boolean checkHasAll(final Class<T> type) {
final Boolean val = haveAll.get(type);
if(val == null) {
return false;
}
return val.booleanValue();
}
@Override
protected <T extends OriannaObject<?>> void doDelete(final Class<T> type, final List<?> keys) {
final File folder = getFolder(type);
for(final Object key : keys) {
final File file = getFile(folder, key);
if(file.exists()) {
file.delete();
}
}
}
@Override
protected <T extends OriannaObject<?>> void doDelete(final Class<T> type, final Object key) {
final File file = getFile(getFolder(type), key);
if(file.exists()) {
file.delete();
}
}
@Override
protected <T extends OriannaObject<?>> List<T> doGet(final Class<T> type, final List<?> keys) {
final File folder = getFolder(type);
final List<T> result = new ArrayList<>(keys.size());
for(final Object key : keys) {
final File file = getFile(folder, key);
if(file.exists()) {
result.add(read(file, type));
}
else {
result.add(null);
}
}
return result;
}
@Override
protected <T extends OriannaObject<?>> T doGet(final Class<T> type, final Object key) {
final File file = getFile(getFolder(type), key);
if(!file.exists()) {
return null;
}
return read(file, type);
}
@Override
protected <T extends OriannaObject<?>> List<T> doGetAll(final Class<T> type) {
final File folder = getFolder(type);
final List<T> result = new ArrayList<>();
for(final File file : folder.listFiles()) {
result.add(read(file, type));
}
return result;
}
@Override
public <T extends OriannaObject<?>> CloseableIterator<T> doGetIterator(final Class<T> type) {
final File folder = getFolder(type);
return CloseableIterator.fromIterator(new FSIterator<>(folder, type));
}
@SuppressWarnings("unchecked")
@Override
protected <T extends OriannaObject<?>> void doStore(final List<T> objs, final List<?> keys, final boolean isFullSet) {
final Class<T> type = (Class<T>)objs.get(0).getClass();
if(isFullSet) {
haveAll.put(type, Boolean.TRUE);
writeFile(new File(root, HAVE_ALL_NAME), haveAll);
}
final File folder = getFolder(type);
for(int i = 0; i < objs.size(); i++) {
write(getFile(folder, keys.get(i)), objs.get(i));
}
}
@Override
protected <T extends OriannaObject<?>> void doStore(final T obj, final Object key) {
write(getFile(getFolder(obj.getClass()), key), obj);
}
/**
* @param folder
* the folder for the object's type
* @param key
* the key
* @return the file that the key is or would be stored in
*/
private File getFile(final File folder, final Object key) {
final int hashCode = Arrays.hashCode(new Object[] {key, key.getClass().getCanonicalName()});
return new File(folder, Integer.toString(hashCode));
}
/**
* @param type
* a type
* @return the folder objects of that type are found in
*/
private File getFolder(final Class<?> type) {
final File folder = new File(root, Integer.toString(type.getCanonicalName().hashCode()));
if(!folder.exists()) {
folder.mkdir();
}
return folder;
}
}
|
package com.telmomenezes.synthetic.cli;
import org.apache.commons.cli.CommandLine;
import com.telmomenezes.synthetic.DiscreteDistrib;
import com.telmomenezes.synthetic.Distrib;
import com.telmomenezes.synthetic.Net;
import com.telmomenezes.synthetic.generators.RandomNet;
import com.telmomenezes.synthetic.io.NetFileType;
import com.telmomenezes.synthetic.motifs.TriadicProfile;
public class Random extends Command {
public boolean run(CommandLine cline) {
if(!cline.hasOption("inet")) {
setErrorMessage("input network file must be specified");
return false;
}
if(!cline.hasOption("odir")) {
setErrorMessage("output directory must be specified");
return false;
}
String netfile = cline.getOptionValue("inet");
Net net = Net.load(netfile);
String outDir = cline.getOptionValue("odir");
int bins = 100;
if(cline.hasOption("bins")) {
bins = new Integer(cline.getOptionValue("bins"));
}
int nodeCount = net.getNodeCount();
int edgeCount = net.getEdgeCount();
Net randomNet = RandomNet.generate(nodeCount, edgeCount);
// write net
randomNet.save(outDir + "/randomnet.txt", NetFileType.SNAP);
// write distributions
DiscreteDistrib inDegrees = new DiscreteDistrib(randomNet.inDegSeq());
DiscreteDistrib outDegrees = new DiscreteDistrib(randomNet.outDegSeq());
Distrib dPageRank = new Distrib(randomNet.prDSeq(), bins);
Distrib uPageRank = new Distrib(randomNet.prUSeq(), bins);
inDegrees.write(outDir + "/random_in_degrees.csv");
outDegrees.write(outDir + "/random_out_degrees.csv");
dPageRank.write(outDir + "/random_d_pagerank.csv");
uPageRank.write(outDir + "/random_u_pagerank.csv");
(new TriadicProfile(randomNet)).write(outDir + "/random_triadic_profile.csv");
return true;
}
}
|
package com.tisawesomeness.minecord.item;
import java.util.regex.Pattern;
import net.dv8tion.jda.core.EmbedBuilder;
/**
* A list of nearly every item in Minecraft. If the item has a recipe,
* there will be a corresponding entry in the Recipe enum.
* @author Tis_awesomeness
*/
public enum Item {
AIR(0, "Air"),
STONE(1, "Stone"),
GRANITE(1, 1, "Granite", "stone[ ]*[:;|/.,\\-_~][ ]*1", Version.V1_8),
POLISHED_GRANITE(1, 2, "Polished Granite", "(polished[^0-9A-Z]*granite)|(stone[ ]*[:;|/.,\\-_~][ ]*2)", Version.V1_8),
DIORITE(1, 3, "Diorite", "stone[ ]*[:;|/.,\\-_~][ ]*3", Version.V1_8),
POLISHED_DIORITE(1, 4, "Polished Diorite", "(polished[^0-9A-Z]*diorite)|(stone[ ]*[:;|/.,\\-_~][ ]*4)", Version.V1_8),
ANDESITE(1, 5, "Andesite", "stone[ ]*[:;|/.,\\-_~][ ]*5", Version.V1_8),
POLISHED_ANDESITE(1, 6, "Polished Andesite", "(polished[^0-9A-Z]*andesite)|(stone[ ]*[:;|/.,\\-_~][ ]*6)", Version.V1_8),
GRASS(2, "Grass"),
DIRT(3, "Dirt"),
COARSE_DIRT(3, 1, "Coarse Dirt", "(coarse[^0-9A-Z]*dirt)|(dirt[ ]*[:;|/.,\\-_~][ ]*1)"),
PODZOL(3, 2, "Podzol"),
COBBLESTONE(4, "Cobblestone", "^cobble[^0-9A-Z]*$"),
OAK_PLANKS(5, "Oak Wood Planks", "^(oak[^0-9A-Z]*(wood[^0-9A-Z]*)?)?plank"),
SPRUCE_PLANKS(5, 1, "Spruce Wood Planks", "(spruce[^0-9A-Z]*(wood[^0-9A-Z]*)?plank)|((wood[^0-9A-Z]*)?plank[ ]*[:;|/.,\\-_~][ ]*1)"),
BIRCH_PLANKS(5, 2, "Birch Wood Planks", "(birch[^0-9A-Z]*(wood[^0-9A-Z]*)?plank)|((wood[^0-9A-Z]*)?plank[ ]*[:;|/.,\\-_~][ ]*2)"),
JUNGLE_PLANKS(5, 3, "Jungle Wood Planks", "(jungle[^0-9A-Z]*(wood[^0-9A-Z]*)?plank)|((wood[^0-9A-Z]*)?plank[ ]*[:;|/.,\\-_~][ ]*3)"),
ACACIA_PLANKS(5, 4, "Acacia Wood Planks", "(acacia[^0-9A-Z]*(wood[^0-9A-Z]*)?plank)|((wood[^0-9A-Z]*)?plank[ ]*[:;|/.,\\-_~][ ]*4)"),
DARK_OAK_PLANKS(5, 5, "Dark Oak Wood Planks", "(dark[^0-9A-Z]*(oak[^0-9A-Z]*(wood[^0-9A-Z]*)?)?plank)|((wood[^0-9A-Z]*)?plank[ ]*[:;|/.,\\-_~][ ]*5)"),
OAK_SAPLING(6, "Oak Sapling", "^sapling"),
SPRUCE_SAPLING(6, 1, "Spruce Sapling", "sapling[ ]*[:;|/.,\\-_~][ ]*1"),
BIRCH_SAPLING(6, 2, "Birch Sapling", "sapling[ ]*[:;|/.,\\-_~][ ]*2"),
JUNGLE_SAPLING(6, 3, "Jungle Sapling", "sapling[ ]*[:;|/.,\\-_~][ ]*3"),
ACACIA_SAPLING(6, 4, "Acacia Sapling", "sapling[ ]*[:;|/.,\\-_~][ ]*4"),
DARK_OAK_SAPLING(6, 5, "Dark Oak Sapling", "(dark[^0-9A-Z]*sapling)|(sapling[ ]*[:;|/.,\\-_~][ ]*5)"),
BEDROCK(7, "Bedrock"),
FLOWING_WATER(8, "Flowing Water"),
STILL_WATER(9, "Still Water"),
FLOWING_LAVA(10, "Flowing Lava"),
STILL_LAVA(11, "Still Lava"),
SAND(12, "Sand"),
RED_SAND(12, 1, "Red Sand", "sand[ ]*[:;|/.,\\-_~][ ]*1"),
GRAVEL(13, "Gravel"),
GOLD_ORE(14, "Gold Ore"),
IRON_ORE(15, "Iron Ore"),
COAL_ORE(16, "Coal Ore"),
OAK_WOOD(17, "Oak Wood", "^(wood)|(log)$"), //Punch wood
SPRUCE_WOOD(17, 1, "Spruce Wood", "(wood)|(log)[ ]*[:;|/.,\\-_~][ ]*1"),
BIRCH_WOOD(17, 2, "Birch Wood", "(wood)|(log)[ ]*[:;|/.,\\-_~][ ]*2"),
JUNGLE_WOOD(17, 3, "Jungle Wood", "(wood)|(log)[ ]*[:;|/.,\\-_~][ ]*3"),
OAK_LEAVES(18, "Oak Leaves", "^leaves"),
SPRUCE_LEAVES(18, 1, "Spruce Leaves", "leaves[ ]*[:;|/.,\\-_~][ ]*1"),
BIRCH_LEAVES(18, 2, "Birch Leaves", "leaves[ ]*[:;|/.,\\-_~][ ]*2"),
JUNGLE_LEAVES(18, 3, "Jungle Leaves", "leaves[ ]*[:;|/.,\\-_~][ ]*3"),
SPONGE(19, "Sponge"),
WET_SPONGE(19, 1, "Wet Sponge", "sponge[ ]*[:;|/.,\\-_~][ ]*1", Version.V1_8),
GLASS(20, "Glass"),
LAPIS_LAZULI_ORE(21, "Lapis Lazuli Ore", "lapis[^0-9A-Z]*ore"),
LAPIS_LAZULI_BLOCK(22, "Lapis Lazuli Block", "lapis[^0-9A-Z]*block"),
DISPENSER(23, "Dispenser"),
SANDSTONE(24, "Sandstone"),
CHISELED_SANDSTONE(24, 1, "Chiseled Sandstone", "sandstone[ ]*[:;|/.,\\-_~][ ]*1"),
SMOOTH_SANDSTONE(24, 2, "Smooth Sandstone", "sandstone[ ]*[:;|/.,\\-_~][ ]*2"),
NOTE_BLOCK(25, "Note Block"), //Play that noteblock nicely
BED_BLOCK(26, "Bed Block"),
POWERED_RAIL(27, "Powered Rail"),
DETECTOR_RAIL(28, "Detector Rail"),
STICKY_PISTON(29, "Sticky Piston"),
COBWEB(30, "Cobweb"),
DEAD_SHRUB(31, "Dead Shrub"),
TALL_GRASS(31, 1, "Tall Grass", "(dead[^0-9A-Z]*shrub[ ]*[:;|/.,\\-_~][ ]*1)|(weed)"),
FERN(31, 2, "Fern", "dead[^0-9A-Z]*shrub[ ]*[:;|/.,\\-_~][ ]*2"),
DEAD_BUSH(32, "Dead Bush"), //[chat filter intensifies]
PISTON(33, "Piston"),
PISTON_HEAD(34, "Piston Head"),
WOOL(35, "Wool"),
ORANGE_WOOL(35, 1, "Orange Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$))"),
MAGENTA_WOOL(35, 2, "Magenta Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$))"),
LIGHT_BLUE_WOOL(35, 3, "Light Blue Wool", "((aqua)|(light[^0-9A-Z]*blue)[^0-9A-Z]*wool)|(((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))"),
YELLOW_WOOL(35, 4, "Yellow Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$))"),
LIME_WOOL(35, 5, "Lime Wool", "(((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))|(((light[^0-9A-Z]*green)|(lime))[^0-9A-Z]*wool)"),
PINK_WOOL(35, 6, "Pink Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((pink)|6)"),
GRAY_WOOL(35, 7, "Gray Wool", "(grey[^0-9A-Z]*wool)|(silver[^0-9A-Z]*wool)|(((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7))"),
LIGHT_GRAY_WOOL(35, 8, "Light Gray Wool", "(light[^0-9A-Z]*grey[^0-9A-Z]*wool)|(((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8))"),
CYAN_WOOL(35, 9, "Cyan Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9)"),
PURPLE_WOOL(35, 10, "Purple Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10))"),
BLUE_WOOL(35, 11, "Blue Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11))"),
BROWN_WOOL(35, 12, "Brown Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12))"),
GREEN_WOOL(35, 13, "Green Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((green)|(13))"),
RED_WOOL(35, 14, "Red Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((red)|(14))"),
BLACK_WOOL(35, 15, "Black Wool", "((35)|(wool))[ ]*[:;|/.,\\-_~][ ]*((black)|(15))"),
//Block 36 is a technical block for the tile entity being moved by a piston
DANDELION(37, "Dandelion", "yellow[^0-9A-Z]*flower"),
POPPY(38, "Poppy", "(rose)|(red[^0-9A-Z]*flower)"),
BLUE_ORCHID(38, 1, "Blue Orchid", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*1"),
ALLIUM(38, 2, "Allium", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*2"),
AZURE_BLUET(38, 3, "Azure Bluet", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*3"),
RED_TULIP(38, 4, "Red Tulip", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*4"),
ORANGE_TULIP(38, 5, "Orange Tulip", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*5"),
WHITE_TULIP(38, 6, "White Tulip", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*6"),
PINK_TULIP(38, 7, "Pink Tulip", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*7"),
OXEYE_DAISY(38, 8, "Oxeye Daisy", "(red[^0-9A-Z]*)?flower[ ]*[:;|/.,\\-_~][ ]*8"),
BROWN_MUSHROOM(39, "Brown Mushroom"),
RED_MUSHROOM(40, "Red Mushroom"),
GOLD_BLOCK(41, "Gold Block"),
IRON_BLOCK(42, "Iron Block"),
DOUBLE_STONE_SLAB(43, "Double Stone Slab"),
DOUBLE_SANDSTONE_SLAB(43, 1, "Double Sandstone Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*1"),
DOUBLE_WOODEN_SLAB(43, 2, "Double Wooden Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*2"),
DOUBLE_COBBLESTONE_SLAB(43, 3, "Double Cobblestone Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*3"),
DOUBLE_BRICK_SLAB(43, 4, "Double Brick Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*4"),
DOUBLE_STONE_BRICK_SLAB(43, 5, "Double Stone Brick Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*5"),
DOUBLE_NETHER_BRICK_SLAB(43, 6, "Double Nether Brick Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*6"),
DOUBLE_QUARTZ_SLAB(43, 7, "Double Quartz Slab", "double[^0-9A-Z]stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*7"),
STONE_SLAB(44, "Stone Slab"),
SANDSTONE_SLAB(44, 1, "Sandstone Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*1"),
WOODEN_SLAB(44, 2, "Wooden Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*2"),
COBBLESTONE_SLAB(44, 3, "Cobblestone Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*3"),
BRICK_SLAB(44, 4, "Brick Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*4"),
STONE_BRICK_SLAB(44, 5, "Stone Brick Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*5"),
NETHER_BRICK_SLAB(44, 6, "Nether Brick Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*6"),
QUARTZ_SLAB(44, 7, "Quartz Slab", "stone[^0-9A-Z]slab[ ]*[:;|/.,\\-_~][ ]*7"),
BRICKS(45, "Bricks"), //Brown bricks
TNT(46, "TNT"), //The first thing we all used when we got Minecraft
BOOKSHELF(47, "Bookshelf"), //You need 15 to get full enchants. You're welcome.
MOSSY_COBBLESTONE(48, "Mossy Cobblestone"),
OBSIDIAN(49, "Obsidian"),
TORCH(50, "Torch"),
FIRE(51, "Fire"),
MONSTER_SPAWNER(52, "Monster Spawner"),
OAK_WOOD_STAIRS(53, "Oak Wood Stairs", "^wood[^0-9A-Z]*stairs"),
CHEST(54, "Chest"),
REDSTONE_WIRE(55, "Redstone Wire", "wire"),
DIAMOND_ORE(56, "Diamond Ore"), //Please mine around
DIAMOND_BLOCK(57, "Diamond Block"),
CRAFTING_TABLE(58, "Crafting Table"),
WHEAT_CROPS(59, "Wheat Crops"),
FARMLAND(60, "Farmland"),
FURNACE(61, "Furnace"),
BURNING_FURNACE(62, "Burning Furnace"),
STANDING_SIGN(63, "Standing Sign"),
OAK_DOOR_BLOCK(64, "Oak Door Block", "^(wood(en)?[^0-9A-Z]*)?door[^0-9A-Z]*block"),
LADDER(65, "Ladder"),
RAIL(66, "Rail"),
COBBLESTONE_STAIRS(67, "Cobblestone Stairs", "cobble(stone)?[^0-9A-Z]*stairs?"),
WALL_SIGN(68, "Wall-mounted Sign Block", "wall[^0-9A-Z]*sign"),
LEVER(69, "Lever"),
STONE_PRESSURE_PLATE(70, "Stone Pressure Plate"),
IRON_DOOR_BLOCK(71, "Iron Door Block"),
WOODEN_PRESSURE_PLATE(72, "Wooden Pressure Plate", "wood[^0-9A-Z]*pressure[^0-9A-Z]*plate"),
REDSTONE_ORE(73, "Redstone Ore"),
GLOWING_REDSTONE_ORE(74, "Glowing Redstone Ore"),
UNLIT_REDSTONE_TORCH(75, "Redstone Torch (off)"),
REDSTONE_TORCH(76, "Redstone Torch"),
STONE_BUTTON(77, "Stone Button"),
SNOW(78, "Snow Layer"),
ICE(79, "Ice"),
SNOW_BLOCK(80, "Snow Block"),
CACTUS(81, "Cactus"),
CLAY_BLOCK(82, "Clay Block"),
SUGAR_CANE_BLOCK(83, "Sugar Cane Block"),
JUKEBOX(84, "Jukebox"),
OAK_FENCE(85, "Oak Fence", "^(oak[^0-9A-Z]*(wood[^0-9A-Z]*)?)?fence$"),
PUMPKIN(86, "Pumpkin"),
NETHERRACK(87, "Netherrack"),
SOUL_SAND(88, "Soul Sand"),
GLOWSTONE(89, "Glowstone"),
NETHER_PORTAL(90, "Nether Portal", "^portal"),
JACK_O_LANTERN(91, "Jack o'Lantern", "jack[^0-9A-Z]*o[^0-9A-Z]*lantern"),
CAKE_BLOCK(92, "Cake Block"),
REDSTONE_REPEATER_BLOCK(93, "Redstone Repeater Block"),
POWERED_REDSTONE_REPEATER_BLOCK(94, "Redstone Repeater Block (on)"),
STAINED_GLASS(95, "Stained Glass", "((colored)|(dyed))[^0-9A-Z]*glass"),
ORANGE_STAINED_GLASS(95, 1, "Orange Stained Glass", "(orange[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$)))"),
MAGENTA_STAINED_GLASS(95, 2, "Magenta Stained Glass", "(magenta[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$)))"),
LIGHT_BLUE_STAINED_GLASS(95, 3, "Light Blue Stained Glass", "(((aqua)|(light[^0-9A-Z]*blue))[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))"),
YELLOW_STAINED_GLASS(95, 4, "Yellow Stained Glass", "(yellow[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$)))"),
LIME_STAINED_GLASS(95, 5, "Lime Stained Glass", "(((lime)|(light[^0-9A-Z]*green))[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))"),
PINK_STAINED_GLASS(95, 6, "Pink Stained Glass", "(pink[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((pink)|6))"),
GRAY_STAINED_GLASS(95, 7, "Gray Stained Glass", "(grey[^0-9A-Z]*wool)|(silver[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7))"),
LIGHT_GRAY_STAINED_GLASS(95, 8, "Light Gray Stained Glass", "(light[^0-9A-Z]*grey[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8))"),
CYAN_STAINED_GLASS(95, 9, "Cyan Stained Glass", "(cyan[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9))"),
PURPLE_STAINED_GLASS(95, 10, "Purple Stained Glass", "(purple[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10)))"),
BLUE_STAINED_GLASS(95, 11, "Blue Stained Glass", "(blue[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11)))"),
BROWN_STAINED_GLASS(95, 12, "Brown Stained Glass", "(brown[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12)))"),
GREEN_STAINED_GLASS(95, 13, "Green Stained Glass", "(green[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((green)|(13)))"),
RED_STAINED_GLASS(95, 14, "Red Stained Glass", "(red[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((red)|(14)))"),
BLACK_STAINED_GLASS(95, 15, "Black Stained Glass", "(black[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass))[ ]*[:;|/.,\\-_~][ ]*((black)|(15)))"),
WOODEN_TRAPDOOR(96, "Wooden Trapdoor", "wood(en)?[^0-9A-Z]*trapdoor"),
STONE_MONSTER_EGG(97, "Stone Monster Egg"),
COBBLESTONE_MONSTER_EGG(97, 1, "Cobblestone Monster Egg", "(cobble[^0-9A-Z]*monster[^0-9A-Z]*egg)|(monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*1)"),
STONE_BRICK_MONSTER_EGG(97, 2, "Stone Brick Monster Egg", "monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*2"),
MOSSY_STONE_BRICK_MONSTER_EGG(97, 3, "Mossy Stone Brick Monster Egg", "(mossy?[^0-9A-Z]*stone[^0-9A-Z]*brick[^0-9A-Z]*monster[^0-9A-Z]*egg)|(monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*3)"),
CRACKED_STONE_BRICK_MONSTER_EGG(97, 4, "Cracked Stone Brick Monster Egg", "monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*4"),
CHISELED_STONE_BRICK_MONSTER_EGG(97, 5, "Chiseled Stone Brick Monster Egg", "monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*5"),
STONE_BRICKS(98, "Stone Bricks", "^stone[^0-9A-Z]*brick"),
MOSSY_STONE_BRICKS(98, 1, "Mossy Stone Bricks", "(mossy?[^0-9A-Z]*stone[^0-9A-Z]*brick)|(monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*1)"),
CRACKED_STONE_BRICKS(98, 2, "Cracked Stone Bricks", "(cracked[^0-9A-Z]*stone[^0-9A-Z]*brick)|(monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*2)"),
CHISELED_STONE_BRICKS(98, 3, "Chiseled Stone Bricks", "(chiseled[^0-9A-Z]*stone[^0-9A-Z]*brick)|(monster[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*3)"),
BROWN_MUSHROOM_BLOCK(99, "Brown Mushroom Block"),
RED_MUSHROOM_BLOCK(100, "Red Mushroom Block"),
IRON_BARS(101, "Iron Bars", "iron[^0-9A-Z]*bar"),
GLASS_PANE(102, "Glass Pane"),
MELON_BLOCK(103, "Melon Block"),
PUMPKIN_STEM(104, "Pumpkin Stem"),
MELON_STEM(105, "Melon Stem"),
VINES(106, "Vines"),
OAK_FENCE_GATE(107, "Oak Fence Gate", "(oak[^0-9A-Z]*(wood[^0-9A-Z]*)?)?fence[^0-9A-Z]*gate"),
BRICK_STAIRS(108, "Brick Stairs", "^brick[^0-9A-Z]*stair"),
STONE_BRICK_STAIRS(109, "Stone Brick Stairs", "stone[^0-9A-Z]*brick[^0-9A-Z]*stair"),
MYCELIUM(110, "Mycelium"),
LILY_PAD(111, "Lily Pad"),
NETHER_BRICK(112, "Nether Brick"),
NETHER_BRICK_FENCE(113, "Nether Brick Fence"),
NETHER_BRICK_STAIRS(114, "Nether Brick Stairs", "nether[^0-9A-Z]*brick[^0-9A-Z]*stair"),
NETHER_WART_PLANT(115, "Nether Wart (plant)"),
ENCHANTMENT_TABLE(116, "Enchantment Table", "enchant(ing)?[^0-9A-Z]*table"),
BREWING_STAND_BLOCK(117, "Brewing Stand Block"),
CAULDRON_BLOCK(118, "Cauldron Block"),
END_PORTAL(119, "End Portal"),
END_PORTAL_FRAME(120, "End Portal Frame"),
END_STONE(121, "End Stone"),
DRAGON_EGG(122, "Dragon Egg"),
REDSTONE_LAMP(123, "Redstone Lamp"),
POWERED_REDSTONE_LAMP(124, "Powered Redstone Lamp"),
DOUBLE_OAK_WOOD_SLAB(125, "Double Oak Wood Slab", "double[^0-9A-Z]*(oak[^0-9A-Z]*)?wood[^0-9A-Z]*slab"),
DOUBLE_BIRCH_WOOD_SLAB(125, 1, "Double Birch Wood Slab", "(double[^0-9A-Z]*birch[^0-9A-Z]*slab)|(double[^0-9A-Z]*wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*1)"),
DOUBLE_SPRUCE_WOOD_SLAB(125, 2, "Double Spruce Wood Slab", "(double[^0-9A-Z]*spruce[^0-9A-Z]*slab)|(double[^0-9A-Z]*wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*2)"),
DOUBLE_JUNGLE_WOOD_SLAB(125, 3, "Double Jungle Wood Slab", "(double[^0-9A-Z]*jungle[^0-9A-Z]*slab)|(double[^0-9A-Z]*wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*3)"),
DOUBLE_ACACIA_WOOD_SLAB(125, 4, "Double Acacia Wood Slab", "(double[^0-9A-Z]*acacia[^0-9A-Z]*slab)|(double[^0-9A-Z]*wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*4)"),
DOUBLE_DARK_OAK_WOOD_SLAB(125, 5, "Double Dark Oak Wood Slab", "(double[^0-9A-Z]*dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?slab)|(double[^0-9A-Z]*wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*5)"),
OAK_WOOD_SLAB(126, "Oak Wood Slab", "^(oak[^0-9A-Z]*)?wood[^0-9A-Z]*slab"),
BIRCH_WOOD_SLAB(126, 1, "Birch Wood Slab", "^(birch[^0-9A-Z]*slab)|(wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*1)"),
SPRUCE_WOOD_SLAB(126, 2, "Spruce Wood Slab", "^(spruce[^0-9A-Z]*slab)|(wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*2)"),
JUNGLE_WOOD_SLAB(126, 3, "Jungle Wood Slab", "^(jungle[^0-9A-Z]*slab)|(wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*3)"),
ACACIA_WOOD_SLAB(126, 4, "Acacia Wood Slab", "^(acacia[^0-9A-Z]*slab)|(wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*4)"),
DARK_OAK_WOOD_SLAB(126, 5, "Dark Oak Wood Slab", "^(dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?slab)|(wood(en)?[^0-9A-Z]*slab[ ]*[:;|/.,\\-_~][ ]*5)"),
COCOA(127, "Cocoa"),
SANDSTONE_STAIRS(128, "Sandstone Stairs", "sandstone[^0-9A-Z]*stair"),
EMERALD_ORE(129, "Emerald Ore"),
ENDER_CHEST(130, "Ender Chest"),
TRIPWIRE_HOOK(131, "Tripwire Hook"),
TRIPWIRE(132, "Tripwire"),
EMERALD_BLOCK(133, "Emerald Block"),
SPRUCE_STAIRS(134, "Spruce Wood Stairs", "^spruce[^0-9A-Z]*(wood[^0-9A-Z]*)?stairs?"),
BIRCH_STAIRS(135, "Birch Wood Stairs", "^birch[^0-9A-Z]*(wood[^0-9A-Z]*)?stairs?"),
JUNGLE_STAIRS(136, "Jungle Wood Stairs", "^jungle[^0-9A-Z]*(wood[^0-9A-Z]*)?stairs?"),
COMMAND_BLOCK(137, "Command Block"), //Overpowered
BEACON(138, "Beacon"),
COBBLESTONE_WALL(139, "Cobblestone Wall", "^(cobble(stone)?[^0-9A-Z]*)?wall"), //We need to build a wall
MOSSY_COBBLESTONE_WALL(139, 1, "Mossy Cobblestone Wall", "(^mossy?[^0-9A-Z]*(cobble(stone)?[^0-9A-Z]*)?wall)|((cobble(stone)?[^0-9A-Z]*)?wall[ ]*[:;|/.,\\-_~][ ]*1)"),
FLOWER_POT_BLOCK(140, "Flower Pot Block"),
CARROTS(141, "Carrots", "carrot[^0-9A-Z]*block"),
POTATOES(142, "Potatoes", "potato[^0-9A-Z]*block"),
WOODEN_BUTTON(143, "Wooden Button", "wood[^0-9A-Z]*button"),
SKULL_BLOCK(144, "Mob Head"),
ANVIL(145, "Anvil"),
TRAPPED_CHEST(146, "Trapped Chest"),
LIGHT_WEIGHTED_PRESSURE_PLATE(147, "Weighted Pressure Plate (light)", "light[^0-9A-Z]*pressure[^0-9A-Z]*plate"),
HEAVY_WEIGHTED_PRESSURE_PLATE(148, "Weighted Pressure Plate (heavy)", "heavy[^0-9A-Z]*pressure[^0-9A-Z]*plate"),
UNPOWERED_COMPARATOR(149, "Redstone Comparator (inactive)"),
POWERED_COMPARATOR(150, "Redstone Comparator (active)"),
DAYLIGHT_DETECTOR(151, "Daylight Sensor"),
REDSTONE_BLOCK(152, "Redstone Block"),
QUARTZ_ORE(153, "Nether Quartz Ore", "quartz[^0-9A-Z]*ore"),
HOPPER(154, "Hopper"),
QUARTZ_BLOCK(155, "Quartz Block", "^quartz$"),
CHISELED_QUARTZ_BLOCK(155, 1, "Chiseled Quartz Block", "quartz[^0-9A-Z]*(block[^0-9A-Z]*)?[ ]*[:;|/.,\\-_~][ ]*1"),
PILLAR_QUARTZ_BLOCK(155, 2, "Pillar Quartz Block", "quartz[^0-9A-Z]*(block[^0-9A-Z]*)?[ ]*[:;|/.,\\-_~][ ]*2"),
QUARTZ_STAIRS(156, "Quartz Stairs", "quartz[^0-9A-Z]*stair"),
ACTIVATOR_RAIL(157, "Activator Rail"),
DROPPER(158, "Dropper"),
STAINED_HARDENED_CLAY(159, "White Hardened Clay", "^(white[^0-9A-Z]*)?((stained)|(colored)|(dyed))[^0-9A-Z]*clay$"), //Regex why
ORANGE_STAINED_HARDENED_CLAY(159, 1, "Orange Hardened Clay", "(orange[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$)))"),
MAGENTA_STAINED_HARDENED_CLAY(159, 2, "Magenta Hardened Clay", "(magenta[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$)))"),
LIGHT_BLUE_STAINED_HARDENED_CLAY(159, 3, "Light Blue Hardened Clay", "(((aqua)|(light[^0-9A-Z]*blue))[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|((((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$))))"),
YELLOW_STAINED_HARDENED_CLAY(159, 4, "Yellow Hardened Clay", "(yellow[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$)))"),
LIME_STAINED_HARDENED_CLAY(159, 5, "Lime Hardened Clay", "(((lime)|(light[^0-9A-Z]*green))[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|((((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(3$))))"),
PINK_STAINED_HARDENED_CLAY(159, 6, "Pink Hardened Clay", "(pink[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((pink)|6))"),
GRAY_STAINED_HARDENED_CLAY(159, 7, "Gray Hardened Clay", "(gr(a|e)y[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7))"),
LIGHT_GRAY_STAINED_HARDENED_CLAY(159, 8, "Light Gray Hardened Clay", "((light[^0-9A-Z]*gr(a|e)y)|(silver)[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8))"),
CYAN_STAINED_HARDENED_CLAY(159, 9, "Cyan Hardened Clay", "(cyan[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9))"),
PURPLE_STAINED_HARDENED_CLAY(159, 10, "Purple Hardened Clay", "(purple[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10)))"),
BLUE_STAINED_HARDENED_CLAY(159, 11, "Blue Hardened Clay", "(blue[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11)))"),
BROWN_STAINED_HARDENED_CLAY(159, 12, "Brown Hardened Clay", "(brown[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12)))"),
GREEN_STAINED_HARDENED_CLAY(159, 13, "Green Hardened Clay", "(green[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((green)|(13)))"),
RED_STAINED_HARDENED_CLAY(159, 14, "Red Hardened Clay", "(red[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((red)|(14)))"),
BLACK_STAINED_HARDENED_CLAY(159, 15, "Black Hardened Clay", "(black[^0-9A-Z]*(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))|(((hardened)|(((stained)|(colored)|(dyed))([^0-9A-Z]*hardened)?))[^0-9A-Z]*clay|(terr?acott?a)|(159))[ ]*[:;|/.,\\-_~][ ]*((black)|(15)))"),
STAINED_GLASS_PANE(160, "Stained Glass Pane", "((colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane"),
ORANGE_STAINED_GLASS_PANE(160, 1, "Orange Stained Glass Pane", "(orange[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$)))"),
MAGENTA_STAINED_GLASS_PANE(160, 2, "Magenta Stained Glass Pane", "(magenta[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$)))"),
LIGHT_BLUE_STAINED_GLASS_PANE(160, 3, "Light Blue Stained Glass Pane", "(((aqua)|(light[^0-9A-Z]*blue))[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))"),
YELLOW_STAINED_GLASS_PANE(160, 4, "Yellow Stained Glass Pane", "(yellow[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$)))"),
LIME_STAINED_GLASS_PANE(160, 5, "Lime Stained Glass Pane", "(((lime)|(light[^0-9A-Z]*green))[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))"),
PINK_STAINED_GLASS_PANE(160, 6, "Pink Stained Glass Pane", "(pink[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((pink)|6))"),
GRAY_STAINED_GLASS_PANE(160, 7, "Gray Stained Glass Pane", "(grey[^0-9A-Z]*wool)|(silver[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7))"),
LIGHT_GRAY_STAINED_GLASS_PANE(160, 8, "Light Gray Stained Glass Pane", "(light[^0-9A-Z]*grey[^0-9A-Z]*((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane)|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8))"),
CYAN_STAINED_GLASS_PANE(160, 9, "Cyan Stained Glass Pane", "(cyan[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9))"),
PURPLE_STAINED_GLASS_PANE(160, 10, "Purple Stained Glass Pane", "(purple[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10)))"),
BLUE_STAINED_GLASS_PANE(160, 11, "Blue Stained Glass Pane", "(blue[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11)))"),
BROWN_STAINED_GLASS_PANE(160, 12, "Brown Stained Glass Pane", "(brown[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12)))"),
GREEN_STAINED_GLASS_PANE(160, 13, "Green Stained Glass Pane", "(green[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((green)|(13)))"),
RED_STAINED_GLASS_PANE(160, 14, "Red Stained Glass Pane", "(red[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((red)|(14)))"),
BLACK_STAINED_GLASS_PANE(160, 15, "Black Stained Glass Pane", "(black[^0-9A-Z]*((stained)|(colored)|(dyed)))[^0-9A-Z]*glass[^0-9A-Z]*pane|(((95)|(((stained)|(colored)|(dyed))[^0-9A-Z]*glass[^0-9A-Z]*pane))[ ]*[:;|/.,\\-_~][ ]*((black)|(15)))"),
ACACIA_LEAVES(161, "Acacia Leaves", "leaves2$"),
DARK_OAK_LEAVES(161, 1, "Dark Oak Leaves", "(dark[^0-9A-Z]*leaves)|(leaves2[ ]*[:;|/.,\\-_~][ ]*1)"),
ACACIA_WOOD(162, "Acacia Wood", "log2$"),
DARK_OAK_WOOD(162, 1, "Dark Oak Wood", "(^dark[^0-9A-Z]*wood)|(log2[ ]*[:;|/.,\\-_~][ ]*1)"),
ACACIA_STAIRS(163, "Acacia Wood Stairs", "acacia[^0-9A-Z]*(wood[^0-9A-Z]*)?stairs?"),
DARK_OAK_STAIRS(164, "Dark Oak Wood Stairs", "dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?stairs?"),
SLIME_BLOCK(165, "Slime Block", Version.V1_8),
BARRIER(166, "Barrier", Version.V1_8),
IRON_TRAPDOOR(167, "Iron Trapdoor", Version.V1_8),
PRISMARINE(168, "Prismarine", Version.V1_8),
PRISMARINE_BRICKS(168, 1, "Prismarine Bricks", "prismarine[ ]*[:;|/.,\\-_~][ ]*1", Version.V1_8),
DARK_PRISMARINE(168, 2, "Dark Prismarine", "prismarine[ ]*[:;|/.,\\-_~][ ]*2", Version.V1_8),
SEA_LANTERN(169, "Sea Lantern", Version.V1_8),
HAY_BLOCK(170, "Hay Bale", "hay"),
CARPET(171, "White Carpet"),
ORANGE_CARPET(171, 1, "Orange Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$))"),
MAGENTA_CARPET(171, 2, "Magenta Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$))"),
LIGHT_BLUE_CARPET(171, 3, "Light Blue Carpet", "((aqua)|light[^0-9A-Z]*blue[^0-9A-Z]*carpet)|(((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))"),
YELLOW_CARPET(171, 4, "Yellow Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$))"),
LIME_CARPET(171, 5, "Lime Carpet", "((lime)|light[^0-9A-Z]*green[^0-9A-Z]*carpet)|(((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))"),
PINK_CARPET(171, 6, "Pink Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((pink)|6)"),
GRAY_CARPET(171, 7, "Gray Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((gray)|7)"),
LIGHT_GRAY_CARPET(171, 8, "Light Gray Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8)"),
CYAN_CARPET(171, 9, "Cyan Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9)"),
PURPLE_CARPET(171, 10, "Purple Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10))"),
BLUE_CARPET(171, 11, "Blue Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11))"),
BROWN_CARPET(171, 12, "Brown Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12))"),
GREEN_CARPET(171, 13, "Green Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((green)|(13))"),
RED_CARPET(171, 14, "Red Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((red)|(14))"),
BLACK_CARPET(171, 15, "Black Carpet", "((171)|(carpet))[ ]*[:;|/.,\\-_~][ ]*((black)|(15))"),
HARDENED_CLAY(172, "Hardened Clay"),
COAL_BLOCK(173, "Block of Coal"),
PACKED_ICE(174, "Packed Ice"),
SUNFLOWER(175, "Sunflower", "(sun[^0-9A-Z]*flower)|(double[^0-9A-Z]*plant([ ]*[:;|/.,\\-_~][ ]*0)?$)"),
LILAC(175, 1, "Lilac", "double[^0-9A-Z]*plant[ ]*[:;|/.,\\-_~][ ]*1"),
DOUBLE_TALL_GRASS(175, 2, "Double Tallgrass", "double[^0-9A-Z]*plant[ ]*[:;|/.,\\-_~][ ]*2"),
LARGE_FERN(175, 3, "Large Fern", "double[^0-9A-Z]*plant[ ]*[:;|/.,\\-_~][ ]*3"),
ROSE_BUSH(175, 4, "Rose Bush", "double[^0-9A-Z]*plant[ ]*[:;|/.,\\-_~][ ]*4"),
PEONY(175, 5, "Peony", "double[^0-9A-Z]*plant[ ]*[:;|/.,\\-_~][ ]*5"),
STANDING_BANNER(176, "Free-standing Banner", Version.V1_8),
WALL_BANNER(177, "Wall-mounted Banner", Version.V1_8),
DAYLIGHT_DETECTOR_INVERTED(178, "Inverted Daylight Sensor"),
RED_SANDSTONE(179, "Red Sandstone", Version.V1_8),
CHISELED_RED_SANDSTONE(179, 1, "Chiseled Red Sandstone", "red[^0-9A-Z]*sandstone[ ]*[:;|/.,\\-_~][ ]*1", Version.V1_8),
SMOOTH_RED_SANDSTONE(179, 2, "Smooth Red Sandstone", "red[^0-9A-Z]*sandstone[ ]*[:;|/.,\\-_~][ ]*2", Version.V1_8),
RED_SANDSTONE_STAIRS(180, "Red Sandstone Stairs", "red[^0-9A-Z]*sandstone[^0-9A-Z]*stair", Version.V1_8),
DOUBLE_STONE_SLAB2(181, "Double Red Sandstone Slab", "double[^0-9A-Z]*stone[^0-9A-Z]*slab2", Version.V1_8),
STONE_SLAB2(182, "Red Sandstone Slab", "stone[^0-9A-Z]*slab2", Version.V1_8),
SPRUCE_FENCE_GATE(183, "Spruce Fence Gate", "spruce[^0-9A-Z]*(wood[^0-9A-Z]*)?fence[^0-9A-Z]*gate", Version.V1_8),
BIRCH_FENCE_GATE(184, "Birch Fence Gate", "birch[^0-9A-Z]*(wood[^0-9A-Z]*)?fence[^0-9A-Z]*gate", Version.V1_8),
JUNGLE_FENCE_GATE(185, "Jungle Fence Gate", "jungle[^0-9A-Z]*(wood[^0-9A-Z]*)?fence[^0-9A-Z]*gate", Version.V1_8),
DARK_OAK_FENCE_GATE(186, "Dark Oak Fence Gate", "dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?fence[^0-9A-Z]*gate", Version.V1_8),
ACACIA_FENCE_GATE(187, "Acacia Fence Gate", "acacia[^0-9A-Z]*(wood[^0-9A-Z]*)?fence[^0-9A-Z]*gate", Version.V1_8),
SPRUCE_FENCE(188, "Spruce Fence", "spruce[^0-9A-Z]*(wood[^0-9A-Z]*)?fence", Version.V1_8),
BIRCH_FENCE(189, "Birch Fence", "birch[^0-9A-Z]*(wood[^0-9A-Z]*)?fence", Version.V1_8),
JUNGLE_FENCE(190, "Jungle Fence", "jungle[^0-9A-Z]*wood[^0-9A-Z]*fence", Version.V1_8),
DARK_OAK_FENCE(191, "Dark Oak Fence", "dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?fence", Version.V1_8),
ACACIA_FENCE(192, "Acacia Fence", "acacia[^0-9A-Z]*wood[^0-9A-Z]*fence", Version.V1_8),
SPRUCE_DOOR_BLOCK(193, "Spruce Door Block", "spruce[^0-9A-Z]*wood[^0-9A-Z]*door[^0-9A-Z]*block", Version.V1_8),
BIRCH_DOOR_BLOCK(194, "Birch Door Block", "birch[^0-9A-Z]*wood[^0-9A-Z]*door[^0-9A-Z]*block", Version.V1_8),
JUNGLE_DOOR_BLOCK(195, "Jungle Door Block", "jungle[^0-9A-Z]*wood[^0-9A-Z]*door[^0-9A-Z]*block", Version.V1_8),
ACACIA_DOOR_BLOCK(196, "Acacia Door Block", "acacia[^0-9A-Z]*wood[^0-9A-Z]*door[^0-9A-Z]*block", Version.V1_8),
DARK_OAK_DOOR_BLOCK(197, "Dark Oak Door Block", "dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?door[^0-9A-Z]*block", Version.V1_8),
END_ROD(198, "End Rod", Version.V1_9),
CHORUS_PLANT(199, "Chorus Plant", Version.V1_9),
CHORUS_FLOWER(200, "Chorus Flower", Version.V1_9),
PURPUR_BLOCK(201, "Purpur Block", "purpur$", Version.V1_9),
PURPUR_PILLAR(202, "Purpur Pillar", Version.V1_9),
PURPUR_STAIRS(203, "Purpur Stairs", Version.V1_9),
PURPUR_DOUBLE_SLAB(204, "Purpur Double Slab", Version.V1_9),
PURPUR_SLAB(205, "Purpur Slab", Version.V1_9),
END_BRICKS(206, "End Stone Bricks", "end[^0-9A-Z]*(stone[^0-9A-Z]*)?brick", Version.V1_9),
BEETROOTS(207, "Beetroot Block", Version.V1_9),
GRASS_PATH(208, "Grass Path", "path", Version.V1_9),
END_GATEWAY(209, "End Gateway", "gateway", Version.V1_9),
REPEATING_COMMAND_BLOCK(210, "Repeating Command Block", Version.V1_9),
CHAIN_COMMAND_BLOCK(211, "Chain Command Block", Version.V1_9),
FROSTED_ICE(212, "Frosted Ice", Version.V1_9),
MAGMA(213, "Magma Block", Version.V1_10),
NETHER_WART_BLOCK(214, "Nether Wart Block", Version.V1_10),
RED_NETHER_BRICK(215, "Red Nether Brick", "red[^0-9A-Z]*nether[^0-9A-Z]*bricks", Version.V1_10),
BONE_BLOCK(216, "Bone Block", Version.V1_10),
STRUCTURE_VOID(217, "Structure Void", Version.V1_10),
OBSERVER(218, "Observer", Version.V1_11),
WHITE_SHULKER_BOX(219, "White Shulker Box", Version.V1_11),
ORANGE_SHULKER_BOX(220, "Orange Shulker Box", Version.V1_11),
MAGENTA_SHULKER_BOX(221, "Magenta Shulker Box", Version.V1_11),
LIGHT_BLUE_SHULKER_BOX(222, "Light Blue Shulker Box", "aqua[^0-9A-Z]*shulker[^0-9A-Z]*box", Version.V1_11),
YELLOW_SHULKER_BOX(223, "Yellow Shulker Box", Version.V1_11),
LIME_SHULKER_BOX(224, "Lime Shulker Box", "light[^0-9A-Z]*green[^0-9A-Z]*shulker[^0-9A-Z]*box", Version.V1_11),
PINK_SHULKER_BOX(225, "Pink Shulker Box", Version.V1_11),
GRAY_SHULKER_BOX(226, "Gray Shulker Box", "grey[^0-9A-Z]*shulker[^0-9A-Z]*box", Version.V1_11),
SILVER_SHULKER_BOX(227, "Light Gray Shulker Box", "light[^0-9A-Z]*grey[^0-9A-Z]*shulker[^0-9A-Z]*box", Version.V1_11),
CYAN_SHULKER_BOX(228, "Cyan Shulker Box", Version.V1_11),
PURPLE_SHULKER_BOX(229, "Purple Shulker Box", "^shulker[^0-9A-Z]*box", Version.V1_11),
BLUE_SHULKER_BOX(230, "Blue Shulker Box", Version.V1_11),
BROWN_SHULKER_BOX(231, "Brown Shulker Box", Version.V1_11),
GREEN_SHULKER_BOX(232, "Green Shulker Box", Version.V1_11),
RED_SHULKER_BOX(233, "Red Shulker Box", Version.V1_11),
BLACK_SHULKER_BOX(234, "Black Shulker Box", Version.V1_11),
WHITE_GLAZED_TERRACOTTA(235, "White Glazed Terracotta", "^(glazed[^0-9A-Z]*)?terr?acott?a", Version.V1_12),
ORANGE_GLAZED_TERRACOTTA(236, "Orange Glazed Terracotta", "orange[^0-9A-Z]*terr?acott?a", Version.V1_12),
MAGENTA_GLAZED_TERRACOTTA(237, "Magenta Glazed Terracotta", "magenta[^0-9A-Z]*terr?acott?a", Version.V1_12),
LIGHT_BLUE_GLAZED_TERRACOTTA(238, "Light Blue Glazed Terracotta", "((aqua)|(light[^0-9A-Z]*blue))[^0-9A-Z](glazed[^0-9A-Z]*)?terr?acott?a", Version.V1_12),
YELLOW_GLAZED_TERRACOTTA(239, "Yellow Glazed Terracotta", "yellow[^0-9A-Z]*terr?acott?a", Version.V1_12),
LIME_GLAZED_TERRACOTTA(240, "Lime Glazed Terracotta", "((lime)|(light[^0-9A-Z]*green))[^0-9A-Z](glazed[^0-9A-Z]*)?terr?acott?a", Version.V1_12),
PINK_GLAZED_TERRACOTTA(241, "Pink Glazed Terracotta", "pink[^0-9A-Z]*terr?acott?a", Version.V1_12),
GRAY_GLAZED_TERRACOTTA(242, "Gray Glazed Terracotta", "gr(a|e)y[^0-9A-Z]*terr?acott?a", Version.V1_12),
LIGHT_GRAY_GLAZED_TERRACOTTA(243, "Light Gray Glazed Terracotta", "light[^0-9A-Z]*gr(a|e)y[^0-9A-Z]*terr?acott?a", Version.V1_12),
CYAN_GLAZED_TERRACOTTA(244, "Cyan Glazed Terracotta", "cyan[^0-9A-Z]*terr?acott?a", Version.V1_12),
PURPLE_GLAZED_TERRACOTTA(245, "Purple Glazed Terracotta", "purple[^0-9A-Z]*terr?acott?a", Version.V1_12),
BLUE_GLAZED_TERRACOTTA(246, "Blue Glazed Terracotta", "blue[^0-9A-Z]*terr?acott?a", Version.V1_12),
BROWN_GLAZED_TERRACOTTA(247, "Brown Glazed Terracotta", "brown[^0-9A-Z]*terr?acott?a", Version.V1_12),
GREEN_GLAZED_TERRACOTTA(248, "Green Glazed Terracotta", "green[^0-9A-Z]*terr?acott?a", Version.V1_12),
RED_GLAZED_TERRACOTTA(249, "Red Glazed Terracotta", "red[^0-9A-Z]*terr?acott?a", Version.V1_12),
BLACK_GLAZED_TERRACOTTA(250, "Black Glazed Terracotta", "black[^0-9A-Z]*terr?acott?a", Version.V1_12),
CONCRETE(251, "White Concrete", "^concrete$", Version.V1_12),
ORANGE_CONCRETE(251, 1, "Orange Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$))", Version.V1_12),
MAGENTA_CONCRETE(251, 2, "Magenta Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$))", Version.V1_12),
LIGHT_BLUE_CONCRETE(251, 3, "Light Blue Concrete", "(aqua[^0-9A-Z]*concrete)|(((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))", Version.V1_12),
YELLOW_CONCRETE(251, 4, "Yellow Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$))", Version.V1_12),
LIME_CONCRETE(251, 5, "Lime Concrete", "(light[^0-9A-Z]*green[^0-9A-Z]*concrete)|(((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))", Version.V1_12),
PINK_CONCRETE(251, 6, "Pink Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((pink)|6)", Version.V1_12),
GRAY_CONCRETE(251, 7, "Gray Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7)", Version.V1_12),
LIGHT_GRAY_CONCRETE(251, 8, "Light Gray Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8)", Version.V1_12),
CYAN_CONCRETE(251, 9, "Cyan Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9)", Version.V1_12),
PURPLE_CONCRETE(251, 10, "Purple Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10))", Version.V1_12),
BLUE_CONCRETE(251, 11, "Blue Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11))", Version.V1_12),
BROWN_CONCRETE(251, 12, "Brown Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12))", Version.V1_12),
GREEN_CONCRETE(251, 13, "Green Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((green)|(13))", Version.V1_12),
RED_CONCRETE(251, 14, "Red Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((red)|(14))", Version.V1_12),
BLACK_CONCRETE(251, 15, "Black Concrete", "((251)|(concrete))[ ]*[:;|/.,\\-_~][ ]*((black)|(15))", Version.V1_12),
CONCRETE_POWDER(252, "White Concrete Powder", "^concrete[^0-9A-Z]*powder", Version.V1_12),
ORANGE_CONCRETE_POWDER(252, 1, "Orange Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((orange)|(1$))", Version.V1_12),
MAGENTA_CONCRETE_POWDER(252, 2, "Magenta Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((magenta)|(2$))", Version.V1_12),
LIGHT_BLUE_CONCRETE_POWDER(252, 3, "Light Blue Concrete Powder", "(aqua[^0-9A-Z]*concrete[^0-9A-Z]*powder)|(((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((aqua)|(light[^0-9A-Z]*blue)|(3$)))", Version.V1_12),
YELLOW_CONCRETE_POWDER(252, 4, "Yellow Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((yellow)|(4$))", Version.V1_12),
LIME_CONCRETE_POWDER(252, 5, "Lime Concrete Powder", "(light[^0-9A-Z]*green[^0-9A-Z]*concrete[^0-9A-Z]*powder)|(((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((lime)|(light[^0-9A-Z]*green)|(5$)))", Version.V1_12),
PINK_CONCRETE_POWDER(252, 6, "Pink Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((pink)|6)", Version.V1_12),
GRAY_CONCRETE_POWDER(252, 7, "Gray Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((gr(a|e)y)|7)", Version.V1_12),
LIGHT_GRAY_CONCRETE_POWDER(252, 8, "Light Gray Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((light[^0-9A-Z]*gr(a|e)y)|(silver)|8)", Version.V1_12),
CYAN_CONCRETE_POWDER(252, 9, "Cyan Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((cyan)|9)", Version.V1_12),
PURPLE_CONCRETE_POWDER(252, 10, "Purple Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((purple)|(10))", Version.V1_12),
BLUE_CONCRETE_POWDER(252, 11, "Blue Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((blue)|(11))", Version.V1_12),
BROWN_CONCRETE_POWDER(252, 12, "Brown Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((brown)|(12))", Version.V1_12),
GREEN_CONCRETE_POWDER(252, 13, "Green Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((green)|(13))", Version.V1_12),
RED_CONCRETE_POWDER(252, 14, "Red Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((red)|(14))", Version.V1_12),
BLACK_CONCRETE_POWDER(252, 15, "Black Concrete Powder", "((252)|(concrete[^0-9A-Z]*powder))[ ]*[:;|/.,\\-_~][ ]*((black)|(15))", Version.V1_12),
STRUCTURE_BLOCK(255, "Structure Block", Version.V1_9_USE_1_10),
IRON_SHOVEL(256, "Iron Shovel"),
IRON_PICKAXE(257, "Iron Pickaxe"),
IRON_AXE(258, "Iron Axe"),
FLINT_AND_STEEL(259, "Flint and Steel", "flint[^0-9A-Z]*&[^0-9A-Z]*steel"),
APPLE(260, "Apple"),
BOW(261, "Bow"),
ARROW(262, "Arrow"),
COAL(263, "Coal"),
CHARCOAL(263, 1, "Charcoal", "coal[ ]*[:;|/.,\\-_~][ ]*1"),
DIAMOND(264, "Diamond"),
IRON_INGOT(265, "Iron Ingot"),
GOLD_INGOT(266, "Gold Ingot"),
IRON_SWORD(267, "Iron Sword"),
WOODEN_SWORD(268, "Wooden Sword"),
WOODEN_SHOVEL(269, "Wooden Shovel"),
WOODEN_PICKAXE(270, "Wooden Pickaxe"),
WOODEN_AXE(271, "Wooden Axe"),
STONE_SWORD(272, "Stone Sword"),
STONE_SHOVEL(273, "Stone Shovel"),
STONE_PICKAXE(274, "Stone Pickaxe"),
STONE_AXE(275, "Stone Axe"),
DIAMOND_SWORD(276, "Diamond Sword"),
DIAMOND_SHOVEL(277, "Diamond Shovel"),
DIAMOND_PICKAXE(278, "Diamond Pickaxe"),
DIAMOND_AXE(279, "Diamond Axe"),
STICK(280, "Stick"),
BOWL(281, "Bowl"),
MUSHROOM_STEW(282, "Mushroom Stew"),
GOLDEN_SWORD(283, "Golden Sword"),
GOLDEN_SHOVEL(284, "Golden Shovel"),
GOLDEN_PICKAXE(285, "Golden Pickaxe"),
GOLDEN_AXE(286, "Golden Axe"),
STRING(287, "String"),
FEATHER(288, "Feather"),
GUNPOWDER(289, "Gunpowder", "sulphur"),
WOODEN_HOE(290, "Wooden Hoe"),
STONE_HOE(291, "Stone Hoe"),
IRON_HOE(292, "Iron Hoe"),
DIAMOND_HOE(293, "Diamond Hoe"), //srsly
GOLDEN_HOE(294, "Golden Hoe"),
WHEAT_SEEDS(295, "Wheat Seeds"),
WHEAT(296, "Wheat"),
BREAD(297, "Bread"),
LEATHER_HELMET(298, "Leather Helmet"),
LEATHER_CHESTPLATE(299, "Leather Tunic", "leather[^0-9A-Z]*shirt"),
LEATHER_LEGGINGS(300, "Leather Pants"),
LEATHER_BOOTS(301, "Leather Boots"),
CHAINMAIL_HELMET(302, "Chainmail Helmet"),
CHAINMAIL_CHESTPLATE(303, "Chainmail Chestplate"),
CHAINMAIL_LEGGINGS(304, "Chainmail Leggings"),
CHAINMAIL_BOOTS(305, "Chainmail Boots"),
IRON_HELMET(306, "Iron Helmet"),
IRON_CHESTPLATE(307, "Iron Chestplate"),
IRON_LEGGINGS(308, "Iron Leggings"),
IRON_BOOTS(309, "Iron Boots"),
DIAMOND_HELMET(310, "Diamond Helmet"),
DIAMOND_CHESTPLATE(311, "Diamond Chestplate"),
DIAMOND_LEGGINGS(312, "Diamond Leggings"),
DIAMOND_BOOTS(313, "Diamond Boots"),
GOLDEN_HELMET(314, "Golden Helmet"),
GOLDEN_CHESTPLATE(315, "Golden Chestplate"),
GOLDEN_LEGGINGS(316, "Golden Leggings"),
GOLDEN_BOOTS(317, "Golden Boots"),
FLINT(318, "Flint"),
PORKCHOP(319, "Raw Porkchop"),
COOKED_PORKCHOP(320, "Cooked Porkchop"),
PAINTING(321, "Painting"), //WHY ARE THE IMAGES RANDOM?
GOLDEN_APPLE(322, "Golden Apple", "gapple"),
ENCHANTED_GOLDEN_APPLE(322, 1, "Enchanted Golden Apple", "(god[^0-9A-Z]*apple)|(golden[^0-9A-Z]*apple[ ]*[:;|/.,\\-_~][ ]*1)"), //I actually like that this was removed. Fight me.
SIGN(323, "Sign"),
WOODEN_DOOR(324, "Oak Door", "((oak[^0-9A-Z]*)?wood[^0-9A-Z]*door)|(^door)"),
BUCKET(325, "Bucket"),
WATER_BUCKET(326, "Water Bucket"), //Always bring one while mining
LAVA_BUCKET(327, "Lava Bucket"), //Never hold it in your hotbar
MINECART(328, "Minecart"),
SADDLE(329, "Saddle"),
IRON_DOOR(330, "Iron Door"),
REDSTONE(331, "Redstone"),
SNOWBALL(332, "Snowball"),
BOAT(333, "Oak Boat"),
LEATHER(334, "Leather"),
MILK_BUCKET(335, "Milk Bucket"),
BRICK(336, "Brick"),
CLAY_BALL(337, "Clay"),
REEDS(338, "Sugar Canes", "sugar[^0-9A-Z]*cane"),
PAPER(339, "Paper"),
BOOK(340, "Book"),
SLIME_BALL(341, "Slimeball"),
CHEST_MINECART(342, "Minecart with Chest", "minecart[^0-9A-Z]*chest"),
FURNACE_MINECART(343, "Minecart with Furnace", "minecraft[^0-9A-Z]*furnace"),
EGG(344, "Egg"),
COMPASS(345, "Compass"),
FISHING_ROD(346, "Fishing Rod"),
CLOCK(347, "Clock"),
GLOWSTONE_DUST(348, "Glowstone Dust"),
FISH(349, "Raw Fish"),
SALMON(349, 1, "Raw Salmon", "fish[ ]*[:;|/.,\\-_~][ ]*1"),
CLOWNFISH(349, 2, "Clownfish", "fish[ ]*[:;|/.,\\-_~][ ]*2"),
PUFFERFISH(349, 3, "Pufferfish", "fish[ ]*[:;|/.,\\-_~][ ]*3"),
COOKED_FISH(350, "Cooked Fish"),
COOKED_SALMON(350, 1, "Cooked Salmon", "cooked[^0-9A-Z]*fish[ ]*[:;|/.,\\-_~][ ]*1"),
INK_SACK(351, "Ink Sack", "(inc[^0-9A-Z]*sac)|(^dye)"),
ROSE_RED(351, 1, "Rose Red", "(red[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*1$)"),
CACTUS_GREEN(351, 2, "Cactus Green", "(^green[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*2$)"),
COCO_BEANS(351, 3, "Coco Beans", "(cocoa[^0-9A-Z]*beans)|(brown[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*3$)"),
LAPIS_LAZULI(351, 4, "Lapis Lazuli", "(lapis)|(^blue[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*4$)"),
PURPLE_DYE(351, 5, "Purple Dye", "dye[ ]*[:;|/.,\\-_~][ ]*5$"),
CYAN_DYE(351, 6, "Cyan Dye", "dye[ ]*[:;|/.,\\-_~][ ]*6"),
LIGHT_GRAY_DYE(351, 7, "Light Gray Dye", "dye[ ]*[:;|/.,\\-_~][ ]*7"),
GRAY_DYE(351, 8, "Gray Dye", "dye[ ]*[:;|/.,\\-_~][ ]*8"),
PINK_DYE(351, 9, "Pink Dye", "dye[ ]*[:;|/.,\\-_~][ ]*9"),
LIME_DYE(351, 10, "Lime Dye", "(light[^0-9A-Z]*green[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*10)"),
DANDELION_YELLOW(351, 11, "Dandelion Yellow", "(yellow[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*11)"),
LIGHT_BLUE_DYE(351, 12, "Light Blue Dye", "(aqua[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*12)"),
MAGENTA_DYE(351, 13, "Magenta Dye", "dye[ ]*[:;|/.,\\-_~][ ]*13"),
ORANGE_DYE(351, 14, "Orange Dye", "dye[ ]*[:;|/.,\\-_~][ ]*14"),
BONE_MEAL(351, 15, "Bone Meal", "(white[^0-9A-Z]*dye)|(dye[ ]*[:;|/.,\\-_~][ ]*15)"),
BONE(352, "Bone"), //Do not put any of these in my pizza
SUGAR(353, "Sugar"),
CAKE(354, "Cake"),
BED(355, "Bed"),
REPEATER(356, "Redstone Repeater"),
COOKIE(357, "Cookie"),
FILLED_MAP(358, "Map"),
SHEARS(359, "Shears"),
MELON(360, "Melon"),
PUMPKIN_SEEDS(361, "Pumpkin Seeds"),
MELON_SEEDS(362, "Melon Seeds"),
BEEF(363, "Raw Beef"),
COOKED_BEEF(364, "Steak"),
CHICKEN(365, "Raw Chicken"),
COOKED_CHICKEN(366, "Cooked Chicken"),
ROTTEN_FLESH(367, "Rotten Flesh"),
ENDER_PEARL(368, "Ender Pearl"),
BLAZE_ROD(369, "Blaze Rod"),
GHAST_TEAR(370, "Ghast Tear"),
GOLD_NUGGET(371, "Gold Nugget"),
NETHER_WART(372, "Nether Wart"),
POTION(373, "Potion"),
//Potion ID variants go here when brewing is added
GLASS_BOTTLE(374, "Glass Bottle"),
SPIDER_EYE(375, "Spider Eye"),
FERMENTED_SPIDER_EYE(376, "Fermented Spider Eye"),
BLAZE_POWDER(377, "Blaze Powder"),
MAGMA_CREAM(378, "Magma Cream"),
BREWING_STAND(379, "Brewing Stand"),
CAULDRON(380, "Cauldron"),
ENDER_EYE(381, "Eye of Ender"),
SPECKLED_MELON(382, "Glistering Melon"),
ELDER_GUARDIAN_SPAWN_EGG(383, 4, "Spawn Elder Guardian", "(elder[^0-9A-Z]*guardian[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*4)"),
WITHER_SKELETON_SPAWN_EGG(383, 5, "Spawn Wither Skeleton", "(wither[^0-9A-Z]*skeleton[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*5)"),
STRAY_SPAWN_EGG(383, 6, "Spawn Stray", "(stray[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*6)"),
HUSK_SPAWN_EGG(383, 23, "Spawn Husk", "(husk[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*23)"),
ZOMBIE_VILLAGER_SPAWN_EGG(383, 27, "Spawn Zombie Villager", "(zombie[^0-9A-Z]*villager[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*27)"),
SKELETON_HORSE_SPAWN_EGG(383, 28, "Spawn Skeleton Horse", "(skeleton[^0-9A-Z]*horse[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*28)"),
ZOMBIE_HORSE_SPAWN_EGG(383, 29, "Spawn Zombie Horse", "(zombie[^0-9A-Z]*horse[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*29)"),
DONKEY_SPAWN_EGG(383, 31, "Spawn Donkey", "(donkey[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*31)"),
MULE_SPAWN_EGG(383, 32, "Spawn Mule", "(mule[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*32)"),
EVOKER_SPAWN_EGG(383, 34, "Spawn Evoker", "(evoker[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*34)"),
VEX_SPAWN_EGG(383, 35, "Spawn Vex", "(vex[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*35)"),
VINDICATOR_SPAWN_EGG(383, 36, "Spawn Vindicator", "(vindicator[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*36)"),
CREEPER_SPAWN_EGG(383, 50, "Spawn Creeper", "(creeper[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*50)"),
SKELETON_SPAWN_EGG(383, 51, "Spawn Skeleton", "(skeleton[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*51)"), //Spooky scary
SPIDER_SPAWN_EGG(383, 52, "Spawn Spider", "(spider[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*52)"),
ZOMBIE_SPAWN_EGG(383, 54, "Spawn Zombie", "(zombie[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*54)"),
SLIME_SPAWN_EGG(383, 55, "Spawn Slime", "(slime[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*55)"),
GHAST_SPAWN_EGG(383, 56, "Spawn Ghast", "(ghast[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*56)"),
ZOMBIE_PIGMAN_SPAWN_EGG(383, 57, "Spawn Zombie Pigman", "(zombie[^0-9A-Z]*pigman[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*57)"),
ENDERMAN_SPAWN_EGG(383, 58, "Spawn Enderman", "(enderman[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*58)"),
CAVE_SPIDER_SPAWN_EGG(383, 59, "Spawn Cave Spider", "(cave[^0-9A-Z]*spider[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*59)"),
SILVERFISH_SPAWN_EGG(383, 60, "Spawn Silverfish", "(silverfish[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*60)"),
BLAZE_SPAWN_EGG(383, 61, "Spawn Blaze", "(blaze[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*61)"),
MAGMA_CUBE_SPAWN_EGG(383, 62, "Spawn Magma Cube", "(magma[^0-9A-Z]*cube[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*62)"),
BAT_SPAWN_EGG(383, 65, "Spawn Bat", "(bat[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*65)"),
WITCH_SPAWN_EGG(383, 66, "Spawn Witch", "(witch[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*66)"),
ENDERMITE_SPAWN_EGG(383, 67, "Spawn Endermite", "(endermite[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*67)"),
GUARDIAN_SPAWN_EGG(383, 68, "Spawn Guardian", "(guardian[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*68)"),
SHULKERSPAWN_EGG(383, 69, "Spawn Shulker", "(shulker[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*69)"),
PIG_SPAWN_EGG(383, 90, "Spawn Pig", "(pig[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*90)"),
SHEEP_SPAWN_EGG(383, 91, "Spawn Sheep", "(sheep[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*91)"),
COW_SPAWN_EGG(383, 92, "Spawn Cow", "(cow[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*92)"),
CHICKEN_SPAWN_EGG(383, 93, "Spawn Chicken", "(chicken[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*93)"),
SQUID_SPAWN_EGG(383, 94, "Spawn Squid", "(squid[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*94)"),
WOLF_SPAWN_EGG(383, 95, "Spawn Wolf", "(wolf[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*95)"),
MOOSHROOM_SPAWN_EGG(383, 96, "Spawn Mooshroom", "(spawn[^0-9A-Z]*mushroom[^0-9A-Z]*cow)|((mooshroom)|(mushroom[^0-9A-Z]*cow)[^0-9A-Z]*(spawn[^0-9A-Z]*)?egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*96)"),
OCELOT_SPAWN_EGG(383, 98, "Spawn Ocelot", "(spawn[^0-9A-Z]*ozelot)|(o(c|z)elot[^0-9A-Z]*(spawn[^0-9A-Z]*)?egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*98)"),
HORSE_SPAWN_EGG(383, 100, "Spawn Horse", "(horse[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*100)"),
RABBIT_SPAWN_EGG(383, 101, "Spawn Rabbit", "(spawn[^0-9A-Z]*bunny)|((rabbit)|(bunny)[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*101)"),
POLAR_BEAR_SPAWN_EGG(383, 102, "Spawn Polar Bear", "(polar[^0-9A-Z]*bear[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*102)"),
LLAMA_SPAWN_EGG(383, 103, "Spawn Llama", "(llama[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*103)"),
VILLAGER_SPAWN_EGG(383, 120, "Spawn Villager", "(villager[^0-9A-Z]*egg)|(spawn[^0-9A-Z]*egg[ ]*[:;|/.,\\-_~][ ]*120)"),
EXPERIENCE_BOTTLE(384, "Bottle o' Enchanting"),
FIRE_CHARGE(385, "Fire Charge"),
WRITABLE_BOOK(386, "Book and Quill", "book[^0-9A-Z]*&[^0-9A-Z]*quill"),
WRITTEN_BOOK(387, "Written Book", "signed[^0-9A-Z]*book"),
EMERALD(388, "Emerald"),
ITEM_FRAME(389, "Item Frame"),
FLOWER_POT(390, "Flower Pot"),
CARROT(391, "Carrot"),
POTATO(392, "Potato"),
BAKED_POTATO(393, "Baked Potato"),
POISONOUS_POTATO(394, "Poisonous Potato"),
MAP(395, "Empty Map"),
GOLDEN_CARROT(396, "Golden Carrot"),
SKELETON_HEAD(397, "Mob Head (Skeleton)"),
WITHER_SKELETON_HEAD(397, 1, "Mob Head (Wither Skeleton)"),
ZOMBIE_HEAD(397, 2, "Mob Head (Zombie)"),
PLAYER_HEAD(397, 3, "Mob Head (Human)"),
CREEPER_HEAD(397, 4, "Mob Head (Creeper)"),
DRAGON_HEAD(397, 5, "Mob Head (Dragon)"),
CARROT_ON_A_STICK(398, "Carrot on a Stick", "carrot[^0-9A-Z]*stick"),
NETHER_STAR(399, "Nether Star"),
PUMPKIN_PIE(400, "Pumpkin Pie"),
FIREWORKS(401, "Firework Rocket"),
FIREWORK_CHARGE(402, "Firework Star"),
ENCHANTED_BOOK(403, "Enchanted Book"),
COMPARATOR(404, "Redstone Comparator"), //Not found
NETHERBRICK(405, "Nether Brick"),
QUARTZ(406, "Nether Quartz"),
TNT_MINECART(407, "Minecart with TNT", "minecart[^0-9A-Z]*tnt"),
HOPPER_MINECART(408, "Minecart with Hopper", "hopper[^0-9A-Z]*minecart"),
PRISMARINE_SHARD(409, "Prismarine Shard", Version.V1_8),
PRISMARINE_CRYSTALS(410, "Prismarine Crystals", Version.V1_8),
RABBIT(411, "Raw Rabbit", Version.V1_8),
COOKED_RABBIT(412, "Cooked Rabbit", Version.V1_8),
RABBIT_STEW(413, "Rabbit Stew", Version.V1_8),
RABBIT_FOOT(414, "Rabbit's Foot", Version.V1_8),
RABBIT_HIDE(415, "Rabbit Hide", Version.V1_8),
ARMOR_STAND(416, "Armor Stand", Version.V1_8),
IRON_HORSE_ARMOR(417, "Iron Horse Armor"),
GOLDEN_HORSE_ARMOR(418, "Golden Horse Armor"),
DIAMOND_HORSE_ARMOR(419, "Diamond Horse Armor"),
LEAD(420, "Lead"), //blaze it
NAME_TAG(421, "Name Tag", "nametag"),
COMMAND_BLOCK_MINECART(422, "Minecart with Command Block", "minecart[^0-9A-Z]*command[^0-9A-Z]*block"),
MUTTON(423, "Raw Mutton", Version.V1_8),
COOKED_MUTTON(424, "Cooked Mutton", Version.V1_8),
BANNER(425, "Banner", Version.V1_8),
//Missing ID
SPRUCE_DOOR(427, "Spruce Door", "spruce[^0-9A-Z]*wood[^0-9A-Z]*door"),
BIRCH_DOOR(428, "Birch Door", "birch[^0-9A-Z]*wood[^0-9A-Z]*door"),
JUNGLE_DOOR(429, "Jungle Door", "jungle[^0-9A-Z]*wood[^0-9A-Z]*door"),
ACACIA_DOOR(430, "Acacia Door", "acacia[^0-9A-Z]*wood[^0-9A-Z]*door"),
DARK_OAK_DOOR(431, "Dark Oak Door", "dark[^0-9A-Z]*(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?door"),
CHORUS_FRUIT(432, "Chorus Fruit", Version.V1_9),
POPPED_CHORUS_FRUIT(433, "Popped Chorus Fruit", Version.V1_9),
BEETROOT(434, "Beetroot", Version.V1_9),
BEETROOT_SEEDS(435, "Beetroot Seeds", Version.V1_9),
BEETROOT_SOUP(436, "Beetroot Soup", Version.V1_9),
DRAGON_BREATH(437, "Dragon's Breath", Version.V1_9),
SPLASH_POTION(438, "Splash Potion"),
//Potion IDs go here
SPECTRAL_ARROW(439, "Spectral Arrow", "glowing[^0-9A-Z]*arrow", Version.V1_9),
TIPPED_ARROW(440, "Tipped Arrow", Version.V1_9),
LINGERING_POTION(441, "Lingering Potion", Version.V1_9),
//Potion IDs go here
SHIELD(442, "Shield", Version.V1_9),
ELYTRA(443, "Elytra", Version.V1_9), //Best item in the game hands down
SPRUCE_BOAT(444, "Spruce Boat", "spruce[^0-9A-Z]*(wood[^0-9A-Z]*)?boat", Version.V1_9),
BIRCH_BOAT(445, "Birch Boat", "birch[^0-9A-Z]*(wood[^0-9A-Z]*)?boat", Version.V1_9),
JUNGLE_BOAT(446, "Jungle Boat", "jungle[^0-9A-Z]*(wood[^0-9A-Z]*)?boat", Version.V1_9),
ACACIA_BOAT(447, "Acacia Boat", "acacia[^0-9A-Z]*(wood[^0-9A-Z]*)?boat", Version.V1_9),
DARK_OAK_BOAT(448, "Dark Oak Boat", "dark(oak[^0-9A-Z]*)?(wood[^0-9A-Z]*)?boat", Version.V1_9),
TOTEM_OF_UNDYING(449, "Totem of Undying"), //I want to know what drugs they were on when they thought this was a good idea
SHULKER_SHELL(450, "Shulker Shell", Version.V1_11),
//Missing ID
IRON_NUGGET(452, "Iron Nugget", Version.V1_11_1),
RECORD_13(2256, "13 Disc"),
RECORD_CAT(2257, "Cat Disc"),
RECORD_BLOCKS(2258, "Blocks Disc"),
RECORD_CHIRP(2259, "Chirp Disc"),
RECORD_FAR(2260, "Far Disc"),
RECORD_MALL(2261, "Mall Disc"),
RECORD_MELLOHI(2262, "Mellohi Disc"),
RECORD_STAL(2263, "Stal Disc"),
RECORD_STRAD(2264, "Strad Disc"),
RECORD_WARD(2265, "Ward Disc"),
RECORD_11(2266, "11 Disc"),
RECORD_WAIT(2267, "Wait Disc");
public final int id;
public final int data;
public final String name;
public final String regex;
public final Version version;
public final Tool tool;
public final int enchantability;
private Item(int id, String name) {
this(id, 0, name, null, null, null, 0);
}
private Item(int id, int data, String name) {
this(id, data, name, null, null, null, 0);
}
private Item(int id, String name, String regex) {
this(id, 0, name, regex, null, null, 0);
}
private Item(int id, String name, Version version) {
this(id, 0, name, null, version, null, 0);
}
private Item(int id, String name, String regex, Version version) {
this(id, 0, name, regex, version, null, 0);
}
private Item(int id, int data, String name, String regex) {
this(id, data, name, regex, null, null, 0);
}
private Item(int id, int data, String name, Version version) {
this(id, data, name, null, version, null, 0);
}
private Item(int id, int data, String name, String regex, Version version) {
this(id, data, name, regex, version, null, 0);
}
private Item(int id, int data, String name, String regex, Tool tool, int enchantability) {
this(id, data, name, regex, null, tool, 0);
}
private Item(int id, int data, String name, String regex, Version version, Tool tool, int enchantability) {
this.id = id;
this.data = data;
this.name = name;
this.regex = regex;
this.version = version;
this.tool = tool;
this.enchantability = enchantability;
}
public boolean matches(String str, int mode) {
switch (mode) {
case 0:
//Display name
return name.equalsIgnoreCase(str);
case 1:
//Item id and data
String pattern = "^" + id;
if (data != 0) pattern += "[ ]*[:;|/.,\\-_~][ ]*" + data;
return Pattern.compile(pattern + "$").matcher(str).find();
case 2:
//Display name regex
String displayRegex = "^";
for (String s : name.split(" ")) {
displayRegex += s + "[^0-9A-Z]*";
}
displayRegex += "$";
return name.contains(" ") && Pattern.compile(displayRegex, Pattern.CASE_INSENSITIVE).matcher(str).find();
case 3:
//Enum name regex
String enumRegex = "^";
for (String s : this.name().split("_")) {
enumRegex += s + "[^0-9A-Z]*";
}
enumRegex += "$";
return name.contains(" ") && Pattern.compile(enumRegex, Pattern.CASE_INSENSITIVE).matcher(str).find();
case 4:
//Predefined regex
return regex != null && Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(str).find();
default:
throw new IllegalArgumentException("Mode must be between 0-4!");
}
}
/**
* @return The embed info for this item.
*/
public EmbedBuilder getInfo() {
EmbedBuilder eb = new EmbedBuilder();
String desc = "**Id: `" + id + "`\nData: `" + data + "`**";
//If a recipe for this item exists
try {
Recipe r = Recipe.valueOf(this.name());
if (r.notes != null) desc += "\n" + r.notes;
if (r.version != null) desc += "\n" + r.version.toString();
String ext = ".png";
if (r.gif) ext = ".gif";
eb.setImage("https://minecord.github.io/recipes/" + id + "-" + data + ext);
} catch (IllegalArgumentException ex) {
if (version != null) desc += "\n" + version.toString();
eb.setThumbnail("https://minecord.github.io/items/" + id + "-" + data + ".png");
}
eb.setDescription(desc);
return eb;
}
}
|
package it.asg.hustle;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar; // la toolbar
private DrawerLayout myDrawerLayout; // imposta NavigationDrawer
private FloatingActionButton fab; // FloatingActionButton
private NavigationView navigationView; // NavigationView (per il navigation drawer)
private MenuItem SearchAction;
private boolean isSearchOpened = false;
private EditText edtSeach;
private Display display;
static int numOfElements = 3; //3=default(small and normal); 4=large; 5=xlarge
private SQLiteDatabase db = null;
private SQLiteOpenHelper helper = null;
com.facebook.login.widget.ProfilePictureView profilePictureInvisible = null;
de.hdodenhof.circleimageview.CircleImageView circleImageView = null;
TextView account_name_facebook_tv = null;
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter; // adapter per RecyclerView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize facebook sdk
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
// apre o crea il db
helper = new DBHelper(this);
db = helper.getWritableDatabase();
Log.d("HUSTLE", "Aperto database con nome: " + helper.getDatabaseName());
// imposto ActionBar sulla Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.title));
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
//prendo DrawerLayout
myDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//click elementi su NavigationDrawer
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
myDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
if (menuItem.getTitle().equals(getResources().getString(R.string.nav_item_login)) == true) {
// accesso facebook
Intent intentactivityfacebook = new Intent(MainActivity.this, FacebookActivity.class);
startActivity(intentactivityfacebook);
}
return true;
}
});
//click del FAB
fab = (FloatingActionButton) findViewById(R.id.fab_plus);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("HUSTLE", "FAB was pressed");
// Launch activity for searching a TV show
startActivity(new Intent(getApplicationContext(), SearchActivity.class));
}
});
// prendo dimensioni del display per vedere quanti elementi della griglia posso mettere
display = getWindowManager().getDefaultDisplay();
MainActivity.numOfElements = getDisplayDimensions(display);
// Crea un TvShowAdapter
TvShowAdapter adapter = new TvShowAdapter(getSupportFragmentManager());
// Prende il ViewPager e imposta come adapter il TvShowAdapter: in base alla tab
// selezionata, mostra il fragment relativo
ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
// Prende il TabLayout e imposta il ViewPager
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
// Imposta
circleImageView = (de.hdodenhof.circleimageview.CircleImageView)findViewById(R.id.circleView);
profilePictureInvisible = (com.facebook.login.widget.ProfilePictureView)findViewById(R.id.profilePictureInvisible);
account_name_facebook_tv = (TextView) findViewById(R.id.account_name_facebook);
//Log.d("HUSTLE", "profilePictureInvisible: " + profilePictureInvisible);
updateCircleProfile();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
updateCircleProfile();
myDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
return true;
case R.id.action_search:
handleMenuSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void handleMenuSearch(){
ActionBar action = getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true); //show the title in the action bar
//hides the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);
//add the search icon in the action bar
SearchAction.setIcon(getResources().getDrawable(R.drawable.ic_search));
isSearchOpened = false;
} else { //open the search entry
action.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar.
action.setCustomView(R.layout.search_bar);//add the custom view
action.setDisplayShowTitleEnabled(false); //hide the title
edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor
//this is a listener to do a search when the user clicks on search button
edtSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String searchingTitle = v.getText().toString();
Intent i = new Intent(getApplicationContext(), SearchActivity.class);
Bundle b = new Bundle();
b.putString("SearchTitle", searchingTitle);
i.putExtras(b);
startActivity(i);
return true;
}
return false;
}
});
edtSeach.requestFocus();
//open the keyboard focused in the edtSearch
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);
//add the close icon
SearchAction.setIcon(getResources().getDrawable(R.drawable.ic_close));
isSearchOpened = true;
}
}
@Override
public void onBackPressed() {
if(isSearchOpened) {
handleMenuSearch();
return;
}
super.onBackPressed();
}
// for serching button (on Toolbar)
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SearchAction = menu.findItem(R.id.action_search);
return super.onPrepareOptionsMenu(menu);
}
// sottoclasse per gestire i fragment della pagina inziale
public static class TvShowFragment extends Fragment {
private static final String TAB_POSITION = "tab_position";
public TvShowFragment() {
}
public static TvShowFragment newInstance(int tabPosition) {
TvShowFragment fragment = new TvShowFragment();
Bundle args = new Bundle();
args.putInt(TAB_POSITION, tabPosition);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
int tabPosition = args.getInt(TAB_POSITION);
Log.d("asg","tabPosition "+tabPosition);
// TODO: in base alla tabPosition mostra le serie
/*
ArrayList<String> items = new ArrayList<String>();
for(int i=0 ; i < 50 ; i++){
items.add("TV-Show "+i);
} */
/*View v = inflater.inflate(R.layout.fragment_list_view, container, false);
RecyclerView recyclerView = (RecyclerView)v.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new ShowRecyclerAdapter(items)); */
View v = inflater.inflate(R.layout.fragment_list_view, container, false);
RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity() , numOfElements);
recyclerView.setLayoutManager(gridLayoutManager);
it.asg.hustle.GridAdapter newAdapter = new GridAdapter();
recyclerView.setAdapter(newAdapter);
//recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//recyclerView.setAdapter(new ShowRecyclerAdapter(items));
return v;
}
}
public int getDisplayDimensions(Display d){
Point size = new Point();
d.getSize(size);
int widthPX = size.x;
//int heightPX = size.y;
int widthDPI = pxToDp(widthPX);
//int heightDPI = pxToDp(heightPX);
Log.d("asg", "widthDPI vale: " +widthDPI);
int wPX = (int) getResources().getDimension(R.dimen.grid_item_RelativeLayout_width);
int wDP = pxToDp(wPX);
Log.d("asg","W vale: "+wDP);
int num = (int) Math.floor(widthDPI/wDP);
Log.d("asg", "widthDPI/num vale: " + num);
return num;
}
//sottoclasse per l'adapter per i fragment e i titoli (delle varie tab)
class TvShowAdapter extends FragmentStatePagerAdapter {
private int number_of_tabs=3;
public TvShowAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return TvShowFragment.newInstance(position);
}
@Override
public int getCount() {
return number_of_tabs;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getResources().getString(R.string.tab_myshow);
// break;
case 1:
return getResources().getString(R.string.tab_friends);
// break;
case 2:
return getResources().getString(R.string.tab_mostviewed);
// break;
}
return "";
}
}
@Override
protected void onResume() {
super.onResume();
updateCircleProfile();
}
void updateCircleProfile() {
SharedPreferences options = getSharedPreferences("id_facebook", Context.MODE_PRIVATE);
String id = options.getString("id_facebook", null);
String fbId = profilePictureInvisible.getProfileId();
Log.d("HUSTLE", "Sto per aggiornare facebook, profileID: " + profilePictureInvisible.getProfileId() + ", id delle preferenze: " + id);
Log.d("HUSTLE", "SETTING id facebook: " + id);
profilePictureInvisible.setProfileId(id);
Log.d("HUSTLE", "Updating circle profile");
//ImageView profileImageView = ((ImageView)profilePictureInvisible.getChildAt(0));
Bitmap bitmap = ((BitmapDrawable)((ImageView)profilePictureInvisible.getChildAt(0)).getDrawable()).getBitmap();
circleImageView.setImageBitmap(bitmap);
//aggiornamento textview nome
options = getSharedPreferences("name_facebook", Context.MODE_PRIVATE);
String name = options.getString("name_facebook", null);
if (name != null){
account_name_facebook_tv.setText(name);
account_name_facebook_tv.invalidate();
}
else{
account_name_facebook_tv.setText(getResources().getString(R.string.account_default_name));
account_name_facebook_tv.invalidate();
}
}
@Override
protected void onStart() {
super.onStart();
}
public int pxToDp(int px) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
int dp = (int) ((px/displayMetrics.density)+0.5);
return dp;
}
}
|
package org.jpos.ee.pm.core.operations;
import org.jpos.ee.Constants;
import org.jpos.ee.pm.core.*;
/**
*
* @author jpaoletti
*/
public class ListOperation extends OperationCommandSupport {
public ListOperation(String operationId) {
super(operationId);
}
@Override
protected void doExecute(PMContext ctx) throws PMException {
super.doExecute(ctx);
final ListManager listManager = new ListManager();
final Operations operations = (Operations) ctx.get(OPERATIONS);
PaginatedList pmlist = ctx.getList();
if (pmlist == null) {
pmlist = listManager.initList(ctx, operations);
}
configureOrder(ctx, pmlist);
pmlist.setPage((Integer) ctx.get("page"));
pmlist.setRowsPerPage((Integer) ctx.get("rows_per_page"));
ctx.put(Constants.PM_LIST_ORDER, pmlist.getOrder());
ctx.put(Constants.PM_LIST_ASC, !pmlist.isDesc());
listManager.configureList(ctx, pmlist, operations);
}
public void configureOrder(PMContext ctx, PaginatedList pmlist) {
final String o = ctx.getString("order");
try {
if (o != null) {
pmlist.setOrder(o);
} else {
pmlist.setOrder(ctx.getEntity().getOrderedFields().get(0).getId());
}
} catch (PMException e) {
PresentationManager.getPm().error(e);
}
pmlist.setDesc(ctx.getBoolean("desc",false));
}
}
|
package org.hbase.async;
import org.jboss.netty.buffer.ChannelBuffer;
import org.hbase.async.generated.ClientPB.MutateRequest;
import org.hbase.async.generated.ClientPB.MutateResponse;
import org.hbase.async.generated.ClientPB.MutationProto;
/**
* Deletes some data into HBase.
*
* <h1>A note on passing {@code byte} arrays in argument</h1>
* None of the method that receive a {@code byte[]} in argument will copy it.
* For more info, please refer to the documentation of {@link HBaseRpc}.
* <h1>A note on passing {@code String}s in argument</h1>
* All strings are assumed to use the platform's default charset.
* <h1>A note on passing {@code timestamp}s in argument</h1>
* Irrespective of the order in which you send RPCs, a {@code DeleteRequest}
* that is created with a specific timestamp in argument will only delete
* values in HBase that were previously stored with a timestamp less than
* or equal to that of the {@code DeleteRequest} unless
* {@link #setDeleteAtTimestampOnly} is also called, in which case only the
* value at the specified timestamp is deleted.
*/
public final class DeleteRequest extends BatchableRpc
implements HBaseRpc.HasTable, HBaseRpc.HasKey,
HBaseRpc.HasFamily, HBaseRpc.HasQualifiers, HBaseRpc.IsEdit {
private static final byte[] DELETE = new byte[] {
'd', 'e', 'l', 'e', 't', 'e'
};
/** Code type used for serialized `Delete' objects. */
static final byte CODE = 31;
/** Special value for {@link #qualifiers} when deleting a whole family. */
private static final byte[][] DELETE_FAMILY_MARKER =
new byte[][] { HBaseClient.EMPTY_ARRAY };
/** Special value for {@link #family} when deleting a whole row. */
static final byte[] WHOLE_ROW = new byte[0];
private final byte[][] qualifiers;
/** Whether to delete the value only at the specified timestamp. */
private boolean at_timestamp_only = false;
public DeleteRequest(final byte[] table, final byte[] key) {
this(table, key, null, null, KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table, final byte[] key,
final long timestamp) {
this(table, key, null, null, timestamp, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family) {
this(table, key, family, null, KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final long timestamp) {
this(table, key, family, null, timestamp, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier) {
this(table, key, family,
qualifier == null ? null : new byte[][] { qualifier },
KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier,
final long timestamp) {
this(table, key, family,
qualifier == null ? null : new byte[][] { qualifier },
timestamp, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers) {
this(table, key, family, qualifiers,
KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final long timestamp) {
this(table, key, family, qualifiers, timestamp, RowLock.NO_LOCK);
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier,
final RowLock lock) {
this(table, key, family,
qualifier == null ? null : new byte[][] { qualifier },
KeyValue.TIMESTAMP_NOW, lock.id());
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier,
final long timestamp,
final RowLock lock) {
this(table, key, family,
qualifier == null ? null : new byte[][] { qualifier },
timestamp, lock.id());
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final RowLock lock) {
this(table, key, family, qualifiers, KeyValue.TIMESTAMP_NOW, lock.id());
}
public DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final long timestamp,
final RowLock lock) {
this(table, key, family, qualifiers, timestamp, lock.id());
}
public DeleteRequest(final String table, final String key) {
this(table.getBytes(), key.getBytes(), null, null,
KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final String table,
final String key,
final String family) {
this(table.getBytes(), key.getBytes(), family.getBytes(), null,
KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final String table,
final String key,
final String family,
final String qualifier) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
qualifier == null ? null : new byte[][] { qualifier.getBytes() },
KeyValue.TIMESTAMP_NOW, RowLock.NO_LOCK);
}
public DeleteRequest(final String table,
final String key,
final String family,
final String qualifier,
final RowLock lock) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
qualifier == null ? null : new byte[][] { qualifier.getBytes() },
KeyValue.TIMESTAMP_NOW, lock.id());
}
/**
* Constructor to delete a specific cell.
* @param table The table to edit.
* @param kv The specific {@link KeyValue} to delete. Note that if this
* {@link KeyValue} specifies a timestamp, then this specific timestamp only
* will be deleted.
* @since 1.2
*/
public DeleteRequest(final byte[] table, final KeyValue kv) {
this(table, kv.key(), kv.family(), new byte[][] { kv.qualifier() },
kv.timestamp(), RowLock.NO_LOCK);
}
/**
* Constructor to delete a specific cell with an explicit row lock.
* @param table The table to edit.
* @param kv The specific {@link KeyValue} to delete. Note that if this
* {@link KeyValue} specifies a timestamp, then this specific timestamp only
* will be deleted.
* @param lock An explicit row lock to use with this request.
* @since 1.2
*/
public DeleteRequest(final byte[] table,
final KeyValue kv,
final RowLock lock) {
this(table, kv.key(), kv.family(), new byte[][] { kv.qualifier() },
kv.timestamp(), lock.id());
}
/** Private constructor. */
private DeleteRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[][] qualifiers,
final long timestamp,
final long lockid) {
super(table, key, family == null ? WHOLE_ROW : family, timestamp, lockid);
if (family != null) {
KeyValue.checkFamily(family);
}
if (qualifiers != null) {
if (family == null) {
throw new IllegalArgumentException("You can't delete specific qualifiers"
+ " without specifying which family they belong to."
+ " table=" + Bytes.pretty(table)
+ ", key=" + Bytes.pretty(key));
}
if (qualifiers.length == 0) {
throw new IllegalArgumentException("Don't pass an empty list of"
+ " qualifiers, this would delete the entire row of table="
+ Bytes.pretty(table) + " at key " + Bytes.pretty(key));
}
for (final byte[] qualifier : qualifiers) {
KeyValue.checkQualifier(qualifier);
}
this.qualifiers = qualifiers;
} else {
// No specific qualifier to delete: delete the entire family. Not that
// if `family == null', we'll delete the whole row anyway.
this.qualifiers = DELETE_FAMILY_MARKER;
}
}
/**
* Deletes only the cell value with the timestamp specified in the
* constructor.
* <p>
* Only applicable when qualifier(s) is also specified.
* @since 1.5
*/
public void setDeleteAtTimestampOnly(final boolean at_timestamp_only) {
this.at_timestamp_only = at_timestamp_only;
}
/**
* Returns whether to only delete the cell value at the timestamp.
* @since 1.5
*/
public boolean deleteAtTimestampOnly() {
return at_timestamp_only;
}
@Override
byte[] method(final byte server_version) {
return (server_version >= RegionClient.SERVER_VERSION_095_OR_ABOVE
? MUTATE
: DELETE);
}
@Override
public byte[] table() {
return table;
}
@Override
public byte[] key() {
return key;
}
@Override
public byte[][] qualifiers() {
return qualifiers;
}
public String toString() {
return super.toStringWithQualifiers("DeleteRequest", family, qualifiers);
}
// Package private stuff. //
@Override
byte version(final byte unused_server_version) {
// Versions are:
// 1: Before 0.92.0. This method only gets called for 0.92 and above.
// 2: HBASE-3921 in 0.92.0 added "attributes" at the end.
// 3: HBASE-3961 in 0.92.0 allowed skipping the WAL.
return 3; // 3 because we allow skipping the WAL.
}
@Override
byte code() {
return CODE;
}
@Override
int numKeyValues() {
return qualifiers.length;
}
@Override
void serializePayload(final ChannelBuffer buf) {
if (family == null) {
return; // No payload when deleting whole rows.
}
// Are we deleting a whole family at once or just a bunch of columns?
final byte type = (qualifiers == DELETE_FAMILY_MARKER
? KeyValue.DELETE_FAMILY
: (at_timestamp_only
? KeyValue.DELETE
: KeyValue.DELETE_COLUMN));
// Write the KeyValues
for (final byte[] qualifier : qualifiers) {
KeyValue.serialize(buf, type, timestamp,
key, family, qualifier, null);
}
}
/**
* Predicts a lower bound on the serialized size of this RPC.
* This is to avoid using a dynamic buffer, to avoid re-sizing the buffer.
* Since we use a static buffer, if the prediction is wrong and turns out
* to be less than what we need, there will be an exception which will
* prevent the RPC from being serialized. That'd be a severe bug.
*/
private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 1; // byte: Type again (see HBASE-2877).
size += 1; // byte: Version of Delete.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
size += 8; // long: Timestamp.
size += 8; // long: Lock ID.
size += 4; // int: Number of families.
size += 1; // vint: Family length (guaranteed on 1 byte).
if (family == null) {
return size;
}
size += family.length; // The column family.
size += 4; // int: Number of KeyValues for this family.
return size + payloadSize();
}
/** Returns the serialized size of all the {@link KeyValue}s in this RPC. */
@Override
int payloadSize() {
if (family == WHOLE_ROW) {
return 0; // No payload when deleting whole rows.
}
int size = 0;
size += 4; // int: Total length of the whole KeyValue.
size += 4; // int: Total length of the key part of the KeyValue.
size += 4; // int: Length of the value part of the KeyValue.
size += 2; // short:Length of the key.
size += key.length; // The row key (again!).
size += 1; // byte: Family length (again!).
size += family.length; // The column family (again!).
size += 8; // long: The timestamp (again!).
size += 1; // byte: The type of KeyValue.
size *= qualifiers.length;
for (final byte[] qualifier : qualifiers) {
size += qualifier.length; // The column qualifier.
}
return size;
}
@Override
MutationProto toMutationProto() {
final MutationProto.Builder del = MutationProto.newBuilder()
.setRow(Bytes.wrap(key))
.setMutateType(MutationProto.MutationType.DELETE);
if (family != WHOLE_ROW) {
final MutationProto.ColumnValue.Builder columns = // All columns ...
MutationProto.ColumnValue.newBuilder()
.setFamily(Bytes.wrap(family)); // ... for this family.
final MutationProto.DeleteType type =
(qualifiers == DELETE_FAMILY_MARKER
? MutationProto.DeleteType.DELETE_FAMILY
: (at_timestamp_only
? MutationProto.DeleteType.DELETE_ONE_VERSION
: MutationProto.DeleteType.DELETE_MULTIPLE_VERSIONS));
// Now add all the qualifiers to delete.
for (int i = 0; i < qualifiers.length; i++) {
final MutationProto.ColumnValue.QualifierValue column =
MutationProto.ColumnValue.QualifierValue.newBuilder()
.setQualifier(Bytes.wrap(qualifiers[i]))
.setTimestamp(timestamp)
.setDeleteType(type)
.build();
columns.addQualifierValue(column);
}
del.addColumnValue(columns);
}
if (!durable) {
del.setDurability(MutationProto.Durability.SKIP_WAL);
}
return del.build();
}
/** Serializes this request. */
ChannelBuffer serialize(final byte server_version) {
if (server_version < RegionClient.SERVER_VERSION_095_OR_ABOVE) {
return serializeOld(server_version);
}
final MutateRequest req = MutateRequest.newBuilder()
.setRegion(region.toProtobuf())
.setMutation(toMutationProto())
.build();
return toChannelBuffer(MUTATE, req);
}
/** Serializes this request for HBase 0.94 and before. */
private ChannelBuffer serializeOld(final byte server_version) {
final ChannelBuffer buf = newBuffer(server_version,
predictSerializedSize());
buf.writeInt(2); // Number of parameters.
// 1st param: byte array containing region name
writeHBaseByteArray(buf, region.name());
// 2nd param: Delete object.
buf.writeByte(CODE); // Code for a `Delete' parameter.
buf.writeByte(CODE); // Code again (see HBASE-2877).
buf.writeByte(1); // Delete#DELETE_VERSION. Stick to v1 here for now.
writeByteArray(buf, key);
buf.writeLong(timestamp); // Maximum timestamp.
buf.writeLong(lockid); // Lock ID.
// Families.
if (family == WHOLE_ROW) {
buf.writeInt(0); // Number of families that follow.
return buf;
}
buf.writeInt(1); // Number of families that follow.
// Each family is then written like so:
writeByteArray(buf, family); // Column family name.
buf.writeInt(qualifiers.length); // How many KeyValues for this family?
serializePayload(buf);
return buf;
}
@Override
Object deserialize(final ChannelBuffer buf, int cell_size) {
HBaseRpc.ensureNoCell(cell_size);
final MutateResponse resp = readProtobuf(buf, MutateResponse.PARSER);
return null;
}
}
|
package makyu.view;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkActivity extends AppCompatActivity implements View.OnClickListener{
private static final String RANK_API_URL = "http://yige.cc/api/rs_rank100";
private static final String ACTIVITY_TAG = "NetworkDemo";
public Button getDataButton;
public TextView text;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
text.setText((String) msg.obj);
}
};
Runnable newTread = new Runnable() {
@Override
public void run() {
Message msg = handler.obtainMessage();
try {
URL url = new URL(RANK_API_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.setRequestProperty("Charset", "UTF-8");
int code = conn.getResponseCode();
if(code != 200) {
throw new RuntimeException("url");
}
InputStream inputStream = conn.getInputStream();
String res = streamToString(inputStream);
msg.obj = "" + code + "\n" + res;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(NetworkActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
text = (TextView) findViewById(R.id.text_res);
getDataButton = (Button) findViewById(R.id.getNetData);
getDataButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.getNetData :
getData();
break;
}
}
private void getData() {
Thread t = new Thread(newTread);
t.start();
}
/**
*
* @param is
* @return
*/
public static String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (Exception e) {
Log.e(ACTIVITY_TAG, e.toString());
return null;
}
}
}
|
package org.wikipedia.page;
import androidx.annotation.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.wikipedia.json.GsonUtil;
import java.util.Arrays;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.defaultString;
/**
* Gson POJO for one section of a page.
*/
public class Section {
private int id;
private int level;
private String anchor;
private String text;
private String title;
public static List<Section> fromJson(String json) {
return Arrays.asList(GsonUtil.getDefaultGson().fromJson(json, Section[].class));
}
/** Default constructor used by Gson deserialization. Good for setting default values. */
public Section() {
level = 1;
}
public Section(int id, int level, String heading, String anchor, String content) {
this.id = id;
this.level = level;
this.title = heading;
this.anchor = anchor;
this.text = content;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Section)) {
return false;
}
Section other = (Section) o;
return getId() == other.getId()
&& getLevel() == other.getLevel()
&& StringUtils.equals(getHeading(), other.getHeading())
&& StringUtils.equals(getAnchor(), other.getAnchor())
&& StringUtils.equals(getContent(), other.getContent());
}
@Override
public int hashCode() {
int result = getId();
result = 31 * result + getHeading().hashCode();
result = 31 * result + getAnchor().hashCode();
result = 31 * result + getContent().hashCode();
return result;
}
@NonNull
@Override
public String toString() {
return "Section{"
+ "id=" + id
+ ", level=" + level
+ ", anchor='" + anchor + '\''
+ ", text='" + text + '\''
+ '}';
}
public boolean isLead() {
return id == 0;
}
public int getId() {
return id;
}
public int getLevel() {
return level;
}
@NonNull public String getHeading() {
return defaultString(title);
}
@NonNull public String getAnchor() {
return defaultString(anchor);
}
@NonNull public String getContent() {
return defaultString(text);
}
}
|
package com.haulmont.cuba.web.auth;
import com.haulmont.cuba.core.global.AppBeans;
import com.haulmont.cuba.core.global.Configuration;
import com.haulmont.cuba.core.global.Messages;
import com.haulmont.cuba.security.global.LoginException;
import org.apache.commons.lang.StringUtils;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.support.LdapUtils;
import javax.inject.Inject;
import javax.servlet.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* @author artamonov
* @version $Id$
*/
public class LdapAuthProvider implements CubaAuthProvider {
@Inject
protected Messages messages;
protected LdapContextSource ldapContextSource;
protected LdapTemplate ldapTemplate;
@Override
public void authenticate(String login, String password, Locale messagesLocale) throws LoginException {
if (!ldapTemplate.authenticate(LdapUtils.emptyLdapName(), buildPersonFilter(login), password)) {
throw new LoginException(
String.format(messages.getMessage(LdapAuthProvider.class, "LoginException.InvalidLoginOrPassword", messagesLocale), login)
);
}
}
protected String buildPersonFilter(String login) {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("sAMAccountName", login));
return filter.encode();
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
ldapContextSource = new LdapContextSource();
Configuration configuration = AppBeans.get(Configuration.NAME);
WebAuthConfig webAuthConfig = configuration.getConfig(WebAuthConfig.class);
checkRequiredConfigProperties(webAuthConfig);
ldapContextSource.setBase(webAuthConfig.getLdapBase());
List<String> ldapUrls = webAuthConfig.getLdapUrls();
ldapContextSource.setUrls(ldapUrls.toArray(new String[ldapUrls.size()]));
ldapContextSource.setUserDn(webAuthConfig.getLdapUser());
ldapContextSource.setPassword(webAuthConfig.getLdapPassword());
ldapContextSource.afterPropertiesSet();
ldapTemplate = new LdapTemplate(ldapContextSource);
ldapTemplate.setIgnorePartialResultException(true);
}
protected void checkRequiredConfigProperties(WebAuthConfig webAuthConfig) {
List<String> missingProperties = new ArrayList<>();
if (StringUtils.isBlank(webAuthConfig.getLdapBase())) {
missingProperties.add("cuba.web.ldap.base");
}
if (webAuthConfig.getLdapUrls().isEmpty()) {
missingProperties.add("cuba.web.ldap.urls");
}
if (StringUtils.isBlank(webAuthConfig.getLdapUser())) {
missingProperties.add("cuba.web.ldap.user");
}
if (StringUtils.isBlank(webAuthConfig.getLdapPassword())) {
missingProperties.add("cuba.web.ldap.password");
}
if (!missingProperties.isEmpty()) {
throw new IllegalStateException("Please configure required application properties for LDAP integration: \n" +
StringUtils.join(missingProperties, "\n"));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
|
package org.msgpack.core.buffer;
import sun.misc.Unsafe;
import sun.nio.ch.DirectBuffer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;
import static org.msgpack.core.Preconditions.*;
/**
* MessageBuffer class is an abstraction of memory for reading/writing message packed data.
* This MessageBuffers ensures short/int/float/long/double values are written in the big-endian order.
*
* This class is optimized for fast memory access, so many methods are
* implemented without using any interface method that produces invokeinterface call in JVM.
* Compared to invokevirtual, invokeinterface is 30% slower in general because it needs to find a target function from the table.
*
*/
public class MessageBuffer {
static final Unsafe unsafe;
static final Constructor byteBufferConstructor;
static final boolean isByteBufferConstructorTakesBufferReference;
static final int ARRAY_BYTE_BASE_OFFSET;
static final int ARRAY_BYTE_INDEX_SCALE;
static {
try {
// Fetch theUnsafe object for Orackle JDK and OpenJDK
Unsafe u;
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
u = (Unsafe) field.get(null);
}
catch(NoSuchFieldException e) {
// Workaround for creating an Unsafe instance for Android OS
Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();
unsafeConstructor.setAccessible(true);
u = (Unsafe) unsafeConstructor.newInstance();
}
unsafe = u;
if (unsafe == null) {
throw new RuntimeException("Unsafe is unavailable");
}
ARRAY_BYTE_BASE_OFFSET = unsafe.arrayBaseOffset(byte[].class);
ARRAY_BYTE_INDEX_SCALE = unsafe.arrayIndexScale(byte[].class);
// Make sure the VM thinks bytes are only one byte wide
if (ARRAY_BYTE_INDEX_SCALE != 1) {
throw new IllegalStateException("Byte array index scale must be 1, but is " + ARRAY_BYTE_INDEX_SCALE);
}
// Find the hidden constructor for DirectByteBuffer
Class<?> directByteBufferClass = ClassLoader.getSystemClassLoader().loadClass("java.nio.DirectByteBuffer");
Constructor directByteBufferConstructor = null;
boolean isAcceptReference = true;
try {
directByteBufferConstructor = directByteBufferClass.getDeclaredConstructor(long.class, int.class, Object.class);
}
catch(NoSuchMethodError e) {
directByteBufferConstructor = directByteBufferClass.getDeclaredConstructor(long.class, int.class);
isAcceptReference = true;
}
byteBufferConstructor = directByteBufferConstructor;
isByteBufferConstructorTakesBufferReference = isAcceptReference;
if(byteBufferConstructor == null)
throw new RuntimeException("Constructor of DirectByteBuffer is not found");
byteBufferConstructor.setAccessible(true);
// Check the endian of this CPU
boolean isLittleEndian = true;
byte[] a = new byte[8];
unsafe.putLong(a, (long) ARRAY_BYTE_BASE_OFFSET, 0x0102030405060708L);
switch (a[0]) {
case 0x01:
isLittleEndian = false;
break;
case 0x08:
isLittleEndian = true;
break;
default:
assert false;
}
String bufferClsName = isLittleEndian ? "org.msgpack.core.buffer.MessageBuffer" : "org.msgpack.core.buffer.MessageBufferBE";
msgBufferClass = Class.forName(bufferClsName);
}
catch (Exception e) {
e.printStackTrace(System.err);
throw new RuntimeException(e);
}
}
/**
* MessageBuffer class to use. If this machine is big-endian, it uses MessageBufferBE, which overrides some methods in this class that translate endians. If not, uses MessageBuffer.
*/
private final static Class<?> msgBufferClass;
/**
* Base object for resolving the relative address of the raw byte array.
* If base == null, the address value is a raw memory address
*/
protected final Object base;
/**
* Head address of the underlying memory. If base is null, the address is a direct memory address, and if not,
* it is the relative address within an array object (base)
*/
protected final long address;
/**
* Size of the underlying memory
*/
protected final int size;
/**
* Reference is used to hold a reference to an object that holds the underlying memory so that it cannot be
* released by the garbage collector.
*/
protected final ByteBuffer reference;
// TODO life-time managment of this buffer
//private AtomicInteger referenceCounter;
static MessageBuffer newOffHeapBuffer(int length) {
long address = unsafe.allocateMemory(length);
return new MessageBuffer(address, length);
}
public static MessageBuffer newDirectBuffer(int length) {
ByteBuffer m = ByteBuffer.allocateDirect(length);
return newMessageBuffer(m);
}
public static MessageBuffer newBuffer(int length) {
return newMessageBuffer(new byte[length]);
}
public static MessageBuffer wrap(byte[] array) {
return newMessageBuffer(array);
}
public static MessageBuffer wrap(ByteBuffer bb) {
return newMessageBuffer(bb);
}
/**
* Creates a new MessageBuffer instance backed by ByteBuffer
* @param bb
* @return
*/
private static MessageBuffer newMessageBuffer(ByteBuffer bb) {
checkNotNull(bb);
try {
// We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be
// generated to resolve one of the method references when two or more classes overrides the method.
Constructor<?> constructor = msgBufferClass.getDeclaredConstructor(ByteBuffer.class);
return (MessageBuffer) constructor.newInstance(bb);
}
catch(NoSuchMethodException e) {
throw new IllegalStateException(e);
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
/**
* Creates a new MessageBuffer instance backed by a java heap array
* @param arr
* @return
*/
private static MessageBuffer newMessageBuffer(byte[] arr) {
checkNotNull(arr);
try {
Constructor<?> constructor = msgBufferClass.getDeclaredConstructor(byte[].class);
return (MessageBuffer) constructor.newInstance(arr);
}
catch(NoSuchMethodException e) {
throw new IllegalStateException(e);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static void releaseBuffer(MessageBuffer buffer) {
if(buffer.base instanceof byte[]) {
// We have nothing to do. Wait until the garbage-collector collects this array object
}
else if(buffer.base instanceof DirectBuffer) {
((DirectBuffer) buffer.base).cleaner().clean();
}
else {
// Maybe cannot reach here
unsafe.freeMemory(buffer.address);
}
}
/**
* Create a MessageBuffer instance from a given memory address and length
* @param address
* @param length
*/
MessageBuffer(long address, int length) {
this.base = null;
this.address = address;
this.size = length;
this.reference = null;
}
/**
* Create a MessageBuffer instance from a given ByteBuffer instance
* @param bb
*/
MessageBuffer(ByteBuffer bb) {
if(bb.isDirect()) {
// Direct buffer or off-heap memory
DirectBuffer db = DirectBuffer.class.cast(bb);
this.base = null;
this.address = db.address();
this.size = bb.capacity();
this.reference = bb;
}
else if(bb.hasArray()) {
this.base = bb.array();
this.address = ARRAY_BYTE_BASE_OFFSET;
this.size = bb.array().length;
this.reference = null;
} else {
throw new IllegalArgumentException("Only the array-backed ByteBuffer or DirectBuffer are supported");
}
}
/**
* Create a MessageBuffer instance from an java heap array
* @param arr
*/
MessageBuffer(byte[] arr) {
this.base = arr;
this.address = ARRAY_BYTE_BASE_OFFSET;
this.size = arr.length;
this.reference = null;
}
protected MessageBuffer(Object base, long address, int length, ByteBuffer reference) {
this.base = base;
this.address = address;
this.size = length;
this.reference = reference;
}
/**
* byte size of the buffer
* @return
*/
public int size() { return size; }
public MessageBuffer slice(int offset, int length) {
// TODO ensure deleting this slice does not collapse this MessageBuffer
if(offset == 0 && length == size())
return this;
else {
checkArgument(offset + length <= size());
return new MessageBuffer(base, address + offset, length, reference);
}
}
public byte getByte(int index) {
return unsafe.getByte(base, address + index);
}
public boolean getBoolean(int index) {
return unsafe.getBoolean(base, address + index);
}
public short getShort(int index) {
short v = unsafe.getShort(base, address + index);
return Short.reverseBytes(v);
}
/**
* Read a big-endian int value at the specified index
* @param index
* @return
*/
public int getInt(int index) {
// Reading little-endian value
int i = unsafe.getInt(base, address + index);
// Reversing the endian
return Integer.reverseBytes(i);
}
public float getFloat(int index) {
return Float.intBitsToFloat(getInt(index));
}
public long getLong(int index) {
long l = unsafe.getLong(base, address + index);
return Long.reverseBytes(l);
}
public double getDouble(int index) {
return Double.longBitsToDouble(getLong(index));
}
public void getBytes(int index, byte[] dst, int dstOffset, int length) {
unsafe.copyMemory(base, address+index, dst, ARRAY_BYTE_BASE_OFFSET + dstOffset, length);
}
public void getBytes(int index, int len, ByteBuffer dst) {
if(dst.remaining() > len)
throw new BufferOverflowException();
ByteBuffer src = toByteBuffer(index, len);
dst.put(src);
}
public void putByte(int index, byte v) {
unsafe.putByte(base, address + index, v);
}
public void putBoolean(int index, boolean v) {
unsafe.putBoolean(base, address + index, v);
}
public void putShort(int index, short v) {
v = Short.reverseBytes(v);
unsafe.putShort(base, address + index, v);
}
/**
* Write a big-endian integer value to the memory
* @param index
* @param v
*/
public void putInt(int index, int v){
// Reversing the endian
v = Integer.reverseBytes(v);
unsafe.putInt(base, address + index, v);
}
public void putFloat(int index, float v) {
putInt(index, Float.floatToRawIntBits(v));
}
public void putLong(int index, long l) {
// Reversing the endian
l = Long.reverseBytes(l);
unsafe.putLong(base, address + index, l);
}
public void putDouble(int index, double v) {
putLong(index, Double.doubleToRawLongBits(v));
}
public void putBytes(int index, byte[] src, int srcOffset, int length) {
unsafe.copyMemory(src, ARRAY_BYTE_BASE_OFFSET + srcOffset, base, address+index, length);
}
public void putByteBuffer(int index, ByteBuffer src, int len) {
assert(len <= src.remaining());
if(src.isDirect()) {
DirectBuffer db = (DirectBuffer) src;
unsafe.copyMemory(null, db.address() + src.position(), base, address+index, len);
} else if(src.hasArray()) {
byte[] srcArray = src.array();
unsafe.copyMemory(srcArray, ARRAY_BYTE_BASE_OFFSET + src.position(), base, address+index, len);
} else {
if(base != null) {
src.get((byte []) base, index, len);
}
else {
for(int i=0; i<len; ++i) {
unsafe.putByte(base, address + index, src.get());
}
}
}
src.position(src.position() + len);
}
/**
* Create a ByteBuffer view of the range [index, index+length) of this memory
* @param index
* @param length
* @return
*/
public ByteBuffer toByteBuffer(int index, int length) {
if(base instanceof byte[]) {
return ByteBuffer.wrap((byte[]) base, (int) ((address-ARRAY_BYTE_BASE_OFFSET) + index), length);
}
try {
if(isByteBufferConstructorTakesBufferReference)
return (ByteBuffer) byteBufferConstructor.newInstance(address + index, length, reference);
else
return (ByteBuffer) byteBufferConstructor.newInstance(address + index, length);
} catch(Throwable e) {
// Convert checked exception to unchecked exception
throw new RuntimeException(e);
}
}
public ByteBuffer toByteBuffer() {
return toByteBuffer(0, size());
}
public byte[] toByteArray() {
byte[] b = new byte[size()];
unsafe.copyMemory(base, address, b, ARRAY_BYTE_BASE_OFFSET, size());
return b;
}
public void relocate(int offset, int length, int dst) {
unsafe.copyMemory(base, address + offset, base, address+dst, length);
}
/**
* Copy this buffer contents to another MessageBuffer
* @param index
* @param dst
* @param offset
* @param length
*/
public void copyTo(int index, MessageBuffer dst, int offset, int length) {
unsafe.copyMemory(base, address + index, dst.base, dst.address + offset, length);
}
public String toHexString(int offset, int length) {
StringBuilder s = new StringBuilder();
for(int i=offset; i<length; ++i) {
if(i != offset)
s.append(" ");
s.append(String.format("%02x", getByte(i)));
}
return s.toString();
}
}
|
package net.lecousin.framework.io;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import net.lecousin.framework.concurrent.CancelException;
import net.lecousin.framework.concurrent.Task;
import net.lecousin.framework.concurrent.TaskManager;
import net.lecousin.framework.concurrent.synch.AsyncWork;
import net.lecousin.framework.concurrent.synch.AsyncWork.AsyncWorkListener;
import net.lecousin.framework.concurrent.synch.ISynchronizationPoint;
import net.lecousin.framework.concurrent.synch.JoinPoint;
import net.lecousin.framework.concurrent.synch.SynchronizationPoint;
import net.lecousin.framework.event.Listener;
import net.lecousin.framework.exception.NoException;
import net.lecousin.framework.io.IO.Seekable.SeekType;
import net.lecousin.framework.io.buffering.PreBufferedReadable;
import net.lecousin.framework.io.text.BufferedReadableCharacterStream;
import net.lecousin.framework.mutable.Mutable;
import net.lecousin.framework.mutable.MutableInteger;
import net.lecousin.framework.mutable.MutableLong;
import net.lecousin.framework.progress.WorkProgress;
import net.lecousin.framework.util.Pair;
import net.lecousin.framework.util.RunnableWithParameter;
import net.lecousin.framework.util.UnprotectedStringBuffer;
/**
* Utility methods for IO.
*/
public class IOUtil {
/**
* Fill the remaining bytes of the given buffer.
* @param io the readable to read from
* @param buffer the buffer to fill
* @return the number of bytes read, which is less than the remaining bytes of the buffer only if the end of the IO is reached.
* @throws IOException in case of error reading bytes
*/
public static int readFully(IO.Readable io, ByteBuffer buffer) throws IOException {
int read = 0;
while (buffer.hasRemaining()) {
int nb = io.readSync(buffer);
if (nb <= 0) break;
read += nb;
}
return read;
}
/**
* Fill the given buffer.
* @param io the readable to read from
* @param buffer the buffer to fill
* @return the number of bytes read, which is less than the length of the buffer only if the end of the IO is reached.
* @throws IOException in case of error reading bytes
*/
public static int readFully(IO.ReadableByteStream io, byte[] buffer) throws IOException {
int read = 0;
while (read < buffer.length) {
int nb = io.read(buffer, read, buffer.length - read);
if (nb <= 0) break;
read += nb;
}
return read;
}
/**
* Read the given number of bytes.
* @param io the readable to read from
* @param buffer the buffer to fill
* @param off the offset of the buffer from which to fill
* @param len the number of bytes to read
* @return the number of bytes read, which is less than the len only if the end of the IO is reached.
* @throws IOException in case of error reading bytes
*/
public static int readFully(IO.ReadableByteStream io, byte[] buffer, int off, int len) throws IOException {
int read = 0;
while (read < len) {
int nb = io.read(buffer, off + read, len - read);
if (nb <= 0) break;
read += nb;
}
return read;
}
/**
* Fill the remaining bytes of the given buffer.
* @param io the readable to read from
* @param pos the position in the io to start from
* @param buffer the buffer to fill
* @return the number of bytes read, which is less than the remaining bytes of the buffer only if the end of the IO is reached.
* @throws IOException in case of error reading bytes
*/
public static int readFullySync(IO.Readable.Seekable io, long pos, ByteBuffer buffer) throws IOException {
int read = 0;
while (buffer.hasRemaining()) {
int nb = io.readSync(pos, buffer);
if (nb <= 0) break;
read += nb;
pos += nb;
}
return read;
}
/**
* Fill the remaining bytes of the given buffer asynchronously.
* @param io the readable to read from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read, which is less than the remaining bytes of the buffer only if the end of the IO is reached.
*/
public static AsyncWork<Integer,IOException> readFullyAsynch(
IO.Readable io, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
return readFullyAsynch(io,buffer,0,ondone);
}
/**
* Fill the remaining bytes of the given buffer asynchronously.
* @param io the readable to read from
* @param buffer the buffer to fill
* @param done number of bytes already read (will be added to the returned number of bytes read)
* @param ondone a listener to call before to return the result
* @return the number of bytes read, which is less than the remaining bytes of the buffer only if the end of the IO is reached.
*/
public static AsyncWork<Integer,IOException> readFullyAsynch(
IO.Readable io, ByteBuffer buffer, int done, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
AsyncWork<Integer,IOException> read = io.readAsync(buffer);
if (read.isUnblocked()) {
if (!read.isSuccessful()) {
if (ondone != null && read.getError() != null) ondone.run(new Pair<>(null, read.getError()));
return read;
}
if (!buffer.hasRemaining()) {
if (done == 0) {
if (ondone != null) ondone.run(new Pair<>(read.getResult(), null));
return read;
}
if (read.getResult().intValue() <= 0) {
if (ondone != null) ondone.run(new Pair<>(Integer.valueOf(done), null));
return new AsyncWork<>(Integer.valueOf(done), null);
}
if (ondone != null) ondone.run(new Pair<>(Integer.valueOf(read.getResult().intValue() + done),null));
return new AsyncWork<>(Integer.valueOf(read.getResult().intValue() + done),null);
}
if (read.getResult().intValue() <= 0) {
if (done == 0) {
if (ondone != null) ondone.run(new Pair<>(read.getResult(), null));
return read;
}
if (ondone != null) ondone.run(new Pair<>(Integer.valueOf(done), null));
return new AsyncWork<>(Integer.valueOf(done), null);
}
return readFullyAsynch(io, buffer, read.getResult().intValue() + done, ondone);
}
AsyncWork<Integer,IOException> sp = new AsyncWork<>();
MutableInteger total = new MutableInteger(done);
Mutable<AsyncWork<Integer,IOException>> r = new Mutable<>(read);
read.listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void ready(Integer result) {
if (!buffer.hasRemaining() || result.intValue() <= 0) {
if (total.get() == 0) {
if (ondone != null) ondone.run(new Pair<>(result, null));
sp.unblockSuccess(result);
} else if (result.intValue() >= 0) {
if (ondone != null) ondone.run(new Pair<>(Integer.valueOf(result.intValue() + total.get()), null));
sp.unblockSuccess(Integer.valueOf(result.intValue() + total.get()));
} else {
if (ondone != null) ondone.run(new Pair<>(Integer.valueOf(total.get()), null));
sp.unblockSuccess(Integer.valueOf(total.get()));
}
return;
}
total.add(result.intValue());
r.set(io.readAsync(buffer));
r.get().listenInline(this);
}
@Override
public void error(IOException error) {
if (ondone != null) ondone.run(new Pair<>(null, error));
sp.unblockError(error);
}
@Override
public void cancelled(CancelException event) {
sp.unblockCancel(event);
}
});
sp.listenCancel(new Listener<CancelException>() {
@Override
public void fire(CancelException event) {
r.get().unblockCancel(event);
}
});
return sp;
}
/**
* Fill the remaining bytes of the given buffer.
* @param io the readable to read from
* @param pos the position in the io to start from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read, which is less than the remaining bytes of the buffer only if the end of the IO is reached.
*/
public static AsyncWork<Integer,IOException> readFullyAsynch(
IO.Readable.Seekable io, long pos, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
AsyncWork<Integer,IOException> read = io.readAsync(pos, buffer);
if (read.isUnblocked()) {
if (ondone != null) {
if (read.getError() != null) ondone.run(new Pair<>(null, read.getError()));
else if (read.getResult() != null) ondone.run(new Pair<>(read.getResult(), null));
}
if (!read.isSuccessful()) return read;
if (!buffer.hasRemaining()) return read;
if (read.getResult().intValue() <= 0) return read;
}
AsyncWork<Integer,IOException> sp = new AsyncWork<>();
MutableInteger total = new MutableInteger(0);
Mutable<AsyncWork<Integer,IOException>> r = new Mutable<>(read);
read.listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void ready(Integer result) {
if (!buffer.hasRemaining() || result.intValue() <= 0) {
if (total.get() == 0) {
if (ondone != null) ondone.run(new Pair<>(result, null));
sp.unblockSuccess(result);
} else if (result.intValue() >= 0) {
Integer r = Integer.valueOf(result.intValue() + total.get());
if (ondone != null) ondone.run(new Pair<>(r, null));
sp.unblockSuccess(r);
} else {
Integer r = Integer.valueOf(total.get());
if (ondone != null) ondone.run(new Pair<>(r, null));
sp.unblockSuccess(r);
}
return;
}
total.add(result.intValue());
r.set(io.readAsync(pos + total.get(), buffer));
r.get().listenInline(this);
}
@Override
public void error(IOException error) {
sp.unblockError(error);
}
@Override
public void cancelled(CancelException event) {
sp.unblockCancel(event);
}
});
sp.listenCancel(new Listener<CancelException>() {
@Override
public void fire(CancelException event) {
r.get().unblockCancel(event);
}
});
return sp;
}
/**
* Implement an asynchronous read using a task calling the synchronous one.
* This must be used only if the synchronous read is using CPU.
* @param io the readable to read from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read
*/
public static Task<Integer,IOException> readAsyncUsingSync(
IO.Readable io, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer,IOException>(
"Reading from " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.readSync(buffer));
}
};
task.start();
return task;
}
/**
* Implement an asynchronous read using a task calling the synchronous one.
* This must be used only if the synchronous read is using CPU.
* @param io the readable to read from
* @param pos the position in the io to start from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read
*/
public static Task<Integer,IOException> readAsyncUsingSync(
IO.Readable.Seekable io, long pos, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer,IOException>(
"Reading from " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.readSync(pos, buffer));
}
};
task.start();
return task;
}
/**
* Implement an asynchronous read using a task calling the synchronous one.
* This must be used only if the synchronous read is using CPU.
* @param io the readable to read from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read
*/
public static Task<Integer,IOException> readFullyAsyncUsingSync(
IO.Readable io, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer,IOException>(
"Reading from " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.readFullySync(buffer));
}
};
task.start();
return task;
}
/**
* Implement an asynchronous read using a task calling the synchronous one.
* This must be used only if the synchronous read is using CPU.
* @param io the readable to read from
* @param pos the position in the io to start from
* @param buffer the buffer to fill
* @param ondone a listener to call before to return the result
* @return the number of bytes read
*/
public static Task<Integer,IOException> readFullyAsyncUsingSync(
IO.Readable.Seekable io, long pos, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer,IOException>(
"Reading from " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.readFullySync(pos, buffer));
}
};
task.start();
return task;
}
/**
* Implement a synchronous skip using a synchronous read.
*/
public static long skipSyncByReading(IO.Readable io, long n) throws IOException {
if (n <= 0) return 0;
int l = n > 65536 ? 65536 : (int)n;
ByteBuffer b = ByteBuffer.allocate(l);
long total = 0;
while (total < n) {
int len = n - total > l ? l : (int)(n - total);
b.clear();
b.limit(len);
int nb = io.readSync(b);
if (nb <= 0) break;
total += nb;
}
return total;
}
/**
* Implement an asynchronous skip using a task calling a synchronous skip.
* This must be used only if the synchronous skip is using only CPU.
*/
public static AsyncWork<Long,IOException> skipAsyncUsingSync(IO.Readable io, long n, RunnableWithParameter<Pair<Long,IOException>> ondone) {
Task<Long,IOException> task = new Task.Cpu<Long,IOException>("Skipping bytes", io.getPriority(), ondone) {
@Override
public Long run() throws IOException {
long total = skipSyncByReading(io, n);
return Long.valueOf(total);
}
};
task.start();
return task.getSynch();
}
/**
* Implement an asynchronous skip using readAsync.
*/
public static AsyncWork<Long, IOException> skipAsyncByReading(IO.Readable io, long n, RunnableWithParameter<Pair<Long,IOException>> ondone) {
if (n <= 0) {
if (ondone != null) ondone.run(new Pair<>(Long.valueOf(0), null));
return new AsyncWork<>(Long.valueOf(0), null);
}
ByteBuffer b = ByteBuffer.allocate(n > 65536 ? 65536 : (int)n);
MutableLong done = new MutableLong(0);
AsyncWork<Long, IOException> result = new AsyncWork<>();
io.readAsync(b).listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void ready(Integer nb) {
int read = nb.intValue();
if (read <= 0) {
if (ondone != null) ondone.run(new Pair<>(Long.valueOf(done.get()), null));
result.unblockSuccess(Long.valueOf(done.get()));
return;
}
done.add(nb.intValue());
if (done.get() == n) {
if (ondone != null) ondone.run(new Pair<>(Long.valueOf(n), null));
result.unblockSuccess(Long.valueOf(n));
return;
}
b.clear();
if (n - done.get() < b.remaining())
b.limit((int)(n - done.get()));
io.readAsync(b).listenInline(this);
}
@Override
public void error(IOException error) {
result.error(error);
}
@Override
public void cancelled(CancelException event) {
result.cancel(event);
}
});
return result;
}
/**
* Write the given Readable to a temporary file, and return the temporary file.
*/
public static File toTempFile(IO.Readable io) throws IOException {
File file = File.createTempFile("net.lecousin.framework.io", "streamtofile");
ByteBuffer buffer = ByteBuffer.allocateDirect(65536);
try (RandomAccessFile f = new RandomAccessFile(file, "w"); FileChannel c = f.getChannel()) {
do {
int nb = io.readFullySync(buffer);
if (nb <= 0) break;
buffer.flip();
c.write(buffer);
buffer.clear();
} while (true);
return file;
}
}
/**
* Implement a synchronous read using an asynchronous one and blocking until it finishes.
*/
public static int readSyncUsingAsync(IO.Readable io, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.readAsync(buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous read using an asynchronous one and blocking until it finishes.
*/
public static int readSyncUsingAsync(IO.Readable.Seekable io, long pos, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.readAsync(pos, buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous read using an asynchronous one and blocking until it finishes.
*/
public static int readFullySyncUsingAsync(IO.Readable io, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.readFullyAsync(buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous read using an asynchronous one and blocking until it finishes.
*/
public static int readFullySyncUsingAsync(IO.Readable.Seekable io, long pos, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.readFullyAsync(pos, buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous skip using an asynchronous one and blocking until it finishes.
*/
public static long skipSyncUsingAsync(IO.Readable io, long n) throws IOException {
AsyncWork<Long,IOException> sp = io.skipAsync(n);
try { return sp.blockResult(0).longValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous write using an asynchronous one and blocking until it finishes.
*/
public static int writeSyncUsingAsync(IO.Writable io, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.writeAsync(buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement a synchronous write using an asynchronous one and blocking until it finishes.
*/
public static int writeSyncUsingAsync(IO.Writable.Seekable io, long pos, ByteBuffer buffer) throws IOException {
AsyncWork<Integer,IOException> sp = io.writeAsync(pos, buffer);
try { return sp.blockResult(0).intValue(); }
catch (CancelException e) { throw new IOException("Cancelled",e); }
}
/**
* Implement an asynchronous write using a task calling a synchronous write.
* This must be used only if the synchronous write is only using CPU.
*/
public static Task<Integer,IOException> writeAsyncUsingSync(
IO.Writable io, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer, IOException>(
"Writing to " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.writeSync(buffer));
}
};
task.start();
return task;
}
/**
* Implement an asynchronous write using a task calling a synchronous write.
* This must be used only if the synchronous write is only using CPU.
*/
public static Task<Integer,IOException> writeAsyncUsingSync(
IO.Writable.Seekable io, long pos, ByteBuffer buffer, RunnableWithParameter<Pair<Integer,IOException>> ondone
) {
Task<Integer,IOException> task = new Task.Cpu<Integer, IOException>(
"Writing to " + io.getSourceDescription(), io.getPriority(), ondone
) {
@Override
public Integer run() throws IOException {
return Integer.valueOf(io.writeSync(pos, buffer));
}
};
task.start();
return task;
}
/**
* Read all bytes from the given Readable and convert it as a String using the given charset encoding.
*/
@SuppressWarnings("resource")
public static Task<UnprotectedStringBuffer,IOException> readFullyAsString(IO.Readable io, Charset charset, byte priority) {
IO.Readable.Buffered bio;
if (io instanceof IO.Readable.Buffered)
bio = (IO.Readable.Buffered)io;
else
bio = new PreBufferedReadable(io, 1024, priority, 8192, priority, 8);
Task<UnprotectedStringBuffer,IOException> task = new Task.Cpu<UnprotectedStringBuffer,IOException>(
"Read file as string: " + io.getSourceDescription(), priority
) {
@Override
public UnprotectedStringBuffer run() throws IOException {
BufferedReadableCharacterStream stream = new BufferedReadableCharacterStream(bio, charset, 64, 128);
UnprotectedStringBuffer str = new UnprotectedStringBuffer();
do {
try { str.append(stream.read()); }
catch (EOFException e) { break; }
} while (true);
return str;
}
};
task.startOn(bio.canStartReading(), false);
return task;
}
/**
* Read all bytes from the given Readable and convert it as a String using the given charset encoding.
*/
public static String readFullyAsStringSync(IO.Readable io, Charset charset) throws IOException {
if (io instanceof IO.KnownSize) {
byte[] bytes = new byte[(int)((IO.KnownSize)io).getSizeSync()];
io.readFullySync(ByteBuffer.wrap(bytes));
return new String(bytes, charset);
}
StringBuilder s = new StringBuilder();
byte[] buf = new byte[1024];
do {
int nb = io.readFullySync(ByteBuffer.wrap(buf));
if (nb <= 0) break;
s.append(new String(buf, 0, nb, charset));
if (nb < 1024) break;
} while (true);
return s.toString();
}
/**
* Read all bytes from the given file and convert it as a String using the given charset encoding.
*/
public static String readFullyAsStringSync(File file, Charset charset) throws IOException {
try (FileIO.ReadOnly io = new FileIO.ReadOnly(file, Task.PRIORITY_RATHER_IMPORTANT)) {
return readFullyAsStringSync(io, charset);
}
}
/**
* Implement an asynchronous seek using a task calling a synchronous one.
* This must be used only if the synchronous seek is only using CPU.
*/
public static Task<Long,IOException> seekAsyncUsingSync(
IO.Readable.Seekable io, SeekType type, long move, RunnableWithParameter<Pair<Long,IOException>> ondone
) {
Task<Long,IOException> task = new Task.Cpu<Long,IOException>("Seeking", io.getPriority(), ondone) {
@Override
public Long run() throws IOException {
return Long.valueOf(io.seekSync(type, move));
}
};
task.start();
return task;
}
/**
* Implement a synchronous sync by calling an asynchronous one and blocking until the result is available.
*/
public static long seekSyncUsingAsync(IO.Readable.Seekable io, SeekType type, long move) throws IOException {
AsyncWork<Long,IOException> seek = io.seekAsync(type, move);
seek.block(0);
if (seek.hasError())
throw seek.getError();
return seek.getResult().longValue();
}
/**
* Implement an asynchronous setSize using a task calling a synchronous one.
* This must be used only if the synchronous setSize is only using CPU.
*/
public static Task<Void,IOException> setSizeAsyncUsingSync(IO.Resizable io, long newSize,byte priority) {
Task<Void,IOException> task = new Task.Cpu<Void,IOException>("Resizing " + io.getSourceDescription(), priority) {
@Override
public Void run() throws IOException {
io.setSizeSync(newSize);
return null;
}
};
task.start();
return task;
}
/**
* Copy from a Readable to a Writable.
* @param input input to read from
* @param output output to write to
* @param size number of bytes to copy, or -1 if it is not known
* @param closeIOs if true both IOs will be closed at the end of the copy
* @param progress progress
* @param work amount of work in the progress
* @return number of bytes copied
*/
public static AsyncWork<Long, IOException> copy(
IO.Readable input, IO.Writable output, long size, boolean closeIOs, WorkProgress progress, long work
) {
AsyncWork<Long, IOException> sp = new AsyncWork<>();
copy(input, output, size, closeIOs, sp, progress, work);
return sp;
}
@SuppressWarnings("resource")
private static void copy(
IO.Readable input, IO.Writable output, long size, boolean closeIOs, AsyncWork<Long, IOException> sp, WorkProgress progress, long work
) {
if (size == 0) {
if (progress != null) progress.progress(work);
copyEnd(input, output, sp, null, null, closeIOs, 0);
return;
}
if (size < 0) {
if (input instanceof IO.KnownSize) {
AsyncWork<Long, IOException> getSize = ((IO.KnownSize)input).getSizeAsync();
getSize.listenInline(new Runnable() {
@Override
public void run() {
if (getSize.hasError())
copyEnd(input, output, sp, getSize.getError(), null, closeIOs, 0);
else if (getSize.isCancelled())
copyEnd(input, output, sp, null, getSize.getCancelEvent(), closeIOs, 0);
else
copy(input, output, getSize.getResult().longValue(), closeIOs, sp, progress, work);
}
});
return;
}
// unknown size
TaskManager tmIn = getUnderlyingTaskManager(input);
TaskManager tmOut = getUnderlyingTaskManager(output);
if (tmIn == tmOut) {
// same task manager
// - no need to pre-fill many buffers in input
// - use a buffer size quite large
copySameTM(input, output, 2 * 1024 * 1024, -1, sp, closeIOs, progress, work);
return;
}
// different task manager
if (input instanceof IO.Readable.Buffered) {
// input is already buffered, let's use it as is
copyStep((IO.Readable.Buffered)input, output, sp, 0, closeIOs, progress, work);
return;
}
PreBufferedReadable binput = new PreBufferedReadable(input, 65536, input.getPriority(), 1024 * 1024, input.getPriority(), 16);
copyStep(binput, output, sp, 0, closeIOs, progress, work);
return;
}
// known size
if (size <= 256 * 1024) {
// better to first read fully, then write fully
copySameTM(input, output, (int)size, size, sp, closeIOs, progress, work);
return;
}
TaskManager tmIn = getUnderlyingTaskManager(input);
TaskManager tmOut = getUnderlyingTaskManager(output);
if (tmIn == tmOut) {
// same task manager
if (size <= 4 * 1024 * 1024) {
// less then 4MB, better to first read fully, then write fully
copySameTM(input, output, (int)size, size, sp, closeIOs, progress, work);
return;
}
if (size <= 8 * 1024 * 1024) {
// let's do it in 2 buffers
copySameTM(input, output, (int)(size / 2 + 1), size, sp, closeIOs, progress, work);
return;
}
copySameTM(input, output, 4 * 1024 * 1024, size, sp, closeIOs, progress, work);
return;
}
// different task manager
if (input instanceof IO.Readable.Buffered) {
// input is already buffered, let's use it as is
copyStep((IO.Readable.Buffered)input, output, sp, 0, closeIOs, progress, work);
return;
}
PreBufferedReadable binput;
if (size <= 1024 * 1024)
binput = new PreBufferedReadable(input, size, 64 * 1024, input.getPriority(), 128 * 1024, input.getPriority(), 6);
else if (size <= 16 * 1024 * 1024)
binput = new PreBufferedReadable(input, size, 128 * 1024, input.getPriority(), 512 * 1024, input.getPriority(), 8);
else
binput = new PreBufferedReadable(input, size, 256 * 1024, input.getPriority(), 2 * 1024 * 1024, input.getPriority(), 5);
copyStep(binput, output, sp, 0, closeIOs, progress, work);
}
private static void copyEnd(
IO.Readable input, IO.Writable output,
AsyncWork<Long, IOException> sp, IOException error, CancelException cancel,
boolean closeIOs, long written
) {
if (!closeIOs) {
if (error != null)
sp.error(error);
else if (cancel != null)
sp.cancel(cancel);
else
sp.unblockSuccess(Long.valueOf(written));
return;
}
ISynchronizationPoint<IOException> sp1 = input.closeAsync();
ISynchronizationPoint<IOException> sp2 = output.closeAsync();
JoinPoint.fromSynchronizationPoints(sp1, sp2).listenInline(new Runnable() {
@Override
public void run() {
IOException e = error;
if (e == null) {
if (sp1.hasError()) e = sp1.getError();
else if (sp2.hasError()) e = sp2.getError();
}
if (e != null) {
sp.error(e);
return;
}
if (cancel != null)
sp.cancel(cancel);
else
sp.unblockSuccess(Long.valueOf(written));
}
});
}
private static void copySameTM(
IO.Readable input, IO.Writable output, int bufferSize, long total,
AsyncWork<Long,IOException> end, boolean closeIOs, WorkProgress progress, long work
) {
new Task.Cpu<Void, NoException>("Allocate buffers to copy IOs", input.getPriority()) {
@Override
public Void run() {
copySameTMStep(input, output, ByteBuffer.allocate(bufferSize), 0, total, end, closeIOs, progress, work);
return null;
}
}.start();
}
private static void copySameTMStep(
IO.Readable input, IO.Writable output, ByteBuffer buf, long written, long total,
AsyncWork<Long,IOException> end, boolean closeIOs, WorkProgress progress, long work
) {
input.readFullyAsync(buf).listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void ready(Integer result) {
int nb = result.intValue();
if (nb <= 0) {
if (progress != null) progress.progress(work);
copyEnd(input, output, end, null, null, closeIOs, written);
} else {
buf.flip();
if (progress != null) progress.progress(nb * work / (total * 2));
AsyncWork<Integer,IOException> write = output.writeAsync(buf);
write.listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void ready(Integer result) {
long w;
if (progress != null) {
w = nb * work / total;
progress.progress(w - (nb * work / (total * 2)));
w = work - w;
} else w = 0;
if (nb < buf.capacity() || (total > 0 && total == written + result.longValue()))
copyEnd(input, output, end, null, null, closeIOs, written + result.longValue());
else {
buf.clear();
copySameTMStep(input, output, buf, written + result.longValue(), total,
end, closeIOs, progress, w);
}
}
@Override
public void error(IOException error) {
copyEnd(input, output, end, error, null, closeIOs, written);
}
@Override
public void cancelled(CancelException event) {
copyEnd(input, output, end, null, event, closeIOs, written);
}
});
}
}
@Override
public void error(IOException error) {
copyEnd(input, output, end, error, null, closeIOs, written);
}
@Override
public void cancelled(CancelException event) {
copyEnd(input, output, end, null, event, closeIOs, written);
}
});
}
private static void copyStep(
IO.Readable.Buffered input, IO.Writable output, AsyncWork<Long, IOException> sp, long written,
boolean closeIOs, WorkProgress progress, long work
) {
AsyncWork<ByteBuffer, IOException> read = input.readNextBufferAsync();
read.listenInline(new Runnable() {
@Override
public void run() {
if (read.hasError()) {
copyEnd(input, output, sp, read.getError(), null, closeIOs, written);
return;
}
if (read.isCancelled()) {
copyEnd(input, output, sp, null, read.getCancelEvent(), closeIOs, written);
return;
}
ByteBuffer buf = read.getResult();
if (buf == null) {
if (progress != null) progress.progress(work);
copyEnd(input, output, sp, null, null, closeIOs, written);
return;
}
if (progress != null && work >= 2) progress.progress(1);
AsyncWork<Integer, IOException> write = output.writeAsync(buf);
write.listenInline(new Runnable() {
@Override
public void run() {
if (write.hasError()) {
copyEnd(input, output, sp, write.getError(), null, closeIOs, written);
return;
}
if (write.isCancelled()) {
copyEnd(input, output, sp, null, write.getCancelEvent(), closeIOs, written);
return;
}
if (progress != null && work >= 1) progress.progress(1);
copyStep(input, output, sp, written + write.getResult().intValue(), closeIOs, progress, work - 2);
}
});
}
});
}
// skip checkstyle: OverloadMethodsDeclarationOrder
/**
* Copy bytes inside a Seekable IO.
* @param io the IO
* @param src source position
* @param dst target position
* @param len number of bytes to copy
*/
public static <T extends IO.Writable.Seekable & IO.Readable.Seekable>
SynchronizationPoint<IOException> copy(T io, long src, long dst, long len) {
SynchronizationPoint<IOException> sp = new SynchronizationPoint<>();
if (len < 4 * 1024 * 1024) {
ByteBuffer buffer = ByteBuffer.allocate((int)len);
copy(io, src, dst, buffer, len, sp);
} else {
ByteBuffer buffer = ByteBuffer.allocate(4 * 1024 * 1024);
copy(io, src, dst, buffer, len, sp);
}
return sp;
}
private static <T extends IO.Writable.Seekable & IO.Readable.Seekable>
void copy(T io, long src, long dst, ByteBuffer buffer, long len, SynchronizationPoint<IOException> sp) {
io.readFullyAsync(src, buffer).listenInline(new Runnable() {
@Override
public void run() {
buffer.flip();
AsyncWork<Integer, IOException> write = io.writeAsync(dst, buffer);
if (len <= 4 * 1024 * 1024)
write.listenInline(sp);
else write.listenInline(new Runnable() {
@Override
public void run() {
long nl = len - 4 * 1024 * 1024;
buffer.clear();
if (nl < 4 * 1024 * 1024) buffer.limit((int)nl);
copy(io, src + 4 * 1024 * 1024, dst + 4 * 1024 * 1024, buffer, nl, sp);
}
});
}
});
}
/** Copy a file. */
@SuppressWarnings("resource")
public static AsyncWork<Long, IOException> copy(
File src, File dst, byte priority, long knownSize, WorkProgress progress, long work, ISynchronizationPoint<?> startOn
) {
AsyncWork<Long, IOException> sp = new AsyncWork<>();
Task.Cpu<Void,NoException> task = new Task.Cpu<Void,NoException>("Start copying files", priority) {
@Override
public Void run() {
FileIO.ReadOnly input = new FileIO.ReadOnly(src, priority);
FileIO.WriteOnly output = new FileIO.WriteOnly(dst, priority);
input.canStart().listenInline(new Runnable() {
@Override
public void run() {
if (input.canStart().hasError()) {
copyEnd(input, output, sp,
new IOException("Unable to open file " + src.getAbsolutePath(),
input.canStart().getError()),
null, true, 0);
return;
}
copy(input, output, knownSize, true, sp, progress, work);
}
});
return null;
}
};
if (startOn == null)
task.start();
else
task.startOn(startOn, true);
return sp;
}
/** Implement an asynchronous close using a task calling the synchronous close. */
public static ISynchronizationPoint<IOException> closeAsync(Closeable toClose) {
Task<Void,IOException> task = new Task.Cpu<Void, IOException>("Closing resource", Task.PRIORITY_RATHER_IMPORTANT) {
@Override
public Void run() throws IOException {
toClose.close();
return null;
}
};
task.start();
return task.getSynch();
}
/** Read the content of a file and return a byte array. */
@SuppressWarnings("resource")
public static AsyncWork<byte[], IOException> readFully(File file, byte priority) {
AsyncWork<byte[], IOException> result = new AsyncWork<>();
FileIO.ReadOnly f = new FileIO.ReadOnly(file, priority);
f.getSizeAsync().listenInline(new AsyncWorkListener<Long, IOException>() {
@Override
public void error(IOException error) {
try { f.close(); } catch (Throwable e) { /* ignore */ }
result.error(error);
}
@Override
public void cancelled(CancelException event) {
try { f.close(); } catch (Throwable e) { /* ignore */ }
result.cancel(event);
}
@Override
public void ready(Long size) {
byte[] buf = new byte[size.intValue()];
f.readFullyAsync(ByteBuffer.wrap(buf)).listenInline(new AsyncWorkListener<Integer, IOException>() {
@Override
public void error(IOException error) {
try { f.close(); } catch (Throwable e) { /* ignore */ }
result.error(error);
}
@Override
public void cancelled(CancelException event) {
try { f.close(); } catch (Throwable e) { /* ignore */ }
result.cancel(event);
}
@Override
public void ready(Integer read) {
if (read.intValue() != buf.length)
result.error(new IOException(
"Only " + read.intValue() + " bytes read on file size " + buf.length));
else {
try { f.close(); } catch (Throwable e) { /* ignore */ }
result.unblockSuccess(buf);
}
}
});
}
});
return result;
}
/** Get the underlying task manager by going through the wrapped IO. */
@SuppressWarnings("resource")
public static TaskManager getUnderlyingTaskManager(IO io) {
io = getUnderlyingIO(io);
return io.getTaskManager();
}
/** Get the underlying IO by going through the wrapped IO until the last one. */
public static IO getUnderlyingIO(IO io) {
do {
@SuppressWarnings("resource")
IO parent = io.getWrappedIO();
if (parent == null)
return io;
io = parent;
} while (true);
}
}
|
package org.orange.familylink;
import java.util.List;
import org.orange.familylink.alarm.AccelerometerListener;
import org.orange.familylink.alarm.AccelerometerListener.OnFallListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
*
* @author Team Orange
*/
public class StatusActivity extends ActionBarActivity {
private TextView mMainTextView;
private GraphView mStatusGraphView;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setupContentView();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//TODO
if(mAccelerometer == null)
finish();
showSensorInformation();
}
/**
* {@link ActionBar}
*/
protected void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
/**
*
* @see #setContentView(android.view.View)
*/
protected void setupContentView() {
LinearLayout mainContainer = new LinearLayout(this);
mainContainer.setOrientation(LinearLayout.VERTICAL);
setContentView(mainContainer);
mStatusGraphView = new GraphView(this);
mainContainer.addView(mStatusGraphView, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0, 6));
ScrollView scroll = new ScrollView(this);
mMainTextView = new TextView(this);
scroll.addView(mMainTextView);
mainContainer.addView(scroll, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0, 4));
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mAccelerometerListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
// mSensorManager.registerListener(mSensorEventListener, mAccelerometer, 1000000);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(mAccelerometerListener);
}
protected void showSensorInformation() {
StringBuilder sb = new StringBuilder();
sb.append("Accelerometers on Device:\n");
List<Sensor> deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
for(Sensor sensor : deviceSensors)
sb.append(sensor.getName()).append(" ")
.append(sensor.getType()).append(" ")
.append(sensor.getVendor()).append(" ")
.append(sensor.getVersion()).append(" ")
.append(sensor.getPower()).append(" ")
.append("\n\n");
sb.append("Default Accelerometer:\n")
.append(mAccelerometer.getName()).append(" ")
.append(mAccelerometer.getType()).append(" ")
.append(mAccelerometer.getVendor()).append(" ")
.append(mAccelerometer.getVersion()).append(" ")
.append(mAccelerometer.getPower()).append(" ")
.append("\n\n");
mMainTextView.setText(sb.toString());
}
protected AccelerometerListener mAccelerometerListener = new AccelerometerListener(null) {
@Override
public void onSensorChanged(SensorEvent event) {
super.onSensorChanged(event);
mStatusGraphView.update(GraphView.DataType.GRAVITY, getGravity());
mStatusGraphView.update(GraphView.DataType.LINEAR_ACCELERATION, getLinearAcceleration());
}
}.setOnFallListener(new OnFallListener() {
@Override
public void onFall(AccelerometerListener eventSource, float[] raw,
float[] gravity, float[] linearAcceleration) {
SensorEvent event = eventSource.getSensorEvent();
String info = "[" + event.timestamp+" "+event.accuracy+"] "+"\n"
+"raw :"+event.values[0]+" "+event.values[1]+" "+event.values[2]+"\n"
+"gavi:"+gravity[0]+" "+gravity[1]+" "+gravity[2]+"\n"
+"liac:"+linearAcceleration[0]+" "+linearAcceleration[1]+" "+linearAcceleration[2]+"\n\n";
mMainTextView.append(info);
}
});
/* copy from Android sample src/com.example.android.apis/os/Sensors.java */
private static class GraphView extends View {
public enum DataType{
GRAVITY,
LINEAR_ACCELERATION
}
private Bitmap mBitmap;
private Paint mPaint = new Paint();
private Canvas mCanvas = new Canvas();
private Path mPath = new Path();
private RectF mRect = new RectF();
private float mLastValues[] = new float[3*2];
private float mOrientationValues[] = new float[3];
private int mColors[] = new int[3*2];
private float mLastX;
private float mScale[] = new float[2];
private float mYOffset;
private float mMaxX;
private float mSpeed = 1.0f;
private float mWidth;
private float mHeight;
public GraphView(Context context) {
super(context);
// mColors[0] = Color.argb(192, 255, 64, 64);
// mColors[1] = Color.argb(192, 64, 128, 64);
// mColors[2] = Color.argb(192, 64, 64, 255);
// mColors[3] = Color.argb(192, 64, 255, 255);
// mColors[4] = Color.argb(192, 128, 64, 128);
// mColors[5] = Color.argb(192, 255, 255, 64);
mColors[0] = Color.rgb(64, 64, 255);
mColors[1] = mColors[0];
mColors[2] = mColors[0];
mColors[3] = Color.rgb(128, 64, 128);
mColors[4] = mColors[3];
mColors[5] = mColors[3];
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mRect.set(-0.5f, -0.5f, 0.5f, 0.5f);
mPath.arcTo(mRect, 0, 180);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
mCanvas.setBitmap(mBitmap);
mCanvas.drawColor(0xFFFFFFFF);
mYOffset = h * 0.5f;
mScale[0] = - (h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));
mScale[1] = - (h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));
mWidth = w;
mHeight = h;
if (mWidth < mHeight) {
mMaxX = w;
} else {
mMaxX = w-50;
}
mLastX = mMaxX;
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
synchronized (this) {
if (mBitmap != null) {
final Paint paint = mPaint;
final Path path = mPath;
final int outer = 0xFFC0C0C0;
final int inner = 0xFFff7010;
if (mLastX >= mMaxX) {
mLastX = 0;
final Canvas cavas = mCanvas;
final float yoffset = mYOffset;
final float maxx = mMaxX;
final float oneG = SensorManager.STANDARD_GRAVITY * mScale[0];
paint.setColor(0xFFAAAAAA);
cavas.drawColor(0xFFFFFFFF);
cavas.drawLine(0, yoffset, maxx, yoffset, paint);
cavas.drawLine(0, yoffset+oneG, maxx, yoffset+oneG, paint);
cavas.drawLine(0, yoffset-oneG, maxx, yoffset-oneG, paint);
}
canvas.drawBitmap(mBitmap, 0, 0, null);
float[] values = mOrientationValues;
if (mWidth < mHeight) {
float w0 = mWidth * 0.333333f;
float w = w0 - 32;
float x = w0*0.5f;
for (int i=0 ; i<3 ; i++) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(x, w*0.5f + 4.0f);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
paint.setColor(outer);
canvas.scale(w, w);
canvas.drawOval(mRect, paint);
canvas.restore();
canvas.scale(w-5, w-5);
paint.setColor(inner);
canvas.rotate(-values[i]);
canvas.drawPath(path, paint);
canvas.restore();
x += w0;
}
} else {
float h0 = mHeight * 0.333333f;
float h = h0 - 32;
float y = h0*0.5f;
for (int i=0 ; i<3 ; i++) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(mWidth - (h*0.5f + 4.0f), y);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
paint.setColor(outer);
canvas.scale(h, h);
canvas.drawOval(mRect, paint);
canvas.restore();
canvas.scale(h-5, h-5);
paint.setColor(inner);
canvas.rotate(-values[i]);
canvas.drawPath(path, paint);
canvas.restore();
y += h0;
}
}
}
}
}
public void update(DataType type, float[] values) {
synchronized (this) {
if(mBitmap == null)
return;
final Canvas canvas = mCanvas;
final Paint paint = mPaint;
// if (type == Sensor.TYPE_ORIENTATION) {
// for (int i=0 ; i<3 ; i++) {
// mOrientationValues[i] = values[i];
// } else {
float deltaX = mSpeed;
float newX = mLastX + deltaX;
int j = (type == DataType.GRAVITY) ? 1 : 0;
for (int i=0 ; i<3 ; i++) {
int k = i+j*3;
final float v = mYOffset + values[i] * mScale[j];
paint.setColor(mColors[k]);
canvas.drawLine(mLastX, mLastValues[k], newX, v, paint);
mLastValues[k] = v;
}
if (type == DataType.LINEAR_ACCELERATION)
mLastX += mSpeed;
invalidate();
}
}
}
}
|
package org.rocket.network.netty;
import com.github.blackrush.acara.EventBus;
import com.google.inject.Key;
import io.netty.channel.Channel;
import org.fungsi.Unit;
import org.fungsi.concurrent.Future;
import org.fungsi.concurrent.Futures;
import org.rocket.network.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
final class NettyClient implements NetworkClient {
final Channel channel;
final long id;
final EventBus eventBus;
final HashPropBag props = new HashPropBag();
NettyClient(Channel channel, long id, EventBus eventBus) {
this.channel = channel;
this.id = id;
this.eventBus = eventBus;
}
@Override
public EventBus getEventBus() {
return eventBus;
}
@Override
public Future<Unit> write(Object msg) {
channel.writeAndFlush(msg);
return Futures.unit();
}
@Override
public Future<Unit> transaction(Consumer<NetworkTransaction> fn) {
fn.accept(channel::write);
channel.flush();
return Futures.unit();
}
@Override
public Future<Unit> close() {
return RocketNetty.toFungsi(channel.close()).toUnit();
}
@Override
public <T> Prop<T> getProp(Key<?> key) {
return props.getProp(key);
}
@Override
public <T> MutProp<T> getMutProp(Key<?> key) {
return props.getMutProp(key);
}
@Override
public Stream<Key<?>> getPresentPropKeys() {
return props.getPresentPropKeys();
}
@Override
public boolean isPropPresent(Key<?> key) {
return props.isPropPresent(key);
}
@Override
public int getNrPresentProps() {
return props.getNrPresentProps();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || o.getClass() != NettyClient.class) return false;
NettyClient that = (NettyClient) o;
return id == that.id;
}
@Override
public int hashCode() {
return Long.hashCode(id);
}
@Override
public String toString() {
return "NettyClient(" +
"id=" + id + "," +
"nr-props=" + props.getNrPresentProps() +
')';
}
}
|
package com.github.simonpercic.oklog.utils;
public final class Constants {
private Constants() {
}
public static final String LOG_TAG = "OKLOG";
public static final String LOG_URL_BASE_LOCAL = "http://localhost:8080";
public static final String LOG_URL_BASE_REMOTE = "http://responseecho.herokuapp.com";
public static final String LOG_URL_ECHO_RESPONSE_PATH = "/re/";
}
|
//This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.eventd;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.DataSourceFactory;
import org.opennms.netmgt.eventd.db.AutoAction;
import org.opennms.netmgt.eventd.db.Constants;
import org.opennms.netmgt.eventd.db.OperatorAction;
import org.opennms.netmgt.eventd.db.Parameter;
import org.opennms.netmgt.eventd.db.SnmpInfo;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Header;
import org.opennms.netmgt.xml.event.Operaction;
class Persist {
// Field sizes in the events table
private static final int EVENT_UEI_FIELD_SIZE = 256;
private static final int EVENT_HOST_FIELD_SIZE = 256;
private static final int EVENT_INTERFACE_FIELD_SIZE = 16;
private static final int EVENT_DPNAME_FIELD_SIZE = 12;
private static final int EVENT_SNMPHOST_FIELD_SIZE = 256;
private static final int EVENT_SNMP_FIELD_SIZE = 256;
private static final int EVENT_DESCR_FIELD_SIZE = 4000;
private static final int EVENT_LOGGRP_FIELD_SIZE = 32;
private static final int EVENT_LOGMSG_FIELD_SIZE = 256;
private static final int EVENT_PATHOUTAGE_FIELD_SIZE = 1024;
private static final int EVENT_CORRELATION_FIELD_SIZE = 1024;
private static final int EVENT_OPERINSTRUCT_FIELD_SIZE = 1024;
private static final int EVENT_AUTOACTION_FIELD_SIZE = 256;
private static final int EVENT_OPERACTION_FIELD_SIZE = 256;
private static final int EVENT_OPERACTION_MENU_FIELD_SIZE = 64;
// private static final int EVENT_NOTIFICATION_FIELD_SIZE = 128;
private static final int EVENT_TTICKET_FIELD_SIZE = 128;
private static final int EVENT_FORWARD_FIELD_SIZE = 256;
private static final int EVENT_MOUSEOVERTEXT_FIELD_SIZE = 64;
private static final int EVENT_ACKUSER_FIELD_SIZE = 256;
private static final int EVENT_SOURCE_FIELD_SIZE = 128;
private static final int EVENT_X733_ALARMTYPE_SIZE = 31;
/**
* The character to put in if the log or display is to be set to yes
*/
private static char MSG_YES = 'Y';
/**
* The character to put in if the log or display is to be set to no
*/
private static char MSG_NO = 'N';
/**
* The database connection
*/
protected Connection m_dsConn;
/**
* SQL statement to get service id for a service name
*/
protected PreparedStatement m_getSvcIdStmt;
/**
* SQL statement to get hostname for an ip from the ipinterface table
*/
protected PreparedStatement m_getHostNameStmt;
/**
* SQL statement to get next event id from sequence
*/
protected PreparedStatement m_getNextIdStmt;
/**
* SQL statement to get insert an event into the db
*/
protected PreparedStatement m_insStmt;
protected PreparedStatement m_reductionQuery;
protected PreparedStatement m_upDateStmt;
protected PreparedStatement m_updateEventStmt;
/**
* Sets the statement up for a String value.
*
* @param stmt
* The statement to add the value to.
* @param ndx
* The ndx for the value.
* @param value
* The value to add to the statement.
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the value to the
* statement.
*/
private void set(PreparedStatement stmt, int ndx, String value) throws SQLException {
if (value == null || value.length() == 0) {
stmt.setNull(ndx, Types.VARCHAR);
} else {
stmt.setString(ndx, value);
}
}
/**
* Sets the statement up for an integer type. If the integer type is less
* than zero, then it is set to null!
*
* @param stmt
* The statement to add the value to.
* @param ndx
* The ndx for the value.
* @param value
* The value to add to the statement.
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the value to the
* statement.
*/
private void set(PreparedStatement stmt, int ndx, int value) throws SQLException {
if (value < 0) {
stmt.setNull(ndx, Types.INTEGER);
} else {
stmt.setInt(ndx, value);
}
}
/**
* Sets the statement up for a timestamp type.
*
* @param stmt
* The statement to add the value to.
* @param ndx
* The ndx for the value.
* @param value
* The value to add to the statement.
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the value to the
* statement.
*/
private void set(PreparedStatement stmt, int ndx, Timestamp value) throws SQLException {
if (value == null) {
stmt.setNull(ndx, Types.TIMESTAMP);
} else {
stmt.setTimestamp(ndx, value);
}
}
/**
* Sets the statement up for a character value.
*
* @param stmt
* The statement to add the value to.
* @param ndx
* The ndx for the value.
* @param value
* The value to add to the statement.
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the value to the
* statement.
*/
private void set(PreparedStatement stmt, int ndx, char value) throws SQLException {
stmt.setString(ndx, String.valueOf(value));
}
/**
* This method is used to convert the service name into a service id. It
* first looks up the information from a service map of Eventd and if no
* match is found, by performing a lookup in the database. If the conversion
* is successful then the corresponding integer identifier will be returned
* to the caller.
*
* @param name
* The name of the service
*
* @return The integer identifier for the service name.
*
* @exception java.sql.SQLException
* Thrown if there is an error accessing the stored data or
* the SQL text is malformed. This will also be thrown if the
* result cannot be obtained.
*
* @see EventdConstants#SQL_DB_SVCNAME_TO_SVCID
*
*/
private int getServiceID(String name) throws SQLException {
// Check the name to make sure that it is not null
if (name == null)
throw new NullPointerException("The service name was null");
// ask persistd
int id = Eventd.getServiceID(name);
if (id != -1)
return id;
// talk to the database and get the identifer
m_getSvcIdStmt.setString(1, name);
ResultSet rset = null;
try {
rset = m_getSvcIdStmt.executeQuery();
if (rset.next()) {
id = rset.getInt(1);
}
} catch (SQLException e) {
throw e;
} finally {
rset.close();
}
// inform persistd about the new find
if (id != -1)
Eventd.addServiceMapping(name, id);
// return the id to the caller
return id;
}
/**
* This method is used to convert the event host into a hostname id by
* performing a lookup in the database. If the conversion is successful then
* the corresponding hosname will be returned to the caller.
*
* @param hostip
* The event host
*
* @return The hostname
*
* @exception java.sql.SQLException
* Thrown if there is an error accessing the stored data or
* the SQL text is malformed.
*
* @see EventdConstants#SQL_DB_HOSTIP_TO_HOSTNAME
*
*/
private String getHostName(String hostip) throws SQLException {
// talk to the database and get the identifer
String hostname = hostip;
m_getHostNameStmt.setString(1, hostip);
ResultSet rset = null;
try {
rset = m_getHostNameStmt.executeQuery();
if (rset.next()) {
hostname = rset.getString(1);
}
} catch (SQLException e) {
throw e;
} finally {
rset.close();
}
// hostname can be null - if it is, return the ip
if (hostname == null)
hostname = hostip;
// return the hostname to the caller
return hostname;
}
public void insertOrUpdateAlarm(Header eventHeader, Event event) throws SQLException {
int alarmId = isReductionNeeded(eventHeader, event);
if (alarmId != -1) {
log().debug("AlarmWriter is reducing event for: " +event.getDbid()+ ": "+ event.getUei());
updateAlarm(eventHeader, event, alarmId);
/*
* This removes all previous events that have been reduced.
*/
log().debug("insertOrUpdate: auto-clean is: "+event.getAlarmData().getAutoClean());
if (event.getAlarmData().getAutoClean() == true) {
log().debug("insertOrUpdate: deleting previous events.");
cleanPreviousEvents(alarmId, event.getDbid());
}
} else {
log().debug("AlarmWriter is not reducing event for: " +event.getDbid()+ ": "+ event.getUei());
insertAlarm(eventHeader, event);
}
}
/*
* Don't throw from here, deal with any SQL exception and don't effect updating an alarm.
*/
private void cleanPreviousEvents(int alarmId, int eventId) {
PreparedStatement stmt = null;
try {
stmt = m_dsConn.prepareStatement("DELETE FROM events WHERE alarmId = ? AND eventId != ?");
stmt.setInt(1, alarmId);
stmt.setInt(2, eventId);
stmt.executeUpdate();
} catch (SQLException e) {
log().error("cleanPreviousEvents: Couldn't remove old events.", e);
}
try {
stmt.close();
} catch (SQLException e) {
log().error("cleanPreviousEvents: Couldn't close statement.", e);
}
}
private Category log() {
Category log = ThreadCategory.getInstance(AlarmWriter.class);
return log;
}
private int isReductionNeeded(Header eventHeader, Event event) throws SQLException {
if (log().isDebugEnabled()) {
log().debug("Persist.isReductionNeeded: reductionKey: "+event.getAlarmData().getReductionKey());
}
m_reductionQuery.setString(1, event.getAlarmData().getReductionKey());
ResultSet rs = null;
int alarmId;
try {
rs = m_reductionQuery.executeQuery();
alarmId = -1;
while (rs.next()) {
alarmId = rs.getInt(1);
}
} catch (SQLException e) {
throw e;
} finally {
rs.close();
}
return alarmId;
}
private void updateAlarm(Header eventHeader, Event event, int alarmId) throws SQLException {
Category log = ThreadCategory.getInstance(Persist.class);
m_upDateStmt.setInt(1, event.getDbid());
java.sql.Timestamp eventTime = getEventTime(event, log);
m_upDateStmt.setTimestamp(2, eventTime);
m_upDateStmt.setString(3, event.getAlarmData().getReductionKey());
if (log.isDebugEnabled())
log.debug("Persist.updateAlarm: reducing event: "+event.getDbid()+ "into alarm: ");
m_upDateStmt.executeUpdate();
m_updateEventStmt.setInt(1, alarmId);
m_updateEventStmt.setInt(2, event.getDbid());
m_updateEventStmt.executeUpdate();
}
/**
* Insert values into the ALARMS table
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the event to the
* database.
* @exception java.lang.NullPointerException
* Thrown if a required resource cannot be found in the
* properties file.
*/
private void insertAlarm(Header eventHeader, Event event) throws SQLException {
int alarmID = -1;
Category log = ThreadCategory.getInstance(AlarmWriter.class);
alarmID = getNextId();
if (log.isDebugEnabled()) log.debug("AlarmWriter: DBID: "+ alarmID);
//Column 1, alarmId
m_insStmt.setInt(1, alarmID);
//Column 2, eventUie
m_insStmt.setString(2, Constants.format(event.getUei(), EVENT_UEI_FIELD_SIZE));
//Column 3, dpName
m_insStmt.setString(3, (eventHeader != null) ? Constants.format(eventHeader.getDpName(), EVENT_DPNAME_FIELD_SIZE) : "undefined");
// Column 4, nodeID
int nodeid = (int) event.getNodeid();
m_insStmt.setObject(4, event.hasNodeid() ? new Integer(nodeid) : null);
// Column 5, ipaddr
m_insStmt.setString(5, event.getInterface());
//Column 6, serviceId
// convert the service name to a service id
int svcId = -1;
if (event.getService() != null) {
try {
svcId = getServiceID(event.getService());
} catch (SQLException sqlE) {
log.warn("AlarmWriter.insertAlarm: Error converting service name \"" + event.getService() + "\" to an integer identifier, storing -1", sqlE);
}
}
m_insStmt.setObject(6, (svcId == -1 ? null : new Integer(svcId)));
//Column 7, reductionKey
m_insStmt.setString(7, event.getAlarmData().getReductionKey());
//Column 8, alarmType
m_insStmt.setInt(8, event.getAlarmData().getAlarmType());
//Column 9, counter
m_insStmt.setInt(9, 1);
//Column 10, serverity
set(m_insStmt, 10, Constants.getSeverity(event.getSeverity()));
//Column 11, lastEventId
m_insStmt.setInt(11, event.getDbid());
//Column 12, firstEventTime
java.sql.Timestamp eventTime = getEventTime(event, log);
m_insStmt.setTimestamp(12, eventTime);
//Column 13, lastEventTime
m_insStmt.setTimestamp(13, eventTime);
//Column 14, description
set(m_insStmt, 14, Constants.format(event.getDescr(), EVENT_DESCR_FIELD_SIZE));
//Column 15, logMsg
if (event.getLogmsg() != null) {
// set log message
set(m_insStmt, 15, Constants.format(event.getLogmsg().getContent(), EVENT_LOGMSG_FIELD_SIZE));
} else {
m_insStmt.setNull(15, Types.VARCHAR);
}
//Column 16, operInstruct
set(m_insStmt, 16, Constants.format(event.getOperinstruct(), EVENT_OPERINSTRUCT_FIELD_SIZE));
//Column 17, tticketId
//Column 18, tticketState
if (event.getTticket() != null) {
set(m_insStmt, 17, Constants.format(event.getTticket().getContent(), EVENT_TTICKET_FIELD_SIZE));
int ttstate = 0;
if (event.getTticket().getState().equals("on"))
ttstate = 1;
set(m_insStmt, 18, ttstate);
} else {
m_insStmt.setNull(17, Types.VARCHAR);
m_insStmt.setNull(18, Types.INTEGER);
}
//Column 19, mouseOverText
set(m_insStmt, 19, Constants.format(event.getMouseovertext(), EVENT_MOUSEOVERTEXT_FIELD_SIZE));
//Column 20, suppressedUntil
set(m_insStmt, 20, eventTime);
//Column 21, suppressedUser
m_insStmt.setString(21, null);
//Column 22, suppressedTime
set(m_insStmt, 22, eventTime);
//Column 23, alarmAckUser
m_insStmt.setString(23, null);
//Column 24, alarmAckTime
m_insStmt.setTimestamp(24, null);
//Column 25, clearUie
//Column 26, x733AlarmType
//Column 27, x733ProbableCause
if (event.getAlarmData() == null) {
m_insStmt.setString(25, null);
m_insStmt.setString(26, null);
m_insStmt.setInt(27, -1);
} else {
m_insStmt.setString(25, Constants.format(event.getAlarmData().getClearUei(), EVENT_UEI_FIELD_SIZE));
m_insStmt.setString(26, Constants.format(event.getAlarmData().getX733AlarmType(), EVENT_X733_ALARMTYPE_SIZE));
set(m_insStmt, 27, event.getAlarmData().getX733ProbableCause());
}
if (log.isDebugEnabled())
log.debug("m_insStmt is: "+m_insStmt.toString());
m_insStmt.executeUpdate();
m_updateEventStmt.setInt(1, alarmID);
m_updateEventStmt.setInt(2, event.getDbid());
m_updateEventStmt.executeUpdate();
if (log.isDebugEnabled())
log.debug("SUCCESSFULLY added " + event.getUei() + " related data into the ALARMS table");
}
/**
* Insert values into the EVENTS table
*
* @exception java.sql.SQLException
* Thrown if there is an error adding the event to the
* database.
* @exception java.lang.NullPointerException
* Thrown if a required resource cannot be found in the
* properties file.
*/
protected void insertEvent(Header eventHeader, Event event) throws SQLException {
Category log = ThreadCategory.getInstance(EventWriter.class);
// events next id from sequence
// Execute the statement to get the next event id
int eventID = getNextId();
if (log.isDebugEnabled()) {
log.debug("EventWriter: DBID: " + eventID);
}
synchronized (event) {
event.setDbid(eventID);
}
// Set up the sql information now
// eventID
m_insStmt.setInt(1, eventID);
// eventUEI
m_insStmt.setString(2, Constants.format(event.getUei(), EVENT_UEI_FIELD_SIZE));
// nodeID
int nodeid = (int) event.getNodeid();
set(m_insStmt, 3, event.hasNodeid() ? nodeid : -1);
// eventTime
java.sql.Timestamp eventTime = getEventTime(event, log);
m_insStmt.setTimestamp(4, eventTime);
// Resolve the event host to a hostname using
// the ipinterface table
String hostname = getEventHost(event);
// eventHost
set(m_insStmt, 5, Constants.format(hostname, EVENT_HOST_FIELD_SIZE));
// ipAddr
set(m_insStmt, 6, Constants.format(event.getInterface(), EVENT_INTERFACE_FIELD_SIZE));
// eventDpName
m_insStmt.setString(7, (eventHeader != null) ? Constants.format(eventHeader.getDpName(), EVENT_DPNAME_FIELD_SIZE) : "undefined");
// eventSnmpHost
set(m_insStmt, 8, Constants.format(event.getSnmphost(), EVENT_SNMPHOST_FIELD_SIZE));
// convert the service name to a service id
int svcId = getEventServiceId(event, log);
// service identifier
set(m_insStmt, 9, svcId);
// eventSnmp
if (event.getSnmp() != null)
m_insStmt.setString(10, SnmpInfo.format(event.getSnmp(), EVENT_SNMP_FIELD_SIZE));
else
m_insStmt.setNull(10, Types.VARCHAR);
// eventParms
set(m_insStmt, 11, (event.getParms() != null) ? Parameter.format(event.getParms()) : null);
// grab the ifIndex out of the parms if it is defined
if (event.getIfIndex() != null) {
if (event.getParms() != null) {
Parameter.format(event.getParms());
}
}
// eventCreateTime
java.sql.Timestamp eventCreateTime = new java.sql.Timestamp((new java.util.Date()).getTime());
m_insStmt.setTimestamp(12, eventCreateTime);
// eventDescr
set(m_insStmt, 13, Constants.format(event.getDescr(), EVENT_DESCR_FIELD_SIZE));
// eventLoggroup
set(m_insStmt, 14, (event.getLoggroupCount() > 0) ? Constants.format(event.getLoggroup(), EVENT_LOGGRP_FIELD_SIZE) : null);
// eventLogMsg
// eventLog
// eventDisplay
if (event.getLogmsg() != null) {
// set log message
set(m_insStmt, 15, Constants.format(event.getLogmsg().getContent(), EVENT_LOGMSG_FIELD_SIZE));
String logdest = event.getLogmsg().getDest();
// if 'logndisplay' set both log and display
// column to yes
if (logdest.equals("logndisplay")) {
set(m_insStmt, 16, MSG_YES);
set(m_insStmt, 17, MSG_YES);
}
// if 'logonly' set log column to true
else if (logdest.equals("logonly")) {
set(m_insStmt, 16, MSG_YES);
set(m_insStmt, 17, MSG_NO);
}
// if 'displayonly' set display column to true
else if (logdest.equals("displayonly")) {
set(m_insStmt, 16, MSG_NO);
set(m_insStmt, 17, MSG_YES);
}
// if 'suppress' set both log and display to false
else if (logdest.equals("suppress")) {
set(m_insStmt, 16, MSG_NO);
set(m_insStmt, 17, MSG_NO);
}
} else {
m_insStmt.setNull(15, Types.VARCHAR);
// If this is an event that had no match in the event conf
// mark it as to be logged and displayed so that there
// are no events that slip through the system
// without the user knowing about them
set(m_insStmt, 16, MSG_YES);
set(m_insStmt, 17, MSG_YES);
}
// eventSeverity
set(m_insStmt, 18, Constants.getSeverity(event.getSeverity()));
// eventPathOutage
set(m_insStmt, 19, (event.getPathoutage() != null) ? Constants.format(event.getPathoutage(), EVENT_PATHOUTAGE_FIELD_SIZE) : null);
// eventCorrelation
set(m_insStmt, 20, (event.getCorrelation() != null) ? org.opennms.netmgt.eventd.db.Correlation.format(event.getCorrelation(), EVENT_CORRELATION_FIELD_SIZE) : null);
// eventSuppressedCount
m_insStmt.setNull(21, Types.INTEGER);
// eventOperInstruct
set(m_insStmt, 22, Constants.format(event.getOperinstruct(), EVENT_OPERINSTRUCT_FIELD_SIZE));
// eventAutoAction
set(m_insStmt, 23, (event.getAutoactionCount() > 0) ? AutoAction.format(event.getAutoaction(), EVENT_AUTOACTION_FIELD_SIZE) : null);
// eventOperAction / eventOperActionMenuText
if (event.getOperactionCount() > 0) {
List a = new ArrayList();
List b = new ArrayList();
Enumeration en = event.enumerateOperaction();
while (en.hasMoreElements()) {
Operaction eoa = (Operaction) en.nextElement();
a.add(eoa);
b.add(eoa.getMenutext());
}
set(m_insStmt, 24, OperatorAction.format(a, EVENT_OPERACTION_FIELD_SIZE));
set(m_insStmt, 25, Constants.format(b, EVENT_OPERACTION_MENU_FIELD_SIZE));
} else {
m_insStmt.setNull(24, Types.VARCHAR);
m_insStmt.setNull(25, Types.VARCHAR);
}
// eventNotification, this column no longer needed
m_insStmt.setNull(26, Types.VARCHAR);
// eventTroubleTicket / eventTroubleTicket state
if (event.getTticket() != null) {
set(m_insStmt, 27, Constants.format(event.getTticket().getContent(), EVENT_TTICKET_FIELD_SIZE));
int ttstate = 0;
if (event.getTticket().getState().equals("on"))
ttstate = 1;
set(m_insStmt, 28, ttstate);
} else {
m_insStmt.setNull(27, Types.VARCHAR);
m_insStmt.setNull(28, Types.INTEGER);
}
// eventForward
set(m_insStmt, 29, (event.getForwardCount() > 0) ? org.opennms.netmgt.eventd.db.Forward.format(event.getForward(), EVENT_FORWARD_FIELD_SIZE) : null);
// event mouseOverText
set(m_insStmt, 30, Constants.format(event.getMouseovertext(), EVENT_MOUSEOVERTEXT_FIELD_SIZE));
// eventAckUser
if (event.getAutoacknowledge() != null && event.getAutoacknowledge().getState().equals("on")) {
set(m_insStmt, 31, Constants.format(event.getAutoacknowledge().getContent(), EVENT_ACKUSER_FIELD_SIZE));
// eventAckTime - if autoacknowledge is present,
// set time to event create time
set(m_insStmt, 32, eventCreateTime);
} else {
m_insStmt.setNull(31, Types.INTEGER);
m_insStmt.setNull(32, Types.TIMESTAMP);
}
// eventSource
set(m_insStmt, 33, Constants.format(event.getSource(), EVENT_SOURCE_FIELD_SIZE));
// execute
m_insStmt.executeUpdate();
if (log.isDebugEnabled())
log.debug("SUCCESSFULLY added " + event.getUei() + " related data into the EVENTS table");
}
/**
* @param event
* @param log
* @return
*/
private int getEventServiceId(Event event, Category log) {
int svcId = -1;
if (event.getService() != null) {
try {
svcId = getServiceID(event.getService());
} catch (SQLException sqlE) {
log.warn("EventWriter.add: Error converting service name \"" + event.getService() + "\" to an integer identifier, storing -1", sqlE);
}
}
return svcId;
}
/**
* @param event
* @return
*/
private String getEventHost(Event event) {
String hostname = event.getHost();
if (hostname != null) {
try {
hostname = getHostName(hostname);
} catch (SQLException sqlE) {
// hostname can be null - so do nothing
// use the IP
hostname = event.getHost();
}
}
return hostname;
}
/**
* @param event
* @param log
* @return
*/
private java.sql.Timestamp getEventTime(Event event, Category log) {
java.sql.Timestamp eventTime = null;
try {
java.util.Date date = EventConstants.parseToDate(event.getTime());
eventTime = new java.sql.Timestamp(date.getTime());
} catch (java.text.ParseException pe) {
log.warn("Failed to convert time " + event.getTime() + " to java.sql.Timestamp, Setting current time instead", pe);
eventTime = new java.sql.Timestamp((new java.util.Date()).getTime());
}
return eventTime;
}
/**
* Constructor
* @param connectionFactory
*/
public Persist() throws SQLException {
// Get a database connection
m_dsConn = DataSourceFactory.getInstance().getConnection();
}
/**
* Close all the connection statements
*/
public void close() {
try {
m_dsConn.close();
} catch (SQLException e) {
ThreadCategory.getInstance(EventWriter.class).warn("SQLException while closing database connection", e);
}
}
private int getNextId() throws SQLException {
int id;
// Get the next id from sequence specified in
ResultSet rs = null;
try {
rs = m_getNextIdStmt.executeQuery();
rs.next();
id = rs.getInt(1);
} catch (SQLException e) {
throw e;
} finally {
rs.close();
}
rs = null;
return id;
}
}
|
package jolie;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.regex.Pattern;
import jolie.lang.Constants;
import jolie.net.CommCore;
import jolie.net.ext.CommChannelFactory;
import jolie.net.ext.CommListenerFactory;
import jolie.net.ext.CommProtocolFactory;
import jolie.runtime.AndJarDeps;
import jolie.runtime.CanUseJars;
import jolie.runtime.JavaService;
import jolie.runtime.embedding.EmbeddedServiceLoader;
import jolie.runtime.embedding.EmbeddedServiceLoaderFactory;
/**
* JolieClassLoader is used to resolve the loading of JOLIE extensions and external libraries.
* @author Fabrizio Montesi
*/
public final class JolieClassLoader extends URLClassLoader
{
private final static String EXTENSION_SPLIT_CHAR = ":";
private final Map< String, String > channelExtensionClassNames = new HashMap<>();
private final Map< String, String > listenerExtensionClassNames = new HashMap<>();
private final Map< String, String > protocolExtensionClassNames = new HashMap<>();
private final Map< String, String > embeddingExtensionClassNames = new HashMap<>();
private void init( URL[] urls )
throws IOException
{
for( URL url : urls ) {
if ( "jar".equals( url.getProtocol() ) ) {
try {
checkJarForJolieExtensions( (JarURLConnection)url.openConnection() );
} catch( IOException e ) {
throw new IOException( "Loading failed for jolie extension jar " + url.toString(), e );
}
}
}
}
/**
* Constructor
* @param urls the urls to use for the lookup of libraries
* @param parent the parent class loader to use for lookup fallback
* @throws java.io.IOException if the initialization fails,
* e.g. if a required dependency in some specified
* file can not be satisfied
*/
public JolieClassLoader( URL[] urls, ClassLoader parent )
throws IOException
{
super( urls, parent );
init( urls );
}
@Override
protected Class<?> findClass( String className )
throws ClassNotFoundException
{
final Class<?> c = super.findClass( className );
if ( JavaService.class.isAssignableFrom( c ) ) {
checkForJolieAnnotations( c );
}
return c;
}
private final static Pattern DELEGATED_PACKAGES = Pattern.compile(
"(java\\."
+ "|jolie\\.jap\\."
+ "|jolie\\.lang\\."
+ "|jolie\\.runtime\\."
+ "|jolie\\.process\\."
+ "|jolie\\.util\\."
+ ").*"
);
@Override
public Class<?> loadClass( final String className )
throws ClassNotFoundException
{
if ( DELEGATED_PACKAGES.matcher( className ).matches() ) {
return getParent().loadClass( className );
}
try {
final Class<?> c = findLoadedClass( className );
return ( c == null ) ? findClass( className ) : c;
} catch( ClassNotFoundException e ) {
return getParent().loadClass( className );
}
}
private void checkForJolieAnnotations( Class<?> c )
{
final AndJarDeps needsJars = c.getAnnotation( AndJarDeps.class );
if ( needsJars != null ) {
for( String filename : needsJars.value() ) {
/*
* TODO jar unloading when service is unloaded?
* Consider other services needing the same jars in that.
*/
try {
addJarResource( filename );
} catch( MalformedURLException e ) {
e.printStackTrace();
} catch( IOException e ) {
e.printStackTrace();
}
}
}
final CanUseJars canUseJars = c.getAnnotation( CanUseJars.class );
if ( canUseJars != null ) {
for( String filename : canUseJars.value() ) {
/*
* TODO jar unloading when service is unloaded?
* Consider other services needing the same jars in that.
*/
try {
addJarResource( filename );
} catch( MalformedURLException e ) {
} catch( IOException e ) {
}
}
}
}
private Class<?> loadExtensionClass( String className )
throws ClassNotFoundException
{
final Class<?> c = loadClass( className );
checkForJolieAnnotations( c );
return c;
}
/**
* Creates and returns an {@link EmbeddedServiceLoader}, selecting it
* from the built-in and externally loaded Jolie extensions.
* @param name
* @param interpreter
* @return
* @throws java.io.IOException
*/
public synchronized EmbeddedServiceLoaderFactory createEmbeddedServiceLoaderFactory( String name, Interpreter interpreter )
throws IOException
{
String className = embeddingExtensionClassNames.get( name );
if ( className != null ) {
try {
final Class<?> c = loadExtensionClass( className );
if ( EmbeddedServiceLoaderFactory.class.isAssignableFrom( c ) ) {
final Class< ? extends EmbeddedServiceLoaderFactory > fClass = (Class< ? extends EmbeddedServiceLoaderFactory >)c;
return fClass.getConstructor().newInstance();
}
} catch( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) {
throw new IOException( e );
}
}
return null;
}
/**
* Creates and returns a <code>CommChannelFactory</code>, selecting it
* from the built-in and externally loaded JOLIE extensions.
* @param name the identifier of the factory to create
* @param commCore the <code>CommCore</code> instance to use for constructing the factory
* @return the requested factory
* @throws java.io.IOException if the factory could not have been created
*/
public synchronized CommChannelFactory createCommChannelFactory( String name, CommCore commCore )
throws IOException
{
CommChannelFactory factory = null;
String className = channelExtensionClassNames.get( name );
if ( className != null ) {
try {
Class<?> c = loadExtensionClass( className );
if ( CommChannelFactory.class.isAssignableFrom( c ) ) {
Class< ? extends CommChannelFactory > fClass = (Class< ? extends CommChannelFactory >)c;
factory = fClass.getConstructor( CommCore.class ).newInstance( commCore );
}
} catch( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) {
throw new IOException( e );
}
}
return factory;
}
private void checkForChannelExtension( Attributes attrs )
throws IOException
{
String extension = attrs.getValue( Constants.Manifest.CHANNEL_EXTENSION );
if ( extension != null ) {
String[] pair = extension.split( EXTENSION_SPLIT_CHAR );
if ( pair.length == 2 ) {
channelExtensionClassNames.put( pair[0], pair[1] );
} else {
throw new IOException( "Invalid extension definition found in manifest file: " + extension );
}
}
}
private void checkForEmbeddingExtension( Attributes attrs )
throws IOException
{
String extension = attrs.getValue( Constants.Manifest.EMBEDDING_EXTENSION );
if ( extension != null ) {
String[] pair = extension.split( EXTENSION_SPLIT_CHAR );
if ( pair.length == 2 ) {
embeddingExtensionClassNames.put( pair[0], pair[1] );
} else {
throw new IOException( "Invalid extension definition found in manifest file: " + extension );
}
}
}
/**
* Creates and returns a <code>CommListenerFactory</code>, selecting it
* from the built-in and externally loaded JOLIE extensions.
* @param name the identifier of the factory to create
* @param commCore the <code>CommCore</code> instance to use for constructing the factory
* @return the requested factory
* @throws java.io.IOException if the factory could not have been created
*/
public synchronized CommListenerFactory createCommListenerFactory( String name, CommCore commCore )
throws IOException
{
CommListenerFactory factory = null;
String className = listenerExtensionClassNames.get( name );
if ( className != null ) {
try {
Class<?> c = loadExtensionClass( className );
if ( CommListenerFactory.class.isAssignableFrom( c ) ) {
Class< ? extends CommListenerFactory > fClass = (Class< ? extends CommListenerFactory >)c;
factory = fClass.getConstructor( CommCore.class ).newInstance( commCore );
}
} catch( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) {
throw new IOException( e );
}
}
return factory;
}
private void checkForListenerExtension( Attributes attrs )
throws IOException
{
String extension = attrs.getValue( Constants.Manifest.LISTENER_EXTENSION );
if ( extension != null ) {
String[] pair = extension.split( EXTENSION_SPLIT_CHAR );
if ( pair.length == 2 ) {
listenerExtensionClassNames.put( pair[0], pair[1] );
} else {
throw new IOException( "Invalid extension definition found in manifest file: " + extension );
}
}
}
/**
* Creates and returns a <code>CommProtocolFactory</code>, selecting it
* from the built-in and externally loaded JOLIE extensions.
* @param name the identifier of the factory to create
* @param commCore the <code>CommCore</code> instance to use for constructing the factory
* @return the requested factory
* @throws java.io.IOException if the factory could not have been created
*/
public synchronized CommProtocolFactory createCommProtocolFactory( String name, CommCore commCore )
throws IOException
{
CommProtocolFactory factory = null;
String className = protocolExtensionClassNames.get( name );
if ( className != null ) {
try {
Class<?> c = loadExtensionClass( className );
if ( CommProtocolFactory.class.isAssignableFrom( c ) ) {
Class< ? extends CommProtocolFactory > fClass = (Class< ? extends CommProtocolFactory >)c;
factory = fClass.getConstructor( CommCore.class ).newInstance( commCore );
}
} catch( ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e ) {
throw new IOException( e );
}
}
return factory;
}
private void checkForProtocolExtension( Attributes attrs )
throws IOException
{
String extension = attrs.getValue( Constants.Manifest.PROTOCOL_EXTENSION );
if ( extension != null ) {
String[] pair = extension.split( EXTENSION_SPLIT_CHAR );
if ( pair.length == 2 ) {
protocolExtensionClassNames.put( pair[0], pair[1] );
} else {
throw new IOException( "Invalid extension definition found in manifest file: " + extension );
}
}
}
private void checkJarForJolieExtensions( JarURLConnection jarConnection )
throws IOException
{
final Attributes attrs = jarConnection.getMainAttributes();
if ( attrs != null ) {
checkForChannelExtension( attrs );
checkForListenerExtension( attrs );
checkForProtocolExtension( attrs );
checkForEmbeddingExtension( attrs );
}
}
/**
* Adds a Jar file to the pool of resource to look into for extensions.
* @param jarName the Jar filename
* @throws java.net.MalformedURLException
* @throws java.io.IOException if the Jar file could not be found or if jarName does not refer to a Jar file
*/
public void addJarResource( String jarName )
throws MalformedURLException, IOException
{
URL url = findResource( jarName );
if ( url == null ) {
throw new IOException( "Resource not found: " + jarName );
}
if ( url.getProtocol().startsWith( "jap" ) ) {
addURL( new URL( url + "!/" ) );
} else {
addURL( new URL( "jap:" + url + "!/" ) );
}
}
}
|
package com.openxc.sinks;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.openxc.remote.RawMeasurement;
import android.util.Log;
/**
* Functionality to notify multiple clients asynchronously of new measurements.
*
* This class encapsulates the functionality to keep a thread-safe list of
* listeners that want to be notified of updates asyncronously. Subclasses need
* only to implement the {@link #propagateMeasurement(String, RawMeasurement)}
* to add the actual logic for looping over the list of receivers and send them
* new values.
*
* New measurments are queued up and propagated to receivers in a separate
* thread, to avoid blocking the original sender of the data.
*/
public abstract class AbstractQueuedCallbackSink extends BaseVehicleDataSink {
private final static String TAG = "AbstractQueuedCallbackSink";
private final static int MAX_QUEUE_LENGTH = 500;
private NotificationThread mNotificationThread;
private BlockingQueue<String> mNotificationQueue;
public AbstractQueuedCallbackSink() {
mNotificationQueue = new ArrayBlockingQueue<String>(MAX_QUEUE_LENGTH);
mNotificationThread = new NotificationThread();
mNotificationThread.start();
}
abstract protected void propagateMeasurement(String measurementId,
RawMeasurement measurement);
public synchronized void stop() {
if(mNotificationThread != null) {
mNotificationThread.done();
}
}
public void receive(RawMeasurement rawMeasurement)
throws DataSinkException {
super.receive(rawMeasurement);
try {
mNotificationQueue.put(rawMeasurement.getName());
} catch(InterruptedException e) {}
}
private class NotificationThread extends Thread {
private boolean mRunning = true;
private synchronized boolean isRunning() {
return mRunning;
}
public synchronized void done() {
Log.d(TAG, "Stopping notification thread");
mRunning = false;
// A context switch right can cause a race condition if we
// used take() instead of poll(): when mRunning is set to
// false and interrupt is called but we haven't called
// take() yet, so nobody is waiting. By using poll we can not be
// locked for more than 1s.
interrupt();
}
public void run() {
while(isRunning()) {
String measurementId = null;
try {
measurementId = mNotificationQueue.poll(1, TimeUnit.SECONDS);
} catch(InterruptedException e) {
Log.d(TAG, "Interrupted while waiting for a new " +
"item for notification -- likely shutting down");
return;
}
if(measurementId != null) {
RawMeasurement rawMeasurement = get(measurementId);
if(rawMeasurement != null) {
propagateMeasurement(measurementId, rawMeasurement);
}
}
}
Log.d(TAG, "Stopped measurement notifier");
}
}
}
|
package org.asup.il.data.nio;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.asup.fw.core.FrameworkCoreRuntimeException;
import org.asup.fw.core.QContext;
import org.asup.fw.core.QContextID;
import org.asup.il.core.QIntegratedLanguageCoreFactory;
import org.asup.il.core.QOverlay;
import org.asup.il.core.annotation.Overlay;
import org.asup.il.data.BinaryType;
import org.asup.il.data.DatetimeType;
import org.asup.il.data.DecimalType;
import org.asup.il.data.FloatingType;
import org.asup.il.data.QArray;
import org.asup.il.data.QArrayDef;
import org.asup.il.data.QBinary;
import org.asup.il.data.QBinaryDef;
import org.asup.il.data.QBufferedData;
import org.asup.il.data.QBufferedDataDef;
import org.asup.il.data.QCharacter;
import org.asup.il.data.QCharacterDef;
import org.asup.il.data.QCompoundDataPart;
import org.asup.il.data.QData;
import org.asup.il.data.QDataDef;
import org.asup.il.data.QDataFactory;
import org.asup.il.data.QDataStruct;
import org.asup.il.data.QDataStructDef;
import org.asup.il.data.QDataStructDelegator;
import org.asup.il.data.QDataTerm;
import org.asup.il.data.QDatetime;
import org.asup.il.data.QDatetimeDef;
import org.asup.il.data.QDecimal;
import org.asup.il.data.QDecimalDef;
import org.asup.il.data.QEnum;
import org.asup.il.data.QEnumDef;
import org.asup.il.data.QFloating;
import org.asup.il.data.QFloatingDef;
import org.asup.il.data.QHexadecimal;
import org.asup.il.data.QHexadecimalDef;
import org.asup.il.data.QIndicator;
import org.asup.il.data.QIndicatorDef;
import org.asup.il.data.QIntegratedLanguageDataFactory;
import org.asup.il.data.QIntegratedLanguageDataPackage;
import org.asup.il.data.QMultipleAtomicDataDef;
import org.asup.il.data.QMultipleAtomicDataTerm;
import org.asup.il.data.QMultipleCompoundDataDef;
import org.asup.il.data.QMultipleCompoundDataTerm;
import org.asup.il.data.QPointerDef;
import org.asup.il.data.QScroller;
import org.asup.il.data.QScrollerDef;
import org.asup.il.data.QStroller;
import org.asup.il.data.QStrollerDef;
import org.asup.il.data.QStruct;
import org.asup.il.data.QUnaryAtomicDataDef;
import org.asup.il.data.QUnaryAtomicDataTerm;
import org.asup.il.data.QUnaryCompoundDataDef;
import org.asup.il.data.QUnaryCompoundDataTerm;
import org.asup.il.data.annotation.DataType;
import org.asup.il.data.impl.DataTermImpl;
import org.asup.il.data.impl.EnumDefImpl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.osgi.framework.FrameworkUtil;
public class NIODataFactoryImpl implements QDataFactory {
private QContext context;
private QContextID contextID;
protected NIOBufferReference parent;
protected NIODataFactoryImpl(QContext context, QContextID contextID) {
this.context = context;
this.contextID = contextID;
}
protected NIODataFactoryImpl(QContext context, QContextID contextID, NIOBufferReference parent) {
this(context, contextID);
this.parent = parent;
}
@Override
public QData createData(QDataTerm<?> dataTerm) {
return createData((QDataDef<?>) dataTerm.getDefinition());
}
@SuppressWarnings("unchecked")
@Override
public <D extends QData> D createData(QDataDef<D> dataDef) {
D data = null;
// dataStroller
if(dataDef instanceof QStrollerDef<?>) {
QStrollerDef<?> strollerDef = (QStrollerDef<?>)dataDef;
Class<? extends QDataStruct> delegator = null;
if(strollerDef.getClassDelegator() != null)
delegator = (Class<? extends QDataStruct>) context.loadClass(contextID, strollerDef.getClassDelegator());
QDataStruct bufferedData = createDataStruct(delegator, strollerDef.getElements(), strollerDef.getLength());
data = (D) createStroller(bufferedData, Integer.parseInt(strollerDef.getOccurrences()));
}
// scroller
else if(dataDef instanceof QScrollerDef<?>) {
QScrollerDef<?> scrollerDef = (QScrollerDef<?>)dataDef;
QBufferedData bufferedData = (QBufferedData) createData(scrollerDef.getArgument());
data = (D) createScroller(bufferedData, Integer.parseInt(scrollerDef.getOccurrences()));
}
// array
else if (dataDef instanceof QArrayDef) {
QArrayDef<?> arrayDef = (QArrayDef<?>) dataDef;
QUnaryAtomicDataDef<QBufferedData> argument = (QUnaryAtomicDataDef<QBufferedData>) arrayDef.getArgument();
int dimension = 0;
if(arrayDef.getDimension().equalsIgnoreCase("%elem(£JAXSWK)"))
dimension = 300;
else {
dimension = Integer.parseInt(arrayDef.getDimension());
}
QBufferedData bufferedData = createArray(argument, dimension);
data = (D) bufferedData;
}
// dataStruct
else if (dataDef instanceof QDataStructDef) {
QDataStructDef dataStructDef = (QDataStructDef) dataDef;
Class<? extends QDataStruct> delegator = null;
if(dataStructDef.getClassDelegator() != null)
delegator = (Class<? extends QDataStruct>) context.loadClass(contextID, dataStructDef.getClassDelegator());
QDataStruct bufferedData = createDataStruct(delegator, dataStructDef.getElements(), dataStructDef.getLength());
data = (D) bufferedData;
}
// base
else if (dataDef instanceof QBinaryDef) {
QBinaryDef binaryType = (QBinaryDef) dataDef;
data = (D) createBinary(binaryType.getType(), binaryType.isUnsigned());
}
else if (dataDef instanceof QCharacterDef) {
QCharacterDef characterType = (QCharacterDef) dataDef;
data = (D) createCharacter(characterType.getLength(),characterType.isVarying());
}
else if (dataDef instanceof QDatetimeDef) {
QDatetimeDef datetimeType = (QDatetimeDef) dataDef;
data = (D) createDate(datetimeType.getType(), datetimeType.getFormat());
}
else if (dataDef instanceof QDecimalDef) {
QDecimalDef decimalType = (QDecimalDef) dataDef;
data = (D) createDecimal(decimalType.getPrecision(),decimalType.getScale(), decimalType.getType());
}
else if(dataDef instanceof QEnumDef<?, ?>) {
data = (D) _createData(dataDef);
}
else if (dataDef instanceof QFloatingDef) {
QFloatingDef floatingType = (QFloatingDef) dataDef;
data = (D) createFloating(floatingType.getType());
}
else if (dataDef instanceof QHexadecimalDef) {
QHexadecimalDef hexadecimalDef = (QHexadecimalDef)dataDef;
data = (D) createHexadecimal(hexadecimalDef.getLength());
}
else if (dataDef instanceof QIndicatorDef) {
data = (D) createIndicator();
}
else if(dataDef instanceof QPointerDef) {
// QPointerDef pointerDef = (QPointerDef)dataDef;
data = (D) createPointer();
}
else {
// TODO external dataDef
throw new FrameworkCoreRuntimeException("Unknown dataType: "+ dataDef);
}
return data;
}
@SuppressWarnings("unchecked")
private <E extends Enum<E>, BD extends QBufferedData, D extends QData> D _createData(QDataDef<D> dataDef) {
QEnumDef<E, BD> enumDef = (QEnumDef<E, BD>)dataDef;
return (D) createEnum(enumDef.getKlass(), createData(enumDef.getDelegate()));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public QDataDef<?> createDataDef(Type type, List<Annotation> annotations) {
// annotations
if (annotations == null)
annotations = new ArrayList<Annotation>();
// arguments
List<Type> arguments = new ArrayList<Type>();
// complete
Class<? extends QData> klass = completeMetadata(type, arguments, annotations);
QDataDef<?> dataDef = null;
// dataStructureDelegator
if (QDataStructDelegator.class.isAssignableFrom(klass)) {
QDataStructDef dataStructDef = QIntegratedLanguageDataFactory.eINSTANCE.createDataStructDef();
// delegator
String address = getAddress(klass);
dataStructDef.setClassDelegator(address);
completeStructPart(dataStructDef, klass);
dataDef = dataStructDef;
}
// array
else if (QArray.class.isAssignableFrom(klass)) {
QArrayDef<?> arrayDef = QIntegratedLanguageDataFactory.eINSTANCE.createArrayDef();
// argument
QUnaryAtomicDataDef<?> argument = (QUnaryAtomicDataDef<?>) createDataDef(arguments.get(0), annotations);
arrayDef.setArgument(argument);
dataDef = arrayDef;
}
// stroller
else if(QStroller.class.isAssignableFrom(klass)) {
QStrollerDef<?> strollerDef = QIntegratedLanguageDataFactory.eINSTANCE.createStrollerDef();
// argument
QUnaryCompoundDataDef<?> argument = (QUnaryCompoundDataDef<?>) createDataDef(arguments.get(0), annotations);
strollerDef.setClassDelegator(argument.getClassDelegator());
strollerDef.setPrefix(argument.getPrefix());
strollerDef.setQualified(argument.isQualified());
strollerDef.getElements().addAll(argument.getElements());
dataDef = strollerDef;
}
// scroller
else if(QScroller.class.isAssignableFrom(klass)) {
QScrollerDef<?> scrollerDef = QIntegratedLanguageDataFactory.eINSTANCE.createScrollerDef();
// argument
QUnaryAtomicDataDef<?> argument = (QUnaryAtomicDataDef<?>) createDataDef(arguments.get(0), annotations);
scrollerDef.setArgument(argument);
dataDef = scrollerDef;
}
// enum
else if(QEnum.class.isAssignableFrom(klass)) {
class MyDef<E extends Enum<E>> extends EnumDefImpl<E, QBufferedData> {
private static final long serialVersionUID = 1L;
public MyDef(Class<E> klass, List<Annotation> annotations, Class<?> delegate) {
setDelegate((QBufferedDataDef<QBufferedData>) createDataDef(delegate, annotations));
setKlass(klass);
}
@Override
public Class<?> getJavaClass() {
return getKlass();
}
@Override
public Class<?> getDataClass() {
return QEnum.class;
}
}
dataDef = new MyDef((Class<?>) arguments.get(0), annotations, (Class<?>)arguments.get(1));
}
// other
else {
// EMF reflection
EClassifier eClassifier = QIntegratedLanguageDataPackage.eINSTANCE.getEClassifier(klass.getSimpleName().substring(1) + "Def");
if (eClassifier != null)
dataDef = (QDataDef<?>) QIntegratedLanguageDataFactory.eINSTANCE.create((EClass) eClassifier);
}
if (dataDef == null)
throw new FrameworkCoreRuntimeException("Unknown class: " + klass);
injectAnnotations(annotations, dataDef);
return dataDef;
}
private void completeStructPart(QCompoundDataPart structPart, Class<? extends QData> klass) {
// fields introspection
for (Field field : klass.getFields()) {
// annotations field
List<Annotation> annotationsField = new ArrayList<Annotation>();
for (Annotation annotation : field.getAnnotations()) {
annotationsField.add(annotation);
}
QDataDef<?> elementDef = createDataDef(field.getGenericType(), annotationsField);
QDataTerm<?> elementTerm = createDataTermByDef(elementDef);
elementTerm.setName(field.getName());
structPart.getElements().add(elementTerm);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private <DD extends QDataDef<?>> QDataTerm<DD> createDataTermByDef(DD elementDef) {
QDataTerm<DD> elementTerm = null;
if (elementDef instanceof QMultipleCompoundDataDef) {
QMultipleCompoundDataTerm<?> multipleCompoundDataTerm = QIntegratedLanguageDataFactory.eINSTANCE.createMultipleCompoundDataTerm();
elementTerm = (QDataTerm<DD>) multipleCompoundDataTerm;
}
else if(elementDef instanceof QMultipleAtomicDataDef) {
QMultipleAtomicDataTerm<?> multipleAtomicDataTerm = QIntegratedLanguageDataFactory.eINSTANCE.createMultipleAtomicDataTerm();
elementTerm = (QDataTerm<DD>) multipleAtomicDataTerm;
}
else if(elementDef instanceof QUnaryCompoundDataDef) {
QUnaryCompoundDataTerm<?> unaryCompoundDataTerm = QIntegratedLanguageDataFactory.eINSTANCE.createUnaryCompoundDataTerm();
elementTerm = (QDataTerm<DD>) unaryCompoundDataTerm;
}
else if(elementDef instanceof QUnaryAtomicDataDef) {
QUnaryAtomicDataTerm<?> unaryAtomicDataTerm = QIntegratedLanguageDataFactory.eINSTANCE.createUnaryAtomicDataTerm();
elementTerm = (QDataTerm<DD>) unaryAtomicDataTerm;
}
else if(elementDef instanceof QEnumDef) {
class MyTerm<ED extends QEnumDef<?, ?>> extends DataTermImpl<ED> {
private static final long serialVersionUID = 1L;
}
elementTerm = new MyTerm();
}
else {
throw new RuntimeException("Unknown dataDef: "+elementDef);
}
elementTerm.setDefinition(elementDef);
return elementTerm;
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <D extends QBufferedData> QArray<D> createArray(QUnaryAtomicDataDef<D> argument, int dimension) {
boolean initialize = (parent == null ? true : false);
D[] elements = (D[]) new QBufferedData[dimension];
NIOArrayImpl<D> array = null;
NIODataFactoryImpl arrayDataFactory = this;
if(initialize) {
ByteBuffer buffer = ByteBuffer.allocate(((QBufferedDataDef<D>)argument).getLength()*dimension);
array = new NIOArrayImpl(elements, buffer);
arrayDataFactory = new NIODataFactoryImpl(context, contextID, array);
}
else {
array = new NIOArrayImpl(elements, parent.getBuffer());
}
int position = 1;
for(int i=1; i<=dimension; i++) {
elements[i-1] = arrayDataFactory.createData(argument);
array.slice(elements[i-1], position);
position = position+elements[i-1].length();
}
return array;
}
@SuppressWarnings({ "unchecked"})
@Override
public <D extends QDataStruct> D createDataStruct(Class<D> classDelegator, List<QDataTerm<?>> dataTerms, int length) {
boolean initialize = (parent == null ? true : false);
// data structure
D dataStructure = null;
if(classDelegator != null) {
try {
dataStructure = (D) classDelegator.newInstance();
NIODataStructureWrapperImpl dataStructureDelegate = new NIODataStructureWrapperImpl(length, (QDataStructDelegator) dataStructure, false);
QDataFactory dataStructureFactory = this;
if (initialize)
dataStructureFactory = new NIODataFactoryImpl(context, contextID, (NIOBufferReference) dataStructureDelegate);
else
throw new RuntimeException("Unexpcted condition p4jo8765sfd087thtwmuj90");
// fields introspection
List<QBufferedData> fields = new ArrayList<>();
for (Field field : classDelegator.getFields()) {
// annotations field
List<Annotation> annotationsField = new ArrayList<Annotation>();
for (Annotation annotation : field.getAnnotations()) {
annotationsField.add(annotation);
}
// build
Type type = field.getGenericType();
QDataDef<QBufferedData> dataDef = (QDataDef<QBufferedData>) dataStructureFactory.createDataDef(type, annotationsField);
QBufferedData dataElement = dataStructureFactory.createData(dataDef);
dataStructureDelegate.addElement(field.getName(), dataElement);
fields.add(dataElement);
}
// slice
if (initialize) {
dataStructureDelegate.init();
initializeElements(dataStructureDelegate, fields);
}
((QDataStructDelegator)dataStructure).setDelegate(dataStructureDelegate);
} catch (InstantiationException | IllegalAccessException | SecurityException e) {
e.printStackTrace();
return null;
}
}
else {
NIODataStructureImpl dataStructureDelegate = new NIODataStructureImpl(length, new LinkedHashMap<String, QBufferedData>(), false);
// build
QDataFactory dataStructureFactory = new NIODataFactoryImpl(context, contextID, (NIOBufferReference) dataStructureDelegate);
for (QDataTerm<?> dataTerm : dataTerms) {
QBufferedData element = dataStructureFactory.createData((QDataDef<D>) dataTerm.getDefinition());
dataStructureDelegate.addElement(dataTerm.getName(), element);
}
// slice
if (initialize) {
dataStructureDelegate.init();
initializeTerms(dataStructureDelegate, dataTerms);
}
dataStructure = (D) dataStructureDelegate;
}
return dataStructure;
}
@Override
public <E extends Enum<E>, D extends QBufferedData> QEnum<E, D> createEnum(Class<E> classEnumerator, D dataDelegate) {
return new NIOEnumImpl<E, D>(classEnumerator, dataDelegate);
}
@Override
public QCharacter createCharacter(int length, boolean varying) {
boolean initialize = (parent == null ? true : false);
QCharacter character = null;
if (varying)
character = new NIOCharacterVaryingImpl(length, null, initialize);
else
character = new NIOCharacterImpl(length, null, initialize);
return character;
}
private void initializeTerms(QDataStruct dataStructure, List<QDataTerm<?>> terms) {
int p = 1;
int i = 1;
for (QDataTerm<?> element : terms) {
QOverlay overlay = element.getFacet(QOverlay.class);
String position = null;
if (overlay != null)
position = overlay.getPosition();
if (position != null) {
if (position.equals("*NEXT")) {
} else {
p = Integer.parseInt(position);
}
}
QBufferedData data = dataStructure.getElement(i);
if (data instanceof NIOBufferReference)
((NIOBufferReference) dataStructure).slice(data, p);
else if (data instanceof NIOBufferDelegator)
((NIOBufferReference) dataStructure).slice(((NIOBufferDelegator)data).getDelegate(), p);
else
throw new FrameworkCoreRuntimeException("Error 92d74c234n");
p += data.size();
i++;
}
}
private void initializeElements(QDataStruct dataStructure, List<QBufferedData> elements) {
int p = 1;
for (QBufferedData data : elements) {
if (data instanceof NIOBufferReference)
((NIOBufferReference) dataStructure).slice(data, p);
else if (data instanceof NIOBufferDelegator)
((NIOBufferReference) dataStructure).slice(((NIOBufferDelegator)data).getDelegate(), p);
else
throw new FrameworkCoreRuntimeException("Error 92d7fd7834n");
if(data instanceof NIOArrayImpl) {
NIOArrayImpl<?> nioArray = (NIOArrayImpl<?>)data;
int position = 1;
for(int i=1; i<=nioArray.capacity(); i++) {
QBufferedData arrayElement = nioArray.get(i);
nioArray.slice(arrayElement, position);
position = position+arrayElement.length();
}
}
p += data.size();
}
}
@Override
public QBinary createBinary(BinaryType type, boolean unsigned) {
boolean initialize = (parent == null ? true : false);
QBinary binary = null;
switch (type) {
case BYTE:
binary = new NIOBinaryImpl(1, null, initialize);
break;
case SHORT:
binary = new NIOBinaryImpl(3, null, initialize);
break;
case INTEGER:
binary = new NIOBinaryImpl(5, null, initialize);
break;
case LONG:
binary = new NIOBinaryImpl(10, null, initialize);
break;
default:
throw new FrameworkCoreRuntimeException("Unknown data type " + type);
}
return binary;
}
@Override
public QCharacter createCharacter(int length) {
return createCharacter(length, false);
}
@Override
public QDecimal createDecimal(int precision) {
return createDecimal(precision, 0);
}
@Override
public QDecimal createDecimal(int precision, int scale) {
return createDecimal(precision, scale, DecimalType.ZONED);
}
@Override
public QDecimal createDecimal(int precision, int scale, DecimalType type) {
boolean initialize = (parent == null ? true : false);
QDecimal decimal = null;
switch (type) {
case ZONED:
decimal = new NIODecimalImpl(precision, scale, null, initialize);
break;
case PACKED:
break;
}
return decimal;
}
@Override
public QIndicator createIndicator() {
return new NIOIndicatorImpl(true);
}
@SuppressWarnings("unchecked")
private Class<? extends QData> completeMetadata(Type type, List<Type> arguments, List<Annotation> annotations) {
// klass
Class<? extends QData> klass = null;
if(type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)type;
klass = (Class<? extends QData>) pType.getRawType();
for(Type argument: pType.getActualTypeArguments())
arguments.add(argument);
}
else
klass = (Class<? extends QData>) type;
// append class annotation
for (Annotation annotation : klass.getAnnotations()) {
// dataType filter
if (!annotation.annotationType().isAnnotationPresent(DataType.class))
continue;
annotations.add(annotation);
}
return klass;
}
private void injectAnnotations(List<Annotation> annotations, Object target) {
EObject eObject = (EObject) target;
EClass eClass = eObject.eClass();
// merge annotations by reflection
for (Annotation annotation : annotations) {
for (Method method : annotation.getClass().getDeclaredMethods()) {
// EMF reflection
// TODO Java reflection
EStructuralFeature eFeature = null;
// if default field (value) use annotation name
// if (method.getName().equals("value"))
// eFeature = eClass.getEStructuralFeature(annotation.annotationType().getSimpleName().toLowerCase());
// else
eFeature = eClass.getEStructuralFeature(method.getName());
if(eFeature == null) {
if(eClass.getName().replaceAll("Def", "").equalsIgnoreCase(method.getName().replace("Type", ""))) {
eFeature = eClass.getEStructuralFeature("type");
}
else if(eClass.getName().replaceAll("Def", "").equalsIgnoreCase(method.getName().replace("Format", ""))) {
eFeature = eClass.getEStructuralFeature("format");
}
}
if (eFeature != null) {
try {
Object object = method.invoke(annotation, new Object[] {});
if(object instanceof Overlay) {
Overlay overlay = (Overlay)object;
QOverlay qOverlay = QIntegratedLanguageCoreFactory.eINSTANCE.createOverlay();
qOverlay.setName(overlay.name());
qOverlay.setPosition(overlay.position());
object = qOverlay;
}
if(!(object instanceof Class<?>)) {
eObject.eSet(eFeature, object);
}
} catch (Exception e) {
throw new FrameworkCoreRuntimeException(e);
}
}
}
}
}
@Override
public <D extends QStruct> QStroller<D> createStroller(D dataDelegate, int occurrences) {
return new NIOStrollerImpl<D>(dataDelegate, occurrences, true);
}
@Override
public QDatetime createDate(DatetimeType type, String format) {
boolean initialize = (parent == null ? true : false);
NIODatetimeImpl datetime = new NIODatetimeImpl(type, format, null, initialize);
return datetime;
}
@Override
public QFloating createFloating(FloatingType type) {
// TODO Auto-generated method stub
return null;
}
@Override
public QHexadecimal createHexadecimal(int length) {
boolean initialize = (parent == null ? true : false);
return new NIOHexadecimalImpl(length, null, initialize);
}
@Override
public QHexadecimal createPointer() {
// TODO Auto-generated method stub
return null;
}
@Override
public <D extends QBufferedData> QScroller<D> createScroller(D dataDelegate, int occurrences) {
return new NIOScrollerImpl<D>(dataDelegate, occurrences, true);
}
@Override
public QDatetime createTime() {
// TODO Auto-generated method stub
return null;
}
@Override
public QDatetime createTimestamp() {
// TODO Auto-generated method stub
return null;
}
private String getAddress(Class<?> klass) {
String address = "asup:/omac/"+FrameworkUtil.getBundle(klass).getSymbolicName() + "/" + klass.getName();
return address;
}
}
|
package org.basex.tests.w3c;
import static org.basex.tests.w3c.QT3Constants.*;
import static org.basex.util.Prop.*;
import static org.basex.util.Token.*;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.*;
import javax.xml.namespace.*;
import org.basex.core.*;
import org.basex.io.*;
import org.basex.io.out.*;
import org.basex.io.serial.*;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.func.fn.DeepEqual.Mode;
import org.basex.query.value.item.*;
import org.basex.query.value.type.*;
import org.basex.tests.bxapi.*;
import org.basex.tests.bxapi.xdm.*;
import org.basex.util.*;
import org.basex.util.options.Options.YesNo;
public final class QT3TS extends Main {
/** EQName pattern. */
private static final Pattern BIND = Pattern.compile("^Q\\{(.*?)\\}(.+)$");
/** Path to the test suite (ignored if {@code null}). */
private String basePath;
/** Maximum length of result output. */
private int maxout = 2000;
/** Correct results. */
private final TokenBuilder right = new TokenBuilder();
/** Wrong results. */
private final TokenBuilder wrong = new TokenBuilder();
/** Ignored tests. */
private final TokenBuilder ignore = new TokenBuilder();
/** Report builder. */
private QT3TSReport report;
/** Number of total queries. */
private int total;
/** Number of tested queries. */
private int tested;
/** Number of correct queries. */
private int correct;
/** Number of ignored queries. */
private int ignored;
/** Current base uri. */
private String baseURI;
/** Current base directory. */
private String baseDir;
/** Slow queries flag. */
private TreeMap<Long, String> slow;
/** Query filter string. */
private String single = "";
/** Verbose flag. */
private boolean verbose;
/** Error code flag. */
private boolean errors = true;
/** Also print ignored files. */
private boolean ignoring;
/** All flag. */
private boolean all;
/** Database context. */
final Context ctx = new Context();
/** Global environments. */
private final ArrayList<QT3Env> genvs = new ArrayList<>();
/**
* Main method of the test class.
* @param args command-line arguments
* @throws Exception exception
*/
public static void main(final String... args) throws Exception {
try {
new QT3TS(args).run();
} catch(final IOException ex) {
Util.errln(ex);
System.exit(1);
}
}
/**
* Constructor.
* @param args command-line arguments
*/
QT3TS(final String[] args) {
super(args);
}
/**
* Runs all tests.
* @throws Exception exception
*/
private void run() throws Exception {
final IOFile sandbox = new IOFile(TEMPDIR, "tests");
ctx.soptions.set(StaticOptions.DBPATH, sandbox + "/data");
parseArgs();
final Performance perf = new Performance();
final SerializerOptions sopts = new SerializerOptions();
sopts.set(SerializerOptions.METHOD, SerialMethod.XML);
sopts.set(SerializerOptions.OMIT_XML_DECLARATION, YesNo.NO);
ctx.options.set(MainOptions.SERIALIZER, sopts);
final XdmValue doc = new XQuery("doc('" + file(false, CATALOG) + "')", ctx).value();
final String version = asString("*:catalog/@version", doc);
Util.outln(NL + "QT Test Suite " + version);
Util.outln("Test directory: " + file(false, "."));
Util.out("Parsing queries");
/**
* Runs a single test set.
* @param name name of test set
* @throws Exception exception
*/
private void testSet(final String name) throws Exception {
final XdmValue doc = new XQuery("doc(' " + file(false, name) + "')", ctx).value();
final XdmValue set = new XQuery("*:test-set", ctx).context(doc).value();
final IO base = IO.get(doc.getBaseURI());
baseURI = base.path();
baseDir = base.dir();
if(supported(set)) {
// parse environment of test-set
final ArrayList<QT3Env> envs = new ArrayList<>();
for(final XdmItem ienv : new XQuery("*:environment", ctx).context(set))
envs.add(new QT3Env(ctx, ienv));
if(report != null) report.addSet(asString("@name", set));
// run all test cases
for(final XdmItem its : new XQuery("*:test-case", ctx).context(set)) {
try {
testCase(its, envs);
} catch(final IOException ex) {
Util.debug(ex);
}
}
}
}
/**
* Runs a single test case.
* @param test node
* @param envs environments
* @throws Exception exception
*/
private void testCase(final XdmItem test, final ArrayList<QT3Env> envs) throws Exception {
if(total++ % 500 == 0) Util.out(".");
if(!supported(test)) {
if(ignoring) ignore.add(asString("@name", test)).add(NL);
ignored++;
return;
}
// skip queries that do not match filter
final String name = asString("@name", test);
if(!name.startsWith(single)) {
if(ignoring) ignore.add(name).add(NL);
ignored++;
return;
}
tested++;
// expected result
/**
* Assigns the query environment.
* @param query query
* @param env environment
* @return query;
*/
private XQuery environment(final XQuery query, final QT3Env env) {
if(env != null) {
// bind namespaces
for(final HashMap<String, String> ns : env.namespaces) {
query.namespace(ns.get(PREFIX), ns.get(URI));
}
// bind variables
for(final HashMap<String, String> par : env.params) {
query.variable(par.get(NNAME), new XQuery(par.get(SELECT), ctx).value());
}
}
return query;
}
/**
* Normalizes special characters in the specified string.
* @param in input string
* @return result
*/
private String normSpecial(final String in) {
return in.replaceAll("^<\\?xml.*?>\r?\n?", "").replace("\n", "%0A").replace("\r", "%0D").
replace("\t", "%09");
}
/** Flags for dependencies that are not supported. */
private static final String NOSUPPORT =
"('schema-location-hint', 'schemaImport', 'schemaValidation', " +
"'staticTyping', 'typedData', 'XQUpdate')";
/**
* Checks if the current test case is supported.
* @param test test case
* @return result of check
*/
private boolean supported(final XdmValue test) {
// the following query generates a result if the specified test is not supported
return all || new XQuery(
/**
* Returns the specified environment, or {@code null}.
* @param envs environments
* @param ref reference
* @return environment
*/
private static QT3Env envs(final ArrayList<QT3Env> envs, final String ref) {
for(final QT3Env env : envs) {
if(env.name.equals(ref)) return env;
}
return null;
}
/**
* Tests the result of a test case.
* @param result query result
* @param expected expected result
* @return {@code null} if test was successful; otherwise, expected test suite result
*/
private String test(final QT3Result result, final XdmValue expected) {
final String type = expected.getName().getLocalPart();
try {
final String msg;
if(type.equals("error")) {
msg = assertError(result, expected);
} else if(type.equals("assert-serialization-error")) {
msg = assertSerializationError(result, expected);
} else if(type.equals("all-of")) {
msg = allOf(result, expected);
} else if(type.equals("not")) {
msg = not(result, expected);
} else if(type.equals("any-of")) {
msg = anyOf(result, expected);
} else if(result.value != null) {
switch(type) {
case "assert":
msg = assertQuery(result, expected);
break;
case "assert-count":
msg = assertCount(result, expected);
break;
case "assert-deep-eq":
msg = assertDeepEq(result, expected);
break;
case "assert-empty":
msg = assertEmpty(result);
break;
case "assert-eq":
msg = assertEq(result, expected);
break;
case "assert-false":
msg = assertBoolean(result, false);
break;
case "assert-permutation":
msg = assertPermutation(result, expected);
break;
case "assert-xml":
msg = assertXML(result, expected);
break;
case "serialization-matches":
msg = serializationMatches(result, expected);
break;
case "assert-string-value":
msg = assertStringValue(result, expected);
break;
case "assert-true":
msg = assertBoolean(result, true);
break;
case "assert-type":
msg = assertType(result, expected);
break;
default:
msg = "Test type not supported: " + type;
break;
}
} else {
msg = expected.toString();
}
return msg;
} catch(final Exception ex) {
Util.stack(ex);
return "Exception: " + ex.getMessage();
}
}
/**
* Tests error.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertError(final QT3Result result, final XdmValue expected) {
final String exp = asString('@' + CODE, expected);
if(result.xqerror == null) return exp;
if(!errors || exp.equals("*")) return null;
final QNm resErr = result.xqerror.getException().qname();
String name = exp, uri = string(QueryText.ERROR_URI);
final Matcher m = BIND.matcher(exp);
if(m.find()) {
uri = m.group(1);
name = m.group(2);
}
final QNm expErr = new QNm(name, uri);
return expErr.eq(resErr) ? null : exp;
}
/**
* Tests not.
* @param result query result
* @param exp expected result
* @return optional expected test suite result
*/
private String not(final QT3Result result, final XdmValue exp) {
final TokenBuilder tb = new TokenBuilder();
for(final XdmItem item : environment(new XQuery("*", ctx), result.env).context(exp)) {
final String msg = test(result, item);
if(msg != null) tb.add(tb.isEmpty() ? "" : ", ").add(msg);
}
return tb.isEmpty() ? "not(...)" : null;
}
/**
* Tests all-of.
* @param result query result
* @param exp expected result
* @return optional expected test suite result
*/
private String allOf(final QT3Result result, final XdmValue exp) {
final TokenBuilder tb = new TokenBuilder();
for(final XdmItem item : environment(new XQuery("*", ctx), result.env).context(exp)) {
final String msg = test(result, item);
if(msg != null) tb.add(tb.isEmpty() ? "" : ", ").add(msg);
}
return tb.isEmpty() ? null : tb.toString();
}
/**
* Tests any-of.
* @param result query result
* @param exp expected result
* @return optional expected test suite result
*/
private String anyOf(final QT3Result result, final XdmValue exp) {
final TokenBuilder tb = new TokenBuilder();
for(final XdmItem item : environment(new XQuery("*", ctx), result.env).context(exp)) {
final String msg = test(result, item);
if(msg == null) return null;
tb.add(tb.isEmpty() ? "" : ", ").add(msg);
}
return "any of { " + tb + " }";
}
/**
* Tests assertion.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertQuery(final QT3Result result, final XdmValue expected) {
final String exp = expected.getString();
try {
final String query = "declare variable $result external; " + exp;
return environment(new XQuery(query, ctx), result.env).variable("$result", result.value).
value().getBoolean() ? null : exp;
} catch(final XQueryException ex) {
// should not occur
return ex.getException().getMessage();
}
}
/**
* Tests count.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private static String assertCount(final QT3Result result, final XdmValue expected) {
final long exp = expected.getInteger();
final int res = result.value.size();
return exp == res ? null : Util.info("% items (% found)", exp, res);
}
/**
* Tests equality.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertEq(final QT3Result result, final XdmValue expected) {
final String exp = expected.getString();
try {
final String query = "declare variable $returned external; $returned eq " + exp;
return environment(new XQuery(query, ctx), result.env).variable("$returned", result.value).
value().getBoolean() ? null : exp;
} catch(final XQueryException err) {
// numeric overflow: try simple string comparison
return err.getCode().equals("FOAR0002") && exp.equals(result.value.getString()) ?
null : err.getException().getMessage();
}
}
/**
* Tests deep equals.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertDeepEq(final QT3Result result, final XdmValue expected) {
final XdmValue exp = environment(new XQuery(expected.getString(), ctx), result.env).value();
return exp.deepEqual(result.value) ? null : exp.toString();
}
/**
* Tests permutation.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertPermutation(final QT3Result result, final XdmValue expected) {
// cache expected results
final HashSet<String> exp = new HashSet<>();
for(final XdmItem item : environment(new XQuery(expected.getString(), ctx), result.env))
exp.add(item.getString());
// cache actual results
final HashSet<String> res = new HashSet<>();
for(final XdmItem item : result.value) res.add(item.getString());
if(exp.size() != res.size())
return Util.info("% results (found: %)", exp.size(), res.size());
for(final String s : exp.toArray(String[]::new)) {
if(!res.contains(s)) return Util.info("% (missing)", s);
}
for(final String s : res.toArray(String[]::new)) {
if(!exp.contains(s))
return Util.info("% (missing in expected result)", s);
}
return null;
}
/**
* Tests the serialized result.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertXML(final QT3Result result, final XdmValue expected) {
final String file = asString("@file", expected);
final boolean norm = asBoolean("@normalize-space=('true','1')", expected);
final boolean pref = asBoolean("@ignore-prefixes=('true','1')", expected);
String exp = expected.getString();
try {
if(!file.isEmpty()) exp = string(new IOFile(baseDir, file).read());
exp = normNL(exp);
if(norm) exp = string(normalize(token(exp)));
final XdmValue returned = result.value;
final String res = normNL(
asString("serialize(., map{ 'indent':'no','method':'xml' })", returned));
if(exp.equals(res)) return null;
final String r = normNL(asString(
"serialize(., map{ 'indent':'no','method':'xml','omit-xml-declaration':'no' })",
returned));
if(exp.equals(r)) return null;
// include check for comments, processing instructions and namespaces
final StringBuilder flags = new StringBuilder("'").append(Mode.ALLNODES).append('\'');
if(!pref) flags.append(",'").append(Mode.NAMESPACES).append('\'');
final String query = Function._UTIL_DEEP_EQUAL.args(" <X>" + exp + "</X>",
" <X>" + res + "</X>" , " (" + flags.append(")").toString());
return asBoolean(query, expected) ? null : exp;
} catch(final IOException ex) {
return Util.info("% (found: %)", exp, ex);
}
}
/**
* Tests the serialized result.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String serializationMatches(final QT3Result result, final XdmValue expected) {
try {
final String flags = asString("@flags", expected);
final XdmValue returned = XdmValue.get(Str.get(serialize(result)));
final String query = "declare variable $returned external;"
+ "declare variable $expected external;"
+ "matches($returned, string($expected), '" + flags + "')";
return environment(new XQuery(query, ctx), result.env).variable("returned", returned).
variable("expected", expected).value().getBoolean() ? null : expected.getString();
} catch(final Exception err) {
return Util.info("% (found: %)", expected.getString(), err);
}
}
/**
* Tests a serialization error.
* @param result returned result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertSerializationError(final QT3Result result, final XdmValue expected) {
final String expCode = asString('@' + CODE, expected);
if(result.xqerror != null) {
if(!errors || expCode.equals("*")) return null;
final String resCode = string(result.xqerror.getException().qname().local());
if(resCode.equals(expCode)) return null;
}
try {
if(result.value != null) serialize(result);
return expCode;
} catch(final QueryException ex) {
if(!errors || expCode.equals("*")) return null;
final String resCode = string(ex.qname().local());
if(resCode.equals(expCode)) return null;
return Util.info("% (found: %)", expCode, ex);
} catch(final IOException ex) {
return Util.info("% (found: %)", expCode, ex);
}
}
/**
* Serializes values.
* @param result query result
* @return optional expected test suite result
* @throws QueryException query exception
* @throws IOException I/O exception
*/
private static String serialize(final QT3Result result) throws QueryException, IOException {
try {
final ArrayOutput ao = new ArrayOutput();
try(Serializer ser = result.query.qp().serializer(ao)) {
for(final Item item : result.value.internal()) ser.serialize(item);
}
return ao.toString();
} catch(final QueryIOException ex) {
throw ex.getCause();
}
}
/**
* Tests string value.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertStringValue(final QT3Result result, final XdmValue expected) {
String exp = expected.getString();
// normalize space
final boolean norm = asBoolean("@normalize-space=('true','1')", expected);
if(norm) exp = string(normalize(token(exp)));
final TokenBuilder tb = new TokenBuilder();
int c = 0;
for(final XdmItem item : result.value) {
if(c++ != 0) tb.add(' ');
tb.add(item.getString());
}
final String res = norm ? string(normalize(tb.finish())) : tb.toString();
return exp.equals(res) ? null : exp;
}
/**
* Tests boolean.
* @param result query result
* @param expected expected
* @return optional expected test suite result
*/
private static String assertBoolean(final QT3Result result, final boolean expected) {
final XdmValue returned = result.value;
return returned.getType().eq(SeqType.BOOLEAN_O) && returned.getBoolean() == expected ?
null : Util.info(expected);
}
/**
* Tests empty sequence.
* @param result query result
* @return optional expected test suite result
*/
private static String assertEmpty(final QT3Result result) {
return result.value == XdmEmpty.EMPTY ? null : "";
}
/**
* Tests type.
* @param result query result
* @param expected expected result
* @return optional expected test suite result
*/
private String assertType(final QT3Result result, final XdmValue expected) {
final String exp = expected.getString();
try {
final String query = "declare variable $returned external; $returned instance of " + exp;
final XQuery xquery = environment(new XQuery(query, ctx), result.env);
final XdmValue returned = result.value;
return xquery.variable("returned", returned).value().getBoolean() ? null :
Util.info("Type '%' (found: '%')", exp, returned.getType().toString());
} catch(final XQueryException ex) {
// should not occur
return ex.getException().getMessage();
}
}
/**
* Returns the string representation of a query result.
* @param query query string
* @param value optional context value
* @return optional expected test suite result
*/
String asString(final String query, final XdmValue value) {
return XQuery.string(query, value, ctx);
}
/**
* Returns the boolean representation of a query result.
* @param query query string
* @param value optional context value
* @return optional expected test suite result
*/
boolean asBoolean(final String query, final XdmValue value) {
final XdmValue val = new XQuery(query, ctx).context(value).value();
return val.size() != 0 && val.getBoolean();
}
/**
* Returns the path to a given file.
* @param base base flag
* @param file file name
* @return path to the file
*/
private String file(final boolean base, final String file) {
final String dir = base ? baseDir : basePath;
return dir == null ? file : new IOFile(dir, file).path();
}
/**
* Calculates the percentage of correct queries.
* @param v value
* @param t total value
* @return percentage
*/
private static String pc(final int v, final long t) {
return (t == 0 ? 100 : v * 10000 / t / 100.0d) + "%";
}
/**
* Normalizes newline characters.
* @param in input string
* @return result
*/
private static String normNL(final String in) {
return in.replaceAll("\r\n|\r|\n", NL);
}
@Override
protected void parseArgs() throws IOException {
final MainParser arg = new MainParser(this);
while(arg.more()) {
if(arg.dash()) {
final char c = arg.next();
if(c == 'v') {
verbose = true;
} else if(c == 'a') {
all = true;
} else if(c == 'd') {
debug = true;
} else if(c == 'i') {
ignoring = true;
} else if(c == 'e') {
errors = false;
} else if(c == 'r') {
report = new QT3TSReport();
} else if(c == 's') {
slow = new TreeMap<>();
} else if(c == 'p') {
final File f = new File(arg.string());
if(!f.isDirectory()) throw arg.usage();
basePath = f.getCanonicalPath();
} else {
throw arg.usage();
}
} else {
single = arg.string();
maxout = Integer.MAX_VALUE;
}
}
}
/**
* Structure for storing XQuery results.
*/
static class QT3Result {
/** Test environment. */
QT3Env env;
/** Query instance. */
XQuery query;
/** Query result. */
XdmValue value;
/** Query exception. */
XQueryException xqerror;
/** Query error. */
Throwable error;
}
@Override
public String header() {
return Util.info(Text.S_CONSOLE_X, Util.className(this));
}
@Override
public String usage() {
return " -v [pat]" + NL +
" [pat] perform tests starting with a pattern" + NL +
" -a save all tests" + NL +
" -d debugging mode" + NL +
" -e ignore error codes" + NL +
" -i also save ignored files" + NL +
" -p path to the test suite" + NL +
" -r generate report file" + NL +
" -s print slow queries" + NL +
" -v verbose output";
}
}
|
// Do not change any of the contents unless you are absolutely certain you know what you are doing.
package com.$(AUTHOR).$(SAFETITLE);
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
public class WebSharperMobileActivity extends Activity implements SensorEventListener {
SensorManager myManager;
Sensor accSensor;
WebView wv;
Activity env;
boolean cameraNeeded = false;
Camera cmr;
WebSharperBridge bridge;
float[] acceleration = new float[] { 0, 0, (float) -9.8 };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
env = this;
wv = new WebView(this);
// enable JavaScript
wv.getSettings().setJavaScriptEnabled(true);
// enable HTML5 LocalStorage
wv.getSettings().setDomStorageEnabled(true);
bridge = new WebSharperBridge();
wv.loadUrl("file:///android_asset/www/index.html");
// in JavaScript, websharperBridge is the Java bridge object (of type WebSharperBridge)
wv.addJavascriptInterface(bridge, "websharperBridge");
setContentView(wv);
try
{
// request acceleration updates
myManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = myManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors.size() > 0)
{
accSensor = sensors.get(0);
myManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_UI);
}
}
catch (Exception e)
{ }
}
@Override
public void onPause()
{
// release resources
if (cameraNeeded && cmr != null)
cmr.release();
if (accSensor != null)
myManager.unregisterListener(this);
bridge.pause();
super.onPause();
}
@Override
public void onResume()
{
// reacquire resources
super.onResume();
bridge.resume();
if (accSensor != null)
myManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_UI);
if (cameraNeeded)
cmr = Camera.open();
}
class WebSharperBridge implements LocationListener
{
double lat = 0, lng = 0;
public void pause()
{
LocationManager locationManager = (LocationManager)env.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
public void resume()
{
try
{
// request location updates
LocationManager locationManager = (LocationManager)env.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 100, 0, this);
lat = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude();
lng = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude();
}
catch (Exception e)
{ }
}
@Override
public void onLocationChanged(Location location)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
// this function is used for XHR, so JavaScript will know where is the RPC server
public String serverLocation()
{
try
{
InputStream is = getAssets().open("www/serverLocation.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String result = new String(buffer);
return "({ $ : 1, $0 : \"" + result + "\" })";
}
catch (Exception e)
{
return "({ $ : 0 })";
}
}
public String location()
{
return "({ Lat : " + lat + ", Long : " + lng + " })";
}
public String acceleration()
{
return "({ X : " + acceleration[0] + ", Y : " + acceleration[1] + ", Z : " + acceleration[2] + " })";
}
public void camera(int maxHeight, int maxWidth, final String callback, final String fail)
{
try
{
cmr = Camera.open();
Camera.Parameters params = cmr.getParameters();
cmr.setParameters(params);
// the surface is the graphical interface for the camera, since Android SDK does not supply a default one
final SurfaceView sv = new SurfaceView(env);
sv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
Camera.PictureCallback jpegCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
StringBuffer sb = new StringBuffer(data.length * 2);
for (int i = 0; i < data.length; i++) {
int v = data[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
wv.loadUrl("javascript:" + callback + ".call(null,\"" + sb.toString().toUpperCase() + "\")");
camera.release();
env.runOnUiThread(new Runnable() {
public void run()
{
env.setContentView(wv);
}});
cmr = null;
}
};
cmr.takePicture(null, null, jpegCallback);
return true;
}
});
sv.setClickable(true);
env.runOnUiThread(new Runnable() {
public void run()
{
env.setContentView(sv);
}});
cmr.setPreviewDisplay(sv.getHolder());
cmr.startPreview();
Toast toast = Toast.makeText(env, "Long-click the screen to take photo.", Toast.LENGTH_SHORT);
toast.show();
}
catch (Exception e)
{
wv.loadUrl("javascript:" + fail + ".call(null,\"" + e.getMessage() + "\")");
}
}
public void alert(final String msg)
{
env.runOnUiThread(new Runnable() {
public void run()
{
new AlertDialog.Builder(env)
.setMessage(msg)
.setNeutralButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
});
}
// this function prints to logcat
public void log(String msg)
{
Log.d("DebugJS", msg);
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent args) {
acceleration = args.values.clone();
}
}
|
package tec.uom.client.fitbit.model.activity;
import tec.units.ri.function.Nameable;
import tec.uom.lib.common.function.LongIdentifiable;
public class DisplayableActivity implements Nameable, LongIdentifiable {
private long id;
private String name;
public DisplayableActivity(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}
|
package net.hyperic.sigar;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import java.util.StringTokenizer;
public class OperatingSystem {
private static final String ETC =
System.getProperty("sigar.etc.dir", "/etc") + "/";
private static OperatingSystem instance = null;
private String name;
private String version;
private String arch;
private String patchLevel;
private String vendor;
private String vendorVersion;
private OperatingSystem() {
}
public static synchronized OperatingSystem getInstance() {
if (instance == null) {
OperatingSystem os = new OperatingSystem();
Properties props = System.getProperties();
os.name = props.getProperty("os.name");
os.version = props.getProperty("os.version");
os.arch = props.getProperty("os.arch");
os.patchLevel = props.getProperty("sun.os.patch.level");
if (os.name.equals("Linux")) {
os.getLinuxInfo();
}
instance = os;
}
return instance;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
public String getArch() {
return this.arch;
}
public String getPatchLevel() {
return this.patchLevel;
}
public String getVendor() {
return this.vendor;
}
public String getVendorVersion() {
return this.vendorVersion;
}
private void getLinuxInfo() {
VendorInfo[] info = {
new GenericVendor("mandrake-release", "Mandrake"),
new GenericVendor("SuSE-release", "SuSE"),
new GenericVendor("gentoo-release", "Gentoo"),
new GenericVendor("debian_version", "Debian"),
new GenericVendor("slackware-version", "Slackware"),
new GenericVendor("fedora-release", "Fedora"),
new RedHatVendor("redhat-release", "Red Hat"),
new VMwareVendor("/proc/vmware/version", "VMware"),
};
for (int i=0; i<info.length; i++) {
File file = new File(info[i].getFileName());
if (!file.exists()) {
continue;
}
FileReader reader = null;
try {
int len = (int)file.length();
char[] data = new char[len];
reader = new FileReader(file);
reader.read(data, 0, len);
info[i].parse(new String(data), this);
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) { }
}
}
break;
}
}
private static String parseVersion(String line) {
StringTokenizer tok = new StringTokenizer(line);
while (tok.hasMoreTokens()) {
String s = tok.nextToken();
if (Character.isDigit(s.charAt(0))) {
int i;
for (i=1; i<s.length(); i++) {
char c = s.charAt(i);
if (!(Character.isDigit(c) || (c == '.'))) {
break;
}
}
return s.substring(0, i);
}
}
return null;
}
private interface VendorInfo {
public String getFileName();
public void parse(String data, OperatingSystem os);
}
private class RedHatVendor extends GenericVendor {
public RedHatVendor(String file, String name) {
super(file, name);
}
public void parse(String line, OperatingSystem os) {
super.parse(line, os);
String token = "Red Hat Enterprise Linux AS";
if (line.startsWith(token)) {
os.vendorVersion = "AS " + os.vendorVersion;
}
}
}
private class VMwareVendor extends GenericVendor {
public VMwareVendor(String file, String name) {
super(file, name);
}
public String getFileName() {
return this.file;
}
public void parse(String line, OperatingSystem os) {
os.vendor = this.name;
os.vendorVersion = "ESX 2.x"; //XXX
}
}
private class GenericVendor implements VendorInfo {
protected String file;
protected String name;
public GenericVendor(String file, String name) {
this.file = file;
this.name = name;
}
public String getFileName() {
return ETC + this.file;
}
public void parse(String line, OperatingSystem os) {
os.vendor = this.name;
os.vendorVersion = parseVersion(line);
}
}
public static void main(String[] args) {
OperatingSystem os = OperatingSystem.getInstance();
System.out.println("vendor..." + os.vendor);
System.out.println("vendor version..." + os.vendorVersion);
}
}
|
package uk.ac.ebi.atlas.profiles.baseline;
import au.com.bytecode.opencsv.CSVReader;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.model.baseline.BaselineExpression;
import uk.ac.ebi.atlas.model.baseline.BaselineProfile;
import uk.ac.ebi.atlas.model.baseline.Factor;
import uk.ac.ebi.atlas.profiles.ExpressionProfileInputStream;
import uk.ac.ebi.atlas.profiles.BaselineExpressionsKryoReader;
import uk.ac.ebi.atlas.utils.CsvReaderFactory;
import uk.ac.ebi.atlas.utils.KryoReaderFactory;
import javax.inject.Inject;
import javax.inject.Named;
import java.text.MessageFormat;
import java.util.Set;
@Named("baselineProfileInputStreamFactory")
@Scope("prototype")
public class BaselineProfileInputStreamFactory {
private static final Logger LOGGER = Logger.getLogger(BaselineProfileInputStreamFactory.class);
@Value("#{configuration['experiment.magetab.path.template']}")
protected String baselineExperimentDataFileUrlTemplate;
@Value("#{configuration['experiment.kryo_expressions.path.template']}")
protected String baselineExperimentSerializedDataFileUrlTemplate;
private ExpressionsRowDeserializerBaselineBuilder expressionsRowDeserializerBaselineBuilder;
private ExpressionsRowRawDeserializerBaselineBuilder expressionsRowRawDeserializerBaselineBuilder;
private CsvReaderFactory csvReaderFactory;
private KryoReaderFactory kryoReaderFactory;
public BaselineProfileInputStreamFactory() {
}
@Inject
public BaselineProfileInputStreamFactory(ExpressionsRowDeserializerBaselineBuilder expressionsRowDeserializerBaselineBuilder,
ExpressionsRowRawDeserializerBaselineBuilder expressionsRowRawDeserializerBaselineBuilder,
CsvReaderFactory csvReaderFactory, KryoReaderFactory kryoReaderFactory) {
this.expressionsRowDeserializerBaselineBuilder = expressionsRowDeserializerBaselineBuilder;
this.expressionsRowRawDeserializerBaselineBuilder = expressionsRowRawDeserializerBaselineBuilder;
this.csvReaderFactory = csvReaderFactory;
this.kryoReaderFactory = kryoReaderFactory;
}
public ExpressionProfileInputStream<BaselineProfile, BaselineExpression> createBaselineProfileInputStream(String experimentAccession, String queryFactorType, double cutOff, Set<Factor> filterFactors) {
IsBaselineExpressionAboveCutoffAndForFilterFactors baselineExpressionFilter = new IsBaselineExpressionAboveCutoffAndForFilterFactors();
baselineExpressionFilter.setCutoff(cutOff);
baselineExpressionFilter.setFilterFactors(filterFactors);
BaselineProfileReusableBuilder baselineProfileReusableBuilder = new BaselineProfileReusableBuilder(baselineExpressionFilter, queryFactorType);
String serializedFileURL = MessageFormat.format(baselineExperimentSerializedDataFileUrlTemplate, experimentAccession);
try {
BaselineExpressionsKryoReader baselineExpressionsKryoReader = kryoReaderFactory.createBaselineExpressionsKryoReader(serializedFileURL);
return new BaselineProfilesKryoInputStream(baselineExpressionsKryoReader, experimentAccession, expressionsRowRawDeserializerBaselineBuilder, baselineProfileReusableBuilder);
}
catch (IllegalArgumentException e) {
LOGGER.error("Could not read serialized file " + serializedFileURL);
String tsvFileURL = MessageFormat.format(baselineExperimentDataFileUrlTemplate, experimentAccession);
CSVReader csvReader = csvReaderFactory.createTsvReader(tsvFileURL);
return new BaselineProfilesTsvInputStream(csvReader, experimentAccession, expressionsRowDeserializerBaselineBuilder, baselineProfileReusableBuilder);
}
}
public ExpressionProfileInputStream<BaselineProfile, BaselineExpression> create(BaselineProfileStreamOptions options) {
String experimentAccession = options.getExperimentAccession();
double cutOff = options.getCutoff();
String queryFactorType = options.getQueryFactorType();
Set<Factor> filterFactors = options.getSelectedFilterFactors();
return createBaselineProfileInputStream(experimentAccession, queryFactorType, cutOff, filterFactors);
}
}
|
// JSMath.java
package ed.js;
import ed.util.StringParseUtil;
import ed.js.func.*;
import ed.js.engine.*;
public class JSMath extends JSObjectBase {
private static JSMath _instance = new JSMath();
public static JSMath getInstance(){
return _instance;
}
private JSMath(){
set( "max" ,
new JSFunctionCalls2(){
public Object call( Scope s , Object a , Object b , Object foo[] ){
if ( a != null && ! ( a instanceof Number ) )
return Double.NaN;
if ( b != null && ! ( b instanceof Number ) )
return Double.NaN;
if ( a == null && b == null )
return 0;
if ( a == null )
return b;
if ( b == null )
return a;
return ((Number)a).doubleValue() > ((Number)b).doubleValue() ? a : b;
}
} );
set( "min" ,
new JSFunctionCalls2(){
public Object call( Scope s , Object a , Object b , Object foo[] ){
if ( a != null && ! ( a instanceof Number ) )
return Double.NaN;
if ( b != null && ! ( b instanceof Number ) )
return Double.NaN;
if ( a == null && b == null )
return 0;
if ( a == null )
return b;
if ( b == null )
return a;
return ((Number)a).doubleValue() < ((Number)b).doubleValue() ? a : b;
}
} );
set( "random" ,
new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
return Math.random();
}
} );
set( "floor" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( a == null )
return 0;
if ( ! ( a instanceof Number ) )
try {
a = StringParseUtil.parseStrict(a.toString());
}
catch (Exception e) {
return Double.NaN;
}
return (int)Math.floor(((Number)a).doubleValue());
}
} );
set( "ceil" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( a == null )
return 0;
if ( ! ( a instanceof Number ) )
try {
a = StringParseUtil.parseStrict(a.toString());
}
catch (Exception e) {
return Double.NaN;
}
return (int)Math.ceil(((Number)a).doubleValue());
}
} );
set( "round" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( a == null )
return 0;
if ( ! ( a instanceof Number ) )
try {
a = StringParseUtil.parseStrict(a.toString());
}
catch (Exception e) {
return Double.NaN;
}
return (int)Math.round(((Number)a).doubleValue());
}
} );
set( "abs" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( a == null )
return 0;
if ( ! ( a instanceof Number ) )
try {
a = StringParseUtil.parseStrict(a.toString());
}
catch (Exception e) {
return Double.NaN;
}
if ( a instanceof Integer )
return Math.abs(((Integer)a).intValue());
return Math.abs(((Number)a).doubleValue());
}
} );
set( "sqrt" ,
new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( a == null )
return 0;
if ( ! ( a instanceof Number ) )
try {
a = StringParseUtil.parseStrict(a.toString());
}
catch (Exception e) {
return Double.NaN;
}
return Math.sqrt( ((Number)a).doubleValue() );
}
} );
set( "posOrNeg" , new JSFunctionCalls1(){
public Object call( Scope s , Object a , Object foo[] ){
if ( ! ( a instanceof Number ) )
return 0;
Number n = (Number)a;
double d = n.doubleValue();
if ( d > 0 )
return 1;
if ( d < 0 )
return -1;
return 0;
}
} );
set( "sigFig" , new JSFunctionCalls2(){
public Object call( Scope s , Object xObject , Object nObject , Object foo[] ){
double X = ((Number)xObject).doubleValue();
double N = nObject == null ? 3 : ((Number)nObject).doubleValue();
return sigFig( X , N );
}
} );
}
public static double sigFig( double X ){
return sigFig( X , 3 );
}
public static double sigFig( double X , double N ){
double p = Math.pow( 10, N - Math.ceil( Math.log( Math.abs(X) ) / LN10 ) );
return Math.round(X*p)/p;
}
public static final double LN10 = Math.log(10);
}
|
package org.knowm.xchange.binance.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.binance.dto.BinanceException;
import org.knowm.xchange.binance.dto.account.BinanceAccountInformation;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.FundingRecord;
import org.knowm.xchange.dto.account.FundingRecord.Status;
import org.knowm.xchange.dto.account.FundingRecord.Type;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.service.account.AccountService;
import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams;
import org.knowm.xchange.service.trade.params.HistoryParamsFundingType;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrency;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.WithdrawFundsParams;
public class BinanceAccountService extends BinanceAccountServiceRaw implements AccountService {
public BinanceAccountService(Exchange exchange) {
super(exchange);
}
@Override
public AccountInfo getAccountInfo() throws IOException {
Long recvWindow = (Long) exchange.getExchangeSpecification().getExchangeSpecificParametersItem("recvWindow");
BinanceAccountInformation acc = super.account(recvWindow, System.currentTimeMillis());
List<Balance> balances = acc.balances.stream()
.map(b -> new Balance(Currency.getInstance(b.asset), b.free.add(b.locked), b.free))
.collect(Collectors.toList());
return new AccountInfo(new Wallet(balances));
}
@Override
public String withdrawFunds(Currency currency, BigDecimal amount, String address)
throws IOException {
withdraw0(currency.getCurrencyCode(), address, amount);
return null;
}
@Override
public String withdrawFunds(WithdrawFundsParams params)
throws IOException {
if (!(params instanceof DefaultWithdrawFundsParams)) {
throw new RuntimeException("DefaultWithdrawFundsParams must be provided.");
}
DefaultWithdrawFundsParams p = (DefaultWithdrawFundsParams) params;
withdraw0(p.currency.getCurrencyCode(), p.address, p.amount);
return null;
}
private void withdraw0(String asset, String address, BigDecimal amount) throws IOException, BinanceException {
// the name parameter seams to be mandatory
String name = address.length() <= 10 ? address : address.substring(0, 10);
Long recvWindow = (Long) exchange.getExchangeSpecification().getExchangeSpecificParametersItem("recvWindow");
super.withdraw(asset, address, amount, name, recvWindow, System.currentTimeMillis());
}
@Override
public String requestDepositAddress(Currency currency, String... args)
throws IOException {
throw new NotAvailableFromExchangeException();
}
@Override
public TradeHistoryParams createFundingHistoryParams() {
return new BinanceFundingHistoryParams();
}
@Override
public List<FundingRecord> getFundingHistory(TradeHistoryParams params)
throws IOException {
if (!(params instanceof TradeHistoryParamCurrency)) {
throw new RuntimeException("You must provide the currency in order to get the funding history (TradeHistoryParamCurrency).");
}
TradeHistoryParamCurrency cp = (TradeHistoryParamCurrency) params;
final String asset = cp.getCurrency().getCurrencyCode();
Long recvWindow = (Long) exchange.getExchangeSpecification().getExchangeSpecificParametersItem("recvWindow");
boolean withdrawals = true;
boolean deposits = true;
Long startTime = null;
Long endTime = null;
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan tp = (TradeHistoryParamsTimeSpan) params;
if (tp.getStartTime() != null) {
startTime = tp.getStartTime().getTime();
}
if (tp.getEndTime() != null) {
endTime = tp.getEndTime().getTime();
}
}
if (params instanceof HistoryParamsFundingType) {
HistoryParamsFundingType f = (HistoryParamsFundingType) params;
withdrawals = f.getType() != null && f.getType() == Type.WITHDRAWAL;
deposits = f.getType() != null && f.getType() == Type.DEPOSIT;
}
List<FundingRecord> result = new ArrayList<>();
if (withdrawals) {
super.withdrawHistory(asset, startTime, endTime, recvWindow, System.currentTimeMillis()).forEach(w -> {
result.add(new FundingRecord(w.address, new Date(w.applyTime), Currency.getInstance(w.asset), w.amount, null, null, Type.WITHDRAWAL, withdrawStatus(w.status), null, null, null));
});
}
if (deposits) {
super.depositHistory(asset, startTime, endTime, recvWindow, System.currentTimeMillis()).forEach(d -> {
result.add(new FundingRecord(null, new Date(d.insertTime), Currency.getInstance(d.asset), d.amount, null, null, Type.DEPOSIT, depositStatus(d.status), null, null, null));
});
}
return result;
}
/**
* (0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6Completed)
*/
private static FundingRecord.Status withdrawStatus(int status) {
switch (status) {
case 0:
case 2:
case 4:
return Status.PROCESSING;
case 1:
return Status.CANCELLED;
case 3:
case 5:
return Status.FAILED;
case 6:
return Status.COMPLETE;
default:
throw new RuntimeException("Unknown binance withdraw status: " + status);
}
}
/**
* (0:pending,1:success)
*/
private static FundingRecord.Status depositStatus(int status) {
switch (status) {
case 0:
return Status.PROCESSING;
case 1:
return Status.COMPLETE;
default:
throw new RuntimeException("Unknown binance deposit status: " + status);
}
}
}
|
package org.keyczar;
import org.apache.log4j.Logger;
import org.keyczar.RsaPublicKey.Padding;
import org.keyczar.enums.KeyPurpose;
import org.keyczar.enums.KeyStatus;
import org.keyczar.enums.KeyType;
import org.keyczar.exceptions.KeyczarException;
import org.keyczar.i18n.Messages;
import org.keyczar.interfaces.KeyczarReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
/**
* Wrapper class to access Keyczar utility methods of reading and manipulating
* key metadata files. Also contains additional utility methods for pushing
* updates to meta files on disk and exporting public key sets.
*
* @author steveweis@gmail.com (Steve Weis)
* @author arkajit.dey@gmail.com (Arkajit Dey)
*
*/
public class GenericKeyczar extends Keyczar {
private static final Logger LOG = Logger.getLogger(GenericKeyczar.class);
public GenericKeyczar(KeyczarReader reader) throws KeyczarException {
super(reader);
}
public GenericKeyczar(String location) throws KeyczarException {
super(location);
}
@Override
public boolean isAcceptablePurpose(KeyPurpose purpose) {
return true;
}
public KeyMetadata getMetadata() {
return this.kmd;
}
public Set<KeyVersion> getVersions() {
return Collections.unmodifiableSet(versionMap.keySet());
}
public KeyczarKey getKey(KeyVersion v) {
return versionMap.get(v);
}
/**
* Promotes the status of key with given version number. Promoting ACTIVE key
* automatically demotes current PRIMARY key to ACTIVE.
*
* @param versionNumber integer version number to promote
* @throws KeyczarException if invalid version number or trying to promote
* a primary key.
*/
public void promote(int versionNumber) throws KeyczarException {
KeyVersion version = getVersion(versionNumber);
LOG.debug(Messages.getString("Keyczar.PromotedVersion", version));
switch (version.getStatus()) {
case PRIMARY:
throw new KeyczarException(
Messages.getString("Keyczar.CantPromotePrimary"));
case ACTIVE:
version.setStatus(KeyStatus.PRIMARY); // promote to PRIMARY
if (primaryVersion != null) {
primaryVersion.setStatus(KeyStatus.ACTIVE); // only one PRIMARY key
}
primaryVersion = version;
break;
case INACTIVE:
version.setStatus(KeyStatus.ACTIVE);
break;
}
}
/**
* Demotes the status of key with given version number. Demoting PRIMARY key
* results in a key set with no primary version.
*
* @param versionNumber integer version number to demote
* @throws KeyczarException if invalid version number or trying to demote
* a key scheduled for revocation.
*/
public void demote(int versionNumber) throws KeyczarException {
KeyVersion version = getVersion(versionNumber);
LOG.debug(Messages.getString("Keyczar.DemotingVersion", version));
switch (version.getStatus()) {
case PRIMARY:
version.setStatus(KeyStatus.ACTIVE);
primaryVersion = null; // no more PRIMARY keys in the set
break;
case ACTIVE:
version.setStatus(KeyStatus.INACTIVE);
break;
case INACTIVE:
throw new KeyczarException(
Messages.getString("Keyczar.CantDemoteScheduled"));
}
}
/**
* Uses default key size and padding to add a new key version.
*/
public void addVersion(KeyStatus status) throws KeyczarException {
addVersion(status, null, kmd.getType().defaultSize());
}
/**
* Uses default padding to add a new key version.
*/
public void addVersion(KeyStatus status, int keySize) throws KeyczarException {
addVersion(status, null, keySize);
}
/**
* Uses default key size to add a new key version.
*
* @param status KeyStatus desired for new key version
* @param padding Encryption padding type for RSA keys. Should be null for others.
*/
public void addVersion(KeyStatus status, Padding padding) throws KeyczarException {
addVersion(status, padding, kmd.getType().defaultSize());
}
/**
* Adds a new key version with given status and next available version
* number to key set. Generates a new key of same type (repeated until hash
* identifier is unique) for this version. Uses supplied key size in lieu
* of the default key size. If this is an unacceptable key size, defaults
* to the default key size.
*
* @param status KeyStatus desired for new key version
* @param padding Encryption padding type for RSA keys. Should be null for others.
* @param keySize desired key size in bits
* @throws KeyczarException if key type is unsupported.
*/
public void addVersion(KeyStatus status, Padding padding, int keySize) throws KeyczarException {
KeyczarKey key;
if (keySize < kmd.getType().defaultSize()) { // print a warning statement
LOG.warn(Messages.getString("Keyczar.SizeWarning",
keySize, kmd.getType().defaultSize(), kmd.getType().toString()));
}
do { // Make sure no keys collide on their identifiers
key = KeyczarKey.genKey(kmd.getType(), padding, keySize);
} while (getKey(key.hash()) != null);
addVersion(status, key);
}
/**
* Adds the given key as a new version with given status and next available
* version number to key set.
*
* @param status KeyStatus desired for new key version
*/
public void addVersion(KeyStatus status, KeyczarKey key) {
KeyVersion version = new KeyVersion(numVersions() + 1, status, false);
if (status == KeyStatus.PRIMARY) {
if (primaryVersion != null) {
primaryVersion.setStatus(KeyStatus.ACTIVE);
}
primaryVersion = version;
}
addKey(version, key);
LOG.debug(Messages.getString("Keyczar.NewVersion", version));
}
/**
* Returns the version corresponding to the version number if it exists.
*
* @param versionNumber
* @return KeyVersion if it exists
* @throws KeyczarException if version number doesn't exist
*/
public KeyVersion getVersion(int versionNumber) throws KeyczarException {
KeyVersion version = kmd.getVersion(versionNumber);
if (version == null) {
throw new KeyczarException(
Messages.getString("Keyczar.NoSuchVersion", versionNumber));
}
return version;
}
/**
* Revokes the key with given version number if it is scheduled to be revoked.
*
* @param versionNumber integer version number to be revoked
* @throws KeyczarException if version number nonexistent or key is not
* scheduled for revocation.
*/
public void revoke(int versionNumber) throws KeyczarException {
KeyVersion version = getVersion(versionNumber);
if (version.getStatus() == KeyStatus.INACTIVE) {
kmd.removeVersion(versionNumber);
} else {
throw new KeyczarException(Messages.getString("Keyczar.CantRevoke"));
}
}
/**
* Returns the number of versions in the keyset.
*/
private int numVersions() {
return versionMap.size();
}
/**
* For the managed key set, exports a set of public keys at given location.
* Client's key must be a private key for DSA or RSA. For DSA private key,
* purpose must be SIGN_AND_VERIFY. For RSA private key, purpose can also
* be DECRYPT_AND_ENCRYPT.KeyczarTool
*
* @param destination String pathname of directory to export key set to
* @throws KeyczarException if unable to export key set.
*/
void publicKeyExport(String destination) throws KeyczarException {
if (destination != null && !destination.endsWith(File.separator)) {
destination += File.separator;
}
KeyMetadata kmd = getMetadata();
// Can only export if type is DSA_PRIV and purpose is SIGN_AND_VERIFY
KeyMetadata publicKmd = null;
switch(kmd.getType()) {
case DSA_PRIV: // DSA Private Key
if (kmd.getPurpose() == KeyPurpose.SIGN_AND_VERIFY) {
publicKmd = new KeyMetadata(kmd.getName(), KeyPurpose.VERIFY,
KeyType.DSA_PUB);
}
break;
case RSA_PRIV: // RSA Private Key
switch(kmd.getPurpose()) {
case DECRYPT_AND_ENCRYPT:
publicKmd = new KeyMetadata(kmd.getName(), KeyPurpose.ENCRYPT,
KeyType.RSA_PUB);
break;
case SIGN_AND_VERIFY:
publicKmd = new KeyMetadata(kmd.getName(), KeyPurpose.VERIFY,
KeyType.RSA_PUB);
break;
}
break;
}
if (publicKmd == null) {
throw new KeyczarException(
Messages.getString("KeyczarTool.CannotExportPubKey",
kmd.getType(), kmd.getPurpose()));
}
for (KeyVersion version : getVersions()) {
KeyczarKey publicKey =
((KeyczarPrivateKey) getKey(version)).getPublic();
if (KeyczarTool.getMock() == null) {
writeFile(publicKey.toString(), destination
+ version.getVersionNumber());
} else { // for testing, update mock object
KeyczarTool.getMock().setPublicKey(version.getVersionNumber(), publicKey);
}
publicKmd.addVersion(version);
}
if (KeyczarTool.getMock() == null) {
writeFile(publicKmd.toString(), destination
+ KeyczarFileReader.META_FILE);
} else { // for testing, update mock public kmd
KeyczarTool.getMock().setPublicKeyMetadata(publicKmd);
}
}
/**
* Pushes updated KeyMetadata and KeyVersion info to files at given
* directory location. Version files are named by their number and the
* meta file is named meta.
*
* @param location String pathname of directory to write to
* @throws KeyczarException if unable to write to given location.
*/
void write(String location) throws KeyczarException {
writeFile(kmd.toString(), location
+ KeyczarFileReader.META_FILE);
for (KeyVersion version : getVersions()) {
writeFile(getKey(version).toString(), location
+ version.getVersionNumber());
}
}
/**
* Encrypts the key files before writing them out to disk
*
* @param location Location of key set
* @param encrypter The encrypter object used to encrypt keys
* @throws KeyczarException If unable to write to a given location
*/
void writeEncrypted(String location, Encrypter encrypter)
throws KeyczarException {
KeyMetadata kmd = getMetadata();
kmd.setEncrypted(true);
writeFile(kmd.toString(), location + KeyczarFileReader.META_FILE);
for (KeyVersion version : getVersions()) {
writeFile(encrypter.encrypt(getKey(version).toString()), location
+ version.getVersionNumber());
}
}
/**
* Utility function to write given data to a file at given location.
*
* @param data String data to be written
* @param location String pathname of destination file
* @throws KeyczarException if unable to write to file.
*/
void writeFile(String data, String location)
throws KeyczarException {
File outputFile = new File(location);
try {
FileWriter writer = new FileWriter(outputFile);
writer.write(data);
writer.close();
} catch (IOException e) {
throw new KeyczarException(
Messages.getString("KeyczarTool.UnableToWrite",
outputFile.toString()), e);
}
}
}
|
package fi.vrk.xroad.catalog.collector.util;
import fi.vrk.xroad.catalog.collector.wsimport.*;
import lombok.extern.slf4j.Slf4j;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.UUID;
/**
* WS client
*/
@Slf4j
public class XRoadClient {
private XRoadClient() {
// Private empty constructor
}
/**
* Calls the service using JAX-WS endpoints that have been generated from wsdl
*/
public static List<XRoadServiceIdentifierType> getMethods(String securityServerHost, XRoadClientIdentifierType
securityServerIdentity,
ClientType client)
throws MalformedURLException {
XRoadServiceIdentifierType serviceIdentifierType = new XRoadServiceIdentifierType();
copyIdentifierType(serviceIdentifierType, client.getId());
serviceIdentifierType.setServiceCode("listMethods");
serviceIdentifierType.setServiceVersion("v1");
serviceIdentifierType.setObjectType(XRoadObjectType.SERVICE);
URL url = new URL(securityServerHost);
log.info("SOAP call at url {} for member {} and service {}", url, ClientTypeUtil.toString
(securityServerIdentity), ClientTypeUtil
.toString(serviceIdentifierType));
MetaServicesPort port = getMetaServicesPort(url);
ListMethodsResponse response = port.listMethods(
new ListMethods(),
new Holder<>(securityServerIdentity),
new Holder<>(serviceIdentifierType),
new Holder<>("xroad-catalog-collector-"+ UUID.randomUUID()),
new Holder<>("xroad-catalog-collector"),
new Holder<>("4.x"));
return response.getService();
}
/**
* MetaServicesPort for url
*/
public static MetaServicesPort getMetaServicesPort(URL url) {
URL wsdl = XRoadClient.class.getClassLoader()
.getResource("schema/list-methods.wsdl");
ProducerPortService service = new ProducerPortService(wsdl,
new QName("http://metadata.x-road.eu/", "producerPortService"));
MetaServicesPort port = service.getMetaServicesPortSoap11();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext()
.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());
return port;
}
protected static void copyIdentifierType
(XRoadIdentifierType target, XRoadIdentifierType source) {
target.setGroupCode(source.getGroupCode());
target.setObjectType(XRoadObjectType.fromValue(source.getObjectType().value()));
target.setMemberCode(source.getMemberCode());
target.setServiceVersion(source.getServiceVersion());
target.setMemberClass(source.getMemberClass());
target.setServiceCode(source.getServiceCode());
target.setSecurityCategoryCode(source.getSecurityCategoryCode());
target.setServerCode(source.getServerCode());
target.setXRoadInstance(source.getXRoadInstance());
target.setSubsystemCode(source.getSubsystemCode());
}
}
|
package org.xwiki.platform;
import junit.framework.TestCase;
import org.xwiki.platform.patchservice.api.RWOperation;
import org.xwiki.platform.patchservice.impl.OperationFactoryImpl;
import com.xpn.xwiki.XWikiException;
public class CheckAllOperationsImplementedTest extends TestCase
{
public void testAllOperationsImplemented() throws XWikiException
{
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_CONTENT_INSERT));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_CONTENT_DELETE));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_PROPERTY_SET));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_CLASS_PROPERTY_ADD));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_CLASS_PROPERTY_CHANGE));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_CLASS_PROPERTY_DELETE));
assertNotNull(OperationFactoryImpl.getInstance()
.newOperation(RWOperation.TYPE_OBJECT_ADD));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_OBJECT_DELETE));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_OBJECT_PROPERTY_SET));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_ATTACHMENT_ADD));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_ATTACHMENT_SET));
assertNotNull(OperationFactoryImpl.getInstance().newOperation(
RWOperation.TYPE_ATTACHMENT_DELETE));
}
/* Uncomment to get a sample of the XML output.when running tests. */
// public void testXmlOutput() throws Exception
// Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
// Element root = doc.createElement("patch");
// doc.appendChild(root);
// root.appendChild(doc.createTextNode("\n"));
// RWOperation operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_INSERT);
// operation.insert(" as/<>\"'&d ", new PositionImpl(2, 3, " \"'<>befo&re", "after "));
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_DELETE);
// operation.delete("Here ", new PositionImpl(0, 0));
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_PROPERTY_SET);
// operation.setProperty("prop", "val");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// BaseClass b = new BaseClass();
// b.addBooleanField("field", "The field", "yesno");
// operation = getOperation((PropertyClass) b.get("field"), true);
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation = getOperation((PropertyClass) b.get("field"), false);
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(
// RWOperation.TYPE_CLASS_PROPERTY_DELETE);
// operation.deleteType("XWiki.Class", "prop1");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_ADD);
// operation.addObject("XWiki.Class");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_DELETE);
// operation.deleteObject("XWiki.Class", 2);
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_PROPERTY_SET);
// operation.setObjectProperty("XWiki.Class", 2, "propertyName", "value");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(
// RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT);
// operation.insertInProperty("XWiki.Class", 0, "property", "inserted text",
// new PositionImpl(2, 0));
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(
// RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT);
// operation.deleteFromProperty("XWiki.Class", 0, "property", "deleted text",
// new PositionImpl(2, 0));
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_ADD);
// operation.addAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_SET);
// operation.setAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// operation =
// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_DELETE);
// operation.deleteAttachment("file");
// root.appendChild(operation.toXml(doc));
// root.appendChild(doc.createTextNode("\n"));
// DOMImplementationLS ls = (DOMImplementationLS) doc.getImplementation();
// System.out.println(ls.createLSSerializer().writeToString(doc));
// private RWOperation getOperation(PropertyClass property, boolean create)
// throws XWikiException
// String type = property.getClass().getCanonicalName();
// Map config = new HashMap();
// for (Iterator it2 = property.getFieldList().iterator(); it2.hasNext();) {
// BaseProperty pr = (BaseProperty) it2.next();
// config.put(pr.getName(), pr.getValue());
// RWOperation operation =
// OperationFactoryImpl.getInstance().newOperation(
// create ? RWOperation.TYPE_CLASS_PROPERTY_ADD
// : RWOperation.TYPE_CLASS_PROPERTY_CHANGE);
// if (create) {
// operation.createType("XWiki.Class", property.getName(), type, config);
// } else {
// operation.modifyType("XWiki.Class", property.getName(), config);
// return operation;
}
|
package org.xwiki.rendering.listener.chaining;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Stores information about the listeners in the chain and the order in which they need to be called. Also sports a
* feature that allows pushing and popping listeners that are stackable. This feature is useful since listeners can hold
* stateful information and sometimes you may need to push new versions of them to start with new state information. For
* example this is used in the XWiki Syntax Renderer when group event is found to start the rendering for that group
* using reset state information.
*
* @version $Id$
* @since 1.8RC1
*/
public class ListenerChain
{
/**
* The full list of chaining listeners. For each of them we have a stack since the ones that implement the
* {@link StackableChainingListener} interface can be stacked.
*/
private Map<Class<? extends ChainingListener>, Deque<ChainingListener>> listeners = new HashMap<>();
/**
* The ordered list of listeners. We only allow one instance per listener class name so we just need to store the
* class object and then the instance can be found in {@link #listeners}.
*/
private List<Class<? extends ChainingListener>> nextListeners = new ArrayList<>();
/**
* @param listener the chaining listener to add to the chain. If an instance of that listener is already present
* then we stack the new instance instead.
*/
public void addListener(ChainingListener listener)
{
// If there's already an entry for that listener then push it on the existing stack
// and don't add the listener as an additional listener in the list (since it's already
// in there). We need to take these steps since the push() methods below will create
// new instances of listeners which will add themselves in the chain automatically.
Deque<ChainingListener> stack = this.listeners.get(listener.getClass());
if (stack == null) {
stack = new ArrayDeque<>();
this.listeners.put(listener.getClass(), stack);
this.nextListeners.add(listener.getClass());
}
stack.push(listener);
}
/**
* @param listenerClass the listener to remove from the chain
*/
public void removeListener(Class<? extends ChainingListener> listenerClass)
{
this.listeners.remove(listenerClass);
this.nextListeners.remove(listenerClass);
}
/**
* @param listenerClass the listener for which we need to find the next listener in the chain
* @return the next listener in the chain
*/
public ChainingListener getNextListener(Class<? extends ChainingListener> listenerClass)
{
ChainingListener next = null;
int pos = indexOf(listenerClass);
if (pos > -1 && this.nextListeners.size() > pos + 1) {
next = this.listeners.get(this.nextListeners.get(pos + 1)).peek();
}
return next;
}
/**
* @param listenerClass the listener class for which we want to find the listener instance
* @return the listener instance corresponding to the passed class. Note that the last instance of the stack is
* returned
*/
public ChainingListener getListener(Class<? extends ChainingListener> listenerClass)
{
return this.listeners.get(listenerClass).peek();
}
/**
* @param listenerClass the listener class for which to find the position in the chain
* @return the position in the chain (first position is 0)
*/
public int indexOf(Class<? extends ChainingListener> listenerClass)
{
return this.nextListeners.indexOf(listenerClass);
}
/**
* Create a new instance of the passed chaining listener if it's stackable (ie it implements the
* {@link org.xwiki.rendering.listener.chaining.StackableChainingListener} interface. This allows creating a clean
* state when some sub rendering has to be done with some new state.
*
* @param listenerClass the listener class for which to create a new instance (if stackable)
*/
public void pushListener(Class<? extends ChainingListener> listenerClass)
{
if (StackableChainingListener.class.isAssignableFrom(listenerClass)) {
Deque<ChainingListener> stack = this.listeners.get(listenerClass);
stack.push(((StackableChainingListener) stack.peek()).createChainingListenerInstance());
}
}
/**
* Create new instances of all chaining listeners that are stackable (ie that implement the
* {@link org.xwiki.rendering.listener.chaining.StackableChainingListener} interface. This allows creating a clean
* state when some sub rendering has to be done with some new state.
*/
public void pushAllStackableListeners()
{
for (Class<? extends ChainingListener> listenerClass : this.listeners.keySet()) {
pushListener(listenerClass);
}
}
/**
* Remove all pushed stackable listeners to go back to the previous state (see {@link #pushAllStackableListeners()}.
*/
public void popAllStackableListeners()
{
for (Class<? extends ChainingListener> listenerClass : this.listeners.keySet()) {
popListener(listenerClass);
}
}
/**
* Remove the last instance corresponding to the passed listener class if it's stackable, in order to go back to the
* previous state.
*
* @param listenerClass the class of the chaining listener to pop
*/
public void popListener(Class<? extends ChainingListener> listenerClass)
{
if (StackableChainingListener.class.isAssignableFrom(listenerClass)) {
this.listeners.get(listenerClass).pop();
}
}
}
|
package com.yuwen.support.util.statusbar;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* @author yuwen 20161120
*/
public class StatusBarHelper {
private static String TAG = "StatusBarHelper";
/**
*
*
* @param window
* @param immersive
* @return boolean true
*/
public static boolean setImmersiveWindow(Window window, boolean immersive) {
boolean result = false;
if (window != null) {
if (immersive) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
systemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
}
result = true;
}
return result;
}
public static boolean setStatusBarDarkMode(Window window, boolean dark) {
boolean result = false;
if (isMIUI6Later()) {
result = setMiuiStatusBarDarkMode(window, dark);
} else if (isFlyme4Later()) {
result = setFlymeStatusBarDarkMode(window, dark);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
result = setUsualStatusBarDarkMode(window, dark);
}
return result;
}
/**
*
*
* @param window
* @param dark
* @return boolean true
*/
private static boolean setMiuiStatusBarDarkMode(Window window, boolean dark) {
boolean result = false;
Class<? extends Window> clazz = window.getClass();
try {
int darkModeFlag;
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(window, dark ? darkModeFlag : 0, darkModeFlag);
result = true;
} catch (Exception e) {
Log.e(TAG, "setMiuiStatusBarDarkMode: failed");
}
return result;
}
/**
*
*
* @param window
* @param dark
* @return boolean true
*/
private static boolean setFlymeStatusBarDarkMode(Window window, boolean dark) {
boolean result = false;
if (window != null) {
try {
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class
.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class
.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
result = true;
} catch (Exception e) {
Log.e(TAG, "setFlymeStatusBarDarkIcon: failed");
}
}
return result;
}
/**
* android 6.0
*/
private static boolean setUsualStatusBarDarkMode(Window window, boolean dark) {
// Android 6.0 False
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;
boolean result = false;
if (window != null) {
try {
if (dark) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
int systemUiVisibility = window.getDecorView().getSystemUiVisibility();
systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
window.getDecorView().setSystemUiVisibility(systemUiVisibility);
}
result = true;
} catch (Exception e) {
Log.e(TAG, "setUsualStatusBarDarkMode: failed");
}
}
return result;
}
/**
* MIUI6
*/
public static boolean isMIUI6Later() {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method mtd = clz.getMethod("get", String.class);
String val = (String) mtd.invoke(null, "ro.miui.ui.version.name");
val = val.replaceAll("[vV]", "");
int version = Integer.parseInt(val);
return version >= 6;
} catch (Exception e) {
return false;
}
}
/**
* Flyme4
*/
public static boolean isFlyme4Later() {
return Build.FINGERPRINT.contains("Flyme_OS_4")
|| Build.VERSION.INCREMENTAL.contains("Flyme_OS_4")
|| Pattern.compile("Flyme OS [4|5]", Pattern.CASE_INSENSITIVE).matcher(Build.DISPLAY).find()
|| Build.DISPLAY.contains("Flyme 5");
}
/**
* actionbar
*
* @param context
* @param actionbar ActionBar
* @return int ActionBar
*/
public static int getActionBarHeight(Context context, ActionBar actionbar) {
if (actionbar != null) {
TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize,
tv, true)) {
return TypedValue.complexToDimensionPixelSize(tv.data, context
.getResources().getDisplayMetrics());
}
return actionbar.getHeight();
}
return 0;
}
public static void setStatusBarHeight(Activity activity, View view) {
view.setPadding(
view.getPaddingLeft(),
StatusBarHelper.getStatusBarHeight(activity),
view.getPaddingRight(),
view.getPaddingBottom());
}
/**
*
*
* @param context
* @return int
*/
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
|
package org.basex.util;
import static org.basex.core.Text.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.function.*;
import org.basex.io.*;
import org.basex.query.*;
import org.basex.util.list.*;
public final class Util {
/** Flag for using default standard input. */
private static final boolean NOCONSOLE = System.console() == null;
/** Hidden constructor. */
private Util() { }
/**
* Returns an information string for an unexpected exception.
* @param throwable exception
* @return dummy object
*/
public static String bug(final Throwable throwable) {
final TokenBuilder tb = new TokenBuilder().add(S_BUGINFO);
tb.add(NL).add("Contact: ").add(MAILING_LIST);
tb.add(NL).add("Version: ").add(TITLE);
tb.add(NL).add("Java: ").add(System.getProperty("java.vendor"));
tb.add(", ").add(System.getProperty("java.version"));
tb.add(NL).add("OS: ").add(System.getProperty("os.name"));
tb.add(", ").add(System.getProperty("os.arch"));
tb.add(NL).add("Stack Trace: ");
for(final String e : toArray(throwable)) tb.add(NL).add(e);
return tb.toString();
}
/**
* Throws a runtime exception for an unexpected exception.
* @return runtime exception (indicates that an error is raised)
*/
public static RuntimeException notExpected() {
return notExpected("Not Expected.");
}
/**
* Throws a runtime exception for an unexpected exception.
* @param message message
* @param ext optional extension
* @return runtime exception (indicates that an error is raised)
*/
public static RuntimeException notExpected(final Object message, final Object... ext) {
return new RuntimeException(info(message, ext));
}
/**
* Returns the class name of the specified object, excluding its path.
* @param object object
* @return class name
*/
public static String className(final Object object) {
return className(object.getClass());
}
/**
* Returns the name of the specified class, excluding its path.
* @param clazz class
* @return class name
*/
public static String className(final Class<?> clazz) {
return clazz.getSimpleName();
}
public static String className(final Supplier<?> supplier) {
return supplier.get().getClass().getSimpleName();
}
/**
* Returns a single line from standard input.
* @return string
*/
public static String input() {
final Scanner sc = new Scanner(System.in);
return sc.hasNextLine() ? sc.nextLine().trim() : "";
}
/**
* Returns a password from standard input.
* @return password or empty string
*/
public static String password() {
// use standard input if no console if defined (such as in Eclipse)
if(NOCONSOLE) return input();
// hide password
final char[] pw = System.console().readPassword();
return pw != null ? new String(pw) : "";
}
/**
* Prints a newline to standard output.
*/
public static void outln() {
out(NL);
}
/**
* Prints a string to standard output, followed by a newline.
* @param string output string
* @param ext text optional extensions
*/
public static void outln(final Object string, final Object... ext) {
out((string instanceof byte[] ? Token.string((byte[]) string) : string) + NL, ext);
}
/**
* Prints a string to standard output.
* @param string output string
* @param ext text optional extensions
*/
public static void out(final Object string, final Object... ext) {
System.out.print(info(string, ext));
}
/**
* Returns the root query exception.
* @param throwable throwable
* @return root exception
*/
public static Throwable rootException(final Throwable throwable) {
Throwable th = throwable;
while(true) {
debug(th);
final Throwable ca = th.getCause();
if(ca == null || th instanceof QueryException && !(ca instanceof QueryException)) return th;
th = ca;
}
}
/**
* Prints a string to standard error, followed by a newline.
* @param object error object
* @param ext text optional extensions
*/
public static void errln(final Object object, final Object... ext) {
err((object instanceof Throwable ? message((Throwable) object) : object) + NL, ext);
}
/**
* Prints a string to standard error.
* @param string debug string
* @param ext text optional extensions
*/
public static void err(final String string, final Object... ext) {
System.err.print(info(string, ext));
}
/**
* Returns a more user-friendly error message for the specified exception.
* @param throwable throwable reference
* @return error message
*/
public static String message(final Throwable throwable) {
debug(throwable);
if(throwable instanceof BindException) return SRV_RUNNING;
if(throwable instanceof ConnectException) return CONNECTION_ERROR;
if(throwable instanceof SocketTimeoutException) return TIMEOUT_EXCEEDED;
if(throwable instanceof SocketException) return CONNECTION_ERROR;
String msg = throwable.getMessage();
if(msg == null || msg.isEmpty() || throwable instanceof RuntimeException)
msg = throwable.toString();
if(throwable instanceof FileNotFoundException) return info(RES_NOT_FOUND_X, msg);
if(throwable instanceof UnknownHostException) return info(UNKNOWN_HOST_X, msg);
if(throwable.getClass() == IOException.class && msg.length() > 200) {
msg = msg.substring(0, 200) + DOTS;
}
return msg;
}
/**
* Prints the exception stack trace if the {@link Prop#debug} flag is set.
* @param throwable exception
*/
public static void debug(final Throwable throwable) {
if(Prop.debug && throwable != null) stack(throwable);
}
/**
* Prints a string to standard error if the {@link Prop#debug} flag is set.
* @param string debug string
* @param ext text optional extensions
*/
public static void debug(final Object string, final Object... ext) {
if(Prop.debug) errln(string, ext);
}
/**
* Returns a string and replaces all % characters by the specified extensions
* (see {@link TokenBuilder#addExt} for details).
* @param string string to be extended
* @param ext text text extensions
* @return extended string
*/
public static String info(final Object string, final Object... ext) {
return Token.string(inf(string, ext));
}
/**
* Returns a token and replaces all % characters by the specified extensions
* (see {@link TokenBuilder#addExt} for details).
* @param string string to be extended
* @param ext text text extensions
* @return token
*/
public static byte[] inf(final Object string, final Object... ext) {
return new TokenBuilder().addExt(string, ext).finish();
}
/**
* Prints the current stack trace to System.err.
* @param message error message
*/
public static void stack(final String message) {
stack(message, Short.MAX_VALUE);
}
/**
* Prints the current stack trace to System.err.
* @param depth number of steps to print
*/
public static void stack(final int depth) {
stack("You're here:", depth);
}
/**
* Prints the current stack trace to System.err.
* @param message message
* @param depth number of steps to print
*/
private static void stack(final String message, final int depth) {
errln(message);
final String[] stack = toArray(new Throwable());
final int l = Math.min(Math.max(2, depth + 2), stack.length);
for(int s = 2; s < l; ++s) errln(stack[s]);
}
/**
* Prints the stack of the specified error to standard error.
* @param throwable error/exception instance
*/
public static void stack(final Throwable throwable) {
throwable.printStackTrace();
}
/**
* Returns an string array representation of the specified throwable.
* @param throwable throwable
* @return string array
*/
private static String[] toArray(final Throwable throwable) {
final StackTraceElement[] st = throwable.getStackTrace();
final int sl = st.length;
final String[] obj = new String[sl + 1];
obj[0] = throwable.toString();
for(int s = 0; s < sl; s++) obj[s + 1] = "\tat " + st[s];
return obj;
}
/**
* Starts the specified class in a separate process. A -D (daemon) flag will be added to the
* command-line options.
* @param clazz class to start
* @param args command-line arguments
* @return reference to a {@link Process} instance representing the started process
*/
public static Process start(final Class<?> clazz, final String... args) {
final String[] largs = { "java", "-Xmx" + Runtime.getRuntime().maxMemory(),
"-cp", System.getProperty("java.class.path") };
final StringList sl = new StringList().add(largs);
System.getProperties().forEach((key, value) -> {
if(key.toString().startsWith(Prop.DBPREFIX)) sl.add("-D" + key + '=' + value);
});
sl.add(clazz.getName()).add("-D").add(args);
try {
return new ProcessBuilder(sl.finish()).start();
} catch(final IOException ex) {
throw notExpected(ex);
}
}
/**
* Returns the error message of a process.
* @param process process
* @param timeout time out in milliseconds
* @return error message or {@code null}
*/
public static String error(final Process process, final int timeout) {
final int wait = 200, to = Math.max(timeout / wait, 1);
for(int c = 0; c < to; c++) {
try {
final int exit = process.exitValue();
if(exit == 1) return Token.string(new IOStream(process.getErrorStream()).read());
break;
} catch(final IllegalThreadStateException ex) {
debug(ex);
// process is still running
Performance.sleep(wait);
} catch(final IOException ex) {
// return error message of exception
return ex.getLocalizedMessage();
}
}
return null;
}
}
|
package com.udacity.gamedev.inputtestbed;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.Random;
public class BouncingBall extends InputAdapter {
private static final Color COLOR = Color.RED;
private static final float DRAG = 1.0f;
private static final float RADIUS_FACTOR = 1.0f / 20;
private static final float RADIUS_GROWTH_RATE = 1.5f;
private static final float MIN_RADIUS_MULTIPLIER = 0.1f;
private static final float ACCELERATION = 500.0f;
private static final float MAX_SPEED = 400.0f;
private static final float FOLLOW_MULTIPLIER = 2.0f;
private static final float KICK_VELOCITY = 500.0f;
Vector2 flickStart;
boolean flicking = false;
// TODO: Declare a Vector2 to hold the ball's target position
Vector2 targetPosition;
// TODO: Declare a boolean to hold whether the ball is following something (and set it to false)
boolean following=false;
float baseRadius;
float radiusMultiplier;
Vector2 position;
Vector2 velocity;
Viewport viewport;
public BouncingBall(Viewport viewport) {
this.viewport = viewport;
init();
}
public void init() {
position = new Vector2(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2);
velocity = new Vector2();
baseRadius = RADIUS_FACTOR * Math.min(viewport.getWorldWidth(), viewport.getWorldHeight());
radiusMultiplier = 1;
}
private void randomKick() {
Random random = new Random();
float angle = MathUtils.PI2 * random.nextFloat();
velocity.x += KICK_VELOCITY * MathUtils.cos(angle);
velocity.y += KICK_VELOCITY * MathUtils.sin(angle);
}
public void update(float delta) {
// Growing and shrinking
if (Gdx.input.isKeyPressed(Keys.Z)) {
radiusMultiplier += delta * RADIUS_GROWTH_RATE;
}
if (Gdx.input.isKeyPressed(Keys.X)) {
radiusMultiplier -= delta * RADIUS_GROWTH_RATE;
radiusMultiplier = Math.max(radiusMultiplier, MIN_RADIUS_MULTIPLIER);
}
// TODO: If we're following something, calculate the difference vector between the targetPosition and the ball's position
// TODO: Set the velocity to that vector times the FOLLOW_MULTIPLIER
if (following) {
Vector2 followVector = new Vector2(targetPosition.x - position.x, targetPosition.y - position.y);
velocity.x = FOLLOW_MULTIPLIER * followVector.x;
velocity.y = FOLLOW_MULTIPLIER * followVector.y;
}
// Movement
if (Gdx.input.isKeyPressed(Keys.LEFT)) {
velocity.x -= delta * ACCELERATION;
}
if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
velocity.x += delta * ACCELERATION;
}
if (Gdx.input.isKeyPressed(Keys.UP)) {
velocity.y += delta * ACCELERATION;
}
if (Gdx.input.isKeyPressed(Keys.DOWN)) {
velocity.y -= delta * ACCELERATION;
}
velocity.clamp(0, MAX_SPEED);
velocity.x -= delta * DRAG * velocity.x;
velocity.y -= delta * DRAG * velocity.y;
position.x += delta * velocity.x;
position.y += delta * velocity.y;
collideWithWalls(baseRadius * radiusMultiplier, viewport.getWorldWidth(), viewport.getWorldHeight());
}
private void collideWithWalls(float radius, float viewportWidth, float viewportHeight) {
if (position.x - radius < 0) {
position.x = radius;
velocity.x = -velocity.x;
}
if (position.x + radius > viewportWidth) {
position.x = viewportWidth - radius;
velocity.x = -velocity.x;
}
if (position.y - radius < 0) {
position.y = radius;
velocity.y = -velocity.y;
}
if (position.y + radius > viewportHeight) {
position.y = viewportHeight - radius;
velocity.y = -velocity.y;
}
}
public void render(ShapeRenderer renderer) {
renderer.set(ShapeType.Filled);
renderer.setColor(COLOR);
renderer.circle(position.x, position.y, baseRadius * radiusMultiplier);
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Keys.SPACE) {
randomKick();
}
if (keycode == Keys.R) {
init();
}
return true;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector2 worldClick = viewport.unproject(new Vector2(screenX, screenY));
if (worldClick.dst(position) < baseRadius * radiusMultiplier) {
Gdx.app.log("Ball", "Click in the ball, starting flick.");
flicking = true;
flickStart = worldClick;
} else {
// TODO: Set the target position
targetPosition = worldClick;
// TODO: Set the following flag
following=true;
}
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO: If we're following, then update the target position (remember to unproject the touch location)
if(following)
{
targetPosition=viewport.unproject(new Vector2(screenX,screenY));
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (flicking) {
flicking = false;
Vector2 flickEnd = viewport.unproject(new Vector2(screenX, screenY));
velocity.x += 3 * (flickEnd.x - flickStart.x);
velocity.y += 3 * (flickEnd.y - flickStart.y);
Gdx.app.log("Ball", "End flick");
}
// TODO: Reset the following flag
following=false;
return true;
}
}
|
package amai.org.conventions.events.activities;
import android.content.DialogInterface;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.ContextThemeWrapper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import amai.org.conventions.FeedbackActivity;
import amai.org.conventions.R;
import amai.org.conventions.ThemeAttributes;
import amai.org.conventions.events.DefaultEventFavoriteChangedListener;
import amai.org.conventions.events.ProgrammeConventionEvent;
import amai.org.conventions.events.ViewPagerAnimator;
import amai.org.conventions.events.adapters.SwipeableEventsViewOrHourAdapter;
import amai.org.conventions.events.holders.EventTimeViewHolder;
import amai.org.conventions.model.Convention;
import amai.org.conventions.model.ConventionEvent;
import amai.org.conventions.navigation.NavigationActivity;
import amai.org.conventions.networking.ModelRefresher;
import amai.org.conventions.utils.Dates;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView.OnHeaderClickListener;
public class ProgrammeActivity extends NavigationActivity implements OnHeaderClickListener, SwipeRefreshLayout.OnRefreshListener {
public static final String EXTRA_DELAY_SCROLLING = "DelayScrollingExtra";
private static final String STATE_PREVENT_SCROLLING = "StatePreventScrolling";
private static final String STATE_NAVIGATE_ICON_MODIFIED = "StateNavigateIconModified";
private SwipeableEventsViewOrHourAdapter adapter;
private StickyListHeadersListView listView;
private List<ProgrammeConventionEvent> events;
private Menu menu;
private boolean navigateToMyEventsIconModified = false;
private SwipeRefreshLayout swipeLayout;
private boolean cancelScroll;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentInContentContainer(R.layout.activity_programme);
setToolbarTitle(getResources().getString(R.string.programme_title));
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.programme_swipe_layout);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(ThemeAttributes.getColor(this, R.attr.toolbarBackground));
listView = (StickyListHeadersListView) findViewById(R.id.programmeList);
events = getEventList();
adapter = new SwipeableEventsViewOrHourAdapter(events);
listView.setAdapter(adapter);
adapter.setOnEventFavoriteChangedListener(new DefaultEventFavoriteChangedListener(listView) {
@Override
public void onEventFavoriteChanged(ConventionEvent updatedEvent) {
super.onEventFavoriteChanged(updatedEvent);
if (!navigateToMyEventsIconModified) {
navigateToMyEventsIconModified = true;
final MenuItem item = menu.findItem(R.id.programme_navigate_to_my_events);
View actionView = getLayoutInflater().inflate(R.layout.my_events_icon, null);
ImageView myEventsNonAnimatedIcon = (ImageView) actionView.findViewById(R.id.non_animated_icon);
int accentColor = ThemeAttributes.getColor(ProgrammeActivity.this, R.attr.toolbarIconAccentColor);
myEventsNonAnimatedIcon.setColorFilter(accentColor, PorterDuff.Mode.MULTIPLY);
final ImageView myEventsAnimatedIcon = (ImageView) actionView.findViewById(R.id.icon_to_animate);
AnimationSet set = new AnimationSet(true);
set.addAnimation(new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f));
set.addAnimation(new AlphaAnimation(1, 0));
set.setDuration(800);
myEventsAnimatedIcon.startAnimation(set);
item.setActionView(actionView);
set.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
item.setActionView(null);
changeIconColor(item);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
});
listView.setOnHeaderClickListener(this);
if (savedInstanceState != null && savedInstanceState.getBoolean(STATE_NAVIGATE_ICON_MODIFIED, false)) {
navigateToMyEventsIconModified = true;
}
if (savedInstanceState == null || !savedInstanceState.getBoolean(STATE_PREVENT_SCROLLING, false)) {
final int position = findHourPosition(Dates.now());
if (position != -1) {
cancelScroll = false;
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// For some reason if the user touches the list view after scrolling ends (before bounce), there is no down event
if (event.getActionMasked() == MotionEvent.ACTION_DOWN || event.getActionMasked() == MotionEvent.ACTION_MOVE) {
cancelScroll = true;
listView.setOnTouchListener(null);
}
return false;
}
});
final ViewTreeObserver vto = listView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
// Unregister the listener to only call scrollToPosition once
listView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int delay = getIntent().getIntExtra(EXTRA_DELAY_SCROLLING, 0);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
scrollToPosition(position, true);
}
}, delay);
}
});
}
}
}
@Override
protected void onRestart() {
super.onRestart();
// Always redraw the list during onResume, since it's a fast operation, and this ensures the data is up to date in case the activity got paused.
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.programme_menu, menu);
if (navigateToMyEventsIconModified) {
MenuItem item = menu.findItem(R.id.programme_navigate_to_my_events);
changeIconColor(item);
}
Convention convention = Convention.getInstance();
if (!convention.canFillFeedback()) {
menu.removeItem(R.id.programme_navigate_to_feedback);
} else if (convention.hasEnded() && !convention.getFeedback().isSent() && !convention.isFeedbackSendingTimeOver()) {
MenuItem item = menu.findItem(R.id.programme_navigate_to_feedback);
changeIconColor(item);
}
return true;
}
/**
* Change color of menu item icon to be accented
* @param item the menu item
* @return The new color
*/
private int changeIconColor(MenuItem item) {
Drawable icon = item.getIcon().mutate();
int accentColor = ThemeAttributes.getColor(ProgrammeActivity.this, R.attr.toolbarIconAccentColor);
icon.setColorFilter(accentColor, PorterDuff.Mode.MULTIPLY);
return accentColor;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.programme_navigate_to_my_events:
navigateToMyEventsIconModified = false;
item.getIcon().clearColorFilter();
navigateToActivity(MyEventsActivity.class);
return true;
case R.id.programme_navigate_to_feedback:
navigateToActivity(FeedbackActivity.class);
return true;
case R.id.programme_navigate_to_search:
navigateToActivity(ProgrammeSearchActivity.class, false, null);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(STATE_PREVENT_SCROLLING, true);
outState.putBoolean(STATE_NAVIGATE_ICON_MODIFIED, navigateToMyEventsIconModified);
super.onSaveInstanceState(outState);
}
@Override
public void onHeaderClick(StickyListHeadersListView stickyListHeadersListView, View view, int i, long l, boolean b) {
EventTimeViewHolder eventTimeViewHolder = (EventTimeViewHolder) view.getTag();
int selectedTimeSectionHour = eventTimeViewHolder.getCurrentHour();
// Setup number picker dialog
final NumberPicker numberPicker = new NumberPicker(this);
int minValue = events.get(0).getTimeSection().get(Calendar.HOUR_OF_DAY);
int maxValue = events.get(events.size() - 1).getTimeSection().get(Calendar.HOUR_OF_DAY);
numberPicker.setMinValue(minValue);
numberPicker.setMaxValue(maxValue);
List<String> values = new ArrayList<>(maxValue - minValue + 1);
for (int value = minValue; value <= maxValue; ++value) {
String hour = String.valueOf(value);
if (hour.length() == 1) {
hour = "0" + hour;
}
hour += ":00";
values.add(hour);
}
numberPicker.setDisplayedValues(values.toArray(new String[values.size()]));
numberPicker.setValue(selectedTimeSectionHour);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
AlertDialog dialog = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog))
.setView(numberPicker)
.setPositiveButton(R.string.select_hour_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
int position = findHourPosition(numberPicker.getValue());
if (position != -1) {
cancelScroll = false;
scrollToPosition(position, false);
}
}
})
.create();
dialog.show();
}
private void scrollToPosition(final int position, final boolean shouldApplyFavoriteReminderAnimation) {
if (!cancelScroll) {
listView.smoothScrollToPositionFromTop(position, 0, 500);
// There is a bug in smoothScrollToPositionFromTop that sometimes it doesn't scroll all the way.
// As a workaround, we listen to when it finished scrolling, and then scroll again to
// the same position.
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
listView.setOnScrollListener(null);
if (!cancelScroll) {
listView.smoothScrollToPositionFromTop(position, 0, 500);
// In some cases we'll want to show bounce animation to the scrolled view, to make it easier for users
// to understand the views are swipeable.
if (shouldApplyFavoriteReminderAnimation) {
listView.postDelayed(new Runnable() {
@Override
public void run() {
triggerBounceAnimationIfNeeded();
listView.setOnTouchListener(null);
}
}, 1500);
} else {
listView.setOnTouchListener(null);
}
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
}
}
private void triggerBounceAnimationIfNeeded() {
if (!Convention.getInstance().hasFavorites() && !cancelScroll) {
if (listView.getListChildCount() > 1) {
// Apply the animation on the second listView child, since the first will always be hidden by a sticky header
View currentEvent = listView.getListChildAt(1);
ViewPager currentEventViewPager = (ViewPager) currentEvent.findViewById(R.id.swipe_pager);
ViewPagerAnimator.applyBounceAnimation(currentEventViewPager);
}
}
}
private int findHourPosition(int hour) {
int i = 0;
for (ProgrammeConventionEvent event : events) {
// This is called from the hour popup, the date is not relevant in this case
if (event.getTimeSection().get(Calendar.HOUR_OF_DAY) >= hour) {
return i;
}
i++;
}
// If we got here it means the user selected an hour later then the last event. In this case,
// return the last position (which is i-1, since it's a zero based count)
return -1;
}
private int findHourPosition(Date time) {
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(time);
// Only keep up to the hour part
timeCalendar.set(Calendar.MINUTE, 0);
timeCalendar.set(Calendar.SECOND, 0);
timeCalendar.set(Calendar.MILLISECOND, 0);
int i = 0;
for (ProgrammeConventionEvent event : events) {
// This is called from the activity startup, we don't want to scroll if it's not the convention date
if (!event.getTimeSection().before(timeCalendar)) {
return i;
}
i++;
}
// If we got here it means the selected hour is after the last event ends so no scrolling is required
return -1;
}
private List<ProgrammeConventionEvent> getEventList() {
List<ConventionEvent> events = new ArrayList<>(Convention.getInstance().getEvents());
List<ProgrammeConventionEvent> programmeEvents = new LinkedList<>();
for (ConventionEvent event : events) {
// Convert the event start time to hourly time sections, and duplicate it if needed (e.g. if an event started at 13:30 and ended at 15:00, its
// time sections are 13:00 and 14:00)
int eventDurationInHours = getEndHour(event.getEndTime()) - getHour(event.getStartTime()) + 1;
for (int i = 0; i < eventDurationInHours; i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(event.getStartTime());
calendar.add(Calendar.HOUR_OF_DAY, i);
calendar.clear(Calendar.MINUTE);
programmeEvents.add(new ProgrammeConventionEvent(event, calendar));
}
}
Collections.sort(programmeEvents, new Comparator<ProgrammeConventionEvent>() {
@Override
public int compare(ProgrammeConventionEvent lhs, ProgrammeConventionEvent rhs) {
// First compare by sections
int result = lhs.getTimeSection().compareTo(rhs.getTimeSection());
// In the same section, compare by hall order
if (result == 0) {
result = lhs.getEvent().getHall().getOrder() - rhs.getEvent().getHall().getOrder();
}
// For 2 events in the same hall and section, compare by start time
if (result == 0) {
result = lhs.getEvent().getStartTime().compareTo(rhs.getEvent().getStartTime());
}
return result;
}
});
return programmeEvents;
}
private static int getHour(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
private static int getEndHour(Date endTime) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(endTime);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
// The first minute of the next hour is considered this hour. For example, an event
// ending at 12:00 is only considered to run during hour 11:00.
return minute > 0 ? hour : hour - 1;
}
@Override
public void onRefresh() {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
ModelRefresher modelRefresher = new ModelRefresher();
return modelRefresher.refreshFromServer();
}
@Override
protected void onPostExecute(Boolean isSuccess) {
swipeLayout.setRefreshing(false);
if (isSuccess) {
adapter.setItems(getEventList());
} else {
Toast.makeText(ProgrammeActivity.this, R.string.update_refresh_failed, Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
}
|
package com.birthstone.base.activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.birthstone.R;
/**
* @author
* ?
* */
public class UINavigationBar extends RelativeLayout implements View.OnClickListener{
private RelativeLayout mRelativeLayout;
private ImageView mIvLeft;
private ImageView mIvRight;
private TextView mTvLeft;
private int left_button_textColor;
private int left_button_textSize;
private TextView mTvTilte;
public static int BACKGROUND_COLOR = 0;
private String title_text;
private int title_textColor;
private int title_textSize;
private View line;
private TextView mTvRight;
private int right_button_image_id;
private String right_button_text;
private int right_button_textColor;
private int right_button_textSize;
private String left_button_text;
private int left_button_imageId;
/*
* navigationbar
* */
public IUINavigationBar UINavigationBarDelegat;
public UINavigationBar(Context context) {
super(context);
setId(R.id.uiNavigationBar);
initView(context);
}
public UINavigationBar(Context context,boolean isShowBtnBack){
super(context);
initView(context);
mIvLeft.setVisibility(isShowBtnBack?VISIBLE:GONE);
}
private void initView(Context context) {
View.inflate(context, R.layout.es_actionbar, this);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relay_background);
mIvLeft = (ImageView) findViewById(R.id.iv_left);
mIvLeft.setOnClickListener(this);
mTvLeft = (TextView) findViewById(R.id.tv_left);
mTvLeft.setOnClickListener(this);
mTvTilte = (TextView) findViewById(R.id.tv_title);
mTvRight = (TextView) findViewById(R.id.tv_right);
mTvRight.setOnClickListener(this);
mIvRight = (ImageView) findViewById(R.id.iv_right);
mIvRight.setOnClickListener(this);
line = findViewById(R.id.line);
mRelativeLayout.setBackgroundColor(BACKGROUND_COLOR);
}
/*
*
* @param color
* */
public static void setBarTintColor(int color){
BACKGROUND_COLOR = color;
}
public void setTitle(String tilte) {
if (TextUtils.isEmpty(tilte)) {
mTvTilte.setVisibility(GONE);
} else {
mTvTilte.setText(tilte);
mTvTilte.setVisibility(VISIBLE);
}
}
public void setLeftText(String text) {
if (TextUtils.isEmpty(text)) {
mTvLeft.setVisibility(GONE);
} else {
mTvLeft.setVisibility(VISIBLE);
mTvLeft.setText(text);
mIvLeft.setVisibility(GONE);
}
}
public void setLeftTextColor(int textColor) {
mTvLeft.setTextColor(textColor);
}
public void setRightText(String text) {
if (TextUtils.isEmpty(text)) {
mTvRight.setVisibility(GONE);
} else {
mTvRight.setVisibility(VISIBLE);
mTvRight.setText(text);
mIvRight.setVisibility(GONE);
}
}
/**
*
*
* @param textColor
*/
public void setRightTextColor(int textColor) {
mTvRight.setTextColor(textColor);
}
/**
*
*
* @param resId
*/
public void setLeftButtonImage(int resId) {
if (resId == 0) {
mIvLeft.setVisibility(View.GONE);
mTvLeft.setVisibility(View.VISIBLE);
} else {
mIvLeft.setVisibility(View.VISIBLE);
mIvLeft.setImageResource(resId);
mTvLeft.setVisibility(View.GONE);
}
}
/**
*
*
* @param resId
*/
public void setRightButtonImage(int resId) {
if (resId==0) {
mIvRight.setVisibility(View.GONE);
mTvRight.setVisibility(View.VISIBLE);
} else {
mIvRight.setVisibility(View.VISIBLE);
mIvRight.setImageResource(resId);
mTvRight.setVisibility(View.GONE);
}
}
/**
*
*
* @param visibility
*/
public void setLineIsVisible(int visibility) {
line.setVisibility(visibility);
}
/**
*
*
* @param visibility
*/
public void setRightButtonVisibility(int visibility) {
mIvRight.setVisibility(visibility);
}
/**
*
*
* @param visibility
*/
public void setLeftButtonVisibility(int visibility) {
mIvLeft.setVisibility(visibility);
}
/**
*
*
* @param resId
*/
public void setTitleBarBackground(int resId) {
mRelativeLayout.setBackgroundResource(resId);
}
public void setLeftViewClickListener(OnClickListener listener){
this.mIvLeft.setOnClickListener(listener);
this.mTvLeft.setOnClickListener(listener);
}
public void setRightViewClickListener(OnClickListener listener){
this.mIvRight.setOnClickListener(listener);
this.mTvRight.setOnClickListener(listener);
}
@Override
public void onClick(View view) {
if (view.getId()==R.id.iv_right || view.getId()==R.id.tv_right){
if (UINavigationBarDelegat!=null){
UINavigationBarDelegat.onRightClick();
}
}
if (view.getId()==R.id.iv_left || view.getId()==R.id.tv_left){
if (UINavigationBarDelegat!=null){
UINavigationBarDelegat.onLeftClick();
}
}
}
}
|
package com.angluswang.festival_sms.fragment;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.angluswang.festival_sms.R;
import com.angluswang.festival_sms.bean.SendedMsg;
import com.angluswang.festival_sms.db.SmsProvider;
import com.angluswang.festival_sms.view.FlowLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class SmsHistoryFragment extends ListFragment {
private static final int LOADER_ID = 1;
private LayoutInflater mInflater;
private CursorAdapter mCursorAdapter;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mInflater = LayoutInflater.from(getActivity());
initLoader();
setupListAdapter();
}
private void setupListAdapter() {
mCursorAdapter = new CursorAdapter(getActivity(), null, false) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.item_sended_msg, parent, false);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView msg = (TextView) view.findViewById(R.id.id_tv_msg);
FlowLayout fl = (FlowLayout) view.findViewById(R.id.id_fl_contacts);
TextView fes = (TextView) view.findViewById(R.id.id_tv_festival);
TextView date = (TextView) view.findViewById(R.id.id_tv_date);
msg.setText(cursor.getString(cursor.getColumnIndex(SendedMsg.COLUME_MSG)));
fes.setText(cursor.getString(cursor.getColumnIndex(SendedMsg.COLUME_FESTIVAL_NAME)));
long dateVal = cursor.getLong(cursor.getColumnIndex(SendedMsg.COLUME_DATE));
date.setText(ParseDate(dateVal));
String names = cursor.getString(cursor.getColumnIndex(SendedMsg.COLUME_NAMES));
if (TextUtils.isEmpty(names)) {
return;
}
fl.removeAllViews();
for (String name : names.split(":")) {
addTag(name, fl);
}
}
};
setListAdapter(mCursorAdapter);
}
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
private String ParseDate(long dateVal) {
return df.format(dateVal);
}
private void addTag(String name, FlowLayout fl) {
TextView view = (TextView) mInflater.inflate(R.layout.tag, fl, false);
view.setText(name);
fl.addView(view);
}
private void initLoader() {
getLoaderManager().initLoader(LOADER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(
getActivity(), SmsProvider.URI_SMS_ALL, null, null, null, null);
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == LOADER_ID) {
mCursorAdapter.swapCursor(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
});
}
}
|
package hageldave.imagingkit.core;
import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
import org.junit.Test;
import hageldave.imagingkit.core.PixelConvertingSpliterator.PixelConverter;
public class PixelConvertingSpliteratorTest {
@Test
public void testAll(){
Img img = new Img(1000,1000);
img.forEach(px->px.setB(1+(px.getIndex()%0xfe)));
assertEquals(1, img.getData()[0]);
Consumer<double[]> rotateChannels = (px) -> {double t=px[0]; px[0]=px[1]; px[1]=px[2]; px[2]=t;};
{
Spliterator<Pixel> delegate = img.spliterator();
Spliterator<double[]> split = PixelConvertingSpliterator.getDoubletArrayElementSpliterator(delegate);
assertTrue(split.hasCharacteristics(delegate.characteristics()));
assertEquals(img.numValues(), split.getExactSizeIfKnown());
LinkedList<Spliterator<double[]>> all = new LinkedList<>();
all.add(split);
int idx = 0;
while(idx < all.size()){
Spliterator<double[]> sp = all.get(idx);
Spliterator<double[]> child = sp.trySplit();
if(child != null){
all.add(child);
} else {
idx++;
}
}
for(Spliterator<double[]> iter: all){
iter.tryAdvance(rotateChannels);
iter.forEachRemaining(rotateChannels);
}
for(int i = 0; i < img.numValues(); i++){
// g channel will contain special value
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
}
}
{
img.setSpliteratorMinimumSplitSize(77);
Spliterator<double[]> split = PixelConvertingSpliterator.getDoubletArrayElementSpliterator(img.colSpliterator());
StreamSupport.stream(split, true).forEach(rotateChannels);
for(int i = 0; i < img.numValues(); i++){
// now r channel will contain special value
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.g(img.getData()[i]));
}
}
PixelConverter<double[]> converter = PixelConverter.fromFunctions(
()->new double[3],
(px,a)->{a[0]=px.r_normalized();a[1]=px.g_normalized();a[2]=px.b_normalized();},
(a,px)->{px.setRGB_fromNormalized_preserveAlpha(a[0], a[1], a[2]);});
{
img.forEach(converter, false, rotateChannels);
for(int i = 0; i < img.numValues(); i++){
// b now
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.b(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.g(img.getData()[i]));
}
img.forEach(converter, true, rotateChannels);
for(int i = 0; i < img.numValues(); i++){
// g again
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
}
img.forEach(converter, false, 0, 0, img.getWidth(), 1, rotateChannels);
for(int i = img.getWidth(); i < img.numValues(); i++){
// g for all except first row
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
}
for(int i = 0; i < img.getWidth(); i++){
// r for first row
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
}
img.forEach(converter, true, 0, 0, img.getWidth(), 1, rotateChannels);
for(int i = img.getWidth(); i < img.numValues(); i++){
// g for all except first row
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.b(img.getData()[i]));
}
for(int i = 0; i < img.getWidth(); i++){
// b for first row
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.g(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 1+(i%0xfe), Pixel.b(img.getData()[i]));
assertEquals("i="+i+" "+Integer.toHexString(img.getData()[i]), 0, Pixel.r(img.getData()[i]));
}
}
{
double sumb1 = img.stream().mapToDouble(px->px.b_normalized()).sum();
double sumb2 = img.stream(converter, false).mapToDouble(a->a[2]).sum();
assertNotEquals(0, sumb1, 0);
assertEquals(sumb1, sumb2, 0);
double sumg1 = img.stream().mapToDouble(px->px.g_normalized()).sum();
double sumg2 = img.stream(converter, true).mapToDouble(a->a[1]).sum();
assertNotEquals(0, sumg1, 0);
assertEquals(sumg1, sumg2, 0);
double sumw1 = img.stream(0, 0, img.getWidth(), 1).mapToDouble(px->px.r_normalized()+px.g_normalized()+px.b_normalized()).sum();
double sumw2 = img.stream(converter, false, 0, 0, img.getWidth(), 1).mapToDouble(a->a[0]+a[1]+a[2]).sum();
assertNotEquals(0, sumw1, 0);
assertEquals(sumw1, sumw2, 0);
}
}
}
|
package collections.implementations;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import collections.interfaces.ImmutableList;
public class ImmutableArrayList<E> //implements ImmutableList<E>
{
private final E[] _array;
private final int _length;
/**
* Constructs an empty list with an initial capacity of 0.
*/
public ImmutableArrayList ()
{
_array = (E[]) new Object[0];
_length = 0;
}
/**
* <p>Constructs a list containing the given elements
* <p>If the specified collection is null, constructs an empty ArrayList with a capacity of 0.
* @param elems - the collection whose elements are to be placed into this list
*/
public ImmutableArrayList (E... elems)
{
if(elems == null )
{
_array = (E[]) new Object[0];
_length = 0;
}
else
{
_array = elems;
_length = _array.length;
}
}
/**
* <p>Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
* <p>If the specified collection is null, constructs an empty ArrayList with a capacity of 0.
* @param elems - the collection whose elements are to be placed into this list
*/
public ImmutableArrayList(Collection<E> elems)
{
if(elems == null )
{
_array = (E[]) new Object[0];
_length = 0;
}
else
{
_array = (E[])elems.toArray();
_length = _array.length;
}
}
/**
* Private accessor to get the inner array.
* @return the inner array.
*/
private E[] getArray() {
return _array;
}
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return null;
}
public boolean isEmpty() { //TODO A tester
return _length == 0 ? true : false;
}
public int size() { //TODO tester.
return _length;
}
public E get(int index) { //TODO a tester
if(index >0 && index < _length)
return _array[index];
else
return null;
}
public int indexOf(E elem) {
// TODO Auto-generated method stub
return 0;
}
public E head() {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> tail() {
// TODO Auto-generated method stub
return null;
}
public E last() {
// TODO Auto-generated method stub
return null;
}
public List<E> subList(int from, int size) {
// TODO Auto-generated method stub
return null;
}
public List<E> reverse() {
// TODO Auto-generated method stub
return null;
}
public List<E> sort(Comparator<? super E> comparator) {
// TODO Auto-generated method stub
return null;
}
public boolean contains(E elem) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(Collection<E> elems) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(ImmutableList<E> elems) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(E... elems) {
// TODO Auto-generated method stub
return false;
}
public boolean any(Predicate<? super E> predicate) {
// TODO Auto-generated method stub
return false;
}
public boolean all(Predicate<? super E> predicate) {
// TODO Auto-generated method stub
return false;
}
public ImmutableList<E> cons(E elem) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> concat(Collection<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> concat(ImmutableList<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> concat(E... elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> concat(E elem) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> remove(Collection<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> remove(ImmutableList<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> remove(E... elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> remove(E elem) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> remove(int index) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> union(Collection<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> union(ImmutableList<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> union(E... elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> intersect(Collection<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> intersect(ImmutableList<E> elems) {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> intersect(E... elems) {
// TODO Auto-generated method stub
return null;
}
public <F> ImmutableList<F> map(Function<? super E, ? super F> mapper) {
// TODO Auto-generated method stub
return null;
}
public <F> ImmutableList<E> filter(Predicate<? super E> predicate) {
// TODO Auto-generated method stub
return null;
}
public Optional<E> reduce(BinaryOperator<E> accumulator) {
// TODO Auto-generated method stub
return null;
}
public E reduce(E identity, BinaryOperator<E> accumulator) {
// TODO Auto-generated method stub
return null;
}
public <F> F reduce(F identity, BiFunction<F, ? super E, F> accumulator,
BinaryOperator<F> combiner) {
// TODO Auto-generated method stub
return null;
}
public Stream<E> stream() {
// TODO Auto-generated method stub
return null;
}
public Stream<E> parallelStream() {
// TODO Auto-generated method stub
return null;
}
public ImmutableList<E> clone() {
// TODO Auto-generated method stub
return null;
}
public E[] toArray() {
// TODO Auto-generated method stub
return null;
}
public List<E> asList() {
// TODO Auto-generated method stub
return null;
}
}
|
package tddmicroexercises.textconvertor;
import static org.junit.Assert.*;
import org.junit.Test;
public class HtmlTextConverterTest {
@Test
public void should_set_the_filename_correctly() {
HtmlTextConverter converter = new HtmlTextConverter("foo");
assertEquals("fixme", converter.getFilename());
}
@Test
public void should_transform_peculiar_signs_into_html(){
}
}
|
package alma.alarmsystem.source;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Iterator;
import alma.acs.util.XmlNormalizer;
/**
* ACS implementation of the AlarmSystemInterface.
* The alarms are published in the logging.
*
* @author acaproni
*
*/
public class ACSAlarmSystemInterfaceProxy implements ACSAlarmSystemInterface {
// The logger to publish the alarms
private Logger m_logger;
// The name of the source
String name;
/**
* The basic constructor
*
* @param name The name of the source
* @param logger The logger to log alarms in
*/
public ACSAlarmSystemInterfaceProxy(String name, Logger logger) {
if (logger==null) {
throw new IllegalArgumentException("Invalid null logger in constructor");
}
this.name=name;
m_logger = logger;
m_logger.fine("Alarm source of "+name+" connected to the logging");
}
/**
* Set the source name.
* @param newSourceName the source name.
*/
public void setSourceName(String newSourceName) {
name = newSourceName;
}
/**
* Get the source name.
* @return the source name.
*/
public String getSourceName() {
return name;
}
/**
* Close and deallocate resources.
*/
public void close() {}
/**
* Push a fault state.
* @param state the fault state change to push.
* @throws ASIException if the fault state can not be pushed.
*/
public void push(ACSFaultState state) {
logFaultState(state);
}
/**
* Push a collection of fault states.
* @param states
* @throws ASIException if the fault state collection can not be pushed.
*/
public void push(Collection states) {
if (states==null || states.size()==0) {
return;
}
Iterator iterator = states.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
if (next instanceof ACSFaultState) {
push((ACSFaultState) next);
} else {
throw new IllegalArgumentException("states collection does not contain ACSFaultState instances");
}
}
}
/**
* Push the set of active fault states.
* @param active the active fault states.
* @throws ASIException if the fault state active list can not be pushed.
*/
public void pushActiveList(Collection active) {
if (active==null || active.size()==0) {
return;
}
push(active);
}
/**
* Write the ACSFaultState in the log
*
* @param fs The ACSFaultState to log
*/
private void logFaultState(ACSFaultState fs) {
if (fs==null) {
return;
}
StringBuilder sb = new StringBuilder("Alarm sent: <");
sb.append(fs.getFamily()+','+fs.getMember()+','+fs.getCode()+'>');
sb.append(" "+fs.getDescriptor());
m_logger.severe(XmlNormalizer.normalize(sb.toString()));
}
}
|
package net.protyposis.android.mediaplayerdemo;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import net.protyposis.android.mediaplayer.MediaPlayer;
import net.protyposis.android.mediaplayer.MediaSource;
import net.protyposis.android.mediaplayer.VideoView;
public class VideoViewActivity extends Activity {
private static final String TAG = VideoViewActivity.class.getSimpleName();
private VideoView mVideoView;
private ProgressBar mProgress;
private MediaController.MediaPlayerControl mMediaPlayerControl;
private MediaController mMediaController;
private Uri mVideoUri;
private int mVideoPosition;
private float mVideoPlaybackSpeed;
private boolean mVideoPlaying;
private MediaSource mMediaSource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videoview);
Utils.setActionBarSubtitleEllipsizeMiddle(this);
mVideoView = (VideoView) findViewById(R.id.vv);
mProgress = (ProgressBar) findViewById(R.id.progress);
mMediaPlayerControl = mVideoView; //new MediaPlayerDummyControl();
mMediaController = new MediaController(this);
mMediaController.setAnchorView(findViewById(R.id.container));
mMediaController.setMediaPlayer(mMediaPlayerControl);
mMediaController.setEnabled(false);
mProgress.setVisibility(View.VISIBLE);
// Init video playback state (will eventually be overwritten by saved instance state)
mVideoUri = getIntent().getData();
mVideoPosition = 0;
mVideoPlaybackSpeed = 1;
mVideoPlaying = false;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mVideoUri = savedInstanceState.getParcelable("uri");
mVideoPosition = savedInstanceState.getInt("position");
mVideoPlaybackSpeed = savedInstanceState.getFloat("playbackSpeed");
mVideoPlaying = savedInstanceState.getBoolean("playing");
}
@Override
protected void onResume() {
super.onResume();
initPlayer();
}
private void initPlayer() {
getActionBar().setSubtitle(mVideoUri+"");
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer vp) {
mProgress.setVisibility(View.GONE);
mMediaController.setEnabled(true);
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(VideoViewActivity.this,
"Cannot play the video, see logcat for the detailed exception",
Toast.LENGTH_LONG).show();
mProgress.setVisibility(View.GONE);
mMediaController.setEnabled(false);
return true;
}
});
mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
String whatName = "";
switch (what) {
case MediaPlayer.MEDIA_INFO_BUFFERING_END:
whatName = "MEDIA_INFO_BUFFERING_END";
break;
case MediaPlayer.MEDIA_INFO_BUFFERING_START:
whatName = "MEDIA_INFO_BUFFERING_START";
break;
case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
whatName = "MEDIA_INFO_VIDEO_RENDERING_START";
break;
case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
whatName = "MEDIA_INFO_VIDEO_TRACK_LAGGING";
break;
}
Log.d(TAG, "onInfo " + whatName);
return false;
}
});
mVideoView.setOnSeekListener(new MediaPlayer.OnSeekListener() {
@Override
public void onSeek(MediaPlayer mp) {
Log.d(TAG, "onSeek");
mProgress.setVisibility(View.VISIBLE);
}
});
mVideoView.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mp) {
Log.d(TAG, "onSeekComplete");
mProgress.setVisibility(View.GONE);
}
});
mVideoView.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "onBufferingUpdate " + percent + "%");
}
});
Utils.MediaSourceAsyncCallbackHandler mMediaSourceAsyncCallbackHandler =
new Utils.MediaSourceAsyncCallbackHandler() {
@Override
public void onMediaSourceLoaded(MediaSource mediaSource) {
mMediaSource = mediaSource;
mVideoView.setVideoSource(mediaSource);
mVideoView.seekTo(mVideoPosition);
mVideoView.setPlaybackSpeed(mVideoPlaybackSpeed);
if (mVideoPlaying) {
mVideoView.start();
}
}
@Override
public void onException(Exception e) {
Log.e(TAG, "error loading video", e);
}
};
if(mMediaSource == null) {
// Convert uri to media source asynchronously to avoid UI blocking
// It could take a while, e.g. if it's a DASH source and needs to be preprocessed
Utils.uriToMediaSourceAsync(this, mVideoUri, mMediaSourceAsyncCallbackHandler);
} else {
// Media source is already here, just use it
mMediaSourceAsyncCallbackHandler.onMediaSourceLoaded(mMediaSource);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.videoview, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_slowspeed) {
mVideoView.setPlaybackSpeed(0.2f);
return true;
} else if(id == R.id.action_halfspeed) {
mVideoView.setPlaybackSpeed(0.5f);
return true;
} else if(id == R.id.action_doublespeed) {
mVideoView.setPlaybackSpeed(2.0f);
return true;
} else if(id == R.id.action_quadspeed) {
mVideoView.setPlaybackSpeed(4.0f);
return true;
} else if(id == R.id.action_normalspeed) {
mVideoView.setPlaybackSpeed(1.0f);
return true;
} else if(id == R.id.action_seekcurrentposition) {
mVideoView.pause();
mVideoView.seekTo(mVideoView.getCurrentPosition());
return true;
} else if(id == R.id.action_seekcurrentpositionplus1ms) {
mVideoView.pause();
mVideoView.seekTo(mVideoView.getCurrentPosition()+1);
return true;
} else if(id == R.id.action_seektoend) {
mVideoView.pause();
mVideoView.seekTo(mVideoView.getDuration());
return true;
} else if(id == R.id.action_getcurrentposition) {
Toast.makeText(this, "current position: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mMediaController.isShowing()) {
mMediaController.hide();
} else {
mMediaController.show();
}
}
return super.onTouchEvent(event);
}
@Override
protected void onStop() {
mMediaController.hide();
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mVideoView != null) {
mVideoPosition = mVideoView.getCurrentPosition();
mVideoPlaybackSpeed = mVideoView.getPlaybackSpeed();
mVideoPlaying = mVideoView.isPlaying();
// the uri is stored in the base activity
outState.putParcelable("uri", mVideoUri);
outState.putInt("position", mVideoPosition);
outState.putFloat("playbackSpeed", mVideoView.getPlaybackSpeed());
outState.putBoolean("playing", mVideoPlaying);
}
}
}
|
package ca.ualberta.cs.cmput301t02project.test;
import junit.framework.TestCase;
import ca.ualberta.cs.cmput301t02project.controller.FavoritesController;
import ca.ualberta.cs.cmput301t02project.model.CommentListModel;
import ca.ualberta.cs.cmput301t02project.model.CommentModel;
public class FavoritesControllerTest extends TestCase {
FavoritesController controller;
CommentListModel model;
public FavoritesControllerTest(String name) {
super(name);
}
protected void setUp() throws Exception {
super.setUp();
model = new CommentListModel();
controller = new FavoritesController(model);
}
// Use Case 11 - KW
public void testFavoriteComment() {
CommentModel comment = new CommentModel("original text", null ,"username");
int oldRating = comment.getRating();
controller.favoriteComment(comment);
int newRating = comment.getRating();
assertEquals((oldRating+1), newRating);
}
}
|
package de.uni_hildesheim.sse.qmApp.editors;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import de.uni_hildesheim.sse.model.confModel.IDecisionVariable;
import de.uni_hildesheim.sse.qmApp.dialogs.DialogsUtil;
import de.uni_hildesheim.sse.qmApp.model.PipelineDiagramUtils;
/**
* Implements an (cell) editor dialog for modifying a set of constraints. Constraints
* are given in IVML syntax separated by {@link #SEPARATOR}.
*
* @author Holger Eichelberger
*/
class ConstraintsEditorDialog extends Dialog {
static final String SEPARATOR = PipelineDiagramUtils.CONSTRAINT_SEPARATOR;
private String constraints;
private TableViewer tableViewer;
private IDecisionVariable context;
private MenuManager manager;
/**
* Creates the dialog.
*
* @param context the IVML model element the constraint shall be defined in
* @param parentShell the parent shell
* @param constraints the constraints as text (IVML syntax, separated by ";")
*/
ConstraintsEditorDialog(Shell parentShell, IDecisionVariable context, String constraints) {
super(parentShell);
this.constraints = constraints;
this.context = context;
}
/**
* Splits the (possibly multiple) <code>constraints</code> into individual strings.
*
* @param constraints the constraints to split (IVML syntax, separated by {@link #SEPARATOR})
* @return the individual constraints as array
*/
static String[] splitConstraints(String constraints) {
return constraints.split(SEPARATOR);
}
/**
* Combines individual constraints given as Strings in IVML syntax.
*
* @param constraints the constraints to be combined
* @return the combined constraints string (using {@link #SEPARATOR} as separator)
*/
static String combineConstraints(String[] constraints) {
StringBuilder tmp = new StringBuilder();
for (int c = 0; c < constraints.length; c++) {
String constraint = constraints[c].trim();
if (constraint.length() > 0) {
if (tmp.length() > 0) {
tmp.append(SEPARATOR);
}
tmp.append(constraint);
}
}
return tmp.toString();
}
/**
* Returns the constraints as text.
*
* @return the constraints as text (IVML syntax, separated by ";")
*/
public String getConstraintsText() {
return constraints;
}
@Override
protected Control createDialogArea(Composite parent) {
final Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout(2, false));
Composite tablePanel = new Composite(composite, SWT.NONE);
tablePanel.setLayout(new GridLayout(1, false));
Label label = new Label(tablePanel, SWT.NONE);
label.setText("constraints:");
tableViewer = ConstraintsEditor.createTableViewer(tablePanel, false);
GridData gridData = new GridData();
gridData.widthHint = 400;
gridData.heightHint = 150;
gridData.verticalAlignment = SWT.FILL;
gridData.grabExcessVerticalSpace = true;
tableViewer.getTable().setLayoutData(gridData);
ConstraintsEditor.fillTable(splitConstraints(constraints), tableViewer);
Composite buttonPanel = new Composite(composite, SWT.NONE);
buttonPanel.setLayout(new GridLayout(1, false));
Button add = new Button(buttonPanel, SWT.PUSH);
add.setText("Add constraint");
add.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
addConstraint();
}
});
Button remove = new Button(buttonPanel, SWT.PUSH);
remove.setText("Remove constraint");
remove.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent evt) {
removeSelectedConstraint();
}
});
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
// IStructuredSelection does not work well until content provider is used
if (tableViewer == event.getSource()) {
editSelectedConstraint();
}
}
});
manager = new MenuManager();
tableViewer.getControl().setMenu(manager.createContextMenu(tableViewer.getControl()));
manager.add(new Action("Add constraint", null) {
@Override
public void run() {
addConstraint();
}
});
manager.add(new Action("Remove constraint", null) {
@Override
public void run() {
removeSelectedConstraint();
}
});
return composite;
}
/**
* Adds a new constraint.
*/
private void addConstraint() {
ConstraintEditorDialog dlg = new ConstraintEditorDialog(getShell(), context, null);
if (ConstraintEditorDialog.OK == dlg.open()) {
String constraint = dlg.getConstraintText();
if (constraint.length() > 0) {
TableItem item = new TableItem(tableViewer.getTable(), SWT.NULL);
item.setText(constraint);
}
}
}
/**
* Edits the selected constraint.
*/
private void editSelectedConstraint() {
TableItem[] selected = tableViewer.getTable().getSelection();
if (selected.length > 0) {
final TableItem item = selected[0]; // at max one from table
getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
ConstraintEditorDialog dlg = new ConstraintEditorDialog(getShell(), context, item.getText());
if (ConstraintEditorDialog.OK == dlg.open()) {
String constraint = dlg.getConstraintText();
item.setText(constraint);
tableViewer.refresh(item);
}
}
});
}
}
/**
* Removes the selected constraint.
*/
private void removeSelectedConstraint() {
int index = tableViewer.getTable().getSelectionIndex();
if (index >= 0) {
tableViewer.getTable().remove(index);
}
}
@Override
protected void okPressed() {
constraints = combineConstraints(ConstraintsEditor.getConstraints(tableViewer));
super.okPressed();
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Edit constraints");
DialogsUtil.centerShell(newShell);
}
@Override
protected Point getInitialSize() {
return new Point(650, 300);
}
@Override
public boolean close() {
manager.dispose();
return super.close();
}
}
|
package com.aha.userinterface;
import com.aha.businesslogic.model.Booking;
import com.aha.businesslogic.model.Flight;
import com.aha.businesslogic.model.Passenger;
import com.aha.businesslogic.model.Seat;
import com.aha.businesslogic.model.User;
import com.aha.data.BookingRepository;
import com.aha.data.UserRepository;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
/**
*
* @author simonicsanett
*/
public class SelectSeatForm extends javax.swing.JFrame {
UserRepository userRepository = new UserRepository();
BookingRepository repository = new BookingRepository();
private Flight flight;
private Seat selectedSeat;
private User user;
/**
* Form to
*
* @param flight
* @param user
*/
public SelectSeatForm(Flight flight, User user) {
this.flight = flight;
this.user = user;
initComponents();
flightNumberLabel.setText(String.valueOf(flight.getFlightNumber()));
jLabel3.setText(flight.getAirportFrom().getCity());
jLabel4.setText(flight.getAirportTo().getCity());
String date = new SimpleDateFormat("yyyy-MM-dd").format(flight.getDeparture());
jLabel5.setText(date);
drawSeatRadioButtons();
this.pack();
}
private void drawSeatRadioButtons() {
List<Seat> seats = flight.getSeats();
seatsPanel.setLayout(new GridLayout(0, 7, 0, 0));
// Empty label - top left
seatsPanel.add(new JLabel());
// Set title
for (char letter = 'A'; letter <= 'F'; letter++) {
JLabel label = new JLabel(String.valueOf(letter));
label.setHorizontalAlignment(JLabel.CENTER);
seatsPanel.add(label);
}
for (final Seat seat : seats) {
if (seat.getLetter().equals("A")) {
JLabel label = new JLabel(String.valueOf(seat.getRow()));
seatsPanel.add(label);
}
JRadioButton seatButton = new JRadioButton();
ActionListener seatButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectedSeat = seat;
selectSeatLabel.setText(seat.getRow() + seat.getLetter());
}
};
seatButton.addActionListener(seatButtonListener);
// Only allow booking there is no existing booking on seat
seatButton.setEnabled(seat.getBooking() == null);
seatButtonGroup.add(seatButton);
seatsPanel.add(seatButton);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
seatButtonGroup = new javax.swing.ButtonGroup();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
seatsPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
flightNumberLabel = new javax.swing.JLabel();
javax.swing.JLabel dateLabel = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
fromLabel = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
toLabel = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
selectSeatLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Select seat");
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
jLabel2.setText("Flight details:");
javax.swing.GroupLayout seatsPanelLayout = new javax.swing.GroupLayout(seatsPanel);
seatsPanel.setLayout(seatsPanelLayout);
seatsPanelLayout.setHorizontalGroup(
seatsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 248, Short.MAX_VALUE)
);
seatsPanelLayout.setVerticalGroup(
seatsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 374, Short.MAX_VALUE)
);
jPanel1.setLayout(new java.awt.GridLayout(5, 2, 0, 10));
jLabel1.setText("Flight number:");
jPanel1.add(jLabel1);
flightNumberLabel.setText("jLabel1");
jPanel1.add(flightNumberLabel);
dateLabel.setText("Date: ");
jPanel1.add(dateLabel);
jLabel5.setText("jLabel5");
jPanel1.add(jLabel5);
fromLabel.setText("From: ");
jPanel1.add(fromLabel);
jLabel3.setText("jLabel3");
jPanel1.add(jLabel3);
toLabel.setText("To: ");
jPanel1.add(toLabel);
jLabel4.setText("jLabel4");
jPanel1.add(jLabel4);
jLabel6.setText("Selected Seat: ");
jPanel1.add(jLabel6);
selectSeatLabel.setText("jLabel1");
selectSeatLabel.setName(""); // NOI18N
jPanel1.add(selectSeatLabel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(seatsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(okButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 351, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 56, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(44, 44, 44)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 84, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(cancelButton))
.addGap(69, 69, 69))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(seatsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
this.dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
if (selectedSeat != null) {
Booking booking = new Booking();
booking.setBookingNumber(flight.getFlightNumber() + selectedSeat.getRow() + selectedSeat.getLetter());
booking.setRow(selectedSeat.getRow());
booking.setLetter(selectedSeat.getLetter());
booking.setFlight(flight);
booking.setBookingDate(new Date());
selectedSeat.setBooking(booking);
booking.setPassenger((Passenger) userRepository.getUserById(user.getId()));
repository.addBooking(booking);
this.dispose();
}
else {
JOptionPane.showMessageDialog(null, "Please select a seat.");
}
}//GEN-LAST:event_okButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JLabel flightNumberLabel;
private javax.swing.JLabel fromLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JButton okButton;
private javax.swing.ButtonGroup seatButtonGroup;
private javax.swing.JPanel seatsPanel;
private javax.swing.JLabel selectSeatLabel;
private javax.swing.JLabel toLabel;
// End of variables declaration//GEN-END:variables
}
|
package org.splevo.utilities.metrics.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;
import org.splevo.utilities.metrics.calculator.MetricCalculationException;
import org.splevo.utilities.metrics.calculator.MetricResultItem;
import org.splevo.utilities.metrics.calculator.MetricsCalculator;
import org.splevo.utilities.metrics.calculator.MetricsResultSet;
/**
* The view to present metric results for the elements currently selected in the workbench.
*
* @author Benjamin Klatt
*
*/
public class MetricsView extends ViewPart implements ISelectionListener {
/** The id of the view. */
public static final String ID = "org.splevo.utilities.MetricsView"; //$NON-NLS-1$
/** The id of the metrics calculator extension point. */
private static final String METRICS_CALCULATOR_EXTENSION_POINT_ID = "org.splevo.utilities.metrics.calculator";
/** The id of the extension point calculator class. */
private static final String EXTENSION_POINT_ATTR_CALCULATOR_CLASS = "calculator.class";;
/** The list of currently selected items. */
private List<Object> selectedItems = new ArrayList<Object>();
/** The folder for the tabs. */
private TabFolder tabFolder = null;
/** The tab for the raw output. */
private TabItem tabRawOutput;
/** The text field for the result output. */
private Text metricResultOutput;
/**
* Default constructor.
*/
public MetricsView() {
}
/**
* Create contents of the view part.
*
* @param parent
* the parent
*/
@Override
public void createPartControl(Composite parent) {
Composite topContainer = new Composite(parent, SWT.FILL);
topContainer.setLayout(new FillLayout(SWT.HORIZONTAL));
tabFolder = new TabFolder(topContainer, SWT.BOTTOM);
createRawOutputTab(tabFolder);
createActions();
initializeToolBar();
initializeMenu();
ISelectionService selectionService = getSite().getWorkbenchWindow().getSelectionService();
selectionService.addSelectionListener(this);
}
/**
* Create the tab for the raw text output.
*
* @param tabFolder
* The tab folder to place the raw input tab in.
*/
private void createRawOutputTab(TabFolder tabFolder) {
tabRawOutput = new TabItem(tabFolder, SWT.NONE);
tabRawOutput.setText("Raw Output");
metricResultOutput = new Text(tabFolder, SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL
| SWT.MULTI);
tabRawOutput.setControl(metricResultOutput);
}
/**
* Create the actions.
*/
private void createActions() {
// Create the actions
}
/**
* Initialize the toolbar.
*/
@SuppressWarnings("unused")
private void initializeToolBar() {
IToolBarManager toolbarManager = getViewSite().getActionBars().getToolBarManager();
}
/**
* Initialize the menu.
*/
@SuppressWarnings("unused")
private void initializeMenu() {
IMenuManager menuManager = getViewSite().getActionBars().getMenuManager();
}
@Override
public void setFocus() {
// Set the focus
}
/**
* React on selection changes in the ui. {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
selectedItems = structuredSelection.toList();
updateMetricsView();
}
}
/**
* Update the metrics view by calculating the metrics for the selected items and trigger the
* result presentation.
*/
private void updateMetricsView() {
// remove all tab items except of the raw output
for (TabItem tabItem : tabFolder.getItems()) {
if (tabItem != tabRawOutput) {
tabItem.dispose();
}
}
// check that at least one item has been selected.
if (selectedItems == null || selectedItems.size() < 1) {
metricResultOutput.setText("Please select item(s) to calculate metrics.");
tabRawOutput.getParent().setSelection(1);
return;
}
try {
List<MetricsResultSet> resultSets = calculateMetrics(selectedItems);
for (MetricsResultSet metricsResultSet : resultSets) {
createResultTableTab(tabFolder, metricsResultSet);
}
updateRawOutput(resultSets);
} catch (MetricCalculationException e) {
System.err.println(e.getMessage());
}
}
/**
* Calculate the metrics.
*
* @param selectedItems
* the selected items
* @return The prepared result set.
* @throws MetricCalculationException
* Failed to calculate metrics.
*/
private List<MetricsResultSet> calculateMetrics(List<Object> selectedItems) throws MetricCalculationException {
List<MetricsResultSet> results = new ArrayList<MetricsResultSet>();
List<MetricsCalculator> calculators = getAvailableCalculators();
for (MetricsCalculator metricsCalculator : calculators) {
MetricsResultSet resultSet = metricsCalculator.calculateMetrics(selectedItems);
if (resultSet.getMetricResultItems().size() > 0 || resultSet.getTotalMetrics().size() > 0) {
results.add(resultSet);
}
}
// // File metrics
// CommonLOCMetricCalculator fileCalculator = new CommonLOCMetricCalculator();
// MetricsResultSet fileResultSet = fileCalculator.calculateMetrics(selectedItems);
// results.add(fileResultSet);
// // QVTo metrics
// QVToMetricCalculator qvtoCalculator = new QVToMetricCalculator();
// MetricsResultSet qvtoResultSet = qvtoCalculator.calculateMetrics(selectedItems);
// if (qvtoResultSet.getMetrics().size() > 0 || qvtoResultSet.getTotalMetrics().size() > 0) {
// results.add(qvtoResultSet);
return results;
}
/**
* Get the list of available metric calculators registered
* at the according extension point.
* @return The list of registered calculators.
*/
private List<MetricsCalculator> getAvailableCalculators() {
List<MetricsCalculator> calculators = new ArrayList<MetricsCalculator>();
IExtensionRegistry registry = Platform.getExtensionRegistry();
if (registry == null) {
System.err.println("No extension point registry available.");
return calculators;
}
IExtensionPoint extensionPoint = registry.getExtensionPoint(METRICS_CALCULATOR_EXTENSION_POINT_ID);
if (extensionPoint == null) {
System.err.println("No extension point found for the ID " + METRICS_CALCULATOR_EXTENSION_POINT_ID);
return null;
}
IExtension[] extensions = extensionPoint.getExtensions();
for (IExtension extension : extensions) {
IConfigurationElement[] configurations = extension.getConfigurationElements();
for (IConfigurationElement element : configurations) {
try {
Object o = element.createExecutableExtension(EXTENSION_POINT_ATTR_CALCULATOR_CLASS);
if ((o != null) && (o instanceof MetricsCalculator)) {
MetricsCalculator analyzer = (MetricsCalculator) o;
calculators.add(analyzer);
}
} catch (CoreException e) {
System.err.println("Failed to load metrics calculator extension ");
e.printStackTrace();
}
}
}
return calculators;
}
/**
* Update the textual output tab.
*
* @param resultSets
* The list of result sets to present.
*/
private void updateRawOutput(List<MetricsResultSet> resultSets) {
metricResultOutput.setText("");
StringBuilder metricsOutput = new StringBuilder();
for (MetricsResultSet metricsResultSet : resultSets) {
metricsOutput.append("==============================\n");
metricsOutput.append("=== METRIC SET: ");
metricsOutput.append(metricsResultSet.getId().toUpperCase());
metricsOutput.append(" ===\n");
metricsOutput.append("==============================\n");
for (MetricResultItem metricItem : metricsResultSet.getMetricResultItems()) {
metricsOutput.append(metricItem.getItemName());
for (String key : metricItem.keySet()) {
metricsOutput.append("\t");
metricsOutput.append(key);
metricsOutput.append("\t");
metricsOutput.append(metricItem.get(key).toString());
}
metricsOutput.append("\n");
}
metricsOutput.append("\n");
Map<String, Object> totalMetrics = metricsResultSet.getTotalMetrics();
if (totalMetrics.size() > 0) {
metricsOutput.append("
metricsOutput.append("Total Metrics\n");
for (String key : totalMetrics.keySet()) {
metricsOutput.append(key);
metricsOutput.append(":\t");
metricsOutput.append(totalMetrics.get(key).toString());
metricsOutput.append("\n");
}
}
}
metricResultOutput.setText(metricsOutput.toString());
}
/**
* Create a result set tab.
*
* @param tabFolder
* The tab folder to add the tab to.
* @param resultSet
* The result set to present on the tab.
*/
private void createResultTableTab(TabFolder tabFolder, MetricsResultSet resultSet) {
TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
tabItem.setText(resultSet.getId());
// initialize the table container
Composite overviewTabContainer = new Composite(tabFolder, SWT.NONE);
tabItem.setControl(overviewTabContainer);
FillLayout overviewTabContainerLayout = new FillLayout(SWT.VERTICAL);
overviewTabContainerLayout.spacing = 4;
overviewTabContainer.setLayout(overviewTabContainerLayout);
SashForm sashForm = new SashForm(overviewTabContainer, SWT.SMOOTH | SWT.VERTICAL);
sashForm.setSashWidth(2);
// Create the table for the detail metric results
TableViewer detailTableViewer = new TableViewer(sashForm, SWT.BORDER | SWT.FULL_SELECTION);
detailTableViewer.setContentProvider(ArrayContentProvider.getInstance());
Table detailTable = detailTableViewer.getTable();
detailTable.setLinesVisible(true);
detailTable.setHeaderVisible(true);
// Create the table for the total Results
TableViewer totalTableViewer = new TableViewer(sashForm, SWT.BORDER | SWT.FULL_SELECTION);
totalTableViewer.setContentProvider(ArrayContentProvider.getInstance());
Table totalTable = totalTableViewer.getTable();
totalTable.setLinesVisible(true);
totalTable.setHeaderVisible(true);
// create the metric name column
TableViewerColumn metricNameViewerColumn = new TableViewerColumn(totalTableViewer, SWT.FILL);
TableColumn metricNameColumn = metricNameViewerColumn.getColumn();
metricNameColumn.setText("Total Metric");
metricNameColumn.setResizable(true);
metricNameColumn.setMoveable(true);
metricNameColumn.setWidth(200);
metricNameViewerColumn.setLabelProvider(new MetricNameLabelProvider());
// create the metric name column
TableViewerColumn metricValueViewerColumn = new TableViewerColumn(totalTableViewer, SWT.FILL);
TableColumn metricValueColumn = metricValueViewerColumn.getColumn();
metricValueColumn.setText("Value");
metricValueColumn.setResizable(true);
metricValueColumn.setMoveable(true);
metricValueColumn.setWidth(200);
metricValueViewerColumn.setLabelProvider(new MetricValueLabelProvider());
sashForm.setWeights(new int[] { 2, 1 });
updateCommonTable(detailTableViewer, totalTableViewer, resultSet);
}
/**
* Update the common table for default presentation of result sets.
*
* @param detailTableViewer
* The table viewer for the detailed metric results.
* @param totalTableViewer
* The table viewer for the aggregated results.
* @param resultSet
* The result set to present.
*/
private void updateCommonTable(TableViewer detailTableViewer, TableViewer totalTableViewer,
MetricsResultSet resultSet) {
// remove the current input
// commonTableViewer.setInput(null);
// remove the current tables
TableColumn[] columns = detailTableViewer.getTable().getColumns();
for (TableColumn tc : columns) {
tc.dispose();
}
// create the item name column
TableViewerColumn itemNameViewerColumn = new TableViewerColumn(detailTableViewer, SWT.FILL);
TableColumn itemNameColumn = itemNameViewerColumn.getColumn();
itemNameColumn.setText("Item");
itemNameColumn.setResizable(true);
itemNameColumn.setMoveable(true);
itemNameColumn.setWidth(200);
itemNameViewerColumn.setLabelProvider(new ItemLabelProvider());
// create the metric columns
for (String metricKey : resultSet.getAvailableMetrics()) {
TableViewerColumn viewerColumn = new TableViewerColumn(detailTableViewer, SWT.FILL);
TableColumn column = viewerColumn.getColumn();
column.setText(metricKey);
column.setResizable(true);
column.setMoveable(true);
column.setWidth(200);
viewerColumn.setLabelProvider(new MetricLabelProvider(metricKey));
}
detailTableViewer.setInput(resultSet.getMetricResultItems());
detailTableViewer.refresh();
totalTableViewer.setInput(resultSet.getTotalMetrics().entrySet());
totalTableViewer.refresh();
}
@Override
public void dispose() {
ISelectionService selectionService = getSite().getWorkbenchWindow().getSelectionService();
selectionService.removeSelectionListener(this);
super.dispose();
}
}
|
package com.appspot.movevote.entity;
public class Constant {
public static final String INSING_HOSTNAME = "https:
public static final String DEV_HOSTNAME = "http://localhost:8888/";
public static final String PUB_HOSTNAME = "https://movevote.appspot.com/";
public static final String TMDB_API_KEY = "71fdea3ca66d6ddd2938d5c931e7ea82";
public static final String TMDB_HOSTNAME = "https://api.themoviedb.org/3/";
public static final String TMDB_IMAGE_URL = "https://image.tmdb.org/t/p/";
// tmdb poster size
public static final String TMDB_IMAGE_POSTER_SIZE = "w500";
public static final String TMDB_IMAGE_LOGO_SIZE = "w92";
public static final String TMDB_IMAGE_PROFILE_SIZE = "w45";
// movie provider
public static final String PROVIDER_INSING = "is";
public static final String PROVIDER_TMDB = "tmdb";
// Google Identity Toolkit
public static final String GIT_COOKIE_NAME = "gtoken";
public static final String GIT_SERVICE_ACCOUNT_EMAIL = "movevote@appspot.gserviceaccount.com";
public static final String GIT_CLIENT_ID = "123477425429910-r99e3tmjtvst1qsfp0ttk9gcs9ffbq68.apps.googleusercontent.com";
public static final String GIT_PROJECT_ID = "movevote";
public static final String GIT_DEV_WIDGET_URL = DEV_HOSTNAME + "gitkit";
public static final String GIT_PUB_WIDGET_URL = PUB_HOSTNAME + "gitkit";
public static final String LOGIN_PATH = "/gitkit?mode=select";
// MailJet
public static final String MAILJET_API_Key = "c5bac2520255752262e21a9bdff488e4";
public static final String MAILJET_Secret_Key = "ff41dd63e9d30dc8c2c84321c3f5246d";
// movie action
public static final String MOVIE_EVENT_ACTION_CLICK = "click";
public static final String MOVIE_EVENT_ACTION_RATE = "rate";
public static final String MOVIE_EVENT_ACTION_WANT_TO_WATCH = "want_to_watch";
public static final String MOVIE_EVENT_ACTION_WATCH = "watched";
public static final String MOVIE_EVENT_ACTION_SHOWTIME = "showtime";
// DataStore
// tables
public static final String DS_TABLE_INSING_MOVIE = "now_showing_insing_movie";
public static final String DS_TABLE_USER = "user";
public static final String DS_TABLE_MOVIE_EVENT = "movie_event";
public static final String DS_TABLE_TMDB_MOVIE = "tmdb_movie";
}
|
package com.devinhartzell.chess.board;
import javax.swing.JPanel;
import com.devinhartzell.chess.pieces.ChessPiece;
import com.devinhartzell.chess.pieces.NullPiece;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.border.LineBorder;
public class Square extends JPanel {
private static final long serialVersionUID = -7287090345533630180L;
private ChessPiece piece = new NullPiece(this.getX(), this.getY());
private boolean color;
private boolean selected;
private static boolean disableGraphicChanges = false;
private Graphics g;
public Square(final int x, final int y, boolean black) {
this.color = black;
if (black)
setBackground(Color.BLUE);
else
setBackground(Color.WHITE);
this.setLocation((50 * x) - 50 , (50 * y) - 50);
setSize(50, 50);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (piece.type != '0' && !getBackground().equals(Color.ORANGE) && piece.getColor() == Board.getTurn()) {
for (int i=1; i<=8; i++) {
for (int j=1; j<=8; j++) {
Board.getBoardArray()[i][j].setHighlighted(false);
Board.getBoardArray()[i][j].setSelected(false);
Board.getBoardArray()[i][j].repaint();
Board.getBoardArray()[i][j].revalidate();
}
}
for (Coordinate s : piece.getPossibleMoves()){
if (piece.getType() == 'k')
System.out.println(s.getX() + " " + s.getY());
Board.getBoardArray()[s.getX()][s.getY()].setHighlighted(true);
}
setSelected(true);
}
if (getBackground().equals(Color.ORANGE)) {
if (piece.getClass().equals(NullPiece.class)) {
piece.kill();
}
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
if (Board.getBoardArray()[i][j].selected) {
Board.getBoardArray()[i][j].getPiece().move(x, y);
Board.getBoardArray()[i][j].repaint();
}
}
}
}
}
});
}
public void setSelected(boolean b) {
this.selected = b;
}
public ChessPiece getPiece() {
return piece;
}
public void setHighlighted(boolean b) {
if (b) {
setBackground(Color.ORANGE);
setBorder(new LineBorder(new Color(0, 0, 128), 3));
} else {
if (color)
setBackground(Color.BLUE);
else
setBackground(Color.WHITE);
setBorder(new LineBorder(new Color(0, 0, 128), 0));
}
revalidate();
repaint();
}
public void setPiece(ChessPiece newpiece) {
this.piece = newpiece;
if (!disableGraphicChanges) {
try {
if (piece.getType() == '0')
g.drawImage(piece.getImage(), 5, 5, 1, 1, null);
else
g.drawImage(piece.getImage(), 5, 5, 40, 40, null);
} catch (NullPointerException npe) {}
repaint();
revalidate();
}
}
public boolean hasPiece() {
return !piece.isNull();
}
public static void setDisabledGraphics(boolean b) {
Square.disableGraphicChanges = b;
}
@Override
protected void paintComponent(Graphics g) {
if (!disableGraphicChanges) {
this.g = g;
try {
super.paintComponent(g);
if (piece.getType() == '0')
g.drawImage(piece.getImage(), 5, 5, 1, 1, null);
else
g.drawImage(piece.getImage(), 5, 5, 40, 40, null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package com.ecyrd.jspwiki.filters;
import java.util.*;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.TextUtil;
import org.apache.oro.text.*;
import org.apache.oro.text.regex.*;
import org.apache.log4j.Logger;
/**
* A regular expression-based spamfilter.
*
* @since 2.1.112
* @author Janne Jalkanen
*/
public class SpamFilter
extends BasicPageFilter
{
private String m_forbiddenWordsPage = "SpamFilterWordList";
private String m_errorPage = "RejectedMessage";
private static final String LISTVAR = "spamwords";
private PatternMatcher m_matcher = new Perl5Matcher();
private PatternCompiler m_compiler = new Perl5Compiler();
private Collection m_spamPatterns = null;
private Date m_lastRebuild = new Date( 0L );
static Logger log = Logger.getLogger( SpamFilter.class );
public static final String PROP_WORDLIST = "wordlist";
public static final String PROP_ERRORPAGE = "errorpage";
public void initialize( Properties properties )
{
m_forbiddenWordsPage = properties.getProperty( PROP_WORDLIST,
m_forbiddenWordsPage );
m_errorPage = properties.getProperty( PROP_ERRORPAGE,
m_errorPage );
}
private Collection parseWordList( WikiPage source, String list )
{
ArrayList compiledpatterns = new ArrayList();
if( list != null )
{
StringTokenizer tok = new StringTokenizer( list, " \t\n" );
while( tok.hasMoreTokens() )
{
String pattern = tok.nextToken();
try
{
compiledpatterns.add( m_compiler.compile( pattern ) );
}
catch( MalformedPatternException e )
{
log.debug( "Malformed spam filter pattern "+pattern );
source.setAttribute("error", "Malformed spam filter pattern "+pattern);
}
}
}
return compiledpatterns;
}
public String preSave( WikiContext context, String content )
throws RedirectException
{
WikiPage source = context.getEngine().getPage( m_forbiddenWordsPage );
if( source != null )
{
if( m_spamPatterns == null || m_spamPatterns.isEmpty() || source.getLastModified().after(m_lastRebuild) )
{
m_lastRebuild = source.getLastModified();
m_spamPatterns = parseWordList( source,
(String)source.getAttribute( LISTVAR ) );
log.info("Spam filter reloaded - recognizing "+m_spamPatterns.size()+" patterns from page "+m_forbiddenWordsPage);
}
}
// If we have no spam patterns defined, or we're trying to save
// the page containing the patterns, just return.
if( m_spamPatterns == null || context.getPage().getName().equals( m_forbiddenWordsPage ) )
{
return content;
}
for( Iterator i = m_spamPatterns.iterator(); i.hasNext(); )
{
Pattern p = (Pattern) i.next();
log.debug("Attempting to match page contents with "+p.getPattern());
if( m_matcher.contains( content, p ) )
{
// Spam filter has a match.
throw new RedirectException( "Content matches the spam filter '"+p.getPattern()+"'",
context.getEngine().getViewURL(m_errorPage) );
}
}
return content;
}
}
|
package com.essiembre.eclipse.rbe.ui;
import java.util.Locale;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* Utility methods related to application UI.
* @author Pascal Essiembre (essiembre@users.sourceforge.net)
* @version $Author$ $Revision$ $Date$
*/
public final class UIUtils {
/** Image registry. */
private static final ImageRegistry imageRegistry = new ImageRegistry();
/**
* Constructor.
*/
private UIUtils() {
super();
}
/**
* Creates a font by altering the font associated with the given control
* and applying the provided style (size is unaffected).
* @param control control we base our font data on
* @param style style to apply to the new font
* @return newly created font
*/
public static Font createFont(Control control, int style) {
//TODO consider dropping in favor of control-less version?
return createFont(control, style, 0);
}
/**
* Creates a font by altering the font associated with the given control
* and applying the provided style and relative size.
* @param control control we base our font data on
* @param style style to apply to the new font
* @param relSize size to add or remove from the control size
* @return newly created font
*/
public static Font createFont(Control control, int style, int relSize) {
//TODO consider dropping in favor of control-less version?
FontData[] fontData = control.getFont().getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(fontData[i].getHeight() + relSize);
fontData[i].setStyle(style);
}
return new Font(control.getDisplay(), fontData);
}
/**
* Creates a font by altering the system font
* and applying the provided style and relative size.
* @param style style to apply to the new font
* @return newly created font
*/
public static Font createFont(int style) {
return createFont(style, 0);
}
/**
* Creates a font by altering the system font
* and applying the provided style and relative size.
* @param style style to apply to the new font
* @param relSize size to add or remove from the control size
* @return newly created font
*/
public static Font createFont(int style, int relSize) {
Display display = RBEPlugin.getDefault().getWorkbench().getDisplay();
FontData[] fontData = display.getSystemFont().getFontData();
for (int i = 0; i < fontData.length; i++) {
fontData[i].setHeight(fontData[i].getHeight() + relSize);
fontData[i].setStyle(style);
}
return new Font(display, fontData);
}
/**
* Gets a system color.
* @param colorId SWT constant
* @return system color
*/
public static Color getSystemColor(int colorId) {
return RBEPlugin.getDefault().getWorkbench()
.getDisplay().getSystemColor(colorId);
}
/**
* Gets the approximate width required to display a given number of
* characters in a control.
* @param control the control on which to get width
* @param widthInChars the number of chars
* @return
*/
public static int getWidthInChars(Control control, int widthInChars) {
GC gc = new GC(control);
Point extent = gc.textExtent("W");//$NON-NLS-1$
gc.dispose();
return widthInChars * extent.x;
}
/**
* Shows an error dialog based on the supplied arguments.
* @param shell the shell
* @param exception the core exception
* @param msgKey key to the plugin message text
*/
public static void showErrorDialog(
Shell shell, CoreException exception, String msgKey) {
exception.printStackTrace();
ErrorDialog.openError(
shell,
RBEPlugin.getString(msgKey),
exception.getLocalizedMessage(),
exception.getStatus());
}
/**
* Shows an error dialog based on the supplied arguments.
* @param shell the shell
* @param exception the core exception
* @param msgKey key to the plugin message text
*/
public static void showErrorDialog(
Shell shell, Exception exception, String msgKey) {
exception.printStackTrace();
IStatus status = new Status(
IStatus.ERROR,
RBEPlugin.ID,
0,
RBEPlugin.getString(msgKey) + " "
+ RBEPlugin.getString("error.seeLogs"),
exception);
ErrorDialog.openError(
shell,
RBEPlugin.getString(msgKey),
exception.getLocalizedMessage(),
status);
}
public static String getDisplayName(Locale locale) {
if (locale == null) {
return RBEPlugin.getString("editor.default");
}
return locale.getDisplayName();
}
public static Image getImage(String imageName) {
Image image = imageRegistry.get(imageName);
if (image == null) {
image = RBEPlugin.getImageDescriptor(imageName).createImage();
imageRegistry.put(imageName, image);
}
return image;
}
}
|
package com.gh4a.adapter;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.gh4a.R;
import com.gh4a.loader.NotificationHolder;
import com.gh4a.utils.StringUtils;
import com.gh4a.utils.UiUtils;
import org.eclipse.egit.github.core.Notification;
import org.eclipse.egit.github.core.NotificationSubject;
import org.eclipse.egit.github.core.Repository;
public class NotificationAdapter extends
RootAdapter<NotificationHolder, NotificationAdapter.ViewHolder> {
private static final int VIEW_TYPE_NOTIFICATION_HEADER = RootAdapter.CUSTOM_VIEW_TYPE_START + 1;
private static final String SUBJECT_ISSUE = "Issue";
private static final String SUBJECT_PULL_REQUEST = "PullRequest";
private static final String SUBJECT_COMMIT = "Commit";
public interface OnNotificationActionCallback {
void markAsRead(NotificationHolder notificationHolder);
void unsubscribe(NotificationHolder notificationHolder);
}
private final int mTopBottomMargin;
private final int mBottomPadding;
private final Context mContext;
private final OnNotificationActionCallback mActionCallback;
public NotificationAdapter(Context context, OnNotificationActionCallback actionCallback) {
super(context);
mContext = context;
mActionCallback = actionCallback;
Resources resources = context.getResources();
mTopBottomMargin = resources.getDimensionPixelSize(R.dimen.card_top_bottom_margin);
mBottomPadding = resources.getDimensionPixelSize(R.dimen.notification_card_padding_bottom);
}
public void markAsRead(@Nullable Repository repository, @Nullable Notification notification) {
NotificationHolder previousRepoItem = null;
int notificationsInSameRepoCount = 0;
boolean isMarkingSingleNotification = repository == null && notification != null;
for (int i = 0; i < getCount(); i++) {
NotificationHolder item = getItem(i);
// Passing both repository and notification as null will mark everything as read
if ((repository == null && notification == null)
|| (repository != null && item.repository.equals(repository))
|| (item.notification != null && item.notification.equals(notification))) {
item.setIsRead(true);
}
// When marking single notification as read also mark the repository if it contained
// only 1 notification
if (isMarkingSingleNotification) {
if (item.notification == null) {
if (previousRepoItem != null && notificationsInSameRepoCount == 1
&& previousRepoItem.repository.equals(notification.getRepository())) {
previousRepoItem.setIsRead(true);
}
previousRepoItem = item;
notificationsInSameRepoCount = 0;
} else {
notificationsInSameRepoCount += 1;
}
}
}
// Additional check for the very last notification
if (isMarkingSingleNotification && previousRepoItem != null
&& notificationsInSameRepoCount == 1
&& previousRepoItem.repository.equals(notification.getRepository())) {
previousRepoItem.setIsRead(true);
}
notifyDataSetChanged();
}
@Override
protected ViewHolder onCreateViewHolder(LayoutInflater inflater, ViewGroup parent,
int viewType) {
int layoutResId = viewType == VIEW_TYPE_NOTIFICATION_HEADER
? R.layout.row_notification_header
: R.layout.row_notification;
View v = inflater.inflate(layoutResId, parent, false);
return new ViewHolder(v, mActionCallback);
}
@Override
protected int getItemViewType(NotificationHolder item) {
if (item.notification == null) {
return VIEW_TYPE_NOTIFICATION_HEADER;
}
return super.getItemViewType(item);
}
@Override
protected void onBindViewHolder(ViewHolder holder, NotificationHolder item) {
holder.ivAction.setTag(item);
float alpha = item.isRead() ? 0.5f : 1f;
holder.tvTitle.setAlpha(alpha);
if (item.notification == null) {
holder.ivAction.setVisibility(item.isRead() ? View.GONE : View.VISIBLE);
Repository repository = item.repository;
holder.tvTitle.setText(repository.getOwner().getLogin() + "/" + repository.getName());
return;
}
holder.ivIcon.setAlpha(alpha);
holder.tvTimestamp.setAlpha(alpha);
holder.mPopupMenu.getMenu().findItem(R.id.mark_as_read).setVisible(!item.isRead());
NotificationSubject subject = item.notification.getSubject();
int iconResId = getIconResId(subject.getType());
if (iconResId > 0) {
holder.ivIcon.setImageResource(iconResId);
holder.ivIcon.setVisibility(View.VISIBLE);
} else {
holder.ivIcon.setVisibility(View.INVISIBLE);
}
holder.tvTitle.setText(subject.getTitle());
holder.tvTimestamp.setText(StringUtils.formatRelativeTime(mContext,
item.notification.getUpdatedAt(), true));
int bottomPadding = item.isLastRepositoryNotification() ? mBottomPadding : 0;
holder.cvCard.setContentPadding(0, 0, 0, bottomPadding);
ViewGroup.MarginLayoutParams layoutParams =
(ViewGroup.MarginLayoutParams) holder.cvCard.getLayoutParams();
int bottomMargin = item.isLastRepositoryNotification() ? mTopBottomMargin : 0;
layoutParams.setMargins(0, 0, 0, bottomMargin);
holder.cvCard.setLayoutParams(layoutParams);
}
private int getIconResId(String subjectType) {
if (SUBJECT_ISSUE.equals(subjectType)) {
return UiUtils.resolveDrawable(mContext, R.attr.issueIcon);
}
if (SUBJECT_PULL_REQUEST.equals(subjectType)) {
return UiUtils.resolveDrawable(mContext, R.attr.pullRequestIcon);
}
if (SUBJECT_COMMIT.equals(subjectType)) {
return UiUtils.resolveDrawable(mContext, R.attr.commitIcon);
}
return -1;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
PopupMenu.OnMenuItemClickListener {
public ViewHolder(View view, OnNotificationActionCallback actionCallback) {
super(view);
mActionCallback = actionCallback;
ivAction = (ImageView) view.findViewById(R.id.iv_action);
ivAction.setOnClickListener(this);
ivIcon = (ImageView) view.findViewById(R.id.iv_icon);
tvTitle = (TextView) view.findViewById(R.id.tv_title);
cvCard = (CardView) view.findViewById(R.id.cv_card);
tvTimestamp = (TextView) view.findViewById(R.id.tv_timestamp);
mPopupMenu = new PopupMenu(view.getContext(), ivAction);
mPopupMenu.getMenuInflater().inflate(R.menu.notification_menu, mPopupMenu.getMenu());
mPopupMenu.setOnMenuItemClickListener(this);
}
private final ImageView ivIcon;
private final ImageView ivAction;
private final TextView tvTitle;
private final CardView cvCard;
private final TextView tvTimestamp;
private final PopupMenu mPopupMenu;
private final OnNotificationActionCallback mActionCallback;
@Override
public void onClick(View v) {
if (v.getId() == R.id.iv_action) {
NotificationHolder notificationHolder = (NotificationHolder) v.getTag();
if (notificationHolder.notification == null) {
mActionCallback.markAsRead(notificationHolder);
} else {
mPopupMenu.show();
}
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
NotificationHolder notificationHolder = (NotificationHolder) ivAction.getTag();
switch (item.getItemId()) {
case R.id.mark_as_read:
mActionCallback.markAsRead(notificationHolder);
return true;
case R.id.unsubscribe:
mActionCallback.unsubscribe(notificationHolder);
return true;
}
return false;
}
}
}
|
package com.haskforce.parsing;
import com.haskforce.parsing.jsonParser.JsonParser;
import com.haskforce.parsing.srcExtsDatatypes.*;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import static com.haskforce.parsing.HaskellTypes2.*;
// These can be imported as * when the old parser is removed.
import static com.haskforce.psi.HaskellTypes.OPENPRAGMA;
import static com.haskforce.psi.HaskellTypes.CLOSEPRAGMA;
import static com.haskforce.psi.HaskellTypes.OPENCOM;
import static com.haskforce.psi.HaskellTypes.CLOSECOM;
import static com.haskforce.psi.HaskellTypes.CPPIF;
import static com.haskforce.psi.HaskellTypes.CPPELSE;
import static com.haskforce.psi.HaskellTypes.CPPENDIF;
import static com.haskforce.psi.HaskellTypes.COMMENT;
import static com.haskforce.psi.HaskellTypes.COMMENTTEXT;
import static com.haskforce.psi.HaskellTypes.DOUBLEQUOTE;
import static com.haskforce.psi.HaskellTypes.STRINGTOKEN;
import static com.haskforce.psi.HaskellTypes.BADSTRINGTOKEN;
import static com.haskforce.psi.HaskellTypes.MODULE;
import static com.haskforce.psi.HaskellTypes.WHERE;
import static com.haskforce.psi.HaskellTypes.PRAGMA;
import static com.haskforce.psi.HaskellTypes.EQUALS;
import static com.haskforce.psi.HaskellTypes.IMPORT;
import static com.haskforce.psi.HaskellTypes.QUALIFIED;
import static com.haskforce.psi.HaskellTypes.HIDING;
import static com.haskforce.psi.HaskellTypes.PERIOD;
import static com.haskforce.psi.HaskellTypes.DOUBLEPERIOD;
import static com.haskforce.psi.HaskellTypes.RPAREN;
import static com.haskforce.psi.HaskellTypes.LPAREN;
import static com.haskforce.psi.HaskellTypes.RBRACKET;
import static com.haskforce.psi.HaskellTypes.LBRACKET;
import static com.haskforce.psi.HaskellTypes.AS;
import static com.haskforce.psi.HaskellTypes.TYPE;
import static com.haskforce.psi.HaskellTypes.DATA;
import static com.haskforce.psi.HaskellTypes.IN;
import static com.haskforce.psi.HaskellTypes.DOUBLECOLON;
import static com.haskforce.psi.HaskellTypes.COLON;
import static com.haskforce.psi.HaskellTypes.COMMA;
import static com.haskforce.psi.HaskellTypes.RIGHTARROW;
import static com.haskforce.psi.HaskellTypes.LEFTARROW;
import static com.haskforce.psi.HaskellTypes.MINUS;
import static com.haskforce.psi.HaskellTypes.DO;
import static com.haskforce.psi.HaskellTypes.BACKSLASH;
import static com.haskforce.psi.HaskellTypes.HASH;
import static com.haskforce.psi.HaskellTypes.FOREIGN;
import static com.haskforce.psi.HaskellTypes.EXPORTTOKEN;
import static com.haskforce.psi.HaskellTypes.DOUBLEARROW;
import static com.haskforce.psi.HaskellTypes.BACKTICK;
import static com.haskforce.psi.HaskellTypes.INSTANCE;
import static com.haskforce.psi.HaskellTypes.LBRACE;
import static com.haskforce.psi.HaskellTypes.RBRACE;
import static com.haskforce.psi.HaskellTypes.EXLAMATION; // FIXME: Rename.
import static com.haskforce.psi.HaskellTypes.PIPE;
import static com.haskforce.psi.HaskellTypes.CHARTOKEN;
import static com.haskforce.psi.HaskellTypes.LET;
import static com.haskforce.psi.HaskellTypes.INTEGERTOKEN;
import static com.haskforce.psi.HaskellTypes.VARIDREGEXP;
import static com.haskforce.psi.HaskellTypes.ASTERISK;
import static com.haskforce.psi.HaskellTypes.SINGLEQUOTE;
import static com.haskforce.psi.HaskellTypes.DEFAULT;
import static com.haskforce.psi.HaskellTypes.AMPERSAT;
import static com.haskforce.psi.HaskellTypes.PLUS;
import static com.haskforce.psi.HaskellTypes.TILDE;
import static com.haskforce.psi.HaskellTypes.THEN;
import static com.haskforce.psi.HaskellTypes.CASE;
import static com.haskforce.psi.HaskellTypes.OF;
import static com.haskforce.psi.HaskellTypes.SEMICOLON;
import static com.haskforce.psi.HaskellTypes.DERIVING;
import static com.haskforce.psi.HaskellTypes.FLOATTOKEN;
import static com.haskforce.psi.HaskellTypes.IF;
import static com.haskforce.psi.HaskellTypes.ELSE;
import static com.haskforce.psi.HaskellTypes.QUESTION;
import static com.haskforce.psi.HaskellTypes.PERCENT;
import static com.haskforce.psi.HaskellTypes.CLASSTOKEN;
import static com.haskforce.psi.HaskellTypes.DOLLAR;
import static com.haskforce.psi.HaskellTypes.THQUOTE;
import static com.haskforce.psi.HaskellTypes.CONID;
import static com.haskforce.psi.HaskellTypes.FORALLTOKEN;
/**
* New Parser using parser-helper.
*/
public class HaskellParser2 implements PsiParser {
private static final Logger LOG = Logger.getInstance(HaskellParser2.class);
private final Project myProject;
private final JsonParser myJsonParser;
public HaskellParser2(@NotNull Project project) {
myProject = project;
myJsonParser = new JsonParser(project);
}
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
PsiBuilder.Marker rootMarker = builder.mark();
TopPair tp = myJsonParser.parse(builder.getOriginalText());
if (tp.error != null && !tp.error.isEmpty()) {
// TODO: Parse failed. Possibly warn. Could be annoying.
}
try {
IElementType e = builder.getTokenType();
while (!builder.eof() && (isInterruption(e) && e != OPENPRAGMA)) {
if (e == COMMENT || e == OPENCOM) {
parseComment(e, builder, tp.comments);
e = builder.getTokenType();
} else if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
// Ignore CPP-tokens, they are not fed to parser-helper anyways.
builder.advanceLexer();
e = builder.getTokenType();
} else {
throw new ParserErrorException("Unexpected failure on: " +
(e == null ? "" : e.toString()));
}
}
parseModule(builder, (Module) tp.moduleType, tp.comments);
} catch (ParserErrorException e1) {
rootMarker.rollbackTo();
PsiBuilder.Marker newRoot = builder.mark();
final PsiBuilder.Marker errorMark = builder.mark();
while (!builder.eof()) {
builder.advanceLexer();
}
errorMark.error(e1.getMessage());
newRoot.done(root);
return builder.getTreeBuilt();
}
return chewEverything(rootMarker, root, builder);
}
private static ASTNode chewEverything(PsiBuilder.Marker marker, IElementType e, PsiBuilder builder) {
while (!builder.eof()) {
builder.advanceLexer();
}
marker.done(e);
ASTNode result = builder.getTreeBuilt();
// System.out.println("Psifile:" + builder.getTreeBuilt().getPsi().getContainingFile().getName());
return result;
}
/**
* Parses a complete module.
*/
private static void parseModule(PsiBuilder builder, Module module, Comment[] comments) {
parseModulePragmas(builder, module == null ? null : module.modulePragmas, comments);
parseModuleHead(builder, module == null ? null : module.moduleHeadMaybe, comments);
parseImportDecls(builder, module == null ? null : module.importDecls, comments);
parseBody(builder, module == null ? null : module.decls, comments);
}
/**
* Parses "module NAME [modulepragmas] [exportSpecList] where".
*/
private static void parseModuleHead(PsiBuilder builder, ModuleHead head, Comment[] comments) {
IElementType e = builder.getTokenType();
if (e != MODULE) return;
PsiBuilder.Marker moduleMark = builder.mark();
consumeToken(builder, MODULE);
parseModuleName(builder, head == null ? null : head.moduleName, comments);
// TODO: parseExportSpecList(builder, head.exportSpecList, comments);
IElementType e2 = builder.getTokenType();
while (e2 != WHERE) {
if (e2 == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
} else {
builder.advanceLexer();
}
e2 = builder.getTokenType();
}
consumeToken(builder, WHERE);
moduleMark.done(e);
}
private static void parseModuleName(PsiBuilder builder, ModuleName name, Comment[] comments) {
IElementType e = builder.getTokenType(); // Need to getTokenType to advance lexer over whitespace.
int startPos = builder.getCurrentOffset();
while ((name != null &&
(builder.getCurrentOffset() - startPos) < name.name.length()) ||
name == null && (e != WHERE && e != LPAREN)) {
consumeToken(builder, CONID);
e = builder.getTokenType();
if (e == PERIOD) consumeToken(builder, PERIOD);
}
}
/**
* Parses a list of import statements.
*/
private static void parseImportDecls(PsiBuilder builder, ImportDecl[] importDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (isInterruption(e) ||
importDecls != null && i < importDecls.length) {
if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
builder.advanceLexer();
e = builder.getTokenType();
continue;
} else if (e == OPENCOM) {
parseComment(e, builder, comments);
e = builder.getTokenType();
continue;
} else if (e == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
e = builder.getTokenType();
continue;
}
if (e != IMPORT) return;
parseImportDecl(builder, importDecls[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Returns true for elements that can occur anywhere in the tree,
* for example comments or pragmas.
*/
private static boolean isInterruption(IElementType e) {
return (e == CPPIF || e == CPPELSE || e == CPPENDIF || e == OPENCOM ||
e == OPENPRAGMA);
}
/**
* Parses an import statement.
*/
private static void parseImportDecl(PsiBuilder builder, ImportDecl importDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker importMark = builder.mark();
consumeToken(builder, IMPORT);
IElementType e2 = builder.getTokenType();
if (e2 == QUALIFIED || (importDecl != null && importDecl.importQualified)) {
consumeToken(builder, QUALIFIED);
}
parseModuleName(builder, importDecl == null ? null : importDecl.importModule, comments);
e2 = builder.getTokenType();
if (e2 == AS || false) { // TODO: Update.
consumeToken(builder, AS);
e2 = builder.getTokenType();
parseModuleName(builder, importDecl == null ? null : importDecl.importAs, comments);
e2 = builder.getTokenType();
}
if (e2 == HIDING || false) { // (importDecl != null && importDecl.importSpecs)) { TODO: FIXME
consumeToken(builder, HIDING);
e2 = builder.getTokenType();
}
int nest = e2 == LPAREN ? 1 : 0;
while (nest > 0) {
builder.advanceLexer();
e2 = builder.getTokenType();
if (e2 == LPAREN) {
nest++;
} else if (e2 == RPAREN) {
nest
}
}
if (e2 == RPAREN) consumeToken(builder, RPAREN);
importMark.done(IMPDECL);
}
/**
* Parses a foreign import statement.
*/
private static void parseForeignImportDecl(PsiBuilder builder, ForImp importDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, FOREIGN);
consumeToken(builder, IMPORT);
IElementType e2 = builder.getTokenType();
builder.advanceLexer(); // TODO: Parse 'ccall' etc.
e2 = builder.getTokenType();
if (e2 != DOUBLEQUOTE) { // TODO: Parse safety.
builder.advanceLexer();
e2 = builder.getTokenType();
}
if (e2 == DOUBLEQUOTE || false) {
parseStringLiteral(builder);
}
e2 = builder.getTokenType();
parseName(builder, importDecl.name, comments);
e2 = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, importDecl.type, comments);
}
/**
* Parses a foreign export statement.
*/
private static void parseForeignExportDecl(PsiBuilder builder, ForExp forExp, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, FOREIGN);
e = builder.getTokenType();
consumeToken(builder, EXPORTTOKEN);
IElementType e2 = builder.getTokenType();
builder.advanceLexer(); // TODO: Parse 'ccall' etc.
e2 = builder.getTokenType();
if (e2 == DOUBLEQUOTE || false) {
parseStringLiteral(builder);
}
e2 = builder.getTokenType();
parseName(builder, forExp.name, comments);
e2 = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, forExp.type, comments);
}
private static void parseBody(PsiBuilder builder, DeclTopType[] decls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (isInterruption(e) ||
decls != null && i < decls.length) {
if (e == CPPIF || e == CPPELSE || e == CPPENDIF) {
builder.advanceLexer();
e = builder.getTokenType();
continue;
} else if (e == OPENCOM) {
parseComment(e, builder, comments);
e = builder.getTokenType();
continue;
} else if (e == OPENPRAGMA) {
parseGenericPragma(builder, null, comments);
e = builder.getTokenType();
continue;
}
parseDecl(builder, decls == null ? null : decls[i], comments);
e = builder.getTokenType();
i++;
}
}
/**
* Parse a list of declarations.
*/
private static void parseDecls(PsiBuilder builder, DeclTopType[] decl, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (decl != null && i < decl.length) {
parseDecl(builder, decl[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Parse a single declaration.
*/
private static void parseDecl(PsiBuilder builder, DeclTopType decl, Comment[] comments) {
IElementType e = builder.getTokenType();
// Pragmas are handled by the outer loop in parseBody, so they are no-ops.
if (decl instanceof PatBind) {
PsiBuilder.Marker declMark = builder.mark();
parsePatBind(builder, (PatBind) decl, comments);
declMark.done(e);
} else if (decl instanceof FunBind) {
PsiBuilder.Marker declMark = builder.mark();
parseFunBind(builder, (FunBind) decl, comments);
declMark.done(e);
} else if (decl instanceof TypeFamDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeFamDecl(builder, (TypeFamDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DataDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDataDecl(builder, (DataDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof GDataDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseGDataDecl(builder, (GDataDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DataFamDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDataFamDecl(builder, (DataFamDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof TypeInsDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeInsDecl(builder, (TypeInsDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof TypeDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeDecl(builder, (TypeDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DataInsDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDataInstanceDecl(builder, (DataInsDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof GDataInsDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseGDataInstanceDecl(builder, (GDataInsDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof ClassDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseClassDecl(builder, (ClassDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof InstDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseInstDecl(builder, (InstDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DerivDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDerivDecl(builder, (DerivDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof InfixDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseInfixDecl(builder, (InfixDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof DefaultDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseDefaultDecl(builder, (DefaultDecl) decl, comments);
declMark.done(e);
} else if (decl instanceof SpliceDecl) {
PsiBuilder.Marker declMark = builder.mark();
parseExpTopType(builder, ((SpliceDecl) decl).exp, comments);
declMark.done(e);
} else if (decl instanceof TypeSig) {
PsiBuilder.Marker declMark = builder.mark();
parseTypeSig(builder, (TypeSig) decl, comments);
declMark.done(e);
} else if (decl instanceof ForImp) {
PsiBuilder.Marker declMark = builder.mark();
parseForeignImportDecl(builder, (ForImp) decl, comments);
declMark.done(e);
} else if (decl instanceof ForExp) {
PsiBuilder.Marker declMark = builder.mark();
parseForeignExportDecl(builder, (ForExp) decl, comments);
declMark.done(e);
} else if (decl instanceof InlineSig) {
// parseGenericPragma(builder, (InlineSig) decl, comments);
} else if (decl instanceof InlineConlikeSig) {
// parseGenericPragma(builder, (InlineConlikeSig) decl, comments);
} else if (decl instanceof SpecSig) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof SpecInlineSig) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof RulePragmaDecl) {
// parseGenericPragma(builder, (SpecSig) decl, comments);
} else if (decl instanceof DeprPragmaDecl) {
// parseGenericPragma(builder, (DeprPragmaDecl) decl, comments);
} else if (decl instanceof WarnPragmaDecl) {
// parseGenericPragma(builder, (WarnPragmaDecl) decl, comments);
} else if (decl instanceof InstSig) {
PsiBuilder.Marker declMark = builder.mark();
parseInstSig(builder, (InstSig) decl, comments);
declMark.done(e);
} else if (decl instanceof AnnPragma) {
// parseGenericPragma(builder, (AnnPragma) decl, comments);
} else if (decl != null) {
throw new ParserErrorException("Unexpected decl type: " + decl.toString());
}
}
/**
* Parse a pattern binding.
*/
private static void parsePatBind(PsiBuilder builder, PatBind patBind, Comment[] comments) {
IElementType e = builder.getTokenType();
parsePatTopType(builder, patBind.pat, comments);
if (patBind.type != null) throw new ParserErrorException("Unexpected type in patbind");
// TODO: parseType(builder, patBind.type, comments);
parseRhsTopType(builder, patBind.rhs, comments);
if (patBind.binds != null) throw new ParserErrorException("Unexpected binds in patbind");
}
/**
* Parse a function binding.
*/
private static void parseFunBind(PsiBuilder builder, FunBind funBind, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (funBind.match != null && i < funBind.match.length) {
parseMatchTop(builder, funBind.match[i], comments);
i++;
}
}
/**
* Parse a derive declaration.
*/
private static void parseDerivDecl(PsiBuilder builder, DerivDecl derivDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DERIVING);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
parseContextTopType(builder, derivDecl.contextMaybe, comments);
e = builder.getTokenType();
parseInstHead(builder, derivDecl.instHead, comments);
e = builder.getTokenType();
}
/**
* Parses an instance specialization.
*/
private static void parseInstSig(PsiBuilder builder, InstSig instSig, Comment[] comments) {
IElementType e = builder.getTokenType();
parseGenericPragma(builder, null, null);
e = builder.getTokenType();
// TODO: Improve precision of specialize instance pragma parsing.
// parseContextTopType(builder, instSig.contextMaybe, comments);
// e = builder.getTokenType();
// parseInstHead(builder, instSig.instHead, comments);
// e = builder.getTokenType();
}
/**
* Parse a list of class declarations.
*/
private static void parseClassDeclTopTypes(PsiBuilder builder, ClassDeclTopType[] classDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (classDecls != null && i < classDecls.length) {
parseClassDeclTopType(builder, classDecls[i], comments);
i++;
}
}
/**
* Parse a class declaration.
*/
private static void parseClassDeclTopType(PsiBuilder builder, ClassDeclTopType classDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
if (classDecl instanceof ClsDecl) {
parseDecl(builder, ((ClsDecl) classDecl).decl, comments);
e = builder.getTokenType();
} else if (classDecl instanceof ClsDataFam) {
consumeToken(builder, DATA);
e = builder.getTokenType();
parseContextTopType(builder, ((ClsDataFam) classDecl).contextMaybe, comments);
e = builder.getTokenType();
parseDeclHead(builder, ((ClsDataFam) classDecl).declHead, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseKindTopType(builder, ((ClsDataFam) classDecl).kindMaybe, comments);
e = builder.getTokenType();
} else if (classDecl instanceof ClsTyFam) {
consumeToken(builder, TYPE);
parseDeclHead(builder, ((ClsTyFam) classDecl).declHead, comments);
e = builder.getTokenType();
if (e == DOUBLECOLON) {
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, ((ClsTyFam) classDecl).kindMaybe, comments);
e = builder.getTokenType();
}
} else if (classDecl instanceof ClsTyDef) {
throw new ParserErrorException("TODO: ClsTyDef");
}
}
/**
* Parse a class declaration.
*/
private static void parseClassDecl(PsiBuilder builder, ClassDecl classDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, CLASSTOKEN);
e = builder.getTokenType();
parseContextTopType(builder, classDecl.contextMaybe, comments);
e = builder.getTokenType();
if (classDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW);
parseDeclHead(builder, classDecl.declHead, comments);
e = builder.getTokenType();
if (e == PIPE) { // TODO: Detailed Fundeps parsing.
consumeToken(builder, PIPE);
e = builder.getTokenType();
while (e != WHERE) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
if (e == WHERE) {
consumeToken(builder, WHERE);
e = builder.getTokenType();
}
parseClassDeclTopTypes(builder, classDecl.classDecls, comments);
e = builder.getTokenType();
}
/**
* Parse a instance declaration.
*/
private static void parseInstDecl(PsiBuilder builder, InstDecl instDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseContextTopType(builder, instDecl.contextMaybe, comments);
e = builder.getTokenType();
if (instDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW);
parseInstHead(builder, instDecl.instHead, comments);
e = builder.getTokenType();
consumeToken(builder, WHERE);
parseInstDeclTopTypes(builder, instDecl.instDecls, comments);
e = builder.getTokenType();
}
/**
* Parse a list of instance declarations.
*/
private static void parseInstDeclTopTypes(PsiBuilder builder, InstDeclTopType[] instDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (instDecls != null && i < instDecls.length) {
parseInstDeclTopType(builder, instDecls[i], comments);
i++;
}
}
/**
* Parses a single instance declaration.
*/
private static void parseInstDeclTopType(PsiBuilder builder, InstDeclTopType decl, Comment[] comments) {
IElementType e = builder.getTokenType();
if (decl instanceof InsDecl) {
parseDecl(builder, ((InsDecl) decl).decl, comments);
e = builder.getTokenType();
} else if (decl instanceof InsType) {
consumeToken(builder, TYPE);
e = builder.getTokenType();
parseTypeTopType(builder, ((InsType) decl).t1, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseTypeTopType(builder, ((InsType) decl).t2, comments);
e = builder.getTokenType();
} else if (decl instanceof InsData) {
consumeToken(builder, DATA);
e = builder.getTokenType();
parseTypeTopType(builder, ((InsData) decl).type, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseQualConDecls(builder, ((InsData) decl).qualConDecls, comments);
e = builder.getTokenType();
if (((InsData) decl).derivingMaybe != null) throw new ParserErrorException("Deriving unparsed" + decl.toString());
} else if (decl instanceof InsGData) {
throw new ParserErrorException("InsGData not implemented:" + decl.toString());
}
}
/**
* Parses a type family declaration.
*/
private static void parseTypeFamDecl(PsiBuilder builder, TypeFamDecl typeFamDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, TYPE);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: family token.
e = builder.getTokenType();
parseDeclHead(builder, typeFamDecl.declHead, comments);
e = builder.getTokenType();
if (e == DOUBLECOLON) {
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, typeFamDecl.kindMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses a type instance declaration.
*/
private static void parseTypeInsDecl(PsiBuilder builder, TypeInsDecl typeInsDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, TYPE);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseTypeTopType(builder, typeInsDecl.t1, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseTypeTopType(builder, typeInsDecl.t2, comments);
}
/**
* Parses a data declaration.
*/
private static void parseDataDecl(PsiBuilder builder, DataDecl dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
parseDeclHead(builder, dataDecl.declHead, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseQualConDecls(builder, dataDecl.qualConDecls, comments);
parseDeriving(builder, dataDecl.deriving, comments);
}
/**
* Parses a gadt-style data declaration.
*/
private static void parseGDataDecl(PsiBuilder builder, GDataDecl gDataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
parseDeclHead(builder, gDataDecl.declHead, comments);
e = builder.getTokenType();
if (e == DOUBLECOLON) {
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, gDataDecl.kindMaybe, comments);
e = builder.getTokenType();
}
if (e == WHERE) consumeToken(builder, WHERE);
int i = 0;
e = builder.getTokenType();
while (gDataDecl.gadtDecls != null && i < gDataDecl.gadtDecls.length) {
parseGadtDecl(builder, gDataDecl.gadtDecls[i], comments);
i++;
if (i < gDataDecl.gadtDecls.length) {
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
}
/**
* Parses a data family declaration.
*/
private static void parseDataFamDecl(PsiBuilder builder, DataFamDecl dataFamDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Keyword: family.
e = builder.getTokenType();
parseContextTopType(builder, dataFamDecl.contextMaybe, comments);
e = builder.getTokenType();
parseDeclHead(builder, dataFamDecl.declHead, comments);
e = builder.getTokenType();
if (e == DOUBLECOLON) {
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, dataFamDecl.kindMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses a data instance declaration.
*/
private static void parseDataInstanceDecl(PsiBuilder builder, DataInsDecl dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseTypeTopType(builder, dataDecl.type, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
int i = 0;
e = builder.getTokenType();
while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) {
parseQualConDecl(builder, dataDecl.qualConDecls[i], comments);
i++;
if (i < dataDecl.qualConDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
e = builder.getTokenType();
if (dataDecl.derivingMaybe != null) throw new ParserErrorException("TODO: deriving unimplemeted");
}
/**
* Parses a gadt-style data instance declaration.
*/
private static void parseGDataInstanceDecl(PsiBuilder builder, GDataInsDecl gDataInsDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DATA);
e = builder.getTokenType();
consumeToken(builder, INSTANCE);
e = builder.getTokenType();
parseTypeTopType(builder, gDataInsDecl.type, comments);
e = builder.getTokenType();
parseKindTopType(builder, gDataInsDecl.kindMaybe, comments);
e = builder.getTokenType();
if (e == WHERE) consumeToken(builder, WHERE);
int i = 0;
e = builder.getTokenType();
while (gDataInsDecl.gadtDecls != null && i < gDataInsDecl.gadtDecls.length) {
parseGadtDecl(builder, gDataInsDecl.gadtDecls[i], comments);
i++;
if (i < gDataInsDecl.gadtDecls.length) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
e = builder.getTokenType();
if (gDataInsDecl.derivingMaybe != null) throw new ParserErrorException("TODO: deriving unimplemeted");
}
/**
* Parse a single gadt-style declaration.
*/
private static void parseGadtDecl(PsiBuilder builder, GadtDecl gadtDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseName(builder, gadtDecl.name, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, gadtDecl.type, comments);
e = builder.getTokenType();
}
/**
* Parses the left side of '=' in a data/type declaration.
*/
private static void parseDeclHead(PsiBuilder builder, DeclHeadTopType declHead, Comment[] comments) {
IElementType e = builder.getTokenType();
if (declHead instanceof DHead) {
parseName(builder, ((DHead) declHead).name, comments);
e = builder.getTokenType();
parseTyVarBinds(builder, ((DHead) declHead).tyVars, comments);
} else if (declHead instanceof DHInfix) {
parseTyVarBind(builder, ((DHInfix) declHead).tb1, comments);
e = builder.getTokenType();
parseName(builder, ((DHInfix) declHead).name, comments);
e = builder.getTokenType();
parseTyVarBind(builder, ((DHInfix) declHead).tb2, comments);
e = builder.getTokenType();
} else if (declHead instanceof DHParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseDeclHead(builder, ((DHParen) declHead).declHead, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parse a list of qualified constructor declarations.
*/
private static void parseInstHeads(PsiBuilder builder, InstHeadTopType[] instHeads, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (instHeads != null && i < instHeads.length) {
parseInstHead(builder, instHeads[i], comments);
i++;
}
}
/**
* Parses the left side of '=>' in an instance declaration.
*/
private static void parseInstHead(PsiBuilder builder, InstHeadTopType instHead, Comment[] comments) {
IElementType e = builder.getTokenType();
if (instHead instanceof IHead) {
parseQName(builder, ((IHead) instHead).qName, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((IHead) instHead).types, comments);
e = builder.getTokenType();
} else if (instHead instanceof IHInfix) {
parseTypeTopType(builder, ((IHInfix) instHead).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((IHInfix) instHead).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((IHInfix) instHead).t2, comments);
e = builder.getTokenType();
} else if (instHead instanceof IHParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseInstHead(builder, ((IHParen) instHead).instHead, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses the type variables in a data declaration.
*/
private static void parseTyVarBinds(PsiBuilder builder, TyVarBindTopType[] tyVarBindTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
boolean foralled = e == FORALLTOKEN;
if (foralled) consumeToken(builder, FORALLTOKEN);
while (tyVarBindTopType != null && i < tyVarBindTopType.length) {
parseTyVarBind(builder, tyVarBindTopType[i], comments);
i++;
}
e = builder.getTokenType();
if (foralled) consumeToken(builder, PERIOD);
e = builder.getTokenType();
}
/**
* Parses the type variables in a data declaration.
*/
private static void parseTyVarBind(PsiBuilder builder, TyVarBindTopType tyVarBindTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (tyVarBindTopType instanceof KindedVar) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseName(builder, ((KindedVar) tyVarBindTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, ((KindedVar) tyVarBindTopType).kind, comments);
consumeToken(builder, RPAREN);
} else if (tyVarBindTopType instanceof UnkindedVar) {
parseName(builder, ((UnkindedVar) tyVarBindTopType).name, comments);
}
e = builder.getTokenType();
}
/**
* Parses a type declaration.
*/
private static void parseTypeDecl(PsiBuilder builder, TypeDecl typeDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, TYPE);
parseDeclHead(builder, typeDecl.declHead, comments);
e = builder.getTokenType();
if (e == EQUALS) consumeToken(builder, EQUALS);
parseTypeTopType(builder, typeDecl.type, comments);
e = builder.getTokenType();
}
/**
* Parses a type signature.
*/
private static void parseTypeSig(PsiBuilder builder, TypeSig dataDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseNames(builder, dataDecl.names, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, dataDecl.type, comments);
}
/**
* Parse a list of qualified constructor declarations.
*/
private static void parseQualConDecls(PsiBuilder builder, QualConDecl[] qualConDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (qualConDecls != null && i < qualConDecls.length) {
parseQualConDecl(builder, qualConDecls[i], comments);
i++;
}
}
/**
* Parses a qualified constructor declaration.
*/
private static void parseQualConDecl(PsiBuilder builder, QualConDecl qualConDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseTyVarBinds(builder, qualConDecl.tyVarBinds, comments);
e = builder.getTokenType();
if (qualConDecl.contextMaybe != null) throw new ParserErrorException("QualCondeclContext != null");
e = builder.getTokenType();
parseConDecl(builder, qualConDecl == null ? null : qualConDecl.conDecl, comments);
}
/**
* Parses a constructor declaration.
*/
private static void parseConDecl(PsiBuilder builder, ConDeclTopType conDecl, Comment[] comments) {
IElementType e1 = builder.getTokenType();
if (conDecl instanceof ConDecl) {
parseName(builder, ((ConDecl) conDecl).name, comments);
IElementType e = builder.getTokenType();
parseBangTypes(builder, conDecl == null ? null : ((ConDecl) conDecl).bangTypes, comments);
} else if (conDecl instanceof InfixConDecl) {
IElementType e = builder.getTokenType();
parseBangType(builder, ((InfixConDecl) conDecl).b1, comments);
e = builder.getTokenType();
parseName(builder, ((InfixConDecl) conDecl).name, comments);
parseBangType(builder, ((InfixConDecl) conDecl).b2, comments);
} else if (conDecl instanceof RecDecl) {
parseName(builder, ((RecDecl) conDecl).name, comments);
boolean layouted = false;
IElementType e = builder.getTokenType();
if (e == LBRACE) {
consumeToken(builder, LBRACE);
e = builder.getTokenType();
layouted = true;
}
parseFieldDecls(builder, ((RecDecl) conDecl).fields, comments);
e = builder.getTokenType();
if (layouted) {
consumeToken(builder, RBRACE);
e = builder.getTokenType();
}
}
}
/**
* Parses the field declarations in a GADT-style declaration.
*/
private static void parseFieldDecls(PsiBuilder builder, FieldDecl[] fieldDecls, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fieldDecls != null && i < fieldDecls.length) {
parseFieldDecl(builder, fieldDecls[i], comments);
i++;
e = builder.getTokenType();
if (i < fieldDecls.length) {
consumeToken(builder, COMMA);
}
}
e = builder.getTokenType();
}
/**
* Parses a field declaration.
*/
private static void parseFieldDecl(PsiBuilder builder, FieldDecl fieldDecl, Comment[] comments) {
IElementType e = builder.getTokenType();
parseNames(builder, fieldDecl.names, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseBangType(builder, fieldDecl.bang, comments);
e = builder.getTokenType();
}
/**
* Parses a list of bang types.
*/
private static void parseBangTypes(PsiBuilder builder, BangTypeTopType[] bangTypes, Comment[] comments) {
int i = 0;
while (bangTypes != null && i < bangTypes.length) {
parseBangType(builder, bangTypes[i], comments);
i++;
}
}
/**
* Parses one bang type.
*/
private static void parseBangType(PsiBuilder builder, BangTypeTopType bangType, Comment[] comments) {
IElementType e = builder.getTokenType();
// TODO: Refine bangType.
if (bangType instanceof UnBangedTy) {
parseTypeTopType(builder, ((UnBangedTy) bangType).type, comments);
} else if (bangType instanceof BangedTy) {
consumeToken(builder, EXLAMATION);
parseTypeTopType(builder, ((BangedTy) bangType).type, comments);
e = builder.getTokenType();
} else if (bangType instanceof UnpackedTy) {
parseGenericPragma(builder, null, comments);
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
parseTypeTopType(builder, ((UnpackedTy) bangType).type, comments);
e = builder.getTokenType();
}
}
private static void parseMatchTop(PsiBuilder builder, MatchTopType matchTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (matchTopType instanceof Match) {
parseMatch(builder, (Match) matchTopType, comments);
} else if (matchTopType instanceof InfixMatch) {
parseInfixMatch(builder, (InfixMatch) matchTopType, comments);
}
}
/**
* Parses a single match.
*/
private static void parseMatch(PsiBuilder builder, Match match, Comment[] comments) {
IElementType e = builder.getTokenType();
parseName(builder, match.name, comments);
int i = 0;
while (match.pats != null && i < match.pats.length) {
parsePatTopType(builder, match.pats[i], comments);
i++;
}
parseRhsTopType(builder, match.rhs, comments);
e = builder.getTokenType();
if (e == WHERE) {
consumeToken(builder, WHERE);
parseBindsTopType(builder, match.bindsMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses a single infix declaration.
*/
private static void parseInfixDecl(PsiBuilder builder, InfixDecl decl, Comment[] comments) {
IElementType e = builder.getTokenType();
builder.advanceLexer(); // TOOD: Parse infix/infixl/infixr
e = builder.getTokenType();
if (e == INTEGERTOKEN) consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
int i = 0;
while (decl.ops != null && i < decl.ops.length) {
parseOp(builder, decl.ops[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses a single default declaration.
*/
private static void parseDefaultDecl(PsiBuilder builder, DefaultDecl decl, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, DEFAULT);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopTypes(builder, decl.types, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
}
/**
* Parses a single infix match.
*/
private static void parseInfixMatch(PsiBuilder builder, InfixMatch match, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean startParen = e == LPAREN && !(match.pat instanceof PParen);
if (startParen) consumeToken(builder, LPAREN);
e = builder.getTokenType();
parsePatTopType(builder, match.pat, comments);
e = builder.getTokenType();
parseName(builder, match.name, comments);
e = builder.getTokenType();
int i = 0;
while (match.pats != null && i < match.pats.length) {
parsePatTopType(builder, match.pats[i], comments);
if (startParen && i == 0) {
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
i++;
}
parseRhsTopType(builder, match.rhs, comments);
e = builder.getTokenType();
if (e == WHERE) {
consumeToken(builder, WHERE);
parseBindsTopType(builder, match.bindsMaybe, comments);
e = builder.getTokenType();
}
}
/**
* Parses one binding.
*/
private static void parseBindsTopType(PsiBuilder builder, BindsTopType bindsTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (bindsTopType instanceof BDecls) {
parseDecls(builder, ((BDecls) bindsTopType).decls, comments);
} else if (bindsTopType instanceof IPBinds) {
throw new ParserErrorException("TODO: Implement IPBinds:" + bindsTopType.toString());
}
}
/**
* Parses several patterns.
*/
private static void parsePatTopTypes(PsiBuilder builder, PatTopType[] pats, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while(pats != null && i < pats.length) {
parsePatTopType(builder, pats[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA && i < pats.length) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses one pattern.
*/
private static void parsePatTopType(PsiBuilder builder, PatTopType patTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (patTopType instanceof PVar) {
parsePVar(builder, (PVar) patTopType, comments);
} else if (patTopType instanceof PLit) {
parseLiteralTop(builder, ((PLit) patTopType).lit, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PNeg) {
e = builder.getTokenType();
consumeToken(builder, MINUS);
e = builder.getTokenType();
parsePatTopType(builder, ((PNeg) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PNPlusK) {
e = builder.getTokenType();
parseName(builder, ((PNPlusK) patTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, PLUS);
e = builder.getTokenType();
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (patTopType instanceof PInfixApp) {
e = builder.getTokenType();
parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments);
e = builder.getTokenType();
parseQName(builder, ((PInfixApp) patTopType).qName, comments);
e = builder.getTokenType();
parsePatTopType(builder, ((PInfixApp) patTopType).p2, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PApp) {
e = builder.getTokenType();
parseQName(builder, ((PApp) patTopType).qName, comments);
e = builder.getTokenType();
parsePatTopTypes(builder, ((PApp) patTopType).pats, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((PTuple) patTopType).boxed, comments);
parsePatTopTypes(builder, ((PTuple) patTopType).pats, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (patTopType instanceof PList) {
consumeToken(builder, LBRACKET);
parsePatTopTypes(builder, ((PList) patTopType).pats, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (patTopType instanceof PParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parsePatTopType(builder, ((PParen) patTopType).pat, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (patTopType instanceof PRec) {
parseQName(builder, ((PRec) patTopType).qName, comments);
e = builder.getTokenType();
consumeToken(builder, LBRACE);
parsePatFieldTopTypes(builder, ((PRec) patTopType).patFields, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACE);
e = builder.getTokenType();
} else if (patTopType instanceof PAsPat) {
parseName(builder, ((PAsPat) patTopType).name, comments);
e = builder.getTokenType();
consumeToken(builder, AMPERSAT);
parsePatTopType(builder, ((PAsPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PWildCard) {
builder.advanceLexer(); // TODO: Token.UNDERSCORE?
e = builder.getTokenType();
} else if (patTopType instanceof PIrrPat) {
consumeToken(builder, TILDE);
e = builder.getTokenType();
parsePatTopType(builder, ((PIrrPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PatTypeSig) {
parsePatTopType(builder, ((PatTypeSig) patTopType).pat, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
parseTypeTopType(builder, ((PatTypeSig) patTopType).type, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PViewPat) {
parseExpTopType(builder, ((PViewPat) patTopType).exp, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
parsePatTopType(builder, ((PViewPat) patTopType).pat, comments);
e = builder.getTokenType();
} else if (patTopType instanceof PRPat) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PXTag) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PXETag) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PXPcdata) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PXPatTag) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PXRPats) {
// TODO: Implement once there are tests.
} else if (patTopType instanceof PQuasiQuote) {
e = builder.getTokenType();
consumeToken(builder, LBRACKET);
builder.advanceLexer();
e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
while (e != PIPE) {
builder.advanceLexer();
e = builder.getTokenType();
}
consumeToken(builder, PIPE);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (patTopType instanceof PBangPat) {
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
parsePatTopType(builder, ((PBangPat) patTopType).pat, comments);
e = builder.getTokenType();
}
}
private static void parseComment(IElementType start, PsiBuilder builder, Comment[] comments) {
PsiBuilder.Marker startCom = builder.mark();
IElementType e = builder.getTokenType();
while (e == COMMENT || e == COMMENTTEXT ||
e == OPENCOM || e == CLOSECOM) {
builder.advanceLexer();
e = builder.getTokenType();
}
startCom.done(NCOMMENT);
}
/**
* Parses a group of module pragmas.
*/
private static void parseModulePragmas(PsiBuilder builder, ModulePragmaTopType[] modulePragmas, Comment[] comments) {
int i = 0;
while(modulePragmas != null && i < modulePragmas.length) {
parseModulePragma(builder, modulePragmas[i], comments);
i++;
}
}
/**
* Parses a module pragma.
*/
private static void parseModulePragma(PsiBuilder builder, ModulePragmaTopType modulePragmaTopType, Comment[] comments) {
int i = 0;
if (modulePragmaTopType instanceof LanguagePragma) {
LanguagePragma langPragma = (LanguagePragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
consumeToken(builder, OPENPRAGMA);
consumeToken(builder, PRAGMA);
while (langPragma.names != null && i < langPragma.names.length) {
// TODO: Improve precision of pragma lexing.
// parseName(builder, langPragma.names[i], comments);
i++;
}
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(PPRAGMA);
} else if (modulePragmaTopType instanceof OptionsPragma) {
// FIXME: Use optionsPragma information.
OptionsPragma optionsPragma = (OptionsPragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(PPRAGMA);
} else if (modulePragmaTopType instanceof AnnModulePragma) {
// FIXME: Use annModulePragma information.
AnnModulePragma annModulePragma = (AnnModulePragma) modulePragmaTopType;
IElementType e = builder.getTokenType();
PsiBuilder.Marker pragmaMark = builder.mark();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(PPRAGMA);
}
}
/**
* Parses a pattern variable.
*/
private static void parsePVar(PsiBuilder builder, PVar pVar, Comment[] comments) {
parseName(builder, pVar.name, comments);
}
/**
* Parses a group of GuardedRhss.
*/
private static void parseGuardedRhss(PsiBuilder builder, GuardedRhs[] rhss, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while(rhss != null && i < rhss.length) {
parseGuardedRhs(builder, rhss[i], comments);
i++;
e = builder.getTokenType();
}
}
/**
* Parses one GuardedRhs.
*/
private static void parseGuardedRhs(PsiBuilder builder, GuardedRhs rhs, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
parseStmtTopTypes(builder, rhs.stmts, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
parseExpTopType(builder, rhs.exp, comments);
e = builder.getTokenType();
}
/**
* Parses one Rhs.
*/
private static void parseRhsTopType(PsiBuilder builder, RhsTopType rhsTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (rhsTopType instanceof UnGuardedRhs) {
consumeToken(builder, EQUALS);
parseExpTopType(builder, ((UnGuardedRhs) rhsTopType).exp, comments);
} else if (rhsTopType instanceof GuardedRhss) {
e = builder.getTokenType();
parseGuardedRhss(builder, ((GuardedRhss) rhsTopType).rhsses, comments);
}
}
/**
* Parses an unqualified op.
*/
private static void parseOp(PsiBuilder builder, OpTopType opTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean backticked = e == BACKTICK;
if (backticked) {
consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
if (opTopType instanceof VarOp) {
parseName(builder, ((VarOp) opTopType).name, comments);
} else if (opTopType instanceof ConOp) {
parseName(builder, ((ConOp) opTopType).name, comments);
}
if (backticked) consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
/**
* Parses a qualified op.
*/
private static void parseQOp(PsiBuilder builder, QOpTopType qOpTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
boolean backticked = e == BACKTICK;
if (backticked) {
consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
if (qOpTopType instanceof QVarOp) {
parseQName(builder, ((QVarOp) qOpTopType).qName, comments);
} else if (qOpTopType instanceof QConOp) {
parseQName(builder, ((QConOp) qOpTopType).qName, comments);
}
if (backticked) consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
/**
* Parses a qualified name.
*/
private static void parseQName(PsiBuilder builder, QNameTopType qNameTopType, Comment[] comments) {
if (qNameTopType instanceof Qual) {
Qual name = (Qual) qNameTopType;
parseModuleName(builder, name.moduleName, comments);
parseName(builder, name.name, comments);
} else if (qNameTopType instanceof UnQual) {
parseName(builder, ((UnQual) qNameTopType).name, comments);
} else if (qNameTopType instanceof Special) {
parseSpecialConTopType(builder, ((Special) qNameTopType).specialCon, comments);
}
}
/**
* Parses a special constructor.
*/
private static void parseSpecialConTopType(PsiBuilder builder, SpecialConTopType specialConTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (specialConTopType instanceof UnitCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof ListCon) {
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (specialConTopType instanceof FunCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof TupleCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TupleCon) specialConTopType).boxed, comments);
e = builder.getTokenType();
int i = 1;
while (i < ((TupleCon) specialConTopType).i) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
i++;
}
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (specialConTopType instanceof Cons) {
consumeToken(builder, COLON);
e = builder.getTokenType();
} else if (specialConTopType instanceof UnboxedSingleCon) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
}
}
/**
* Parses a list of names.
*/
private static void parseNames(PsiBuilder builder, NameTopType[] names, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (names != null && i < names.length) {
parseName(builder, names[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a name.
*/
private static void parseName(PsiBuilder builder, NameTopType nameTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (nameTopType instanceof Ident) {
boolean startTick = e == BACKTICK;
if (startTick) consumeToken(builder, BACKTICK);
e = builder.getTokenType();
int startPos = builder.getCurrentOffset();
while ((builder.getCurrentOffset() - startPos) <
((Ident) nameTopType).name.length()) {
builder.remapCurrentToken(NAME);
consumeToken(builder, NAME);
e = builder.getTokenType();
}
e = builder.getTokenType();
if (startTick) {
consumeToken(builder, BACKTICK);
e = builder.getTokenType();
}
} else if (nameTopType instanceof Symbol) {
boolean startParen = e == LPAREN;
if (startParen) consumeToken(builder, LPAREN);
e = builder.getTokenType();
int startPos = builder.getCurrentOffset();
while ((builder.getCurrentOffset() - startPos) <
((Symbol) nameTopType).symbol.length()) {
builder.remapCurrentToken(SYMBOL);
consumeToken(builder, SYMBOL);
e = builder.getTokenType();
}
e = builder.getTokenType();
if (startParen) {
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
}
/**
* Parses a literal
*/
private static void parseLiteralTop(PsiBuilder builder, LiteralTopType literalTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (literalTopType instanceof CharLit) {
consumeToken(builder, CHARTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof StringLit) {
parseStringLiteral(builder);
} else if (literalTopType instanceof IntLit) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof FracLit) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimInt) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimWord) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimFloat) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimDouble) {
consumeToken(builder, FLOATTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimChar) {
consumeToken(builder, CHARTOKEN);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
} else if (literalTopType instanceof PrimString) {
parseStringLiteral(builder);
e = builder.getTokenType();
consumeToken(builder, HASH);
e = builder.getTokenType();
}
}
/**
* Parse a string literal.
*/
private static void parseStringLiteral(PsiBuilder builder) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker marker = builder.mark();
consumeToken(builder, DOUBLEQUOTE);
IElementType e2 = builder.getTokenType();
while (e2 != DOUBLEQUOTE) {
if (e2 == BADSTRINGTOKEN) {
builder.error("Bad stringtoken");
builder.advanceLexer();
} else {
consumeToken(builder, STRINGTOKEN);
}
e2 = builder.getTokenType();
}
consumeToken(builder, DOUBLEQUOTE);
marker.done(PSTRINGTOKEN);
}
/**
* Parses a list of statements.
*/
private static void parseStmtTopTypes(PsiBuilder builder, StmtTopType[] stmtTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (stmtTopTypes != null && i < stmtTopTypes.length) {
parseStmtTopType(builder, stmtTopTypes[i], comments);
i++;
}
}
/**
* Parses a statement.
*/
private static void parseStmtTopType(PsiBuilder builder, StmtTopType stmtTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker stmtMark = builder.mark();
if (stmtTopType instanceof Generator) {
parsePatTopType(builder, ((Generator) stmtTopType).pat, comments);
consumeToken(builder, LEFTARROW);
parseExpTopType(builder, ((Generator) stmtTopType).exp, comments);
} else if (stmtTopType instanceof Qualifier) {
parseExpTopType(builder, ((Qualifier) stmtTopType).exp, comments);
} else if (stmtTopType instanceof LetStmt) {
consumeToken(builder, LET);
parseBindsTopType(builder, ((LetStmt) stmtTopType).binds, comments);
} else if (stmtTopType instanceof RecStmt) {
builder.advanceLexer();
IElementType e1 = builder.getTokenType();
parseStmtTopTypes(builder, ((RecStmt) stmtTopType).stmts, comments);
e1 = builder.getTokenType();
}
stmtMark.done(e);
}
/**
* Parses a list of expressions.
*/
private static void parseExpTopTypes(PsiBuilder builder, ExpTopType[] expTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (expTopType != null && i < expTopType.length) {
parseExpTopType(builder, expTopType[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses an expression.
*/
private static void parseExpTopType(PsiBuilder builder, ExpTopType expTopType, Comment[] comments) {
IElementType e1 = builder.getTokenType();
if (expTopType instanceof App) {
parseExpTopType(builder, ((App) expTopType).e1, comments);
parseExpTopType(builder, ((App) expTopType).e2, comments);
} else if (expTopType instanceof Var) {
parseQName(builder, ((Var) expTopType).qName, comments);
} else if (expTopType instanceof IPVar) {
parseIPNameTopType(builder, ((IPVar) expTopType).ipName, comments);
} else if (expTopType instanceof Con) {
parseQName(builder, ((Con) expTopType).qName, comments);
} else if (expTopType instanceof Lit) {
parseLiteralTop(builder, ((Lit) expTopType).literal, comments);
} else if (expTopType instanceof InfixApp) {
parseExpTopType(builder, ((InfixApp) expTopType).e1, comments);
IElementType e = builder.getTokenType();
parseQOp(builder, ((InfixApp) expTopType).qop, comments);
e = builder.getTokenType();
parseExpTopType(builder, ((InfixApp) expTopType).e2, comments);
e = builder.getTokenType();
} else if (expTopType instanceof List) {
builder.advanceLexer();
parseExpTopTypes(builder, ((List) expTopType).exps, comments);
IElementType e = builder.getTokenType();
builder.advanceLexer();
} else if (expTopType instanceof NegApp) {
consumeToken(builder, MINUS);
parseExpTopType(builder, ((NegApp) expTopType).e1, comments);
} else if (expTopType instanceof Case) {
IElementType e = builder.getTokenType();
consumeToken(builder, CASE);
e = builder.getTokenType();
parseExpTopType(builder, ((Case) expTopType).scrutinee, comments);
e = builder.getTokenType();
consumeToken(builder, OF);
e = builder.getTokenType();
parseAlts(builder, ((Case) expTopType).alts, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Do) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker doMark = builder.mark();
consumeToken(builder, DO);
parseStmtTopTypes(builder, ((Do) expTopType).stmts, comments);
doMark.done(e);
} else if (expTopType instanceof MDo) {
IElementType e = builder.getTokenType();
PsiBuilder.Marker doMark = builder.mark();
builder.advanceLexer(); // TODO: Token.MDO
parseStmtTopTypes(builder, ((MDo) expTopType).stmts, comments);
doMark.done(e);
} else if (expTopType instanceof Lambda) {
consumeToken(builder, BACKSLASH);
IElementType e = builder.getTokenType();
parsePatTopTypes(builder, ((Lambda) expTopType).pats, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
parseExpTopType(builder, ((Lambda) expTopType).exp, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Tuple) {
consumeToken(builder, LPAREN);
IElementType e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((Tuple) expTopType).boxed, comments);
e = builder.getTokenType();
parseExpTopTypes(builder, ((Tuple) expTopType).exps, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof TupleSection) {
TupleSection ts = (TupleSection) expTopType;
consumeToken(builder, LPAREN);
IElementType e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TupleSection) expTopType).boxed, comments);
e = builder.getTokenType();
int i = 0;
while (ts.expMaybes != null && i < ts.expMaybes.length) {
if (ts.expMaybes[i] != null) parseExpTopType(builder, ts.expMaybes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof Paren) {
consumeToken(builder, LPAREN);
e1 = builder.getTokenType();
parseExpTopType(builder, ((Paren) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof LeftSection) {
e1 = builder.getTokenType();
consumeToken(builder, LPAREN);
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftSection) expTopType).exp, comments);
e1 = builder.getTokenType();
parseQOp(builder, ((LeftSection) expTopType).qop, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightSection) {
e1 = builder.getTokenType();
consumeToken(builder, LPAREN);
parseQOp(builder, ((RightSection) expTopType).qop, comments);
parseExpTopType(builder, ((RightSection) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, RPAREN);
e1 = builder.getTokenType();
} else if (expTopType instanceof RecConstr) {
e1 = builder.getTokenType();
parseQName(builder, ((RecConstr) expTopType).qName, comments);
e1 = builder.getTokenType();
consumeToken(builder, LBRACE);
parseFieldUpdateTopTypes(builder, ((RecConstr) expTopType).fieldUpdates, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACE);
e1 = builder.getTokenType();
} else if (expTopType instanceof RecUpdate) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RecUpdate) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, LBRACE);
parseFieldUpdateTopTypes(builder, ((RecUpdate) expTopType).fieldUpdates, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACE);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFrom) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFrom) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromTo) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromTo) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromTo) expTopType).to, comments);
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromThen) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThen) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, COMMA);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThen) expTopType).step, comments);
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof EnumFromThenTo) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).from, comments);
e1 = builder.getTokenType();
consumeToken(builder, COMMA);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).step, comments);
consumeToken(builder, DOUBLEPERIOD);
e1 = builder.getTokenType();
parseExpTopType(builder, ((EnumFromThenTo) expTopType).to, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ListComp) {
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((ListComp) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, PIPE);
e1 = builder.getTokenType();
parseQualStmtTopTypes(builder, ((ListComp) expTopType).qualStmts, comments);
e1 = builder.getTokenType();
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ParComp) {
ParComp p = (ParComp) expTopType;
consumeToken(builder, LBRACKET);
e1 = builder.getTokenType();
parseExpTopType(builder, ((ParComp) expTopType).exp, comments);
e1 = builder.getTokenType();
consumeToken(builder, PIPE);
e1 = builder.getTokenType();
int i = 0;
while (p.qualStmts != null && i < p.qualStmts.length) {
parseQualStmtTopTypes(builder, p.qualStmts[i], comments);
i++;
e1 = builder.getTokenType();
if (e1 == PIPE) consumeToken(builder, PIPE);
e1 = builder.getTokenType();
}
consumeToken(builder, RBRACKET);
e1 = builder.getTokenType();
} else if (expTopType instanceof ExpTypeSig) {
IElementType e = builder.getTokenType();
parseExpTopType(builder, ((ExpTypeSig) expTopType).exp, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, ((ExpTypeSig) expTopType).type, comments);
e = builder.getTokenType();
} else if (expTopType instanceof Let) {
builder.advanceLexer();
IElementType e = builder.getTokenType();
parseBindsTopType(builder, ((Let) expTopType).binds, comments);
e = builder.getTokenType();
consumeToken(builder, IN);
e = builder.getTokenType();
parseExpTopType(builder, ((Let) expTopType).exp, comments);
e = builder.getTokenType();
} else if (expTopType instanceof If) {
consumeToken(builder, IF);
IElementType e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).cond, comments);
e = builder.getTokenType();
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).t, comments);
e = builder.getTokenType();
consumeToken(builder, ELSE);
e = builder.getTokenType();
parseExpTopType(builder, ((If) expTopType).f, comments);
e = builder.getTokenType();
} else if (expTopType instanceof MultiIf) {
consumeToken(builder, IF);
IElementType e = builder.getTokenType();
parseIfAlts(builder, ((MultiIf) expTopType).alts, comments);
e = builder.getTokenType();
} else if (expTopType instanceof VarQuote) {
IElementType e = builder.getTokenType();
consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
parseQName(builder, ((VarQuote) expTopType).qName, comments);
e = builder.getTokenType();
} else if (expTopType instanceof TypQuote) {
IElementType e = builder.getTokenType();
consumeToken(builder, THQUOTE);
e = builder.getTokenType();
parseQName(builder, ((TypQuote) expTopType).qName, comments);
e = builder.getTokenType();
} else if (expTopType instanceof BracketExp) {
IElementType e = builder.getTokenType();
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
if (e != PIPE) {
builder.advanceLexer(); // 'd', 't', etc
e = builder.getTokenType();
}
consumeToken(builder, PIPE);
e = builder.getTokenType();
while (e != PIPE) {
builder.advanceLexer();
e = builder.getTokenType();
}
consumeToken(builder, PIPE);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (expTopType instanceof SpliceExp) {
IElementType e = builder.getTokenType();
consumeToken(builder, DOLLAR);
boolean parenSplice = ((SpliceExp) expTopType).splice instanceof ParenSplice;
if (parenSplice) {
consumeToken(builder, LPAREN);
parseExpTopType(builder, ((ParenSplice) ((SpliceExp) expTopType).splice).exp, comments);
consumeToken(builder, RPAREN);
} else {
consumeToken(builder, VARIDREGEXP);
}
e = builder.getTokenType();
} else if (expTopType instanceof QuasiQuote) {
IElementType e = builder.getTokenType();
consumeToken(builder, LBRACKET);
builder.advanceLexer();
e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
while (e != PIPE) {
builder.advanceLexer();
e = builder.getTokenType();
}
consumeToken(builder, PIPE);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (expTopType instanceof CorePragma) {
parseGenericPragma(builder, null, comments);
parseExpTopType(builder, ((CorePragma) expTopType).exp, comments);
} else if (expTopType instanceof SCCPragma) {
parseGenericPragma(builder, null, comments);
parseExpTopType(builder, ((SCCPragma) expTopType).exp, comments);
} else if (expTopType instanceof Proc) {
e1 = builder.getTokenType();
builder.advanceLexer(); // TODO: consumeToken(builder, PROCTOKEN);
e1 = builder.getTokenType();
parsePatTopType(builder, ((Proc) expTopType).pat, comments);
consumeToken(builder, RIGHTARROW);
parseExpTopType(builder, ((Proc) expTopType).exp, comments);
} else if (expTopType instanceof LeftArrApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightArrApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, RightArrApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof LeftArrHighApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrHighApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrHighApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((LeftArrHighApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof RightArrHighApp) {
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrHighApp) expTopType).e1, comments);
builder.advanceLexer(); // TODO: consumeToken(builder, RightArrHighApp);
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
builder.advanceLexer();
e1 = builder.getTokenType();
parseExpTopType(builder, ((RightArrHighApp) expTopType).e2, comments);
e1 = builder.getTokenType();
} else if (expTopType instanceof LCase) {
IElementType e = builder.getTokenType();
consumeToken(builder, BACKSLASH);
e = builder.getTokenType();
consumeToken(builder, CASE);
e = builder.getTokenType();
parseAlts(builder, ((LCase) expTopType).alts, comments);
e = builder.getTokenType();
} else {
throw new ParserErrorException("parseExpTopType: " + expTopType.toString());
}
}
/**
* Parses a list of field patterns.
*/
private static void parsePatFieldTopTypes(PsiBuilder builder, PatFieldTopType[] fields, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fields != null && i < fields.length) {
parsePatFieldTopType(builder, fields[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a field pattern.
*/
private static void parsePatFieldTopType(PsiBuilder builder, PatFieldTopType field, Comment[] comments) {
IElementType e = builder.getTokenType();
if (field instanceof PFieldPat) {
parseQName(builder, ((PFieldPat) field).qName, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parsePatTopType(builder, ((PFieldPat) field).pat, comments);
e = builder.getTokenType();
} else if (field instanceof PFieldPun) {
consumeToken(builder, VARIDREGEXP);
e = builder.getTokenType();
} else if (field instanceof PFieldWildcard) {
builder.advanceLexer(); // TODO: Token.UNDERSCORE?
e = builder.getTokenType();
}
}
/**
* Parses a list of field updates.
*/
private static void parseFieldUpdateTopTypes(PsiBuilder builder, FieldUpdateTopType[] fieldUpdateTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (fieldUpdateTopTypes != null && i < fieldUpdateTopTypes.length) {
parseFieldUpdateTopType(builder, fieldUpdateTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a field update.
*/
private static void parseFieldUpdateTopType(PsiBuilder builder, FieldUpdateTopType fieldUpdate, Comment[] comments) {
IElementType e = builder.getTokenType();
if (fieldUpdate instanceof FieldUpdate) {
parseQName(builder, ((FieldUpdate) fieldUpdate).qName, comments);
e = builder.getTokenType();
consumeToken(builder, EQUALS);
e = builder.getTokenType();
parseExpTopType(builder, ((FieldUpdate) fieldUpdate).exp, comments);
e = builder.getTokenType();
} else if (fieldUpdate instanceof FieldPun) {
throw new ParserErrorException("TODO: FieldPun not implemented");
} else if (fieldUpdate instanceof FieldWildcard) {
throw new ParserErrorException("TODO: FieldWildcard not implemented");
}
}
/**
* Parses a list of alts.
*/
private static void parseAlts(PsiBuilder builder, Alt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == SEMICOLON) consumeToken(builder, SEMICOLON);
}
}
/**
* Parses a single alt.
*/
private static void parseAlt(PsiBuilder builder, Alt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
parsePatTopType(builder, alt.pat, comments);
e = builder.getTokenType();
parseGuardedAltsTopType(builder, alt.guardedAlts, comments);
e = builder.getTokenType();
parseBindsTopType(builder, alt.bindsMaybe, comments);
e = builder.getTokenType();
}
/**
* Parses a list of IfAlts.
*/
private static void parseIfAlts(PsiBuilder builder, IfAlt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseIfAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == PIPE) consumeToken(builder, PIPE);
}
}
/**
* Parses a single IfAlt
*/
private static void parseIfAlt(PsiBuilder builder, IfAlt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
parseExpTopType(builder, alt.e1, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, alt.e2, comments);
e = builder.getTokenType();
}
/**
* Parses a single guarded alt.
*/
private static void parseGuardedAltsTopType(PsiBuilder builder, GuardedAltsTopType alt, Comment[] comments) {
IElementType e = builder.getTokenType();
if (alt instanceof UnGuardedAlt) {
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, ((UnGuardedAlt) alt).exp, comments);
e = builder.getTokenType();
} else if (alt instanceof GuardedAlts) {
parseGuardedAlts(builder, ((GuardedAlts) alt).alts, comments);
e = builder.getTokenType();
}
}
/**
* Parses a list of guarded alts.
*/
private static void parseGuardedAlts(PsiBuilder builder, GuardedAlt[] alts, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (alts != null && i < alts.length) {
parseGuardedAlt(builder, alts[i], comments);
i++;
e = builder.getTokenType();
if (e == SEMICOLON) consumeToken(builder, SEMICOLON);
}
}
/**
* Parses a single guarded alt.
*/
private static void parseGuardedAlt(PsiBuilder builder, GuardedAlt alt, Comment[] comments) {
IElementType e = builder.getTokenType();
consumeToken(builder, PIPE);
e = builder.getTokenType();
parseStmtTopTypes(builder, alt.stmts, comments);
e = builder.getTokenType();
consumeToken(builder, RIGHTARROW);
e = builder.getTokenType();
parseExpTopType(builder, alt.exp, comments);
e = builder.getTokenType();
}
/**
* Parses a list of types.
*/
private static void parseTypeTopTypes(PsiBuilder builder, TypeTopType[] typeTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (typeTopTypes != null && i < typeTopTypes.length) {
parseTypeTopType(builder, typeTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a type.
*/
private static void parseTypeTopType(PsiBuilder builder, TypeTopType typeTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (typeTopType instanceof TyForall) {
TyForall t = (TyForall) typeTopType;
e = builder.getTokenType();
if (t.tyVarBinds != null) { // Implicit foralls for typeclasses.
builder.advanceLexer();
e = builder.getTokenType();
parseTyVarBinds(builder, t.tyVarBinds, comments);
e = builder.getTokenType();
}
parseContextTopType(builder, t.context, comments);
e = builder.getTokenType();
if (e == DOUBLEARROW) consumeToken(builder, DOUBLEARROW);
parseTypeTopType(builder, t.type, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyFun) {
parseTypeTopType(builder, ((TyFun) typeTopType).t1, comments);
consumeToken(builder, RIGHTARROW);
parseTypeTopType(builder, ((TyFun) typeTopType).t2, comments);
} else if (typeTopType instanceof TyTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
boolean unboxed = parseBoxed(builder, ((TyTuple) typeTopType).boxed, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((TyTuple) typeTopType).types, comments);
e = builder.getTokenType();
if (unboxed) {
consumeToken(builder, HASH);
e = builder.getTokenType();
}
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyList) {
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyList) typeTopType).t, comments);
e = builder.getTokenType();
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (typeTopType instanceof TyApp) {
parseTypeTopType(builder, ((TyApp) typeTopType).t1, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyApp) typeTopType).t2, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyVar) {
parseName(builder, ((TyVar) typeTopType).name, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyCon) {
parseQName(builder, ((TyCon) typeTopType).qName, comments);
} else if (typeTopType instanceof TyParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyParen) typeTopType).type, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyInfix) {
e = builder.getTokenType();
parseTypeTopType(builder, ((TyInfix) typeTopType).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((TyInfix) typeTopType).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyInfix) typeTopType).t2, comments);
e = builder.getTokenType();
} else if (typeTopType instanceof TyKind) {
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseTypeTopType(builder, ((TyKind) typeTopType).type, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseKindTopType(builder, ((TyKind) typeTopType).kind, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (typeTopType instanceof TyPromoted) {
parsePromotedTopType(builder, ((TyPromoted) typeTopType).promoted, comments);
e = builder.getTokenType();
}
}
/**
* Parses a list of kinds.
*/
private static void parseKindTopTypes(PsiBuilder builder, KindTopType[] kinds, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (kinds != null && i < kinds.length) {
parseKindTopType(builder, kinds[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses a kind.
*/
private static void parseKindTopType(PsiBuilder builder, KindTopType kind, Comment[] comments) {
IElementType e = builder.getTokenType();
if (kind instanceof KindStar) {
consumeToken(builder, ASTERISK);
e = builder.getTokenType();
} else if (kind instanceof KindBang) {
consumeToken(builder, EXLAMATION);
e = builder.getTokenType();
} else if (kind instanceof KindFn) {
parseKindTopType(builder, ((KindFn) kind).k1, comments);
consumeToken(builder, RIGHTARROW);
parseKindTopType(builder, ((KindFn) kind).k2, comments);
} else if (kind instanceof KindParen) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseKindTopType(builder, ((KindParen) kind).kind, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (kind instanceof KindVar) {
parseQName(builder, ((KindVar) kind).qName, comments);
e = builder.getTokenType();
} else if (kind instanceof KindApp) {
parseKindTopType(builder, ((KindApp) kind).k1, comments);
e = builder.getTokenType();
parseKindTopType(builder, ((KindApp) kind).k2, comments);
e = builder.getTokenType();
} else if (kind instanceof KindTuple) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseKindTopTypes(builder, ((KindTuple) kind).kinds, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (kind instanceof KindList) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LBRACKET);
e = builder.getTokenType();
parseKindTopTypes(builder, ((KindList) kind).kinds, comments);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
}
}
/**
* Parses a list of promoted types.
*/
private static void parsePromotedTopTypes(PsiBuilder builder,PromotedTopType[] promotedTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (promotedTopTypes != null && i < promotedTopTypes.length) {
parsePromotedTopType(builder, promotedTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses one promoted type.
*/
private static void parsePromotedTopType(PsiBuilder builder, PromotedTopType promotedTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (promotedTopType instanceof PromotedInteger) {
consumeToken(builder, INTEGERTOKEN);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedString) {
parseStringLiteral(builder);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedCon) {
parseQName(builder, ((PromotedCon) promotedTopType).qName, comments);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedList) {
if (((PromotedList) promotedTopType).leadingQuote) consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LBRACKET);
parsePromotedTopTypes(builder, ((PromotedList) promotedTopType).promoteds, comments);
consumeToken(builder, RBRACKET);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedTuple) {
e = builder.getTokenType();
if (e == SINGLEQUOTE) {
consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
}
consumeToken(builder, LPAREN);
parsePromotedTopTypes(builder, ((PromotedTuple) promotedTopType).promoteds, comments);
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (promotedTopType instanceof PromotedUnit) {
consumeToken(builder, SINGLEQUOTE);
e = builder.getTokenType();
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses a list of qualified statements.
*/
private static void parseQualStmtTopTypes(PsiBuilder builder, QualStmtTopType[] qualStmtTopTypes, Comment[] comments) {
IElementType e = builder.getTokenType();
int i = 0;
while (qualStmtTopTypes != null && i < qualStmtTopTypes.length) {
parseQualStmtTopType(builder, qualStmtTopTypes[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) consumeToken(builder, COMMA);
}
}
/**
* Parses one qualified statement.
*/
private static void parseQualStmtTopType(PsiBuilder builder, QualStmtTopType qualStmtTopType, Comment[] comments) {
IElementType e = builder.getTokenType();
if (qualStmtTopType instanceof QualStmt) {
parseStmtTopType(builder, ((QualStmt) qualStmtTopType).stmt, comments);
} else if (qualStmtTopType instanceof ThenTrans) {
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((ThenTrans) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof ThenBy) {
consumeToken(builder, THEN);
e = builder.getTokenType();
parseExpTopType(builder, ((ThenBy) qualStmtTopType).e1, comments);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.BY
e = builder.getTokenType();
parseExpTopType(builder, ((ThenBy) qualStmtTopType).e2, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupBy) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING
e = builder.getTokenType();
parseExpTopType(builder, ((GroupBy) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupUsing) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING
e = builder.getTokenType();
parseExpTopType(builder, ((GroupUsing) qualStmtTopType).exp, comments);
e = builder.getTokenType();
} else if (qualStmtTopType instanceof GroupByUsing) {
consumeToken(builder, THEN);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.GROUP
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.BY
e = builder.getTokenType();
parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e1, comments);
e = builder.getTokenType();
builder.advanceLexer(); // TODO: Add Token.USING.
parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e2, comments);
e = builder.getTokenType();
}
}
/**
* Parses contexts.
*/
private static void parseContextTopType(PsiBuilder builder, ContextTopType context, Comment[] comments) {
IElementType e = builder.getTokenType();
if (context instanceof CxSingle) {
parseAsstTopType(builder, ((CxSingle) context).asst, comments);
} else if (context instanceof CxTuple) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
parseAsstTopTypes(builder, ((CxTuple) context).assts, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (context instanceof CxParen) {
consumeToken(builder, LPAREN);
parseContextTopType(builder, ((CxParen) context).context, comments);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
} else if (context instanceof CxEmpty) {
consumeToken(builder, LPAREN);
e = builder.getTokenType();
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses a list of Assts.
*/
private static void parseAsstTopTypes(PsiBuilder builder, AsstTopType[] assts, Comment[] comments) {
int i = 0;
IElementType e = builder.getTokenType();
while (assts != null && i < assts.length) {
parseAsstTopType(builder, assts[i], comments);
i++;
e = builder.getTokenType();
if (e == COMMA) {
consumeToken(builder, COMMA);
e = builder.getTokenType();
}
}
}
/**
* Parses Assts.
*/
private static void parseAsstTopType(PsiBuilder builder, AsstTopType asst, Comment[] comments) {
IElementType e = builder.getTokenType();
if (asst instanceof ClassA) {
parseQName(builder, ((ClassA) asst).qName, comments);
e = builder.getTokenType();
parseTypeTopTypes(builder, ((ClassA) asst).types, comments);
e = builder.getTokenType();
} else if (asst instanceof InfixA) {
parseTypeTopType(builder, ((InfixA) asst).t1, comments);
e = builder.getTokenType();
parseQName(builder, ((InfixA) asst).qName, comments);
e = builder.getTokenType();
parseTypeTopType(builder, ((InfixA) asst).t2, comments);
e = builder.getTokenType();
} else if (asst instanceof IParam) {
parseIPNameTopType(builder, ((IParam) asst).ipName, comments);
e = builder.getTokenType();
consumeToken(builder, DOUBLECOLON);
e = builder.getTokenType();
parseTypeTopType(builder, ((IParam) asst).type, comments);
e = builder.getTokenType();
} else if (asst instanceof EqualP) {
parseTypeTopType(builder, ((EqualP) asst).t1, comments);
consumeToken(builder, TILDE);
e = builder.getTokenType();
parseTypeTopType(builder,((EqualP) asst).t2, comments);
e = builder.getTokenType();
}
}
/**
* Parses Implicit parameter names.
*/
private static void parseIPNameTopType(PsiBuilder builder, IPNameTopType ipNameTopType, Comment[] comments) { // TODO: Improve granularity.
IElementType e = builder.getTokenType();
if (ipNameTopType instanceof IPDup) {
consumeToken(builder, QUESTION);
e = builder.getTokenType();
builder.advanceLexer();
e = builder.getTokenType();
} else if (ipNameTopType instanceof IPLin) {
consumeToken(builder, PERCENT);
e = builder.getTokenType();
builder.advanceLexer();
e = builder.getTokenType();
}
}
/**
* Parses box annotations.
*/
private static boolean parseBoxed(PsiBuilder builder, BoxedTopType boxedTopType, Comment[] comments) { // TODO: Improve granularity.
IElementType e = builder.getTokenType();
if (boxedTopType instanceof Boxed) {
return false;
} else if (boxedTopType instanceof Unboxed) {
consumeToken(builder, HASH);
return true;
}
return false; // Never reached.
}
/**
* Parses box annotations.
*/
private static void parseDeriving(PsiBuilder builder, Deriving deriving, Comment[] comments) { // TODO: Improve granularity.
IElementType e = builder.getTokenType();
if (e != DERIVING) return;
consumeToken(builder, DERIVING);
e = builder.getTokenType();
boolean startParen = e == LPAREN;
if (startParen) consumeToken(builder, LPAREN);
parseInstHeads(builder, deriving == null ? null : deriving.instHeads, comments);
if (startParen) {
consumeToken(builder, RPAREN);
e = builder.getTokenType();
}
}
/**
* Parses a generic pragma.
*/
private static void parseGenericPragma(PsiBuilder builder, DeclTopType annPragma, Comment[] comments) { // TODO: Improve granularity.
PsiBuilder.Marker pragmaMark = builder.mark();
IElementType e = builder.getTokenType();
chewPragma(builder);
consumeToken(builder, CLOSEPRAGMA);
pragmaMark.done(PPRAGMA);
}
/**
* Eats a complete pragma and leaves the builder at CLOSEPRAGMA token.
*/
private static void chewPragma(PsiBuilder builder) {
IElementType e = builder.getTokenType();
while (e != CLOSEPRAGMA) {
builder.advanceLexer();
e = builder.getTokenType();
}
}
private static boolean consumeToken(PsiBuilder builder_, IElementType token) {
if (nextTokenIsInner(builder_, token)) {
builder_.advanceLexer();
return true;
}
return false;
}
private static boolean nextTokenIsInner(PsiBuilder builder_, IElementType expectedToken) {
IElementType tokenType = builder_.getTokenType();
if (expectedToken != tokenType) {
PsiBuilder.Marker mark = builder_.mark();
builder_.advanceLexer();
mark.error("Got " + tokenType + " but expected " + expectedToken);
}
return expectedToken == tokenType;
}
/**
* Critical parser errors.
*/
public static class ParserErrorException extends RuntimeException {
public ParserErrorException(String message) {
super(message);
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
}
|
package com.haxademic.app.blobs;
import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.app.config.AppSettings;
import com.haxademic.core.data.constants.PBlendModes;
import com.haxademic.core.draw.color.ColorUtil;
import com.haxademic.core.draw.color.Gradients;
import com.haxademic.core.draw.context.PG;
import com.haxademic.core.draw.context.OpenGLUtil;
import com.haxademic.core.draw.filters.pshader.BlurHFilter;
import com.haxademic.core.draw.filters.pshader.BlurVFilter;
import com.haxademic.core.draw.filters.pshader.InvertFilter;
import com.haxademic.core.draw.filters.pshader.WobbleFilter;
import com.haxademic.core.draw.image.TickerScroller;
import com.haxademic.core.draw.shapes.Icosahedron;
import com.haxademic.core.draw.shapes.PShapeSolid;
import com.haxademic.core.draw.shapes.PShapeUtil;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.math.easing.Penner;
import processing.core.PGraphics;
import processing.core.PImage;
import processing.core.PShape;
import processing.opengl.PShader;
public class HaiBlobsSSAO
extends PAppletHax {
public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }
protected boolean DEBUG_MODE = false;
// gradient colors
// protected int COLOR_1 = ColorUtil.colorFromHex("#7B73DB");
// protected int COLOR_2 = ColorUtil.colorFromHex("#9B6CBB");
// protected int COLOR_3 = ColorUtil.colorFromHex("#FC655F");
// protected int COLOR_4 = ColorUtil.colorFromHex("#FD8C6B");
//inverted
protected int COLOR_1 = ColorUtil.colorFromHex("#848927");
protected int COLOR_2 = ColorUtil.colorFromHex("#659146");
protected int COLOR_3 = ColorUtil.colorFromHex("#05999c");
protected int COLOR_4 = ColorUtil.colorFromHex("#047390");
// objects
protected PGraphics sphereTexture1;
protected PGraphics sphereTexture2;
protected PShapeSolid shapeIcos_solid;
protected PShapeSolid shapeIcos__wire;
protected PGraphics overlayMask;
protected TickerScroller ticker;
protected PGraphics tickerFXBuffer;
// animation/noise/layout props
protected int _frames = 1500;
protected int icosaDetail = 4;
protected int noiseSeed = 853;
protected boolean debugNoiseSeed = false;
protected float circleMaskScale = 0.36f;
protected float blobScale = 0.26f; // 0.36f
protected float blobDeformAmp = 0.3f; // 0.7f
protected int noiseOctaves = 3;
protected float noiseFalloff = 0.55f;
// protected float wobbleStrength = .3f;
// protected float wobbleSize = 8f;
protected float wobbleStrength = .03f;
protected float wobbleSize = 5f;
protected boolean drawsOverlay = false;
protected float objScale = 1;
// animation progress
protected float progress;
protected float easedPercent;
protected float progressRadians;
// lighting props
public float directionLight = 180;
public float emissiveMaterial = 1f;
public float ambientLight = 50f;
public float specularMaterial = 50f;
public float specularLight = 100f;
public float shininessVal = 5f; // 50f
public float lightsFalloffVal = 0.12f;
public float lightsFalloffConstantVal = 0.12f;
protected void overridePropsFile() {
p.appConfig.setProperty( AppSettings.WIDTH, 1000 );
p.appConfig.setProperty( AppSettings.HEIGHT, 1000 );
p.appConfig.setProperty( AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH );
p.appConfig.setProperty( AppSettings.RENDERING_MOVIE, false );
p.appConfig.setProperty( AppSettings.RENDERING_MOVIE_START_FRAME, 1 );
p.appConfig.setProperty( AppSettings.RENDERING_MOVIE_STOP_FRAME, (int)_frames + 1 );
}
public void setup() {
super.setup();
p.noStroke();
p.noiseSeed(noiseSeed);
buildSSAO();
OpenGLUtil.setQuality(p.g, OpenGLUtil.GL_QUALITY_HIGH);
}
public void mouseMoved() {
super.mouseMoved();
if(debugNoiseSeed == false) return;
int newSeed = (int)P.map(p.mouseX, 0, p.width, 0, 1000f);
P.println("newSeed", newSeed);
p.noiseSeed(newSeed);
}
public void keyPressed() {
super.keyPressed();
if(p.key == 'd') DEBUG_MODE = !DEBUG_MODE;
}
protected void initObjects() {
buildOverlay();
builtGradientTextureLoop();
// shapeIcos_solid = newSolidIcos(p.width * blobScale, ticker.image());
// shapeIcos_solid = newSolidIcos(p.width * blobScale, null);
float icosaSize = p.width * blobScale;
PShape icos = Icosahedron.createIcosahedronGrouped(p, icosaDetail, ticker.image(), p.color(255), p.color(0, 0), 0.004f);
PShapeUtil.scaleShapeToExtent(icos, icosaSize);
// PShapeUtil.scaleObjToExtentVerticesAdjust(icos, icosaSize);
shapeIcos_solid = new PShapeSolid(icos);
// PShape icosWire = Icosahedron.createIcosahedronGrouped(p, icosaDetail, null, p.color(255,0,0,0), p.color(0), 0.004f);
// PShapeUtil.scaleShapeToExtent(icosWire, icosaSize);
// shapeIcos__wire = new PShapeSolid(icosWire);
}
protected void buildOverlay() {
overlayMask = p.createGraphics(p.width, p.height, P.P2D);
overlayMask.smooth(8);
overlayMask.beginDraw();
overlayMask.clear();
overlayMask.fill(0);
overlayMask.noStroke();
overlayMask.beginShape();
// Exterior part of shape, clockwise winding
overlayMask.vertex(0, 0);
overlayMask.vertex(overlayMask.width, 0);
overlayMask.vertex(overlayMask.width, overlayMask.height);
overlayMask.vertex(0, p.height);
// Interior part of shape, counter-clockwise winding
overlayMask.beginContour();
float segments = 360f;
float segmentRads = P.TWO_PI / segments;
float radius = overlayMask.width * circleMaskScale;
for(float i = 0; i < segments; i++) {
overlayMask.vertex(overlayMask.width * 0.5f + radius * P.cos(-i * segmentRads), overlayMask.height * 0.5f + radius * P.sin(-i * segmentRads));
}
overlayMask.endContour();
overlayMask.endShape(CLOSE);
overlayMask.endDraw();
}
protected void builtGradientTextureLoop() {
int textureW = p.width * 1;
int textureH = p.height;
int gradientW = textureW / 4;
PGraphics img = p.createGraphics(textureW, textureH, P.P2D);
img.smooth(8);
tickerFXBuffer = p.createGraphics(textureW, textureH, P.P2D);
tickerFXBuffer.smooth(8);
img.beginDraw();
img.noStroke();
img.translate(gradientW / 2, textureH/2);
Gradients.linear(img, gradientW, textureH, COLOR_1, COLOR_3);
img.translate(gradientW, 0);
Gradients.linear(img, gradientW, textureH, COLOR_3, COLOR_2);
img.translate(gradientW, 0);
Gradients.linear(img, gradientW, textureH, COLOR_2, COLOR_4);
img.translate(gradientW, 0);
Gradients.linear(img, gradientW, textureH, COLOR_4, COLOR_1);
img.endDraw();
BlurHFilter.instance(p).setBlurByPercent(0.5f, img.width);
BlurHFilter.instance(p).setBlurByPercent(0.5f, img.width);
BlurHFilter.instance(p).setBlurByPercent(0.5f, img.width);
BlurHFilter.instance(p).setBlurByPercent(0.5f, img.width);
ticker = new TickerScroller(img, p.color(255), textureW, textureH, (float)textureW / (float)_frames);
}
protected PShapeSolid newSolidIcos(float size, PImage texture) {
PShape group = createShape(GROUP);
PShape icos = Icosahedron.createIcosahedron(p.g, icosaDetail, texture);
PShapeUtil.scaleShapeToExtent(icos, size);
group.addChild(icos);
return new PShapeSolid(group);
}
// protected PShapeSolid newSolidIcosGrouped(float size, PImage texture) {
// PShape icos = Icosahedron.createIcosahedronGrouped(p, icosaDetail, texture);
// PShapeUtil.scaleSvgToExtent(icos, size);
// return new PShapeSolid(icos);
public void drawApp() {
if(p.frameCount == 1) initObjects();
p.background(0);
// PG.setDrawCenter(p);
// get progress
progress = ((float)(p.frameCount%_frames)/_frames);
easedPercent = Penner.easeInOutQuart(progress % 1, 0, 1, 1);
progressRadians = progress * P.TWO_PI;
// update textures
ticker.update();
tickerFXBuffer.beginDraw();
PG.setDrawCenter(tickerFXBuffer);
tickerFXBuffer.translate(tickerFXBuffer.width/2, tickerFXBuffer.height/2);
tickerFXBuffer.rotate(progressRadians);
tickerFXBuffer.scale(2);
tickerFXBuffer.image(ticker.image(), 0, 0);
tickerFXBuffer.endDraw();
WobbleFilter.instance(p).setTime(P.sin(progressRadians * 3f) * 0.9f);
WobbleFilter.instance(p).setStrength(wobbleStrength);
WobbleFilter.instance(p).setSize(wobbleSize);
WobbleFilter.instance(p).applyTo(tickerFXBuffer);
// draw blob
drawTextureOnSphere();
// hide controls
p.translate(100000, 0);
}
protected void drawTextureOnSphere() {
blobDeformAmp = 1.2f;
noiseOctaves = 4;
buffer.beginDraw();
buffer.clear();
buffer.pushMatrix();
buffer.translate(p.width * 0.5f, p.height * 0.5f);
buffer.rotateY(P.sin(progressRadians));
PG.setDrawCorner(buffer);
PG.setDrawCorner(p);
// shapeIcos_solid.shape().setTexture(ticker.image());
shapeIcos_solid.shape().setTexture(tickerFXBuffer);
// lights
// buffer.ambient(127);
buffer.lightSpecular(230, 230, 230);
// buffer.directionalLight(200, 200, 200, -0.0f, -0.0f, 1);
buffer.directionalLight(directionLight, directionLight, directionLight, 0.0f, 0.0f, -1);
// buffer.specular(p.color(200));
// buffer.shininess(15.0f);
// global lights & materials setup
// basic global lights:
buffer.lightFalloff(lightsFalloffConstantVal, lightsFalloffVal, 0.0f);
buffer.ambientLight(ambientLight, ambientLight, ambientLight);
// buffer.lightSpecular(specularLight, specularLight, specularLight);
// materials:
buffer.emissive(emissiveMaterial, emissiveMaterial, emissiveMaterial);
buffer.specular(specularMaterial, specularMaterial, specularMaterial);
buffer.shininess(shininessVal); // affects the specular blur
// draw solid sphere
// shapeIcos_solid.setVertexColorWithAudio(p.color(255,0,0));
// shapeIcos_solid.updateWithTrig(false, progress * 1f, 0.12f, 3.f);
// shapeIcos_solid.updateWithTrigGradient(progress * 1f, 0.12f, 3.f, ticker.image());
// shapeIcos_solid.updateWithNoise(progress * P.TWO_PI, 1f, blobDeformAmp, noiseOctaves, noiseFalloff);
shapeIcos_solid.updateWithTrigAndNoiseCombo(progress * P.TWO_PI, 0.1f, 0.2f, 0.75f, 1f, blobDeformAmp, noiseOctaves, noiseFalloff);
// shapeIcos__wire.updateWithTrigAndNoiseCombo(progress * P.TWO_PI, 0.10f, 3.f, 0.75f, 1f, blobDeformAmp, noiseOctaves, noiseFalloff);
buffer.pushMatrix();
// buffer.rotateX(P.map(p.mouseX, 0, p.width, 0, P.TWO_PI));
buffer.shape(shapeIcos_solid.shape());
// PShapeUtil.drawTriangles(p, shapeIcos_solid.shape());
// buffer.shape(shapeIcos__wire.shape());
buffer.popMatrix();
buffer.popMatrix();
buffer.endDraw();
// depth shader & SSAO
drawDepth();
// flat overlay
PG.setDrawFlat2d(p, true);
if(drawsOverlay == true) p.image(overlayMask, 0, 0);
p.image(buffer, 0, 0);
p.blendMode(PBlendModes.SCREEN);
p.image(ssao, 0, 0);
p.blendMode(PBlendModes.BLEND);
if(DEBUG_MODE == true) {
p.image(tickerFXBuffer, 0, 0);
// p.image(depth, 0, 0);
p.image(ssao, 0, 0);
// p.image(imageCycler.image(), 0, 0);
// p.image(ticker.image(), 0, 0);
}
PG.setDrawFlat2d(p, false);
// InvertFilter.instance(p).applyTo(p);
}
PGraphics buffer;
PGraphics depth;
PGraphics ssao;
PShader depthShader;
PShader ssaoShader;
protected String onlyAO = "onlyAO";
protected String aoClamp = "aoClamp";
protected String lumInfluence = "lumInfluence";
protected String cameraNear = "cameraNear";
protected String cameraFar = "cameraFar";
protected String samples = "samples";
protected String radius = "radius";
protected String useNoise = "useNoise";
protected String noiseAmount = "noiseAmount";
protected String diffArea = "diffArea";
protected String gDisplace = "gDisplace";
protected String diffMult = "diffMult";
protected String gaussMult = "gaussMult";
protected void buildSSAO() {
// values for render:
// cameraNear = 100f;
// cameraFar = 1130f;
// onlyAO = false;
// aoClamp = 0.89f;
// lumInfluence = 1.3f;
// samples = 128; // more
// useNoise = false;
// noiseAmount = 0;
// diffArea = 3.9f;
// gDisplace = 0;
// diffMult = 1000; // more
// gaussMult = -0.04f;
p.ui.addSlider(onlyAO, 0, 0, 1, 1, false);
p.ui.addSlider(aoClamp, 2f, -5f, 5f, 0.01f, false);
p.ui.addSlider(lumInfluence, -1.5f, -5f, 5f, 0.01f, false);
p.ui.addSlider(cameraNear, 300, 1, 500, 1, false);
p.ui.addSlider(cameraFar, 1280, 500f, 2000f, 1, false);
p.ui.addSlider(samples, 32, 2, 128, 1, false);
p.ui.addSlider(radius, 30, 0, 100, 0.02f, false);
p.ui.addSlider(diffArea, 0.5f, 0, 5, 0.01f, false);
p.ui.addSlider(gDisplace, 1.0f, 0, 5, 0.01f, false);
p.ui.addSlider(diffMult, 200f, 1, 1000, 1f, false);
p.ui.addSlider(gaussMult, -2, -4, 4, 0.01f, false);
p.ui.addSlider(useNoise, 1, 0, 1, 1, false);
p.ui.addSlider(noiseAmount, 0.00003f, 0.00003f, 0.003f, 0.00001f, false);
buffer = p.createGraphics(p.width, p.height, P.P3D);
buffer.smooth(OpenGLUtil.SMOOTH_HIGH);
OpenGLUtil.setTextureQualityHigh(buffer);
depth = p.createGraphics(p.width, p.height, P.P3D);
depth.smooth(OpenGLUtil.SMOOTH_HIGH);
OpenGLUtil.setTextureQualityHigh(depth);
ssao = p.createGraphics(p.width, p.height, P.P3D);
ssao.smooth(OpenGLUtil.SMOOTH_HIGH);
OpenGLUtil.setTextureQualityHigh(ssao);
depthShader = loadShader(
FileUtil.getFile("haxademic/shaders/vertex/depth-frag.glsl"),
FileUtil.getFile("haxademic/shaders/vertex/depth-vert.glsl")
);
ssaoShader = loadShader(
FileUtil.getFile("haxademic/shaders/vertex/ssao-frag.glsl"),
FileUtil.getFile("haxademic/shaders/vertex/ssao-vert.glsl")
);
ssaoShader.set("size", (float) p.width, (float) p.height );
ssaoShader.set("tDiffuse", buffer );
ssaoShader.set("tDepth", depth );
}
protected void drawDepth() {
depthShader.set("near", p.ui.value(cameraNear));
depthShader.set("far", p.ui.value(cameraFar));
ssaoShader.set("onlyAO", p.ui.value(onlyAO) == 1);
ssaoShader.set("aoClamp", p.ui.value(aoClamp));
ssaoShader.set("lumInfluence", p.ui.value(lumInfluence));
ssaoShader.set("cameraNear", p.ui.value(cameraNear));
ssaoShader.set("cameraFar", p.ui.value(cameraFar));
ssaoShader.set("samples", p.ui.valueInt(samples));
ssaoShader.set("radius", p.ui.value(radius));
ssaoShader.set("useNoise", p.ui.value(useNoise) == 1);
ssaoShader.set("noiseAmount", p.ui.value(noiseAmount));
ssaoShader.set("diffArea", p.ui.value(diffArea));
ssaoShader.set("gDisplace", p.ui.value(gDisplace));
ssaoShader.set("diffMult", p.ui.value(diffMult));
ssaoShader.set("gaussMult", p.ui.value(gaussMult));
// draw shapes to get depth map
depth.beginDraw();
depth.clear();
depth.translate(depth.width/2, depth.height/2);
depth.rotateY(P.sin(progressRadians));
depth.shader(depthShader);
depth.fill(0);
depth.noStroke();
// PShapeUtil.drawTriangles(depth, shapeIcos__wire.shape(), null, objScale);
PShapeUtil.drawTriangles(depth, shapeIcos_solid.shape(), null, objScale);
depth.endDraw();
ssaoShader.set("tDiffuse", buffer );
ssaoShader.set("tDepth", depth );
ssao.filter(ssaoShader);
// BlurVFilter.instance(p).setBlurByPercent(0.3f, ssao.width);
// BlurHFilter.instance(p).setBlurByPercent(0.3f, ssao.width);
// BlurVFilter.instance(p).applyTo(ssao);
// BlurHFilter.instance(p).applyTo(ssao);
}
}
|
package com.hp.hpl.jena.graph.impl;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.mem.GraphMem;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.impl.ModelCom;
import com.hp.hpl.jena.shared.*;
import java.io.*;
/**
A FileGraph is a memory-based graph that is optionally read in from a file
when it is created, and is written back when it is closed. It is not
particularly robust, alas.
TODO: consider a version which saves "every now and then"
@author hedgehog
*/
public class FileGraph extends GraphMem
{
File name;
Model model;
String lang;
/**
See FileCraph( f, create, strict, Reifier.Style ).
*/
public FileGraph( File f, boolean create, boolean strict )
{ this( f, create, strict, Reifier.Minimal ); }
/**
Construct a new FileGraph who's name is given by the specified File,
If create is true, this is a new file, and any existing file will be destroyed;
if create is false, this is an existing file, and its current contents will
be loaded. The language code for the file is guessed from its suffix.
@param f the File naming the associated file-system file
@param create true to create a new one, false to read an existing one
@param strict true to throw exceptions for create: existing, open: not found
@param style the reification style for the graph
*/
public FileGraph( File f, boolean create, boolean strict, Reifier.Style style )
{
super( style );
this.name = f;
this.model = new ModelCom( this );
this.lang = guessLang( this.name.toString() );
if (create)
{
if (f.exists() && strict) throw new AlreadyExistsException( f.toString() );
}
else
readModel( this.model, name.toString(), this.lang, strict );
}
private void readModel( Model m, String name, String lang, boolean strict )
{
FileInputStream in = null;
try
{
in = new FileInputStream( name );
model.read( in, "", this.lang );
}
catch (FileNotFoundException f)
{ if (strict) throw new DoesNotExistException( name ); }
finally
{
if (in != null) try {in.close();} catch (IOException ignore) {}
}
}
/**
As for FileGraph(File,boolean), except the name is given as a String.
*/
public FileGraph( String s, boolean create )
{ this( new File( s ), create, true ); }
public static FileGraph create()
{ return new FileGraph( GraphTestBase.tempFileName( "xxx", ".rdf" ), true, true );
}
/**
Guess the language of the specified file by looking at the suffix.
If it ends in .n3, assume N3; if it ends in .nt, assume N-TRIPLE;
otherwise assume RDF/XML.
@param name the pathname of the file to guess from
@return "N3", "N-TRIPLE", or "RDF/XML"
*/
public static String guessLang( String name )
{
String suffix = name.substring( name.lastIndexOf( '.' ) + 1 );
if (suffix.equals( "n3" )) return "N3";
if (suffix.equals( "nt" )) return "N-TRIPLE";
return "RDF/XML";
}
/**
Write out and then close this FileGraph. The graph is written out to the
named file in the language guessed from the suffix, and then the
parent close is invoked. The write-out goes to an intermediate file
first, which is then renamed to the correct name, to try and ensure
that the output is either done completely or not at all.
@see com.hp.hpl.jena.graph.Graph#close()
*/
public void close()
{
try
{
File intermediate = new File( name.getPath() + ".new" );
FileOutputStream out = new FileOutputStream( intermediate );
model.write( out, lang );
out.close();
updateFrom( intermediate );
super.close();
}
catch (IOException e)
{ throw new JenaException( e ); }
}
/**
The file intermediate has the new file contents. We want to move
them to the current file. renameTo doesn't have a powerful enough
semantics, so we anticipate failure and attempt to bypass it ...
<p>
If the rename works, that's fine. If it fails, we attempt to rename the
current file to name.old, rename name.new to name, and then
delete name.old; if bits of that don't work, we throw an exception.
*/
private void updateFrom( File intermediate )
{
if (intermediate.renameTo( name ) == false)
{
if (name.exists()) mustDelete( name );
mustRename( intermediate, name );
}
}
private void mustDelete( File f )
{ if (f.delete() == false) throw new JenaException( "could not delete " + f ); }
private void mustRename( File from, File to )
{
if (from.renameTo( to ) == false)
throw new JenaException( "could not rename " + from + " to " + to );
}
}
|
package ru.stqa.pft.addressbook.tests;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import java.util.Set;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
public class ContactDeletionTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.goTo().homePage();
if (app.db().contacts().size() == 0){
app.goTo().addNew();
app. contact().create(new ContactData().withFirstname("Ivan11").withLastname("Pomidorov")
.withAddress("Minsk, Gagarina 21/14").withHomePhone("+375 17 5544120")
.withMobilePhone("+375 29 6222552").withWorkPhone("4576895")
.withEmail("lkj@yui.io").withEmail2("ooo@iii.uu").withEmail3("yyy@uuu.gg")
.withGroup("test2"), true);
}
|
package com.rauljuarezjaramillo.cerocorrupcion.persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.appengine.api.utils.SystemProperty;
/**
* Clase ligera para el acceso a Base de Datos CCMX
* @author Appix Creative
*
*/
public class BD {
private static final String AES_KEY = "C3R0";
/**
* La conexion
*/
Connection c = null;
/**
* Crea una nueva instancia de esta clase
*/
public BD() {
}
/**
* Abre la conexion con la base de datos
*/
public void abrir() {
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://cerocorrupcionmx:ccmx/ccmx?user=root";
} else {
// Local MySQL instance to use during development.
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://173.194.85.206:3306/ccmx";
// Alternatively, connect to a Google Cloud SQL instance using:
// jdbc:mysql://ip-address-of-google-cloud-sql-instance:3306/guestbook?user=root
}
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
Connection conn = DriverManager.getConnection(url);
c = conn;
} catch (Exception ex) {
ex.printStackTrace();
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Cierra la conexion con la bd
*/
public void cerrar() {
try {
c.close();
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Metodo de utileria para cerrar un Statement, lidiando con excepciones
* @param stmt el Statement
*/
public void cerrar(Statement stmt) {
try {
stmt.close();
} catch (Exception ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Metodo de utileria para cerrar un Prepared Statement, lidiando con excepciones
* @param ps el PreparedStatement
*/
public void cerrar(PreparedStatement ps) {
try {
ps.close();
} catch (Exception ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Metodo de utileria para cerrar un ResultSet, lidiando con excepciones
* @param rs el ResultSet
*/
public void cerrar(ResultSet rs) {
try {
rs.close();
} catch (Exception ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Obtiene la conexion a la base de datos
* @return la conexion
*/
public Connection getConnection() {
return c;
}
/**
* Inserta un registro que representa un archivo
* @param idDenuncia
* @param archivo
* @param nombre
* @param extension
* @param mime
* @param ubicacion
* @param latitud
* @param longitud
* @param userId
* @return
*/
public int insertarArchivo(int idDenuncia, String archivo, String nombre, String extension, String mime, String ubicacion, double latitud,
double longitud, String userId) {
int id = -1;
try {
PreparedStatement stmt = c.prepareStatement(
"INSERT INTO EVIDENCIA(IDDENUNCIA, ARCHIVO, MIMETYPE, EXTENSION, NOMBRE, UBICACION, LATITUD, LONGITUD, USUARIOCREACION, FECHACREACION) "
+ " VALUES (?,?,?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, idDenuncia);
stmt.setString(2, archivo);
stmt.setString(3, mime);
stmt.setString(4, extension);
stmt.setString(5, nombre);
stmt.setString(6, ubicacion);
stmt.setDouble(7, latitud);
stmt.setDouble(8, longitud);
stmt.setString(9, userId);
stmt.setTimestamp(10, new Timestamp(System.currentTimeMillis()));
stmt.executeUpdate();
ResultSet resultSet = stmt.getGeneratedKeys();
while (resultSet.next()) {
id = resultSet.getInt(1);
}
resultSet.close();
stmt.close();
return id;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return -1;
}
/**
* Obtiene los archivos agregados a una denuncia
* @param idDenuncia el identificador de la denuncia
* @return la lita de archivos (evidencias)
*/
public List<Map<String, Object>> getArchivos(int idDenuncia) {
List<Map<String, Object>> lista = new ArrayList<Map<String, Object>>();
try {
Statement stmt = c.createStatement();
ResultSet resultSet = stmt
.executeQuery("SELECT IDEVIDENCIA, IDDENUNCIA, ARCHIVO, MIMETYPE, EXTENSION, NOMBRE, UBICACION, LATITUD, LONGITUD, USUARIOCREACION, FECHACREACION FROM EVIDENCIA WHERE IDDENUNCIA="
+ idDenuncia);
while (resultSet.next()) {
Map<String, Object> info = new HashMap<String, Object>();
info.put("IDEVIDENCIA", Integer.valueOf(resultSet.getInt(1)));
info.put("IDDENUNCIA", Integer.valueOf(resultSet.getInt(2)));
info.put("ARCHIVO", resultSet.getString(3));
info.put("MIMETYPE", resultSet.getString(4));
info.put("EXTENSION", resultSet.getString(5));
info.put("NOMBRE", resultSet.getString(6));
info.put("UBICACION", resultSet.getString(7));
info.put("LATITUD", Double.valueOf(resultSet.getDouble(8)));
info.put("LONGITUD", Double.valueOf(resultSet.getDouble(9)));
info.put("USUARIOCREACION", resultSet.getString(10));
info.put("FECHACREACION", new Date(resultSet.getTimestamp(11).getTime()));
lista.add(info);
}
resultSet.close();
stmt.close();
return lista;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
/**
* Obtiene los archivos agregados a una denuncia
* @param idDenuncia el identificador de la denuncia
* @return la lita de archivos (evidencias)
*/
public Map<String, Object> getArchivo(int idEvidencia) {
try {
Map<String, Object> info = new HashMap<String, Object>();
Statement stmt = c.createStatement();
ResultSet resultSet = stmt
.executeQuery("SELECT IDEVIDENCIA, IDDENUNCIA, ARCHIVO, MIMETYPE, EXTENSION, NOMBRE, UBICACION, LATITUD, LONGITUD, USUARIOCREACION, FECHACREACION FROM EVIDENCIA WHERE IDEVIDENCIA="
+ idEvidencia);
if (resultSet.next()) {
info.put("IDEVIDENCIA", Integer.valueOf(resultSet.getInt(1)));
info.put("IDDENUNCIA", Integer.valueOf(resultSet.getInt(2)));
info.put("ARCHIVO", resultSet.getString(3));
info.put("MIMETYPE", resultSet.getString(4));
info.put("EXTENSION", resultSet.getString(5));
info.put("NOMBRE", resultSet.getString(6));
info.put("UBICACION", resultSet.getString(7));
info.put("LATITUD", Double.valueOf(resultSet.getDouble(8)));
info.put("LONGITUD", Double.valueOf(resultSet.getDouble(9)));
info.put("USUARIOCREACION", resultSet.getString(10));
info.put("FECHACREACION", new Date(resultSet.getTimestamp(11).getTime()));
}
resultSet.close();
stmt.close();
return info;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public int ultimoIdInsertado() {
int id = -1;
try {
Statement stmt = c.createStatement();
ResultSet resultSet = stmt.getGeneratedKeys();
while (resultSet.next()) {
id = resultSet.getInt(1);
}
resultSet.close();
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return id;
}
/**
* Inserta un registro de denuncia
* @param tipo
* @param idEstatus
* @param folio
* @param idPersona
* @param persona
* @param hechos
* @param ubicacion
* @param latitud
* @param longitud
* @param anonima
* @param nombre
* @param direccion
* @param telefono
* @param correo
* @param idDenunciaLocal
* @param userId
* @return el identificador generado para la denuncia
*/
public int insertarDenuncia(int tipo, int idEstatus, String folio, int idPersona, String persona, String hechos, String ubicacion,
double latitud, double longitud, int anonima, String nombre, String direccion, String telefono, String correo, int idDenunciaLocal,
String userId) {
int id = -1;
try {
PreparedStatement stmt = c
.prepareStatement(
"INSERT INTO DENUNCIA(TIPODENUNCIA, IDESTATUS, FECHAESTATUS, FOLIO, IDPERSONA, NOMBREPERSONA, HECHOS, UBICACION, LATITUD, LONGITUD, ANONIMA, NOMBRE, DIRECCION, TELEFONO, CORREO, USUARIOCREACION, FECHACREACION, IDDENUNCIALOCAL) "
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, tipo);
stmt.setInt(2, idEstatus);
stmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
stmt.setString(4, folio);
stmt.setInt(5, idPersona);
stmt.setString(6, persona);
stmt.setString(7, hechos);
stmt.setString(8, ubicacion);
stmt.setDouble(9, latitud);
stmt.setDouble(10, longitud);
stmt.setInt(11, anonima);
stmt.setString(12, nombre);
stmt.setString(13, direccion);
stmt.setString(14, telefono);
stmt.setString(15, correo);
stmt.setString(16, userId);
stmt.setTimestamp(17, new Timestamp(System.currentTimeMillis()));
stmt.setInt(18, idDenunciaLocal);
stmt.executeUpdate();
ResultSet resultSet = stmt.getGeneratedKeys();
while (resultSet.next()) {
id = resultSet.getInt(1);
}
resultSet.close();
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return id;
}
/**
* Establece el folio de la denuncia
* @param idDenuncia el identificador de la denuncia
* @param folio el folio de la denuncia (debiera estar encriptado)
* @return true, si todo se ok, false en caso contrario
*/
public boolean actualizarFolioDenuncia(int idDenuncia, String folio) {
boolean b = false;
try {
PreparedStatement stmt = c.prepareStatement("UPDATE DENUNCIA SET FOLIO=? WHERE IDDENUNCIA=?");
stmt.setString(1, folio);
stmt.setInt(2, idDenuncia);
stmt.executeUpdate();
stmt.close();
b = true;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return b;
}
/**
* Obtiene la informacion y estatus de una denuncia
* @param idDenuncia el identificador de la denuncia
* @return mapa con la informacion de la denuncia
*/
public Map<String, Object> getDenuncia(int idDenuncia) {
Map<String, Object> info = new LinkedHashMap<String, Object>();
try {
Statement stmt = c.createStatement();
ResultSet resultSet = stmt
.executeQuery("SELECT IDDENUNCIA, TIPODENUNCIA, DENUNCIA.IDESTATUS,ESTATUS.DESCRIPCION ESTATUS, FECHAESTATUS, FOLIO, IDPERSONA, NOMBREPERSONA, HECHOS, UBICACION, LATITUD, LONGITUD, ANONIMA, NOMBRE, DIRECCION, TELEFONO, CORREO, USUARIOCREACION, FECHACREACION"
+ " FROM DENUNCIA" + " LEFT JOIN ESTATUS ON DENUNCIA.IDESTATUS=ESTATUS.IDESTATUS" + " WHERE IDDENUNCIA=" + idDenuncia);
if (resultSet.next()) {
System.out.println("denuncia encontrada");
info.put("IDDENUNCIA", Integer.valueOf(resultSet.getInt(1)));
info.put("TIPODENUNCIA", Integer.valueOf(resultSet.getInt(2)));
info.put("IDESTATUS", Integer.valueOf(resultSet.getInt(3)));
info.put("ESTATUS", resultSet.getString(4));
info.put("FECHAESTATUS", new Date(resultSet.getTimestamp(5).getTime()));
info.put("FOLIO", resultSet.getString(6));
info.put("IDPERSONA", Integer.valueOf(resultSet.getInt(7)));
info.put("PERSONA", resultSet.getString(8));
info.put("HECHOS", resultSet.getString(9));
info.put("UBICACION", resultSet.getString(10));
info.put("LATITUD", Double.valueOf(resultSet.getDouble(11)));
info.put("LONGITUD", Double.valueOf(resultSet.getDouble(12)));
info.put("ANONIMA", Integer.valueOf(resultSet.getInt(13)));
info.put("NOMBRE", resultSet.getString(14));
info.put("DIRECCION", resultSet.getString(15));
info.put("TELEFONO", resultSet.getString(16));
info.put("CORREO", resultSet.getString(17));
info.put("USUARIOCREACION", resultSet.getString(18));
info.put("FECHACREACION", new Date(resultSet.getTimestamp(19).getTime()));
} else {
System.out.println("denuncia no encontrado");
}
resultSet.close();
stmt.close();
return info;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return info;
}
/**
* Inserta un registro de sugerencia
* @param descripcion
* @param userId
* @return el identificador generado para la sugerencia
*/
public int insertarSugerencia(String descripcion, String userId) {
int id = -1;
try {
PreparedStatement stmt = c.prepareStatement("INSERT INTO SUGERENCIAS(COMENTARIOS,USUARIOCREACION, FECHACREACION) " + " VALUES(?, ?, ?)",
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, descripcion);
stmt.setString(2, userId);
stmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
stmt.executeUpdate();
ResultSet resultSet = stmt.getGeneratedKeys();
while (resultSet.next()) {
id = resultSet.getInt(1);
}
resultSet.close();
stmt.close();
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
return id;
}
/**
* Guarda la configuracion del usuario. Si la configuracion no existe la inserta, y en caso de existir solo la actualiza
* @param userId el usuario (id del dispositivo)
* @param geo si debe utilizarse la geolocalizacion
* @param push si deben enviarsele notificaciones push
* @return true, si todo ok, false en caso contrario
*/
public boolean insertarOActualizarConfiguracion(String userId, int geo, int push) {
boolean b=false;
int cont = 0;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = c.prepareStatement("SELECT COUNT(*) FROM CONFIG WHERE USUARIOCREACION=?");
stmt.setString(1, userId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
cont = resultSet.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
cerrar(resultSet);
cerrar(stmt);
}
if (cont == 0) {
try {
stmt = c.prepareStatement("INSERT INTO CONFIG(USUARIOCREACION, USARGEO, NOTIFICACIONESPUSH) VALUES(?, ?, ?)",
Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, userId);
stmt.setInt(2, geo);
stmt.setInt(3, push);
stmt.executeUpdate();
resultSet = stmt.getGeneratedKeys();
b=true;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
} finally {
cerrar(resultSet);
cerrar(stmt);
}
} else {
try {
stmt = c.prepareStatement("UPDATE CONFIG SET USARGEO=?, NOTIFICACIONESPUSH=? WHERE USUARIOCREACION=?");
stmt.setInt(1, geo);
stmt.setInt(2, push);
stmt.setString(3, userId);
stmt.executeUpdate();
b=true;
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
} finally {
cerrar(stmt);
}
}
return b;
}
/**
* De acuerdo con 'q' se buscan personas con nombre coincidente
* @param q parte del nombre a buscar
* @return lista de personas coincidentes
*/
public List<Map<String,String>> buscarPersonas(String q){
StringBuilder sb=new StringBuilder();
String split[]=q.split(" ");
for(int i =0;i<split.length;i++){
if(i>0){
sb.append(" ");
}
sb.append(split[i]).append("%");
}
System.out.println("sb="+sb);
PreparedStatement stmt=null;
ResultSet rs=null;
List<Map<String,String>> lista=new ArrayList<Map<String,String>>();
try {
stmt = c.prepareStatement("select CONCAT_WS(' ',NOMBRE,APATERNO,AMATERNO) NOMBRE,UNIDADADMINISTRATIVA AREA,CARGO SUBAREA from PERSONASPOT where NOMBRECOMPLETO like ? limit 10");
stmt.setString(1, sb.toString());
rs=stmt.executeQuery();
while(rs.next()){
Map<String,String> resultado=new HashMap<String, String>();
resultado.put("nombre", rs.getString(1));
resultado.put("area", rs.getString(2));
resultado.put("subarea", rs.getString(3));
lista.add(resultado);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
cerrar(rs);
cerrar(stmt);
}
return lista;
}
/**
* Obtiene el registro de configuracion de usuario (usar geolocalizacion, notificaciones push)
* @param userId el usuario
* @return la configuracion del usuario en caso de existir, la configuracion por defecto en caso contrario
*/
public Map<String,Object> getConfiguracionDeUsuario(String userId) {
Map<String,Object> mapa=new HashMap<String,Object>();
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
stmt = c.prepareStatement("SELECT USARGEO GEO, NOTIFICACIONESPUSH PUSH FROM CONFIG WHERE USUARIOCREACION=?");
stmt.setString(1, userId);
resultSet = stmt.executeQuery();
if(resultSet.next()){
mapa.put("GEO", resultSet.getInt(1));
mapa.put("PUSH", resultSet.getInt(2));
}
} catch (SQLException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
} finally {
cerrar(resultSet);
cerrar(stmt);
}
if(!mapa.containsKey("GEO")){//Si no se encontro en BD se regresa el default
mapa.put("GEO", 1);
mapa.put("PUSH", 1);
}
return mapa;
}
public int validarLogin(String usuario,String contrasena){
int idUsuario = 0;
try {
PreparedStatement stmt = c.prepareStatement(
"SELECT IDUSUARIO FROM USUARIO WHERE USUARIO=? AND AES_DECRYPT(PASSWORD, ?) = ?", Statement.KEEP_CURRENT_RESULT);
stmt.setString(1, usuario);
stmt.setString(2, AES_KEY);
stmt.setString(3, contrasena);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
idUsuario = resultSet.getInt("IDUSUARIO");
}
resultSet.close();
stmt.close();
return idUsuario;
} catch (Exception e) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, e);
}
return idUsuario;
}
public List obtenerDenuncias(int idEstatus){
List<Map<String, Object>> denuncias = new ArrayList<Map<String, Object>>();
String sql = " SELECT " +
" DEN.IDDENUNCIA," +
" CASE DEN.TIPODENUNCIA" +
" WHEN 1 THEN 'QUEJA' " +
" WHEN 2 THEN 'DENUNCIA'" +
" END TIPO," +
" STS.DESCRIPCION ESTATUS," +
" DEN.FECHAESTATUS," +
" DEN.FOLIO," +
" DEN.NOMBREPERSONA," +
" DEN.HECHOS," +
" DEN.UBICACION," +
" DEN.LATITUD," +
" DEN.LONGITUD," +
" CASE DEN.ANONIMA" +
" WHEN 1 THEN 'Si'" +
" WHEN 2 THEN 'No'" +
" END ANONIMA" +
" FROM " +
" DENUNCIA DEN" +
" LEFT JOIN" +
" ESTATUS STS ON DEN.IDESTATUS = STS.IDESTATUS" +
" WHERE" +
" DEN.IDESTATUS = ?" +
" ORDER BY" +
" FECHACREACION DESC" ;
try {
PreparedStatement stmt = c.prepareStatement(
sql, Statement.KEEP_CURRENT_RESULT);
stmt.setInt(1, idEstatus);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
Map<String, Object> den = new HashMap<String, Object>();
den.put("IDDENUNCIA", resultSet.getInt(1));
den.put("TIPO", resultSet.getString(2));
den.put("ESTATUS", resultSet.getString(3));
den.put("FECHAESTATUS", resultSet.getDate(4));
den.put("FOLIO", resultSet.getString(5));
den.put("NOMBREPERSONA", resultSet.getString(6));
den.put("HECHOS", resultSet.getString(7));
den.put("UBICACION", resultSet.getString(8));
den.put("LATITUD", resultSet.getBigDecimal(9));
den.put("LONGITUD", resultSet.getBigDecimal(10));
den.put("ANONIMA", resultSet.getString(11));
denuncias.add(den);
}
resultSet.close();
stmt.close();
return denuncias;
} catch (Exception e) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, e);
}
return null;
}
}
|
package com.ichmed.trinketeers.entity;
import static org.lwjgl.opengl.GL11.*;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
import com.ichmed.trinketeers.Game;
import com.ichmed.trinketeers.ai.Behaviour;
import com.ichmed.trinketeers.ai.waypoint.Waypoint;
import com.ichmed.trinketeers.util.AxisAllignedBoundingBox;
import com.ichmed.trinketeers.util.Loot;
import com.ichmed.trinketeers.util.render.GLHelper;
import com.ichmed.trinketeers.util.render.IWorldGraphic;
import com.ichmed.trinketeers.util.render.light.ILight;
import com.ichmed.trinketeers.world.World;
public class Entity implements IWorldGraphic, Waypoint
{
public Vector3f position = new Vector3f();
public Vector2f direction = new Vector2f(1, 0), size = new Vector2f(.1f, .1f);
public Vector2f preferredDirection = new Vector2f(1, 0);
public float speed = 0f;
public float preferredSpeed = 0f;
public float acceleration = 0.01f;
public Vector3f color = this.getColor();
public boolean isDead;
protected int despawnCountDown = 100;
public float health = 10, maxHealth = 10;
protected int maxCollisionIterations = 10;
protected int damageCooldown, maxDamageCooldown = 3;
public int stun = 0;
public boolean isSolid = true;
public boolean isVulnerable = true;
public int lifespan = -1;
public float rotation = 0;
public ILight light;
public boolean isMoveable = true;
public int ticksExisted = 0;
public boolean renderWhenDead = false, solidWhenDead = false, dropLootOnDeath = false;
public float lootRange = 2.0f;
public int lootValue = 5;
public List<Behaviour> behaviours = new ArrayList<>();
public Waypoint currentWaypoint;
public float visionRange = 0.7f;
public int attackCooldown, maxAttackcooldown;
public String name = "test";
public String behaviourString = null;
public void tick(World world)
{
behaviourString = null;
if (this.getLight() != null) this.getLight().setPosition(this.getCenter());
if (direction.length() > 0) direction.normalise();
if (this.isDead) despawnCountDown
if (this.lifespan == 0) this.kill(world);
this.damageCooldown
this.lifespan
this.stun
if (this.health <= 0) this.kill(world);
if (this.despawnCountDown <= 0) world.removeEntity(this);
this.ticksExisted++;
if (!this.isDead) for (int i = 0; i < Behaviour.MAX_PRIORITY; i++)
for (Behaviour b : behaviours)
if (b.getPriority(this) == i && b.isActive(this, world)) b.perform(this, world);
ArrayList<Entity> exclude = new ArrayList<>();
exclude.add(this);
if (this.damageCooldown > 0) this.color = new Vector3f(0.75f, 0.2f, 0.2f);
else this.color = this.getColor();
world.removeEntityFromChunk(this);
performRecursiveCollisionX(0, world, exclude);
performRecursiveCollisionY(0, world, exclude);
world.addEntityToChunk(this);
if (this.stun <= 0)
{
// Adjust speed
if (this.speed > this.preferredSpeed) this.speed -= Math.min(this.speed - this.preferredSpeed, this.acceleration);
if (this.speed < this.preferredSpeed) this.speed += Math.min(this.preferredSpeed - this.speed, this.acceleration);
this.direction = new Vector2f(this.preferredDirection);
} else if (this.speed > 0) this.speed -= Math.min(this.speed, this.acceleration);
if (this.isDead) this.speed = 0;
}
public void onSpawn(World w)
{
this.light = createLight();
if (this.light != null) w.addLight(this.getLight());
}
public ILight createLight()
{
return null;
}
public ILight getLight()
{
return this.light;
}
public void damage(float damage)
{
if (this.damageCooldown <= 0)
{
this.health -= damage;
this.damageCooldown = this.maxDamageCooldown;
}
}
private boolean performRecursiveCollisionX(int iteration, World world, ArrayList<Entity> exclude)
{
if (!this.isSolid)
{
this.position.translate(direction.x * this.speed, 0, 0);
return true;
}
if (iteration >= maxCollisionIterations) return false;
float speedMod = (float) Math.pow(2, iteration);
Vector2f iteratedSpeed = new Vector2f((this.direction.x / speedMod) * this.speed, 0);
AxisAllignedBoundingBox predictedPosition = new AxisAllignedBoundingBox(position.x + iteratedSpeed.x, position.y + iteratedSpeed.y, size.x, size.y);
if (world.getListOfIntersectingEntities(predictedPosition, exclude, true).size() == 0 && !world.isPositionStuckInGeometry(predictedPosition, (int)world.player.position.z))
{
this.position.translate(iteratedSpeed.x, iteratedSpeed.y, 0);
return true;
}
return performRecursiveCollisionX(iteration + 1, world, exclude);
}
private boolean performRecursiveCollisionY(int iteration, World world, ArrayList<Entity> exclude)
{
if (!this.isSolid)
{
this.position.translate(0, direction.y * this.speed, 0);
return true;
}
if (iteration >= maxCollisionIterations) return false;
float speedMod = (float) Math.pow(2, iteration);
Vector2f iteratedSpeed = new Vector2f(0, (this.direction.y / speedMod) * this.speed);
AxisAllignedBoundingBox predictedPosition = new AxisAllignedBoundingBox(position.x + iteratedSpeed.x, position.y + iteratedSpeed.y, size.x, size.y);
if (world.getListOfIntersectingEntities(predictedPosition, exclude, true).size() == 0 && !world.isPositionStuckInGeometry(predictedPosition, (int)world.player.position.z))
{
this.position.translate(iteratedSpeed.x, iteratedSpeed.y, 0);
return true;
}
return performRecursiveCollisionY(iteration + 1, world, exclude);
}
public List<Entity> getEntitiesExcludedFromCollision()
{
ArrayList<Entity> exclude = new ArrayList<>();
exclude.add(this);
return exclude;
}
public void render(World w)
{
if (!this.isDead || this.renderWhenDead) this.actualRender(w);
if (Game.renderHitBoxes) renderHitBox(w);
}
protected void actualRender(World w)
{
AxisAllignedBoundingBox renderArea = this.getRenderArea();
glPushMatrix();
glColor3f(this.color.x, this.color.y, this.color.z);
glTranslatef(renderArea.pos.x, renderArea.pos.y, 0);
glTranslated(renderArea.size.x / 2, renderArea.size.x / 2, 0);
glRotated(this.rotation, 0, 0, 1);
glTranslated(-renderArea.size.x / 2, -renderArea.size.y / 2, 0);
// GLHelper.drawRect(this.size.x, this.size.y);
GLHelper.renderTexturedQuad(0, 0, renderArea.size.x, renderArea.size.y, this.getTextureForState(w));
glColor3f(1, 1, 1);
glPopMatrix();
}
public String getTextureForState(World w)
{
if( this.behaviourString != null) return this.name + behaviourString;
if(this.isDead)return this.name + "Dead";
if(this.speed > 0)return this.name + "Moving";
return this.name + "Idle_" + (this.ticksExisted % 240) / 60;
}
protected void renderHitBox(World w)
{
glPushMatrix();
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_TEXTURE_2D);
glTranslatef(this.position.x, this.position.y, 0);
GLHelper.drawRect(this.size.x, this.size.y);
glColor3f(1, 1, 1);
glEnable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPopMatrix();
}
public boolean kill(World world)
{
if (this.isDead) return true;
this.isDead = true;
this.isSolid = this.solidWhenDead;
this.onDeath(world);
return this.isDead;
}
public Vector2f getCenter()
{
return new Vector2f(this.position.x + this.size.x / 2, this.position.y + this.size.y / 2);
}
public Entity setCenter(Vector2f v)
{
this.position = new Vector3f(v.x - this.size.x / 2, v.y - this.size.y / 2, 0);
return this;
}
public Entity setPosition(Vector2f v)
{
this.position = new Vector3f(v.x, v.y, this.position.z);
return this;
}
protected void onDeath(World world)
{
world.removeLight(this.getLight());
if (this.dropLootOnDeath)
{
Vector2f c = this.getCenter();
List<Entity> l = Loot.getLootForValue(this.lootValue);
for (int i = 0; i < l.size(); i++)
{
Vector2f p = new Vector2f(c.x + ((float) (Math.random() - 0.5) * this.lootRange), c.y + ((float) (Math.random() - 0.5) * this.lootRange));
world.spawn(l.get(i).setCenter(p), false);
}
}
}
public AxisAllignedBoundingBox getColissionBox()
{
return new AxisAllignedBoundingBox(this.position, this.size);
}
public Vector3f getColor()
{
return new Vector3f(1f, 1f, 1f);
}
public Vector2f getSize()
{
return size;
}
@Override
public float getY()
{
return this.position.y + this.size.y;
}
@Override
public void render()
{
}
public AxisAllignedBoundingBox getRenderArea()
{
return this.getColissionBox();
}
public boolean isHostile()
{
return false;
}
@Override
public Vector2f getPosition()
{
return new Vector2f(this.position.x, this.position.y);
}
public boolean isReached(Entity e)
{
return new Vector2f(this.position.x - e.position.x, this.position.y + e.position.y).length() <= this.getRadius();
}
@Override
public float getRadius()
{
return this.size.length();
}
}
|
package de.geeksfactory.opacclient.apis;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.acra.ACRA;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.apis.OpacApi.MultiStepResult.Status;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.storage.MetaDataSource;
/**
* OpacApi implementation for Web Opacs of the SISIS SunRise product, developed
* by OCLC.
*
* Restrictions: Bookmarks are only constantly supported if the library uses the
* BibTip extension.
*/
public class SISIS extends BaseApi implements OpacApi {
protected String opac_url = "";
protected JSONObject data;
protected MetaDataSource metadata;
protected boolean initialised = false;
protected String last_error;
protected Library library;
protected String CSId;
protected String identifier;
protected String reusehtml;
protected int resultcount = 10;
protected long logged_in;
protected Account logged_in_as;
protected final long SESSION_LIFETIME = 1000 * 60 * 3;
protected String ENCODING = "UTF-8";
protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>();
static {
defaulttypes.put("g", MediaType.EBOOK);
defaulttypes.put("d", MediaType.CD);
defaulttypes.put("0", MediaType.BOOK);
defaulttypes.put("1", MediaType.BOOK);
defaulttypes.put("2", MediaType.BOOK);
defaulttypes.put("3", MediaType.BOOK);
defaulttypes.put("4", MediaType.BOOK);
defaulttypes.put("6", MediaType.SCORE_MUSIC);
defaulttypes.put("7", MediaType.CD_MUSIC);
defaulttypes.put("8", MediaType.CD_MUSIC);
defaulttypes.put("12", MediaType.CD);
defaulttypes.put("13", MediaType.CD);
defaulttypes.put("14", MediaType.CD);
defaulttypes.put("15", MediaType.DVD);
defaulttypes.put("16", MediaType.CD);
defaulttypes.put("17", MediaType.MOVIE);
defaulttypes.put("18", MediaType.MOVIE);
defaulttypes.put("19", MediaType.MOVIE);
defaulttypes.put("20", MediaType.DVD);
defaulttypes.put("21", MediaType.SCORE_MUSIC);
defaulttypes.put("22", MediaType.BOARDGAME);
defaulttypes.put("26", MediaType.CD);
defaulttypes.put("27", MediaType.CD);
defaulttypes.put("28", MediaType.EBOOK);
defaulttypes.put("31", MediaType.BOARDGAME);
defaulttypes.put("36", MediaType.DVD);
defaulttypes.put("37", MediaType.CD);
defaulttypes.put("29", MediaType.AUDIOBOOK);
defaulttypes.put("41", MediaType.GAME_CONSOLE);
defaulttypes.put("42", MediaType.GAME_CONSOLE);
defaulttypes.put("46", MediaType.GAME_CONSOLE_NINTENDO);
defaulttypes.put("52", MediaType.EBOOK);
defaulttypes.put("56", MediaType.EBOOK);
defaulttypes.put("96", MediaType.EBOOK);
defaulttypes.put("97", MediaType.EBOOK);
defaulttypes.put("99", MediaType.EBOOK);
defaulttypes.put("EB", MediaType.EBOOK);
defaulttypes.put("buch01", MediaType.BOOK);
defaulttypes.put("buch02", MediaType.PACKAGE_BOOKS);
defaulttypes.put("buch03", MediaType.BOOK);
defaulttypes.put("buch04", MediaType.PACKAGE_BOOKS);
defaulttypes.put("buch05", MediaType.PACKAGE_BOOKS);
}
@Override
public String[] getSearchFields() {
return new String[] { KEY_SEARCH_QUERY_FREE, KEY_SEARCH_QUERY_TITLE,
KEY_SEARCH_QUERY_AUTHOR, KEY_SEARCH_QUERY_KEYWORDA,
KEY_SEARCH_QUERY_KEYWORDB, KEY_SEARCH_QUERY_HOME_BRANCH,
KEY_SEARCH_QUERY_BRANCH, KEY_SEARCH_QUERY_ISBN,
KEY_SEARCH_QUERY_YEAR, KEY_SEARCH_QUERY_SYSTEM,
KEY_SEARCH_QUERY_AUDIENCE, KEY_SEARCH_QUERY_PUBLISHER };
}
@Override
public String getLast_error() {
return last_error;
}
public void extract_meta(Document doc) {
// Zweigstellen auslesen
Elements zst_opts = doc.select("#selectedSearchBranchlib option");
metadata.open();
metadata.clearMeta(library.getIdent());
for (int i = 0; i < zst_opts.size(); i++) {
Element opt = zst_opts.get(i);
if (!opt.val().equals(""))
metadata.addMeta(MetaDataSource.META_TYPE_BRANCH,
library.getIdent(), opt.val(), opt.text());
}
zst_opts = doc.select("#selectedViewBranchlib option");
List<String[]> metas = new ArrayList<String[]>();
for (int i = 0; i < zst_opts.size(); i++) {
Element opt = zst_opts.get(i);
if (!opt.val().equals("")) {
if (opt.attr("selected").length() != 0)
metas.add(0, new String[] { opt.val(), opt.text() });
else
metas.add(new String[] { opt.val(), opt.text() });
}
}
for (String[] meta : metas) {
metadata.addMeta(MetaDataSource.META_TYPE_HOME_BRANCH,
library.getIdent(), meta[0], meta[1]);
}
metadata.close();
}
@Override
public void start() throws ClientProtocolException, SocketException,
IOException, NotReachableException {
// Some libraries require start parameters for start.do, like Login=foo
String startparams = "";
if (data.has("startparams")) {
try {
startparams = "?" + data.getString("startparams");
} catch (JSONException e) {
e.printStackTrace();
}
}
String html = httpGet(opac_url + "/start.do" + startparams, ENCODING);
initialised = true;
Document doc = Jsoup.parse(html);
CSId = doc.select("input[name=CSId]").val();
metadata.open();
if (!metadata.hasMeta(library.getIdent())) {
metadata.close();
extract_meta(doc);
} else {
metadata.close();
}
}
@Override
public void init(MetaDataSource metadata, Library lib) {
super.init(metadata, lib);
this.metadata = metadata;
this.library = lib;
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
} catch (JSONException e) {
ACRA.getErrorReporter().handleException(e);
}
}
public static String getStringFromBundle(Bundle bundle, String key) {
// Workaround for Bundle.getString(key, default) being available not
// before API 12
String res = bundle.getString(key);
if (res == null)
res = "";
return res;
}
protected int addParameters(Bundle query, String key, String searchkey,
List<NameValuePair> params, int index) {
if (!query.containsKey(key) || query.getString(key).equals(""))
return index;
if (index != 0)
params.add(new BasicNameValuePair("combinationOperator[" + index
+ "]", "AND"));
params.add(new BasicNameValuePair("searchCategories[" + index + "]",
searchkey));
params.add(new BasicNameValuePair("searchString[" + index + "]", query
.getString(key)));
return index + 1;
}
@Override
public SearchRequestResult search(Bundle query) throws IOException,
NotReachableException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
if (query.containsKey("volume")) {
params.add(new BasicNameValuePair("methodToCall", "volumeSearch"));
params.add(new BasicNameValuePair("dbIdentifier", query
.getString("dbIdentifier")));
params.add(new BasicNameValuePair("catKey", query
.getString("catKey")));
params.add(new BasicNameValuePair("periodical", "N"));
} else {
int index = 0;
start();
params.add(new BasicNameValuePair("methodToCall", "submit"));
params.add(new BasicNameValuePair("CSId", CSId));
params.add(new BasicNameValuePair("methodToCallParameter",
"submitSearch"));
index = addParameters(query, KEY_SEARCH_QUERY_FREE, "-1", params,
index);
index = addParameters(query, KEY_SEARCH_QUERY_TITLE, "331", params,
index);
index = addParameters(query, KEY_SEARCH_QUERY_AUTHOR, "100",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_ISBN, "540", params,
index);
index = addParameters(query, KEY_SEARCH_QUERY_KEYWORDA, "902",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_KEYWORDB, "710",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_YEAR, "425", params,
index);
index = addParameters(query, KEY_SEARCH_QUERY_PUBLISHER, "412",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_SYSTEM, "700",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_AUDIENCE, "1001",
params, index);
index = addParameters(query, KEY_SEARCH_QUERY_LOCATION, "714",
params, index);
if (index == 0) {
last_error = "Es wurden keine Suchkriterien eingegeben.";
return null;
}
if (index > 4) {
last_error = "Diese Bibliothek unterstützt nur bis zu vier benutzte Suchkriterien.";
return null;
}
params.add(new BasicNameValuePair("submitSearch", "Suchen"));
params.add(new BasicNameValuePair("callingPage", "searchParameters"));
params.add(new BasicNameValuePair("numberOfHits", "10"));
params.add(new BasicNameValuePair("selectedSearchBranchlib", query
.getString(KEY_SEARCH_QUERY_BRANCH)));
if (query.getString(KEY_SEARCH_QUERY_HOME_BRANCH) != null) {
if (!query.getString(KEY_SEARCH_QUERY_HOME_BRANCH).equals(""))
params.add(new BasicNameValuePair("selectedViewBranchlib",
query.getString(KEY_SEARCH_QUERY_HOME_BRANCH)));
}
}
String html = httpGet(
opac_url + "/search.do?"
+ URLEncodedUtils.format(params, "UTF-8"), ENCODING);
return parse_search(html, 1);
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
NotReachableException {
if (!initialised)
start();
String html = httpGet(opac_url
+ "/hitList.do?methodToCall=pos&identifier=" + identifier
+ "&curPos=" + (((page - 1) * resultcount) + 1), ENCODING);
return parse_search(html, page);
}
protected SearchRequestResult parse_search(String html, int page) {
Document doc = Jsoup.parse(html);
doc.setBaseUri(opac_url + "/searchfoo");
if (doc.select(".error").size() > 0) {
last_error = doc.select(".error").text().trim();
return null;
} else if (doc.select(".nohits").size() > 0) {
last_error = doc.select(".nohits").text().trim();
return null;
} else if (doc.select(".box-header h2").text()
.contains("keine Treffer")) {
return new SearchRequestResult(new ArrayList<SearchResult>(), 0, 1,
1);
}
int results_total = -1;
String resultnumstr = doc.select(".box-header h2").first().text();
if (resultnumstr.contains("(1/1)") || resultnumstr.contains(" 1/1")) {
reusehtml = html;
last_error = "is_a_redirect";
return null;
} else if (resultnumstr.contains("(")) {
results_total = Integer.parseInt(resultnumstr.replaceAll(
".*\\(([0-9]+)\\).*", "$1"));
} else if (resultnumstr.contains(": ")) {
results_total = Integer.parseInt(resultnumstr.replaceAll(
".*: ([0-9]+)$", "$1"));
}
Elements table = doc.select("table.data tbody tr");
identifier = null;
Elements links = doc.select("table.data a");
boolean haslink = false;
for (int i = 0; i < links.size(); i++) {
Element node = links.get(i);
if (node.hasAttr("href")
& node.attr("href").contains("singleHit.do") && !haslink) {
haslink = true;
try {
List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI(
((Element) node).attr("href").replace(" ", "%20")
.replace("&", "&")), ENCODING);
for (NameValuePair nv : anyurl) {
if (nv.getName().equals("identifier")) {
identifier = nv.getValue();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
List<SearchResult> results = new ArrayList<SearchResult>();
for (int i = 0; i < table.size(); i++) {
Element tr = table.get(i);
SearchResult sr = new SearchResult();
if (tr.select("td img").size() > 0) {
String[] fparts = tr.select("td img").get(0).attr("src")
.split("/");
String fname = fparts[fparts.length - 1];
if (data.has("mediatypes")) {
try {
sr.setType(MediaType.valueOf(data.getJSONObject(
"mediatypes").getString(fname)));
} catch (JSONException e) {
sr.setType(defaulttypes.get(fname.toLowerCase()
.replace(".jpg", "").replace(".gif", "")
.replace(".png", "")));
} catch (IllegalArgumentException e) {
sr.setType(defaulttypes.get(fname.toLowerCase()
.replace(".jpg", "").replace(".gif", "")
.replace(".png", "")));
}
} else {
sr.setType(defaulttypes.get(fname.toLowerCase()
.replace(".jpg", "").replace(".gif", "")
.replace(".png", "")));
}
}
String alltext = tr.text();
if (alltext.contains("eAudio") || alltext.contains("eMusic"))
sr.setType(MediaType.MP3);
else if (alltext.contains("eVideo"))
sr.setType(MediaType.EVIDEO);
else if (alltext.contains("eBook"))
sr.setType(MediaType.EBOOK);
else if (alltext.contains("Munzinger"))
sr.setType(MediaType.EDOC);
if (tr.children().size() > 3
&& tr.child(3).select("img[title*=cover]").size() == 1) {
sr.setCover(tr.child(3).select("img[title*=cover]")
.attr("abs:src"));
if (sr.getCover().contains("showCover.do"))
downloadCover(sr);
}
Element middlething;
if (tr.children().size() > 2)
middlething = tr.child(2);
else
middlething = tr.child(1);
List<Node> children = middlething.childNodes();
if (middlething.select("div")
.not("#hlrightblock,.bestellfunktionen").size() == 1) {
Element indiv = middlething.select("div")
.not("#hlrightblock,.bestellfunktionen").first();
if (indiv.children().size() > 1)
children = indiv.childNodes();
} else if (middlething.select("span.titleData").size() == 1) {
children = middlething.select("span.titleData").first()
.childNodes();
}
int childrennum = children.size();
List<String[]> strings = new ArrayList<String[]>();
for (int ch = 0; ch < childrennum; ch++) {
Node node = children.get(ch);
if (node instanceof TextNode) {
String text = ((TextNode) node).text().trim();
if (text.length() > 3)
strings.add(new String[] { "text", "", text });
} else if (node instanceof Element) {
List<Node> subchildren = node.childNodes();
for (int j = 0; j < subchildren.size(); j++) {
Node subnode = subchildren.get(j);
if (subnode instanceof TextNode) {
String text = ((TextNode) subnode).text().trim();
if (text.length() > 3)
strings.add(new String[] {
((Element) node).tag().getName(),
"text", text,
((Element) node).className(),
((Element) node).attr("style") });
} else if (subnode instanceof Element) {
String text = ((Element) subnode).text().trim();
if (text.length() > 3)
strings.add(new String[] {
((Element) node).tag().getName(),
((Element) subnode).tag().getName(),
text, ((Element) node).className(),
((Element) node).attr("style") });
}
}
}
}
StringBuilder description = null;
if (tr.select("span.Z3988").size() == 1) {
// Sometimes there is a <span class="Z3988"> item which provides
// data in a standardized format.
List<NameValuePair> z3988data;
boolean hastitle = false;
try {
description = new StringBuilder();
z3988data = URLEncodedUtils.parse(new URI("http://dummy/?"
+ tr.select("span.Z3988").attr("title")), "UTF-8");
for (NameValuePair nv : z3988data) {
if (nv.getValue() != null) {
if (!nv.getValue().trim().equals("")) {
if (nv.getName().equals("rft.btitle")
&& !hastitle) {
description.append("<b>" + nv.getValue()
+ "</b>");
hastitle = true;
} else if (nv.getName().equals("rft.atitle")
&& !hastitle) {
description.append("<b>" + nv.getValue()
+ "</b>");
hastitle = true;
} else if (nv.getName().equals("rft.au")) {
description
.append("<br />" + nv.getValue());
} else if (nv.getName().equals("rft.date")) {
description
.append("<br />" + nv.getValue());
}
}
}
}
} catch (URISyntaxException e) {
description = null;
}
}
boolean described = false;
if (description != null && description.length() > 0) {
sr.setInnerhtml(description.toString());
described = true;
} else {
description = new StringBuilder();
}
int k = 0;
boolean yearfound = false;
boolean titlefound = false;
boolean sigfound = false;
for (String[] part : strings) {
if (!described) {
if (part[0] == "a" && (k == 0 || !titlefound)) {
if (k != 0)
description.append("<br />");
description.append("<b>" + part[2] + "</b>");
titlefound = true;
} else if (part[2].matches("\\D*[0-9]{4}\\D*")
&& part[2].length() <= 10) {
yearfound = true;
if (k != 0)
description.append("<br />");
description.append(part[2]);
} else if (k == 1 && !yearfound
&& part[2].matches("^\\s*\\([0-9]{4}\\)$")) {
if (k != 0)
description.append("<br />");
description.append(part[2]);
} else if (k == 1 && !yearfound
&& part[2].matches("^\\s*\\([0-9]{4}\\)$")) {
if (k != 0)
description.append("<br />");
description.append(part[2]);
} else if (k > 1 && k < 4 && !sigfound
&& part[0].equals("text")
&& part[2].matches("^[A-Za-z0-9,\\- ]+$")) {
description.append("<br />");
description.append(part[2]);
}
}
if (part.length == 4) {
if (part[0].equals("span") && part[3].equals("textgruen")) {
sr.setStatus(SearchResult.Status.GREEN);
} else if (part[0].equals("span")
&& part[3].equals("textrot")) {
sr.setStatus(SearchResult.Status.RED);
}
} else if (part.length == 5) {
if (part[4].contains("purple")) {
sr.setStatus(SearchResult.Status.YELLOW);
}
}
if (sr.getStatus() == null) {
if (part[2].contains("entliehen")
&& part[2]
.startsWith("Vormerkung ist leider nicht möglich")) {
sr.setStatus(SearchResult.Status.RED);
} else if (part[2].startsWith("entliehen")
|| part[2]
.contains("Ein Exemplar finden Sie in einer anderen Zweigstelle")) {
sr.setStatus(SearchResult.Status.YELLOW);
} else if ((part[2].startsWith("bestellbar") && !part[2]
.contains("nicht bestellbar"))
|| (part[2].startsWith("vorbestellbar") && !part[2]
.contains("nicht vorbestellbar"))
|| (part[2].startsWith("vorbestellbar") && !part[2]
.contains("nicht vorbestellbar"))
|| (part[2].startsWith("vormerkbar") && !part[2]
.contains("nicht vormerkbar"))
|| (part[2].contains("heute zurückgebucht"))
|| (part[2].contains("ausleihbar") && !part[2]
.contains("nicht ausleihbar"))) {
sr.setStatus(SearchResult.Status.GREEN);
}
if (sr.getType() != null) {
if (sr.getType().equals(MediaType.EBOOK)
|| sr.getType().equals(MediaType.EVIDEO)
|| sr.getType().equals(MediaType.MP3))
// Especially Onleihe.de ebooks are often marked
// green though they are not available.
sr.setStatus(SearchResult.Status.UNKNOWN);
}
}
k++;
}
if (!described)
sr.setInnerhtml(description.toString());
sr.setNr(10 * (page - 1) + i);
sr.setId(null);
results.add(sr);
}
resultcount = results.size();
return new SearchRequestResult(results, results_total, page);
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException, NotReachableException {
if (id == null && reusehtml != null) {
return parse_result(reusehtml);
}
// Some libraries require start parameters for start.do, like Login=foo
String startparams = "";
if (data.has("startparams")) {
try {
startparams = data.getString("startparams") + "&";
} catch (JSONException e) {
e.printStackTrace();
}
}
String hbp = "";
if (homebranch != null)
hbp = "&selectedViewBranchlib=" + homebranch;
String html = httpGet(opac_url + "/start.do?" + startparams
+ "searchType=1&Query=0%3D%22" + id + "%22" + hbp, ENCODING);
return parse_result(html);
}
@Override
public DetailledItem getResult(int nr) throws IOException {
String html = httpGet(
opac_url
+ "/singleHit.do?tab=showExemplarActive&methodToCall=showHit&curPos="
+ (nr + 1) + "&identifier=" + identifier, ENCODING);
return parse_result(html);
}
protected DetailledItem parse_result(String html) throws IOException {
Document doc = Jsoup.parse(html);
doc.setBaseUri(opac_url);
String html2 = httpGet(opac_url
+ "/singleHit.do?methodToCall=activateTab&tab=showTitleActive",
ENCODING);
Document doc2 = Jsoup.parse(html2);
doc2.setBaseUri(opac_url);
String html3 = httpGet(
opac_url
+ "/singleHit.do?methodToCall=activateTab&tab=showAvailabilityActive",
ENCODING);
Document doc3 = Jsoup.parse(html3);
doc3.setBaseUri(opac_url);
DetailledItem result = new DetailledItem();
try {
result.setId(doc.select("#bibtip_id").text().trim());
} catch (Exception ex) {
ex.printStackTrace();
}
List<String> reservationlinks = new ArrayList<String>();
for (Element link : doc3.select("#vormerkung a, #tab-content a")) {
Uri href = Uri.parse(link.absUrl("href"));
if (result.getId() == null) {
// ID retrieval
String key = href.getQueryParameter("katkey");
if (key != null) {
result.setId(key);
break;
}
}
// Vormerken
if (href.getQueryParameter("methodToCall") != null) {
if (href.getQueryParameter("methodToCall").equals(
"doVormerkung")
|| href.getQueryParameter("methodToCall").equals(
"doBestellung"))
reservationlinks.add(href.getQuery());
}
}
if (reservationlinks.size() == 1) {
result.setReservable(true);
result.setReservation_info(reservationlinks.get(0));
} else if (reservationlinks.size() == 0) {
result.setReservable(false);
} else {
// TODO: Multiple options - handle this case!
}
if (doc.select(".data td img").size() == 1) {
result.setCover(doc.select(".data td img").first().attr("abs:src"));
downloadCover(result);
}
if (doc.select(".aw_teaser_title").size() == 1) {
result.setTitle(doc.select(".aw_teaser_title").first().text()
.trim());
} else if (doc.select(".data td strong").size() > 0) {
result.setTitle(doc.select(".data td strong").first().text().trim());
} else {
result.setTitle("");
}
if (doc.select(".aw_teaser_title_zusatz").size() > 0) {
result.addDetail(new Detail("Titelzusatz", doc
.select(".aw_teaser_title_zusatz").text().trim()));
}
String title = "";
String text = "";
Element detailtrs = doc2.select("#tab-content .data td").first();
if (detailtrs != null) {
for (Node node : detailtrs.childNodes()) {
if (node instanceof Element) {
if (((Element) node).tagName().equals("strong")) {
if (!text.equals("") && !title.equals("")) {
result.addDetail(new Detail(title.trim(), text
.trim()));
if (title.equals("Titel:")) {
result.setTitle(text.trim());
}
text = "";
}
title = ((Element) node).text().trim();
} else {
if (((Element) node).tagName().equals("a")
&& ((Element) node).text().trim()
.contains("hier klicken")) {
text = text + ((Element) node).attr("href");
} else {
text = text + ((Element) node).text();
}
}
} else if (node instanceof TextNode) {
text = text + ((TextNode) node).text();
}
}
} else {
if (doc2.select("#tab-content .fulltitle tr").size() > 0) {
Elements rows = doc2.select("#tab-content .fulltitle tr");
for (Element tr : rows) {
if (tr.children().size() == 2) {
Element valcell = tr.child(1);
String value = valcell.text().trim();
if (valcell.select("a").size() == 1) {
value = valcell.select("a").first().absUrl("href");
}
result.addDetail(new Detail(tr.child(0).text().trim(),
value));
}
}
} else {
result.addDetail(new Detail("Fehler",
"Details konnten nicht abgerufen werden, bitte erneut probieren!"));
}
}
if (!text.equals("") && !title.equals("")) {
result.addDetail(new Detail(title.trim(), text.trim()));
if (title.equals("Titel:")) {
result.setTitle(text.trim());
}
}
for (Element link : doc3.select("#tab-content a")) {
Uri href = Uri.parse(link.absUrl("href"));
if (result.getId() == null) {
// ID retrieval
String key = href.getQueryParameter("katkey");
if (key != null) {
result.setId(key);
break;
}
}
}
Map<String, Integer> copy_columnmap = new HashMap<String, Integer>();
// Default values
copy_columnmap.put(DetailledItem.KEY_COPY_BARCODE, 1);
copy_columnmap.put(DetailledItem.KEY_COPY_BRANCH, 3);
copy_columnmap.put(DetailledItem.KEY_COPY_STATUS, 4);
Elements copy_columns = doc.select("#tab-content .data tr#bg2 th");
for (int i = 0; i < copy_columns.size(); i++) {
Element th = copy_columns.get(i);
String head = th.text().trim();
if (head.contains("Status")) {
copy_columnmap.put(DetailledItem.KEY_COPY_STATUS, i);
}
if (head.contains("Zweigstelle")) {
copy_columnmap.put(DetailledItem.KEY_COPY_BRANCH, i);
}
if (head.contains("Mediennummer")) {
copy_columnmap.put(DetailledItem.KEY_COPY_BARCODE, i);
}
if (head.contains("Standort")) {
copy_columnmap.put(DetailledItem.KEY_COPY_LOCATION, i);
}
if (head.contains("Signatur")) {
copy_columnmap.put(DetailledItem.KEY_COPY_SHELFMARK, i);
}
}
Pattern status_lent = Pattern
.compile("^(entliehen) bis ([0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}) \\(gesamte Vormerkungen: ([0-9]+)\\)$");
Pattern status_and_barcode = Pattern.compile("^(.*) ([0-9A-Za-z]+)$");
Elements exemplartrs = doc.select("#tab-content .data tr").not("#bg2");
for (Element tr : exemplartrs) {
try {
ContentValues e = new ContentValues();
Element status = tr.child(copy_columnmap
.get(DetailledItem.KEY_COPY_STATUS));
Element barcode = tr.child(copy_columnmap
.get(DetailledItem.KEY_COPY_BARCODE));
String barcodetext = barcode.text().trim()
.replace(" Wegweiser", "");
// STATUS
String statustext = "";
if (status.getElementsByTag("b").size() > 0) {
statustext = status.getElementsByTag("b").text().trim();
} else {
statustext = status.text().trim();
}
if (copy_columnmap.get(DetailledItem.KEY_COPY_STATUS) == copy_columnmap
.get(DetailledItem.KEY_COPY_BARCODE)) {
Matcher matcher1 = status_and_barcode.matcher(statustext);
if (matcher1.matches()) {
statustext = matcher1.group(1);
barcodetext = matcher1.group(2);
}
}
Matcher matcher = status_lent.matcher(statustext);
if (matcher.matches()) {
e.put(DetailledItem.KEY_COPY_STATUS, matcher.group(1));
e.put(DetailledItem.KEY_COPY_RETURN, matcher.group(2));
e.put(DetailledItem.KEY_COPY_RESERVATIONS, matcher.group(3));
} else {
e.put(DetailledItem.KEY_COPY_STATUS, statustext);
}
e.put(DetailledItem.KEY_COPY_BARCODE, barcodetext);
String branchtext = tr
.child(copy_columnmap
.get(DetailledItem.KEY_COPY_BRANCH)).text()
.trim().replace(" Wegweiser", "");
e.put(DetailledItem.KEY_COPY_BRANCH, branchtext);
if (copy_columnmap.containsKey(DetailledItem.KEY_COPY_LOCATION)) {
e.put(DetailledItem.KEY_COPY_LOCATION,
tr.child(
copy_columnmap
.get(DetailledItem.KEY_COPY_LOCATION))
.text().trim().replace(" Wegweiser", ""));
}
if (copy_columnmap
.containsKey(DetailledItem.KEY_COPY_SHELFMARK)) {
e.put(DetailledItem.KEY_COPY_SHELFMARK,
tr.child(
copy_columnmap
.get(DetailledItem.KEY_COPY_SHELFMARK))
.text().trim().replace(" Wegweiser", ""));
}
result.addCopy(e);
} catch (Exception ex) {
ex.printStackTrace();
}
}
try {
Element isvolume = null;
Bundle volume = new Bundle();
Elements links = doc.select(".data td a");
int elcount = links.size();
for (int eli = 0; eli < elcount; eli++) {
List<NameValuePair> anyurl = URLEncodedUtils.parse(new URI(
links.get(eli).attr("href")), "UTF-8");
for (NameValuePair nv : anyurl) {
if (nv.getName().equals("methodToCall")
&& nv.getValue().equals("volumeSearch")) {
isvolume = links.get(eli);
} else if (nv.getName().equals("catKey")) {
volume.putString("catKey", nv.getValue());
} else if (nv.getName().equals("dbIdentifier")) {
volume.putString("dbIdentifier", nv.getValue());
}
}
if (isvolume != null) {
volume.putBoolean("volume", true);
result.setVolumesearch(volume);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
public ReservationResult reservation(DetailledItem item, Account acc,
int useraction, String selection) throws IOException {
String reservation_info = item.getReservation_info();
final String branch_inputfield = "issuepoint";
Document doc = null;
String action = "reservation";
if (reservation_info.contains("doBestellung")) {
action = "order";
}
if (useraction == ReservationResult.ACTION_CONFIRMATION) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("methodToCall", action));
nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
String html = httpPost(opac_url + "/" + action + ".do",
new UrlEncodedFormEntity(nameValuePairs), ENCODING);
doc = Jsoup.parse(html);
} else if (selection == null || useraction == 0) {
String html = httpGet(opac_url + "/availability.do?"
+ reservation_info, ENCODING);
doc = Jsoup.parse(html);
if (doc.select("input[name=username]").size() > 0) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username", acc
.getName()));
nameValuePairs.add(new BasicNameValuePair("password", acc
.getPassword()));
nameValuePairs.add(new BasicNameValuePair("methodToCall",
"submit"));
nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
nameValuePairs.add(new BasicNameValuePair("login_action",
"Login"));
html = httpPost(opac_url + "/login.do",
new UrlEncodedFormEntity(nameValuePairs), ENCODING);
doc = Jsoup.parse(html);
if (doc.getElementsByClass("error").size() == 0) {
logged_in = System.currentTimeMillis();
logged_in_as = acc;
}
}
if (doc.select("input[name=" + branch_inputfield + "]").size() > 0) {
ContentValues branches = new ContentValues();
for (Element option : doc
.select("input[name=" + branch_inputfield + "]")
.first().parent().parent().parent().select("td")) {
if (option.select("input").size() != 1)
continue;
String value = option.text().trim();
String key = option.select("input").val();
branches.put(key, value);
}
ReservationResult result = new ReservationResult(
MultiStepResult.Status.SELECTION_NEEDED);
result.setActionIdentifier(ReservationResult.ACTION_BRANCH);
result.setSelection(branches);
return result;
}
} else if (useraction == ReservationResult.ACTION_BRANCH) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair(branch_inputfield,
selection));
nameValuePairs.add(new BasicNameValuePair("methodToCall", action));
nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
String html = httpPost(opac_url + "/" + action + ".do",
new UrlEncodedFormEntity(nameValuePairs), ENCODING);
doc = Jsoup.parse(html);
}
if (doc == null)
return new ReservationResult(MultiStepResult.Status.ERROR);
if (doc.getElementsByClass("error").size() >= 1) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.getElementsByClass("error").get(0).text());
}
if (doc.getElementsByClass("textrot").size() >= 1) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.getElementsByClass("textrot").get(0).text());
}
if (doc.select("#CirculationForm p").size() > 0) {
List<String[]> details = new ArrayList<String[]>();
for (String row : doc.select("#CirculationForm p").first().html()
.split("<br />")) {
Document frag = Jsoup.parseBodyFragment(row);
if (frag.text().contains(":")) {
String[] split = frag.text().split(":");
if (split.length >= 2)
details.add(new String[] { split[0].trim() + ":",
split[1].trim() });
} else {
details.add(new String[] { "", frag.text().trim() });
}
}
ReservationResult result = new ReservationResult(
Status.CONFIRMATION_NEEDED);
result.setDetails(details);
return result;
}
return new ReservationResult(Status.OK);
}
@Override
public ProlongResult prolong(String a, Account account, int useraction,
String Selection) throws IOException {
// the URI of the page this item was found on and the query string the
// prolonging link links to, seperated by a $.
if (a.startsWith("§")) {
return new ProlongResult(MultiStepResult.Status.ERROR,
a.substring(1));
}
String[] parts = a.split("\\$");
String offset = parts[0];
String query = parts[1];
if (!initialised)
start();
if (System.currentTimeMillis() - logged_in > SESSION_LIFETIME
|| logged_in_as == null) {
try {
account(account);
} catch (JSONException e) {
e.printStackTrace();
return new ProlongResult(MultiStepResult.Status.ERROR);
}
} else if (logged_in_as.getId() != account.getId()) {
try {
account(account);
} catch (JSONException e) {
e.printStackTrace();
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
// We have to call the page we originally found the link on first...
httpGet(opac_url + "/userAccount.do?methodToCall=showAccount&typ=1",
ENCODING);
if (offset != "1")
httpGet(opac_url
+ "/userAccount.do?methodToCall=pos&accountTyp=AUSLEIHEN&anzPos="
+ offset, ENCODING);
String html = httpGet(opac_url + "/userAccount.do?" + query, ENCODING);
Document doc = Jsoup.parse(html);
if (doc.select("#middle .textrot").size() > 0) {
return new ProlongResult(MultiStepResult.Status.ERROR, doc
.select("#middle .textrot").first().text());
}
return new ProlongResult(MultiStepResult.Status.OK);
}
@Override
public boolean cancel(Account account, String a) throws IOException,
NotReachableException {
if (!initialised)
start();
String[] parts = a.split("\\$");
String type = parts[0];
String offset = parts[1];
String query = parts[2];
if (System.currentTimeMillis() - logged_in > SESSION_LIFETIME
|| logged_in_as == null) {
try {
account(account);
} catch (JSONException e) {
e.printStackTrace();
return false;
}
} else if (logged_in_as.getId() != account.getId()) {
try {
account(account);
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
// We have to call the page we originally found the link on first...
httpGet(opac_url + "/userAccount.do?methodToCall=showAccount&typ="
+ type, ENCODING);
if (offset != "1")
httpGet(opac_url + "/userAccount.do?methodToCall=pos&anzPos="
+ offset, ENCODING);
httpGet(opac_url + "/userAccount.do?" + query, ENCODING);
return true;
}
protected boolean login(Account acc) {
String html;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
try {
String loginPage;
loginPage = httpGet(opac_url
+ "/userAccount.do?methodToCall=show&type=1", ENCODING);
Document loginPageDoc = Jsoup.parse(loginPage);
if (loginPageDoc.select("input[name=as_fid]").size() > 0)
nameValuePairs.add(new BasicNameValuePair("as_fid",
loginPageDoc.select("input[name=as_fid]").first()
.attr("value")));
} catch (IOException e1) {
e1.printStackTrace();
}
nameValuePairs.add(new BasicNameValuePair("username", acc.getName()));
nameValuePairs
.add(new BasicNameValuePair("password", acc.getPassword()));
nameValuePairs.add(new BasicNameValuePair("CSId", CSId));
nameValuePairs.add(new BasicNameValuePair("methodToCall", "submit"));
try {
html = httpPost(opac_url + "/login.do", new UrlEncodedFormEntity(
nameValuePairs), ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Document doc = Jsoup.parse(html);
if (doc.getElementsByClass("error").size() > 0) {
last_error = doc.getElementsByClass("error").get(0).text();
return false;
}
logged_in = System.currentTimeMillis();
logged_in_as = acc;
return true;
}
protected void parse_medialist(List<ContentValues> medien, Document doc,
int offset) throws ClientProtocolException, IOException {
Elements copytrs = doc.select(".data tr");
doc.setBaseUri(opac_url);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
int trs = copytrs.size();
if (trs == 1)
return;
assert (trs > 0);
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
ContentValues e = new ContentValues();
if (tr.text().contains("keine Daten")) {
return;
}
e.put(AccountData.KEY_LENT_TITLE, tr.child(1).select("strong")
.text().trim());
try {
e.put(AccountData.KEY_LENT_AUTHOR,
tr.child(1).html().split("<br />")[1].trim());
String[] col2split = tr.child(2).html().split("<br />");
String frist = col2split[0].trim();
if (frist.contains("-"))
frist = frist.split("-")[1].trim();
e.put(AccountData.KEY_LENT_DEADLINE, frist);
if (col2split.length > 1)
e.put(AccountData.KEY_LENT_BRANCH, col2split[1].trim());
if (!frist.equals("")) {
try {
e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP,
sdf.parse(
e.getAsString(AccountData.KEY_LENT_DEADLINE))
.getTime());
} catch (ParseException e1) {
e1.printStackTrace();
}
}
if (tr.select("a").size() > 0) {
for (Element link : tr.select("a")) {
Uri uri = Uri.parse(link.attr("abs:href"));
if (uri.getQueryParameter("methodToCall").equals(
"renewalPossible")) {
e.put(AccountData.KEY_LENT_LINK,
offset + "$" + uri.getQuery());
break;
}
}
} else if (tr.select(".textrot, .textgruen").size() == 1) {
e.put(AccountData.KEY_LENT_LINK,
"§" + tr.select(".textrot, .textgruen").text());
}
} catch (Exception ex) {
ex.printStackTrace();
}
medien.add(e);
}
assert (medien.size() == trs - 1);
}
protected void parse_reslist(String type, List<ContentValues> reservations,
Document doc, int offset) throws ClientProtocolException,
IOException {
Elements copytrs = doc.select(".data tr");
doc.setBaseUri(opac_url);
int trs = copytrs.size();
if (trs == 1)
return;
assert (trs > 0);
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
ContentValues e = new ContentValues();
if (tr.text().contains("keine Daten")) {
return;
}
e.put(AccountData.KEY_RESERVATION_TITLE,
tr.child(1).select("strong").text().trim());
try {
String[] rowsplit1 = tr.child(1).html().split("<br />");
String[] rowsplit2 = tr.child(2).html().split("<br />");
if (rowsplit1.length > 1)
e.put(AccountData.KEY_RESERVATION_AUTHOR,
rowsplit1[1].trim());
if (rowsplit2.length > 2)
e.put(AccountData.KEY_RESERVATION_BRANCH,
rowsplit2[2].trim());
if (tr.select("a").size() == 1)
e.put(AccountData.KEY_RESERVATION_CANCEL,
type
+ "$"
+ offset
+ "$"
+ Uri.parse(tr.select("a").attr("abs:href"))
.getQuery());
} catch (Exception ex) {
ex.printStackTrace();
}
reservations.add(e);
}
assert (reservations.size() == trs - 1);
}
@Override
public AccountData account(Account acc) throws IOException,
NotReachableException, JSONException, SocketException {
start(); // TODO: Is this necessary?
int resultNum;
if (!login(acc))
return null;
// Geliehene Medien
String html = httpGet(opac_url
+ "/userAccount.do?methodToCall=showAccount&typ=1", ENCODING);
List<ContentValues> medien = new ArrayList<ContentValues>();
Document doc = Jsoup.parse(html);
doc.setBaseUri(opac_url);
parse_medialist(medien, doc, 1);
if (doc.select(".box-right").size() > 0) {
for (Element link : doc.select(".box-right").first().select("a")) {
Uri uri = Uri.parse(link.attr("abs:href"));
if (uri == null
|| uri.getQueryParameter("methodToCall") == null)
continue;
if (uri.getQueryParameter("methodToCall").equals("pos")
&& !"1".equals(uri.getQueryParameter("anzPos"))) {
html = httpGet(uri.toString(), ENCODING);
parse_medialist(medien, Jsoup.parse(html),
Integer.parseInt(uri.getQueryParameter("anzPos")));
}
}
}
if (doc.select("#label1").size() > 0) {
resultNum = 0;
String rNum = doc.select("#label1").first().text().trim()
.replaceAll(".*\\(([0-9]*)\\).*", "$1");
if (rNum.length() > 0)
resultNum = Integer.parseInt(rNum);
assert (resultNum == medien.size());
}
// Bestellte Medien
html = httpGet(opac_url
+ "/userAccount.do?methodToCall=showAccount&typ=6", ENCODING);
List<ContentValues> reserved = new ArrayList<ContentValues>();
doc = Jsoup.parse(html);
doc.setBaseUri(opac_url);
parse_reslist("6", reserved, doc, 1);
Elements label6 = doc.select("#label6");
if (doc.select(".box-right").size() > 0) {
for (Element link : doc.select(".box-right").first().select("a")) {
Uri uri = Uri.parse(link.attr("abs:href"));
if (uri == null
|| uri.getQueryParameter("methodToCall") == null)
break;
if (uri.getQueryParameter("methodToCall").equals("pos")
&& !"1".equals(uri.getQueryParameter("anzPos"))) {
html = httpGet(uri.toString(), ENCODING);
parse_reslist("6", medien, Jsoup.parse(html),
Integer.parseInt(uri.getQueryParameter("anzPos")));
}
}
}
// Vorgemerkte Medien
html = httpGet(opac_url
+ "/userAccount.do?methodToCall=showAccount&typ=7", ENCODING);
doc = Jsoup.parse(html);
doc.setBaseUri(opac_url);
parse_reslist("7", reserved, doc, 1);
if (doc.select(".box-right").size() > 0) {
for (Element link : doc.select(".box-right").first().select("a")) {
Uri uri = Uri.parse(link.attr("abs:href"));
if (uri == null
|| uri.getQueryParameter("methodToCall") == null)
break;
if (uri.getQueryParameter("methodToCall").equals("pos")
&& !"1".equals(uri.getQueryParameter("anzPos"))) {
html = httpGet(uri.toString(), ENCODING);
parse_reslist("7", medien, Jsoup.parse(html),
Integer.parseInt(uri.getQueryParameter("anzPos")));
}
}
}
if (label6.size() > 0 && doc.select("#label7").size() > 0) {
resultNum = 0;
String rNum = label6.text().trim()
.replaceAll(".*\\(([0-9]*)\\).*", "$1");
if (rNum.length() > 0)
resultNum = Integer.parseInt(rNum);
rNum = doc.select("#label7").text().trim()
.replaceAll(".*\\(([0-9]*)\\).*", "$1");
if (rNum.length() > 0)
resultNum += Integer.parseInt(rNum);
assert (resultNum == reserved.size());
}
AccountData res = new AccountData(acc.getId());
if (doc.select("#label8").size() > 0) {
String text = doc.select("#label8").first().text().trim();
if (text.matches("Geb.+hren[^\\(]+\\(([0-9.,]+)[^0-9€A-Z]*(€|EUR|CHF|Fr)\\)")) {
text = text
.replaceAll(
"Geb.+hren[^\\(]+\\(([0-9.,]+)[^0-9€A-Z]*(€|EUR|CHF|Fr)\\)",
"$1 $2");
res.setPendingFees(text);
}
}
Pattern p = Pattern.compile("[^0-9.]*", Pattern.MULTILINE);
if (doc.select(".box3").size() > 0) {
for (Element box : doc.select(".box3")) {
if (box.select("strong").size() == 1) {
String text = box.select("strong").text();
if (text.equals("Jahresgebühren")) {
text = box.text();
text = p.matcher(text).replaceAll("");
res.setValidUntil(text);
}
}
}
}
res.setLent(medien);
res.setReservations(reserved);
return res;
}
@Override
public boolean isAccountSupported(Library library) {
return true;
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account acc)
throws ClientProtocolException, SocketException, IOException,
NotReachableException {
return null;
}
@Override
public String getShareUrl(String id, String title) {
String startparams = "";
if (data.has("startparams")) {
try {
startparams = data.getString("startparams") + "&";
} catch (JSONException e) {
e.printStackTrace();
}
}
if (id != null && id != "")
return opac_url + "/start.do?" + startparams
+ "searchType=1&Query=0%3D%22" + id + "%22";
else
return opac_url + "/start.do?" + startparams
+ "searchType=1&Query=-1%3D%22" + title + "%22";
}
@Override
public int getSupportFlags() {
return 0;
}
@Override
public boolean prolongAll(Account account) throws IOException {
return false;
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException, NotReachableException {
// TODO Auto-generated method stub
return null;
}
}
|
package com.codepunk.demo.interactiveimageview.version6;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.ArrayRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.math.MathUtils;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.OverScroller;
import com.codepunk.demo.R;
import com.codepunk.demo.support.DisplayCompat;
import static android.graphics.Matrix.MSCALE_X;
import static android.graphics.Matrix.MSCALE_Y;
import static android.graphics.Matrix.MTRANS_X;
import static android.graphics.Matrix.MTRANS_Y;
import static java.lang.Float.NaN;
public class InteractiveImageView extends AppCompatImageView
implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener,
ScaleGestureDetector.OnScaleGestureListener {
//region Nested classes
private static class Initializer {
final GestureDetectorCompat gestureDetector;
final ScaleGestureDetector scaleGestureDetector;
final OverScroller overScroller;
final Transformer transformer;
Initializer(InteractiveImageView view) {
final Context context = view.getContext();
gestureDetector = new GestureDetectorCompat(context, view);
gestureDetector.setIsLongpressEnabled(false);
gestureDetector.setOnDoubleTapListener(view);
scaleGestureDetector = new ScaleGestureDetector(context, view);
overScroller = new OverScroller(context);
transformer = new Transformer(context);
}
}
@SuppressWarnings("WeakerAccess")
protected static class Transformer {
/**
* The interpolator, used for making zooms animate 'naturally.'
*/
private Interpolator mInterpolator;
/**
* The total animation duration for a zoom.
*/
private int mAnimationDurationMillis;
/**
* Whether or not the current zoom has finished.
*/
private boolean mFinished = true;
/**
* The X value of the pivot point.
*/
private float mPx;
/**
* The Y value of the pivot point.
*/
private float mPy;
/**
* The current scale X value; computed by {@link #computeScroll()}.
*/
private float mCurrentSx;
/**
* The current scale Y value; computed by {@link #computeScroll()}.
*/
private float mCurrentSy;
/**
* The current X location of the pivot point; computed by {@link #computeScroll()}.
*/
private float mCurrentX;
/**
* The current Y location of the pivot point; computed by {@link #computeScroll()}.
*/
private float mCurrentY;
/**
* The time the zoom started, computed using {@link SystemClock#elapsedRealtime()}.
*/
private long mStartRTC;
private float mStartSx;
private float mStartSy;
private float mStartX;
private float mStartY;
/**
* The destination scale X.
*/
private float mEndSx;
/**
* The destination scale Y.
*/
private float mEndSy;
/**
* The destination X location of the pivot point.
*/
private float mEndX;
/**
* The destination Y location of the pivot point.
*/
private float mEndY;
public Transformer(Context context) {
mInterpolator = new DecelerateInterpolator();
mAnimationDurationMillis =
context.getResources().getInteger(android.R.integer.config_shortAnimTime);
}
/**
* Aborts the animation, setting the current values to the ending value.
*
* @see android.widget.Scroller#abortAnimation()
*/
void abortAnimation() {
mFinished = true;
mCurrentSx = mEndSx;
mCurrentSy = mEndSy;
mCurrentX = mEndX;
mCurrentY = mEndY;
}
/**
* Forces the zoom finished state to the given value. Unlike {@link #abortAnimation()}, the
* current zoom value isn't set to the ending value.
*
* @see android.widget.Scroller#forceFinished(boolean)
*/
void forceFinished(boolean finished) {
mFinished = finished;
}
/**
* Starts a scroll from the supplied start values to the supplied end values.
*
* @see android.widget.Scroller#startScroll(int, int, int, int)
*/
void startTransform(
float px,
float py,
float startSx,
float startSy,
float startX,
float startY,
float endSx,
float endSy,
float endX,
float endY) {
mStartRTC = SystemClock.elapsedRealtime();
mPx = px;
mPy = py;
mCurrentSx = mStartSx = startSx;
mCurrentSy = mStartSy = startSy;
mCurrentX = mStartX = startX;
mCurrentY = mStartY = startY;
mEndSx = endSx;
mEndSy = endSy;
mEndX = endX;
mEndY = endY;
mFinished = false;
}
/**
* Computes the current scroll, returning true if the zoom is still active and false if the
* scroll has finished.
*
* @see android.widget.Scroller#computeScrollOffset()
*/
boolean computeTransform() {
if (mFinished) {
return false;
}
long tRTC = SystemClock.elapsedRealtime() - mStartRTC;
if (tRTC >= mAnimationDurationMillis) {
mFinished = true;
mCurrentSx = mEndSx;
mCurrentSy = mEndSy;
mCurrentX = mEndX;
mCurrentY = mEndY;
return false;
}
float t = tRTC * 1f / mAnimationDurationMillis;
float interpolation = mInterpolator.getInterpolation(t);
mCurrentSx = mStartSx + (mEndSx - mStartSx) * interpolation;
mCurrentSy = mStartSy + (mEndSy - mStartSy) * interpolation;
mCurrentX = mStartX + (mEndX - mStartX) * interpolation;
mCurrentY = mStartY + (mEndY - mStartY) * interpolation;
return true;
}
/**
* Returns the current scale X.
*
* @see android.widget.Scroller#getCurrX()
*/
float getCurrScaleX() {
return mCurrentSx;
}
/**
* Returns the current scale Y.
*
* @see android.widget.Scroller#getCurrX()
*/
float getCurrScaleY() {
return mCurrentSy;
}
/**
* Returns the current translation X.
*
* @see android.widget.Scroller#getCurrX()
*/
float getCurrX() {
return mCurrentX;
}
/**
* Returns the current translation Y.
*
* @see android.widget.Scroller#getCurrX()
*/
float getCurrY() {
return mCurrentY;
}
/**
* Returns the pivot X.
*/
float getPx() {
return mPx;
}
/**
* Returns the pivot Y.
*/
float getPy() {
return mPy;
}
}
//endregion Nested classes
//region Constants
private static final String LOG_TAG = InteractiveImageView.class.getSimpleName();
private static final float MAX_SCALE_BREADTH_MULTIPLIER = 4.0f;
private static final float MAX_SCALE_LENGTH_MULTIPLIER = 6.0f;
private static final float ZOOM_PIVOT_EPSILON = 0.2f;
@SuppressWarnings("unused")
public static final int INTERACTIVITY_FLAG_NONE = 0;
public static final int INTERACTIVITY_FLAG_SCROLL = 0x00000001;
public static final int INTERACTIVITY_FLAG_FLING = 0x00000002;
public static final int INTERACTIVITY_FLAG_SCALE = 0x00000004;
public static final int INTERACTIVITY_FLAG_DOUBLE_TAP = 0x00000008;
public static final int INTERACTIVITY_FLAG_ALL = INTERACTIVITY_FLAG_SCROLL |
INTERACTIVITY_FLAG_FLING |
INTERACTIVITY_FLAG_SCALE |
INTERACTIVITY_FLAG_DOUBLE_TAP;
private static final int INVALID_FLAG_BASELINE_IMAGE_MATRIX = 0x00000001;
private static final int INVALID_FLAG_IMAGE_MAX_SCALE = 0x00000002;
private static final int INVALID_FLAG_IMAGE_MIN_SCALE = 0x00000004;
private static final int INVALID_FLAG_DEFAULT = INVALID_FLAG_BASELINE_IMAGE_MATRIX |
INVALID_FLAG_IMAGE_MAX_SCALE |
INVALID_FLAG_IMAGE_MIN_SCALE;
private static final String KEY_ANIMATE = "animate";
private static final String KEY_PX = "px";
private static final String KEY_PY = "py";
private static final String KEY_SX = "sx";
private static final String KEY_SY = "sy";
private static final String KEY_X = "x";
private static final String KEY_Y = "y";
//endregion Constants
//region Fields
@NonNull
private final GestureDetectorCompat mGestureDetector;
@NonNull
private final ScaleGestureDetector mScaleGestureDetector;
@NonNull
private final OverScroller mOverScroller;
@NonNull
private final Transformer mTransformer;
private int mInteractivity;
private float[] mZoomPivots;
private ScaleType mScaleType = super.getScaleType();
private float mMaxScaleX;
private float mMaxScaleY;
private float mMinScaleX;
private float mMinScaleY;
private float mLastScrollPx;
private float mLastScrollPy;
private float mLastScrollX;
private float mLastScrollY;
private float mLastSpan;
private boolean mNeedsDown;
private final float[] mMatrixValues = new float[9];
private final float[] mSrcPts = new float[2];
private final float[] mDstPts = new float[2];
private final Matrix mBaselineImageMatrix = new Matrix();
private final Matrix mImageMatrix = new Matrix();
private final Matrix mNewImageMatrix = new Matrix();
private final RectF mSrcRect = new RectF();
private final RectF mDstRect = new RectF();
private final Object mLock = new Object();
private Bundle mPendingTransformation = null;
private int mInvalidFlags;
//endregion Fields
//region Constructors
public InteractiveImageView(Context context) {
super(context);
final Initializer initializer = initializeInteractiveImageView(
context,
null,
R.attr.interactiveImageViewStyle,
0);
mGestureDetector = initializer.gestureDetector;
mScaleGestureDetector = initializer.scaleGestureDetector;
mOverScroller = initializer.overScroller;
mTransformer = initializer.transformer;
}
public InteractiveImageView(Context context, AttributeSet attrs) {
super(context, attrs);
final Initializer initializer = initializeInteractiveImageView(
context,
attrs,
R.attr.interactiveImageViewStyle,
0);
mGestureDetector = initializer.gestureDetector;
mScaleGestureDetector = initializer.scaleGestureDetector;
mOverScroller = initializer.overScroller;
mTransformer = initializer.transformer;
}
public InteractiveImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final Initializer initializer =
initializeInteractiveImageView(context, attrs, defStyleAttr, 0);
mGestureDetector = initializer.gestureDetector;
mScaleGestureDetector = initializer.scaleGestureDetector;
mOverScroller = initializer.overScroller;
mTransformer = initializer.transformer;
}
//endregion Constructors
//region Inherited methods
@Override
public void computeScroll() {
super.computeScroll();
synchronized (mLock) {
boolean needsInvalidate = false;
if (mOverScroller.computeScrollOffset()) {
getImageMatrixInternal(mImageMatrix);
mNewImageMatrix.set(mImageMatrix);
mNewImageMatrix.getValues(mMatrixValues);
mMatrixValues[MTRANS_X] = mOverScroller.getCurrX();
mMatrixValues[MTRANS_Y] = mOverScroller.getCurrY();
mNewImageMatrix.setValues(mMatrixValues);
// TODO Can I call setImageTransformInternal here?
if (!mImageMatrix.equals(mNewImageMatrix)) {
if (super.getScaleType() != ScaleType.MATRIX) {
super.setScaleType(ScaleType.MATRIX);
}
super.setImageMatrix(mNewImageMatrix);
needsInvalidate = true;
}
} else if (mTransformer.computeTransform()) {
needsInvalidate = setImageTransformInternal(
mTransformer.getCurrScaleX(),
mTransformer.getCurrScaleY(),
mTransformer.getPx(),
mTransformer.getPy(),
mTransformer.getCurrX(),
mTransformer.getCurrY());
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
} else {
mOverScroller.abortAnimation();
mTransformer.abortAnimation();
}
}
}
@Override
public ScaleType getScaleType() {
return mScaleType;
}
@Override
public void layout(int l, int t, int r, int b) {
super.layout(l, t, r, b);
if (mPendingTransformation != null) {
// TODO We can also defer this to when we have a layout AND a drawable?
final float sx = mPendingTransformation.getFloat(KEY_SX);
final float sy = mPendingTransformation.getFloat(KEY_SY);
final float px = mPendingTransformation.getFloat(KEY_PX);
final float py = mPendingTransformation.getFloat(KEY_PY);
final float x = mPendingTransformation.getFloat(KEY_X, getDefaultTargetX());
final float y = mPendingTransformation.getFloat(KEY_Y, getDefaultTargetY());
final boolean animate = mPendingTransformation.getBoolean(KEY_ANIMATE);
mPendingTransformation = null;
setImageTransform(sx, sy, px, py, x, y, animate);
}
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean retVal = false;
if (drawableHasIntrinsicSize()) {
retVal = mGestureDetector.onTouchEvent(event) ||
mScaleGestureDetector.onTouchEvent(event);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
onUp(event);
}
return retVal || super.onTouchEvent(event);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mInvalidFlags |= INVALID_FLAG_DEFAULT;
}
@Override
public void setImageDrawable(@Nullable Drawable drawable) {
super.setImageDrawable(drawable);
// setScaleType(mScaleType); <-- TODO Does setting this here mess up saving state after configuration change? How to reset?
mInvalidFlags |= INVALID_FLAG_DEFAULT;
}
@Override
public void setImageMatrix(Matrix matrix) {
super.setImageMatrix(matrix);
if (ScaleType.MATRIX == mScaleType) {
mBaselineImageMatrix.set(matrix);
mInvalidFlags &= ~INVALID_FLAG_BASELINE_IMAGE_MATRIX;
mInvalidFlags |= INVALID_FLAG_IMAGE_MAX_SCALE | INVALID_FLAG_IMAGE_MIN_SCALE;
}
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom);
mInvalidFlags |= INVALID_FLAG_DEFAULT;
}
@Override
public void setPaddingRelative(int start, int top, int end, int bottom) {
super.setPaddingRelative(start, top, end, bottom);
mInvalidFlags |= INVALID_FLAG_DEFAULT;
}
@Override
public void setScaleType(ScaleType scaleType) {
mScaleType = scaleType;
super.setScaleType(mScaleType);
mInvalidFlags |= INVALID_FLAG_DEFAULT;
}
//endregion Inherited methods
//region Interface methods
@Override // GestureDetector.OnGestureListener
public boolean onDown(MotionEvent e) {
mOverScroller.forceFinished(true);
mTransformer.forceFinished(true);
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mLastScrollX = e.getX();
mLastScrollY = e.getY();
mSrcPts[0] = mLastScrollX;
mSrcPts[1] = mLastScrollY;
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
mLastScrollPx = mDstPts[0];
mLastScrollPy = mDstPts[1];
}
return true;
}
@Override // GestureDetector.OnGestureListener
public void onShowPress(MotionEvent e) {
}
@Override // GestureDetector.OnGestureListener
public boolean onSingleTapUp(MotionEvent e) {
if ((mInteractivity & INTERACTIVITY_FLAG_DOUBLE_TAP) != INTERACTIVITY_FLAG_DOUBLE_TAP) {
// If we haven't enabled double tap, fire the onSingleTapConfirmed for consistency
this.onSingleTapConfirmed(e);
}
return false;
}
@Override // GestureDetector.OnGestureListener
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mScaleGestureDetector.isInProgress()) {
return false;
}
if (mNeedsDown) {
mNeedsDown = false;
onDown(e2);
}
synchronized (mLock) {
final float sx = getImageScaleX();
final float sy = getImageScaleY();
final float x = e2.getX();
final float y = e2.getY();
final boolean transformed = setImageTransform(
sx,
sy,
mLastScrollPx,
mLastScrollPy,
mLastScrollX - distanceX,
mLastScrollY - distanceY,
false,
true);
// TODO This code is repeating a bit. Consolidate?
mLastScrollX = x;
mLastScrollY = y;
if (!transformed) {
// If the image didn't move while we were scrolling, re-calculate new values
// for mLastScrollPx/mLastScrollPy
getImageMatrixInternal(mImageMatrix);
mSrcPts[0] = mLastScrollX;
mSrcPts[1] = mLastScrollY;
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
mLastScrollPx = mDstPts[0];
mLastScrollPy = mDstPts[1];
}
}
return false;
}
@Override // GestureDetector.OnGestureListener
public void onLongPress(MotionEvent e) {
}
@Override // GestureDetector.OnGestureListener
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
getDrawableIntrinsicRect(mSrcRect);
mImageMatrix.mapRect(mDstRect, mSrcRect);
mImageMatrix.getValues(mMatrixValues);
final float mappedWidth = mDstRect.width();
final float mappedHeight = mDstRect.height();
mOverScroller.fling(
(int) mMatrixValues[MTRANS_X],
(int) mMatrixValues[MTRANS_Y],
(int) velocityX,
(int) velocityY,
(int) getImageMinTransX(mappedWidth),
(int) getImageMaxTransX(mappedWidth),
(int) getImageMinTransY(mappedHeight),
(int) getImageMaxTransY(mappedHeight),
0,
0);
}
return true;
}
@Override // GestureDetector.OnDoubleTapListener
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
@Override // GestureDetector.OnDoubleTapListener
public boolean onDoubleTap(MotionEvent e) {
return false;
}
@Override // GestureDetector.OnDoubleTapListener
public boolean onDoubleTapEvent(MotionEvent e) {
if ((mInteractivity & INTERACTIVITY_FLAG_DOUBLE_TAP) == INTERACTIVITY_FLAG_DOUBLE_TAP) {
if (e.getAction() == MotionEvent.ACTION_UP) {
synchronized (mLock) {
final float nextZoomPivot = getNextZoomPivot();
final float minSx = getImageMinScaleX();
final float minSy = getImageMinScaleY();
mSrcPts[0] = e.getX();
mSrcPts[1] = e.getY();
getImageMatrixInternal(mImageMatrix);
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
setImageTransform(
minSx + (getImageMaxScaleX() - minSx) * nextZoomPivot,
minSy + (getImageMaxScaleY() - minSy) * nextZoomPivot,
mDstPts[0],
mDstPts[1],
getDefaultTargetX(),
getDefaultTargetY(),
true);
return true;
}
}
}
return false;
}
@Override // ScaleGestureDetector.OnScaleGestureListener
public boolean onScale(ScaleGestureDetector detector) {
final float currentSpan = detector.getCurrentSpan();
synchronized (mLock) {
final float spanDelta = (currentSpan / mLastSpan);
final float sx = getImageScaleX() * spanDelta;
final float sy = getImageScaleY() * spanDelta;
final float x = detector.getFocusX();
final float y = detector.getFocusY();
final boolean transformed =
setImageTransform(sx, sy, mLastScrollPx, mLastScrollPy, x, y, false, true);
if (!transformed) {
// If the image didn't move while we were scrolling, re-calculate new values
// for mLastScrollPx/mLastScrollPy
getImageMatrixInternal(mImageMatrix);
mSrcPts[0] = x;
mSrcPts[1] = y;
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
mLastScrollPx = mDstPts[0];
mLastScrollPy = mDstPts[1];
}
}
mLastSpan = currentSpan;
return true;
}
@Override // ScaleGestureDetector.OnScaleGestureListener
public boolean onScaleBegin(ScaleGestureDetector detector) {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mSrcPts[0] = detector.getFocusX();
mSrcPts[1] = detector.getFocusY();
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
mLastScrollPx = mDstPts[0];
mLastScrollPy = mDstPts[1];
mLastSpan = detector.getCurrentSpan();
}
return true;
}
@Override // ScaleGestureDetector.OnScaleGestureListener
public void onScaleEnd(ScaleGestureDetector detector) {
mNeedsDown = true;
}
//endregion Interface methods
//region Methods
protected int getDrawableIntrinsicHeight() {
final Drawable dr = getDrawable();
return (dr == null ? -1 : dr.getIntrinsicHeight());
}
protected int getDrawableIntrinsicWidth() {
final Drawable dr = getDrawable();
return (dr == null ? -1 : dr.getIntrinsicWidth());
}
public float getImagePivotX() {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mSrcPts[0] = getDefaultTargetX();
mSrcPts[1] = 0.0f;
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
return mDstPts[0];
}
}
public float getImagePivotY() {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mSrcPts[0] = 0.0f;
mSrcPts[1] = getDefaultTargetY();
mapViewPointToDrawablePoint(mDstPts, mSrcPts, mImageMatrix);
return mDstPts[1];
}
}
public float getImageMaxScaleX() {
getImageMaxScale();
return mMaxScaleX;
}
public float getImageMaxScaleY() {
getImageMaxScale();
return mMaxScaleY;
}
public float getImageMinScaleX() {
getImageMinScale();
return mMinScaleX;
}
public float getImageMinScaleY() {
getImageMinScale();
return mMinScaleY;
}
public float getImageScaleX() {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mImageMatrix.getValues(mMatrixValues);
return mMatrixValues[MSCALE_X];
}
}
public float getImageScaleY() {
synchronized (mLock) {
getImageMatrixInternal(mImageMatrix);
mImageMatrix.getValues(mMatrixValues);
return mMatrixValues[MSCALE_Y];
}
}
@SuppressWarnings("unused")
public int getInteractivity() {
return mInteractivity;
}
public boolean onUp(MotionEvent e) {
return false;
}
public void setInteractivity(int flags) {
mInteractivity = flags;
}
@SuppressWarnings("UnusedReturnValue")
public boolean setImageTransform(float sx, float sy, float px, float py) {
return setImageTransform(sx, sy, px, py, false);
}
@SuppressWarnings("SameParameterValue")
public boolean setImageTransform(float sx, float sy, float px, float py, boolean animate) {
if (!ViewCompat.isLaidOut(this)) {
mPendingTransformation = newPendingTransformation(sx, sy, px, py, NaN, NaN, animate);
return false;
}
final float x = getDefaultTargetX();
final float y = getDefaultTargetY();
return setImageTransform(sx, sy, px, py, x, y, animate);
}
@SuppressWarnings("unused")
public boolean setImageTransform(float sx, float sy, float px, float py, float x, float y) {
return setImageTransform(sx, sy, px, py, x, y, false);
}
public boolean setImageTransform(
float sx,
float sy,
float px,
float py,
float x,
float y,
boolean animate) {
if (!ViewCompat.isLaidOut(this)) {
mPendingTransformation = newPendingTransformation(sx, sy, px, py, x, y, animate);
return false;
}
return setImageTransform(sx, sy, px, py, x, y, animate, false);
}
public void setZoomPivots(float... pivots) {
mZoomPivots = pivots;
}
//endregion Methods
//region Protected methods
@SuppressWarnings("unused")
protected void clampTransform(
float sx,
float sy,
float px,
float py,
float x,
float y,
@NonNull final PointF outScale,
@NonNull final PointF outViewPt,
final boolean fromUser) {
synchronized (mLock) {
// First, update scale
getImageMinScale();
getImageMaxScale();
outScale.set(MathUtils.clamp(sx, mMinScaleX, mMaxScaleX),
MathUtils.clamp(sy, mMinScaleY, mMaxScaleY));
// Do we want to lock ratio? Or TODO do that in pinch scale?
// Get the resulting rect at the scaled size TODO This could be a helper method
getImageMatrixInternal(mImageMatrix);
mImageMatrix.getValues(mMatrixValues);
mMatrixValues[MSCALE_X] = outScale.x;
mMatrixValues[MSCALE_Y] = outScale.y;
mImageMatrix.setValues(mMatrixValues);
getDrawableIntrinsicRect(mSrcRect);
mImageMatrix.mapRect(mDstRect, mSrcRect);
final float scaledImageWidth = mDstRect.width();
final float scaledImageHeight = mDstRect.height();
mSrcPts[0] = px;
mSrcPts[1] = py;
mImageMatrix.mapPoints(mDstPts, mSrcPts);
// What would tx/ty be if we moved drawablePt to viewPt?
final float tx = x - (mDstPts[0] - mDstRect.left);
final float ty = y - (mDstPts[1] - mDstRect.top);
final float clampedTx = MathUtils.clamp(
tx,
getImageMinTransX(scaledImageWidth),
getImageMaxTransX(scaledImageWidth));
final float clampedTy = MathUtils.clamp(
ty,
getImageMinTransY(scaledImageHeight),
getImageMaxTransY(scaledImageHeight));
// With values clampedTx/clampedTy, where does the drawable point wind up?
mMatrixValues[MTRANS_X] = clampedTx;
mMatrixValues[MTRANS_Y] = clampedTy;
mImageMatrix.setValues(mMatrixValues);
mImageMatrix.mapPoints(mDstPts, mSrcPts);
outViewPt.x = mDstPts[0];
outViewPt.y = mDstPts[1];
Log.d(LOG_TAG, "");
}
}
protected boolean drawableHasIntrinsicSize() {
return getDrawableIntrinsicWidth() > 0 && getDrawableIntrinsicHeight() > 0;
}
protected int getAvailableHeight() {
return getHeight() - getPaddingTop() - getPaddingBottom();
}
protected int getAvailableWidth() {
return getWidth() - getPaddingLeft() - getPaddingRight();
}
@SuppressWarnings("SameParameterValue")
protected void getBaselineImageMatrix(Matrix outMatrix) {
getBaselineImageMatrix(mScaleType, outMatrix);
}
protected void getBaselineImageMatrix(ScaleType scaleType, Matrix outMatrix) {
synchronized (mLock) {
if ((mInvalidFlags & INVALID_FLAG_BASELINE_IMAGE_MATRIX) ==
INVALID_FLAG_BASELINE_IMAGE_MATRIX) {
mInvalidFlags &= ~INVALID_FLAG_BASELINE_IMAGE_MATRIX;
if (drawableHasIntrinsicSize()) {
// We need to do the scaling ourselves.
final int dwidth = getDrawableIntrinsicWidth();
final int dheight = getDrawableIntrinsicHeight();
final int vwidth = getAvailableWidth();
final int vheight = getAvailableHeight();
final boolean fits = (dwidth < 0 || vwidth == dwidth)
&& (dheight < 0 || vheight == dheight);
if (ScaleType.MATRIX == scaleType) {
// Use the specified matrix as-is.
mBaselineImageMatrix.set(getImageMatrix());
} else if (fits) {
// The bitmap fits exactly, no transform needed.
mBaselineImageMatrix.reset();
} else if (ScaleType.CENTER == scaleType) {
// Center bitmap in view, no scaling.
mBaselineImageMatrix.setTranslate(
Math.round((vwidth - dwidth) * 0.5f),
Math.round((vheight - dheight) * 0.5f));
} else if (ScaleType.CENTER_CROP == scaleType) {
float scale;
float dx = 0, dy = 0;
if (dwidth * vheight > vwidth * dheight) {
scale = (float) vheight / (float) dheight;
dx = (vwidth - dwidth * scale) * 0.5f;
} else {
scale = (float) vwidth / (float) dwidth;
dy = (vheight - dheight * scale) * 0.5f;
}
mBaselineImageMatrix.setScale(scale, scale);
mBaselineImageMatrix.postTranslate(Math.round(dx), Math.round(dy));
} else if (ScaleType.CENTER_INSIDE == scaleType) {
float scale;
float dx;
float dy;
if (dwidth <= vwidth && dheight <= vheight) {
scale = 1.0f;
} else {
scale = Math.min((float) vwidth / (float) dwidth,
(float) vheight / (float) dheight);
}
dx = Math.round((vwidth - dwidth * scale) * 0.5f);
dy = Math.round((vheight - dheight * scale) * 0.5f);
mBaselineImageMatrix.setScale(scale, scale);
mBaselineImageMatrix.postTranslate(dx, dy);
} else {
// Generate the required transform.
mSrcRect.set(0.0f, 0.0f, dwidth, dheight);
mDstRect.set(0.0f, 0.0f, vwidth, vheight);
mBaselineImageMatrix.setRectToRect(
mSrcRect,
mDstRect,
scaleTypeToScaleToFit(scaleType));
}
} else {
mBaselineImageMatrix.reset();
}
}
if (outMatrix != null && outMatrix != mBaselineImageMatrix) {
outMatrix.set(mBaselineImageMatrix);
}
}
}
// TODO Maybe change this to return an actual matrix
protected void getImageMatrixInternal(Matrix outMatrix) {
if (ScaleType.FIT_XY == super.getScaleType()) {
getBaselineImageMatrix(ScaleType.FIT_XY, outMatrix);
} else if (outMatrix != null) {
outMatrix.set(getImageMatrix());
}
}
// TODO JavaDoc needs to state that method must call setImageMaxScale if overridden
protected void getImageMaxScale() {
synchronized (mLock) {
if ((mInvalidFlags & INVALID_FLAG_IMAGE_MAX_SCALE) == INVALID_FLAG_IMAGE_MAX_SCALE) {
final float maxScaleX;
final float maxScaleY;
if (drawableHasIntrinsicSize()) {
getDrawableIntrinsicRect(mSrcRect);
getBaselineImageMatrix(null);
final float[] values = new float[9];
mBaselineImageMatrix.getValues(values);
mBaselineImageMatrix.mapRect(mDstRect, mSrcRect);
final float baselineWidth = mDstRect.width();
final float baselineHeight = mDstRect.height();
final float baselineBreadth = Math.min(baselineWidth, baselineHeight);
final float baselineLength = Math.max(baselineWidth, baselineHeight);
final Context context = getContext();
final DisplayMetrics dm;
final WindowManager windowManager =
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE));
if (windowManager == null) {
dm = context.getResources().getDisplayMetrics();
} else {
dm = new DisplayMetrics();
DisplayCompat.getRealMetrics(windowManager.getDefaultDisplay(), dm);
}
final int min = Math.min(dm.widthPixels, dm.heightPixels);
final int max = Math.max(dm.widthPixels, dm.heightPixels);
final float maxBreadth = MAX_SCALE_BREADTH_MULTIPLIER * min;
final float maxLength = MAX_SCALE_LENGTH_MULTIPLIER * max;
final float screenBasedScale = Math.min(
maxBreadth / baselineBreadth,
maxLength / baselineLength);
final int availableWidth = getAvailableWidth();
final int availableHeight = getAvailableHeight();
final int availableSize;
if (baselineWidth < baselineHeight) {
availableSize = availableWidth;
} else if (baselineWidth > baselineHeight) {
availableSize = availableHeight;
} else {
availableSize = Math.min(availableWidth, availableHeight);
}
final float viewBasedScale = availableSize / baselineBreadth;
final float scale = Math.max(screenBasedScale, viewBasedScale);
maxScaleX = scale * values[MSCALE_X];
maxScaleY = scale * values[MSCALE_Y];
} else {
maxScaleX = maxScaleY = 1.0f;
}
setImageMaxScale(maxScaleX, maxScaleY);
}
}
}
protected float getImageMaxTransX(float scaledImageWidth) {
return getImageTransBounds(
getAvailableWidth(),
scaledImageWidth,
ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL,
true);
}
protected float getImageMaxTransY(float scaledImageHeight) {
return getImageTransBounds(
getAvailableHeight(),
scaledImageHeight,
false,
true);
}
protected float getImageMinTransX(float scaledImageWidth) {
return getImageTransBounds(
getAvailableWidth(),
scaledImageWidth,
ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL,
false);
}
protected float getImageMinTransY(float scaledImageHeight) {
return getImageTransBounds(
getAvailableHeight(),
scaledImageHeight,
false,
false);
}
// TODO JavaDoc needs to state that method must call setImageMinScale if overridden
protected void getImageMinScale() {
synchronized (mLock) {
if ((mInvalidFlags & INVALID_FLAG_IMAGE_MIN_SCALE) == INVALID_FLAG_IMAGE_MIN_SCALE) {
getBaselineImageMatrix(null);
mBaselineImageMatrix.getValues(mMatrixValues);
setImageMinScale(mMatrixValues[MSCALE_X], mMatrixValues[MSCALE_Y]);
}
}
}
// TODO REMOVE?
protected void mapViewPointToDrawablePoint(float[] dst, float[] src, Matrix imageMatrix) {
synchronized (mLock) {
imageMatrix.invert(mNewImageMatrix);
mNewImageMatrix.mapPoints(dst, src);
}
}
protected static Matrix.ScaleToFit scaleTypeToScaleToFit(ScaleType scaleType) {
if (scaleType == null) {
return null;
} else switch (scaleType) {
case FIT_CENTER:
return Matrix.ScaleToFit.CENTER;
case FIT_END:
return Matrix.ScaleToFit.END;
case FIT_START:
return Matrix.ScaleToFit.START;
case FIT_XY:
return Matrix.ScaleToFit.FILL;
default:
return null;
}
}
protected void setImageMaxScale(float sx, float sy) {
mInvalidFlags &= ~INVALID_FLAG_IMAGE_MAX_SCALE;
mMaxScaleX = sx;
mMaxScaleY = sy;
}
protected void setImageMinScale(float sx, float sy) {
mInvalidFlags &= ~INVALID_FLAG_IMAGE_MIN_SCALE;
mMinScaleX = sx;
mMinScaleY = sy;
}
protected final boolean setImageTransform(
float sx,
float sy,
float px,
float py,
float x,
float y,
boolean animate,
boolean fromUser) {
synchronized (mLock) {
// TODO Use pools
final PointF outScale = new PointF();
final PointF outViewPt = new PointF();
clampTransform(sx, sy, px, py, x, y, outScale, outViewPt, fromUser);
if (animate) {
mSrcPts[0] = px;
mSrcPts[1] = py;
getImageMatrixInternal(mImageMatrix);
mImageMatrix.mapPoints(mDstPts, mSrcPts);
mTransformer.startTransform(
px,
py,
getImageScaleX(),
getImageScaleY(),
mDstPts[0],
mDstPts[1],
outScale.x,
outScale.y,
outViewPt.x,
outViewPt.y);
ViewCompat.postInvalidateOnAnimation(this);
return true;
} else {
return setImageTransformInternal(outScale.x, outScale.y, px, py, outViewPt.x, outViewPt.y);
}
}
}
protected final boolean setImageTransformInternal(
float sx,
float sy,
float px,
float py,
float x,
float y) {
// First, I need to resolve scale and map px and py to a scaled location
getImageMatrixInternal(mImageMatrix);
mNewImageMatrix.set(mImageMatrix);
mNewImageMatrix.getValues(mMatrixValues);
mMatrixValues[MSCALE_X] = sx;
mMatrixValues[MSCALE_Y] = sy;
mMatrixValues[MTRANS_X] = 0;
mMatrixValues[MTRANS_Y] = 0;
mNewImageMatrix.setValues(mMatrixValues);
mSrcPts[0] = px;
mSrcPts[1] = py;
mNewImageMatrix.mapPoints(mDstPts, mSrcPts);
final float tx = x - getPaddingLeft() - mDstPts[0];
final float ty = y - getPaddingTop() - mDstPts[1];
mMatrixValues[MTRANS_X] = tx;
mMatrixValues[MTRANS_Y] = ty;
mNewImageMatrix.setValues(mMatrixValues);
if (mImageMatrix.equals(mNewImageMatrix)) {
return false;
}
if (super.getScaleType() != ScaleType.MATRIX) {
super.setScaleType(ScaleType.MATRIX);
}
super.setImageMatrix(mNewImageMatrix);
return true;
}
private Bundle newPendingTransformation(
float sx,
float sy,
float px,
float py,
float x,
float y,
boolean animate) {
Bundle bundle = new Bundle();
bundle.putFloat(KEY_SX, sx);
bundle.putFloat(KEY_SY, sy);
bundle.putFloat(KEY_PX, px);
bundle.putFloat(KEY_PY, py);
if (!Float.isNaN(x)) {
bundle.putFloat(KEY_X, x);
}
if (!Float.isNaN(y)) {
bundle.putFloat(KEY_Y, y);
}
bundle.putBoolean(KEY_ANIMATE, animate);
return bundle;
}
private float getDefaultTargetX() {
return getPaddingLeft() + getAvailableWidth() * 0.5f;
}
private float getDefaultTargetY() {
return getPaddingTop() + getAvailableHeight() * 0.5f;
}
private void getDrawableIntrinsicRect(@NonNull final RectF outRect) {
outRect.set(
0.0f,
0.0f,
getDrawableIntrinsicWidth(),
getDrawableIntrinsicHeight());
}
private float getImageTransBounds(
int availableSize,
float scaledImageSize,
boolean isRtl,
boolean isMax) {
final float diff = availableSize - scaledImageSize;
if (diff <= 0) {
// Image size is larger than or equal to available size
return (isMax ? 0.0f : diff);
} else switch (mScaleType) {
// Image size is smaller than available size
case FIT_START:
return (isRtl ? diff : 0.0f);
case FIT_END:
return (isRtl ? 0.0f : diff);
default:
return diff * 0.5f;
}
}
private float getNextZoomPivot() {
float nextZoomPivot = 0.0f;
if (mZoomPivots != null) {
final float minSx = getImageMinScaleX();
final float minSy = getImageMinScaleY();
float relativeSx = (getImageScaleX() - minSx) / (getImageMaxScaleX() - minSx);
float relativeSy = (getImageScaleY() - minSy) / (getImageMaxScaleY() - minSy);
if (Float.isNaN(relativeSx) || Float.isInfinite(relativeSx)) {
relativeSx = 0.0f;
}
if (Float.isNaN(relativeSy) || Float.isInfinite(relativeSy)) {
relativeSy = 0.0f;
}
boolean foundX = false;
boolean foundY = false;
for (final float zoomPivot : mZoomPivots) {
if (zoomPivot - relativeSx > ZOOM_PIVOT_EPSILON) {
foundX = true;
nextZoomPivot = zoomPivot;
}
if (zoomPivot - relativeSy > ZOOM_PIVOT_EPSILON) {
foundY = true;
nextZoomPivot = zoomPivot;
}
if (foundX && foundY) {
break;
}
}
}
return nextZoomPivot;
}
@SuppressWarnings("SameParameterValue")
private Initializer initializeInteractiveImageView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
TypedArray a = context.obtainStyledAttributes(
attrs,
R.styleable.InteractiveImageView,
defStyleAttr,
defStyleRes);
setInteractivity(a.getInt(
R.styleable.InteractiveImageView_interactivity,
INTERACTIVITY_FLAG_ALL));
final @ArrayRes int resId =
a.getResourceId(R.styleable.InteractiveImageView_zoomPivots, -1);
if (resId != -1) {
TypedArray ta = getResources().obtainTypedArray(resId);
final int length = ta.length();
final float[] zoomPivots = new float[length];
for (int i = 0; i < length; i++) {
zoomPivots[i] = ta.getFloat(i, Float.NaN);
}
setZoomPivots(zoomPivots);
ta.recycle();
}
a.recycle();
return new Initializer(this);
}
//endregion Private methods
}
|
package com.irccloud.android;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MessageActivity extends BaseActivity implements UsersListFragment.OnUserSelectedListener, BuffersListFragment.OnBufferSelectedListener, MessageViewFragment.MessageViewListener {
int cid = -1;
int bid = -1;
String name;
String type;
EditText messageTxt;
View sendBtn;
int joined;
int archived;
String status;
UsersDataSource.User selected_user;
View userListView;
View buffersListView;
TextView title;
TextView subtitle;
LinearLayout messageContainer;
HorizontalScrollView scrollView;
NetworkConnection conn;
private boolean shouldFadeIn = false;
ImageView upView;
private RefreshUpIndicatorTask refreshUpIndicatorTask = null;
private ArrayList<Integer> backStack = new ArrayList<Integer>();
PowerManager.WakeLock screenLock = null;
private int launchBid = -1;
private Uri launchURI = null;
private HashMap<Integer, EventsDataSource.Event> pendingEvents = new HashMap<Integer, EventsDataSource.Event>();
@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
buffersListView = findViewById(R.id.BuffersList);
messageContainer = (LinearLayout)findViewById(R.id.messageContainer);
scrollView = (HorizontalScrollView)findViewById(R.id.scroll);
if(scrollView != null) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)messageContainer.getLayoutParams();
params.width = getWindowManager().getDefaultDisplay().getWidth();
messageContainer.setLayoutParams(params);
}
messageTxt = (EditText)findViewById(R.id.messageTxt);
messageTxt.setEnabled(false);
messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(scrollView != null && v == messageTxt && hasFocus)
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
}
});
messageTxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(scrollView != null)
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
}
});
messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN && view.getText().length() > 0) {
new SendTask().execute((Void)null);
}
return true;
}
});
messageTxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Object[] spans = s.getSpans(0, s.length(), Object.class);
for(Object o : spans) {
if(((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING) && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class || o.getClass() == BackgroundColorSpan.class || o.getClass() == UnderlineSpan.class)) {
s.removeSpan(o);
}
}
if(s.length() > 0) {
sendBtn.setEnabled(true);
if(Build.VERSION.SDK_INT >= 11)
sendBtn.setAlpha(1);
} else {
sendBtn.setEnabled(false);
if(Build.VERSION.SDK_INT >= 11)
sendBtn.setAlpha(0.5f);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
sendBtn = findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new SendTask().execute((Void)null);
}
});
userListView = findViewById(R.id.usersListFragment);
getSupportActionBar().setLogo(R.drawable.logo);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle("Channel Topic");
if(c.topic_text.length() > 0) {
final SpannableString s = new SpannableString(c.topic_text);
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
} else
builder.setMessage("No topic set.");
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
editTopic();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
} else if(archived == 0 && subtitle.getText().length() > 0){
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
builder.setTitle(title.getText().toString());
final SpannableString s = new SpannableString(subtitle.getText().toString());
Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
builder.setMessage(s);
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
((TextView)dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}
}
});
upView = (ImageView)v.findViewById(R.id.upIndicator);
if(scrollView != null) {
upView.setVisibility(View.VISIBLE);
upView.setOnClickListener(upClickListener);
ImageView icon = (ImageView)v.findViewById(R.id.upIcon);
icon.setOnClickListener(upClickListener);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
} else {
upView.setVisibility(View.INVISIBLE);
}
title = (TextView)v.findViewById(R.id.title);
subtitle = (TextView)v.findViewById(R.id.subtitle);
getSupportActionBar().setCustomView(v);
if(savedInstanceState != null && savedInstanceState.containsKey("cid")) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
name = savedInstanceState.getString("name");
type = savedInstanceState.getString("type");
joined = savedInstanceState.getInt("joined");
archived = savedInstanceState.getInt("archived");
status = savedInstanceState.getString("status");
backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
}
if(getSharedPreferences("prefs", 0).contains("session_key")) {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, GCMIntentService.GCM_ID);
} else {
if(!getSharedPreferences("prefs", 0).contains("gcm_registered"))
GCMIntentService.scheduleRegisterTimer(30000);
}
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
state.putString("name", name);
state.putString("type", type);
state.putInt("joined", joined);
state.putInt("archived", archived);
state.putString("status", status);
state.putSerializable("backStack", backStack);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer(bid);
String name = buffer.name;
if(buffer != null) {
if(buffer.type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(s != null) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
}
onBufferSelected(buffer.cid, buffer.bid, name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
if(backStack.size() > 0)
backStack.remove(0);
} else {
return super.onKeyDown(keyCode, event);
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class SendTask extends AsyncTaskEx<Void, Void, Void> {
EventsDataSource.Event e = null;
@Override
protected void onPreExecute() {
if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText().length() > 0) {
sendBtn.setEnabled(false);
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
UsersDataSource.User u = UsersDataSource.getInstance().getUser(cid, name, s.nick);
e = EventsDataSource.getInstance().new Event();
e.cid = cid;
e.bid = bid;
e.eid = (System.currentTimeMillis() + conn.clockOffset + 5000) * 1000L;
e.self = true;
e.from = s.nick;
e.nick = s.nick;
if(u != null)
e.from_mode = u.mode;
String msg = messageTxt.getText().toString();
if(msg.startsWith("
msg = msg.substring(1);
else if(msg.startsWith("/") && !msg.startsWith("/me "))
msg = null;
e.msg = msg;
if(msg != null && msg.toLowerCase().startsWith("/me ")) {
e.type = "buffer_me_msg";
e.msg = msg.substring(4);
} else {
e.type = "buffer_msg";
}
e.color = R.color.timestamp;
if(name.equals(s.nick))
e.bg_color = R.color.message_bg;
else
e.bg_color = R.color.self;
e.row_type = 0;
e.html = null;
e.group_msg = null;
e.linkify = true;
e.target_mode = null;
e.highlight = false;
e.reqid = -1;
e.pending = true;
if(e.msg != null) {
EventsDataSource.getInstance().addEvent(e);
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e, mHandler);
}
}
}
@Override
protected Void doInBackground(Void... arg0) {
if(conn.getState() == NetworkConnection.STATE_CONNECTED && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
e.reqid = conn.say(cid, name, messageTxt.getText().toString());
if(e.msg != null)
pendingEvents.put(e.reqid, e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
messageTxt.setText("");
sendBtn.setEnabled(true);
}
}
private class RefreshUpIndicatorTask extends AsyncTaskEx<Void, Void, Void> {
int unread = 0;
int highlights = 0;
@Override
protected Void doInBackground(Void... arg0) {
ArrayList<ServersDataSource.Server> servers = ServersDataSource.getInstance().getServers();
JSONObject channelDisabledMap = null;
JSONObject bufferDisabledMap = null;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
if(conn.getUserInfo().prefs.has("channel-disableTrackUnread"))
channelDisabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(conn.getUserInfo().prefs.has("buffer-disableTrackUnread"))
bufferDisabledMap = conn.getUserInfo().prefs.getJSONObject("buffer-disableTrackUnread");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 0; i < servers.size(); i++) {
ServersDataSource.Server s = servers.get(i);
ArrayList<BuffersDataSource.Buffer> buffers = BuffersDataSource.getInstance().getBuffersForServer(s.cid);
for(int j = 0; j < buffers.size(); j++) {
BuffersDataSource.Buffer b = buffers.get(j);
if(b.type == null)
Log.w("IRCCloud", "Buffer with null type: " + b.bid + " name: " + b.name);
if(b.bid != bid) {
if(unread == 0) {
int u = 0;
try {
u = EventsDataSource.getInstance().getUnreadCountForBuffer(b.bid, b.last_seen_eid, b.type);
if(b.type.equalsIgnoreCase("channel") && channelDisabledMap != null && channelDisabledMap.has(String.valueOf(b.bid)) && channelDisabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
else if(bufferDisabledMap != null && bufferDisabledMap.has(String.valueOf(b.bid)) && bufferDisabledMap.getBoolean(String.valueOf(b.bid)))
u = 0;
} catch (JSONException e) {
e.printStackTrace();
}
unread += u;
}
if(highlights == 0) {
try {
if(!b.type.equalsIgnoreCase("conversation") || bufferDisabledMap == null || !bufferDisabledMap.has(String.valueOf(b.bid)) || !bufferDisabledMap.getBoolean(String.valueOf(b.bid)))
highlights += EventsDataSource.getInstance().getHighlightCountForBuffer(b.bid, b.last_seen_eid, b.type);
} catch (JSONException e) {
}
}
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled()) {
if(highlights > 0) {
upView.setImageResource(R.drawable.up_highlight);
} else if(unread > 0) {
upView.setImageResource(R.drawable.up_unread);
} else {
upView.setImageResource(R.drawable.up);
}
refreshUpIndicatorTask = null;
}
}
}
private class ShowNotificationsTask extends AsyncTaskEx<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
Notifications.getInstance().excludeBid(params[0]);
if(params[0] > 0)
Notifications.getInstance().showNotifications(null);
return null;
}
}
private void setFromIntent(Intent intent) {
long min_eid = 0;
long last_seen_eid = 0;
launchBid = -1;
launchURI = null;
if(intent.hasExtra("bid")) {
if(bid >= 0)
backStack.add(0, bid);
int new_bid = intent.getIntExtra("bid", 0);
if(ServersDataSource.getInstance().count() > 0 && BuffersDataSource.getInstance().getBuffer(new_bid) == null) {
Log.w("IRCCloud", "Invalid bid requested by launch intent");
Notifications.getInstance().deleteNotificationsForBid(new_bid);
new ShowNotificationsTask().execute(bid);
return;
} else {
bid = new_bid;
}
}
if(intent.getData() != null && intent.getData().getScheme().startsWith("irc")) {
if(open_uri(intent.getData()))
return;
launchURI = intent.getData();
} else if(intent.hasExtra("cid")) {
cid = intent.getIntExtra("cid", 0);
name = intent.getStringExtra("name");
type = intent.getStringExtra("type");
joined = intent.getIntExtra("joined", 0);
archived = intent.getIntExtra("archived", 0);
status = intent.getStringExtra("status");
min_eid = intent.getLongExtra("min_eid", 0);
last_seen_eid = intent.getLongExtra("last_seen_eid", 0);
if(bid == -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name);
if(b != null) {
bid = b.bid;
last_seen_eid = b.last_seen_eid;
min_eid = b.min_eid;
archived = b.archived;
}
}
} else if(bid != -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid);
joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
}
if(b.type.equalsIgnoreCase("console"))
b.name = s.name;
cid = b.cid;
name = b.name;
type = b.type;
archived = b.archived;
min_eid = b.min_eid;
last_seen_eid = b.last_seen_eid;
status = s.status;
}
}
if(cid == -1) {
launchBid = bid;
} else {
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
ulf.setArguments(b);
mvf.setArguments(b);
messageTxt.setEnabled(true);
}
}
@Override
protected void onNewIntent(Intent intent) {
if(intent != null) {
setFromIntent(intent);
}
}
@SuppressLint("NewApi")
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
if(prefs.getBoolean("screenlock", false)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(conn.getState() != NetworkConnection.STATE_CONNECTED) {
if(scrollView != null && ServersDataSource.getInstance().count() == 0)
scrollView.setEnabled(false);
messageTxt.setEnabled(false);
} else {
if(scrollView != null) {
scrollView.setEnabled(true);
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(true);
}
if(cid == -1) {
if(getIntent() != null && (getIntent().hasExtra("bid") || getIntent().getData() != null)) {
setFromIntent(getIntent());
} else if(conn.getState() == NetworkConnection.STATE_CONNECTED && conn.getUserInfo() != null && ServersDataSource.getInstance().count() > 0) {
if(!open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null)
scrollView.scrollTo(0,0);
}
}
}
}
updateUsersListFragmentVisibility();
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
invalidateOptionsMenu();
if(ServersDataSource.getInstance().count() > 0)
new ShowNotificationsTask().execute(bid);
sendBtn.setEnabled(messageTxt.getText().length() > 0);
if(Build.VERSION.SDK_INT >= 11 && messageTxt.getText().length() == 0)
sendBtn.setAlpha(0.5f);
}
@Override
public void onPause() {
super.onPause();
if(conn != null)
conn.removeHandler(mHandler);
new ShowNotificationsTask().execute(-1);
}
private boolean open_uri(Uri uri) {
Log.i("IRCCloud", "Launch URI: " + uri);
if(uri != null && ServersDataSource.getInstance().count() > 0) {
ServersDataSource.Server s = null;
if(uri.getPort() > 0)
s = ServersDataSource.getInstance().getServer(uri.getHost(), uri.getPort());
else if(uri.getScheme().equalsIgnoreCase("ircs"))
s = ServersDataSource.getInstance().getServer(uri.getHost(), true);
else
s = ServersDataSource.getInstance().getServer(uri.getHost());
if(s != null) {
if(uri.getPath().length() > 1) {
String key = null;
String channel = uri.getPath().substring(1);
if(channel.contains(",")) {
key = channel.substring(channel.indexOf(",") + 1);
channel = channel.substring(0, channel.indexOf(","));
}
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, channel);
if(b != null)
return open_bid(b.bid);
else
conn.join(s.cid, channel, key);
return true;
} else {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(s.cid, "*");
if(b != null)
return open_bid(b.bid);
}
} else {
EditConnectionFragment connFragment = new EditConnectionFragment();
connFragment.default_hostname = uri.getHost();
if(uri.getPort() > 0)
connFragment.default_port = uri.getPort();
else if(uri.getScheme().equalsIgnoreCase("ircs"))
connFragment.default_port = 6697;
if(uri.getPath().length() > 1)
connFragment.default_channels = uri.getPath().substring(1).replace(",", " ");
connFragment.show(getSupportFragmentManager(), "addnetwork");
return true;
}
}
return false;
}
private boolean open_bid(int bid) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(b.cid);
int joined = 1;
if(b.type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(b.bid);
if(c == null)
joined = 0;
}
String name = b.name;
if(b.type.equalsIgnoreCase("console")) {
if(s.name != null && s.name.length() > 0)
name = s.name;
else
name = s.hostname;
}
onBufferSelected(b.cid, b.bid, name, b.last_seen_eid, b.min_eid, b.type, joined, b.archived, s.status);
return true;
}
return false;
}
private void update_subtitle() {
if(cid == -1 || ServersDataSource.getInstance().count() == 0) {
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(false);
} else {
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
if(archived > 0 && !type.equalsIgnoreCase("console")) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
} else {
if(type == null) {
subtitle.setVisibility(View.GONE);
} else if(type.equalsIgnoreCase("conversation")) {
UsersDataSource.User user = UsersDataSource.getInstance().getUser(cid, name);
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(user != null && user.away > 0) {
subtitle.setVisibility(View.VISIBLE);
if(user.away_msg != null && user.away_msg.length() > 0) {
subtitle.setText("Away: " + user.away_msg);
} else if(b != null && b.away_msg != null && b.away_msg.length() > 0) {
subtitle.setText("Away: " + b.away_msg);
} else {
subtitle.setText("Away");
}
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("channel")) {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
if(c != null && c.topic_text.length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(c.topic_text);
} else {
subtitle.setVisibility(View.GONE);
}
} else if(type.equalsIgnoreCase("console")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid);
if(s != null) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(s.hostname + ":" + s.port);
} else {
subtitle.setVisibility(View.GONE);
}
}
}
}
invalidateOptionsMenu();
}
private void updateUsersListFragmentVisibility() {
boolean hide = false;
if(userListView != null) {
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (Exception e) {
e.printStackTrace();
}
if(hide || type == null || !type.equalsIgnoreCase("channel"))
userListView.setVisibility(View.GONE);
else
userListView.setVisibility(View.VISIBLE);
}
}
@SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
Integer event_bid = 0;
IRCCloudJSONObject event = null;
switch (msg.what) {
case NetworkConnection.EVENT_CONNECTIVITY:
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
for(EventsDataSource.Event e : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
}
pendingEvents.clear();
if(scrollView != null && ServersDataSource.getInstance().count() > 0)
scrollView.setEnabled(true);
if(cid != -1)
messageTxt.setEnabled(true);
} else {
if(scrollView != null) {
if(ServersDataSource.getInstance().count() == 0)
scrollView.setEnabled(false);
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
}
messageTxt.setEnabled(false);
}
break;
case NetworkConnection.EVENT_BANLIST:
event = (IRCCloudJSONObject)msg.obj;
if(event.getString("channel").equalsIgnoreCase(name)) {
Bundle args = new Bundle();
args.putInt("cid", cid);
args.putInt("bid", bid);
args.putString("event", event.toString());
BanListFragment banList = (BanListFragment)getSupportFragmentManager().findFragmentByTag("banlist");
if(banList == null) {
banList = new BanListFragment();
banList.setArguments(args);
banList.show(getSupportFragmentManager(), "banlist");
} else {
banList.setArguments(args);
}
}
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(scrollView != null) {
scrollView.setEnabled(true);
}
if(cid == -1) {
if(launchURI == null || !open_uri(launchURI)) {
if(launchBid == -1 || !open_bid(launchBid)) {
if(conn.getUserInfo() == null || !open_bid(conn.getUserInfo().last_selected_bid)) {
if(!open_bid(BuffersDataSource.getInstance().firstBid())) {
if(scrollView != null && ServersDataSource.getInstance().count() > 0) {
scrollView.scrollTo(0, 0);
}
}
}
}
}
}
update_subtitle();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_USERINFO:
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
if(launchBid == -1 && cid == -1)
launchBid = conn.getUserInfo().last_selected_bid;
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid) {
status = event.getString("new_status");
invalidateOptionsMenu();
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKESERVER:
ServersDataSource.Server server = (ServersDataSource.Server)msg.obj;
if(server.cid == cid) {
status = server.status;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj;
if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) {
Log.i("IRCCloud", "Got my new buffer id: " + buffer.bid);
bid = buffer.bid;
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null)
((BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList)).setSelectedBid(bid);
new ShowNotificationsTask().execute(bid);
}
break;
case NetworkConnection.EVENT_BUFFERARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 1;
invalidateOptionsMenu();
subtitle.setVisibility(View.VISIBLE);
subtitle.setText("(archived)");
}
break;
case NetworkConnection.EVENT_BUFFERUNARCHIVED:
event_bid = (Integer)msg.obj;
if(event_bid == bid) {
archived = 0;
invalidateOptionsMenu();
subtitle.setVisibility(View.GONE);
}
break;
case NetworkConnection.EVENT_JOIN:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_joined_channel")) {
joined = 1;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_PART:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid && event.type().equalsIgnoreCase("you_parted_channel")) {
joined = 0;
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CHANNELINIT:
ChannelsDataSource.Channel channel = (ChannelsDataSource.Channel)msg.obj;
if(channel.bid == bid) {
joined = 1;
archived = 0;
update_subtitle();
invalidateOptionsMenu();
}
break;
case NetworkConnection.EVENT_CONNECTIONDELETED:
case NetworkConnection.EVENT_DELETEBUFFER:
Integer id = (Integer)msg.obj;
if(msg.what==NetworkConnection.EVENT_DELETEBUFFER) {
Log.i("IRCCloud", "Back stack: " + backStack.toString() + " ID: " + id);
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i).equals(id)) {
backStack.remove(i);
i
}
}
Log.i("IRCCloud", "Back stack: " + backStack.toString());
}
if(id == ((msg.what==NetworkConnection.EVENT_CONNECTIONDELETED)?cid:bid)) {
if(backStack != null && backStack.size() > 0) {
Integer bid = backStack.get(0);
backStack.remove(0);
buffer = BuffersDataSource.getInstance().getBuffer(bid);
if(buffer != null) {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
backStack.remove(0);
} else {
finish();
}
} else {
if(!open_bid(BuffersDataSource.getInstance().firstBid()))
finish();
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
event = (IRCCloudJSONObject)msg.obj;
if(event.bid() == bid) {
try {
if(event.getString("topic").length() > 0) {
subtitle.setVisibility(View.VISIBLE);
subtitle.setText(event.getString("topic"));
} else {
subtitle.setVisibility(View.GONE);
}
} catch (Exception e1) {
subtitle.setVisibility(View.GONE);
e1.printStackTrace();
}
}
break;
case NetworkConnection.EVENT_SELFBACK:
try {
event = (IRCCloudJSONObject)msg.obj;
if(event.cid() == cid && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.GONE);
subtitle.setText("");
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_AWAY:
try {
event = (IRCCloudJSONObject)msg.obj;
if((event.bid() == bid || (event.type().equalsIgnoreCase("self_away") && event.cid() == cid)) && event.getString("nick").equalsIgnoreCase(name)) {
subtitle.setVisibility(View.VISIBLE);
if(event.has("away_msg"))
subtitle.setText("Away: " + event.getString("away_msg"));
else
subtitle.setText("Away: " + event.getString("msg"));
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
event = (IRCCloudJSONObject)msg.obj;
if(event.has("_reqid")) {
int reqid = event.getInt("_reqid");
if(pendingEvents.containsKey(reqid)) {
EventsDataSource.Event e = pendingEvents.get(reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(event.getInt("_reqid"));
e.msg = ColorFormatter.irc_to_html(e.msg + " \u00034(FAILED)\u000f");
conn.notifyHandlers(NetworkConnection.EVENT_BUFFERMSG, e);
}
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
try {
EventsDataSource.Event e = (EventsDataSource.Event)msg.obj;
if(e.bid != bid && upView != null) {
if(refreshUpIndicatorTask != null)
refreshUpIndicatorTask.cancel(true);
refreshUpIndicatorTask = new RefreshUpIndicatorTask();
refreshUpIndicatorTask.execute((Void)null);
}
if(e.from.equalsIgnoreCase(name)) {
for(EventsDataSource.Event e1 : pendingEvents.values()) {
EventsDataSource.getInstance().deleteEvent(e1.eid, e1.bid);
}
pendingEvents.clear();
} else if(pendingEvents.containsKey(e.reqid)) {
e = pendingEvents.get(e.reqid);
EventsDataSource.getInstance().deleteEvent(e.eid, e.bid);
pendingEvents.remove(e.reqid);
}
} catch (Exception e1) {
}
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(type != null && ServersDataSource.getInstance().count() > 0) {
if(type.equalsIgnoreCase("channel")) {
getSupportMenuInflater().inflate(R.menu.activity_message_channel_userlist, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_channel, menu);
} else if(type.equalsIgnoreCase("conversation"))
getSupportMenuInflater().inflate(R.menu.activity_message_conversation, menu);
else if(type.equalsIgnoreCase("console"))
getSupportMenuInflater().inflate(R.menu.activity_message_console, menu);
getSupportMenuInflater().inflate(R.menu.activity_message_archive, menu);
}
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if(type != null && ServersDataSource.getInstance().count() > 0) {
if(archived == 0) {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_archive);
} else {
menu.findItem(R.id.menu_archive).setTitle(R.string.menu_unarchive);
}
if(type.equalsIgnoreCase("channel")) {
if(joined == 0) {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_rejoin);
menu.findItem(R.id.menu_archive).setVisible(true);
menu.findItem(R.id.menu_archive).setEnabled(true);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
if(menu.findItem(R.id.menu_userlist) != null) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
}
} else {
menu.findItem(R.id.menu_leave).setTitle(R.string.menu_leave);
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
if(menu.findItem(R.id.menu_userlist) != null) {
boolean hide = false;
try {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hiddenMembers");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
hide = true;
}
} catch (JSONException e) {
}
if(hide) {
menu.findItem(R.id.menu_userlist).setEnabled(false);
menu.findItem(R.id.menu_userlist).setVisible(false);
} else {
menu.findItem(R.id.menu_userlist).setEnabled(true);
menu.findItem(R.id.menu_userlist).setVisible(true);
}
}
}
} else if(type.equalsIgnoreCase("console")) {
menu.findItem(R.id.menu_archive).setVisible(false);
menu.findItem(R.id.menu_archive).setEnabled(false);
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_disconnect);
menu.findItem(R.id.menu_delete).setVisible(false);
menu.findItem(R.id.menu_delete).setEnabled(false);
} else {
menu.findItem(R.id.menu_disconnect).setTitle(R.string.menu_reconnect);
menu.findItem(R.id.menu_delete).setVisible(true);
menu.findItem(R.id.menu_delete).setEnabled(true);
}
}
}
return super.onPrepareOptionsMenu(menu);
}
private OnClickListener upClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
if(scrollView != null) {
if(scrollView.getScrollX() < buffersListView.getWidth() / 4) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
} else {
scrollView.smoothScrollTo(0, 0);
upView.setVisibility(View.INVISIBLE);
}
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder;
AlertDialog dialog;
switch (item.getItemId()) {
case R.id.menu_add_network:
EditConnectionFragment connFragment = new EditConnectionFragment();
connFragment.show(getSupportFragmentManager(), "addnetwork");
break;
case R.id.menu_channel_options:
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(cid, bid);
newFragment.show(getSupportFragmentManager(), "channeloptions");
break;
case R.id.menu_buffer_options:
BufferOptionsFragment bufferFragment = new BufferOptionsFragment(cid, bid, type);
bufferFragment.show(getSupportFragmentManager(), "bufferoptions");
break;
case R.id.menu_userlist:
if(scrollView != null) {
if(scrollView.getScrollX() > buffersListView.getWidth()) {
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
} else {
scrollView.smoothScrollTo(buffersListView.getWidth() + userListView.getWidth(), 0);
}
upView.setVisibility(View.VISIBLE);
}
return true;
case R.id.menu_ignore_list:
Bundle args = new Bundle();
args.putInt("cid", cid);
IgnoreListFragment ignoreList = new IgnoreListFragment();
ignoreList.setArguments(args);
ignoreList.show(getSupportFragmentManager(), "ignorelist");
return true;
case R.id.menu_ban_list:
conn.mode(cid, name, "b");
return true;
case R.id.menu_leave:
if(joined == 0)
conn.join(cid, name, null);
else
conn.part(cid, name, null);
return true;
case R.id.menu_archive:
if(archived == 0)
conn.archiveBuffer(cid, bid);
else
conn.unarchiveBuffer(cid, bid);
return true;
case R.id.menu_delete:
builder = new AlertDialog.Builder(MessageActivity.this);
if(type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(cid);
} else {
conn.deleteBuffer(cid, bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
return true;
case R.id.menu_editconnection:
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
return true;
case R.id.menu_disconnect:
if(status != null && status.contains("connected") && !status.startsWith("dis")) {
conn.disconnect(cid, null);
} else {
conn.reconnect(cid);
}
return true;
}
return super.onOptionsItemSelected(item);
}
void editTopic() {
ChannelsDataSource.Channel c = ChannelsDataSource.getInstance().getChannelForBuffer(bid);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_textprompt,null);
TextView prompt = (TextView)view.findViewById(R.id.prompt);
final EditText input = (EditText)view.findViewById(R.id.textInput);
input.setText(c.topic_text);
prompt.setVisibility(View.GONE);
builder.setTitle("Channel Topic");
builder.setView(view);
builder.setPositiveButton("Set Topic", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.say(cid, name, "/topic " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
@Override
public void onMessageDoubleClicked(EventsDataSource.Event event) {
if(event == null)
return;
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
onUserDoubleClicked(from);
}
@Override
public void onUserDoubleClicked(String from) {
if(messageTxt == null || from == null || from.length() == 0)
return;
if(scrollView != null)
scrollView.scrollTo((int)getResources().getDimension(R.dimen.drawer_width), 0);
if(messageTxt.getText().length() == 0) {
messageTxt.append(from + ": ");
} else {
int oldPosition = messageTxt.getSelectionStart();
String text = messageTxt.getText().toString();
int start = oldPosition - 1;
if(start > 0 && text.charAt(start) == ' ')
start
while(start > 0 && text.charAt(start) != ' ')
start
int match = text.indexOf(from, start);
int end = oldPosition + from.length();
if(end > text.length() - 1)
end = text.length() - 1;
if(match >= 0 && match < end) {
String newtext = "";
if(match > 1 && text.charAt(match - 1) == ' ')
newtext = text.substring(0, match - 1);
else
newtext = text.substring(0, match);
if(match+from.length() < text.length() && text.charAt(match+from.length()) == ':' &&
match+from.length()+1 < text.length() && text.charAt(match+from.length()+1) == ' ') {
if(match+from.length()+2 < text.length())
newtext += text.substring(match+from.length()+2, text.length());
} else if(match+from.length() < text.length()) {
newtext += text.substring(match+from.length(), text.length());
}
if(newtext.endsWith(" "))
newtext = newtext.substring(0, newtext.length() - 1);
if(newtext.equals(":"))
newtext = "";
messageTxt.setText(newtext);
if(match < newtext.length())
messageTxt.setSelection(match);
else
messageTxt.setSelection(newtext.length());
} else {
if(oldPosition == text.length() - 1) {
text += " " + from;
} else {
String newtext = text.substring(0, oldPosition);
if(!newtext.endsWith(" "))
from = " " + from;
if(!text.substring(oldPosition, text.length()).startsWith(" "))
from += " ";
newtext += from;
newtext += text.substring(oldPosition, text.length());
if(newtext.endsWith(" "))
newtext = newtext.substring(0, newtext.length() - 1);
text = newtext;
}
messageTxt.setText(text);
if(text.length() > 0) {
if(oldPosition + from.length() + 2 < text.length())
messageTxt.setSelection(oldPosition + from.length());
else
messageTxt.setSelection(text.length());
}
}
}
messageTxt.requestFocus();
InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(messageTxt, 0);
}
@Override
public boolean onBufferLongClicked(BuffersDataSource.Buffer b) {
if(b == null)
return false;
ArrayList<String> itemList = new ArrayList<String>();
final String[] items;
final BuffersDataSource.Buffer buffer = b;
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(buffer.bid != bid)
itemList.add("Open");
if(ChannelsDataSource.getInstance().getChannelForBuffer(b.bid) != null) {
itemList.add("Leave");
itemList.add("Channel Options");
} else {
if(b.type.equalsIgnoreCase("channel"))
itemList.add("Join");
else if(b.type.equalsIgnoreCase("console")) {
if(s.status.contains("connected") && !s.status.startsWith("dis")) {
itemList.add("Disconnect");
} else {
itemList.add("Connect");
itemList.add("Delete");
}
itemList.add("Edit Connection");
}
if(!b.type.equalsIgnoreCase("console")) {
if(b.archived == 0)
itemList.add("Archive");
else
itemList.add("Unarchive");
itemList.add("Delete");
}
if(!b.type.equalsIgnoreCase("channel")) {
itemList.add("Buffer Options");
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(b.type.equalsIgnoreCase("console"))
builder.setTitle(s.name);
else
builder.setTitle(b.name);
items = itemList.toArray(new String[itemList.size()]);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
AlertDialog dialog;
if(items[item].equals("Open")) {
ServersDataSource.Server s = ServersDataSource.getInstance().getServer(buffer.cid);
if(buffer.type.equalsIgnoreCase("console")) {
onBufferSelected(buffer.cid, buffer.bid, s.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, s.status);
} else {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, s.status);
}
} else if(items[item].equals("Join")) {
conn.join(buffer.cid, buffer.name, null);
} else if(items[item].equals("Leave")) {
conn.part(buffer.cid, buffer.name, null);
} else if(items[item].equals("Archive")) {
conn.archiveBuffer(buffer.cid, buffer.bid);
} else if(items[item].equals("Unarchive")) {
conn.unarchiveBuffer(buffer.cid, buffer.bid);
} else if(items[item].equals("Connect")) {
conn.reconnect(buffer.cid);
} else if(items[item].equals("Disconnect")) {
conn.disconnect(buffer.cid, null);
} else if(items[item].equals("Channel Options")) {
ChannelOptionsFragment newFragment = new ChannelOptionsFragment(buffer.cid, buffer.bid);
newFragment.show(getSupportFragmentManager(), "channeloptions");
} else if(items[item].equals("Buffer Options")) {
BufferOptionsFragment newFragment = new BufferOptionsFragment(buffer.cid, buffer.bid, buffer.type);
newFragment.show(getSupportFragmentManager(), "bufferoptions");
} else if(items[item].equals("Edit Connection")) {
EditConnectionFragment editFragment = new EditConnectionFragment();
editFragment.setCid(buffer.cid);
editFragment.show(getSupportFragmentManager(), "editconnection");
} else if(items[item].equals("Delete")) {
builder = new AlertDialog.Builder(MessageActivity.this);
if(buffer.type.equalsIgnoreCase("console"))
builder.setTitle("Delete Connection");
else
builder.setTitle("Delete History");
if(buffer.type.equalsIgnoreCase("console"))
builder.setMessage("Are you sure you want to remove this connection?");
else if(buffer.type.equalsIgnoreCase("channel"))
builder.setMessage("Are you sure you want to clear your history in " + buffer.name + "?");
else
builder.setMessage("Are you sure you want to clear your history with " + buffer.name + "?");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(type.equalsIgnoreCase("console")) {
conn.deleteServer(buffer.cid);
} else {
conn.deleteBuffer(buffer.cid, buffer.bid);
}
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.show();
}
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
return true;
}
@Override
public boolean onMessageLongClicked(EventsDataSource.Event event) {
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
UsersDataSource.User user;
if(type.equals("channel"))
user = UsersDataSource.getInstance().getUser(cid, name, from);
else
user = UsersDataSource.getInstance().getUser(cid, from);
if(user == null && from != null && event.hostmask != null) {
user = UsersDataSource.getInstance().new User();
user.nick = from;
user.hostmask = event.hostmask;
user.mode = "";
}
if(user == null && event.html == null)
return false;
if(event.html != null)
showUserPopup(user, ColorFormatter.html_to_spanned(event.html));
else
showUserPopup(user, null);
return true;
}
@Override
public void onUserSelected(int c, String chan, String nick) {
UsersDataSource u = UsersDataSource.getInstance();
if(type.equals("channel"))
showUserPopup(u.getUser(cid, name, nick), null);
else
showUserPopup(u.getUser(cid, nick), null);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private void showUserPopup(UsersDataSource.User user, Spanned message) {
ArrayList<String> itemList = new ArrayList<String>();
final String[] items;
final Spanned text_to_copy = message;
selected_user = user;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if(message != null)
itemList.add("Copy Message");
if(selected_user != null) {
itemList.add("Open");
itemList.add("Mention (double tap)");
itemList.add("Invite to a channel");
itemList.add("Ignore");
if(type.equalsIgnoreCase("channel")) {
UsersDataSource.User self_user = UsersDataSource.getInstance().getUser(cid, name, ServersDataSource.getInstance().getServer(cid).nick);
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o")) {
if(selected_user.mode.contains("o"))
itemList.add("Deop");
else
itemList.add("Op");
}
if(self_user.mode.contains("q") || self_user.mode.contains("a") || self_user.mode.contains("o") || self_user.mode.contains("h")) {
itemList.add("Kick");
itemList.add("Ban");
}
}
}
items = itemList.toArray(new String[itemList.size()]);
if(selected_user != null)
builder.setTitle(selected_user.nick + "\n(" + selected_user.hostmask + ")");
else
builder.setTitle("Message");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
AlertDialog.Builder builder = new AlertDialog.Builder(MessageActivity.this);
LayoutInflater inflater = getLayoutInflater();
ServersDataSource s = ServersDataSource.getInstance();
ServersDataSource.Server server = s.getServer(cid);
View view;
final TextView prompt;
final EditText input;
AlertDialog dialog;
if(items[item].equals("Copy Message")) {
if(Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text_to_copy);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("IRCCloud Message",text_to_copy);
clipboard.setPrimaryClip(clip);
}
} else if(items[item].equals("Open")) {
BuffersDataSource b = BuffersDataSource.getInstance();
BuffersDataSource.Buffer buffer = b.getBufferByName(cid, selected_user.nick);
if(getSupportFragmentManager().findFragmentById(R.id.BuffersList) != null) {
if(buffer != null) {
onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, status);
} else {
onBufferSelected(cid, -1, selected_user.nick, 0, 0, "conversation", 1, 0, status);
}
} else {
Intent i = new Intent(MessageActivity.this, MessageActivity.class);
if(buffer != null) {
i.putExtra("cid", buffer.cid);
i.putExtra("bid", buffer.bid);
i.putExtra("name", buffer.name);
i.putExtra("last_seen_eid", buffer.last_seen_eid);
i.putExtra("min_eid", buffer.min_eid);
i.putExtra("type", buffer.type);
i.putExtra("joined", 1);
i.putExtra("archived", buffer.archived);
i.putExtra("status", status);
} else {
i.putExtra("cid", cid);
i.putExtra("bid", -1);
i.putExtra("name", selected_user.nick);
i.putExtra("last_seen_eid", 0L);
i.putExtra("min_eid", 0L);
i.putExtra("type", "conversation");
i.putExtra("joined", 1);
i.putExtra("archived", 0);
i.putExtra("status", status);
}
startActivity(i);
}
} else if(items[item].equals("Mention (double tap)")) {
onUserDoubleClicked(selected_user.nick);
} else if(items[item].equals("Invite to a channel")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Invite " + selected_user.nick + " to a channel");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Invite", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.invite(cid, input.getText().toString(), selected_user.nick);
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ignore")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Ignore messages for " + selected_user.nick + " at this hostmask");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.ignore(cid, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Op")) {
conn.mode(cid, name, "+o " + selected_user.nick);
} else if(items[item].equals("Deop")) {
conn.mode(cid, name, "-o " + selected_user.nick);
} else if(items[item].equals("Kick")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
prompt.setText("Give a reason for kicking");
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Kick", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.kick(cid, name, selected_user.nick, input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
} else if(items[item].equals("Ban")) {
view = inflater.inflate(R.layout.dialog_textprompt,null);
prompt = (TextView)view.findViewById(R.id.prompt);
input = (EditText)view.findViewById(R.id.textInput);
input.setText("*!"+selected_user.hostmask);
prompt.setText("Add a banmask for " + selected_user.nick);
builder.setTitle(server.name + " (" + server.hostname + ":" + (server.port) + ")");
builder.setView(view);
builder.setPositiveButton("Ban", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
conn.mode(cid, name, "+b " + input.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.setOwnerActivity(MessageActivity.this);
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
}
@Override
public void onBufferSelected(int cid, int bid, String name,
long last_seen_eid, long min_eid, String type, int joined,
int archived, String status) {
if(scrollView != null) {
if(buffersListView.getWidth() > 0)
scrollView.smoothScrollTo(buffersListView.getWidth(), 0);
upView.setVisibility(View.VISIBLE);
}
if(bid != this.bid || this.cid == -1) {
if(bid != -1 && conn != null && conn.getUserInfo() != null)
conn.getUserInfo().last_selected_bid = bid;
for(int i = 0; i < backStack.size(); i++) {
if(backStack.get(i) == this.bid)
backStack.remove(i);
}
if(this.bid >= 0)
backStack.add(0, this.bid);
this.cid = cid;
this.bid = bid;
this.name = name;
this.type = type;
this.joined = joined;
this.archived = archived;
this.status = status;
title.setText(name);
getSupportActionBar().setTitle(name);
update_subtitle();
Bundle b = new Bundle();
b.putInt("cid", cid);
b.putInt("bid", bid);
b.putLong("last_seen_eid", last_seen_eid);
b.putLong("min_eid", min_eid);
b.putString("name", name);
b.putString("type", type);
BuffersListFragment blf = (BuffersListFragment)getSupportFragmentManager().findFragmentById(R.id.BuffersList);
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
if(blf != null)
blf.setSelectedBid(bid);
if(mvf != null)
mvf.setArguments(b);
if(ulf != null)
ulf.setArguments(b);
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(200);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = true;
updateUsersListFragmentVisibility();
invalidateOptionsMenu();
new ShowNotificationsTask().execute(bid);
if(upView != null)
new RefreshUpIndicatorTask().execute((Void)null);
}
if(cid != -1) {
if(scrollView != null)
scrollView.setEnabled(true);
messageTxt.setEnabled(true);
}
}
public void showUpButton(boolean show) {
if(upView != null) {
if(show) {
upView.setVisibility(View.VISIBLE);
} else {
upView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onMessageViewReady() {
if(shouldFadeIn) {
MessageViewFragment mvf = (MessageViewFragment)getSupportFragmentManager().findFragmentById(R.id.messageViewFragment);
UsersListFragment ulf = (UsersListFragment)getSupportFragmentManager().findFragmentById(R.id.usersListFragment);
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(200);
anim.setFillAfter(true);
mvf.getListView().startAnimation(anim);
ulf.getListView().startAnimation(anim);
shouldFadeIn = false;
}
}
@Override
public void addButtonPressed(int cid) {
if(scrollView != null)
scrollView.scrollTo(0,0);
}
}
|
package de.lmu.ifi.dbs.database;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.index.spatial.SpatialIndex;
import de.lmu.ifi.dbs.index.spatial.rtree.RTree;
public class RTreeDatabase extends SpatialIndexDatabase {
/**
* The name of the file for storing the RTree.
*/
private String fileName;
/**
* The size of a page in bytes.
*/
private int pageSize = 4000;
/**
* Tthe size of the cache.
*/
private int cacheSize = 50;
/**
* If true, the RTree will have a flat directory
*/
private boolean flatDirectory = false;
/**
* Empty constructor
*/
public RTreeDatabase() {
}
/**
* Creates a new RTreeDatabase with the specified parameters.
*
* @param fileName the name of the file for storing the RTree, if this parameter
* is null the RTree will be hold in main memory
* @param pageSize the size of a page in bytes
* @param cacheSize the size of the cache (must be >= 1)
* @param flatDirectory if true, the RTree will have a flat directory (only one level)
*/
public RTreeDatabase(String fileName, int pageSize, int cacheSize, boolean flatDirectory) {
this.fileName = fileName;
this.pageSize = pageSize;
this.cacheSize = cacheSize;
this.flatDirectory = flatDirectory;
}
/**
* Returns the specific spatial index object for this database.
*
* @return the spatial index for this database
*/
public SpatialIndex createSpatialIndex(final RealVector[] objects, final int[] ids) {
return new RTree(objects, ids, fileName, pageSize, cacheSize, flatDirectory);
}
/**
* Returns the spatial index object with the specified parameters
* for this database.
*
* @param dimensionality the dimensionality of the objects to be indexed
*/
public SpatialIndex createSpatialIndex(int dimensionality) {
return new RTree(dimensionality, fileName, pageSize, cacheSize, flatDirectory);
}
/**
* @see de.lmu.ifi.dbs.database.Database#description()
*/
public String description() {
StringBuffer description = new StringBuffer();
description.append(RTreeDatabase.class.getName());
description.append(" holds all the data in a RTree index structure.");
return description.toString();
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(java.lang.String[])
*/
public String[] setParameters(String[] args) throws IllegalArgumentException {
// TODO set parameters
// TODO return remaining parameters
return args;
}
}
|
package demo.example.com.customarrayadapter.customviews.data;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
// STARTS IN ANDROIDMANIFEST.XML
public class FlavorsProvider extends ContentProvider {
private static final String LOG_TAG = FlavorsProvider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private FlavorsDBHelper mOpenHelper;
// Codes for the UriMatcher //////
private static final int FLAVOR = 100;
private static final int FLAVOR_WITH_ID = 200;
private static final int FAVORITES = 300;
private static final int FAVORITES_WITH_ID = 400;
private static final String QUERY_STATEMENT = "INSERT OR IGNORE INTO favorites(movie_id," +
"version_name," +
"icon," +
"description," +
"film_poster," +
"poster_path," +
"adult," +
"overview," +
"release_date," +
"original_title," +
"original_language," +
"title," +
"backdrop_path," +
"popularity," +
"vote_count," +
"video," +
"vote_average) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
private static UriMatcher buildUriMatcher(){
// Build a UriMatcher by adding a specific code to return based on a match
// It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = FlavorsContract.CONTENT_AUTHORITY;
// add a code for each type of URI you want
// CONTENT_AUTHORITY = "demo.example.com.customarrayadapter.app";
// TABLE_FLAVORS = "flavor";
// FLAVOR = 100;
// EG, demo.example.com.customarrayadapter.app/flavor/100
matcher.addURI(authority, FlavorsContract.FlavorEntry.TABLE_FLAVORS, FLAVOR);
// CONTENT_AUTHORITY = "demo.example.com.customarrayadapter.app";
// TABLE_FLAVORS = "flavor/
// FLAVOR_WITH_ID = 200;
// EG, demo.example.com.customarrayadapter.app/flavor/#/200
matcher.addURI(authority, FlavorsContract.FlavorEntry.TABLE_FLAVORS + "/#", FLAVOR_WITH_ID);
matcher.addURI(authority, FlavorsContract.FavoritesEntry.TABLE_FAVORITES, FAVORITES);
matcher.addURI(authority, FlavorsContract.FavoritesEntry.TABLE_FAVORITES + "/#", FAVORITES_WITH_ID);
return matcher;
}
@Override
public boolean onCreate(){
mOpenHelper = new FlavorsDBHelper(getContext());
return true;
}
@Override
public String getType(@NonNull Uri uri){
final int match = sUriMatcher.match(uri);
Log.d(LOG_TAG,"***uri: "+uri);
switch (match){
case FLAVOR:{
Log.d(LOG_TAG,"getType - FLAVOR");
return FlavorsContract.FlavorEntry.CONTENT_DIR_TYPE;
}
case FLAVOR_WITH_ID:{
Log.d(LOG_TAG,"getType - FLAVOR_WITH_ID");
return FlavorsContract.FlavorEntry.CONTENT_ITEM_TYPE;
}
default:{
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/*
Note:
These function are called from MainActivityFragment.
*/
@Override
public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder){ // uri: ref db,
// projection: columns - id,description,
// selection: specific column,
// selectionArgs: column id = 2
Cursor retCursor;
switch(sUriMatcher.match(uri)){
// All Flavors selected
case FLAVOR:{
retCursor = mOpenHelper.getReadableDatabase().query(
FlavorsContract.FlavorEntry.TABLE_FLAVORS,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
retCursor.setNotificationUri(getContext().getContentResolver(),uri);
Log.d(LOG_TAG,"query - FLAVOR");
return retCursor;
// TEST FAVORITES TABLE!!!!
/*} case FAVORITES:{
retCursor = mOpenHelper.getReadableDatabase().query(
FlavorsContract.FavoritesEntry.TABLE_FAVORITES,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
retCursor.setNotificationUri(getContext().getContentResolver(),uri);
Log.d(LOG_TAG,"query - FLAVOR");
return retCursor;
*/
}
// Individual flavor based on Id selected
case FLAVOR_WITH_ID:{
retCursor = mOpenHelper.getReadableDatabase().query(
FlavorsContract.FlavorEntry.TABLE_FLAVORS,
projection,
FlavorsContract.FlavorEntry._ID + " = ?",
new String[] {String.valueOf(ContentUris.parseId(uri))},
null,
null,
sortOrder);
retCursor.setNotificationUri(getContext().getContentResolver(),uri);
Log.d(LOG_TAG,"query - FLAVOR_WITH_ID");
return retCursor;
}
default:{
// By default, we assume a bad URI
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public Uri insert(@NonNull Uri uri, ContentValues values){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Uri returnUri;
switch (sUriMatcher.match(uri)) {
case FLAVOR: {
long _id = db.insert(FlavorsContract.FlavorEntry.TABLE_FLAVORS, null, values);
// insert unless it is already contained in the database
if (_id > 0) {
returnUri = FlavorsContract.FlavorEntry.buildFlavorsUri(_id);
} else {
throw new android.database.SQLException("Failed to insert row into: " + uri);
}
Log.d(LOG_TAG,"insert - FLAVOR");
break;
} case FAVORITES: {
db.beginTransaction();
SQLiteStatement stmt = null;
try {
stmt = db.compileStatement(QUERY_STATEMENT);
stmt.bindLong(1,
values.getAsInteger( FlavorsContract.FlavorEntry.COLUMN_MOVIE_ID));
String version = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_VERSION_NAME);
stmt.bindString(2,
version != null ? values.getAsString( FlavorsContract.FlavorEntry.COLUMN_VERSION_NAME) : "null");
String icon = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_ICON);
stmt.bindString(3,icon != null ? icon : "null");
String description = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_DESCRIPTION);
stmt.bindString(4,description != null ? description : "null");
String filmPoster = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_FILM_POSTER);
stmt.bindString(5,filmPoster != null ? filmPoster : "null");
String posterPath = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_POSTER_PATH);
stmt.bindString(6,posterPath != null ? posterPath : "null");
stmt.bindLong(7,
values.getAsInteger( FlavorsContract.FlavorEntry.COLUMN_ADULT));
String overview = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_OVERVIEW);
stmt.bindString(8,overview != null ? overview : "null");
String releasedDate = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_RELEASE_DATE);
stmt.bindString(9,releasedDate != null ? releasedDate : "null");
String originalTitle = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_ORIGINAL_TITLE);
stmt.bindString(10,originalTitle != null ? originalTitle : "null");
String originalLanguage = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_ORIGINAL_LANGUAGE);
stmt.bindString(11,originalLanguage != null ? originalLanguage : "null");
String title = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_TITLE);
stmt.bindString(12,title != null ? title : "null");
String backdropPath = values.getAsString( FlavorsContract.FlavorEntry.COLUMN_BACKDROP_PATH);
stmt.bindString(13,backdropPath != null ? backdropPath : "null");
stmt.bindDouble(14,
values.getAsFloat( FlavorsContract.FlavorEntry.COLUMN_POPULARITY));
stmt.bindLong(16,
values.getAsInteger( FlavorsContract.FlavorEntry.COLUMN_VOTE_COUNT));
stmt.bindLong(16,
values.getAsInteger( FlavorsContract.FlavorEntry.COLUMN_VIDEO));
stmt.bindDouble(17,
values.getAsFloat( FlavorsContract.FlavorEntry.COLUMN_VOTE_AVERAGE));
stmt.execute();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
if (stmt != null) stmt.close();
}
// insert unless it is already contained in the database
if (stmt != null) {
// TEST FAVORITES TABLE (DISPLAY TO LOG). IF WORKS USE CURSORLOADER LATER!!!!!!!!!
Cursor retCursor = mOpenHelper.getReadableDatabase().query(
FlavorsContract.FavoritesEntry.TABLE_FAVORITES,
null,
null,
null,
null,
null,
null);
if (retCursor != null ) {
if (retCursor.moveToFirst()) {
do {
String poster = retCursor.getString( retCursor.getColumnIndex(FlavorsContract.FavoritesEntry.COLUMN_TITLE));
Log.d(LOG_TAG,"retCursor: " + poster);
}while (retCursor.moveToNext());
}
}
retCursor.close();
returnUri = FlavorsContract.FavoritesEntry.buildFavoritesUri(0);
} else {
throw new android.database.SQLException("Failed to insert row into: " + uri);
}
Log.d(LOG_TAG,"insert - FAVORITES " + stmt);
break;
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(@NonNull Uri uri, String selection, String[] selectionArgs){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numDeleted;
switch(match){
case FLAVOR:
numDeleted = db.delete(
FlavorsContract.FlavorEntry.TABLE_FLAVORS, selection, selectionArgs);
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
FlavorsContract.FlavorEntry.TABLE_FLAVORS + "'");
Log.d(LOG_TAG,"delete - FLAVOR");
break;
case FLAVOR_WITH_ID:
numDeleted = db.delete(FlavorsContract.FlavorEntry.TABLE_FLAVORS,
FlavorsContract.FlavorEntry._ID + " = ?",
new String[]{String.valueOf(ContentUris.parseId(uri))});
// reset _ID
db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
FlavorsContract.FlavorEntry.TABLE_FLAVORS + "'");
Log.d(LOG_TAG,"delete - FLAVOR_WITH_ID");
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
return numDeleted;
}
@Override
public int bulkInsert(@NonNull Uri uri,@NonNull ContentValues[] values){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch(match){
case FLAVOR:
// allows for multiple transactions
db.beginTransaction();
// keep track of successful inserts
int numInserted = 0;
try{
for(ContentValues value : values){
if (value == null){
throw new IllegalArgumentException("Cannot have null content values");
}
long _id = -1;
try{
_id = db.insertOrThrow(FlavorsContract.FlavorEntry.TABLE_FLAVORS,
null, value);
}catch(SQLiteConstraintException e) {
Log.w(LOG_TAG, "Attempting to insert " +
value.getAsString(
FlavorsContract.FlavorEntry.COLUMN_VERSION_NAME)
+ " but value is already in database.");
}
if (_id != -1){
numInserted++;
}
}
if(numInserted > 0){
// If no errors, declare a successful transaction.
// database will not populate if this is not called
db.setTransactionSuccessful();
}
} finally {
// all transactions occur at once
db.endTransaction();
}
if (numInserted > 0){
// if there was successful insertion, notify the content resolver that there
// was a change
getContext().getContentResolver().notifyChange(uri, null);
}
Log.d(LOG_TAG,"bulkInsert - FLAVOR");
return numInserted;
default:
Log.d(LOG_TAG,"bulkInsert (default) - FLAVOR");
return super.bulkInsert(uri, values);
}
}
@Override
public int update(@NonNull Uri uri, ContentValues contentValues, String selection, String[] selectionArgs){
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int numUpdated;
if (contentValues == null){
throw new IllegalArgumentException("Cannot have null content values");
}
switch(sUriMatcher.match(uri)){
case FLAVOR:{
numUpdated = db.update(FlavorsContract.FlavorEntry.TABLE_FLAVORS,
contentValues,
selection,
selectionArgs);
Log.d(LOG_TAG,"update - FLAVOR");
break;
}
case FLAVOR_WITH_ID: {
numUpdated = db.update(FlavorsContract.FlavorEntry.TABLE_FLAVORS,
contentValues,
FlavorsContract.FlavorEntry._ID + " = ?",
new String[] {String.valueOf(ContentUris.parseId(uri))});
Log.d(LOG_TAG,"update - FLAVOR_WITH_ID");
break;
}
default:{
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
if (numUpdated > 0){
getContext().getContentResolver().notifyChange(uri, null);
}
return numUpdated;
}
}
|
package com.itmill.toolkit.ui;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import com.itmill.toolkit.terminal.PaintException;
import com.itmill.toolkit.terminal.PaintTarget;
import com.itmill.toolkit.terminal.gwt.client.ui.IAbsoluteLayout;
/**
* AbsoluteLayout is a layout implementation that mimics html absolute
* positioning.
*
*/
public class AbsoluteLayout extends AbstractLayout {
private Collection<Component> components = new LinkedHashSet<Component>();
private Map<Component, ComponentPosition> componentToCoordinates = new HashMap<Component, ComponentPosition>();
public AbsoluteLayout() {
setSizeFull();
}
@Override
public String getTag() {
return IAbsoluteLayout.TAGNAME;
}
public Iterator<Component> getComponentIterator() {
return components.iterator();
}
public void replaceComponent(Component oldComponent, Component newComponent) {
ComponentPosition position = getPosition(oldComponent);
removeComponent(oldComponent);
addComponent(newComponent);
componentToCoordinates.put(newComponent, position);
}
@Override
public void addComponent(Component c) {
components.add(c);
super.addComponent(c);
}
@Override
public void removeComponent(Component c) {
components.remove(c);
super.removeComponent(c);
}
public void addComponent(Component c, String cssPosition) {
addComponent(c);
getPosition(c).setCSSString(cssPosition);
}
public ComponentPosition getPosition(Component component) {
if (componentToCoordinates.containsKey(component)) {
return componentToCoordinates.get(component);
} else {
ComponentPosition coords = new ComponentPosition();
componentToCoordinates.put(component, coords);
return coords;
}
}
/**
* TODO symmetric getters and setters for fields to make this simpler to use
* in generic java tools
*
*/
public class ComponentPosition {
private int zIndex = -1;
private float top = -1;
private float right = -1;
private float bottom = -1;
private float left = -1;
private int topUnits;
private int rightUnits;
private int bottomUnits;
private int leftUnits;
/**
* Sets the position attributes using CSS syntax. Example usage:
*
* <code><pre>
* setCSSString("top:10px;left:20%;z-index:16;");
* </pre></code>
*
* @param css
*/
public void setCSSString(String css) {
String[] cssProperties = css.split(";");
for (int i = 0; i < cssProperties.length; i++) {
String[] keyValuePair = cssProperties[i].split(":");
String key = keyValuePair[0].trim();
if (key.equals("")) {
continue;
}
if (key.equals("z-index")) {
zIndex = Integer.parseInt(keyValuePair[1]);
} else {
String value;
if (keyValuePair.length > 1) {
value = keyValuePair[1].trim();
} else {
value = "";
}
String unit = value.replaceAll("[0-9\\.]+", "");
if (!unit.equals("")) {
value = value.substring(0, value.indexOf(unit)).trim();
}
float v = Float.parseFloat(value);
int unitInt = parseCssUnit(unit);
if (key.equals("top")) {
top = v;
topUnits = unitInt;
} else if (key.equals("right")) {
right = v;
rightUnits = unitInt;
} else if (key.equals("bottom")) {
bottom = v;
bottomUnits = unitInt;
} else if (key.equals("left")) {
left = v;
leftUnits = unitInt;
}
}
}
requestRepaint();
}
private int parseCssUnit(String string) {
for (int i = 0; i < UNIT_SYMBOLS.length; i++) {
if (UNIT_SYMBOLS[i].equals(string)) {
return i;
}
}
return 0; // defaults to px (eg. top:0;)
}
public String getCSSString() {
String s = "";
if (top >= 0) {
s += "top:" + top + UNIT_SYMBOLS[topUnits] + ";";
}
if (right >= 0) {
s += "right:" + right + UNIT_SYMBOLS[rightUnits] + ";";
}
if (bottom >= 0) {
s += "bottom:" + bottom + UNIT_SYMBOLS[bottomUnits] + ";";
}
if (left >= 0) {
s += "left:" + left + UNIT_SYMBOLS[leftUnits] + ";";
}
if (zIndex >= 0) {
s += "z-index:" + zIndex + ";";
}
return s;
}
public void setTop(float topValue, int topUnits) {
validateLength(topValue, topUnits);
top = topValue;
this.topUnits = topUnits;
requestRepaint();
}
public void setRight(float rightValue, int rightUnits) {
validateLength(rightValue, rightUnits);
right = rightValue;
this.rightUnits = rightUnits;
requestRepaint();
}
public void setBottom(float bottomValue, int units) {
validateLength(bottomValue, units);
bottom = bottomValue;
bottomUnits = units;
requestRepaint();
}
public void setLeft(float leftValue, int units) {
validateLength(leftValue, units);
left = leftValue;
leftUnits = units;
requestRepaint();
}
public void setZIndex(int zIndex) {
this.zIndex = zIndex;
requestRepaint();
}
}
@Override
public void paintContent(PaintTarget target) throws PaintException {
super.paintContent(target);
for (Component component : components) {
target.startTag("cc");
target.addAttribute("css", getPosition(component).getCSSString());
component.paint(target);
target.endTag("cc");
}
}
private static void validateLength(float topValue, int topUnits2) {
// TODO throw on invalid value
}
}
|
package de.lmu.ifi.dbs.elki.result;
import java.util.ArrayList;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.utilities.ClassGenericsUtil;
/**
* Utilities for handling result objects
*
* @author Erich Schubert
*
*/
public class ResultUtil {
/**
* Set global meta association. It tries to replace an existing Association
* first, then tries to insert in the first {@link MetadataResult} otherwise
* creating a new {@link MetadataResult} if none was found.
*
* @param <M> restriction class
* @param result Result collection
* @param meta Association
* @param value Value
*/
public static final <M> void setGlobalAssociation(MultiResult result, AssociationID<M> meta, M value) {
ArrayList<MetadataResult> mrs = result.filterResults(MetadataResult.class);
// first try to overwrite an existing result.
if(mrs != null) {
for(MetadataResult mri : mrs) {
M res = mri.getAssociation(meta);
if(res != null) {
mri.setAssociation(meta, value);
return;
}
}
// otherwise, set in first
if(mrs.size() > 0) {
mrs.get(0).setAssociation(meta, value);
return;
}
}
// or create a new MetadataResult.
MetadataResult mr = new MetadataResult();
mr.setAssociation(meta, value);
result.addResult(mr);
}
/**
* Get first Association from a MultiResult.
*
* @param <M> restriction class
* @param result Result collection
* @param meta Association
* @return first match or null
*/
public static final <M> M getGlobalAssociation(Result result, AssociationID<M> meta) {
List<MetadataResult> mrs = getMetadataResults(result);
if(mrs != null) {
for(MetadataResult mr : mrs) {
M res = mr.getAssociation(meta);
if(res != null) {
return res;
}
}
}
return null;
}
/**
* (Try to) find an association of the given ID in the result.
*
* @param <T> Association result type
* @param result Result to find associations in
* @param assoc Association
* @return First matching annotation result or null
*/
public static final <T> AnnotationResult<T> findAnnotationResult(Result result, AssociationID<T> assoc) {
List<AnnotationResult<?>> anns = getAnnotationResults(result);
return findAnnotationResult(anns, assoc);
}
/**
* (Try to) find an association of the given ID in the result.
*
* @param <T> Association result type
* @param anns List of Results
* @param assoc Association
* @return First matching annotation result or null
*/
@SuppressWarnings("unchecked")
public static final <T> AnnotationResult<T> findAnnotationResult(List<AnnotationResult<?>> anns, AssociationID<T> assoc) {
if(anns == null) {
return null;
}
for(AnnotationResult<?> a : anns) {
if(a.getAssociationID() == assoc) { // == okay to use: association IDs are
// unique objects
return (AnnotationResult<T>) a;
}
}
return null;
}
/**
* Collect all Annotation results from a Result
*
* @param r Result
* @return List of all annotation results
*/
public static List<AnnotationResult<?>> getAnnotationResults(Result r) {
if(r instanceof AnnotationResult<?>) {
List<AnnotationResult<?>> anns = new ArrayList<AnnotationResult<?>>(1);
anns.add((AnnotationResult<?>) r);
return anns;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(AnnotationResult.class));
}
return null;
}
/**
* Collect all ordering results from a Result
*
* @param r Result
* @return List of ordering results
*/
public static List<OrderingResult> getOrderingResults(Result r) {
if(r instanceof OrderingResult) {
List<OrderingResult> ors = new ArrayList<OrderingResult>(1);
ors.add((OrderingResult) r);
return ors;
}
if(r instanceof MultiResult) {
return ((MultiResult) r).filterResults(OrderingResult.class);
}
return null;
}
/**
* Collect all clustering results from a Result
*
* @param r Result
* @return List of clustering results
*/
public static List<Clustering<?>> getClusteringResults(Result r) {
if(r instanceof Clustering<?>) {
List<Clustering<?>> crs = new ArrayList<Clustering<?>>(1);
crs.add((Clustering<?>) r);
return crs;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(Clustering.class));
}
return null;
}
/**
* Collect all collection results from a Result
*
* @param r Result
* @return List of collection results
*/
public static List<CollectionResult<?>> getCollectionResults(Result r) {
if(r instanceof CollectionResult<?>) {
List<CollectionResult<?>> crs = new ArrayList<CollectionResult<?>>(1);
crs.add((CollectionResult<?>) r);
return crs;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(CollectionResult.class));
}
return null;
}
/**
* Return all Iterable results
*
* @param r Result
* @return List of iterable results
*/
public static List<IterableResult<?>> getIterableResults(Result r) {
if(r instanceof IterableResult<?>) {
List<IterableResult<?>> irs = new ArrayList<IterableResult<?>>(1);
irs.add((IterableResult<?>) r);
return irs;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(IterableResult.class));
}
return null;
}
/**
* Return all Metadata results
*
* @param r Result
* @return List of metadata results
*/
public static List<MetadataResult> getMetadataResults(Result r) {
if(r instanceof MetadataResult) {
List<MetadataResult> irs = new ArrayList<MetadataResult>(1);
irs.add((MetadataResult) r);
return irs;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(MetadataResult.class));
}
return null;
}
/**
* Filter results
*
* @param r Result
* @param restrictionClass Restriction
* @return List of filtered results
*/
@SuppressWarnings("unchecked")
public static <C> List<C> filterResults(Result r, Class<?> restrictionClass) {
if(restrictionClass.isInstance(r)) {
List<C> irs = new ArrayList<C>(1);
irs.add((C) r);
return irs;
}
if(r instanceof MultiResult) {
return ClassGenericsUtil.castWithGenericsOrNull(List.class, ((MultiResult) r).filterResults(restrictionClass));
}
return null;
}
}
|
package com.jcwhatever.nucleus;
import com.jcwhatever.nucleus.commands.CommandDispatcher;
import com.jcwhatever.nucleus.messaging.IChatPrefixed;
import com.jcwhatever.nucleus.messaging.IMessenger;
import com.jcwhatever.nucleus.storage.DataPath;
import com.jcwhatever.nucleus.storage.DataStorage;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.storage.MemoryDataNode;
import com.jcwhatever.nucleus.utils.language.LanguageManager;
import org.bukkit.command.PluginCommand;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* An abstract implementation of a Bukkit plugin with
* NucleusFramework specific features.
*/
public abstract class NucleusPlugin extends JavaPlugin implements IChatPrefixed {
static List<NucleusPlugin> _enabled = new ArrayList<>(10);
private LanguageManager _languageManager;
private IDataNode _dataNode;
private boolean _isDebugging;
private IMessenger _messenger;
private IMessenger _anonMessenger;
private boolean _isTesting;
boolean _isEnabled;
/**
* Constructor.
*/
public NucleusPlugin() {
super();
onInit();
}
/**
* Constructor for testing.
*/
protected NucleusPlugin(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
_isTesting = true;
onInit();
}
/**
* Determine if the plugin is in debug mode.
*/
public final boolean isDebugging() {
return _isDebugging;
}
/**
* Set the plugins debug mode.
*
* @param isDebugging True to turn debug on.
*/
public final void setDebugging(boolean isDebugging) {
_isDebugging = isDebugging;
}
/**
* Determine if the plugin is finished loading.
*/
public boolean isLoaded() {
return isEnabled() && _isEnabled;
}
/**
* Get the plugins chat message prefix.
*/
@Override
public abstract String getChatPrefix();
/**
* Get the plugins console message prefix.
*/
@Override
public abstract String getConsolePrefix();
/**
* Get the plugins data node.
*/
public IDataNode getDataNode() {
return _dataNode;
}
/**
* Get the plugins language manager.
*/
public LanguageManager getLanguageManager() {
return _languageManager;
}
/**
* Get the plugins chat and console messenger.
*/
public IMessenger getMessenger() {
return _messenger;
}
/**
* Get the plugins anonymous chat messenger.
*
* <p>A messenger that has no chat prefix.</p>
*/
public IMessenger getAnonMessenger() {
return _anonMessenger;
}
@Override
public final void onEnable() {
onPreEnable();
_messenger = Nucleus.getMessengerFactory().get(this);
_anonMessenger = Nucleus.getMessengerFactory().getAnon(this);
loadDataNode();
_languageManager = new LanguageManager(this);
Nucleus.registerPlugin(this);
if (!(this instanceof BukkitPlugin))
_enabled.add(this);
onPostPreEnable();
}
@Override
public final void onDisable() {
Nucleus.unregisterPlugin(this);
try {
onDisablePlugin();
}
catch (Throwable e) {
e.printStackTrace();
}
}
/**
* Invoked when the plugin is instantiated.
*/
protected void onInit() {
// do nothing
}
/**
* Invoked before the plugin config is loaded.
*/
protected void onPreEnable() {
// do nothing
}
/**
* Invoked after the plugin config is loaded but before it is enabled.
*/
protected void onPostPreEnable() {
// do nothing
}
/**
* Invoked when the plugin is enabled.
*/
protected abstract void onEnablePlugin();
/**
* Invoked when the plugin is disabled.
*/
protected abstract void onDisablePlugin();
/**
* Register all commands defined in the plugin.yml
* file to the specified dispatcher.
*
* @param dispatcher The dispatcher to register.
*/
protected void registerCommands(CommandDispatcher dispatcher) {
Set<String> commands = getDescription().getCommands().keySet();
for (String cmd : commands) {
PluginCommand command = getCommand(cmd);
command.setExecutor(dispatcher);
command.setTabCompleter(dispatcher);
}
}
/**
* Register event listeners.
*
* @param listeners The listeners to register.
*/
protected void registerEventListeners(Listener...listeners) {
PluginManager pm = getServer().getPluginManager();
for (Listener listener : listeners) {
pm.registerEvents(listener, this);
}
}
/*
* Load the plugins data node.
*/
private void loadDataNode() {
File dir = getDataFolder();
if (!_isTesting && !dir.exists() && !dir.mkdirs()) {
throw new RuntimeException("Failed to create data folders.");
}
if (_isTesting) {
_dataNode = new MemoryDataNode(this);
}
else {
_dataNode = DataStorage.get(this, new DataPath("config"));
if (!_dataNode.load()) {
getServer().getPluginManager().disablePlugin(this);
throw new RuntimeException("The plugins data node (config) could not be loaded!");
}
}
_isDebugging = _dataNode.getBoolean("debug");
}
}
|
package natlab;
import natlab.options.Options;
import natlab.ast.*;
/*import matlab.MatlabParser;
import matlab.TranslationProblem;
import matlab.OffsetTracker;
import matlab.TextPosition;*/
import matlab.*;
import matlab.FunctionEndScanner.NoChangeResult;
import matlab.FunctionEndScanner.ProblemResult;
import matlab.FunctionEndScanner.TranslationResult;
import org.antlr.runtime.ANTLRReaderStream;
import beaver.Parser;
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
public class Main
{
private static Options options;
public static void main(String[] args)
{
boolean quiet; //controls the suppression of messages
StringBuffer errors = new StringBuffer();
options = new Options();
if( processCmdLine( args ) ){
if( options.help() ){
System.err.println(options.getUsage());
}
else{
quiet = options.quiet(); //check if quiet mode is active
if( options.e() ){
if( !quiet )
System.err.println("exhaustive list");
}
if( options.d() ){
if( !quiet )
System.err.println("dynamic linking");
}
if( options.getFiles().size() == 0 ){
System.err.println("No files provided, must have at least one file.");
}
else{
LinkedList<Program> programs = new LinkedList<Program>();
for( Object o : options.getFiles() ){
String file = (String) o;
Reader fileReader = new StringReader("");
if( options.matlab() ){
try{
if( !quiet )
System.err.println("Translating "+file+" to Natlab");
BufferedReader in = new BufferedReader( new FileReader( file ) );
FunctionEndScanner prescanner = new FunctionEndScanner(in);
FunctionEndScanner.Result result = prescanner.translate();
in.close();
if(result instanceof NoChangeResult){
in = new BufferedReader(new FileReader(file) ); //just re-open original file
}else if(result instanceof ProblemResult){
for(TranslationProblem prob : ((ProblemResult) result).getProblems()){
System.err.println(prob);
}
System.exit(0); //terminate early since extraction parser can't work without balanced 'end's
} else if(result instanceof TranslationResult){
TranslationResult transResult = (TranslationResult) result;
in = new BufferedReader(new StringReader(transResult.getText()));
}
OffsetTracker offsetTracker = new OffsetTracker(new TextPosition(1, 1));
List<TranslationProblem> problems = new ArrayList<TranslationProblem>();
String destText = MatlabParser.translate(new ANTLRReaderStream(in), 1, 1, offsetTracker, problems);
fileReader = new StringReader(destText);
}catch(FileNotFoundException e){
System.err.println("File "+file+" not found!\nAborting");
System.exit(1);
}
catch(IOException e){
System.err.println("Error translating "+file);
System.err.println(e.getMessage());
System.err.println("\n\nAborting");
}
}
else{
try{
fileReader = new FileReader( file );
}catch(FileNotFoundException e){
System.err.println("File "+file+" not found!\nAborting");
System.exit(1);
}
}
if( !quiet )
System.err.println("Parsing: " + file);
Program prog = parseFile( file, fileReader, errors );
if( errors.length() > 0 )
System.err.print( errors.toString() );
if( prog == null ){
System.err.println("\nSkipping " + file);
break;
}
programs.add( prog );
}
CompilationUnits cu = new CompilationUnits();
for( Program p : programs ){
cu.addProgram( p );
}
if( options.xml() ){
//System.out.println(cu.ASTtoXML());
System.out.print(cu.XMLtoString(cu.ASTtoXML()));
}
else if( options.pretty() ){
if( !quiet )
System.err.println("Pretty Printing");
System.out.println(cu.getPrettyPrinted());
}
}
}
}
}
//Parse a given file and return a Program ast node
//if file does not exist or other problems, exit program
private static Program parseFile(String fName, Reader file, StringBuffer errBuf )
{
NatlabParser parser = new NatlabParser();
NatlabScanner scanner = null;
CommentBuffer cb = new CommentBuffer();
parser.setCommentBuffer(cb);
try{
scanner = new NatlabScanner( file );
scanner.setCommentBuffer( cb );
try{
Program prog = (Program)parser.parse(scanner);
if( parser.hasError() ){
for( String error : parser.getErrors())
errBuf.append(error + "\n");
prog = null;
}
return prog;
}catch(Parser.Exception e){
errBuf.append(e.getMessage());
for(String error : parser.getErrors()) {
errBuf.append(error + "\n");
}
return null;
}
}catch(FileNotFoundException e){
errBuf.append( "File "+fName+" not found!\n" );
return null;
}
catch(IOException e){
errBuf.append( "Problem parsing "+fName + "\n");
if( e.getMessage() != null )
errBuf.append( e.getMessage() + "\n");
return null;
}
finally{
if(scanner != null) {
scanner.stop();
}
}
}
private static boolean processCmdLine(String[] args)
{
try{
options.parse( args );
if( args.length == 0 ){
System.out.println("No options given\n" +
"Try -help for usage");
return false;
}
return true;
}catch( NullPointerException e ){
System.err.println("options variable not initialized");
throw e;
}
}
}
|
/*
* EDIT: 02/09/2004 - Renamed original WidgetViewport to WidgetViewRectangle.
* GOP
*/
package com.jme.renderer.lwjgl;
import java.io.File;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.Arrays;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBVertexBufferObject;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.glu.GLU;
import com.jme.bounding.BoundingVolume;
import com.jme.curve.Curve;
import com.jme.math.Quaternion;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.RenderQueue;
import com.jme.renderer.Renderer;
import com.jme.scene.CompositeMesh;
import com.jme.scene.Geometry;
import com.jme.scene.Line;
import com.jme.scene.Point;
import com.jme.scene.Spatial;
import com.jme.scene.Text;
import com.jme.scene.TriMesh;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.AttributeState;
import com.jme.scene.state.CullState;
import com.jme.scene.state.DitherState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.FragmentProgramState;
import com.jme.scene.state.GLSLShaderObjectsState;
import com.jme.scene.state.LightState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.ShadeState;
import com.jme.scene.state.StencilState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.VertexProgramState;
import com.jme.scene.state.WireframeState;
import com.jme.scene.state.ZBufferState;
import com.jme.scene.state.lwjgl.LWJGLAlphaState;
import com.jme.scene.state.lwjgl.LWJGLAttributeState;
import com.jme.scene.state.lwjgl.LWJGLCullState;
import com.jme.scene.state.lwjgl.LWJGLDitherState;
import com.jme.scene.state.lwjgl.LWJGLFogState;
import com.jme.scene.state.lwjgl.LWJGLFragmentProgramState;
import com.jme.scene.state.lwjgl.LWJGLLightState;
import com.jme.scene.state.lwjgl.LWJGLMaterialState;
import com.jme.scene.state.lwjgl.LWJGLShadeState;
import com.jme.scene.state.lwjgl.LWJGLShaderObjectsState;
import com.jme.scene.state.lwjgl.LWJGLStencilState;
import com.jme.scene.state.lwjgl.LWJGLTextureState;
import com.jme.scene.state.lwjgl.LWJGLVertexProgramState;
import com.jme.scene.state.lwjgl.LWJGLWireframeState;
import com.jme.scene.state.lwjgl.LWJGLZBufferState;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.widget.WidgetRenderer;
import com.jme.scene.state.RenderState;
/**
* <code>LWJGLRenderer</code> provides an implementation of the
* <code>Renderer</code> interface using the LWJGL API.
*
* @see com.jme.renderer.Renderer
* @author Mark Powell
* @author Joshua Slack - Optimizations and Headless rendering
* @author Tijl Houtbeckers - Small optimizations
* @version $Id: LWJGLRenderer.java,v 1.66 2005-09-07 18:27:57 Mojomonkey Exp $
*/
public class LWJGLRenderer implements Renderer {
// clear color
private ColorRGBA backgroundColor;
// width and height of renderer
private int width;
private int height;
private Vector3f vRot = new Vector3f();
private LWJGLCamera camera;
private LWJGLFont font;
private long numberOfVerts;
private long numberOfTris;
private boolean statisticsOn;
private boolean usingVBO = false;
private LWJGLWireframeState boundsWireState = new LWJGLWireframeState();
private LWJGLTextureState boundsTextState = new LWJGLTextureState();
private LWJGLZBufferState boundsZState = new LWJGLZBufferState();
private boolean inOrthoMode;
private boolean processingQueue;
private RenderQueue queue;
private Vector3f tempVa = new Vector3f();
private DisplayMode mode = Display.getDisplayMode();
private FloatBuffer prevVerts;
private FloatBuffer prevNorms;
private FloatBuffer prevColor;
private FloatBuffer[] prevTex;
private boolean headless = false;
private ContextCapabilities capabilities;
/**
* Constructor instantiates a new <code>LWJGLRenderer</code> object. The
* size of the rendering window is passed during construction.
*
* @param width
* the width of the rendering context.
* @param height
* the height of the rendering context.
*/
public LWJGLRenderer(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
LoggingSystem.getLogger().log(Level.INFO,
"LWJGLRenderer created. W: " + width + "H: " + height);
capabilities = GLContext.getCapabilities();
queue = new RenderQueue(this);
prevTex = new FloatBuffer[createTextureState().getNumberOfUnits()];
}
/**
* Reinitialize the renderer with the given width/height. Also calls resize
* on the attached camera if present.
*
* @param width
* int
* @param height
* int
*/
public void reinit(int width, int height) {
if (width <= 0 || height <= 0) {
LoggingSystem.getLogger().log(Level.WARNING,
"Invalid width " + "and/or height values.");
throw new JmeException("Invalid width and/or height values.");
}
this.width = width;
this.height = height;
if (camera != null)
camera.resize(width, height);
mode = Display.getDisplayMode();
capabilities = GLContext.getCapabilities();
}
/**
* <code>setCamera</code> sets the camera this renderer is using. It
* asserts that the camera is of type <code>LWJGLCamera</code>.
*
* @see com.jme.renderer.Renderer#setCamera(com.jme.renderer.Camera)
*/
public void setCamera(Camera camera) {
if (camera instanceof LWJGLCamera) {
this.camera = (LWJGLCamera) camera;
}
}
/**
* <code>getCamera</code> returns the camera used by this renderer.
*
* @see com.jme.renderer.Renderer#getCamera()
*/
public Camera getCamera() {
return camera;
}
/**
* <code>createCamera</code> returns a default camera for use with the
* LWJGL renderer.
*
* @param width
* the width of the frame.
* @param height
* the height of the frame.
* @return a default LWJGL camera.
*/
public Camera createCamera(int width, int height) {
return new LWJGLCamera(width, height, this);
}
/**
* <code>createAlphaState</code> returns a new LWJGLAlphaState object as a
* regular AlphaState.
*
* @return an AlphaState object.
*/
public AlphaState createAlphaState() {
return new LWJGLAlphaState();
}
/**
* <code>createAttributeState</code> returns a new LWJGLAttributeState
* object as a regular AttributeState.
*
* @return an AttributeState object.
*/
public AttributeState createAttributeState() {
return new LWJGLAttributeState();
}
/**
* <code>createCullState</code> returns a new LWJGLCullState object as a
* regular CullState.
*
* @return a CullState object.
* @see com.jme.renderer.Renderer#createCullState()
*/
public CullState createCullState() {
return new LWJGLCullState();
}
/**
* <code>createDitherState</code> returns a new LWJGLDitherState object as
* a regular DitherState.
*
* @return an DitherState object.
*/
public DitherState createDitherState() {
return new LWJGLDitherState();
}
/**
* <code>createFogState</code> returns a new LWJGLFogState object as a
* regular FogState.
*
* @return an FogState object.
*/
public FogState createFogState() {
return new LWJGLFogState();
}
/**
* <code>createLightState</code> returns a new LWJGLLightState object as a
* regular LightState.
*
* @return an LightState object.
*/
public LightState createLightState() {
return new LWJGLLightState();
}
/**
* <code>createMaterialState</code> returns a new LWJGLMaterialState
* object as a regular MaterialState.
*
* @return an MaterialState object.
*/
public MaterialState createMaterialState() {
return new LWJGLMaterialState();
}
/**
* <code>createShadeState</code> returns a new LWJGLShadeState object as a
* regular ShadeState.
*
* @return an ShadeState object.
*/
public ShadeState createShadeState() {
return new LWJGLShadeState();
}
/**
* <code>createTextureState</code> returns a new LWJGLTextureState object
* as a regular TextureState.
*
* @return an TextureState object.
*/
public TextureState createTextureState() {
return new LWJGLTextureState();
}
/**
* <code>createWireframeState</code> returns a new LWJGLWireframeState
* object as a regular WireframeState.
*
* @return an WireframeState object.
*/
public WireframeState createWireframeState() {
return new LWJGLWireframeState();
}
/**
* <code>createZBufferState</code> returns a new LWJGLZBufferState object
* as a regular ZBufferState.
*
* @return a ZBufferState object.
*/
public ZBufferState createZBufferState() {
return new LWJGLZBufferState();
}
/**
* <code>createVertexProgramState</code> returns a new
* LWJGLVertexProgramState object as a regular VertexProgramState.
*
* @return a LWJGLVertexProgramState object.
*/
public VertexProgramState createVertexProgramState() {
return new LWJGLVertexProgramState();
}
/**
* <code>createFragmentProgramState</code> returns a new
* LWJGLFragmentProgramState object as a regular FragmentProgramState.
*
* @return a LWJGLFragmentProgramState object.
*/
public FragmentProgramState createFragmentProgramState() {
return new LWJGLFragmentProgramState();
}
/**
* <code>createShaderObjectsState</code> returns a new
* LWJGLShaderObjectsState object as a regular ShaderObjectsState.
*
* @return an ShaderObjectsState object.
*/
public GLSLShaderObjectsState createGLSLShaderObjectsState() {
return new LWJGLShaderObjectsState();
}
/**
* <code>createStencilState</code> returns a new LWJGLStencilState object
* as a regular StencilState.
*
* @return a StencilState object.
*/
public StencilState createStencilState() {
return new LWJGLStencilState();
}
/**
* <code>setBackgroundColor</code> sets the OpenGL clear color to the
* color specified.
*
* @see com.jme.renderer.Renderer#setBackgroundColor(com.jme.renderer.ColorRGBA)
* @param c
* the color to set the background color to.
*/
public void setBackgroundColor(ColorRGBA c) {
// if color is null set background to white.
if (c == null) {
backgroundColor.a = 1.0f;
backgroundColor.b = 1.0f;
backgroundColor.g = 1.0f;
backgroundColor.r = 1.0f;
} else {
backgroundColor = c;
}
GL11.glClearColor(backgroundColor.r, backgroundColor.g,
backgroundColor.b, backgroundColor.a);
}
/**
* <code>getBackgroundColor</code> retrieves the clear color of the
* current OpenGL context.
*
* @see com.jme.renderer.Renderer#getBackgroundColor()
* @return the current clear color.
*/
public ColorRGBA getBackgroundColor() {
return backgroundColor;
}
/**
* <code>clearZBuffer</code> clears the OpenGL depth buffer.
*
* @see com.jme.renderer.Renderer#clearZBuffer()
*/
public void clearZBuffer() {
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT);
}
/**
* <code>clearBackBuffer</code> clears the OpenGL color buffer.
*
* @see com.jme.renderer.Renderer#clearBackBuffer()
*/
public void clearColorBuffer() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearBuffers() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
}
/**
* <code>clearBuffers</code> clears both the color and the depth buffer
* for only the part of the buffer defined by the renderer width/height.
*
* @see com.jme.renderer.Renderer#clearBuffers()
*/
public void clearStrictBuffers() {
GL11.glDisable(GL11.GL_DITHER);
GL11.glEnable(GL11.GL_SCISSOR_TEST);
GL11.glScissor(0, 0, width, height);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glDisable(GL11.GL_SCISSOR_TEST);
GL11.glEnable(GL11.GL_DITHER);
}
/**
* <code>displayBackBuffer</code> renders any queued items then flips the
* rendered buffer (back) with the currently displayed buffer.
*
* @see com.jme.renderer.Renderer#displayBackBuffer()
*/
public void displayBackBuffer() {
renderQueue();
prevColor = prevNorms = prevVerts = null;
Arrays.fill(prevTex, null);
GL11.glFlush();
if (!headless)
Display.update();
}
/**
* render queue if needed
*/
public void renderQueue() {
processingQueue = true;
queue.renderBuckets();
if (Spatial.getCurrentState(RenderState.RS_ZBUFFER) != null
&& !((ZBufferState) Spatial
.getCurrentState(RenderState.RS_ZBUFFER)).isWritable()) {
if (Spatial.defaultStateList[RenderState.RS_ZBUFFER] != null)
Spatial.defaultStateList[RenderState.RS_ZBUFFER].apply();
Spatial.clearCurrentState(RenderState.RS_ZBUFFER);
}
processingQueue = false;
}
/**
* clear the render queue
*/
public void clearQueue() {
queue.clearBuckets();
}
public void setOrtho() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(0, mode.getWidth(), 0, mode.getHeight());
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void setOrthoCenter() {
if (inOrthoMode) {
throw new JmeException("Already in Orthographic mode.");
}
// set up ortho mode
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPushMatrix();
GL11.glLoadIdentity();
GLU.gluOrtho2D(-mode.getWidth() / 2, mode.getWidth() / 2, -mode
.getHeight() / 2, mode.getHeight() / 2);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glLoadIdentity();
inOrthoMode = true;
}
public void unsetOrtho() {
if (!inOrthoMode) {
throw new JmeException("Not in Orthographic mode.");
}
// remove ortho mode, and go back to original
// state
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
postdrawMesh();
inOrthoMode = false;
}
/**
* <code>takeScreenShot</code> saves the current buffer to a file. The
* file name is provided, and .png will be appended. True is returned if the
* capture was successful, false otherwise.
*
* @param filename
* the name of the file to save.
* @return true if successful, false otherwise.
*/
public boolean takeScreenShot(String filename) {
if (null == filename) {
throw new JmeException("Screenshot filename cannot be null");
}
LoggingSystem.getLogger().log(Level.INFO,
"Taking screenshot: " + filename + ".png");
// Create a pointer to the image info and create a buffered image to
// hold it.
IntBuffer buff = BufferUtils.createIntBuffer(width * height);
grabScreenContents(buff, 0, 0, width, height);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// Grab each pixel information and set it to the BufferedImage info.
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
img.setRGB(x, y, buff.get((height - y - 1) * width + x));
}
}
// write out the screenshot image to a file.
try {
File out = new File(filename + ".png");
return ImageIO.write(img, "png", out);
} catch (IOException e) {
LoggingSystem.getLogger().log(Level.WARNING,
"Could not create file: " + filename + ".png");
return false;
}
}
/**
* <code>grabScreenContents</code> reads a block of pixels from the
* current framebuffer.
*
* @param buff
* a buffer to store contents in.
* @param x -
* x starting point of block
* @param y -
* y starting point of block
* @param w -
* width of block
* @param h -
* height of block
*/
public void grabScreenContents(IntBuffer buff, int x, int y, int w, int h) {
GL11
.glReadPixels(x, y, w, h, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE,
buff);
}
/**
* <code>draw</code> draws a point object where a point contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Point)
* @param p
* the point object to render.
*/
public void draw(Point p) {
// set world matrix
Quaternion rotation = p.getWorldRotation();
Vector3f translation = p.getWorldTranslation();
Vector3f scale = p.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_POINTS);
// draw points
Vector3f[] vertex = p.getVertices();
Vector3f[] normal = p.getNormals();
ColorRGBA[] color = p.getColors();
Vector2f[] texture = p.getTextures();
if (statisticsOn) {
numberOfVerts += vertex.length;
}
if (normal != null) {
if (color != null) {
if (texture != null) {
// N,C,T
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
} else {
if (color != null) {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length; i++) {
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
// none
for (int i = 0; i < vertex.length; i++) {
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
}
GL11.glEnd();
postdrawMesh();
}
/**
* <code>draw</code> draws a line object where a line contains a
* collection of vertices, normals, colors and texture coordinates.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Line)
* @param l
* the line object to render.
*/
public void draw(Line l) {
// set world matrix
Quaternion rotation = l.getWorldRotation();
Vector3f translation = l.getWorldTranslation();
Vector3f scale = l.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINES);
// draw line
Vector3f[] vertex = l.getVertices();
Vector3f[] normal = l.getNormals();
ColorRGBA[] color = l.getColors();
Vector2f[] texture = l.getTextures();
if (statisticsOn) {
numberOfVerts += vertex.length;
}
if (normal != null) {
if (color != null) {
if (texture != null) {
// N,C,T
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glNormal3f(normal[i].x, normal[i].y, normal[i].z);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
} else {
if (color != null) {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glColor4f(color[i].r, color[i].g, color[i].b,
color[i].a);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
} else {
if (texture != null) {
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glTexCoord2f(texture[i].x, texture[i].y);
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
} else {
// none
for (int i = 0; i < vertex.length - 1; i++) {
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
i++;
GL11.glVertex3f(vertex[i].x, vertex[i].y, vertex[i].z);
}
}
}
}
GL11.glEnd();
postdrawMesh();
}
/**
* <code>draw</code> renders a curve object.
*
* @param c
* the curve object to render.
*/
public void draw(Curve c) {
// set world matrix
Quaternion rotation = c.getWorldRotation();
Vector3f translation = c.getWorldTranslation();
Vector3f scale = c.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
// render the object
GL11.glBegin(GL11.GL_LINE_STRIP);
ColorRGBA[] color = c.getColors();
float colorInterval = 0;
float colorModifier = 0;
int colorCounter = 0;
if (null != color) {
GL11.glColor4f(color[0].r, color[0].g, color[0].b, color[0].a);
colorInterval = 1f / c.getColors().length;
colorModifier = colorInterval;
colorCounter = 0;
}
Vector3f point;
float limit = (1 + (1.0f / c.getSteps()));
for (float t = 0; t <= limit; t += 1.0f / c.getSteps()) {
if (t >= colorInterval && color != null) {
colorInterval += colorModifier;
GL11.glColor4f(c.getColors()[colorCounter].r,
c.getColors()[colorCounter].g,
c.getColors()[colorCounter].b,
c.getColors()[colorCounter].a);
colorCounter++;
}
point = c.getPoint(t, tempVa);
GL11.glVertex3f(point.x, point.y, point.z);
}
if (statisticsOn) {
numberOfVerts += limit;
}
GL11.glEnd();
postdrawMesh();
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param t
* the mesh to render.
*/
public void draw(TriMesh t) {
predrawMesh(t);
IntBuffer indices = t.getIndexAsBuffer();
int verts = (t.getVertQuantity() >= 0 ? t.getVertQuantity() : t
.getVertices().length);
if (statisticsOn) {
numberOfTris += (t.getTriangleQuantity() >= 0 ? t
.getTriangleQuantity() : t.getIndices().length / 3);
numberOfVerts += verts;
}
if (capabilities.OpenGL12)
GL12.glDrawRangeElements(GL11.GL_TRIANGLES, 0, verts, indices);
else
GL11.glDrawElements(GL11.GL_TRIANGLES, indices);
postdrawMesh();
}
/**
* <code>draw</code> renders a <code>CompositeMesh</code> object
* including it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.CompositeMesh)
* @param t
* the mesh to render.
*/
public void draw(CompositeMesh t) {
predrawMesh(t);
IntBuffer indices = t.getIndexAsBuffer().duplicate();
CompositeMesh.IndexRange[] ranges = t.getIndexRanges();
int verts = (t.getVertQuantity() >= 0 ? t.getVertQuantity() : t
.getVertices().length);
if (statisticsOn) {
numberOfVerts += verts;
numberOfTris += t.getTriangleQuantity();
}
indices.position(0);
for (int i = 0; i < ranges.length; i++) {
int mode;
switch (ranges[i].getKind()) {
case CompositeMesh.IndexRange.TRIANGLES:
mode = GL11.GL_TRIANGLES;
break;
case CompositeMesh.IndexRange.TRIANGLE_STRIP:
mode = GL11.GL_TRIANGLE_STRIP;
break;
case CompositeMesh.IndexRange.TRIANGLE_FAN:
mode = GL11.GL_TRIANGLE_FAN;
break;
case CompositeMesh.IndexRange.QUADS:
mode = GL11.GL_QUADS;
break;
case CompositeMesh.IndexRange.QUAD_STRIP:
mode = GL11.GL_QUAD_STRIP;
break;
default:
throw new JmeException("Unknown index range type "
+ ranges[i].getKind());
}
indices.limit(indices.position() + ranges[i].getCount());
if (capabilities.OpenGL12)
GL12.glDrawRangeElements(mode, 0, verts, indices);
else
GL11.glDrawElements(mode, indices);
indices.position(indices.limit());
}
postdrawMesh();
}
IntBuffer buf = BufferUtils.createIntBuffer(16);
public void prepVBO(Geometry g) {
if (!capabilities.GL_ARB_vertex_buffer_object)
return;
if (g.isVBOVertexEnabled() && g.getVBOVertexID() <= 0) {
g.updateVertexBuffer(g.getVertices().length);
ARBVertexBufferObject.glGenBuffersARB(buf);
g.setVBOVertexID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getVBOVertexID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB,
g.getVerticeAsFloatBuffer(), ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
buf.clear();
}
if (g.isVBONormalEnabled() && g.getVBONormalID() <= 0) {
g.updateNormalBuffer(g.getVertices().length);
ARBVertexBufferObject.glGenBuffersARB(buf);
g.setVBONormalID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getVBONormalID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getNormalAsFloatBuffer(),
ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
buf.clear();
}
if (g.isVBOColorEnabled() && g.getVBOColorID() <= 0) {
g.updateColorBuffer(g.getVertices().length);
if (g.getColorAsFloatBuffer() != null) {
ARBVertexBufferObject.glGenBuffersARB(buf);
g.setVBOColorID(buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g.getVBOColorID());
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g
.getColorAsFloatBuffer(), ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
buf.clear();
}
}
if (g.isVBOTextureEnabled()) {
for (int i = 0; i < g.getNumberOfUnits(); i++) {
if (g.getVBOTextureID(i) <= 0
&& g.getTextureAsFloatBuffer(i) != null) {
g.updateTextureBuffer(i, g.getVertices().length);
ARBVertexBufferObject.glGenBuffersARB(buf);
g.setVBOTextureID(i, buf.get(0));
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g
.getVBOTextureID(i));
ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, g
.getTextureAsFloatBuffer(i), ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
buf.clear();
}
}
}
buf.clear();
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param g
* the mesh to render.
*/
public void drawBounds(Geometry g) {
// get the bounds
if (!(g.getWorldBound() instanceof TriMesh))
return;
drawBounds(g.getWorldBound());
}
/**
* <code>draw</code> renders a <code>TriMesh</code> object including
* it's normals, colors, textures and vertices.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.TriMesh)
* @param bv
* the mesh to render.
*/
public void drawBounds(BoundingVolume bv) {
// get the bounds
if (!(bv instanceof TriMesh))
return;
bv.recomputeMesh();
setBoundsStates(true);
draw((TriMesh) bv);
setBoundsStates(false);
}
/**
* <code>draw</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void draw(Spatial s) {
if (s != null) {
s.onDraw(this);
}
}
/**
* <code>drawBounds</code> renders a scene by calling the nodes
* <code>onDraw</code> method.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Spatial)
*/
public void drawBounds(Spatial s) {
if (s != null) {
s.onDrawBounds(this);
}
}
/**
* <code>draw</code> renders a text object using a predefined font.
*
* @see com.jme.renderer.Renderer#draw(com.jme.scene.Text)
*/
public void draw(Text t) {
if (font == null) {
font = new LWJGLFont();
}
font.setColor(t.getTextColor());
font.print((int) t.getWorldTranslation().x, (int) t
.getWorldTranslation().y, t.getWorldScale(), t.getText(), 0);
}
/**
* <code>draw</code> renders a WidgetRenderer object to the back buffer.
*
* @see com.jme.renderer.Renderer#draw(WidgetRenderer)
*/
public void draw(WidgetRenderer wr) {
wr.render();
}
/**
* <code>enableStatistics</code> will turn on statistics gathering.
*
* @param value
* true to use statistics, false otherwise.
*/
public void enableStatistics(boolean value) {
statisticsOn = value;
}
/**
* <code>clearStatistics</code> resets the vertices and triangles counter
* for the statistics information.
*/
public void clearStatistics() {
numberOfVerts = 0;
numberOfTris = 0;
}
/**
* <code>getStatistics</code> returns a string value of the rendering
* statistics information (number of triangles and number of vertices).
*
* @return the string representation of the current statistics.
*/
public String getStatistics() {
return "Number of Triangles: " + numberOfTris
+ " : Number of Vertices: " + numberOfVerts;
}
/**
* <code>getStatistics</code> returns a string value of the rendering
* statistics information (number of triangles and number of vertices).
*
* @return the string representation of the current statistics.
*/
public StringBuffer getStatistics(StringBuffer a) {
a.setLength(0);
a.append("Number of Triangles: ").append(numberOfTris).append(
" : Number of Vertices: ").append(numberOfVerts);
return a;
}
/**
* See Renderer.isHeadless()
*
* @return boolean
*/
public boolean isHeadless() {
return headless;
}
/**
* See Renderer.setHeadless()
*
* @return boolean
*/
public void setHeadless(boolean headless) {
this.headless = headless;
}
public boolean checkAndAdd(Spatial s) {
int rqMode = s.getRenderQueueMode();
if (rqMode != Renderer.QUEUE_SKIP) {
getQueue().addToQueue(s, rqMode);
return true;
}
return false;
}
public RenderQueue getQueue() {
return queue;
}
public boolean isProcessingQueue() {
return processingQueue;
}
/**
* Return true if the system running this supports VBO
*
* @return boolean true if VBO supported
*/
public boolean supportsVBO() {
return capabilities.OpenGL15;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
private void postdrawMesh() {
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
}
/**
* @param t
*/
private void predrawMesh(TriMesh t) {
// set world matrix
Quaternion rotation = t.getWorldRotation();
Vector3f translation = t.getWorldTranslation();
Vector3f scale = t.getWorldScale();
float rot = rotation.toAngleAxis(vRot);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPushMatrix();
GL11.glTranslatef(translation.x, translation.y, translation.z);
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
GL11.glScalef(scale.x, scale.y, scale.z);
if (!(scale.x == 1 && scale.y == 1 && scale.z == 1))
GL11.glEnable(GL11.GL_NORMALIZE); // since we are using
// glScalef, we should enable
// this to keep normals
// working.
prepVBO(t);
// render the object
FloatBuffer verticies = t.getVerticeAsFloatBuffer();
if (prevVerts != verticies) {
GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
if (t.isVBOVertexEnabled() && capabilities.GL_ARB_vertex_buffer_object) {
usingVBO = true;
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, t.getVBOVertexID());
GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
GL11.glVertexPointer(3, 0, t.getVerticeAsFloatBuffer());
}
}
prevVerts = verticies;
FloatBuffer normals = t.getNormalAsFloatBuffer();
if (prevNorms != normals) {
if (normals != null || t.getVBONormalID() > 0) {
GL11.glEnableClientState(GL11.GL_NORMAL_ARRAY);
if (t.isVBONormalEnabled()
&& capabilities.GL_ARB_vertex_buffer_object) {
usingVBO = true;
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, t.getVBONormalID());
GL11.glNormalPointer(GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
GL11.glNormalPointer(0, normals);
}
} else {
GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY);
}
}
prevNorms = normals;
FloatBuffer colors = t.getColorAsFloatBuffer();
if (colors == null || prevColor != colors) {
if (colors != null || t.getVBOColorID() > 0) {
GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
if (t.isVBOColorEnabled()
&& capabilities.GL_ARB_vertex_buffer_object) {
usingVBO = true;
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, t.getVBOColorID());
GL11.glColorPointer(4, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
GL11.glColorPointer(4, 0, colors);
}
prevColor = colors;
} else {
GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
}
}
for (int i = 0; i < t.getNumberOfUnits(); i++) {
FloatBuffer textures = t.getTextureAsFloatBuffer(i);
if (prevTex[i] != textures && textures != null) {
if (capabilities.GL_ARB_multitexture
&& capabilities.OpenGL13) {
GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
}
if (textures != null || t.getVBOTextureID(i) > 0) {
GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
if (t.isVBOTextureEnabled()
&& capabilities.GL_ARB_vertex_buffer_object) {
usingVBO = true;
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, t
.getVBOTextureID(i));
GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
} else {
if (usingVBO)
ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, 0);
GL11.glTexCoordPointer(2, 0, textures);
}
} else {
GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
prevTex[i] = textures;
}
}
/**
*
* <code>setBoundsStates</code> sets the rendering states for bounding
* volumes, this includes wireframe and zbuffer.
*
* @param enabled
* true if these states are to be enabled, false otherwise.
*/
private void setBoundsStates(boolean enabled) {
boundsTextState.apply(); // not enabled -- no texture
boundsWireState.setEnabled(enabled);
boundsWireState.apply();
boundsZState.setEnabled(enabled);
boundsZState.apply();
}
}
|
package com.intellij.ui.content;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.BusyObject;
import com.intellij.util.ContentsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
/**
* Obtain via {@link ContentFactory#createContentManager(ContentUI, boolean, com.intellij.openapi.project.Project)}.
*
* @see ContentsUtil
*/
public interface ContentManager extends Disposable, BusyObject {
boolean canCloseContents();
@NotNull
JComponent getComponent();
void addContent(@NotNull Content content);
void addContent(@NotNull Content content, int order);
boolean removeContent(@NotNull Content content, boolean dispose);
/**
* @param forcedFocus unused
*/
@NotNull
ActionCallback removeContent(@NotNull Content content, boolean dispose, boolean requestFocus, boolean forcedFocus);
void setSelectedContent(@NotNull Content content);
@NotNull
ActionCallback setSelectedContentCB(@NotNull Content content);
void setSelectedContent(@NotNull Content content, boolean requestFocus);
@NotNull
ActionCallback setSelectedContentCB(@NotNull Content content, boolean requestFocus);
/**
* @param forcedFocus unused
*/
void setSelectedContent(@NotNull Content content, boolean requestFocus, boolean forcedFocus);
/**
* @param forcedFocus unused
*/
@NotNull
ActionCallback setSelectedContentCB(@NotNull Content content, boolean requestFocus, boolean forcedFocus);
/**
* @param requestFocus whether content will request focus after selection
* @param forcedFocus unused
* @param implicit if {@code true} and content cannot be focused (e.g. it's minimized at the moment) {@link ActionCallback#REJECTED} will be returned
* @return resulting ActionCallback for both selection and focus transfer (if needed)
*/
@NotNull
ActionCallback setSelectedContent(@NotNull Content content, boolean requestFocus, boolean forcedFocus, boolean implicit);
void addSelectedContent(@NotNull Content content);
@Nullable
Content getSelectedContent();
@NotNull
Content[] getSelectedContents();
void removeAllContents(boolean dispose);
int getContentCount();
@NotNull
Content[] getContents();
//TODO[anton,vova] is this method needed?
Content findContent(String displayName);
@Nullable
Content getContent(int index);
Content getContent(@NotNull JComponent component);
int getIndexOfContent(@NotNull Content content);
@NotNull
String getCloseActionName();
boolean canCloseAllContents();
ActionCallback selectPreviousContent();
ActionCallback selectNextContent();
void addContentManagerListener(@NotNull ContentManagerListener listener);
void removeContentManagerListener(@NotNull ContentManagerListener listener);
/**
* Returns the localized name of the "Close All but This" action.
*/
@NotNull
String getCloseAllButThisActionName();
@NotNull
String getPreviousContentActionName();
@NotNull
String getNextContentActionName();
@NotNull
List<AnAction> getAdditionalPopupActions(@NotNull Content content);
void removeFromSelection(@NotNull Content content);
boolean isSelected(@NotNull Content content);
/**
* @param forced unused
*/
@NotNull
ActionCallback requestFocus(@Nullable Content content, boolean forced);
void addDataProvider(@NotNull DataProvider provider);
@NotNull
ContentFactory getFactory();
boolean isDisposed();
boolean isSingleSelection();
}
|
package com.atlassian.plugin.manager;
import static com.atlassian.plugin.util.Assertions.notNull;
import static com.atlassian.plugin.util.collect.CollectionUtil.filter;
import static com.atlassian.plugin.util.collect.CollectionUtil.toList;
import static com.atlassian.plugin.util.collect.CollectionUtil.transform;
import com.atlassian.plugin.ModuleCompleteKey;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.ModuleDescriptorFactory;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.PluginArtifact;
import com.atlassian.plugin.PluginController;
import com.atlassian.plugin.PluginException;
import com.atlassian.plugin.PluginInstaller;
import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.PluginRestartState;
import com.atlassian.plugin.PluginState;
import com.atlassian.plugin.PluginSystemLifecycle;
import com.atlassian.plugin.StateAware;
import com.atlassian.plugin.classloader.PluginsClassLoader;
import com.atlassian.plugin.descriptors.UnloadableModuleDescriptor;
import com.atlassian.plugin.descriptors.UnloadableModuleDescriptorFactory;
import com.atlassian.plugin.event.PluginEventListener;
import com.atlassian.plugin.event.PluginEventManager;
import com.atlassian.plugin.event.NotificationException;
import com.atlassian.plugin.event.events.PluginDisabledEvent;
import com.atlassian.plugin.event.events.PluginEnabledEvent;
import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent;
import com.atlassian.plugin.event.events.PluginFrameworkStartedEvent;
import com.atlassian.plugin.event.events.PluginFrameworkStartingEvent;
import com.atlassian.plugin.event.events.PluginFrameworkWarmRestartedEvent;
import com.atlassian.plugin.event.events.PluginFrameworkWarmRestartingEvent;
import com.atlassian.plugin.event.events.PluginModuleDisabledEvent;
import com.atlassian.plugin.event.events.PluginModuleEnabledEvent;
import com.atlassian.plugin.event.events.PluginRefreshedEvent;
import com.atlassian.plugin.event.events.PluginUpgradedEvent;
import com.atlassian.plugin.impl.UnloadablePlugin;
import com.atlassian.plugin.impl.UnloadablePluginFactory;
import com.atlassian.plugin.loaders.DynamicPluginLoader;
import com.atlassian.plugin.loaders.PluginLoader;
import com.atlassian.plugin.manager.PluginPersistentState.Builder;
import com.atlassian.plugin.parsers.DescriptorParserFactory;
import com.atlassian.plugin.predicate.EnabledModulePredicate;
import com.atlassian.plugin.predicate.EnabledPluginPredicate;
import com.atlassian.plugin.predicate.ModuleDescriptorOfClassPredicate;
import com.atlassian.plugin.predicate.ModuleDescriptorOfTypePredicate;
import com.atlassian.plugin.predicate.ModuleDescriptorPredicate;
import com.atlassian.plugin.predicate.ModuleOfClassPredicate;
import com.atlassian.plugin.predicate.PluginPredicate;
import com.atlassian.plugin.util.PluginUtils;
import com.atlassian.plugin.util.collect.CollectionUtil;
import com.atlassian.plugin.util.collect.Function;
import com.atlassian.plugin.util.collect.Predicate;
import com.atlassian.plugin.util.concurrent.CopyOnWriteMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.LinkedHashMap;
/**
* This implementation delegates the initiation and classloading of plugins to a
* list of {@link com.atlassian.plugin.loaders.PluginLoader}s and records the state of plugins in a {@link com.atlassian.plugin.manager.PluginPersistentStateStore}.
* <p/>
* This class is responsible for enabling and disabling plugins and plugin modules and reflecting these
* state changes in the PluginPersistentStateStore.
* <p/>
* An interesting quirk in the design is that {@link #installPlugin(com.atlassian.plugin.PluginArtifact)} explicitly stores
* the plugin via a {@link com.atlassian.plugin.PluginInstaller}, whereas {@link #uninstall(com.atlassian.plugin.Plugin)} relies on the
* underlying {@link com.atlassian.plugin.loaders.PluginLoader} to remove the plugin if necessary.
*/
public class DefaultPluginManager implements PluginController, PluginAccessor, PluginSystemLifecycle
{
private static final Logger log = LoggerFactory.getLogger(DefaultPluginManager.class);
private final List<PluginLoader> pluginLoaders;
private final PluginPersistentStateStore store;
private final ModuleDescriptorFactory moduleDescriptorFactory;
private final PluginEventManager pluginEventManager;
private final Map<String, Plugin> plugins = CopyOnWriteMap.newHashMap();
private final PluginsClassLoader classLoader = new PluginsClassLoader(this);
private final PluginEnabler pluginEnabler = new PluginEnabler(this, this);
private final StateTracker tracker = new StateTracker();
/**
* Installer used for storing plugins. Used by {@link #installPlugin(PluginArtifact)}.
*/
private PluginInstaller pluginInstaller;
/**
* Stores {@link Plugin}s as a key and {@link PluginLoader} as a value.
*/
private final Map<Plugin, PluginLoader> pluginToPluginLoader = new HashMap<Plugin, PluginLoader>();
public DefaultPluginManager(final PluginPersistentStateStore store, final List<PluginLoader> pluginLoaders, final ModuleDescriptorFactory moduleDescriptorFactory, final PluginEventManager pluginEventManager)
{
this.pluginLoaders = notNull("Plugin Loaders list must not be null.", pluginLoaders);
this.store = notNull("PluginPersistentStateStore must not be null.", store);
this.moduleDescriptorFactory = notNull("ModuleDescriptorFactory must not be null.", moduleDescriptorFactory);
this.pluginEventManager = notNull("PluginEventManager must not be null.", pluginEventManager);
this.pluginEventManager.register(this);
}
public void init() throws PluginParseException, NotificationException
{
tracker.setState(StateTracker.State.STARTING);
final StopWatch stopWatch = new StopWatch();
stopWatch.start();
log.info("Initialising the plugin system");
pluginEventManager.broadcast(new PluginFrameworkStartingEvent(this, this));
for (final PluginLoader loader : pluginLoaders)
{
if (loader == null)
{
continue;
}
final Collection<Plugin> possiblePluginsToLoad = loader.loadAllPlugins(moduleDescriptorFactory);
final Collection<Plugin> pluginsToLoad = new ArrayList<Plugin>();
for (final Plugin plugin : possiblePluginsToLoad)
{
if (getState().getPluginRestartState(plugin.getKey()) == PluginRestartState.REMOVE)
{
log.info("Plugin " + plugin.getKey() + " was marked to be removed on restart. Removing now.");
loader.removePlugin(plugin);
// PLUG-13: Plugins should not save state across uninstalls.
removeStateFromStore(getStore(), plugin);
}
else
{
pluginsToLoad.add(plugin);
}
}
addPlugins(loader, pluginsToLoad);
}
getStore().save(getBuilder().clearPluginRestartState().toState());
pluginEventManager.broadcast(new PluginFrameworkStartedEvent(this, this));
stopWatch.stop();
log.info("Plugin system started in " + stopWatch);
tracker.setState(StateTracker.State.STARTED);
}
public void shutdown()
{
tracker.setState(StateTracker.State.SHUTTING_DOWN);
log.info("Shutting down the plugin system");
try
{
pluginEventManager.broadcast(new PluginFrameworkShutdownEvent(this, this));
}
catch (NotificationException ex)
{
log.error("At least one error occured while broadcasting the PluginFrameworkShutdownEvent. We will continue to shutdown the Plugin Manager anyway.");
}
plugins.clear();
pluginEventManager.unregister(this);
tracker.setState(StateTracker.State.SHUTDOWN);
}
public final void warmRestart()
{
tracker.setState(StateTracker.State.WARM_RESTARTING);
log.info("Initiating a warm restart of the plugin system");
pluginEventManager.broadcast(new PluginFrameworkWarmRestartingEvent(this, this));
// Make sure we reload plugins in order
final List<Plugin> restartedPlugins = new ArrayList<Plugin>();
final List<PluginLoader> loaders = new ArrayList<PluginLoader>(pluginLoaders);
Collections.reverse(loaders);
for (final PluginLoader loader : pluginLoaders)
{
for (final Map.Entry<Plugin, PluginLoader> entry : pluginToPluginLoader.entrySet())
{
if (entry.getValue() == loader)
{
final Plugin plugin = entry.getKey();
if (isPluginEnabled(plugin.getKey()))
{
disablePluginModules(plugin);
restartedPlugins.add(plugin);
}
}
}
}
//then enable them in reverse order
Collections.reverse(restartedPlugins);
for (final Plugin plugin : restartedPlugins)
{
enablePluginModules(plugin);
}
classLoader.notifyPluginOrModuleEnabled();
pluginEventManager.broadcast(new PluginFrameworkWarmRestartedEvent(this, this));
tracker.setState(StateTracker.State.STARTED);
}
@PluginEventListener
public void onPluginRefresh(final PluginRefreshedEvent event)
{
final Plugin plugin = event.getPlugin();
disablePluginModules(plugin);
// enable the plugin, shamefully copied from notifyPluginEnabled()
classLoader.notifyPluginOrModuleEnabled();
if (enablePluginModules(plugin))
{
pluginEventManager.broadcast(new PluginEnabledEvent(plugin));
}
}
/**
* Set the plugin installation strategy for this manager
*
* @param pluginInstaller the plugin installation strategy to use
* @see PluginInstaller
*/
public void setPluginInstaller(final PluginInstaller pluginInstaller)
{
this.pluginInstaller = pluginInstaller;
}
protected final PluginPersistentStateStore getStore()
{
return store;
}
public String installPlugin(final PluginArtifact pluginArtifact) throws PluginParseException
{
Set<String> keys = installPlugins(pluginArtifact);
if (keys != null && keys.size() == 1)
{
return keys.iterator().next();
}
else
{
// should never happen
throw new PluginParseException("Could not install plugin");
}
}
public Set<String> installPlugins(final PluginArtifact... pluginArtifacts) throws PluginParseException
{
LinkedHashMap<String,PluginArtifact> validatedArtifacts = new LinkedHashMap<String,PluginArtifact>();
try
{
for (PluginArtifact pluginArtifact : pluginArtifacts)
{
validatedArtifacts.put(validatePlugin(pluginArtifact), pluginArtifact);
}
}
catch (PluginParseException ex)
{
throw new PluginParseException("All plugins could not be validated", ex);
}
for (Map.Entry<String,PluginArtifact> entry : validatedArtifacts.entrySet())
{
pluginInstaller.installPlugin(entry.getKey(), entry.getValue());
}
scanForNewPlugins();
return validatedArtifacts.keySet();
}
/**
* Validate a plugin jar. Looks through all plugin loaders for ones that can load the plugin and
* extract the plugin key as proof.
*
* @param pluginArtifact the jar file representing the plugin
* @return The plugin key
* @throws PluginParseException if the plugin cannot be parsed
* @throws NullPointerException if <code>pluginJar</code> is null.
*/
String validatePlugin(final PluginArtifact pluginArtifact) throws PluginParseException
{
boolean foundADynamicPluginLoader = false;
for (final PluginLoader loader : pluginLoaders)
{
if (loader instanceof DynamicPluginLoader)
{
foundADynamicPluginLoader = true;
final String key = ((DynamicPluginLoader) loader).canLoad(pluginArtifact);
if (key != null)
{
return key;
}
}
}
if (!foundADynamicPluginLoader)
{
throw new IllegalStateException("Should be at least one DynamicPluginLoader in the plugin loader list");
}
throw new PluginParseException("Jar " + pluginArtifact.getName() + " is not a valid plugin");
}
public int scanForNewPlugins() throws PluginParseException
{
int numberFound = 0;
for (final PluginLoader loader : pluginLoaders)
{
if (loader != null)
{
if (loader.supportsAddition())
{
final List<Plugin> pluginsToAdd = new ArrayList<Plugin>();
for (Plugin plugin : loader.addFoundPlugins(moduleDescriptorFactory))
{
final Plugin oldPlugin = plugins.get(plugin.getKey());
// Only actually install the plugin if its module descriptors support it. Otherwise, mark it as
// unloadable.
if (!(plugin instanceof UnloadablePlugin))
{
if (PluginUtils.doesPluginRequireRestart(plugin))
{
if (oldPlugin == null)
{
getStore().save(getBuilder().setPluginRestartState(plugin.getKey(), PluginRestartState.INSTALL).toState());
final UnloadablePlugin unloadablePlugin = new UnloadablePlugin("Plugin requires a restart of the application");
unloadablePlugin.setKey(plugin.getKey());
plugin = unloadablePlugin;
}
else
{
getStore().save(getBuilder().setPluginRestartState(plugin.getKey(), PluginRestartState.UPGRADE).toState());
continue;
}
}
// Check to ensure that the old plugin didn't require restart, even if the new one doesn't
else if ((oldPlugin != null) && PluginUtils.doesPluginRequireRestart(oldPlugin))
{
getStore().save(getBuilder().setPluginRestartState(plugin.getKey(), PluginRestartState.UPGRADE).toState());
continue;
}
pluginsToAdd.add(plugin);
}
}
addPlugins(loader, pluginsToAdd);
numberFound = pluginsToAdd.size();
}
}
}
return numberFound;
}
/**
*
* @param plugin
* @throws PluginException If the plugin or loader doesn't support uninstallation
*/
public void uninstall(final Plugin plugin) throws PluginException
{
if (PluginUtils.doesPluginRequireRestart(plugin))
{
ensurePluginAndLoaderSupportsUninstall(plugin);
getStore().save(getBuilder().setPluginRestartState(plugin.getKey(), PluginRestartState.REMOVE).toState());
}
else
{
unloadPlugin(plugin);
// PLUG-13: Plugins should not save state across uninstalls.
removeStateFromStore(getStore(), plugin);
}
}
protected void removeStateFromStore(final PluginPersistentStateStore stateStore, final Plugin plugin)
{
final PluginPersistentState.Builder builder = PluginPersistentState.Builder.create(stateStore.load()).removeState(plugin.getKey());
for (final ModuleDescriptor<?> moduleDescriptor : plugin.getModuleDescriptors())
{
builder.removeState(moduleDescriptor.getCompleteKey());
}
stateStore.save(builder.toState());
}
/**
* Unload a plugin. Called when plugins are added locally,
* or remotely in a clustered application.
*
* @param plugin the plugin to remove
* @throws PluginException if th eplugin cannot be uninstalled
*/
protected void unloadPlugin(final Plugin plugin) throws PluginException
{
final PluginLoader loader = ensurePluginAndLoaderSupportsUninstall(plugin);
if (isPluginEnabled(plugin.getKey()))
{
notifyPluginDisabled(plugin);
}
notifyUninstallPlugin(plugin);
if (loader != null)
{
removePluginFromLoader(plugin);
}
plugins.remove(plugin.getKey());
}
private PluginLoader ensurePluginAndLoaderSupportsUninstall(final Plugin plugin)
{
if (!plugin.isUninstallable())
{
throw new PluginException("Plugin is not uninstallable: " + plugin.getKey());
}
final PluginLoader loader = pluginToPluginLoader.get(plugin);
if ((loader != null) && !loader.supportsRemoval())
{
throw new PluginException("Not uninstalling plugin - loader doesn't allow removal. Plugin: " + plugin.getKey());
}
return loader;
}
private void removePluginFromLoader(final Plugin plugin) throws PluginException
{
if (plugin.isDeleteable())
{
final PluginLoader pluginLoader = pluginToPluginLoader.get(plugin);
pluginLoader.removePlugin(plugin);
}
pluginToPluginLoader.remove(plugin);
}
protected void notifyUninstallPlugin(final Plugin plugin)
{
classLoader.notifyUninstallPlugin(plugin);
for (final ModuleDescriptor<?> descriptor : plugin.getModuleDescriptors())
{
descriptor.destroy(plugin);
}
}
protected PluginPersistentState getState()
{
return getStore().load();
}
/**
* @deprecated Since 2.0.2, use {@link #addPlugins(PluginLoader,Collection<Plugin>...)} instead
*/
@Deprecated
protected void addPlugin(final PluginLoader loader, final Plugin plugin) throws PluginParseException
{
addPlugins(loader, Collections.singletonList(plugin));
}
/**
* Update the local plugin state and enable state aware modules.
* <p>
* If there is an existing plugin with the same key, the version strings of the existing plugin and the plugin
* provided to this method will be parsed and compared. If the installed version is newer than the provided
* version, it will not be changed. If the specified plugin's version is the same or newer, the existing plugin
* state will be saved and the plugin will be unloaded before the provided plugin is installed. If the existing
* plugin cannot be unloaded a {@link PluginException} will be thrown.
*
* @param loader the loader used to load this plugin
* @param pluginsToInstall the plugins to add
* @throws PluginParseException if the plugin cannot be parsed
* @since 2.0.2
*/
protected void addPlugins(final PluginLoader loader, final Collection<Plugin> pluginsToInstall) throws PluginParseException
{
final Set<Plugin> pluginsToEnable = new HashSet<Plugin>();
// Install plugins, looking for upgrades and duplicates
for (final Plugin plugin : new TreeSet<Plugin>(pluginsToInstall))
{
boolean pluginUpgraded = false;
// testing to make sure plugin keys are unique
if (plugins.containsKey(plugin.getKey()))
{
final Plugin existingPlugin = plugins.get(plugin.getKey());
if (plugin.compareTo(existingPlugin) >= 0)
{
try
{
updatePlugin(existingPlugin, plugin);
pluginsToEnable.remove(existingPlugin);
pluginUpgraded = true;
}
catch (final PluginException e)
{
throw new PluginParseException(
"Duplicate plugin found (installed version is the same or older) and could not be unloaded: '" + plugin.getKey() + "'", e);
}
}
else
{
// If we find an older plugin, don't error, just ignore it. PLUG-12.
if (log.isDebugEnabled())
{
log.debug("Duplicate plugin found (installed version is newer): '" + plugin.getKey() + "'");
}
// and don't install the older plugin
continue;
}
}
plugin.install();
boolean isPluginEnabled = getState().isEnabled(plugin);
if (isPluginEnabled)
{
pluginsToEnable.add(plugin);
}
if (plugin.isSystemPlugin() && !isPluginEnabled)
{
log.warn("System plugin is disabled: " + plugin.getKey());
}
if (pluginUpgraded)
{
pluginEventManager.broadcast(new PluginUpgradedEvent(plugin));
}
plugins.put(plugin.getKey(), plugin);
pluginToPluginLoader.put(plugin, loader);
}
// enable all plugins, waiting a time period for them to enable
pluginEnabler.enable(pluginsToEnable);
// handle the plugins that were able to be successfully enabled
for (final Plugin plugin : pluginsToInstall)
{
if (plugin.getPluginState() == PluginState.ENABLED)
{
// This method enables the plugin modules
if (enablePluginModules(plugin))
{
pluginEventManager.broadcast(new PluginEnabledEvent(plugin));
}
}
}
}
/**
* Replace an already loaded plugin with another version. Relevant stored configuration for the plugin will be
* preserved.
*
* @param oldPlugin Plugin to replace
* @param newPlugin New plugin to install
* @throws PluginException if the plugin cannot be updated
*/
protected void updatePlugin(final Plugin oldPlugin, final Plugin newPlugin) throws PluginException
{
if (!oldPlugin.getKey().equals(newPlugin.getKey()))
{
throw new IllegalArgumentException("New plugin must have the same key as the old plugin");
}
if (log.isInfoEnabled())
{
log.info("Updating plugin '" + oldPlugin + "' to '" + newPlugin + "'");
}
// Preserve the old plugin configuration - uninstall changes it (as disable is called on all modules) and then
// removes it
final Map<String, Boolean> oldPluginState = new HashMap<String, Boolean>(getState().getPluginStateMap(oldPlugin));
if (log.isDebugEnabled())
{
log.debug("Uninstalling old plugin: " + oldPlugin);
}
uninstall(oldPlugin);
if (log.isDebugEnabled())
{
log.debug("Plugin uninstalled '" + oldPlugin + "', preserving old state");
}
// Build a set of module keys from the new plugin version
final Set<String> newModuleKeys = new HashSet<String>();
newModuleKeys.add(newPlugin.getKey());
for (final ModuleDescriptor<?> moduleDescriptor : newPlugin.getModuleDescriptors())
{
newModuleKeys.add(moduleDescriptor.getCompleteKey());
}
// Remove any keys from the old plugin state that do not exist in the new version
CollectionUtils.filter(oldPluginState.keySet(), new org.apache.commons.collections.Predicate()
{
public boolean evaluate(final Object o)
{
return newModuleKeys.contains(o);
}
});
getStore().save(getBuilder().addState(oldPluginState).toState());
}
public Collection<Plugin> getPlugins()
{
return plugins.values();
}
/**
* @see PluginAccessor#getPlugins(com.atlassian.plugin.predicate.PluginPredicate)
* @since 0.17
*/
public Collection<Plugin> getPlugins(final PluginPredicate pluginPredicate)
{
return toList(filter(getPlugins(), new Predicate<Plugin>()
{
public boolean evaluate(final Plugin plugin)
{
return pluginPredicate.matches(plugin);
}
}));
}
/**
* @see PluginAccessor#getEnabledPlugins()
*/
public Collection<Plugin> getEnabledPlugins()
{
return getPlugins(new EnabledPluginPredicate(this));
}
/**
* @see PluginAccessor#getModules(com.atlassian.plugin.predicate.ModuleDescriptorPredicate)
* @since 0.17
*/
public <M> Collection<M> getModules(final ModuleDescriptorPredicate<M> moduleDescriptorPredicate)
{
final Collection<ModuleDescriptor<M>> moduleDescriptors = getModuleDescriptors(moduleDescriptorPredicate);
return getModules(moduleDescriptors);
}
/**
* @see PluginAccessor#getModuleDescriptors(com.atlassian.plugin.predicate.ModuleDescriptorPredicate)
* @since 0.17
*/
public <M> Collection<ModuleDescriptor<M>> getModuleDescriptors(final ModuleDescriptorPredicate<M> moduleDescriptorPredicate)
{
final List<ModuleDescriptor<M>> moduleDescriptors = getModuleDescriptorsList(getPlugins());
return toList(filter(moduleDescriptors, new Predicate<ModuleDescriptor<M>>()
{
public boolean evaluate(final ModuleDescriptor<M> input)
{
return moduleDescriptorPredicate.matches(input);
}
}));
}
/**
* Get the all the module descriptors from the given collection of plugins.
* <p>
* Be careful, this does not actually return a list of ModuleDescriptors that are M, it returns all
* ModuleDescriptors of all types, you must further filter the list as required.
*
* @param plugins a collection of {@link Plugin}s
* @return a collection of {@link ModuleDescriptor}s
*/
private <M> List<ModuleDescriptor<M>> getModuleDescriptorsList(final Collection<Plugin> plugins)
{
// hack way to get typed descriptors from plugin and keep generics happy
final List<ModuleDescriptor<M>> moduleDescriptors = new LinkedList<ModuleDescriptor<M>>();
for (final Plugin plugin : plugins)
{
final Collection<ModuleDescriptor<?>> descriptors = plugin.getModuleDescriptors();
for (final ModuleDescriptor<?> moduleDescriptor : descriptors)
{
@SuppressWarnings("unchecked")
final ModuleDescriptor<M> typedDescriptor = (ModuleDescriptor<M>) moduleDescriptor;
moduleDescriptors.add(typedDescriptor);
}
}
return moduleDescriptors;
}
/**
* Get the modules of all the given descriptor. If any of the getModule() calls fails, the error is recorded in
* the logs and the plugin is disabled.
*
* @param moduleDescriptors the collection of module descriptors to get the modules from.
* @return a {@link Collection} modules that can be any type of object.
* This collection will not contain any null value.
*/
private <M> List<M> getModules(final Iterable<ModuleDescriptor<M>> moduleDescriptors)
{
final Set<String> pluginsToDisable = new HashSet<String>();
final List<M> modules = transform(moduleDescriptors, new Function<ModuleDescriptor<M>, M>()
{
public M get(final ModuleDescriptor<M> input)
{
M result = null;
try
{
result = input.getModule();
}
catch (final RuntimeException ex)
{
log.error("Exception when retrieving plugin module " + input.getKey() + ", will disable plugin " + input.getPlugin().getKey(), ex);
pluginsToDisable.add(input.getPlugin().getKey());
}
return result;
}
});
for (final String badPluginKey : pluginsToDisable)
{
disablePlugin(badPluginKey);
}
return modules;
}
public Plugin getPlugin(final String key)
{
Validate.notNull(key, "The plugin key must be specified");
return plugins.get(key);
}
public Plugin getEnabledPlugin(final String pluginKey)
{
if (!isPluginEnabled(pluginKey))
{
return null;
}
return getPlugin(pluginKey);
}
public ModuleDescriptor<?> getPluginModule(final String completeKey)
{
return getPluginModule(new ModuleCompleteKey(completeKey));
}
private ModuleDescriptor<?> getPluginModule(final ModuleCompleteKey key)
{
final Plugin plugin = getPlugin(key.getPluginKey());
if (plugin == null)
{
return null;
}
return plugin.getModuleDescriptor(key.getModuleKey());
}
public ModuleDescriptor<?> getEnabledPluginModule(final String completeKey)
{
final ModuleCompleteKey key = new ModuleCompleteKey(completeKey);
// If it's disabled, return null
if (!isPluginModuleEnabled(key))
{
return null;
}
return getEnabledPlugin(key.getPluginKey()).getModuleDescriptor(key.getModuleKey());
}
/**
* @see PluginAccessor#getEnabledModulesByClass(Class)
*/
public <M> List<M> getEnabledModulesByClass(final Class<M> moduleClass)
{
return getModules(getEnabledModuleDescriptorsByModuleClass(moduleClass));
}
/**
* @see PluginAccessor#getEnabledModulesByClassAndDescriptor(Class[], Class)
* @deprecated since 0.17, use {@link #getModules(com.atlassian.plugin.predicate.ModuleDescriptorPredicate)} with an appropriate predicate instead.
*/
@Deprecated
public <M> List<M> getEnabledModulesByClassAndDescriptor(final Class<ModuleDescriptor<M>>[] descriptorClasses, final Class<M> moduleClass)
{
final Iterable<ModuleDescriptor<M>> moduleDescriptors = filterModuleDescriptors(getEnabledModuleDescriptorsByModuleClass(moduleClass),
new ModuleDescriptorOfClassPredicate<M>(descriptorClasses));
return getModules(moduleDescriptors);
}
/**
* @see PluginAccessor#getEnabledModulesByClassAndDescriptor(Class, Class)
* @deprecated since 0.17, use {@link #getModules(com.atlassian.plugin.predicate.ModuleDescriptorPredicate)} with an appropriate predicate instead.
*/
@Deprecated
public <M> List<M> getEnabledModulesByClassAndDescriptor(final Class<ModuleDescriptor<M>> descriptorClass, final Class<M> moduleClass)
{
final Iterable<ModuleDescriptor<M>> moduleDescriptors = getEnabledModuleDescriptorsByModuleClass(moduleClass);
return getModules(filterModuleDescriptors(moduleDescriptors, new ModuleDescriptorOfClassPredicate<M>(descriptorClass)));
}
/**
* Get all module descriptor that are enabled and for which the module is an instance of the given class.
*
* @param moduleClass the class of the module within the module descriptor.
* @return a collection of {@link ModuleDescriptor}s
*/
private <M> Collection<ModuleDescriptor<M>> getEnabledModuleDescriptorsByModuleClass(final Class<M> moduleClass)
{
Iterable<ModuleDescriptor<M>> moduleDescriptors = getModuleDescriptorsList(getEnabledPlugins());
moduleDescriptors = filterModuleDescriptors(moduleDescriptors, new ModuleOfClassPredicate<M>(moduleClass));
moduleDescriptors = filterModuleDescriptors(moduleDescriptors, new EnabledModulePredicate<M>(this));
return toList(moduleDescriptors);
}
/**
* This method has been reverted to pre PLUG-40 to fix performance issues that were encountered during
* load testing. This should be reverted to the state it was in at 54639 when the fundamental issue leading
* to this slowdown has been corrected (that is, slowness of PluginClassLoader).
*
* @see PluginAccessor#getEnabledModuleDescriptorsByClass(Class)
*/
public <D extends ModuleDescriptor<?>> List<D> getEnabledModuleDescriptorsByClass(final Class<D> descriptorClazz)
{
final List<D> result = new LinkedList<D>();
for (final Plugin plugin : plugins.values())
{
// Skip disabled plugins
if (!isPluginEnabled(plugin.getKey()))
{
if (log.isDebugEnabled())
{
log.debug("Plugin [" + plugin.getKey() + "] is disabled.");
}
continue;
}
for (final ModuleDescriptor<?> module : plugin.getModuleDescriptors())
{
if (descriptorClazz.isInstance(module))
{
if (isPluginModuleEnabled(module.getCompleteKey()))
{
@SuppressWarnings("unchecked")
final D moduleDescriptor = (D) module;
result.add(moduleDescriptor);
}
else if (log.isDebugEnabled())
{
log.debug("Module [" + module.getCompleteKey() + "] is disabled.");
}
}
}
}
return result;
}
public <D extends ModuleDescriptor<?>> List<D> getEnabledModuleDescriptorsByClass(final Class<D> descriptorClazz, final boolean verbose)
{
return getEnabledModuleDescriptorsByClass(descriptorClazz);
}
/**
* @see PluginAccessor#getEnabledModuleDescriptorsByType(String)
* @deprecated since 0.17, use {@link #getModuleDescriptors(com.atlassian.plugin.predicate.ModuleDescriptorPredicate)} with an appropriate predicate instead.
*/
@Deprecated
public <M> List<ModuleDescriptor<M>> getEnabledModuleDescriptorsByType(final String type) throws PluginParseException, IllegalArgumentException
{
Iterable<ModuleDescriptor<M>> moduleDescriptors = getModuleDescriptorsList(getEnabledPlugins());
moduleDescriptors = filterModuleDescriptors(moduleDescriptors, new ModuleDescriptorOfTypePredicate<M>(moduleDescriptorFactory, type));
moduleDescriptors = filterModuleDescriptors(moduleDescriptors, new EnabledModulePredicate<M>(this));
return toList(moduleDescriptors);
}
/**
* Filters out a collection of {@link ModuleDescriptor}s given a predicate.
*
* @param moduleDescriptors the collection of {@link ModuleDescriptor}s to filter.
* @param moduleDescriptorPredicate the predicate to use for filtering.
*/
private static <M> Iterable<ModuleDescriptor<M>> filterModuleDescriptors(final Iterable<ModuleDescriptor<M>> moduleDescriptors, final ModuleDescriptorPredicate<M> moduleDescriptorPredicate)
{
return CollectionUtil.filter(moduleDescriptors, new Predicate<ModuleDescriptor<M>>()
{
public boolean evaluate(final ModuleDescriptor<M> input)
{
return moduleDescriptorPredicate.matches(input);
}
});
}
public void enablePlugin(final String key)
{
if (key == null)
{
throw new IllegalArgumentException("You must specify a plugin key to disable.");
}
if (!plugins.containsKey(key))
{
if (log.isInfoEnabled())
{
log.info("No plugin was found for key '" + key + "'. Not enabling.");
}
return;
}
final Plugin plugin = plugins.get(key);
if (!plugin.getPluginInformation().satisfiesMinJavaVersion())
{
log.error("Minimum Java version of '" + plugin.getPluginInformation().getMinJavaVersion() + "' was not satisfied for module '" + key + "'. Not enabling.");
return;
}
pluginEnabler.enableRecursively(plugin);
if (plugin.getPluginState().equals(PluginState.ENABLED))
{
enablePluginState(plugin, getStore());
notifyPluginEnabled(plugin);
}
}
protected void enablePluginState(final Plugin plugin, final PluginPersistentStateStore stateStore)
{
stateStore.save(getBuilder().setEnabled(plugin, true).toState());
}
/**
* Called on all clustered application nodes, rather than {@link #enablePlugin(String)}
* to just update the local state, state aware modules and loaders, but not affect the
* global plugin state.
*
* @param plugin the plugin being enabled
*/
protected void notifyPluginEnabled(final Plugin plugin)
{
plugin.enable();
classLoader.notifyPluginOrModuleEnabled();
if (enablePluginModules(plugin))
{
pluginEventManager.broadcast(new PluginEnabledEvent(plugin));
}
}
/**
* For each module in the plugin, call the module descriptor's enabled() method if the module is StateAware and enabled.
*
* <p> If any modules fail to enable then the plugin is replaced by an UnloadablePlugin, and this method will return {@code false}.
*
* @param plugin the plugin to enable
* @return true if the modules were all enabled correctly, false otherwise.
*/
private boolean enablePluginModules(final Plugin plugin)
{
boolean success = true;
Set<ModuleDescriptor<?>> enabledDescriptors = new HashSet<ModuleDescriptor<?>>();
for (final ModuleDescriptor<?> descriptor : plugin.getModuleDescriptors())
{
// We only want to re-enable modules that weren't explicitly disabled by the user.
if (!isPluginModuleEnabled(descriptor.getCompleteKey()))
{
if(plugin.isSystemPlugin())
{
log.warn("System plugin module disabled: " + descriptor.getCompleteKey());
}
else if (log.isDebugEnabled())
{
log.debug("Plugin module '" + descriptor.getName() + "' is explicitly disabled, so not re-enabling.");
}
continue;
}
try
{
notifyModuleEnabled(descriptor);
enabledDescriptors.add(descriptor);
}
catch (final Throwable exception) // catch any errors and insert an UnloadablePlugin (PLUG-7)
{
log.error("There was an error loading the descriptor '" + descriptor.getName() + "' of plugin '" + plugin.getKey() + "'. Disabling.",
exception);
// Disable all previously enabled descriptors
for (ModuleDescriptor<?> desc : enabledDescriptors)
{
notifyModuleDisabled(desc);
}
replacePluginWithUnloadablePlugin(plugin, descriptor, exception);
success = false;
}
}
// TODO: Do we need to call this on success = false?
classLoader.notifyPluginOrModuleEnabled();
return success;
}
public void disablePlugin(final String key)
{
disablePluginInternal(key, true);
}
public void disablePluginWithoutPersisting(final String key)
{
disablePluginInternal(key, false);
}
protected void disablePluginInternal(final String key, final boolean persistDisabledState)
{
if (key == null)
{
throw new IllegalArgumentException("You must specify a plugin key to disable.");
}
if (!plugins.containsKey(key))
{
if (log.isInfoEnabled())
{
log.info("No plugin was found for key '" + key + "'. Not disabling.");
}
return;
}
final Plugin plugin = plugins.get(key);
notifyPluginDisabled(plugin);
if (persistDisabledState)
{
disablePluginState(plugin, getStore());
}
}
protected void disablePluginState(final Plugin plugin, final PluginPersistentStateStore stateStore)
{
stateStore.save(getBuilder().setEnabled(plugin, false).toState());
}
protected void notifyPluginDisabled(final Plugin plugin)
{
log.info("Disabling " + plugin.getKey());
disablePluginModules(plugin);
// This needs to happen after modules are disabled to prevent errors
plugin.disable();
pluginEventManager.broadcast(new PluginDisabledEvent(plugin));
}
private void disablePluginModules(Plugin plugin)
{
final List<ModuleDescriptor<?>> moduleDescriptors = new ArrayList<ModuleDescriptor<?>>(plugin.getModuleDescriptors());
Collections.reverse(moduleDescriptors); // disable in reverse order
for (final ModuleDescriptor<?> module : moduleDescriptors)
{
// don't actually disable the module, just fire the events because its plugin is being disabled
// if the module was actually disabled, you'd have to reenable each one when enabling the plugin
if (isPluginModuleEnabled(module.getCompleteKey()))
{
publishModuleDisabledEvents(module);
}
}
}
public void disablePluginModule(final String completeKey)
{
if (completeKey == null)
{
throw new IllegalArgumentException("You must specify a plugin module key to disable.");
}
final ModuleDescriptor<?> module = getPluginModule(completeKey);
if (module == null)
{
if (log.isInfoEnabled())
{
log.info("Returned module for key '" + completeKey + "' was null. Not disabling.");
}
return;
}
disablePluginModuleState(module, getStore());
notifyModuleDisabled(module);
}
protected void disablePluginModuleState(final ModuleDescriptor<?> module, final PluginPersistentStateStore stateStore)
{
stateStore.save(getBuilder().setEnabled(module, false).toState());
}
protected void notifyModuleDisabled(final ModuleDescriptor<?> module)
{
publishModuleDisabledEvents(module);
}
private void publishModuleDisabledEvents(final ModuleDescriptor<?> module)
{
if (log.isDebugEnabled())
{
log.debug("Disabling " + module.getKey());
}
if (module instanceof StateAware)
{
((StateAware) module).disabled();
}
pluginEventManager.broadcast(new PluginModuleDisabledEvent(module));
}
public void enablePluginModule(final String completeKey)
{
if (completeKey == null)
{
throw new IllegalArgumentException("You must specify a plugin module key to disable.");
}
final ModuleDescriptor<?> module = getPluginModule(completeKey);
if (module == null)
{
if (log.isInfoEnabled())
{
log.info("Returned module for key '" + completeKey + "' was null. Not enabling.");
}
return;
}
if (!module.satisfiesMinJavaVersion())
{
log.error("Minimum Java version of '" + module.getMinJavaVersion() + "' was not satisfied for module '" + completeKey + "'. Not enabling.");
return;
}
enablePluginModuleState(module, getStore());
notifyModuleEnabled(module);
}
protected void enablePluginModuleState(final ModuleDescriptor<?> module, final PluginPersistentStateStore stateStore)
{
stateStore.save(getBuilder().setEnabled(module, true).toState());
}
protected void notifyModuleEnabled(final ModuleDescriptor<?> module)
{
if (log.isDebugEnabled())
{
log.debug("Enabling " + module.getKey());
}
classLoader.notifyPluginOrModuleEnabled();
if (module instanceof StateAware)
{
((StateAware) module).enabled();
}
pluginEventManager.broadcast(new PluginModuleEnabledEvent(module));
}
public boolean isPluginModuleEnabled(final String completeKey)
{
// completeKey may be null
return (completeKey == null) ? false : isPluginModuleEnabled(new ModuleCompleteKey(completeKey));
}
private boolean isPluginModuleEnabled(final ModuleCompleteKey key)
{
if (!isPluginEnabled(key.getPluginKey()))
{
return false;
}
final ModuleDescriptor<?> pluginModule = getPluginModule(key);
return (pluginModule != null) && getState().isEnabled(pluginModule);
}
/**
* This method checks to see if the plugin is enabled based on the state manager and the plugin.
*
* @param key The plugin key
* @return True if the plugin is enabled
*/
public boolean isPluginEnabled(final String key)
{
Validate.notNull(key, "The plugin key must be specified");
final Plugin plugin = plugins.get(key);
return (plugin != null) && ((plugin.getPluginState() == PluginState.ENABLED) && getState().isEnabled(plugin));
}
public InputStream getDynamicResourceAsStream(final String name)
{
return getClassLoader().getResourceAsStream(name);
}
public Class<?> getDynamicPluginClass(final String className) throws ClassNotFoundException
{
return getClassLoader().loadClass(className);
}
public PluginsClassLoader getClassLoader()
{
return classLoader;
}
public InputStream getPluginResourceAsStream(final String pluginKey, final String resourcePath)
{
final Plugin plugin = getEnabledPlugin(pluginKey);
if (plugin == null)
{
log.error("Attempted to retreive resource " + resourcePath + " for non-existent or inactive plugin " + pluginKey);
return null;
}
return plugin.getResourceAsStream(resourcePath);
}
/**
* Disables and replaces a plugin currently loaded with an UnloadablePlugin.
*
* @param plugin the plugin to be replaced
* @param descriptor the descriptor which caused the problem
* @param throwable the problem caught when enabling the descriptor
* @return the UnloadablePlugin which replaced the broken plugin
*/
private UnloadablePlugin replacePluginWithUnloadablePlugin(final Plugin plugin, final ModuleDescriptor<?> descriptor, final Throwable throwable)
{
final UnloadableModuleDescriptor unloadableDescriptor = UnloadableModuleDescriptorFactory.createUnloadableModuleDescriptor(plugin,
descriptor, throwable);
final UnloadablePlugin unloadablePlugin = UnloadablePluginFactory.createUnloadablePlugin(plugin, unloadableDescriptor);
unloadablePlugin.setUninstallable(plugin.isUninstallable());
unloadablePlugin.setDeletable(plugin.isDeleteable());
// Add the error text at the plugin level as well. This is useful for logging.
unloadablePlugin.setErrorText(unloadableDescriptor.getErrorText());
plugins.put(plugin.getKey(), unloadablePlugin);
// PLUG-390: We used to persist the disabled state here, but we don't want to do this.
// We want to try load this plugin again on restart as the user may have installed a fixed version of this plugin.
return unloadablePlugin;
}
public boolean isSystemPlugin(final String key)
{
final Plugin plugin = getPlugin(key);
return (plugin != null) && plugin.isSystemPlugin();
}
public PluginRestartState getPluginRestartState(final String key)
{
return getState().getPluginRestartState(key);
}
private Builder getBuilder()
{
return PluginPersistentState.Builder.create(getStore().load());
}
/**
* @deprecated Since 2.0.0.beta2
*/
@Deprecated
public void setDescriptorParserFactory(final DescriptorParserFactory descriptorParserFactory)
{}
}
|
package org.xbill.DNS.utils;
import java.io.*;
import java.math.BigInteger;
/**
* An extension of ByteArrayInputStream to support directly reading types
* used by DNS routines.
* @see DataByteOutputStream
*
* @author Brian Wellington
*/
public class DataByteInputStream extends ByteArrayInputStream {
/**
* Creates a new DataByteInputStream
* @param b The byte array to read from
*/
public
DataByteInputStream(byte [] b) {
super(b);
}
/**
* Read data from the stream.
* @param b The array to read into
* @return The number of bytes read
*/
public int
read(byte b[]) throws IOException {
int n = read(b, 0, b.length);
if (n < b.length)
throw new IOException("end of input");
return n;
}
/**
* Read a byte from the stream
* @return The byte
*/
public byte
readByte() throws IOException {
int i = read();
if (i == -1)
throw new IOException("end of input");
return (byte) i;
}
/**
* Read an unsigned byte from the stream
* @return The unsigned byte as an int
*/
public int
readUnsignedByte() throws IOException {
int i = read();
if (i == -1)
throw new IOException("end of input");
return i;
}
/**
* Read a short from the stream
* @return The short
*/
public short
readShort() throws IOException {
int c1 = read();
int c2 = read();
if (c1 == -1 || c2 == -1)
throw new IOException("end of input");
return (short)((c1 << 8) + c2);
}
/**
* Read an unsigned short from the stream
* @return The unsigned short as an int
*/
public int
readUnsignedShort() throws IOException {
int c1 = read();
int c2 = read();
if (c1 == -1 || c2 == -1)
throw new IOException("end of input");
return ((c1 << 8) + c2);
}
/**
* Read an int from the stream
* @return The int
*/
public int
readInt() throws IOException {
int c1 = read();
int c2 = read();
int c3 = read();
int c4 = read();
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1)
throw new IOException("end of input");
return ((c1 << 24) + (c2 << 16) + (c3 << 8) + c4);
}
/**
* Read a long from the stream
* @return The long
*/
public long
readLong() throws IOException {
int c1 = read();
int c2 = read();
int c3 = read();
int c4 = read();
int c5 = read();
int c6 = read();
int c7 = read();
int c8 = read();
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1 ||
c5 == -1 || c6 == -1 || c7 == -1 || c8 == -1)
throw new IOException("end of input");
return ((c1 << 56) + (c2 << 48) + (c3 << 40) + (c4 << 32) +
(c5 << 24) + (c6 << 16) + (c7 << 8) + c8);
}
/**
* Read a String from the stream, represented as a length byte followed by data
* @return The String
*/
public String
readString() throws IOException {
int len = read();
if (len == -1)
throw new IOException("end of input");
byte [] b = new byte[len];
int n = read(b);
if (n < len)
throw new IOException("end of input");
return new String(b);
}
/**
* Read a BigInteger from the stream, encoded as binary data. A 0 byte is
* prepended so that the value is always positive.
* @param len The number of bytes to read
* @return The BigInteger
*/
public BigInteger
readBigInteger(int len) throws IOException {
byte [] b = new byte[len + 1];
int n = read(b, 1, len);
if (n < len)
throw new IOException("end of input");
return new BigInteger(b);
}
/**
* Read and ignore bytes from the stream
* @param n The number of bytes to skip
*/
public void
skipBytes(int n) throws IOException {
skip(n);
}
/**
* Get the current position in the stream
* @return The current position
*/
public int
getPos() {
return pos;
}
}
|
package com.kopysoft.chronos.content;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.os.Environment;
import android.util.Log;
import com.kopysoft.chronos.enums.Defines;
import com.kopysoft.chronos.types.HoldNote;
import com.kopysoft.chronos.types.Punch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Chronos extends SQLiteOpenHelper {
private static final String TAG = "Chronos - SQL";
//0.9 = 7
//1.0.1 - 1.1.0 = 10
//1.2.0 = 11
//2.0.0 = 12
private static final int DATABASE_VERSION = 12;
public static final String TABLE_NAME_CLOCK = "clockactions";
public static final String TABLE_NAME_JOBS = "jobs";
public static final String TABLE_NAME_NOTE = "notes";
public static final String TABLE_NAME_OTHER = "misc";
public static final String DATABASE_NAME = "Chronos";
//String insertString = "INSERT INTO " + TABLE_NAME_CLOCK + "(time, actionReason) VALUES (?, ?, ?)";
String insertNote = "INSERT INTO " + TABLE_NAME_NOTE + "(note_string, time) VALUES (?, ?)";
public static final String insertLunch = "INSERT INTO " +
TABLE_NAME_OTHER + "(day, lunchTaken) VALUES (?, ?)";
public Chronos(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME_CLOCK +
" ( _id INTEGER PRIMARY KEY NOT NULL, " +
" time LONG NOT NULL, " +
" actionReason INTEGER NOT NULL, " +
" jobNumber INTEGER DEFAULT 0 )");
db.execSQL("CREATE TABLE " + TABLE_NAME_NOTE +
" ( _id LONG PRIMARY KEY, " +
" note_string TEXT NOT NULL, " +
" time LONG NOT NULL, " +
" jobNumber INTEGER DEFAULT 0 )");
db.execSQL("CREATE TABLE " + TABLE_NAME_OTHER +
" ( _id INTEGER PRIMARY KEY NOT NULL, " +
" day LONG NOT NULL, " +
" lunchTaken INTEGER NOT NULL, " +
" jobNumber INTEGER DEFAULT 0 ) ");
db.execSQL("CREATE TABLE " + TABLE_NAME_JOBS +
" ( _id INTEGER PRIMARY KEY NOT NULL, " +
" name String NOT NULL, " +
" default INTEGER NOT NULL )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database, this will drop tables and recreate.");
Log.w(TAG, "oldVerion: " + oldVersion + "\tnewVersion: " + newVersion);
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "/data/com.kopysoft.chronos/databases/" + DATABASE_NAME;
String backupDBPath = DATABASE_NAME + ".db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}catch (Exception e) {
Log.e(TAG, "ERROR: Can not move file");
}
if(oldVersion < 11) {
Log.d(TAG, "Update");
ArrayList<HoldNote> Notes;
try{
Notes = getNotes(db);
} catch (SQLiteException e){
try{
Notes = getNotes(db);
} catch( SQLiteException e2){
//throw(e2);
Notes = null;
}
}
ArrayList<Punch> punches = new ArrayList<Punch>();
Cursor cursor = db.query(TABLE_NAME_CLOCK, null,
null, null, null, null, "_id desc");
final int colId = cursor.getColumnIndex("_id");
final int colTime = cursor.getColumnIndex("time");
final int colAR = cursor.getColumnIndex("actionReason");
if (cursor.moveToFirst()) {
do {
long id = cursor.getLong(colId);
long time = cursor.getLong(colTime);
int type = Defines.REGULAR_TIME;
if(colAR != -1){
type = cursor.getInt(colAR);
}
Punch temp = new Punch(time, Defines.IN, id, type, 0);
punches.add(temp);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
dropAll(db);
for (Punch temp : punches) {
temp.setNeedToUpdate(true);
temp.removeId();
temp.commitToDb(db);
}
if(Notes != null){
reloadNotes(db, Notes);
}
} if (oldVersion == 11){
String dbCal1 = "ALTER TABLE " + TABLE_NAME_CLOCK + "ADD COLUMN jobNumber INTEGER DEFAULT 0";
String dbCal2 = "ALTER TABLE " + TABLE_NAME_NOTE + "ADD COLUMN jobNumber INTEGER DEFAULT 0";
String dbCal3 = "ALTER TABLE " + TABLE_NAME_OTHER + "ADD COLUMN jobNumber INTEGER DEFAULT 0";
String dbCal4 ="CREATE TABLE " + TABLE_NAME_JOBS +
" ( _id INTEGER PRIMARY KEY NOT NULL, " +
" name String NOT NULL, " +
" default INTEGER NOT NULL )";
db.execSQL(dbCal1);
db.execSQL(dbCal2);
db.execSQL(dbCal3);
db.execSQL(dbCal4);
}
}
private void reloadNotes(SQLiteDatabase db, ArrayList<HoldNote> Notes){
for( int i = 0; i < Notes.size(); i++ ){
SQLiteStatement insertStmt = db.compileStatement(insertNote);
insertStmt.bindString(1, Notes.get(i).getText() );
insertStmt.bindLong(2, Notes.get(i).getTime() );
insertStmt.executeInsert();
Log.d(TAG, "Adding entry: " + i);
} //end loop
}
// SQL Section
/**
* @param db database
*
* @return Returns list of HoldNote's
*/
private ArrayList<HoldNote> getNotes(SQLiteDatabase db){
ArrayList<HoldNote> returnValue = new ArrayList<HoldNote>();
Cursor cursor = db.query(TABLE_NAME_NOTE, new String[] { "note_string", "time" },
null, null, null, null, "time ASC ");
long time_temp;
String text_temp;
HoldNote tempNote;
if (cursor.moveToFirst()) {
do {
final int colNote = cursor.getColumnIndex("note_string");
final int colTime = cursor.getColumnIndex("time");
text_temp = cursor.getString(colNote);
time_temp = cursor.getLong(colTime);
tempNote = new HoldNote(time_temp, text_temp);
returnValue.add(tempNote);
} while (cursor.moveToNext());
}
if (!cursor.isClosed()) {
cursor.close();
}
return returnValue;
}
/**
* Drops TABLE_NAME and then recreates the database
*/
public void dropAll(){
SQLiteDatabase db = getWritableDatabase();
Log.w(TAG, "Dropping tables then recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CLOCK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_OTHER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_JOBS);
onCreate(db);
db.close();
}
public void dropAll(SQLiteDatabase db){
Log.w(TAG, "Dropping tables then recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_CLOCK);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_OTHER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_JOBS);
onCreate(db);
}
/**
* Gets the start of the current pay period
* @param dateGiven The start date of any payperiod [year, month, day]
* @param weeks_in_pp number of weeks in the pay period
* @return [year, month, day] of the current pay period
*/
public static int[] getPP(int[] dateGiven, int weeks_in_pp){
int[] returnValue = new int[3];
GregorianCalendar cal1 = new GregorianCalendar();
GregorianCalendar cal2 = new GregorianCalendar(dateGiven[0], dateGiven[1], dateGiven[2]);
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
long diff = time1 - time2;
diff = diff / 1000; //convert ms to s
int weeks = (int) diff / 60 / 60 / 24 / 7;
int pp_diff = weeks / weeks_in_pp;
if ( Defines.DEBUG_PRINT )Log.d(TAG, "days to add: " + (pp_diff * weeks_in_pp * 7) );
cal2.add(Calendar.DAY_OF_YEAR, pp_diff * weeks_in_pp * 7);
returnValue[0] = cal2.get(Calendar.YEAR);
returnValue[1] = cal2.get(Calendar.MONTH);
returnValue[2] = cal2.get(Calendar.DAY_OF_MONTH);
if ( Defines.DEBUG_PRINT )Log.d(TAG, "Start of PP - Y: " + returnValue[0] + "\tM: " +
returnValue[1] + "\tD: " + returnValue[2]);
if ( Defines.DEBUG_PRINT )Log.d(TAG, "Origonal PP: - Y: " + dateGiven[0] + "\tM: " +
dateGiven[1] + "\tD: " + dateGiven[2]);
return returnValue;
}
public static int[] getDate(String date){
String temp[] = date.split("\\.");
int[] returnValue = new int[3];
returnValue[0] = Integer.parseInt(temp[0]);
returnValue[1] = Integer.parseInt(temp[1]) - 1;
returnValue[2] = Integer.parseInt(temp[2]);
return returnValue;
}
}
|
package com.intellij.ide.ui.search;
import com.intellij.application.options.SkipSelfSearchComponent;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.*;
import com.intellij.openapi.options.ex.ConfigurableWrapper;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.util.CollectConsumer;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicComboPopup;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author anna
*/
public class SearchUtil {
private static final String DEBUGGER_CONFIGURABLE_CLASS = "com.intellij.xdebugger.impl.settings.DebuggerConfigurable";
private static final Pattern HTML_PATTERN = Pattern.compile("<[^<>]*>");
private static final Pattern QUOTED = Pattern.compile("\"([^\"]+)\"");
private static final Pattern NON_WORD_PATTERN = Pattern.compile("[\\W&&[^\\p{Punct}\\p{Blank}]]");
public static final String HIGHLIGHT_WITH_BORDER = "searchUtil.highlightWithBorder";
public static final String STYLE_END = "</style>";
private SearchUtil() { }
public static void processProjectConfigurables(Project project, Map<SearchableConfigurable, Set<OptionDescription>> options) {
processConfigurables(ShowSettingsUtilImpl.getConfigurables(project, true), options);
}
private static void processConfigurables(@NotNull List<? extends Configurable> configurables, Map<SearchableConfigurable, Set<OptionDescription>> options) {
for (final Configurable configurable : configurables) {
if (!(configurable instanceof SearchableConfigurable)) {
continue;
}
//ignore invisible root nodes
//noinspection deprecation
if (configurable instanceof SearchableConfigurable.Parent && !((SearchableConfigurable.Parent)configurable).isVisible()) {
continue;
}
final SearchableConfigurable searchableConfigurable = (SearchableConfigurable)configurable;
Set<OptionDescription> configurableOptions = new TreeSet<>();
options.put(searchableConfigurable, configurableOptions);
for (TraverseUIHelper extension : TraverseUIHelper.helperExtensionPoint.getExtensions()) {
extension.beforeConfigurable(searchableConfigurable, configurableOptions);
}
if (configurable instanceof MasterDetails) {
final MasterDetails md = (MasterDetails)configurable;
md.initUi();
processComponent(searchableConfigurable, configurableOptions, md.getMaster());
processComponent(searchableConfigurable, configurableOptions, md.getDetails().getComponent());
}
else {
processComponent(searchableConfigurable, configurableOptions, configurable.createComponent());
final Configurable unwrapped = unwrapConfigurable(configurable);
if (unwrapped instanceof CompositeConfigurable) {
unwrapped.disposeUIResources();
//noinspection unchecked
final List<? extends UnnamedConfigurable> children = ((CompositeConfigurable)unwrapped).getConfigurables();
for (final UnnamedConfigurable child : children) {
final Set<OptionDescription> childConfigurableOptions = new TreeSet<>();
options.put(new SearchableConfigurableAdapter(searchableConfigurable, child), childConfigurableOptions);
if (child instanceof SearchableConfigurable) {
processUILabel(((SearchableConfigurable)child).getDisplayName(), childConfigurableOptions, null);
}
final JComponent component = child.createComponent();
if (component != null) {
processComponent(component, childConfigurableOptions, null);
}
configurableOptions.removeAll(childConfigurableOptions);
}
}
}
for (TraverseUIHelper extension : TraverseUIHelper.helperExtensionPoint.getExtensions()) {
extension.afterConfigurable(searchableConfigurable, configurableOptions);
}
}
}
@NotNull
private static Configurable unwrapConfigurable(@NotNull Configurable configurable) {
if (configurable instanceof ConfigurableWrapper) {
final UnnamedConfigurable wrapped = ((ConfigurableWrapper)configurable).getConfigurable();
if (wrapped instanceof SearchableConfigurable) {
configurable = (Configurable)wrapped;
}
}
if (DEBUGGER_CONFIGURABLE_CLASS.equals(configurable.getClass().getName())) {
final Class<?> clazz = ReflectionUtil.forName(DEBUGGER_CONFIGURABLE_CLASS);
final Configurable rootConfigurable = ReflectionUtil.getField(clazz, configurable, Configurable.class, "myRootConfigurable");
if (rootConfigurable != null) {
return rootConfigurable;
}
}
return configurable;
}
private static void processComponent(SearchableConfigurable configurable, Set<? super OptionDescription> configurableOptions, JComponent component) {
if (component != null) {
for (TraverseUIHelper extension : TraverseUIHelper.helperExtensionPoint.getExtensions()) {
extension.beforeComponent(configurable, component, configurableOptions);
}
processUILabel(configurable.getDisplayName(), configurableOptions, null);
processComponent(component, configurableOptions, null);
for (TraverseUIHelper extension : TraverseUIHelper.helperExtensionPoint.getExtensions()) {
extension.afterComponent(configurable, component, configurableOptions);
}
}
}
private static void processComponent(JComponent component, Set<? super OptionDescription> configurableOptions, String path) {
if (component instanceof SkipSelfSearchComponent) {
return;
}
final Border border = component.getBorder();
if (border instanceof TitledBorder) {
final TitledBorder titledBorder = (TitledBorder)border;
final String title = titledBorder.getTitle();
if (title != null) {
processUILabel(title, configurableOptions, path);
}
}
String label = getLabelFromComponent(component);
if (label != null) {
processUILabel(label, configurableOptions, path);
}
else if (component instanceof JComboBox) {
List<String> labels = getItemsFromComboBox((JComboBox)component);
for (String each : labels) {
processUILabel(each, configurableOptions, path);
}
}
else if (component instanceof JTabbedPane) {
final JTabbedPane tabbedPane = (JTabbedPane)component;
final int tabCount = tabbedPane.getTabCount();
for (int i = 0; i < tabCount; i++) {
final String title = path != null ? path + '.' + tabbedPane.getTitleAt(i) : tabbedPane.getTitleAt(i);
processUILabel(title, configurableOptions, title);
final Component tabComponent = tabbedPane.getComponentAt(i);
if (tabComponent instanceof JComponent) {
processComponent((JComponent)tabComponent, configurableOptions, title);
}
}
}
else if (component instanceof TabbedPaneWrapper.TabbedPaneHolder) {
final TabbedPaneWrapper tabbedPane = ((TabbedPaneWrapper.TabbedPaneHolder)component).getTabbedPaneWrapper();
final int tabCount = tabbedPane.getTabCount();
for (int i = 0; i < tabCount; i++) {
String tabTitle = tabbedPane.getTitleAt(i);
final String title = path != null ? path + '.' + tabTitle : tabTitle;
processUILabel(title, configurableOptions, title);
final JComponent tabComponent = tabbedPane.getComponentAt(i);
if (tabComponent != null) {
processComponent(tabComponent, configurableOptions, title);
}
}
}
else {
final Component[] components = component.getComponents();
if (components != null) {
for (Component child : components) {
if (child instanceof JComponent) {
processComponent((JComponent)child, configurableOptions, path);
}
}
}
}
}
@Nullable
private static String getLabelFromComponent(@Nullable Component component) {
String label = null;
if (component instanceof JLabel) {
label = ((JLabel)component).getText();
}
else if (component instanceof JCheckBox) {
label = ((JCheckBox)component).getText();
}
else if (component instanceof JRadioButton) {
label = ((JRadioButton)component).getText();
}
else if (component instanceof JButton) {
label = ((JButton)component).getText();
}
return StringUtil.nullize(label, true);
}
@NotNull
public static List<String> getItemsFromComboBox(@NotNull JComboBox comboBox) {
ListCellRenderer renderer = comboBox.getRenderer();
if (renderer == null) {
renderer = new DefaultListCellRenderer();
}
JList jList = new BasicComboPopup(comboBox).getList();
List<String> result = new ArrayList<>();
int count = comboBox.getItemCount();
for (int i = 0; i < count; i++) {
Object value = comboBox.getItemAt(i);
//noinspection unchecked
Component labelComponent = renderer.getListCellRendererComponent(jList, value, i, false, false);
String label = getLabelFromComponent(labelComponent);
if (label != null) {
result.add(label);
}
}
return result;
}
private static void processUILabel(String title, Set<? super OptionDescription> configurableOptions, String path) {
title = HTML_PATTERN.matcher(title).replaceAll(" ");
final Set<String> words = SearchableOptionsRegistrar.getInstance().getProcessedWordsWithoutStemming(title);
title = NON_WORD_PATTERN.matcher(title).replaceAll(" ");
for (String option : words) {
configurableOptions.add(new OptionDescription(option, title, path));
}
}
public static void lightOptions(SearchableConfigurable configurable, JComponent component, String option) {
if (!traverseComponentsTree(configurable, component, option, true)) {
traverseComponentsTree(configurable, component, option, false);
}
}
private static int getSelection(String tabIdx, int tabCount, Function<Integer,String> titleGetter) {
SearchableOptionsRegistrar searchableOptionsRegistrar = SearchableOptionsRegistrar.getInstance();
for (int i = 0; i < tabCount; i++) {
final Set<String> pathWords = searchableOptionsRegistrar.getProcessedWords(tabIdx);
final String title = titleGetter.apply(i);
if (!pathWords.isEmpty()) {
final Set<String> titleWords = searchableOptionsRegistrar.getProcessedWords(title);
pathWords.removeAll(titleWords);
if (pathWords.isEmpty()) {
return i;
}
}
else if (tabIdx.equalsIgnoreCase(title)) { //e.g. only stop words
return i;
}
}
return -1;
}
private static boolean traverseComponentsTree(SearchableConfigurable configurable,
JComponent rootComponent,
String option,
boolean force) {
rootComponent.putClientProperty(HIGHLIGHT_WITH_BORDER, null);
if (option == null || option.trim().length() == 0) {
return false;
}
String label = getLabelFromComponent(rootComponent);
if (label != null) {
if (isComponentHighlighted(label, option, force, configurable)) {
highlightComponent(rootComponent, option);
return true; // do not visit children of highlighted component
}
}
else if (rootComponent instanceof JComboBox) {
List<String> labels = getItemsFromComboBox(((JComboBox)rootComponent));
if (ContainerUtil.exists(labels, it -> isComponentHighlighted(it, option, force, configurable))) {
highlightComponent(rootComponent, option);
return true; // do not visit children of highlighted component
}
}
else if (rootComponent instanceof JTabbedPane) {
final JTabbedPane tabbedPane = (JTabbedPane)rootComponent;
final Set<String> paths = SearchableOptionsRegistrar.getInstance().getInnerPaths(configurable, option);
for (String path : paths) {
if (path != null) {
final int index = getSelection(path, tabbedPane.getTabCount(), i -> tabbedPane.getTitleAt(i));
if (index > -1 && index < tabbedPane.getTabCount()) {
if (tabbedPane.getTabComponentAt(index) instanceof JComponent) {
highlightComponent((JComponent)tabbedPane.getTabComponentAt(index), option);
}
}
}
}
}
else if (rootComponent instanceof TabbedPaneWrapper.TabbedPaneHolder) {
final TabbedPaneWrapper tabbedPaneWrapper = ((TabbedPaneWrapper.TabbedPaneHolder)rootComponent).getTabbedPaneWrapper();
final Set<String> paths = SearchableOptionsRegistrar.getInstance().getInnerPaths(configurable, option);
for (String path : paths) {
if (path != null) {
final int index = getSelection(path, tabbedPaneWrapper.getTabCount(), i -> tabbedPaneWrapper.getTitleAt(i));
if (index > -1 && index < tabbedPaneWrapper.getTabCount()) {
highlightComponent((JComponent)tabbedPaneWrapper.getTabComponentAt(index), option);
}
}
}
}
Border border = rootComponent.getBorder();
if (border instanceof TitledBorder) {
String title = ((TitledBorder)border).getTitle();
if (isComponentHighlighted(title, option, force, configurable)) {
highlightComponent(rootComponent, option);
rootComponent.putClientProperty(HIGHLIGHT_WITH_BORDER, Boolean.TRUE);
return true; // do not visit children of highlighted component
}
}
boolean highlight = false;
for (Component component : rootComponent.getComponents()) {
if (component instanceof JComponent && traverseComponentsTree(configurable, (JComponent)component, option, force)) {
highlight = true;
}
}
return highlight;
}
private static void highlightComponent(@NotNull JComponent rootComponent, @NotNull String searchString) {
ApplicationManager.getApplication().getMessageBus().syncPublisher(ComponentHighlightingListener.TOPIC).highlight(rootComponent, searchString);
}
public static boolean isComponentHighlighted(String text, String option, boolean force, final SearchableConfigurable configurable) {
if (text == null || option == null || option.length() == 0) {
return false;
}
final SearchableOptionsRegistrar searchableOptionsRegistrar = SearchableOptionsRegistrar.getInstance();
final Set<String> words = searchableOptionsRegistrar.getProcessedWords(option);
final Set<String> options = configurable != null ? searchableOptionsRegistrar.replaceSynonyms(words, configurable) : words;
if (options.isEmpty()) {
return StringUtil.toLowerCase(text).contains(StringUtil.toLowerCase(option));
}
final Set<String> tokens = searchableOptionsRegistrar.getProcessedWords(text);
if (!force) {
options.retainAll(tokens);
final boolean highlight = !options.isEmpty();
return highlight || StringUtil.toLowerCase(text).contains(StringUtil.toLowerCase(option));
}
else {
options.removeAll(tokens);
return options.isEmpty();
}
}
public static String markup(@NotNull String textToMarkup, @Nullable String filter) {
if (filter == null || filter.length() == 0) {
return textToMarkup;
}
int bodyStart = textToMarkup.indexOf("<body>");
final int bodyEnd = textToMarkup.indexOf("</body>");
final String head;
final String foot;
if (bodyStart >= 0) {
bodyStart += "<body>".length();
head = textToMarkup.substring(0, bodyStart);
if (bodyEnd >= 0) {
foot = textToMarkup.substring(bodyEnd);
}
else {
foot = "";
}
textToMarkup = textToMarkup.substring(bodyStart, bodyEnd);
}
else {
foot = "";
head = "";
}
final Pattern insideHtmlTagPattern = Pattern.compile("[<[^<>]*>]*<[^<>]*");
final SearchableOptionsRegistrar registrar = SearchableOptionsRegistrar.getInstance();
final HashSet<String> quoted = new HashSet<>();
filter = processFilter(quoteStrictOccurrences(textToMarkup, filter), quoted);
final Set<String> options = registrar.getProcessedWords(filter);
final Set<String> words = registrar.getProcessedWords(textToMarkup);
for (String option : options) {
if (words.contains(option)) {
textToMarkup = markup(textToMarkup, insideHtmlTagPattern, option);
}
}
for (String stripped : quoted) {
if (registrar.isStopWord(stripped)) {
continue;
}
textToMarkup = markup(textToMarkup, insideHtmlTagPattern, stripped);
}
return head + textToMarkup + foot;
}
private static String quoteStrictOccurrences(final String textToMarkup, final String filter) {
StringBuilder cur = new StringBuilder();
final String s = StringUtil.toLowerCase(textToMarkup);
for (String part : filter.split(" ")) {
if (s.contains(part)) {
cur.append("\"").append(part).append("\" ");
}
else {
cur.append(part).append(" ");
}
}
return cur.toString();
}
private static String markup(String textToMarkup, final Pattern insideHtmlTagPattern, final String option) {
final int styleIdx = textToMarkup.indexOf("<style");
final int styleEndIdx = textToMarkup.indexOf("</style>");
if (styleIdx < 0 || styleEndIdx < 0) {
return markupInText(textToMarkup, insideHtmlTagPattern, option);
}
return markup(textToMarkup.substring(0, styleIdx), insideHtmlTagPattern, option) +
markup(textToMarkup.substring(styleEndIdx + STYLE_END.length()), insideHtmlTagPattern, option);
}
private static String markupInText(String textToMarkup, Pattern insideHtmlTagPattern, String option) {
StringBuilder result = new StringBuilder();
int beg = 0;
int idx;
while ((idx = StringUtil.indexOfIgnoreCase(textToMarkup, option, beg)) != -1) {
final String prefix = textToMarkup.substring(beg, idx);
final String toMark = textToMarkup.substring(idx, idx + option.length());
if (insideHtmlTagPattern.matcher(prefix).matches()) {
final int lastIdx = textToMarkup.indexOf(">", idx);
result.append(prefix).append(textToMarkup, idx, lastIdx + 1);
beg = lastIdx + 1;
}
else {
result.append(prefix).append("<font color='#ffffff' bgColor='#1d5da7'>").append(toMark).append("</font>");
beg = idx + option.length();
}
}
result.append(textToMarkup.substring(beg));
return result.toString();
}
public static void appendFragments(String filter,
String text,
@SimpleTextAttributes.StyleAttributeConstant int style,
final Color foreground,
final Color background,
final SimpleColoredComponent textRenderer) {
if (text == null) {
return;
}
if (filter == null || filter.length() == 0) {
textRenderer.append(text, new SimpleTextAttributes(background, foreground, JBColor.RED, style));
}
else { //markup
final HashSet<String> quoted = new HashSet<>();
filter = processFilter(quoteStrictOccurrences(text, filter), quoted);
final TreeMap<Integer, String> indx = new TreeMap<>();
for (String stripped : quoted) {
int beg = 0;
int idx;
while ((idx = StringUtil.indexOfIgnoreCase(text, stripped, beg)) != -1) {
indx.put(idx, text.substring(idx, idx + stripped.length()));
beg = idx + stripped.length();
}
}
final List<String> selectedWords = new ArrayList<>();
int pos = 0;
for (Integer index : indx.keySet()) {
final String stripped = indx.get(index);
final int start = index.intValue();
if (pos > start) {
final String highlighted = selectedWords.get(selectedWords.size() - 1);
if (highlighted.length() < stripped.length()) {
selectedWords.remove(highlighted);
}
else {
continue;
}
}
appendSelectedWords(text, selectedWords, pos, start, filter);
selectedWords.add(stripped);
pos = start + stripped.length();
}
appendSelectedWords(text, selectedWords, pos, text.length(), filter);
int idx = 0;
for (String word : selectedWords) {
text = text.substring(idx);
final String before = text.substring(0, text.indexOf(word));
if (before.length() > 0) {
textRenderer.append(before, new SimpleTextAttributes(background, foreground, null, style));
}
idx = text.indexOf(word) + word.length();
textRenderer.append(text.substring(idx - word.length(), idx), new SimpleTextAttributes(background,
foreground, null,
style |
SimpleTextAttributes.STYLE_SEARCH_MATCH));
}
final String after = text.substring(idx);
if (after.length() > 0) {
textRenderer.append(after, new SimpleTextAttributes(background, foreground, null, style));
}
}
}
private static void appendSelectedWords(final String text,
final List<? super String> selectedWords,
final int pos,
int end,
final String filter) {
if (pos < end) {
final Set<String> filters = SearchableOptionsRegistrar.getInstance().getProcessedWords(filter);
final String[] words = text.substring(pos, end).split("[\\W&&[^-]]+");
for (String word : words) {
if (filters.contains(PorterStemmerUtil.stem(StringUtil.toLowerCase(word)))) {
selectedWords.add(word);
}
}
}
}
public static List<Set<String>> findKeys(String filter, Set<? super String> quoted) {
filter = processFilter(StringUtil.toLowerCase(filter), quoted);
final List<Set<String>> keySetList = new ArrayList<>();
final SearchableOptionsRegistrar optionsRegistrar = SearchableOptionsRegistrar.getInstance();
final Set<String> words = optionsRegistrar.getProcessedWords(filter);
for (String word : words) {
final Set<OptionDescription> descriptions = ((SearchableOptionsRegistrarImpl)optionsRegistrar).getAcceptableDescriptions(word);
Set<String> keySet = new HashSet<>();
if (descriptions != null) {
for (OptionDescription description : descriptions) {
keySet.add(description.getPath());
}
}
keySetList.add(keySet);
}
if (keySetList.isEmpty() && !StringUtil.isEmptyOrSpaces(filter)) {
keySetList.add(Collections.singleton(filter));
}
return keySetList;
}
public static String processFilter(String filter, Set<? super String> quoted) {
StringBuilder withoutQuoted = new StringBuilder();
int beg = 0;
final Matcher matcher = QUOTED.matcher(filter);
while (matcher.find()) {
final int start = matcher.start(1);
withoutQuoted.append(" ").append(filter, beg, start);
beg = matcher.end(1);
final String trimmed = filter.substring(start, beg).trim();
if (trimmed.length() > 0) {
quoted.add(trimmed);
}
}
return withoutQuoted + " " + filter.substring(beg);
}
@NotNull
public static List<Configurable> expand(ConfigurableGroup @NotNull [] groups) {
List<Configurable> result = new ArrayList<>();
CollectConsumer<Configurable> consumer = new CollectConsumer<>(result);
for (ConfigurableGroup group : groups) {
processExpandedGroups(group, consumer);
}
return result;
}
@NotNull
public static List<Configurable> expandGroup(@NotNull ConfigurableGroup group) {
List<Configurable> result = new ArrayList<>();
processExpandedGroups(group, new CollectConsumer<>(result));
return result;
}
public static void processExpandedGroups(@NotNull ConfigurableGroup group, @NotNull Consumer<? super Configurable> consumer) {
Configurable[] configurables = group.getConfigurables();
List<Configurable> result = new ArrayList<>();
ContainerUtil.addAll(result, configurables);
for (Configurable each : configurables) {
addChildren(each, result);
}
for (Configurable configurable : result) {
if (isAcceptable(configurable)) {
consumer.accept(configurable);
}
}
}
public static boolean isAcceptable(@NotNull Configurable configurable) {
//noinspection deprecation
return !(configurable instanceof SearchableConfigurable.Parent) || ((SearchableConfigurable.Parent)configurable).isVisible();
}
private static void addChildren(@NotNull Configurable configurable, @NotNull List<? super Configurable> list) {
if (configurable instanceof Configurable.Composite) {
for (Configurable eachKid : ((Configurable.Composite)configurable).getConfigurables()) {
list.add(eachKid);
addChildren(eachKid, list);
}
}
}
private static final class SearchableConfigurableAdapter implements SearchableConfigurable {
private final SearchableConfigurable myOriginal;
private final UnnamedConfigurable myDelegate;
private SearchableConfigurableAdapter(@NotNull final SearchableConfigurable original, @NotNull final UnnamedConfigurable delegate) {
myOriginal = original;
myDelegate = delegate;
}
@NotNull
@Override
public String getId() {
return myOriginal.getId();
}
@Nls(capitalization = Nls.Capitalization.Title)
@Override
public String getDisplayName() {
return myOriginal.getDisplayName();
}
@NotNull
@Override
public Class<?> getOriginalClass() {
return myDelegate instanceof SearchableConfigurable ? ((SearchableConfigurable)myDelegate).getOriginalClass() : myDelegate.getClass();
}
@Nullable
@Override
public JComponent createComponent() {
return null;
}
@Override
public boolean isModified() {
return false;
}
@Override
public void apply() {
}
@Override
public String toString() {
return getDisplayName();
}
}
}
|
package structure.impl;
import structure.intf.Binding;
import structure.intf.QEA;
import exceptions.ShouldNotHappenException;
/**
* A QEA with at most one quantified variable
*
* @author Helena Cuenca
* @author Giles Reger
*/
public abstract class NonSimpleQEA implements QEA { // TODO Check name
protected int[] finalStates; // TODO Can we use a boolean array here?
protected final int initialState;
protected final boolean isPropositional;
protected final boolean quantificationUniversal;
protected final int freeVariablesCount;
public NonSimpleQEA(int numStates, int initialState,
Quantification quantification, int freeVariablesCount) {
finalStates = new int[numStates + 1];
this.initialState = initialState;
this.freeVariablesCount = freeVariablesCount;
switch (quantification) {
case FORALL:
quantificationUniversal = true;
isPropositional = false;
break;
case EXISTS:
quantificationUniversal = false;
isPropositional = false;
break;
case NONE:
quantificationUniversal = false;
isPropositional = true;
break;
default:
throw new ShouldNotHappenException("Unknown quantification "
+ quantification);
}
}
/**
* Adds the specified state to the set of final states
*
* @param state
* State name
*/
public void setStateAsFinal(int state) {
finalStates[state] = 1;
}
/**
* Adds the specified states to the set of final statess
*
* @param states
* Names of states to add
*/
public void setStatesAsFinal(int... states) {
for (int state : states) {
finalStates[state] = 1;
}
}
@Override
public int[] getStates() {
int[] q = new int[finalStates.length - 1];
for (int i = 0; i < q.length; i++) {
q[i] = i + 1;
}
return q;
}
/**
* Creates a new binding of free variable for the current QEA
*
* @return Binding
*/
public Binding newBinding() {
// TODO Free variables names should start in 0 or 1?
return new BindingImpl(freeVariablesCount + 1);
}
/**
* Returns the initial state for this QEA
*
* @return Initial state
*/
public int getInitialState() {
return initialState;
}
@Override
public int[] getLambda() {
if (isPropositional) {
return new int[] {};
}
if (quantificationUniversal) {
return new int[] { -1 };
}
return new int[] { 1 };
}
@Override
public boolean usesFreeVariables() {
return true;
}
@Override
public boolean isStateFinal(int state) {
if (finalStates[state] == 1) {
return true;
}
return false;
}
/**
* @return <code>true</code> if the quantification for the variable of this
* QEA is universal; <code>false</code> if it is existential
*/
public boolean isQuantificationUniversal() {
return quantificationUniversal;
}
/**
* Checks if the specified numbers are equal. In case they are not, throws a
* <code>ShouldNotHappenException</code> exception
*
* @param argsSize
* Length of the arguments
* @param paramSize
* Length of the parameters
*/
protected void checkArgParamLength(int argsLength, int paramLength) {
if (argsLength != paramLength) {
throw new ShouldNotHappenException(
"The number of variables defined for this event doesn't match the number of arguments");
}
}
/**
* Updates the specified free variables binding with the specified
* arguments, according to the variable names in the specified transition
* and returns an array with the values in the binding that were replaced
*
* @param binding
* Binding to be updated
* @param args
* Array of arguments
* @param transition
* Transition containing the variable names to be matched with
* the arguments
* @return Array with the values in the binding that were replaced (free
* variables only). The size of the array is equal to the size of
* <code>args</code>. The order of the values returned corresponds
* to the order of the variables defined in the transition. If there
* is a quantified variable defined in the transition, a
* <code>null</code> value is returned in the corresponding position
*/
protected Object[] updateBinding(Binding binding, Object[] args,
Transition transition) {
Object[] prevBinding = new Object[args.length];
for (int i = 0; i < args.length; i++) {
int varName = transition.getVariableNames()[i];
// Check the variable is free
if (varName >= 0) {
// Save previous value
prevBinding[i] = binding.getValue(varName);
// Set new value
binding.setValue(varName, args[i]);
}
}
return prevBinding;
}
/**
* Updates the specified free variables binding with the specified
* arguments, according to the variable names in the specified transition
* and returns an array with the values in the binding that were replaced
*
* @param binding
* Binding to be updated
* @param args
* Array of arguments. The first position contains the value for
* the quantified variable, while the values starting from the
* second position correspond to free variables
* @param transition
* Transition containing the variable names to be matched with
* the arguments
* @return Array with the values in the binding that were replaced (free
* variables only). The size of the array is equal to the size of
* <code>args - 1</code>. The order of the values returned
* corresponds to the order of the free variables defined in the
* transition
*/
protected Object[] updateBindingFixedQVar(Binding binding, Object[] args,
Transition transition) {
Object[] prevBinding = new Object[args.length - 1];
// Starting in the second position, all parameters are free variables
for (int i = 1; i < args.length; i++) {
int varName = transition.getVariableNames()[i];
// Save previous value
prevBinding[i - 1] = binding.getValue(varName);
// Set new value for the free variable
binding.setValue(varName, args[i]);
}
return prevBinding;
}
/**
* Updates the specified binding with the values in the array
* <code>prevBinding</code>, according to the variable names in the
* specified transition. This method should be used after a call to
* <code>updateBinding</code>
*
* @param binding
* Binding to be returned to its original values
* @param transition
* Transition containing the variable names to be matched with
* the previousBinding
* @param prevBinding
* Array containing the values in the binding that were replaced
* (only free variables)
*/
protected void rollBackBinding(Binding binding, Transition transition,
Object[] prevBinding) {
for (int i = 0; i < prevBinding.length; i++) {
if (transition.getVariableNames()[i] >= 0) {
binding.setValue(transition.getVariableNames()[i],
prevBinding[i]);
}
}
}
/**
* Updates the specified binding with the values in the array
* <code>prevBinding</code>, according to the variable names in the
* specified transition. This method should be used after a call to
* <code>updateBindingFixedQVar</code>
*
* @param binding
* Binding to be returned to its original values
* @param transition
* Transition containing the variable names to be matched with
* the previousBinding
* @param prevBinding
* Array containing the values in the binding that were replaced
* (only free variables)
*/
protected void rollBackBindingFixedQVar(Binding binding,
Transition transition, Object[] prevBinding) {
for (int i = 0; i < prevBinding.length; i++) {
binding.setValue(transition.getVariableNames()[i + 1],
prevBinding[i]);
}
}
}
|
package com.axelor.apps.account.service;
import java.math.BigDecimal;
import org.joda.time.LocalDate;
import com.axelor.apps.account.db.Invoice;
import com.axelor.apps.account.db.InvoicePayment;
import com.axelor.apps.account.db.Journal;
import com.axelor.apps.account.db.Move;
import com.axelor.apps.account.db.MoveLine;
import com.axelor.apps.account.db.PaymentMode;
import com.axelor.apps.account.db.Reconcile;
import com.axelor.apps.account.db.repo.InvoicePaymentRepository;
import com.axelor.apps.account.db.repo.ReconcileRepository;
import com.axelor.apps.account.service.config.AccountConfigService;
import com.axelor.apps.account.service.invoice.InvoiceService;
import com.axelor.apps.account.service.move.MoveCancelService;
import com.axelor.apps.account.service.move.MoveLineService;
import com.axelor.apps.account.service.move.MoveService;
import com.axelor.apps.account.service.payment.PaymentModeService;
import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.Partner;
import com.axelor.apps.base.service.CurrencyService;
import com.axelor.exception.AxelorException;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
public class InvoicePaymentServiceImpl implements InvoicePaymentService {
protected PaymentModeService paymentModeService;
protected MoveService moveService;
protected MoveLineService moveLineService;
protected CurrencyService currencyService;
protected AccountConfigService accountConfigService;
protected InvoicePaymentRepository invoicePaymentRepository;
protected MoveCancelService moveCancelService;
protected InvoiceService invoiceService;
protected ReconcileService reconcileService;
@Inject
public InvoicePaymentServiceImpl(PaymentModeService paymentModeService, MoveService moveService, MoveLineService moveLineService,
CurrencyService currencyService, AccountConfigService accountConfigService, InvoicePaymentRepository invoicePaymentRepository,
MoveCancelService moveCancelService, InvoiceService invoiceService, ReconcileService reconcileService) {
this.paymentModeService = paymentModeService;
this.moveService = moveService;
this.moveLineService = moveLineService;
this.currencyService = currencyService;
this.accountConfigService = accountConfigService;
this.invoicePaymentRepository = invoicePaymentRepository;
this.moveCancelService = moveCancelService;
this.invoiceService = invoiceService;
this.reconcileService = reconcileService;
}
/**
* Method to validate an invoice Payment
*
* Create the eventual move (depending general configuration) and reconcile it with the invoice move
* Compute the amount paid on invoice
* Change the status to validated
*
* @param invoicePayment
* An invoice payment
*
* @throws AxelorException
*
*/
@Transactional(rollbackOn = {AxelorException.class, Exception.class})
public void validate(InvoicePayment invoicePayment) throws AxelorException {
if(invoicePayment.getStatusSelect() != InvoicePaymentRepository.STATUS_DRAFT) { return; }
invoicePayment.setStatusSelect(InvoicePaymentRepository.STATUS_VALIDATED);
Company company = invoicePayment.getInvoice().getCompany();
if(accountConfigService.getAccountConfig(company).getGenerateMoveForInvoicePayment()) {
this.createMoveForInvoicePayment(invoicePayment);
}
invoiceService.updateAmountPaid(invoicePayment.getInvoice());
invoicePaymentRepository.save(invoicePayment);
}
/**
* Method to create a payment move for an invoice Payment
*
* Create a move and reconcile it with the invoice move
*
* @param invoicePayment
* An invoice payment
*
* @throws AxelorException
*
*/
@Transactional(rollbackOn = {AxelorException.class, Exception.class})
public Move createMoveForInvoicePayment(InvoicePayment invoicePayment) throws AxelorException {
Invoice invoice = invoicePayment.getInvoice();
Company company = invoice.getCompany();
PaymentMode paymentMode = invoicePayment.getPaymentMode();
Partner partner = invoice.getPartner();
LocalDate paymentDate = invoicePayment.getPaymentDate();
Journal journal = paymentModeService.getPaymentModeJournal(paymentMode, company);
boolean isDebitInvoice = moveService.getMoveToolService().isDebitCustomer(invoice);
MoveLine invoiceMoveLine = moveService.getMoveToolService().getInvoiceCustomerMoveLineByLoop(invoice);
Move move = moveService.getMoveCreateService().createMove(journal, company, null, partner, paymentDate, paymentMode);
BigDecimal amountConverted = currencyService.getAmountCurrencyConverted(invoicePayment.getCurrency(), invoice.getCurrency(), invoicePayment.getAmount(), paymentDate);
move.addMoveLineListItem(moveLineService.createMoveLine(move, partner, paymentModeService.getPaymentModeAccount(paymentMode, company),
amountConverted, isDebitInvoice, paymentDate, null, 1, ""));
MoveLine customerMoveLine = moveLineService.createMoveLine(move, partner, invoiceMoveLine.getAccount(),
amountConverted, !isDebitInvoice, paymentDate, null, 2, "");
move.addMoveLineListItem(customerMoveLine);
moveService.getMoveValidateService().validate(move);
Reconcile reconcile = reconcileService.reconcile(invoiceMoveLine, customerMoveLine, true);
invoicePayment.setReconcile(reconcile);
invoicePayment.setMove(move);
invoicePaymentRepository.save(invoicePayment);
return move;
}
/**
* Method to cancel an invoice Payment
*
* Cancel the eventual Move and Reconcile
* Compute the total amount paid on the linked invoice
* Change the status to cancel
*
* @param invoicePayment
* An invoice payment
*
* @throws AxelorException
*
*/
@Transactional(rollbackOn = {AxelorException.class, Exception.class})
public void cancel(InvoicePayment invoicePayment) throws AxelorException {
Move paymentMove = invoicePayment.getMove();
Reconcile reconcile = invoicePayment.getReconcile();
if(reconcile != null && reconcile.getStatusSelect() == ReconcileRepository.STATUS_CONFIRMED) {
reconcileService.unreconcile(reconcile);
if(accountConfigService.getAccountConfig(invoicePayment.getInvoice().getCompany()).getAllowRemovalValidatedMove()) {
invoicePayment.setReconcile(null);
Beans.get(ReconcileRepository.class).remove(reconcile);
}
}
if(paymentMove != null) {
invoicePayment.setMove(null);
moveCancelService.cancel(paymentMove);
}
invoicePayment.setStatusSelect(InvoicePaymentRepository.STATUS_CANCELED);
invoicePaymentRepository.save(invoicePayment);
invoiceService.updateAmountPaid(invoicePayment.getInvoice());
}
}
|
package com.shc.silenceengine.backend.android;
import android.opengl.GLSurfaceView;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import com.shc.silenceengine.core.SilenceEngine;
import com.shc.silenceengine.input.InputDevice;
import java.util.HashMap;
import java.util.Map;
import static android.view.KeyEvent.*;
import static com.shc.silenceengine.input.Keyboard.*;
import static com.shc.silenceengine.input.Touch.*;
/**
* @author Sri Harsha Chilakapati
*/
public class AndroidInputDevice extends InputDevice
{
private static Map<Integer, Integer> keyMap;
private GLSurfaceView surfaceView;
public AndroidInputDevice()
{
surfaceView = ((AndroidDisplayDevice) SilenceEngine.display).surfaceView;
surfaceView.setOnKeyListener(this::onKey);
surfaceView.setOnTouchListener(this::onTouch);
prepareKeyMap();
}
private void prepareKeyMap()
{
keyMap = new HashMap<>();
// Escape key
keyMap.put(KEYCODE_ESCAPE, KEY_ESCAPE);
// Function keys
keyMap.put(KEYCODE_F1, KEY_F1);
keyMap.put(KEYCODE_F2, KEY_F2);
keyMap.put(KEYCODE_F3, KEY_F3);
keyMap.put(KEYCODE_F4, KEY_F4);
keyMap.put(KEYCODE_F5, KEY_F5);
keyMap.put(KEYCODE_F6, KEY_F6);
keyMap.put(KEYCODE_F7, KEY_F7);
keyMap.put(KEYCODE_F8, KEY_F8);
keyMap.put(KEYCODE_F9, KEY_F9);
keyMap.put(KEYCODE_F10, KEY_F10);
keyMap.put(KEYCODE_F11, KEY_F11);
keyMap.put(KEYCODE_F12, KEY_F12);
// Number keys
keyMap.put(KEYCODE_0, KEY_0);
keyMap.put(KEYCODE_1, KEY_1);
keyMap.put(KEYCODE_2, KEY_2);
keyMap.put(KEYCODE_3, KEY_3);
keyMap.put(KEYCODE_4, KEY_4);
keyMap.put(KEYCODE_5, KEY_5);
keyMap.put(KEYCODE_6, KEY_6);
keyMap.put(KEYCODE_7, KEY_7);
keyMap.put(KEYCODE_8, KEY_8);
keyMap.put(KEYCODE_9, KEY_9);
// Symbol keys
keyMap.put(KEYCODE_MINUS, KEY_UNDERSCORE);
keyMap.put(KEYCODE_EQUALS, KEY_EQUALS);
keyMap.put(KEYCODE_LEFT_BRACKET, KEY_LEFT_BRACE);
keyMap.put(KEYCODE_RIGHT_BRACKET, KEY_RIGHT_BRACE);
keyMap.put(KEYCODE_BACKSLASH, KEY_BACKWARD_SLASH);
keyMap.put(KEYCODE_SEMICOLON, KEY_SEMICOLON);
keyMap.put(KEYCODE_APOSTROPHE, KEY_DOUBLE_QUOTE);
keyMap.put(KEYCODE_COMMA, KEY_COMMA);
keyMap.put(KEYCODE_PERIOD, KEY_PERIOD);
keyMap.put(KEYCODE_SLASH, KEY_FORWARD_SLASH);
// Lock keys
keyMap.put(KEYCODE_NUM_LOCK, KEY_NUM_LOCK);
keyMap.put(KEYCODE_CAPS_LOCK, KEY_CAPS_LOCK);
keyMap.put(KEYCODE_SCROLL_LOCK, KEY_SCROLL_LOCK);
// Special keys
keyMap.put(KEYCODE_TAB, KEY_TAB);
keyMap.put(KEYCODE_BACK, KEY_BACKSPACE);
keyMap.put(KEYCODE_ENTER, KEY_ENTER);
keyMap.put(KEYCODE_SHIFT_LEFT, KEY_LEFT_SHIFT);
keyMap.put(KEYCODE_SHIFT_RIGHT, KEY_RIGHT_SHIFT);
keyMap.put(KEYCODE_CTRL_LEFT, KEY_LEFT_CTRL);
keyMap.put(KEYCODE_CTRL_RIGHT, KEY_RIGHT_CTRL);
keyMap.put(KEYCODE_ALT_LEFT, KEY_LEFT_ALT);
keyMap.put(KEYCODE_ALT_RIGHT, KEY_RIGHT_ALT);
keyMap.put(KEYCODE_INSERT, KEY_INSERT);
keyMap.put(KEYCODE_DEL, KEY_DELETE);
keyMap.put(KEYCODE_HOME, KEY_HOME);
keyMap.put(KEYCODE_PAGE_DOWN, KEY_PAGEDOWN);
keyMap.put(KEYCODE_PAGE_UP, KEY_PAGEUP);
// Keypad keys
keyMap.put(KEYCODE_NUMPAD_0, KEY_KP_0);
keyMap.put(KEYCODE_NUMPAD_1, KEY_KP_1);
keyMap.put(KEYCODE_NUMPAD_2, KEY_KP_2);
keyMap.put(KEYCODE_NUMPAD_3, KEY_KP_3);
keyMap.put(KEYCODE_NUMPAD_4, KEY_KP_4);
keyMap.put(KEYCODE_NUMPAD_5, KEY_KP_5);
keyMap.put(KEYCODE_NUMPAD_6, KEY_KP_6);
keyMap.put(KEYCODE_NUMPAD_7, KEY_KP_7);
keyMap.put(KEYCODE_NUMPAD_8, KEY_KP_8);
keyMap.put(KEYCODE_NUMPAD_9, KEY_KP_9);
keyMap.put(KEYCODE_NUMPAD_DIVIDE, KEY_KP_SLASH);
keyMap.put(KEYCODE_NUMPAD_MULTIPLY, KEY_KP_ASTERISK);
keyMap.put(KEYCODE_NUMPAD_SUBTRACT, KEY_KP_MINUS);
keyMap.put(KEYCODE_NUMPAD_ADD, KEY_KP_PLUS);
keyMap.put(KEYCODE_NUMPAD_ENTER, KEY_KP_ENTER);
keyMap.put(KEYCODE_NUMPAD_DOT, KEY_KP_PERIOD);
// Arrow keys
keyMap.put(KEYCODE_DPAD_UP, KEY_UP);
keyMap.put(KEYCODE_DPAD_DOWN, KEY_DOWN);
keyMap.put(KEYCODE_DPAD_LEFT, KEY_LEFT);
keyMap.put(KEYCODE_DPAD_RIGHT, KEY_RIGHT);
// Alphabet keys
keyMap.put(KEYCODE_A, KEY_A);
keyMap.put(KEYCODE_B, KEY_B);
keyMap.put(KEYCODE_C, KEY_C);
keyMap.put(KEYCODE_D, KEY_D);
keyMap.put(KEYCODE_E, KEY_E);
keyMap.put(KEYCODE_F, KEY_F);
keyMap.put(KEYCODE_G, KEY_G);
keyMap.put(KEYCODE_H, KEY_H);
keyMap.put(KEYCODE_I, KEY_I);
keyMap.put(KEYCODE_J, KEY_J);
keyMap.put(KEYCODE_K, KEY_K);
keyMap.put(KEYCODE_L, KEY_L);
keyMap.put(KEYCODE_M, KEY_M);
keyMap.put(KEYCODE_N, KEY_N);
keyMap.put(KEYCODE_O, KEY_O);
keyMap.put(KEYCODE_P, KEY_P);
keyMap.put(KEYCODE_Q, KEY_Q);
keyMap.put(KEYCODE_R, KEY_R);
keyMap.put(KEYCODE_S, KEY_S);
keyMap.put(KEYCODE_T, KEY_T);
keyMap.put(KEYCODE_U, KEY_U);
keyMap.put(KEYCODE_V, KEY_V);
keyMap.put(KEYCODE_W, KEY_W);
keyMap.put(KEYCODE_X, KEY_X);
keyMap.put(KEYCODE_Y, KEY_Y);
keyMap.put(KEYCODE_Z, KEY_Z);
keyMap.put(KEYCODE_SPACE, KEY_SPACE);
}
private int translateKeyCode(int nativeCode)
{
Integer code = keyMap.get(nativeCode);
return (code == null) ? 0 : code;
}
private boolean onKey(View v, int keyCode, KeyEvent event)
{
surfaceView.queueEvent(() -> postKeyEvent(translateKeyCode(keyCode), event.getAction() == ACTION_DOWN));
return true;
}
private boolean onTouch(View v, MotionEvent e)
{
final int action = e.getActionMasked();
switch (action)
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
{
final boolean down = action == ACTION_DOWN;
final float x = e.getX();
final float y = e.getY();
surfaceView.queueEvent(() -> postTouchEvent(FINGER_0, down, x, y));
break;
}
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_UP:
{
final int index = e.getActionIndex();
final int finger = index + 1;
if (finger < FINGER_1 || finger > FINGER_9)
break;
final float x = e.getX();
final float y = e.getY();
final boolean isDown = action == MotionEvent.ACTION_POINTER_DOWN;
surfaceView.queueEvent(() -> postTouchEvent(finger, isDown, x, y));
break;
}
case MotionEvent.ACTION_MOVE:
{
for (int i = 0; i < e.getPointerCount(); i++)
{
final int finger = i + 1;
if (finger < FINGER_0 || finger > FINGER_9)
break;
final float x = e.getX(i);
final float y = e.getY(i);
surfaceView.queueEvent(() -> postTouchEvent(finger, true, x, y));
}
for (int i = e.getPointerCount(); i < FINGER_9; i++)
{
final int finger = i + 1;
surfaceView.queueEvent(() -> postTouchEvent(finger, false, 0, 0));
}
break;
}
}
return true;
}
}
|
package com.opencms.template;
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
import com.opencms.file.*;
import com.opencms.core.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import com.opencms.launcher.*;
import org.apache.xerces.*;
import org.apache.xerces.dom.*;
import org.apache.xerces.parsers.*;
public abstract class A_CmsXmlContent implements I_CmsXmlContent, I_CmsLogChannels {
/** parameter types for XML node handling methods. */
public static final Class[] C_PARAMTYPES_HANDLING_METHODS
= new Class[] {Element.class, Object.class, Object.class};
/** parameter types for user methods called by METHOD tags */
public static final Class[] C_PARAMTYPES_USER_METHODS
= new Class[] {A_CmsObject.class, String.class, A_CmsXmlContent.class, Object.class};
/** The classname of the super XML content class */
public static final String C_MINIMUM_CLASSNAME = "com.opencms.template.A_CmsXmlContent";
/** Constant pathname, where to find templates */
public static final String C_TEMPLATEPATH = "/system/workplace/templates/";
/** Constant extension of the template-files. */
public static final String C_TEMPLATE_EXTENSION = "";
/** Error message for bad <code><PROCESS></code> tags */
public static final String C_ERR_NODATABLOCK = "? UNKNOWN DATABLOCK ";
/** A_CmsObject Object for accessing resources */
protected A_CmsObject m_cms;
/** All XML tags known by this class. */
protected Vector m_knownTags = new Vector();
/**
* This Hashtable contains some XML tags as keys
* and the corresponding methods as values.
* Used to pass to processNode() to read in
* include files and scan for datablocks.
*/
protected Hashtable m_firstRunTags = new Hashtable();
/**
* This Hashtable contains some XML tags as keys
* and the corresponding methods as values.
* Used to pass to processNode() before generating
* HTML output.
*/
protected Hashtable m_mainProcessTags = new Hashtable();
/** constant for registering handling tags */
protected final static int C_REGISTER_FIRST_RUN = 1;
/** constant for registering handling tags */
protected final static int C_REGISTER_MAIN_RUN = 2;
/** Boolean for additional debug output control */
private static final boolean C_DEBUG = false;
/** DOM representaion of the template content. */
private Document m_content;
/** Filename this template was read from */
private String m_filename;
/** All datablocks in DOM format */
private Hashtable m_blocks = new Hashtable();
/** Reference All included A_CmsXmlContents */
private Vector m_includedTemplates = new Vector();
/** Cache for parsed documents */
static private Hashtable m_filecache = new Hashtable();
/** XML parser */
private static I_CmsXmlParser parser = new CmsXmlXercesParser();
/** Constructor for creating a new instance of this class */
public A_CmsXmlContent() {
registerAllTags();
}
/**
* Initialize the XML content class.
* Load and parse the content of the given CmsFile object.
* <P>
* If a previously cached parsed content exists, it will be re-used.
* <P>
* If no absolute file name ist given,
* template files will be searched a hierachical order using
* <code>lookupAbsoluteFilename</code>.
*
* @param cms A_CmsObject Object for accessing resources.
* @param file CmsFile object of the file to be loaded and parsed.
* @exception CmsException
* @see #lookupAbsoluteFilename
*/
public void init(A_CmsObject cms, String filename) throws CmsException {
if(! filename.startsWith("/")) {
// this is no absolute filename.
filename = lookupAbsoluteFilename(cms, filename, this);
}
String currentProject = cms.getRequestContext().currentProject().getName();
Document parsedContent = null;
m_cms = cms;
m_filename = filename;
parsedContent = loadCachedDocument(filename);
if(parsedContent == null) {
CmsFile file = cms.readFile(filename);
parsedContent = parse(new String(file.getContents()));
m_filecache.put(currentProject + ":" + filename, parsedContent.cloneNode(true));
} else {
// File was found in cache.
// We have to read the file header to check access rights.
cms.readFileHeader(filename);
}
init(cms, parsedContent, filename);
}
/**
* Initialize the XML content class.
* Load and parse the content of the given CmsFile object.
* @param cms A_CmsObject Object for accessing resources.
* @param file CmsFile object of the file to be loaded and parsed.
* @exception CmsException
*/
public void init(A_CmsObject cms, CmsFile file) throws CmsException {
String filename = file.getAbsolutePath();
String currentProject = cms.getRequestContext().currentProject().getName();
Document parsedContent = null;
m_cms = cms;
m_filename = filename;
parsedContent = loadCachedDocument(filename);
if(parsedContent == null) {
byte[] fileContent = file.getContents();
if(fileContent == null || "".equals(fileContent)) {
// The file content is empty. Possibly the file object is only
// a file header. Re-read the file object and try again
file = cms.readFile(filename);
fileContent = file.getContents();
}
if(fileContent == null || "".equals(fileContent)) {
// The file content is still emtpy.
// Start with an empty XML document.
try {
parsedContent = getXmlParser().createEmptyDocument(getXmlDocumentTagName());
} catch(Exception e) {
throwException("Could not initialize now XML document " + filename + ". " + e, CmsException.C_XML_PARSING_ERROR );
}
} else {
parsedContent = parse(new String(file.getContents()));
}
m_filecache.put(currentProject + ":" + filename, parsedContent.cloneNode(true));
}
init(cms, parsedContent, filename);
}
/**
* Initialize the class with the given parsed XML DOM document.
* @param cms A_CmsObject Object for accessing system resources.
* @param document DOM document object containing the parsed XML file.
* @param filename OpenCms filename of the XML file.
* @exception CmsException
*/
public void init(A_CmsObject cms, Document content, String filename) throws CmsException {
m_cms = cms;
m_content = content;
m_filename = filename;
// First check the document tag. Is this the right document type?
Element docRootElement = m_content.getDocumentElement();
String docRootElementName = docRootElement.getNodeName().toLowerCase();
if(! docRootElementName.equals(getXmlDocumentTagName().toLowerCase())) {
// Hey! This is a wrong XML document!
// We will throw an execption and the document away :-)
removeFromFileCache();
m_content = null;
String errorMessage = "XML document " + getAbsoluteFilename() + " is not of the expected type. This document is \""
+ docRootElementName + "\", but it should be \"" + getXmlDocumentTagName() + "\" (" + getContentDescription() + ").";
throwException(errorMessage, CmsException.C_XML_WRONG_CONTENT_TYPE);
}
// OK. Document tag is fine. Now get the DATA tags and collect them
// in a Hashtable (still in DOM representation!)
try {
processNode(m_content, m_firstRunTags,
A_CmsXmlContent.class.getDeclaredMethod("handleDataTag", C_PARAMTYPES_HANDLING_METHODS),
null, null);
} catch(CmsException e) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "Error while scanning for DATA and INCLUDE tags in file " + getAbsoluteFilename() + ".");
}
throw e;
} catch(NoSuchMethodException e2) {
String errorMessage = "XML tag process method \"handleDataTag\" could not be found";
throwException(errorMessage, CmsException.C_XML_NO_PROCESS_METHOD);
}
}
/**
* Create a new CmsFile object containing an empty XML file of the
* current content type.
* The String returned by <code>getXmlDocumentTagName()</code>
* will be used to build the XML document element.
* @param cms Current cms object used for accessing system resources.
* @param filename Name of the file to be created.
* @param documentType Document type of the new file.
* @exception CmsException if no absolute filename is given or write access failed.
*/
public void createNewFile(A_CmsObject cms, String filename, String documentType) throws CmsException {
if(! filename.startsWith("/")) {
// this is no absolute filename.
this.throwException("Cannot create new file. Bad name.", CmsException.C_BAD_NAME);
}
int slashIndex = filename.lastIndexOf("/") + 1;
String folder = filename.substring(0, slashIndex);
String file = filename.substring(slashIndex);
cms.createFile(folder, file, "".getBytes(), documentType);
cms.lockResource(filename);
m_cms = cms;
m_filename = filename;
try {
m_content = parser.createEmptyDocument(getXmlDocumentTagName());
} catch(Exception e) {
e.printStackTrace();
throwException("Cannot create empty XML document for file " + m_filename + ". ", CmsException.C_XML_PARSING_ERROR);
}
write();
}
/**
* Used by the init method to search a template file if only a filename
* is given instead of a CmsFile Object.
* Previously cached documents will be considered.
* <P>
* Template files will be searched in the following hierachical order:
* <UL>
* <LI> (template path)/(full classname).TemplateName.(Extension) </LI>
* <LI> (template path)/(parent class).TemplateName.(Extension) </LI>
* <LI> ... </LI>
* <LI> (template path)/TemplateName.(Extension) </LI>
* </UL>
* <P>
* The starting classname is determined by the class of the given <code>requestingObject</class>
*
* @param cms A_CmsObject Object for accessing system resources.
* @param filename Template file name to be loaded.
* @param requestingObject Object whose class hierarchy should be used for resolving file names.
* @return absolute path of the filename.
* @exception CmsException
*/
public static String lookupAbsoluteFilename(A_CmsObject cms, String filename, Object requestingObject) throws CmsException {
Class actualClass = requestingObject.getClass();
A_CmsResource retValue = null;
String completeFilename = null;
// we use this Vector for storing all tried filenames.
// so we can give detailled error messages if the
// template file was not found.
Vector checkedFilenames = new Vector();
if(filename.startsWith("/")) {
completeFilename = filename;
} else {
// Now start the loop to search
while(retValue == null) {
completeFilename = C_TEMPLATEPATH + actualClass.getName() + "." + filename + C_TEMPLATE_EXTENSION;
checkedFilenames.addElement(completeFilename);
retValue = null;
try {
retValue = cms.readFileHeader(completeFilename);
} catch(Exception e) {
retValue=null;
}
//retValue = readTemplateFile(cms, completeFilename);
actualClass = actualClass.getSuperclass();
if(actualClass.getName().equals(C_MINIMUM_CLASSNAME)){
if(retValue == null) {
// last chance to get the filename
completeFilename = C_TEMPLATEPATH + filename + C_TEMPLATE_EXTENSION;
checkedFilenames.addElement(completeFilename);
try {
retValue = cms.readFileHeader(completeFilename);
} catch(Exception e) {
retValue=null;
}
break;
}
}
}
if(retValue == null) {
Enumeration checkedEnum = checkedFilenames.elements();
if(A_OpenCms.isLogging()) {
while(checkedEnum.hasMoreElements()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "[A_CmsXmlContent] checked: " + (String)checkedEnum.nextElement());
}
}
throw new CmsException("Cannot find template file for request \"" + filename + "\". ", CmsException.C_NOT_FOUND);
}
}
return completeFilename;
}
/**
* Parses the given file and stores it in the internal list of included files and
* appends the relevant data structures of the new file to its own structures.
*
* @param include Filename of the XML file to be included
* @exception CmsException
*/
public A_CmsXmlContent readIncludeFile(String filename) throws CmsException {
A_CmsXmlContent include = null;
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Including File: " + filename);
}
try {
include = (A_CmsXmlContent)getClass().newInstance();
include.init(m_cms, filename);
} catch(Exception e) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "while include file: " + e);
}
}
readIncludeFile(include);
return include;
}
/**
* Read the datablocks of the given content file and include them
* into the own Hashtable of datablocks.
*
* @param include completely initialized A_CmsXmlObject to be included
* @exception CmsExeption
*/
public void readIncludeFile(A_CmsXmlContent include) throws CmsException {
m_includedTemplates.addElement(include);
m_blocks = concatData(m_blocks, include.getAllData());
}
/**
* Prints the XML parsed content of this template file
* to the given Writer.
*
* @param out Writer to print to.
*/
public void getXmlText(Writer out) {
parser.getXmlText(m_content, out);
}
/**
* Prints the XML parsed content of the given Node and
* its subnodes to the given Writer.
*
* @param out Writer to print to.
* @param n Node that should be printed.
*/
public void getXmlText(Writer out, Node n) {
Document tempDoc = (Document)m_content.cloneNode(false);
tempDoc.appendChild(parser.importNode(tempDoc, n));
parser.getXmlText(tempDoc, out);
}
/**
* Prints the XML parsed content to a String
* @return String with XML content
*/
public String getXmlText() {
StringWriter writer = new StringWriter();
getXmlText(writer);
return writer.toString();
}
/**
* Prints the XML parsed content of a given node and
* its subnodes to a String
* @param n Node that should be printed.
* @return String with XML content
*/
public String getXmlText(Node n) {
StringWriter writer = new StringWriter();
getXmlText(writer, n);
return writer.toString();
}
/**
* Gets the absolute filename of the XML file represented by this content class
* @return Absolute filename
*/
public String getAbsoluteFilename() {
return m_filename;
}
/**
* Gets a short filename (without path) of the XML file represented by this content class
* of the template file.
* @return filename
*/
public String getFilename() {
return m_filename.substring(m_filename.lastIndexOf("/")+1);
}
/**
* Writes the XML document back to the OpenCms system.
* @exception CmsException
*/
public void write() throws CmsException {
// Get the XML content as String
StringWriter writer = new StringWriter();
getXmlText(writer);
byte[] xmlContent = writer.toString().getBytes();
// Get the CmsFile object to write to
String filename = getAbsoluteFilename();
CmsFile file = m_cms.readFile(filename);
// Set the new content and write the file
file.setContents(xmlContent);
m_cms.writeFile(file);
// update the internal parsed content cache with the new file data.
String currentProject = m_cms.getRequestContext().currentProject().getName();
m_filecache.put(currentProject + ":" + filename, m_content.cloneNode(true));
}
/**
* Deletes this object from the internal XML file cache
*/
public void removeFromFileCache() {
String currentProject = m_cms.getRequestContext().currentProject().getName();
m_filecache.remove(currentProject + ":" + getAbsoluteFilename());
}
/**
* Deletes all files from the file cache.
*/
public static void clearFileCache() {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_INFO, "[A_CmsXmlContent] clearing XML file cache.");
}
m_filecache.clear();
}
/**
* Deletes the file with the given key from the file cache.
* If no such file exists nothing happens.
* @param key Key of the template file to be removed from the cache.
*/
public static void clearFileCache(String key) {
m_filecache.remove(key);
}
/**
* Deletes the file represented by the given A_CmsXmlContent from
* the file cache.
* @param doc A_CmsXmlContent representing the XML file to be deleted.
*/
public static void clearFileCache(A_CmsXmlContent doc) {
if(doc != null) {
String currentProject = doc.m_cms.getRequestContext().currentUser().getName();
m_filecache.remove(currentProject + ":" + doc.getAbsoluteFilename());
}
}
/**
* Gets the currently used XML Parser.
* @return currently used parser.
*/
public static I_CmsXmlParser getXmlParser() {
return parser;
}
/**
* This method should be implemented by every extending class.
* It returns the name of the XML document tag to scan for.
* @return name of the XML document tag.
*/
abstract public String getXmlDocumentTagName();
/**
* This method should be implemented by every extending class.
* It returns a short description of the content definition type
* (e.g. "OpenCms news article").
* @return content description.
*/
abstract public String getContentDescription();
/**
* Creates a clone of this object.
* @return cloned object.
* @exception CloneNotSupportedException
*/
public Object clone() throws CloneNotSupportedException {
try {
A_CmsXmlContent newDoc = (A_CmsXmlContent)getClass().newInstance();
newDoc.init(m_cms, (Document)m_content.cloneNode(true), m_filename);
return newDoc;
} catch(Exception e) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Error while trying to clone object.");
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + e);
}
throw new CloneNotSupportedException(e.toString());
}
}
/**
* Registeres a tagname together with a corresponding method for processing
* with processNode. Tags can be registered for two different runs of the processNode
* method. This can be selected by the runSelector.
* <P>
* C_REGISTER_FIRST_RUN registeres the given tag for the first
* run of processNode, just after parsing a XML document. The basic functionality
* of this class uses this run to scan for INCLUDE and DATA tags.
* <P>
* C_REGISTER_MAIN_RUN registeres the given tag for the main run of processNode.
* This will be initiated by getProcessedData(), processDocument() or any
* PROCESS tag.
*
* @param tagname Tag name to register.
* @param c Class containing the handling method.
* @param methodName Name of the method that should handle a occurance of tag "tagname".
* @param runSelector see description above.
*/
public void registerTag(String tagname, Class c, String methodName, int runSelector) {
Hashtable selectedRun = null;
switch(runSelector) {
case C_REGISTER_FIRST_RUN:
selectedRun = m_firstRunTags;
break;
case C_REGISTER_MAIN_RUN:
selectedRun = m_mainProcessTags;
break;
}
try {
selectedRun.put(tagname.toLowerCase(), c.getDeclaredMethod(methodName, C_PARAMTYPES_HANDLING_METHODS));
} catch(Exception e) {
System.err.println(e);
}
registerTag(tagname);
}
/**
* Registers the given tag to be "known" by the system.
* So this tag will not be handled by the default method of processNode.
* Under normal circumstances this feature will only be used for
* the XML document tag.
* @param tagname Tag name to register.
*/
public void registerTag(String tagname) {
if(!(m_knownTags.contains(tagname.toLowerCase()))) {
m_knownTags.addElement(tagname.toLowerCase());
}
}
/**
* Gets a string representation of this object.
* @return String representation of this object.
*/
public String toString() {
StringBuffer output = new StringBuffer();
output.append("[XML file]: ");
output.append(getFilename());
output.append(", content type: ");
output.append(getContentDescription());
return output.toString();
}
/**
* Main processing funtion for the whole XML document.
*
* @see #processNode
* @param keys Hashtable with XML tags to look for and corresponding methods.
* @param defaultMethod Method to be called if the tag is unknown.
* @param callingObject Reference to the object requesting the node processing.
* @param userObj Customizable user object that will be passed through to handling and user methods.
* @exception CmsException
*/
protected void processDocument(Hashtable keys, Method defaultMethod, Object callingObject, Object userObj)
throws CmsException {
processNode(m_content.getDocumentElement(), keys, defaultMethod, callingObject, userObj);
}
/**
* Universal main processing function for parsed XML templates.
* The given node is processed by a tree walk.
* <P>
* Every XML tag will be looked up in the Hashtable "keys".
* If a corresponding entry is found, the tag will be handled
* by the corresponding function returned from the Hashtable.
* <P>
* If an unknown tag is detected the method defaultMethod is called
* instead. Is defaultMethod == null nothing will be done with unknown tags.
* <P>
* The invoked handling methods are allowed to return null or objects
* of the type String, Node, Integer or byte[].
* If the return value is null, nothing happens. In all other cases
* the handled node in the tree will be replaced by a new node.
* The value of this new node depends on the type of the returned value.
*
* @param n Node with its subnodes to process
* @param keys Hashtable with XML tags to look for and corresponding methods.
* @param defaultMethod Method to be called if the tag is unknown.
* @param callingObject Reference to the Object that requested the node processing.
* @param userObj Customizable user object that will be passed to handling and user methods.
* @exception CmsException
*/
protected void processNode(Node n, Hashtable keys, Method defaultMethod,
Object callingObject, Object userObj) throws CmsException {
// Node currently processed
Node child = null;
// Name of the currently processed child
String childName = null;
// Node nextchild needed for the walk through the tree
Node nextchild = null;
// List of new Nodes the current node should be replaced with
NodeList newnodes = null;
// single new Node from newnodes
Node insert = null;
// tag processing method to be called for the current Node
Method callMethod = null;
// Object returned by the tag processing methods
Object methodResult = null;
// only start if there is something to process
if(n != null && n.hasChildNodes()) {
child = n.getFirstChild();
while(child != null) {
childName = child.getNodeName().toLowerCase();
// Get the next node in the tree first
nextchild = treeWalker(child);
// Only look for element nodes
// all other nodes are not very interesting
if(child.getNodeType()==Node.ELEMENT_NODE) {
newnodes = null;
callMethod = null;
if(keys.containsKey(childName)) {
// name of this element found in keys Hashtable
callMethod = (Method)keys.get(childName);
} else if (!m_knownTags.contains(childName)){
// name was not found
// and even name is not known as tag
callMethod = defaultMethod;
}
if(callMethod != null) {
methodResult = null;
try {
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, "<" + childName + "> tag found. Value: " + child.getNodeValue());
A_OpenCms.log(C_OPENCMS_DEBUG, "Tag will be handled by method [" + callMethod.getName() + "]. Invoking method NOW.");
}
// now invoke the tag processing method.
methodResult = callMethod.invoke(this, new Object[] {child, callingObject, userObj});
} catch (Exception e) {
if(e instanceof InvocationTargetException) {
Throwable thrown = ((InvocationTargetException)e).getTargetException();
// if the method has thrown a cms exception then
// throw it again
if(thrown instanceof CmsException) {
throw (CmsException)thrown;
} else {
thrown.printStackTrace();
throwException("processNode received an exception while handling XML tag \""
+ childName + "\" by \"" + callMethod.getName() + "\" for file "
+ getFilename() + ": " + e, CmsException.C_XML_PROCESS_ERROR);
}
} else {
throwException("processNode could not invoke the XML tag handling method "
+ callMethod.getName() + "\" for file " + getFilename() + ": "
+ e, CmsException.C_XML_PROCESS_ERROR);
}
}
// Inspect the type of the method return value
// Currently NodeList, String and Integer are
// recognized. All other types will be ignored.
if(methodResult == null) {
newnodes = null;
} else if(methodResult instanceof NodeList) {
newnodes = (NodeList)methodResult;
} else if(methodResult instanceof String) {
newnodes = stringToNodeList((String)methodResult);
} else if(methodResult instanceof Integer) {
newnodes = stringToNodeList(((Integer)methodResult).toString());
} else if(methodResult instanceof byte[]) {
newnodes = stringToNodeList(new String((byte[])methodResult));
} else {
// Type not recognized.
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, "Return type of method " + callMethod.getName()
+ " not recognized. Cannot insert value.");
}
newnodes = null;
}
// the list of nodes to be inserted could be printed out here.
// uncomment the following to activate this feature.
// printNodeList(newnodes);
if(newnodes != null) {
// the called method returned a valid result.
// we have do remove the old element from the tree
// and replace it by the new nodes.
// WARNING! Do not remove any subchilds from the old
// element. There could be links to the subchilds
// in our Hashtables (e.g. for datablocks).
// Only remove the child itself from the tree!
int numNewChilds = newnodes.getLength();
if(numNewChilds > 0) {
// there are new childs.
// so we can replace the old element
for(int j=0; j<numNewChilds; j++) {
//insert = parser.importNode(m_content, newnodes.item(j));
insert = parser.importNode(child.getOwnerDocument(), newnodes.item(j));
if(j==0) {
nextchild = insert;
}
//A_OpenCms.log(c_OPENCMS_DEBUG, "trying to add node " + newnodes.item(j));
child.getParentNode().insertBefore(insert, child);
//A_OpenCms.log(c_OPENCMS_DEBUG, "Node " + newnodes.item(j) + " added.");
}
} else {
// the list of the new childs is empty.
// so we have to re-calculate the next node
// in the tree since the old nextchild will be deleted
// been deleted.
nextchild = treeWalkerWidth(child);
}
// now delete the old child and get the next one.
child.getParentNode().removeChild(child);
}
}
}
child = nextchild;
}
}
}
/**
* Gets the XML parsed content of this template file as a DOM document.
* <P>
* <em>WARNING: The returned value is the original DOM document, not a clone.
* Any changes will take effect to the behaviour of this class.
* Especially datablocks are concerned by this!</em>
*
* @return the content of this template file.
*/
protected Document getXmlDocument() {
return m_content;
}
/**
* Checks if this Template owns a datablock with the given key.
* @param key Datablock key to be checked.
* @return true if a datablock is found, false otherwise.
*/
protected boolean hasData(String key) {
return m_blocks.containsKey(key.toLowerCase());
}
/**
* Gets a complete datablock from the datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @return Complete DOM element of the datablock for the given key
* or null if no datablock is found for this key.
*/
protected Element getData(String tag) throws CmsException {
Object result = m_blocks.get(tag.toLowerCase());
if(result == null) {
String errorMessage = "Unknown Datablock " + tag + " requested.";
throwException(errorMessage, CmsException.C_XML_UNKNOWN_DATA);
} else if(!(result instanceof Element)) {
String errorMessage = "Unexpected object returned as datablock. Requested Tagname: "
+ tag + ". Returned object: " + result.getClass().getName() + ".";
throwException(errorMessage, CmsException.C_XML_CORRUPT_INTERNAL_STRUCTURE);
}
return (Element)m_blocks.get(tag.toLowerCase());
}
/**
* Gets the text and CDATA content of a datablock from the
* datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @return Datablock content for the given key or null if no datablock
* is found for this key.
*/
protected String getDataValue(String tag) throws CmsException {
Element dataElement = getData(tag);
return getTagValue(dataElement);
}
/**
* Gets a processed datablock from the datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected Element getProcessedData(String tag) throws CmsException {
return getProcessedData(tag, null, null);
}
/**
* Gets a processed datablock from the datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @param callingObject Object that should be used to look up user methods.
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected Element getProcessedData(String tag, Object callingObject) throws CmsException {
return getProcessedData(tag, callingObject, null);
}
/**
* Gets a processed datablock from the datablock hashtable.
* <P>
* The userObj Object is passed to all called user methods.
* By using this, the initiating class can pass customized data to its methods.
*
* @param tag Key for the datablocks hashtable.
* @param callingObject Object that should be used to look up user methods.
* @param userObj any object that should be passed to user methods
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected Element getProcessedData(String tag, Object callingObject, Object userObj)
throws CmsException {
Element dBlock = (Element)getData(tag).cloneNode(true);
processNode(dBlock, m_mainProcessTags, null, callingObject, userObj);
return dBlock;
}
/**
* Gets the text and CDATA content of a processed datablock from the
* datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected String getProcessedDataValue(String tag) throws CmsException {
Element data = getProcessedData(tag);
return getTagValue(data);
}
/**
* Gets the text and CDATA content of a processed datablock from the
* datablock hashtable.
*
* @param tag Key for the datablocks hashtable.
* @param callingObject Object that should be used to look up user methods.
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected String getProcessedDataValue(String tag, Object callingObject) throws CmsException {
Element data = getProcessedData(tag, callingObject);
return getTagValue(data);
}
/**
* Gets the text and CDATA content of a processed datablock from the
* datablock hashtable.
* <P>
* The userObj Object is passed to all called user methods.
* By using this, the initiating class can pass customized data to its methods.
*
* @param tag Key for the datablocks hashtable.
* @param callingObject Object that should be used to look up user methods.
* @param userObj any object that should be passed to user methods
* @return Processed datablock for the given key.
* @exception CmsException
*/
protected String getProcessedDataValue(String tag, Object callingObject, Object userObj)
throws CmsException {
Element data = getProcessedData(tag, callingObject, userObj);
return getTagValue(data);
}
/**
* Gets all datablocks (the datablock hashtable).
* @return Hashtable with all datablocks.
*/
protected Hashtable getAllData() {
return m_blocks;
}
/**
* Fast method to replace a datablock.
* <P>
* <b>USE WITH CARE!</b>
* <P>
* Using this method only if
* <ul>
* <li>The tag name is given in lowercase</li>
* <li>The datablock already exists (it may be empty)</li>
* <li>Neither tag nor data are <code>null</code></li>
* <li>You are sure, there will occure no errors</li>
* </ul>
*
* @param tag Key for this datablock.
* @param data String to be put in the datablock.
*/
protected void fastSetData(String tag, String data) {
Element originalBlock = (Element)(m_blocks.get(tag));
while(originalBlock.hasChildNodes()) {
originalBlock.removeChild(originalBlock.getFirstChild());
}
originalBlock.appendChild(m_content.createTextNode(data));
}
/**
* Creates a datablock consisting of a single TextNode containing
* data and stores this block into the datablock-hashtable.
*
* @param tag Key for this datablock.
* @param data String to be put in the datablock.
*/
protected void setData(String tag, String data) {
// create new XML Element to store the data
//Element newElement = m_content.createElement("DATA");
String attribute = tag;
int dotIndex = tag.lastIndexOf(".");
if(dotIndex != -1) {
attribute = attribute.substring(dotIndex + 1);
}
//newElement.setAttribute("name", attribute);
Element newElement = m_content.createElement(attribute);
if(data == null || "".equals(data)) {
// empty string or null are given.
// put an empty datablock without any text nodes.
setData(tag, newElement);
} else {
// Fine. String is not empty.
// So we can add a new text node containig the string data.
// Leading spaces are removed before creating the text node.
newElement.appendChild(m_content.createTextNode(data.trim()));
setData(tag, newElement);
}
}
/**
* Stores a given datablock element in the datablock hashtable.
*
* @param tag Key for this datablock.
* @param data DOM element node for this datablock.
*/
protected void setData(String tag, Element data) {
// If we got a null data, give this request to setData(Strig, String)
// to create a new text node.
if(data==null) {
setData(tag, "");
} else {
// Now we can be sure to have a correct Element
tag = tag.toLowerCase();
Element newElement = (Element)data.cloneNode(true);
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Putting datablock " + tag + " into internal Hashtable.");
}
if (! (m_blocks.containsKey(tag))) {
// This is a brand new datablock. It can be inserted directly.
//m_blocks.put(tag, newElement);
insertNewDatablock(tag, newElement);
} else {
// datablock existed before, so the childs of the old
// one can be replaced.
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Datablock existed before. Replacing.");
}
// Look up the old datablock and remove all its childs.
Element originalBlock = (Element)(m_blocks.get(tag));
while(originalBlock.hasChildNodes()) {
originalBlock.removeChild(originalBlock.getFirstChild());
}
// And now add all childs of the new node
NodeList newNodes = data.getChildNodes();
int len = newNodes.getLength();
for(int i=0; i<len; i++) {
Node newElement2 = (Node)newNodes.item(i).cloneNode(true);
originalBlock.appendChild(parser.importNode(originalBlock.getOwnerDocument(), newElement2));
}
}
}
}
/**
* Remove a datablock from the internal hashtable and
* from the XML document
* @param tag Key of the datablock to delete.
*/
protected void removeData(String tag) {
Element e = (Element)m_blocks.get(tag.toLowerCase());
if(e != null) {
m_blocks.remove(tag.toLowerCase());
Element parent = (Element)e.getParentNode();
if(parent != null) {
parent.removeChild(e);
}
}
}
/**
* Calls a user method in the object callingObject.
* Every user method has to user the parameter types defined in
* C_PARAMTYPES_USER_METHODS to be recognized by this method.
*
* @see #C_PARAMTYPES_USER_METHODS
* @param methodName Name of the method to be called.
* @param parameter Additional parameter passed to the method.
* @param callingObject Reference to the object containing the called method.
* @param userObj Customizable user object that will be passed through to the user method.
* @exception CmsException
*/
protected Object callUserMethod(String methodName, String parameter, Object callingObject, Object userObj)
throws CmsException {
Object[] params = new Object[] {m_cms, parameter, this, userObj};
Object result = null;
// Check if the user selected a object where to look for the user method.
if(callingObject == null) {
throwException("You are trying to call the user method \"" + methodName + "\" without giving an object containing this method. "
+ "Please select a callingObject in your getProcessedData or getProcessedDataValue call.", CmsException.C_XML_NO_USER_METHOD);
}
// OK. We have a calling object. Now try to invoke the method
try {
// try to invoke the method 'methodName'
result = getUserMethod(methodName, callingObject).invoke(callingObject, params);
} catch(NoSuchMethodException exc) {
throwException("User method " + methodName + " was not found in class "
+ callingObject.getClass().getName() + ".", CmsException.C_XML_NO_USER_METHOD);
} catch(InvocationTargetException targetEx) {
// the method could be invoked, but throwed a exception
// itself. Get this exception and throw it again.
Throwable e = targetEx.getTargetException();
if(!(e instanceof CmsException)) {
// Only print an error if this is NO CmsException
throwException("User method " + methodName + " throwed an exception. " + e, CmsException.C_UNKNOWN_EXCEPTION);
} else {
// This is a CmsException
// Error printing should be done previously.
throw (CmsException)e;
}
} catch(Exception exc2) {
throwException("User method " + methodName + " was found but could not be invoked. " + exc2, CmsException.C_XML_NO_USER_METHOD);
}
if((result != null) && (! (result instanceof String || result instanceof Integer
|| result instanceof NodeList || result instanceof byte[]))) {
throwException("User method " + methodName + " in class " + callingObject.getClass().getName()
+ " returned an unsupported Object: " + result.getClass().getName(), CmsException.C_XML_PROCESS_ERROR);
}
return(result);
}
/**
* Reads all text or CDATA values from the given XML element,
* e.g. <code><ELEMENT>foo blah <![CDATA[<H1>Hello</H1>]]></ELEMENT></code>.
*
* @param n Element that should be read out.
* @return Concatenated string of all text and CDATA nodes or <code>null</code>
* if no nodes were found.
*/
protected String getTagValue(Element n) {
StringBuffer result = new StringBuffer();
if(n != null) {
NodeList childNodes = n.getChildNodes();
Node child = null;
int numchilds = childNodes.getLength();
if(childNodes != null) {
for(int i=0; i<numchilds; i++) {
child = childNodes.item(i);
if(child.getNodeType() == n.TEXT_NODE || child.getNodeType() == n.CDATA_SECTION_NODE) {
result.append(child.getNodeValue());
}
}
}
}
return result.toString();
}
/**
* Help method to print nice classnames in error messages
* @return class name in [ClassName] format
*/
protected String getClassName() {
String name = getClass().getName();
return "[" + name.substring(name.lastIndexOf(".") + 1) + "] ";
}
/**
* Help method to walk through the DOM document tree.
* First it will be looked for children of the given node.
* If there are no children, the siblings and the siblings of our parents
* are examined. This will be done by calling treeWalkerWidth.
* @param n Node representing the actual position in the tree
* @return next node
*/
protected Node treeWalker(Node n) {
Node nextnode = null;
if(n.hasChildNodes()) {
// child has child notes itself
// process these first in the next loop
nextnode = n.getFirstChild();
} else {
// child has no subchild.
// so we take the next sibling
nextnode = treeWalkerWidth(n);
}
return nextnode;
}
/**
* Help method to walk through the DOM document tree by a
* width-first-order.
* @param n Node representing the actual position in the tree
* @return next node
*/
protected Node treeWalkerWidth(Node n) {
Node nextnode = null;
Node parent = null;
nextnode = n.getNextSibling();
parent = n.getParentNode();
while(nextnode == null && parent != null) {
// child has sibling
// last chance: we take our parent's sibling
// (or our grandparent's sibling...)
nextnode = parent.getNextSibling();
parent = parent.getParentNode();
}
return nextnode;
}
/**
* Help method that handles any occuring exception by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the type "unknown".
* @param errorMessage String with the error message to be printed.
* @exception CmsException
*/
protected void throwException(String errorMessage) throws CmsException {
throwException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION);
}
/**
* Help method that handles any occuring exception by writing
* an error message to the OpenCms logfile and throwing a
* CmsException of the given type.
* @param errorMessage String with the error message to be printed.
* @param type Type of the exception to be thrown.
* @exception CmsException
*/
protected void throwException(String errorMessage, int type) throws CmsException {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + errorMessage);
} throw new CmsException(errorMessage, type);
}
/**
* Starts the XML parser with the content of the given CmsFile object.
* After parsing the document it is scanned for INCLUDE and DATA tags
* by calling processNode with m_firstRunParameters.
*
* @param content String to be parsed
* @return Parsed DOM document.
* @see #processNode
* @see #firstRunParameters
*/
private Document parse(String content) throws CmsException {
Document parsedDoc = null;
StringReader reader = new StringReader(content);
// First parse the String for XML Tags and
// get a DOM representation of the document
try {
parsedDoc = parser.parse(reader);
} catch(Exception e) {
// Error while parsing the document.
// there ist nothing to do, we cannot go on.
// throws exception.
String errorMessage = "Cannot parse XML file \"" + getAbsoluteFilename() + "\". " + e;
throwException(errorMessage, CmsException.C_XML_PARSING_ERROR);
}
if(parsedDoc == null) {
String errorMessage = "Unknown error. Parsed DOM document is null.";
throwException(errorMessage, CmsException.C_XML_PARSING_ERROR);
}
parsedDoc.getDocumentElement().normalize();
// Delete all unnecessary text nodes from the tree.
// These nodes could cause errors when serializing this document otherwise
Node loop = parsedDoc.getDocumentElement();
while(loop != null) {
Node next = treeWalker(loop);
if(loop.getNodeType() == loop.TEXT_NODE) {
Node leftSibling = loop.getPreviousSibling();
Node rightSibling = loop.getNextSibling();
if(leftSibling == null || rightSibling == null ||
(leftSibling.getNodeType() == loop.ELEMENT_NODE && rightSibling.getNodeType() == loop.ELEMENT_NODE)) {
if("".equals(loop.getNodeValue().trim())) {
loop.getParentNode().removeChild(loop);
}
}
}
loop = next;
}
return parsedDoc;
}
/**
* Internal method registering all special tags relevant for the basic functionality of
* this abstract class.
* <P>
* OpenCms special tags are:
* <UL>
* <LI><CODE>INCLUDE: </CODE> used to include other XML files</LI>
* <LI><CODE>DATA: </CODE> used to define a datablock that can be handled
* by getData or processed by getProcessedData or <code>PROCESS</CODE></LI>
* <LI><CODE>PROCESS: </CODE> used to insert earlier or external defined datablocks</LI>
* <LI><CODE>METHOD: </CODE> used to call customized methods in the initiating user object</LI>
* </UL>
* All unknown tags will be treated as a shortcut for <code><DATA name="..."></code>.
*/
private void registerAllTags() {
// register tags for scanning "INCLUDE" and "DATA"
registerTag("INCLUDE", A_CmsXmlContent.class, "handleIncludeTag", C_REGISTER_FIRST_RUN);
registerTag("DATA", A_CmsXmlContent.class, "handleDataTag", C_REGISTER_FIRST_RUN);
// register tags for preparing HTML output
registerTag("METHOD", A_CmsXmlContent.class, "handleMethodTag", C_REGISTER_MAIN_RUN);
registerTag("PROCESS", A_CmsXmlContent.class, "handleProcessTag", C_REGISTER_MAIN_RUN);
registerTag("INCLUDE", A_CmsXmlContent.class, "replaceTagByComment", C_REGISTER_MAIN_RUN);
registerTag("DATA", A_CmsXmlContent.class, "replaceTagByComment", C_REGISTER_MAIN_RUN);
registerTag(getXmlDocumentTagName());
}
/**
* Handling of "INCLUDE" tags.
* @param n XML element containing the <code><INCLUDE></code> tag.
* @param callingObject Reference to the object requesting the node processing.
* @param userObj Customizable user object that will be passed through to handling and user methods.
*/
private Object handleIncludeTag(Element n, Object callingObject, Object userObj) throws CmsException {
A_CmsXmlContent include = null;
String tagcontent = getTagValue(n);
include = readIncludeFile(tagcontent);
return include.getXmlDocument().getDocumentElement().getChildNodes();
}
/**
* Handling of "DATA" tags and unknown tags.
* A reference to each data tag ist stored in an internal hashtable with
* the name of the datablock as key.
* Nested datablocks are stored with names like outername.innername
*
* @param n XML element containing the <code><DATA></code> tag.
* @param callingObject Reference to the object requesting the node processing.
* @param userObj Customizable user object that will be passed through to handling and user methods.
*/
private void handleDataTag(Element n, Object callingObject, Object userObj) {
String blockname;
String bestFit = null;
String parentname = null;
Node parent = n.getParentNode();
while(parent != null && parent.getNodeType() == Node.ELEMENT_NODE ) {
// check if this datablock is part of a datablock
// hierarchy like 'language.de.btn_yes'
// look for the best fitting hierarchy name part, too
if(parent.getNodeName().equals("DATA")) {
blockname = ((Element)parent).getAttribute("name");
} else {
blockname = parent.getNodeName();
String secondName = ((Element)parent).getAttribute("name");
if(!"".equals(secondName)) {
blockname = blockname + "." + secondName;
}
}
blockname = blockname.toLowerCase();
if(parentname == null) {
parentname = blockname;
} else {
parentname = blockname + "." + parentname;
}
if(m_blocks.containsKey(parentname)) {
bestFit = parentname;
}
parent = parent.getParentNode();
}
// bestFit now contains the best fitting name part
// next, look for the tag name (the part behind the last ".")
if(n.getNodeName().equals("DATA")) {
blockname = n.getAttribute("name");
} else {
blockname = n.getNodeName();
String secondName = n.getAttribute("name");
if(!"".equals(secondName)) {
blockname = blockname + "." + secondName;
}
}
blockname = blockname.toLowerCase();
// now we can build the complete datablock name
if(bestFit != null) {
blockname = bestFit + "." + blockname;
}
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, "Reading datablock " + blockname);
}
// finally we cat put the new datablock into the hashtable
m_blocks.put(blockname, n);
//return null;
}
/**
* Handling of the "PROCESS" tags.
* Looks up the requested datablocks in the internal hashtable and
* returns its subnodes.
*
* @param n XML element containing the <code><PROCESS></code> tag.
* @param callingObject Reference to the object requesting the node processing.
* @param userObj Customizable user object that will be passed through to handling and user methods.
*/
private Object handleProcessTag(Element n, Object callingObject, Object userObj) {
String blockname = getTagValue(n).toLowerCase();
Element datablock = null;
if(C_DEBUG && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "handleProcessTag() started. Request for datablock \"" + blockname + "\".");
}
datablock = (Element)((Element)m_blocks.get(blockname));
if(datablock == null) {
if(A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_CRITICAL, getClassName() + "Requested datablock \"" + blockname + "\" not found!");
}
return C_ERR_NODATABLOCK + blockname;
} else {
return datablock.getChildNodes();
}
}
/**
* Handling of the "METHOD name=..." tags.
* Name attribute and value of the element are read and the user method
* 'name' is invoked with the element value as parameter.
*
* @param n XML element containing the <code><METHOD></code> tag.
* @param callingObject Reference to the object requesting the node processing.
* @param userObj Customizable user object that will be passed through to handling and user methods.
* @return Object returned by the user method
* @exception CmsException
*/
private Object handleMethodTag(Element n, Object callingObject, Object userObj) throws CmsException {
processNode(n, m_mainProcessTags, null, callingObject, userObj);
String tagcontent = getTagValue(n);
String method = n.getAttribute("name");
Object result = null;
try {
result = callUserMethod(method, tagcontent, callingObject, userObj);
} catch(Throwable e1) {
if(e1 instanceof CmsException) {
throw (CmsException)e1;
} else {
throwException("handleMethodTag() received an exception from callUserMethod() while calling \""
+ method + "\" requested by class " + callingObject.getClass().getName() + ": " + e1);
}
}
return result;
}
/**
* Generates a XML comment.
* It's used to replace no longer needed DOM elements by a short XML comment
*
* @param n XML element containing the tag to be replaced <em>(unused)</em>.
* @param callingObject Reference to the object requesting the node processing <em>(unused)</em>.
* @param userObj Customizable user object that will be passed through to handling and user methods <em>(unused)</em>.
* @return the generated XML comment.
*/
private NodeList replaceTagByComment(Element n, Object callingObject, Object userObj) {
Element tempNode = (Element)n.cloneNode(false);
while(tempNode.hasChildNodes()) {
tempNode.removeChild(tempNode.getFirstChild());
}
tempNode.appendChild(m_content.createComment("removed " + n.getNodeName()));
return tempNode.getChildNodes();
}
/**
* Internal method for creating a new datablock.
* <P>
* This method is called by setData() if a new, not existing
* datablock must be created.
* <P>
* <B>Functionality:</B> If a non-hierarchical datablock is given,
* it is inserted at the end of the DOM document.
* If a hierarchical datablock is given, all possible parent
* names are checked in a backward oriented order. If a
* datablock with a name that equals a part of the hierarchy is
* found, the new datablock will be created as a (sub)child
* of this datablock.
*
* @param tag Key for this datablock.
* @param data DOM element node for this datablock.
*/
private void insertNewDatablock(String tag, Element data) {
// First check, if this is an extended datablock
// in <NAME1 name="name2>... format, that has to be inserted
// as name1.name2
String nameAttr = data.getAttribute("name");
String workTag = null;
if((!data.getNodeName().toLowerCase().equals("data")) &&
nameAttr != null && (!"".equals(nameAttr))) {
// this is an extended datablock
workTag = tag.substring(0, tag.lastIndexOf("."));
} else {
workTag = tag;
}
// Import the node for later inserting
Element importedNode = (Element)parser.importNode(m_content, data);
// Check, if this is a simple datablock without hierarchy.
if(workTag.indexOf(".") == -1) {
// Fine. We can insert the new Datablock at the of the document
m_content.getDocumentElement().appendChild(importedNode);
m_blocks.put(tag, importedNode);
} else {
// This is a hierachical datablock tag. We have to search for
// an appropriate place to insert first.
boolean found = false;
String match = "." + workTag;
int dotIndex = match.lastIndexOf(".");
Vector newBlocks = new Vector();
while((!found) && (dotIndex > 1)) {
match = match.substring(0, dotIndex);
if(hasData(match.substring(1))) {
found = true;
} else {
dotIndex = match.lastIndexOf(".");
newBlocks.addElement(match.substring(dotIndex + 1));
}
}
// newBlocks now contains a (backward oriented) list
// of all datablocks that have to be created, before
// the new datablock named "tag" can be inserted.
String datablockPrefix = "";
if(found) {
datablockPrefix = match.substring(1) + ".";
}
// number of new elements to be created
int numNewBlocks = newBlocks.size();
// used to create the required new elements
Element newElem = null;
// Contains the last existing Element in the hierarchy.
Element lastElem = null;
// now create the new elements backwards
for(int i=numNewBlocks-1; i>=0; i
newElem = m_content.createElement("DATA");
newElem.setAttribute("name", (String)newBlocks.elementAt(i));
m_blocks.put(datablockPrefix + (String)newBlocks.elementAt(i), newElem);
if(lastElem != null) {
lastElem.appendChild(newElem);
} else {
lastElem = newElem;
}
}
// Now all required parent datablocks are created.
// Finally the given datablock can be inserted.
if(lastElem != null) {
lastElem.appendChild(importedNode);
} else {
lastElem = importedNode;
}
m_blocks.put(datablockPrefix + tag, importedNode);
// lastElem now contains the hierarchical tree of all DATA tags to be
// inserted.
// If we have found an existing part of the hierarchy, get
// this part and append the tree. If no part was found, append the
// tree at the end of the document.
if(found) {
Element parent = (Element)m_blocks.get(match.substring(1));
parent.appendChild(lastElem);
} else {
m_content.getDocumentElement().appendChild(lastElem);
}
}
}
/**
* Reloads a previously cached parsed content.
*
* @param filename Absolute pathname of the file to look for.
* @return DOM parsed document or null if the cached content was not found.
*/
private Document loadCachedDocument(String filename) {
Document cachedDoc = null;
String currentProject = m_cms.getRequestContext().currentProject().getName();
Document lookup = (Document)m_filecache.get(currentProject + ":" + filename);
if(lookup != null) {
cachedDoc = lookup.cloneNode(true).getOwnerDocument();
}
if(C_DEBUG && cachedDoc != null && A_OpenCms.isLogging()) {
A_OpenCms.log(C_OPENCMS_DEBUG, getClassName() + "Re-used previously parsed XML file " + getFilename() + ".");
}
return cachedDoc;
}
/**
* Looks up a user defined method requested by a "METHOD" tag.
* The method is searched in the Object callingObject.
* @param methodName Name of the user method
* @param callingObject Object that requested the processing of the XML document
* @return user method
* @exception NoSuchMethodException
*/
private Method getUserMethod(String methodName, Object callingObject)
throws NoSuchMethodException {
if(methodName == null || "".equals(methodName)) {
// no valid user method name
throw(new NoSuchMethodException("method name is null or empty"));
}
return callingObject.getClass().getMethod(methodName, C_PARAMTYPES_USER_METHODS);
}
/**
* Utility method for converting a String to a NodeList containing
* a single TextNode.
* @param s String to convert
* @return NodeList containing a TextNode with s
*/
private NodeList stringToNodeList(String s) {
Element tempNode = m_content.createElement("TEMP");
Text text = m_content.createTextNode(s);
tempNode.appendChild(text);
return tempNode.getChildNodes();
}
/**
* Utility method for putting a single Node to a new NodeList
* consisting only of this Node.
* @param n Node to put in NodeList
* @return NodeList containing copy of the Node n
*/
private NodeList nodeToNodeList(Node n) {
A_OpenCms.log(C_OPENCMS_DEBUG, "nodeToNodeList called with node " + n);
Element tempNode = m_content.createElement("TEMP");
tempNode.appendChild(n.cloneNode(true));
return tempNode.getChildNodes();
}
/**
* Concats two datablock hashtables and returns the resulting one.
*
* @param data1 First datablock hashtable.
* @param data2 Second datablock hashtable.
* @return Concatenated data.
*/
private Hashtable concatData(Hashtable data1, Hashtable data2) {
Hashtable retValue = (Hashtable) data1.clone();
Enumeration keys = data2.keys();
Object key;
while(keys.hasMoreElements()) {
key = keys.nextElement();
retValue.put(key, data2.get(key));
}
return retValue;
}
/**
* Internal method for debugging purposes.
* Dumpes the content of a given NodeList to the logfile.
*
* @param l NodeList to dump.
*/
private void dumpNodeList(NodeList l) {
if(A_OpenCms.isLogging()) {
if(l == null) {
A_OpenCms.log(C_OPENCMS_DEBUG, "******* NODE LIST IS NULL ********");
} else {
int len = l.getLength();
A_OpenCms.log(C_OPENCMS_DEBUG, "******** DUMP OF NODELIST ********");
A_OpenCms.log(C_OPENCMS_DEBUG, "* LEN: " + len);
for(int i=0; i<len; i++) {
A_OpenCms.log(C_OPENCMS_DEBUG, "*" + l.item(i));
}
A_OpenCms.log(C_OPENCMS_DEBUG, "**********************************");
}
}
}
/**
* Internal method for debugging purposes.
* Dumps the content of the datablock hashtable to the logfile.
*/
private void dumpDatablocks() {
if(A_OpenCms.isLogging()) {
Enumeration hashKeys = m_blocks.keys();
String key = null;
Element node = null;
A_OpenCms.log(C_OPENCMS_DEBUG, "******** DUMP OF DATABLOCK HASHTABLE *********");
while(hashKeys.hasMoreElements()) {
key = (String)hashKeys.nextElement();
node = (Element)m_blocks.get(key);
A_OpenCms.log(C_OPENCMS_DEBUG, "* " + key + " --> " + node.getNodeName());
}
A_OpenCms.log(C_OPENCMS_DEBUG, "**********************************************");
}
}
}
|
package com.relteq.sirius.simulator;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Random;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
/** Load, manipulate, and run scenarios.
* <p>
* A scenario is a collection of,
* <ul>
* <li> networks (nodes, links, sensors, and signals), </li>
* <li> network connections, </li>
* <li> initial conditions, </li>
* <li> weaving factor profiles, </li>
* <li> split ratio profiles, </li>
* <li> downstream boundary conditions, </li>
* <li> events, </li>
* <li> controllers, </li>
* <li> fundamental diagram profiles, </li>
* <li> path segments, </li>
* <li> decision points, </li>
* <li> routes, </li>
* <li> background demand profiles, and </li>
* <li> OD demand profiles. </li>
* </ul>
* @author Gabriel Gomes
* @version VERSION NUMBER
*/
public final class Scenario extends com.relteq.sirius.jaxb.Scenario {
/** @y.exclude */ protected Clock clock;
/** @y.exclude */ protected String configfilename;
/** @y.exclude */ protected Random random = new Random();
/** @y.exclude */ protected Scenario.UncertaintyType uncertaintyModel;
/** @y.exclude */ protected int numVehicleTypes; // number of vehicle types
/** @y.exclude */ protected boolean global_control_on; // global control switch
/** @y.exclude */ protected double global_demand_knob; // scale factor for all demands
/** @y.exclude */ protected double simdtinseconds; // [sec] simulation time step
/** @y.exclude */ protected double simdtinhours; // [hr] simulation time step
/** @y.exclude */ protected boolean scenariolocked=false; // true when the simulation is running
/** @y.exclude */ protected ControllerSet controllerset = new ControllerSet();
/** @y.exclude */ protected EventSet eventset = new EventSet(); // holds time sorted list of events
/** @y.exclude */ protected static enum ModeType { normal,
warmupFromZero ,
warmupFromIC };
/** @y.exclude */ protected static enum UncertaintyType { uniform,
gaussian }
// protected constructor
/** @y.exclude */
protected Scenario(){}
// populate / reset / validate / update
/** populate methods copy data from the jaxb state to extended objects.
* They do not throw exceptions or report mistakes. Data errors should be
* circumvented and left for the validation to report.
* @throws SiriusException
* @y.exclude
*/
protected void populate() throws SiriusException {
// network list
if(getNetworkList()!=null)
for( com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork() )
((Network) network).populate(this);
// split ratio profile set (must follow network)
if(getSplitRatioProfileSet()!=null)
((SplitRatioProfileSet) getSplitRatioProfileSet()).populate(this);
// boundary capacities (must follow network)
if(getDownstreamBoundaryCapacitySet()!=null)
for( com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile() )
((CapacityProfile) capacityProfile).populate(this);
if(getDemandProfileSet()!=null)
((DemandProfileSet) getDemandProfileSet()).populate(this);
// fundamental diagram profiles
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile) fd).populate(this);
// initial density profile
if(getInitialDensityProfile()!=null)
((InitialDensityProfile) getInitialDensityProfile()).populate(this);
// initialize controllers and events
controllerset.populate(this);
eventset.populate(this);
}
/** Prepare scenario for simulation:
* set the state of the scenario to the initial condition
* sample profiles
* open output files
* @return success A boolean indicating whether the scenario was successfuly reset.
* @throws SiriusException
* @y.exclude
*/
protected boolean reset(Scenario.ModeType simulationMode) throws SiriusException {
// reset the clock
clock.reset();
// reset network
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
((Network)network).reset(simulationMode);
// reset demand profiles
if(getDemandProfileSet()!=null)
((DemandProfileSet)getDemandProfileSet()).reset();
// reset fundamental diagrams
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile)fd).reset();
// reset controllers
global_control_on = true;
controllerset.reset();
// reset events
eventset.reset();
return true;
}
/**
* @throws SiriusException
* @y.exclude
*/
protected void update() throws SiriusException {
System.out.println("HELLO!");
// sample profiles .............................
if(getDownstreamBoundaryCapacitySet()!=null)
for(com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile())
((CapacityProfile) capacityProfile).update();
if(getDemandProfileSet()!=null)
((DemandProfileSet)getDemandProfileSet()).update();
if(getSplitRatioProfileSet()!=null)
((SplitRatioProfileSet) getSplitRatioProfileSet()).update();
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fdProfile : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
((FundamentalDiagramProfile) fdProfile).update();
// update controllers
if(global_control_on)
controllerset.update();
// update events
eventset.update();
// update the network state......................
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
((Network) network).update();
}
// protected interface
/** Retrieve a network with a given id.
* @param id The string id of the network
* @return The corresponding network if it exists, <code>null</code> otherwise.
*
*/
protected Network getNetworkWithId(String id){
if(getNetworkList()==null)
return null;
if(getNetworkList().getNetwork()==null)
return null;
if(id==null && getNetworkList().getNetwork().size()>1)
return null;
if(id==null && getNetworkList().getNetwork().size()==1)
return (Network) getNetworkList().getNetwork().get(0);
id.replaceAll("\\s","");
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork()){
if(network.getId().equals(id))
return (Network) network;
}
return null;
}
// excluded from API
/** @y.exclude */
public Integer [] getVehicleTypeIndices(com.relteq.sirius.jaxb.VehicleTypeOrder vtypeorder){
Integer [] vehicletypeindex;
// single vehicle types in setting and no vtypeorder, return 0
if(vtypeorder==null && numVehicleTypes==1){
vehicletypeindex = new Integer[numVehicleTypes];
vehicletypeindex[0]=0;
return vehicletypeindex;
}
// multiple vehicle types in setting and no vtypeorder, return 0...n
if(vtypeorder==null && numVehicleTypes>1){
vehicletypeindex = new Integer[numVehicleTypes];
for(int i=0;i<numVehicleTypes;i++)
vehicletypeindex[i] = i;
return vehicletypeindex;
}
// vtypeorder is not null
int numTypesInOrder = vtypeorder.getVehicleType().size();
int i,j;
vehicletypeindex = new Integer[numTypesInOrder];
for(i=0;i<numTypesInOrder;i++)
vehicletypeindex[i] = -1;
if(getSettings()==null)
return vehicletypeindex;
if(getSettings().getVehicleTypes()==null)
return vehicletypeindex;
for(i=0;i<numTypesInOrder;i++){
String vtordername = vtypeorder.getVehicleType().get(i).getName();
List<com.relteq.sirius.jaxb.VehicleType> settingsname = getSettings().getVehicleTypes().getVehicleType();
for(j=0;j<settingsname.size();j++){
if(settingsname.get(j).getName().equals(vtordername)){
vehicletypeindex[i] = j;
break;
}
}
}
return vehicletypeindex;
}
/** @y.exclude */
public boolean validate() {
// validate network
if( getNetworkList()!=null)
for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
if(!((Network)network).validate()){
SiriusErrorLog.addErrorMessage("Network validation failure.");
return false;
}
// NOTE: DO THIS ONLY IF IT IS USED. IE DO IT IN THE RUN WITH CORRECT FUNDAMENTAL DIAGRAMS
// validate initial density profile
// if(getInitialDensityProfile()!=null)
// if(!((_InitialDensityProfile) getInitialDensityProfile()).validate()){
// SiriusErrorLog.addErrorMessage("InitialDensityProfile validation failure.");
// return false;
// validate capacity profiles
if(getDownstreamBoundaryCapacitySet()!=null)
for(com.relteq.sirius.jaxb.CapacityProfile capacityProfile : getDownstreamBoundaryCapacitySet().getCapacityProfile())
if(!((CapacityProfile)capacityProfile).validate()){
SiriusErrorLog.addErrorMessage("DownstreamBoundaryCapacitySet validation failure.");
return false;
}
// validate demand profiles
if(getDemandProfileSet()!=null)
if(!((DemandProfileSet)getDemandProfileSet()).validate()){
SiriusErrorLog.addErrorMessage("DemandProfileSet validation failure.");
return false;
}
// validate split ratio profiles
if(getSplitRatioProfileSet()!=null)
if(!((SplitRatioProfileSet)getSplitRatioProfileSet()).validate()){
SiriusErrorLog.addErrorMessage("SplitRatioProfileSet validation failure.");
return false;
}
// validate fundamental diagram profiles
if(getFundamentalDiagramProfileSet()!=null)
for(com.relteq.sirius.jaxb.FundamentalDiagramProfile fd : getFundamentalDiagramProfileSet().getFundamentalDiagramProfile())
if(!((FundamentalDiagramProfile)fd).validate()){
SiriusErrorLog.addErrorMessage("FundamentalDiagramProfileSet validation failure.");
return false;
}
// validate controllers
if(!controllerset.validate())
return false;
return true;
}
// API
/** Run the scenario <code>numRepetitions</code> times, save output to text files.
*
* <p> The scenario is reset and run multiple times in sequence. All
* probabilistic quantities are re-sampled between runs. Output files are
* created with a common prefix with the index of the simulation appended to
* the file name.
*
* @param outputfileprefix String prefix for all output files.
* @param numRepetitions The integer number of simulations to run.
* @throws SiriusException
*/
public void run(String outputfileprefix,Double timestart,Double timeend,double outdt,int numRepetitions) throws SiriusException{
RunParameters param = new RunParameters(outputfileprefix,timestart,timeend,outdt,simdtinseconds);
run_internal(param,numRepetitions,true,false);
}
/** Run the scenario once, return the state trajectory.
* <p> The scenario is reset and run once.
* @return An object with the history of densities and flows for all links in the scenario.
* @throws SiriusException
*/
public SiriusStateTrajectory run(Double timestart,Double timeend,double outdt) throws SiriusException{
RunParameters param = new RunParameters(null,timestart,timeend,outdt,simdtinseconds);
return run_internal(param,1,false,true);
}
/** Advance the simulation <i>n</i> steps.
*
* <p> This function moves the simulation forward <i>n</i> time steps and stops.
* The first parameter provides the number of time steps to advance. The second parameter
* is a boolean that resets the clock and the scenario.
* @param nsec Number of seconds to advance.
* @throws SiriusException
*/
public void advanceNSeconds(double nsec) throws SiriusException{
if(!scenariolocked)
throw new SiriusException("Run not initialized. Use initialize_run() first.");
if(!SiriusMath.isintegermultipleof(nsec,simdtinseconds))
throw new SiriusException("nsec (" + nsec + ") must be an interger multiple of simulation dt (" + simdtinseconds + ").");
int nsteps = SiriusMath.round(nsec/simdtinseconds);
advanceNSteps_internal(ModeType.normal,nsteps,false,false,null,null,-1);
}
/** Save the scenario to XML.
*
* @param filename The name of the configuration file.
* @throws SiriusException
*/
public void saveToXML(String filename) throws SiriusException{
try {
JAXBContext context = JAXBContext.newInstance("aurora.jaxb");
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(this,new FileOutputStream(filename));
} catch( JAXBException je ) {
throw new SiriusException(je.getMessage());
} catch (FileNotFoundException e) {
throw new SiriusException(e.getMessage());
}
}
/** Current simulation time in seconds.
* @return Simulation time in seconds after midnight.
*/
public double getTimeInSeconds() {
if(clock==null)
return Double.NaN;
return clock.getT();
}
/** Time elapsed since the beginning of the simulation in seconds.
* @return Simulation time in seconds after start time.
*/
public double getTimeElapsedInSeconds() {
if(clock==null)
return Double.NaN;
return clock.getTElapsed();
}
/** Current simulation time step.
* @return Integer number of time steps since the start of the simulation.
*/
public int getCurrentTimeStep() {
if(clock==null)
return 0;
return clock.getCurrentstep();
}
/** Total number of time steps that will be simulated, regardless of the simulation mode.
* @return Integer number of time steps to simulate.
*/
public int getTotalTimeStepsToSimulate(){
return clock.getTotalSteps();
}
/** Number of vehicle types included in the scenario.
* @return Integer number of vehicle types
*/
public int getNumVehicleTypes() {
return numVehicleTypes;
}
/** Vehicle type names.
* @return Array of strings with the names of the vehicles types.
*/
public String [] getVehicleTypeNames(){
String [] vehtypenames = new String [numVehicleTypes];
if(getSettings()==null || getSettings().getVehicleTypes()==null)
vehtypenames[0] = Defaults.vehicleType;
else
for(int i=0;i<getSettings().getVehicleTypes().getVehicleType().size();i++)
vehtypenames[i] = getSettings().getVehicleTypes().getVehicleType().get(i).getName();
return vehtypenames;
}
/** Vehicle type weights.
* @return Array of doubles with the weights of the vehicles types.
*/
public Double [] getVehicleTypeWeights(){
Double [] vehtypeweights = new Double [numVehicleTypes];
if(getSettings()==null || getSettings().getVehicleTypes()==null)
vehtypeweights[0] = 1d;
else
for(int i=0;i<getSettings().getVehicleTypes().getVehicleType().size();i++)
vehtypeweights[i] = getSettings().getVehicleTypes().getVehicleType().get(i).getWeight().doubleValue();
return vehtypeweights;
}
/** Vehicle type index from name
* @return integer index of the vehicle type.
*/
public int getVehicleTypeIndex(String name){
String [] vehicleTypeNames = getVehicleTypeNames();
if(vehicleTypeNames==null)
return 0;
if(vehicleTypeNames.length<=1)
return 0;
for(int i=0;i<vehicleTypeNames.length;i++)
if(vehicleTypeNames[i].equals(name))
return i;
return -1;
}
/** Size of the simulation time step in seconds.
* @return Simulation time step in seconds.
*/
public double getSimDtInSeconds() {
return simdtinseconds;
}
/** Size of the simulation time step in hours.
* @return Simulation time step in hours.
*/
public double getSimDtInHours() {
return simdtinhours;
}
/** Start time of the simulation.
* @return Start time in seconds.
*/
public double getTimeStart() {
if(clock==null)
return Double.NaN;
else
return this.clock.getStartTime();
}
/** End time of the simulation.
* @return End time in seconds.
* @return XXX
*/
public double getTimeEnd() {
if(clock==null)
return Double.NaN;
else
return this.clock.getEndTime();
}
/** Get a reference to a controller by its id.
* @param id Id of the controller.
* @return A reference to the controller if it exists, <code>null</code> otherwise.
*/
public Controller getControllerWithId(String id){
if(controllerset==null)
return null;
for(Controller c : controllerset.get_Controllers()){
if(c.id.equals(id))
return c;
}
return null;
}
/** Get a reference to an event by its id.
* @param id Id of the event.
* @return A reference to the event if it exists, <code>null</code> otherwise.
*/
public Event getEventWithId(String id){
if(eventset==null)
return null;
for(Event e : eventset.sortedevents){
if(e.getId().equals(id))
return e;
}
return null;
}
/** Get a reference to a node by its composite id.
*
* @param network_id String id of the network containing the node.
* @param id String id of the node.
* @return Reference to the node if it exists, <code>null</code> otherwise
*/
public Node getNodeWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getNodeWithId(id);
else
return null;
else
return network.getNodeWithId(id);
}
/** Get a reference to a link by its composite id.
*
* @param network_id String id of the network containing the link.
* @param id String id of the link.
* @return Reference to the link if it exists, <code>null</code> otherwise
*/
public Link getLinkWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getLinkWithId(id);
else
return null;
else
return network.getLinkWithId(id);
}
/** Get a reference to a sensor by its composite id.
*
* @param network_id String id of the network containing the sensor.
* @param id String id of the sensor.
* @return Reference to the sensor if it exists, <code>null</code> otherwise
*/
public Sensor getSensorWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSensorWithId(id);
else
return null;
else
return network.getSensorWithId(id);
}
/** Get a reference to a signal by its composite id.
*
* @param network_id String id of the network containing the signal.
* @param id String id of the signal.
* @return Reference to the signal if it exists, <code>null</code> otherwise
*/
public Signal getSignalWithCompositeId(String network_id,String id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSignalWithId(id);
else
return null;
else
return network.getSignalWithId(id);
}
/** Get a reference to a signal by the composite id of its node.
*
* @param network_id String id of the network containing the signal.
* @param node_id String id of the node under the signal.
* @return Reference to the signal if it exists, <code>null</code> otherwise
*/
public Signal getSignalForNodeId(String network_id,String node_id){
if(getNetworkList()==null)
return null;
Network network = getNetworkWithId(network_id);
if(network==null)
if(getNetworkList().getNetwork().size()==1)
return ((Network) getNetworkList().getNetwork().get(0)).getSignalWithNodeId(node_id);
else
return null;
else
return network.getSignalWithNodeId(node_id);
}
/** Add a controller to the scenario.
*
* <p>Controllers can only be added if a) the scenario is not currently running, and
* b) the controller is valid.
* @param C The controller
* @return <code>true</code> if the controller was successfully added, <code>false</code> otherwise.
*/
public boolean addController(Controller C){
if(scenariolocked)
return false;
if(C==null)
return false;
if(C.myType==null)
return false;
// validate
if(!C.validate())
return false;
// add
controllerset.controllers.add(C);
return true;
}
/** Add an event to the scenario.
*
* <p>Events are not added if the scenario is running. This method does not validate the event.
* @param E The event
* @return <code>true</code> if the event was successfully added, <code>false</code> otherwise.
*/
public boolean addEvent(Event E){
if(scenariolocked)
return false;
if(E==null)
return false;
if(E.myType==null)
return false;
// add event to list
eventset.addEvent(E);
return true;
}
/** Add a sensor to the scenario.
*
* <p>Sensors can only be added if a) the scenario is not currently running, and
* b) the sensor is valid.
* @param S The sensor
* @return <code>true</code> if the sensor was successfully added, <code>false</code> otherwise.
*/
public boolean addSensor(Sensor S){
if(S==null)
return false;
if(S.myType==null)
return false;
if(S.myLink==null)
return false;
if(S.myLink.myNetwork==null)
return false;
// validate
if(!S.validate())
return false;
// add sensor to list
S.myLink.myNetwork.getSensorList().getSensor().add(S);
return true;
}
/** Get the initial density state for the network with given id.
* @param nework_id String id of the network
* @return A two-dimensional array of doubles where the first dimension is the
* link index (ordered as in {@link Network#getListOfLinks}) and the second is the vehicle type
* (ordered as in {@link Scenario#getVehicleTypeNames})
*/
public double [][] getInitialDensityForNetwork(String network_id){
Network network = getNetworkWithId(network_id);
if(network==null)
return null;
double [][] density = new double [network.getLinkList().getLink().size()][getNumVehicleTypes()];
InitialDensityProfile initprofile = (InitialDensityProfile) getInitialDensityProfile();
int i,j;
for(i=0;i<network.getLinkList().getLink().size();i++){
if(initprofile==null){
for(j=0;j<numVehicleTypes;j++)
density[i][j] = 0d;
}
else{
com.relteq.sirius.jaxb.Link link = network.getLinkList().getLink().get(i);
Double [] init_density = initprofile.getDensityForLinkIdInVeh(link.getId(),network.getId());
for(j=0;j<numVehicleTypes;j++)
density[i][j] = init_density[j];
}
}
return density;
}
/** Get the current density state for the network with given id.
* @param nework_id String id of the network
* @return A two-dimensional array of doubles where the first dimension is the
* link index (ordered as in {@link Network#getListOfLinks}) and the second is the vehicle type
* (ordered as in {@link Scenario#getVehicleTypeNames})
*/
public double [][] getDensityForNetwork(String network_id){
Network network = getNetworkWithId(network_id);
if(network==null)
return null;
double [][] density = new double [network.getLinkList().getLink().size()][getNumVehicleTypes()];
int i,j;
for(i=0;i<network.getLinkList().getLink().size();i++){
Link link = (Link) network.getLinkList().getLink().get(i);
Double [] linkdensity = link.getDensityInVeh();
for(j=0;j<numVehicleTypes;j++)
density[i][j] = linkdensity[j];
}
return density;
}
/** Initialize the run before using {@link Scenario#advanceNSeconds(double)}
*
* <p>This method performs certain necessary initialization tasks on the scenario. In particular
* it locks the scenario so that elements may not be added mid-run. It also resets the scenario
* rolling back all profiles and clocks.
*/
public void initialize_run() throws SiriusException{
if(scenariolocked)
throw new SiriusException("Run in progress.");
// use RunParameters constructor to determine the timestart
RunParameters param = new RunParameters("",Double.NEGATIVE_INFINITY,Double.POSITIVE_INFINITY,0,simdtinseconds);
// create the clock
clock = new Clock(param.timestart,Double.POSITIVE_INFINITY,simdtinseconds);
// reset the simulation
if(!reset(ModeType.normal))
throw new SiriusException("Reset failed.");
// lock the scenario
scenariolocked = true;
}
// /** Load sensor data for all sensors in the scenario.
// */
// public void loadSensorData() throws SiriusException{
// for(com.relteq.sirius.jaxb.Network network : getNetworkList().getNetwork())
// ((Network) network).loadSensorData();
// private
private SiriusStateTrajectory run_internal(RunParameters param,int numRepetitions,boolean writefiles,boolean returnstate) throws SiriusException{
if(returnstate && numRepetitions>1)
throw new SiriusException("run with multiple repetitions and returning state not allowed.");
SiriusStateTrajectory state = null;
// create the clock
clock = new Clock(param.timestart,param.timeend,simdtinseconds);
// lock the scenario
scenariolocked = true;
// loop through simulation runs ............................
for(int i=0;i<numRepetitions;i++){
OutputWriter outputwriter = null;
// open output files
if( writefiles && param.simulationMode.compareTo(Scenario.ModeType.normal)==0 ){
outputwriter = new OutputWriter(this);
try {
outputwriter.open(param.outputfileprefix,String.format("%d",i));
} catch (FileNotFoundException e) {
throw new SiriusException("Unable to open output file.");
}
}
// allocate state
if(returnstate)
state = new SiriusStateTrajectory(this,param.outsteps);
// reset the simulation
if(!reset(param.simulationMode))
throw new SiriusException("Reset failed.");
// advance to end of simulation
while( advanceNSteps_internal(param.simulationMode,1,writefiles,returnstate,outputwriter,state,param.outsteps) ){
}
// close output files
if(writefiles){
if(param.simulationMode.compareTo(Scenario.ModeType.normal)==0)
outputwriter.close();
// or save scenario (in warmup mode)
if(param.simulationMode.compareTo(Scenario.ModeType.warmupFromIC)==0 || param.simulationMode.compareTo(Scenario.ModeType.warmupFromZero)==0 ){
// String outfile = "C:\\Users\\gomes\\workspace\\auroralite\\data\\config\\out.xml";
// Utils.save(scenario, outfile);
}
}
}
scenariolocked = false;
return state;
}
// advance the simulation by n steps.
// parameters....
// n: number of steps to advance.
// doreset: call scenario reset if true
// writefiles: write result to text files if true
// returnstate: recored and return the state trajectory if true
// outputwriter: output writing class
// state: state trajectory container
// returns....
// true if scenario advanced n steps without error
// false if scenario reached t_end without error before completing n steps
// throws ....
// SiriusException for all errors
private boolean advanceNSteps_internal(Scenario.ModeType simulationMode,int n,boolean writefiles,boolean returnstate,OutputWriter outputwriter,SiriusStateTrajectory state,int outsteps) throws SiriusException{
// advance n steps
for(int k=0;k<n;k++){
// export initial condition
if(simulationMode.compareTo(ModeType.normal)==0 && outsteps>0 )
if( clock.getCurrentstep()==0 )
recordstate(writefiles,returnstate,outputwriter,state,false,outsteps);
// update scenario
update();
// update time (before write to output)
clock.advance();
if(simulationMode.compareTo(ModeType.normal)==0 && outsteps>0 )
if( clock.getCurrentstep()%outsteps == 0 )
recordstate(writefiles,returnstate,outputwriter,state,true,outsteps);
if(clock.expired())
return false;
}
return true;
}
private void recordstate(boolean writefiles,boolean returnstate,OutputWriter outputwriter,SiriusStateTrajectory state,boolean exportflows,int outsteps) throws SiriusException {
if(writefiles)
outputwriter.recordstate(clock.getT(),exportflows,outsteps);
if(returnstate)
state.recordstate(clock.getCurrentstep(),clock.getT(),exportflows,outsteps);
}
private class RunParameters{
public String outputfileprefix;
public double timestart; // [sec] start of the simulation
public double timeend; // [sec] end of the simulation
public int outsteps; // [-] number of simulation steps per output step
public Scenario.ModeType simulationMode;
// input parameter outdt [sec] output sampling time
public RunParameters(String outputfileprefix,double timestart,double timeend,double outdt,double simdtinseconds) throws SiriusException{
// check timestart < timeend
if(timestart>=timeend)
throw new SiriusException("Empty simulation period.");
// check that outdt is a multiple of simdt
if(!SiriusMath.isintegermultipleof(outdt,simdtinseconds))
throw new SiriusException("outdt (" + outdt + ") must be an interger multiple of simulation dt (" + simdtinseconds + ").");
this.outputfileprefix = outputfileprefix;
this.timestart = timestart;
this.timeend = timeend;
this.outsteps = SiriusMath.round(outdt/simdtinseconds);
// Simulation mode is normal <=> start time == initial profile time stamp
simulationMode = null;
double time_ic;
if(getInitialDensityProfile()!=null)
time_ic = ((InitialDensityProfile)getInitialDensityProfile()).timestamp;
else
time_ic = 0.0;
if(timestart==time_ic){
simulationMode = Scenario.ModeType.normal;
}
else{
// it is a warmup. we need to decide on start and end times
timeend = timestart;
if(time_ic<timestart){ // go from ic to timestart
timestart = time_ic;
simulationMode = Scenario.ModeType.warmupFromIC;
}
else{ // start at earliest demand profile
timestart = Double.POSITIVE_INFINITY;
if(getDemandProfileSet()!=null)
for(com.relteq.sirius.jaxb.DemandProfile D : getDemandProfileSet().getDemandProfile())
timestart = Math.min(timestart,D.getStartTime().doubleValue());
else
timestart = 0.0;
simulationMode = Scenario.ModeType.warmupFromZero;
}
}
}
}
}
|
package com.robrua.orianna.api;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.robrua.orianna.api.queryspecs.Region;
import com.robrua.orianna.api.queryspecs.Season;
import com.robrua.orianna.type.champion.ChampionStatus;
import com.robrua.orianna.type.game.Game;
import com.robrua.orianna.type.game.GameMode;
import com.robrua.orianna.type.game.GamePlayer;
import com.robrua.orianna.type.game.GameType;
import com.robrua.orianna.type.game.RawStats;
import com.robrua.orianna.type.game.SubType;
import com.robrua.orianna.type.league.League;
import com.robrua.orianna.type.league.LeagueEntry;
import com.robrua.orianna.type.league.LeagueType;
import com.robrua.orianna.type.league.MiniSeries;
import com.robrua.orianna.type.league.Tier;
import com.robrua.orianna.type.match.BannedChampion;
import com.robrua.orianna.type.match.BuildingType;
import com.robrua.orianna.type.match.Event;
import com.robrua.orianna.type.match.EventType;
import com.robrua.orianna.type.match.Frame;
import com.robrua.orianna.type.match.Lane;
import com.robrua.orianna.type.match.LaneType;
import com.robrua.orianna.type.match.LevelUpType;
import com.robrua.orianna.type.match.MatchMap;
import com.robrua.orianna.type.match.MatchSummary;
import com.robrua.orianna.type.match.MatchTeam;
import com.robrua.orianna.type.match.MatchTimeline;
import com.robrua.orianna.type.match.MonsterType;
import com.robrua.orianna.type.match.Participant;
import com.robrua.orianna.type.match.ParticipantFrame;
import com.robrua.orianna.type.match.ParticipantStats;
import com.robrua.orianna.type.match.ParticipantTimeline;
import com.robrua.orianna.type.match.ParticipantTimelineData;
import com.robrua.orianna.type.match.Player;
import com.robrua.orianna.type.match.Position;
import com.robrua.orianna.type.match.QueueType;
import com.robrua.orianna.type.match.Role;
import com.robrua.orianna.type.match.Side;
import com.robrua.orianna.type.match.TowerType;
import com.robrua.orianna.type.match.WardType;
import com.robrua.orianna.type.staticdata.BasicDataStats;
import com.robrua.orianna.type.staticdata.Block;
import com.robrua.orianna.type.staticdata.BlockItem;
import com.robrua.orianna.type.staticdata.Champion;
import com.robrua.orianna.type.staticdata.ChampionSpell;
import com.robrua.orianna.type.staticdata.Gold;
import com.robrua.orianna.type.staticdata.Image;
import com.robrua.orianna.type.staticdata.Information;
import com.robrua.orianna.type.staticdata.Item;
import com.robrua.orianna.type.staticdata.LevelTip;
import com.robrua.orianna.type.staticdata.Mastery;
import com.robrua.orianna.type.staticdata.MasteryTree;
import com.robrua.orianna.type.staticdata.MasteryTreeItem;
import com.robrua.orianna.type.staticdata.MasteryTreeList;
import com.robrua.orianna.type.staticdata.MetaData;
import com.robrua.orianna.type.staticdata.Passive;
import com.robrua.orianna.type.staticdata.Realm;
import com.robrua.orianna.type.staticdata.Recommended;
import com.robrua.orianna.type.staticdata.Rune;
import com.robrua.orianna.type.staticdata.RuneType;
import com.robrua.orianna.type.staticdata.Skin;
import com.robrua.orianna.type.staticdata.SpellVariables;
import com.robrua.orianna.type.staticdata.Stats;
import com.robrua.orianna.type.staticdata.SummonerSpell;
import com.robrua.orianna.type.stats.AggregatedStats;
import com.robrua.orianna.type.stats.ChampionStats;
import com.robrua.orianna.type.stats.PlayerStatsSummary;
import com.robrua.orianna.type.stats.PlayerStatsSummaryType;
import com.robrua.orianna.type.summoner.MasteryPage;
import com.robrua.orianna.type.summoner.MasterySlot;
import com.robrua.orianna.type.summoner.RunePage;
import com.robrua.orianna.type.summoner.RuneSlot;
import com.robrua.orianna.type.summoner.Summoner;
import com.robrua.orianna.type.team.MatchHistorySummary;
import com.robrua.orianna.type.team.Roster;
import com.robrua.orianna.type.team.Team;
import com.robrua.orianna.type.team.TeamMemberInformation;
import com.robrua.orianna.type.team.TeamStatDetail;
/**
* Used to convert the responses from the JSONRiotAPI to the Orianna typesystem.
*
* @author Rob Rua (FatalElement - NA) (robrua@alumni.cmu.edu)
*/
public class JSONConverter {
private static Integer convertInteger(final Object object) {
final Long longVersion = (Long)object;
if(longVersion == null) {
return null;
}
return longVersion.intValue();
}
private static LocalDateTime getDateTime(final JSONObject object, final String key) {
final Long epoch = (Long)object.get(key);
if(epoch == null) {
return null;
}
return LocalDateTime.ofEpochSecond(epoch / 1000, 0, ZoneOffset.UTC);
}
private static List<Double> getDoubleList(final JSONArray list) {
return getList(list, d -> (Double)d);
}
private static List<Double> getDoubleList(final JSONObject object, final String key) {
return getList(object, key, d -> (Double)d);
}
private static Duration getDuration(final JSONObject object, final String key, final TemporalUnit unit) {
final Long amt = (Long)object.get(key);
if(amt == null) {
return null;
}
return Duration.of(amt, unit);
}
private static Integer getInteger(final JSONObject object, final String key) {
return convertInteger(object.get(key));
}
private static List<Integer> getIntegerList(final JSONArray list) {
return getList(list, JSONConverter::convertInteger);
}
private static List<Integer> getIntegerList(final JSONObject object, final String key) {
return getList(object, key, JSONConverter::convertInteger);
}
protected static <T> List<T> getList(final JSONArray list, final Function<Object, T> mapper) {
return getList(list, mapper, null);
}
protected static <T> List<T> getList(final JSONArray list, final Function<Object, T> mapper, final Comparator<? super T> sorter) {
if(list == null) {
return null;
}
final List<T> result = new ArrayList<T>(list.size());
for(final Object obj : list) {
final T item = mapper.apply(obj);
result.add(item);
}
if(sorter != null) {
result.sort(sorter);
}
return Collections.unmodifiableList(result);
}
protected static <T> List<T> getList(final JSONObject object, final String key, final Function<Object, T> mapper) {
return getList(object, key, mapper, null);
}
protected static <T> List<T> getList(final JSONObject object, final String key, final Function<Object, T> mapper, final Comparator<? super T> sorter) {
final JSONArray list = (JSONArray)object.get(key);
if(list == null) {
return null;
}
return getList(list, mapper, sorter);
}
protected static <T> List<T> getListFromMap(final JSONObject map, final Function<Object, T> mapper) {
return getListFromMap(map, mapper, null);
}
protected static <T> List<T> getListFromMap(final JSONObject map, final Function<Object, T> mapper, final Comparator<? super T> sorter) {
final List<T> result = new ArrayList<T>(map.size());
for(final Object obj : map.values()) {
final T item = mapper.apply(obj);
result.add(item);
}
if(sorter != null) {
result.sort(sorter);
}
return Collections.unmodifiableList(result);
}
protected static <T> List<T> getListFromMap(final JSONObject object, final String key, final Function<Object, T> mapper) {
return getListFromMap(object, key, mapper, null);
}
protected static <T> List<T> getListFromMap(final JSONObject object, final String key, final Function<Object, T> mapper, final Comparator<? super T> sorter) {
final JSONObject map = (JSONObject)object.get(key);
if(map == null) {
return null;
}
return getListFromMap(map, mapper, sorter);
}
private static MatchMap getMap(final Integer ID) {
switch(ID) {
case 1:
return MatchMap.SUMMONERS_RIFT_SUMMER;
case 2:
return MatchMap.SUMMONERS_RIFT_AUTUMN;
case 3:
return MatchMap.PROVING_GROUNDS;
case 4:
return MatchMap.TWISTED_TREELINE_ORIGINAL;
case 8:
return MatchMap.CRYSTAL_SCAR;
case 10:
return MatchMap.TWISTED_TREELINE;
case 12:
return MatchMap.HOWLING_ABYSS;
default:
return null;
}
}
protected static <T> Map<Object, T> getMapFromList(final JSONArray list, final Function<Object, T> mapper) {
final Map<Object, T> result = new HashMap<Object, T>(list.size());
for(final Object obj : list) {
final T item = mapper.apply(obj);
result.put(obj, item);
}
return Collections.unmodifiableMap(result);
}
protected static <T> Map<Object, T> getMapFromList(final JSONObject object, final String key, final Function<Object, T> mapper) {
final JSONArray list = (JSONArray)object.get(key);
if(list == null) {
return null;
}
return getMapFromList(list, mapper);
}
private static Map<String, Pattern> getScrapedStatPatterns() {
final Map<String, Pattern> patterns = new HashMap<String, Pattern>();
patterns.put("PercentCooldownMod", Pattern.compile("\\+(\\d+) *% Cooldown Reduction *(<br>|</stats>|</passive>|$)"));
patterns.put("FlatArmorPenetrationMod", Pattern.compile("\\+(\\d+) *Armor Penetration *(<br>|</stats>|</passive>|$)"));
patterns.put("PercentArmorPenetrationMod", Pattern.compile("ignores (\\d+)% of the target's Armor"));
patterns.put("FlatMagicPenetrationMod", Pattern.compile("\\+(\\d+) *Magic Penetration *(<br>|</stats>|</passive>|$)"));
patterns.put("PercentMagicPenetrationMod", Pattern.compile("ignores (\\d+)% of the target's Magic Resist"));
patterns.put("FlatGoldPer10Mod", Pattern.compile("\\+(\\d+) *Gold per 10 seconds *(<br>|</stats>|</passive>|$)"));
return patterns;
}
private static Side getSide(final JSONObject object, final String key) {
final Integer teamId = getInteger(object, key);
if(teamId == null) {
return null;
}
else if(teamId == 100) {
return Side.BLUE;
}
else if(teamId == 200) {
return Side.PURPLE;
}
return null;
}
private static List<String> getStringList(final JSONObject object, final String key) {
return getList(object, key, s -> (String)s);
}
private final RiotAPI API;
/**
* @param API
* a RiotAPI which will be used to replace foreign key ID values
* with the specified object
*/
public JSONConverter(final RiotAPI API) {
this.API = API;
}
public AggregatedStats getAggregatedStatsFromJSON(final JSONObject aggregatedStatsInfo) {
if(aggregatedStatsInfo == null) {
return null;
}
final Integer averageAssists = getInteger(aggregatedStatsInfo, "averageAssists");
final Integer averageChampionsKilled = getInteger(aggregatedStatsInfo, "averageChampionsKilled");
final Integer averageCombatPlayerScore = getInteger(aggregatedStatsInfo, "averageCombatPlayerScore");
final Integer averageNodeCapture = getInteger(aggregatedStatsInfo, "averageNodeCapture");
final Integer averageNodeCaptureAssist = getInteger(aggregatedStatsInfo, "averageNodeCaptureAssist");
final Integer averageNodeNeutralize = getInteger(aggregatedStatsInfo, "averageNodeNeutralize");
final Integer averageNodeNeutralizeAssist = getInteger(aggregatedStatsInfo, "averageNodeNeutralizeAssist");
final Integer averageNumDeaths = getInteger(aggregatedStatsInfo, "averageNumDeaths");
final Integer averageObjectivePlayerScore = getInteger(aggregatedStatsInfo, "averageObjectivePlayerScore");
final Integer averageTeamObjective = getInteger(aggregatedStatsInfo, "averageTeamObjective");
final Integer averageTotalPlayerScore = getInteger(aggregatedStatsInfo, "averageTotalPlayerScore");
final Integer botGamesPlayed = getInteger(aggregatedStatsInfo, "botGamesPlayed");
final Integer killingSpree = getInteger(aggregatedStatsInfo, "killingSpree");
final Integer maxAssists = getInteger(aggregatedStatsInfo, "maxAssists");
final Integer maxChampionsKilled = getInteger(aggregatedStatsInfo, "maxChampionsKilled");
final Integer maxCombatPlayerScore = getInteger(aggregatedStatsInfo, "maxCombatPlayerScore");
final Integer maxLargestCriticalStrike = getInteger(aggregatedStatsInfo, "maxLargestCriticalStrike");
final Integer maxLargestKillingSpree = getInteger(aggregatedStatsInfo, "maxLargestKillingSpree");
final Integer maxNodeCapture = getInteger(aggregatedStatsInfo, "maxNodeCapture");
final Integer maxNodeCaputreAssist = getInteger(aggregatedStatsInfo, "maxNodeCaputreAssist");
final Integer maxNodeNeutralize = getInteger(aggregatedStatsInfo, "maxNodeNeutralize");
final Integer maxNodeNeutralizeAssist = getInteger(aggregatedStatsInfo, "maxNodeNeutralizeAssist");
final Integer maxNumDeaths = getInteger(aggregatedStatsInfo, "maxNumDeaths");
final Integer maxObjectivePlayerScore = getInteger(aggregatedStatsInfo, "maxObjectivePlayerScore");
final Integer maxTeamObjective = getInteger(aggregatedStatsInfo, "maxTeamObjective");
final Integer maxTimePlayed = getInteger(aggregatedStatsInfo, "maxTimePlayed");
final Integer maxTimeSpentLiving = getInteger(aggregatedStatsInfo, "maxTimeSpentLiving");
final Integer maxTotalPlayerScore = getInteger(aggregatedStatsInfo, "maxTotalPlayerScore");
final Integer mostChampionKillsPerSession = getInteger(aggregatedStatsInfo, "mostChampionKillsPerSession");
final Integer mostSpellsCast = getInteger(aggregatedStatsInfo, "mostSpellsCast");
final Integer normalGamesPlayed = getInteger(aggregatedStatsInfo, "normalGamesPlayed");
final Integer rankedPremadeGamesPlayed = getInteger(aggregatedStatsInfo, "rankedPremadeGamesPlayed");
final Integer rankedSoloGamesPlayed = getInteger(aggregatedStatsInfo, "rankedSoloGamesPlayed");
final Integer totalAssists = getInteger(aggregatedStatsInfo, "totalAssists");
final Integer totalChampionKills = getInteger(aggregatedStatsInfo, "totalChampionKills");
final Integer totalDamageDealt = getInteger(aggregatedStatsInfo, "totalDamageDealt");
final Integer totalDamageTaken = getInteger(aggregatedStatsInfo, "totalDamageTaken");
final Integer totalDeathsPerSession = getInteger(aggregatedStatsInfo, "totalDeathsPerSession");
final Integer totalDoubleKills = getInteger(aggregatedStatsInfo, "totalDoubleKills");
final Integer totalFirstBlood = getInteger(aggregatedStatsInfo, "totalFirstBlood");
final Integer totalGoldEarned = getInteger(aggregatedStatsInfo, "totalGoldEarned");
final Integer totalHeal = getInteger(aggregatedStatsInfo, "totalHeal");
final Integer totalMagicDamageDealt = getInteger(aggregatedStatsInfo, "totalMagicDamageDealt");
final Integer totalMinionKills = getInteger(aggregatedStatsInfo, "totalMinionKills");
final Integer totalNeutralMinionsKilled = getInteger(aggregatedStatsInfo, "totalNeutralMinionsKilled");
final Integer totalNodeCapture = getInteger(aggregatedStatsInfo, "totalNodeCapture");
final Integer totalNodeNeutralize = getInteger(aggregatedStatsInfo, "totalNodeNeutralize");
final Integer totalPentaKills = getInteger(aggregatedStatsInfo, "totalPentaKills");
final Integer totalPhysicalDamageDealt = getInteger(aggregatedStatsInfo, "totalPhysicalDamageDealt");
final Integer totalQuadraKills = getInteger(aggregatedStatsInfo, "totalQuadraKills");
final Integer totalSessionsLost = getInteger(aggregatedStatsInfo, "totalSessionsLost");
final Integer totalSessionsWon = getInteger(aggregatedStatsInfo, "totalSessionsWon");
final Integer totalTripleKills = getInteger(aggregatedStatsInfo, "totalTripleKills");
final Integer totalTurretsKilled = getInteger(aggregatedStatsInfo, "totalTurretsKilled");
final Integer totalUnrealKills = getInteger(aggregatedStatsInfo, "totalUnrealKills");
return new AggregatedStats(averageAssists, averageChampionsKilled, averageCombatPlayerScore, averageNodeCapture, averageNodeCaptureAssist,
averageNodeNeutralize, averageNodeNeutralizeAssist, averageNumDeaths, averageObjectivePlayerScore, averageTeamObjective,
averageTotalPlayerScore, botGamesPlayed, killingSpree, maxAssists, maxChampionsKilled, maxCombatPlayerScore, maxLargestCriticalStrike,
maxLargestKillingSpree, maxNodeCapture, maxNodeCaputreAssist, maxNodeNeutralize, maxNodeNeutralizeAssist, maxNumDeaths,
maxObjectivePlayerScore, maxTeamObjective, maxTimePlayed, maxTimeSpentLiving, maxTotalPlayerScore, mostChampionKillsPerSession, mostSpellsCast,
normalGamesPlayed, rankedPremadeGamesPlayed, rankedSoloGamesPlayed, totalAssists, totalChampionKills, totalDamageDealt, totalDamageTaken,
totalDeathsPerSession, totalDoubleKills, totalFirstBlood, totalGoldEarned, totalHeal, totalMagicDamageDealt, totalMinionKills,
totalNeutralMinionsKilled, totalNodeCapture, totalNodeNeutralize, totalPentaKills, totalPhysicalDamageDealt, totalQuadraKills,
totalSessionsLost, totalSessionsWon, totalTripleKills, totalTurretsKilled, totalUnrealKills);
}
private List<GamePlayer> getAllGamePlayersFromJSON(final JSONArray playerList) {
if(playerList == null) {
return null;
}
final List<Long> summonerIDs = getList(playerList, m -> (Long)((JSONObject)m).get("summonerId"));
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<Long, Summoner> mapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.ID, summoner);
}
return getList(playerList, p -> {
final JSONObject player = (JSONObject)p;
return getGamePlayerFromJSON(mapping.get(player.get("summonerId")), player);
});
}
private List<GamePlayer> getAllGamePlayersFromJSON(final Map<Long, Summoner> players, final JSONArray playerList) {
if(playerList == null) {
return null;
}
return getList(playerList, p -> {
final JSONObject player = (JSONObject)p;
return getGamePlayerFromJSON(players.get(player.get("summonerId")), player);
});
}
protected List<Game> getAllGamesFromJSON(final JSONArray gameList) {
if(gameList == null) {
return null;
}
final Map<Object, JSONArray> playerLists = getMapFromList(gameList, g -> (JSONArray)((JSONObject)g).get("fellowPlayers"));
final List<Long> summonerIDs = new ArrayList<Long>();
final Map<Object, List<Long>> ownership = new HashMap<Object, List<Long>>();
for(final Object obj : playerLists.keySet()) {
final List<Long> IDs = getList(playerLists.get(obj), m -> (Long)((JSONObject)m).get("summonerId"));
summonerIDs.addAll(IDs);
ownership.put(obj, IDs);
}
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<Long, Summoner> IDMapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
IDMapping.put(summoner.ID, summoner);
}
final Map<Object, Map<Long, Summoner>> mapping = new HashMap<Object, Map<Long, Summoner>>();
for(final Object obj : ownership.keySet()) {
final Map<Long, Summoner> subset = new HashMap<Long, Summoner>();
for(final Long ID : ownership.get(obj)) {
subset.put(ID, IDMapping.get(ID));
}
mapping.put(obj, Collections.unmodifiableMap(subset));
}
return getList(gameList, g -> getGameFromJSON(mapping.get(g), (JSONObject)g));
}
private List<LeagueEntry> getAllLeagueEntriesFromJSON(final JSONArray leagueEntryList) {
if(leagueEntryList == null) {
return null;
}
final String sampleID = (String)((JSONObject)leagueEntryList.get(0)).get("playerOrTeamId");
boolean summonerLeague;
try {
Long.parseLong(sampleID);
summonerLeague = true;
}
catch(final NumberFormatException e) {
summonerLeague = false;
}
if(summonerLeague) {
final List<Long> summonerIDs = getList(leagueEntryList, m -> Long.parseLong((String)((JSONObject)m).get("playerOrTeamId")));
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<String, Summoner> mapping = new HashMap<String, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(Long.toString(summoner.ID), summoner);
}
return getList(leagueEntryList, e -> {
final JSONObject entry = (JSONObject)e;
return getLeagueEntryFromJSON(mapping.get(entry.get("playerOrTeamId")), entry);
}, (final LeagueEntry e0, final LeagueEntry e1) -> e1.leaguePoints.compareTo(e0.leaguePoints));
}
else {
final List<String> teamIDs = getList(leagueEntryList, m -> (String)((JSONObject)m).get("playerOrTeamId"));
final List<Team> teams = API.getTeams(teamIDs);
final Map<String, Team> mapping = new HashMap<String, Team>();
for(final Team team : teams) {
mapping.put(team.ID, team);
}
return getList(leagueEntryList, e -> {
final JSONObject entry = (JSONObject)e;
return getLeagueEntryFromJSON(mapping.get(entry.get("playerOrTeamId")), entry);
});
}
}
protected Map<Long, List<Team>> getAllSummonersTeamsFromJSON(final JSONObject teamList, final List<Long> IDs) {
if(teamList == null || IDs.size() != teamList.size()) {
return null;
}
final Map<Long, Map<JSONObject, List<Long>>> rosterIDs = new HashMap<Long, Map<JSONObject, List<Long>>>();
final List<Long> summonerIDs = new ArrayList<Long>();
for(final Long ID : IDs) {
final Map<JSONObject, List<Long>> oneID = new HashMap<JSONObject, List<Long>>();
final JSONArray teams = (JSONArray)teamList.get(ID.toString());
for(final Object teamObj : teams) {
final JSONObject team = (JSONObject)teamObj;
final JSONObject roster = (JSONObject)team.get("roster");
final JSONArray memberList = (JSONArray)roster.get("memberList");
if(memberList == null) {
// Would've already been cached in a non-empty memberList
summonerIDs.add((Long)roster.get("ownerId"));
oneID.put(team, new ArrayList<Long>());
continue;
}
final List<Long> memberIDs = new ArrayList<Long>();
for(final Object memberObj : memberList) {
final JSONObject member = (JSONObject)memberObj;
final Long memberID = (Long)member.get("playerId");
summonerIDs.add(memberID);
memberIDs.add(memberID);
}
oneID.put(team, memberIDs);
}
rosterIDs.put(ID, oneID);
}
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<Long, Summoner> mapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.ID, summoner);
}
final Map<Long, Map<JSONObject, List<Summoner>>> rosters = new HashMap<Long, Map<JSONObject, List<Summoner>>>();
for(final Long ID : rosterIDs.keySet()) {
final Map<JSONObject, List<Long>> teamsByID = rosterIDs.get(ID);
final Map<JSONObject, List<Summoner>> teamsBySummoner = new HashMap<JSONObject, List<Summoner>>();
for(final JSONObject team : teamsByID.keySet()) {
final List<Long> rosterByID = teamsByID.get(team);
final List<Summoner> rosterSummoners = new ArrayList<Summoner>();
for(final Long summonerID : rosterByID) {
rosterSummoners.add(mapping.get(summonerID));
}
teamsBySummoner.put(team, rosterSummoners);
}
rosters.put(ID, teamsBySummoner);
}
final Map<Long, List<Team>> allTeams = new HashMap<Long, List<Team>>();
for(final Long ID : IDs) {
allTeams.put(ID, getAllTeamsFromJSON(rosters.get(ID)));
}
return Collections.unmodifiableMap(allTeams);
}
private List<TeamMemberInformation> getAllTeamMemberInfoFromJSON(final JSONArray teamMemberList) {
if(teamMemberList == null) {
return null;
}
final List<Long> summonerIDs = getList(teamMemberList, m -> (Long)((JSONObject)m).get("playerId"));
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<Long, Summoner> mapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.ID, summoner);
}
return getList(teamMemberList, m -> {
final JSONObject member = (JSONObject)m;
return getTeamMemberInfoFromJSON(mapping.get(member.get("playerId")), member);
});
}
private List<TeamMemberInformation> getAllTeamMemberInfoFromJSON(final List<Summoner> summoners, final JSONArray teamMemberList) {
if(teamMemberList == null) {
return null;
}
final Map<Long, Summoner> mapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.ID, summoner);
}
return getList(teamMemberList, m -> {
final JSONObject member = (JSONObject)m;
return getTeamMemberInfoFromJSON(mapping.get(member.get("playerId")), member);
});
}
protected List<Team> getAllTeamsFromJSON(final JSONObject teamList, final List<String> teamIDs) {
final List<Long> summonerIDs = new ArrayList<Long>();
final Map<JSONObject, List<Long>> rosterIDs = new HashMap<JSONObject, List<Long>>();
for(final String teamID : teamIDs) {
final JSONObject team = (JSONObject)teamList.get(teamID);
final JSONObject roster = (JSONObject)team.get("roster");
final JSONArray memberList = (JSONArray)roster.get("memberList");
if(memberList == null) {
// Would've already been cached in a non-empty memberList
summonerIDs.add((Long)roster.get("ownerId"));
rosterIDs.put(team, new ArrayList<Long>());
continue;
}
final List<Long> IDs = new ArrayList<Long>();
for(final Object memberObj : memberList) {
final JSONObject member = (JSONObject)memberObj;
final Long memberID = (Long)member.get("playerId");
summonerIDs.add(memberID);
IDs.add(memberID);
}
rosterIDs.put(team, IDs);
}
final List<Summoner> summoners = API.getSummonersByID(summonerIDs);
final Map<Long, Summoner> mapping = new HashMap<Long, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.ID, summoner);
}
final Map<JSONObject, List<Summoner>> rosters = new HashMap<JSONObject, List<Summoner>>();
for(final JSONObject team : rosterIDs.keySet()) {
final List<Long> rosterByID = rosterIDs.get(team);
final List<Summoner> rosterBySummoner = new ArrayList<Summoner>();
for(final Long summonerID : rosterByID) {
rosterBySummoner.add(mapping.get(summonerID));
}
rosters.put(team, rosterBySummoner);
}
return getAllTeamsFromJSON(rosters);
}
private List<Team> getAllTeamsFromJSON(final Map<JSONObject, List<Summoner>> rosters) {
final List<Team> teams = new ArrayList<Team>();
for(final JSONObject team : rosters.keySet()) {
teams.add(getTeamFromJSON(rosters.get(team), team));
}
return Collections.unmodifiableList(teams);
}
public BannedChampion getBannedChampionFromJSON(final JSONObject bannedChampionInfo) {
if(bannedChampionInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(bannedChampionInfo, "championId"));
final Integer pickTurn = getInteger(bannedChampionInfo, "pickTurn");
final Side team = getSide(bannedChampionInfo, "teamId");
return new BannedChampion(champion, pickTurn, team);
}
public BasicDataStats getBasicDataStatsFromJSON(final JSONObject basicDataStatsInfo) {
if(basicDataStatsInfo == null) {
return null;
}
final Double flatArmorMod = (Double)basicDataStatsInfo.get("FlatArmorMod");
final Double flatArmorPenetrationMod = (Double)basicDataStatsInfo.get("FlatArmorPenetrationMod");
final Double flatAttackSpeedMod = (Double)basicDataStatsInfo.get("FlatAttackSpeedMod");
final Double flatBlockMod = (Double)basicDataStatsInfo.get("FlatBlockMod");
final Double flatCritChanceMod = (Double)basicDataStatsInfo.get("FlatCritChanceMod");
final Double flatCritDamageMod = (Double)basicDataStatsInfo.get("FlatCritDamageMod");
final Double flatEXPBonus = (Double)basicDataStatsInfo.get("FlatEXPBonus");
final Double flatEnergyPoolMod = (Double)basicDataStatsInfo.get("FlatEnergyPoolMod");
final Double flatEnergyRegenMod = (Double)basicDataStatsInfo.get("FlatEnergyRegenMod");
final Double flatGoldPer10Mod = (Double)basicDataStatsInfo.get("FlatGoldPer10Mod");
final Double flatHPPoolMod = (Double)basicDataStatsInfo.get("FlatHPPoolMod");
final Double flatHPRegenMod = (Double)basicDataStatsInfo.get("FlatHPRegenMod");
final Double flatMPPoolMod = (Double)basicDataStatsInfo.get("FlatMPPoolMod");
final Double flatMPRegenMod = (Double)basicDataStatsInfo.get("FlatMPRegenMod");
final Double flatMagicDamageMod = (Double)basicDataStatsInfo.get("FlatMagicDamageMod");
final Double flatMagicPenetrationMod = (Double)basicDataStatsInfo.get("FlatMagicPenetrationMod");
final Double flatMovementSpeedMod = (Double)basicDataStatsInfo.get("FlatMovementSpeedMod");
final Double flatPhysicalDamageMod = (Double)basicDataStatsInfo.get("FlatPhysicalDamageMod");
final Double flatSpellBlockMod = (Double)basicDataStatsInfo.get("FlatSpellBlockMod");
final Double percentArmorMod = (Double)basicDataStatsInfo.get("PercentArmorMod");
final Double percentArmorPenetrationMod = (Double)basicDataStatsInfo.get("PercentArmorPenetrationMod");
final Double percentAttackSpeedMod = (Double)basicDataStatsInfo.get("PercentAttackSpeedMod");
final Double percentBlockMod = (Double)basicDataStatsInfo.get("PercentBlockMod");
final Double percentCooldownMod = (Double)basicDataStatsInfo.get("PercentCooldownMod");
final Double percentCritChanceMod = (Double)basicDataStatsInfo.get("PercentCritChanceMod");
final Double percentCritDamageMod = (Double)basicDataStatsInfo.get("PercentCritDamageMod");
final Double percentDodgeMod = (Double)basicDataStatsInfo.get("PercentDodgeMod");
final Double percentEXPBonus = (Double)basicDataStatsInfo.get("PercentEXPBonus");
final Double percentHPPoolMod = (Double)basicDataStatsInfo.get("PercentHPPoolMod");
final Double percentHPRegenMod = (Double)basicDataStatsInfo.get("PercentHPRegenMod");
final Double percentLifeStealMod = (Double)basicDataStatsInfo.get("PercentLifeStealMod");
final Double percentMPPoolMod = (Double)basicDataStatsInfo.get("PercentMPPoolMod");
final Double percentMPRegenMod = (Double)basicDataStatsInfo.get("PercentMPRegenMod");
final Double percentMagicDamageMod = (Double)basicDataStatsInfo.get("PercentMagicDamageMod");
final Double percentMagicPenetrationMod = (Double)basicDataStatsInfo.get("PercentMagicPenetrationMod");
final Double percentMovementSpeedMod = (Double)basicDataStatsInfo.get("PercentMovementSpeedMod");
final Double percentPhysicalDamageMod = (Double)basicDataStatsInfo.get("PercentPhysicalDamageMod");
final Double percentSpellBlockMod = (Double)basicDataStatsInfo.get("PercentSpellBlockMod");
final Double percentSpellVampMod = (Double)basicDataStatsInfo.get("PercentSpellVampMod");
final Double rFlatArmorModPerLevel = (Double)basicDataStatsInfo.get("rFlatArmorModPerLevel");
final Double rFlatArmorPenetrationMod = (Double)basicDataStatsInfo.get("rFlatArmorPenetrationMod");
final Double rFlatArmorPenetrationModPerLevel = (Double)basicDataStatsInfo.get("rFlatArmorPenetrationModPerLevel");
final Double rFlatCritChanceModPerLevel = (Double)basicDataStatsInfo.get("rFlatCritChanceModPerLevel");
final Double rFlatCritDamageModPerLevel = (Double)basicDataStatsInfo.get("rFlatCritDamageModPerLevel");
final Double rFlatDodgeMod = (Double)basicDataStatsInfo.get("rFlatDodgeMod");
final Double rFlatDodgeModPerLevel = (Double)basicDataStatsInfo.get("rFlatDodgeModPerLevel");
final Double rFlatEnergyModPerLevel = (Double)basicDataStatsInfo.get("rFlatEnergyModPerLevel");
final Double rFlatEnergyRegenModPerLevel = (Double)basicDataStatsInfo.get("rFlatEnergyRegenModPerLevel");
final Double rFlatGoldPer10Mod = (Double)basicDataStatsInfo.get("rFlatGoldPer10Mod");
final Double rFlatHPModPerLevel = (Double)basicDataStatsInfo.get("rFlatHPModPerLevel");
final Double rFlatHPRegenModPerLevel = (Double)basicDataStatsInfo.get("rFlatHPRegenModPerLevel");
final Double rFlatMPModPerLevel = (Double)basicDataStatsInfo.get("rFlatMPModPerLevel");
final Double rFlatMPRegenModPerLevel = (Double)basicDataStatsInfo.get("rFlatMPRegenModPerLevel");
final Double rFlatMagicDamageModPerLevel = (Double)basicDataStatsInfo.get("rFlatMagicDamageModPerLevel");
final Double rFlatMagicPenetrationMod = (Double)basicDataStatsInfo.get("rFlatMagicPenetrationMod");
final Double rFlatMagicPenetrationModPerLevel = (Double)basicDataStatsInfo.get("rFlatMagicPenetrationModPerLevel");
final Double rFlatMovementSpeedModPerLevel = (Double)basicDataStatsInfo.get("rFlatMovementSpeedModPerLevel");
final Double rFlatPhysicalDamageModPerLevel = (Double)basicDataStatsInfo.get("rFlatPhysicalDamageModPerLevel");
final Double rFlatSpellBlockModPerLevel = (Double)basicDataStatsInfo.get("rFlatSpellBlockModPerLevel");
final Double rFlatTimeDeadMod = (Double)basicDataStatsInfo.get("rFlatTimeDeadMod");
final Double rFlatTimeDeadModPerLevel = (Double)basicDataStatsInfo.get("rFlatTimeDeadModPerLevel");
final Double rPercentArmorPenetrationMod = (Double)basicDataStatsInfo.get("rPercentArmorPenetrationMod");
final Double rPercentArmorPenetrationModPerLevel = (Double)basicDataStatsInfo.get("rPercentArmorPenetrationModPerLevel");
final Double rPercentAttackSpeedModPerLevel = (Double)basicDataStatsInfo.get("rPercentAttackSpeedModPerLevel");
final Double rPercentCooldownMod = (Double)basicDataStatsInfo.get("rPercentCooldownMod");
final Double rPercentCooldownModPerLevel = (Double)basicDataStatsInfo.get("rPercentCooldownModPerLevel");
final Double rPercentMagicPenetrationMod = (Double)basicDataStatsInfo.get("rPercentMagicPenetrationMod");
final Double rPercentMagicPenetrationModPerLevel = (Double)basicDataStatsInfo.get("rPercentMagicPenetrationModPerLevel");
final Double rPercentMovementSpeedModPerLevel = (Double)basicDataStatsInfo.get("rPercentMovementSpeedModPerLevel");
final Double rPercentTimeDeadMod = (Double)basicDataStatsInfo.get("rPercentTimeDeadMod");
final Double rPercentTimeDeadModPerLevel = (Double)basicDataStatsInfo.get("rPercentTimeDeadModPerLevel");
return new BasicDataStats(flatArmorMod, flatArmorPenetrationMod, flatAttackSpeedMod, flatBlockMod, flatCritChanceMod, flatCritDamageMod, flatEXPBonus,
flatEnergyPoolMod, flatEnergyRegenMod, flatGoldPer10Mod, flatHPPoolMod, flatHPRegenMod, flatMPPoolMod, flatMPRegenMod, flatMagicDamageMod,
flatMagicPenetrationMod, flatMovementSpeedMod, flatPhysicalDamageMod, flatSpellBlockMod, percentArmorMod, percentArmorPenetrationMod,
percentAttackSpeedMod, percentBlockMod, percentCooldownMod, percentCritChanceMod, percentCritDamageMod, percentDodgeMod, percentEXPBonus,
percentHPPoolMod, percentHPRegenMod, percentLifeStealMod, percentMPPoolMod, percentMPRegenMod, percentMagicDamageMod,
percentMagicPenetrationMod, percentMovementSpeedMod, percentPhysicalDamageMod, percentSpellBlockMod, percentSpellVampMod,
rFlatArmorModPerLevel, rFlatArmorPenetrationMod, rFlatArmorPenetrationModPerLevel, rFlatCritChanceModPerLevel, rFlatCritDamageModPerLevel,
rFlatDodgeMod, rFlatDodgeModPerLevel, rFlatEnergyModPerLevel, rFlatEnergyRegenModPerLevel, rFlatGoldPer10Mod, rFlatHPModPerLevel,
rFlatHPRegenModPerLevel, rFlatMPModPerLevel, rFlatMPRegenModPerLevel, rFlatMagicDamageModPerLevel, rFlatMagicPenetrationMod,
rFlatMagicPenetrationModPerLevel, rFlatMovementSpeedModPerLevel, rFlatPhysicalDamageModPerLevel, rFlatSpellBlockModPerLevel, rFlatTimeDeadMod,
rFlatTimeDeadModPerLevel, rPercentArmorPenetrationMod, rPercentArmorPenetrationModPerLevel, rPercentAttackSpeedModPerLevel,
rPercentCooldownMod, rPercentCooldownModPerLevel, rPercentMagicPenetrationMod, rPercentMagicPenetrationModPerLevel,
rPercentMovementSpeedModPerLevel, rPercentTimeDeadMod, rPercentTimeDeadModPerLevel);
}
public Block getBlockFromJSON(final JSONObject blockInfo) {
if(blockInfo == null) {
return null;
}
final Boolean recMath = (Boolean)blockInfo.get("recMath");
final String type = (String)blockInfo.get("type");
final List<BlockItem> items = getList(blockInfo, "items", b -> getBlockItemFromJSON((JSONObject)b));
return new Block(items, recMath, type);
}
public BlockItem getBlockItemFromJSON(final JSONObject blockItemInfo) {
if(blockItemInfo == null) {
return null;
}
final Integer count = getInteger(blockItemInfo, "count");
final Integer ID = getInteger(blockItemInfo, "id");
/*
* Riot's recommended items include some IDs that no longer exist in the
* database. For now, this will be the fix.
*/
// TODO: Remove this after rito fixes it.
Item item = null;
if(ID != 3186 && ID != 3176 && ID != 3210) {
item = API.getItem(ID);
}
return new BlockItem(count, item);
}
public Champion getChampionFromJSON(final JSONObject championInfo) {
if(championInfo == null) {
return null;
}
final List<String> allyTips = getStringList(championInfo, "allytips");
final List<String> enemyTips = getStringList(championInfo, "enemytips");
final List<String> tags = getStringList(championInfo, "tags");
final String blurb = (String)championInfo.get("blurb");
final String key = (String)championInfo.get("key");
final String lore = (String)championInfo.get("lore");
final String name = (String)championInfo.get("name");
final String partype = (String)championInfo.get("partype");
final String title = (String)championInfo.get("title");
final Integer ID = getInteger(championInfo, "id");
final Image image = getImageFromJSON((JSONObject)championInfo.get("image"));
final Information info = getInformationFromJSON((JSONObject)championInfo.get("info"));
final Passive passive = getPassiveFromJSON((JSONObject)championInfo.get("passive"));
final Stats stats = getStatsFromJSON((JSONObject)championInfo.get("stats"));
final List<Recommended> recommended = getList(championInfo, "recommended", r -> getRecommendedFromJSON((JSONObject)r));
final List<Skin> skins = getList(championInfo, "skins", s -> getSkinFromJSON((JSONObject)s));
final List<ChampionSpell> spells = getList(championInfo, "spells", s -> getChampionSpellFromJSON((JSONObject)s));
return new Champion(allyTips, enemyTips, tags, blurb, key, lore, name, partype, title, ID, image, info, passive, recommended, skins, spells, stats);
}
public ChampionSpell getChampionSpellFromJSON(final JSONObject championSpellInfo) {
if(championSpellInfo == null) {
return null;
}
final List<Double> cooldown = getDoubleList(championSpellInfo, "cooldown");
final List<Integer> cost = getIntegerList(championSpellInfo, "cost");
final List<String> effectBurn = getStringList(championSpellInfo, "effectBurn");
final Integer maxRank = getInteger(championSpellInfo, "maxrank");
final String cooldownBurn = (String)championSpellInfo.get("cooldownBurn");
final String costBurn = (String)championSpellInfo.get("costBurn");
final String costType = (String)championSpellInfo.get("costType");
final String description = (String)championSpellInfo.get("description");
final String key = (String)championSpellInfo.get("key");
final String name = (String)championSpellInfo.get("name");
final String rangeBurn = (String)championSpellInfo.get("rangeBurn");
final String resource = (String)championSpellInfo.get("resource");
final String sanitizedDescription = (String)championSpellInfo.get("sanitizedDescription");
final String sanitizedTooltip = (String)championSpellInfo.get("sanitizedTooltip");
final String tooltip = (String)championSpellInfo.get("tooltip");
final Image image = getImageFromJSON((JSONObject)championSpellInfo.get("image"));
final LevelTip levelTip = getLevelTipFromJSON((JSONObject)championSpellInfo.get("leveltip"));
final List<Image> altImages = getList(championSpellInfo, "altimages", i -> getImageFromJSON((JSONObject)i));
final List<SpellVariables> vars = getList(championSpellInfo, "vars", v -> getSpellVariablesFromJSON((JSONObject)v));
final List<List<Double>> effect = getList(championSpellInfo, "effect", l -> getDoubleList((JSONArray)l));
List<Integer> range;
final Object val = championSpellInfo.get("range");
if(val instanceof String) {
range = null;
}
else {
range = getIntegerList((JSONArray)val);
}
return new ChampionSpell(altImages, cooldown, cooldownBurn, costBurn, costType, description, key, name, rangeBurn, resource, sanitizedDescription,
sanitizedTooltip, tooltip, cost, range, effect, effectBurn, image, levelTip, maxRank, vars);
}
public ChampionStats getChampionStatsFromJSON(final JSONObject championStatsInfo) {
if(championStatsInfo == null) {
return null;
}
final AggregatedStats stats = getAggregatedStatsFromJSON((JSONObject)championStatsInfo.get("stats"));
Champion champion;
final Integer championID = getInteger(championStatsInfo, "id");
if(championID == null || championID == 0) {
champion = null;
}
else {
champion = API.getChampion(championID);
}
return new ChampionStats(champion, stats);
}
public ChampionStatus getChampionStatusFromJSON(final JSONObject championStatusInfo) {
if(championStatusInfo == null) {
return null;
}
final Boolean active = (Boolean)championStatusInfo.get("active");
final Boolean botEnabled = (Boolean)championStatusInfo.get("botEnabled");
final Boolean botMmEnabled = (Boolean)championStatusInfo.get("botMmEnabled");
final Boolean freeToPlay = (Boolean)championStatusInfo.get("freeToPlay");
final Boolean rankedPlayEnabled = (Boolean)championStatusInfo.get("rankedPlayEnabled");
final Champion champion = API.getChampion(getInteger(championStatusInfo, "id"));
return new ChampionStatus(active, botEnabled, botMmEnabled, freeToPlay, rankedPlayEnabled, champion);
}
public Event getEventFromJSON(final JSONObject eventInfo, final Map<Integer, Participant> participants, final Map<Side, MatchTeam> teams) {
if(eventInfo == null) {
return null;
}
String typeName = (String)eventInfo.get("buildingType");
final BuildingType buildingType = typeName == null ? null : BuildingType.valueOf(typeName);
typeName = (String)eventInfo.get("eventType");
final EventType eventType = typeName == null ? null : EventType.valueOf(typeName);
typeName = (String)eventInfo.get("laneType");
final LaneType laneType = typeName == null ? null : LaneType.valueOf(typeName);
typeName = (String)eventInfo.get("levelUpType");
final LevelUpType levelUpType = typeName == null ? null : LevelUpType.valueOf(typeName);
typeName = (String)eventInfo.get("monsterType");
final MonsterType monsterType = typeName == null ? null : MonsterType.valueOf(typeName);
typeName = (String)eventInfo.get("towerType");
final TowerType towerType = typeName == null ? null : TowerType.valueOf(typeName);
typeName = (String)eventInfo.get("wardType");
final WardType wardType = typeName == null ? null : WardType.valueOf(typeName);
Integer id = getInteger(eventInfo, "itemAfter");
final Item itemAfter = id == null ? null : API.getItem(id);
id = getInteger(eventInfo, "itemBefore");
final Item itemBefore = id == null ? null : API.getItem(id);
id = getInteger(eventInfo, "itemBefore");
final Item item = id == null ? null : API.getItem(id);
final Integer skillSlot = getInteger(eventInfo, "skillSlot");
final Side side = getSide(eventInfo, "teamId");
final Position position = getPositionFromJSON((JSONObject)eventInfo.get("position"));
final Duration timestamp = getDuration(eventInfo, "timestamp", ChronoUnit.MILLIS);
final Participant creator = participants.get(getInteger(eventInfo, "creatorId"));
final Participant killer = participants.get(getInteger(eventInfo, "killerId"));
final Participant victim = participants.get(getInteger(eventInfo, "victimId"));
final Participant participant = participants.get(getInteger(eventInfo, "participantId"));
final MatchTeam team = teams.get(getSide(eventInfo, "teamId"));
final List<Integer> participantIDs = getIntegerList(eventInfo, "assistingParticipantIds");
final List<Participant> assistingParticipants = participantIDs == null ? null : participantIDs.stream().map((ID) -> participants.get(ID))
.collect(Collectors.toList());
return new Event(assistingParticipants, buildingType, creator, killer, victim, participant, eventType, itemAfter, itemBefore, item, laneType,
levelUpType, monsterType, position, side, skillSlot, team, timestamp, towerType, wardType);
}
@SuppressWarnings("unchecked")
public Frame getFrameFromJSON(final JSONObject frameInfo, final Map<Integer, Participant> participants, final Map<Side, MatchTeam> teams) {
if(frameInfo == null) {
return null;
}
final List<Event> events = getList(frameInfo, "events", (e) -> getEventFromJSON((JSONObject)e, participants, teams));
final Duration timestamp = getDuration(frameInfo, "timestamp", ChronoUnit.MILLIS);
Map<Participant, ParticipantFrame> participantFrames;
final Map<String, JSONObject> pFrames = (Map<String, JSONObject>)frameInfo.get("participantFrames");
if(pFrames == null) {
participantFrames = null;
}
else {
participantFrames = pFrames
.entrySet()
.stream()
.collect(
Collectors.toMap((entry) -> participants.get(new Integer(entry.getKey())),
(entry) -> getParticipantFrameFromJSON(entry.getValue(), participants.get(new Integer(entry.getKey())))));
}
return new Frame(events, participantFrames, timestamp);
}
public Game getGameFromJSON(final JSONObject gameInfo) {
if(gameInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(gameInfo, "championId"));
final LocalDateTime createDate = getDateTime(gameInfo, "createDate");
final Long ID = (Long)gameInfo.get("gameId");
final GameMode gameMode = GameMode.valueOf((String)gameInfo.get("gameMode"));
final GameType gameType = GameType.valueOf((String)gameInfo.get("gameType"));
final SubType subType = SubType.valueOf((String)gameInfo.get("subType"));
final Boolean invalid = (Boolean)gameInfo.get("invalid");
final Integer IPEarned = getInteger(gameInfo, "ipEarned");
final Integer level = getInteger(gameInfo, "level");
final MatchMap map = getMap(getInteger(gameInfo, "mapId"));
final SummonerSpell spell1 = API.getSummonerSpell(getInteger(gameInfo, "spell1"));
final SummonerSpell spell2 = API.getSummonerSpell(getInteger(gameInfo, "spell2"));
final RawStats stats = getRawStatsFromJSON((JSONObject)gameInfo.get("stats"));
final Side team = getSide(gameInfo, "teamId");
final List<GamePlayer> fellowPlayers = getAllGamePlayersFromJSON((JSONArray)gameInfo.get("fellowPlayers"));
return new Game(champion, createDate, fellowPlayers, gameMode, gameType, ID, invalid, IPEarned, level, map, spell1, spell2, stats, subType, team);
}
private Game getGameFromJSON(final Map<Long, Summoner> players, final JSONObject gameInfo) {
if(gameInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(gameInfo, "championId"));
final LocalDateTime createDate = getDateTime(gameInfo, "createDate");
final Long ID = (Long)gameInfo.get("gameId");
final GameMode gameMode = GameMode.valueOf((String)gameInfo.get("gameMode"));
final GameType gameType = GameType.valueOf((String)gameInfo.get("gameType"));
final SubType subType = SubType.valueOf((String)gameInfo.get("subType"));
final Boolean invalid = (Boolean)gameInfo.get("invalid");
final Integer IPEarned = getInteger(gameInfo, "ipEarned");
final Integer level = getInteger(gameInfo, "level");
final MatchMap map = getMap(getInteger(gameInfo, "mapId"));
final SummonerSpell spell1 = API.getSummonerSpell(getInteger(gameInfo, "spell1"));
final SummonerSpell spell2 = API.getSummonerSpell(getInteger(gameInfo, "spell2"));
final RawStats stats = getRawStatsFromJSON((JSONObject)gameInfo.get("stats"));
final Side team = getSide(gameInfo, "teamId");
final List<GamePlayer> fellowPlayers = getAllGamePlayersFromJSON(players, (JSONArray)gameInfo.get("fellowPlayers"));
return new Game(champion, createDate, fellowPlayers, gameMode, gameType, ID, invalid, IPEarned, level, map, spell1, spell2, stats, subType, team);
}
public com.robrua.orianna.type.game.GamePlayer getGamePlayerFromJSON(final JSONObject playerInfo) {
if(playerInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(playerInfo, "championId"));
final Summoner summoner = API.getSummonerByID((Long)playerInfo.get("summonerId"));
final Side team = getSide(playerInfo, "teamId");
return new GamePlayer(champion, summoner, team);
}
public GamePlayer getGamePlayerFromJSON(final Summoner summoner, final JSONObject playerInfo) {
if(playerInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(playerInfo, "championId"));
final Side team = getSide(playerInfo, "teamId");
return new GamePlayer(champion, summoner, team);
}
public Gold getGoldFromJSON(final JSONObject goldInfo) {
if(goldInfo == null) {
return null;
}
final Integer base = getInteger(goldInfo, "base");
final Integer sell = getInteger(goldInfo, "sell");
final Integer total = getInteger(goldInfo, "total");
final Boolean purchasable = (Boolean)goldInfo.get("purchasable");
return new Gold(base, sell, total, purchasable);
}
public Image getImageFromJSON(final JSONObject imageInfo) {
if(imageInfo == null) {
return null;
}
final String full = (String)imageInfo.get("full");
final String group = (String)imageInfo.get("group");
final String sprite = (String)imageInfo.get("sprite");
final Integer h = getInteger(imageInfo, "h");
final Integer w = getInteger(imageInfo, "w");
final Integer x = getInteger(imageInfo, "x");
final Integer y = getInteger(imageInfo, "y");
return new Image(full, group, sprite, h, w, x, y);
}
public Information getInformationFromJSON(final JSONObject informationInfo) {
if(informationInfo == null) {
return null;
}
final Integer attack = getInteger(informationInfo, "attack");
final Integer defense = getInteger(informationInfo, "defense");
final Integer difficulty = getInteger(informationInfo, "difficulty");
final Integer magic = getInteger(informationInfo, "magic");
return new Information(attack, defense, difficulty, magic);
}
private Item getItem(final JSONObject object, final String key) {
final Integer ID = getInteger(object, key);
if(ID == null) {
return null;
}
return API.getItem(ID);
}
@SuppressWarnings("unchecked")
public Item getItemFromJSON(final JSONObject itemInfo) {
if(itemInfo == null) {
return null;
}
final String colloq = (String)itemInfo.get("colloq");
final String description = (String)itemInfo.get("description");
final String group = (String)itemInfo.get("group");
final String name = (String)itemInfo.get("name");
final String plaintext = (String)itemInfo.get("plaintext");
final String requiredChampion = (String)itemInfo.get("requiredChampion");
final String sanitizedDescription = (String)itemInfo.get("sanitizedDescription");
final Boolean consumeOnFull = (Boolean)itemInfo.get("consumeOnFull");
final Boolean consumed = (Boolean)itemInfo.get("consumed");
final Boolean hideFromAll = (Boolean)itemInfo.get("hideFromAll");
final Boolean inStore = (Boolean)itemInfo.get("inStore");
final Integer depth = getInteger(itemInfo, "depth");
final Integer ID = getInteger(itemInfo, "id");
final Integer specialRecipe = getInteger(itemInfo, "specialRecipe");
final Integer stacks = getInteger(itemInfo, "stacks");
final Gold gold = getGoldFromJSON((JSONObject)itemInfo.get("gold"));
final Image image = getImageFromJSON((JSONObject)itemInfo.get("image"));
final MetaData rune = getMetaDataFromJSON((JSONObject)itemInfo.get("rune"));
final List<String> from = getStringList(itemInfo, "from");
final List<String> into = getStringList(itemInfo, "into");
final List<String> tags = getStringList(itemInfo, "tags");
Map<String, Boolean> maps = (Map<String, Boolean>)itemInfo.get("maps");
if(maps != null) {
maps = Collections.unmodifiableMap(maps);
}
/*
* There's a few things Riot doesn't send as stats yet, so we have to
* parse them out of the description and add them ourselves.
*/
// TODO: Remove this after rito fixes it.
final JSONObject statsObj = (JSONObject)itemInfo.get("stats");
final Map<String, Pattern> patterns = getScrapedStatPatterns();
patterns.keySet().parallelStream().forEach((stat) -> {
final Matcher matcher = patterns.get(stat).matcher(description);
if(matcher.find()) {
statsObj.put(stat, new Double(matcher.group(1)));
}
});
final BasicDataStats stats = getBasicDataStatsFromJSON(statsObj);
return new Item(colloq, description, group, name, plaintext, requiredChampion, sanitizedDescription, consumeOnFull, consumed, hideFromAll, inStore,
depth, ID, specialRecipe, stacks, from, into, tags, gold, image, maps, rune, stats);
}
public LeagueEntry getLeagueEntryFromJSON(final JSONObject leagueEntryInfo) {
if(leagueEntryInfo == null) {
return null;
}
final String division = (String)leagueEntryInfo.get("division");
final String playerOrTeamName = (String)leagueEntryInfo.get("playerOrTeamName");
final Boolean isFreshBlood = (Boolean)leagueEntryInfo.get("isFreshBlood");
final Boolean isHotStreak = (Boolean)leagueEntryInfo.get("isHotStreak");
final Boolean isInactive = (Boolean)leagueEntryInfo.get("isInactive");
final Boolean isVeteran = (Boolean)leagueEntryInfo.get("isVeteran");
final Integer leaguePoints = getInteger(leagueEntryInfo, "leaguePoints");
final Integer wins = getInteger(leagueEntryInfo, "wins");
final MiniSeries miniSeries = getMiniSeriesFromJSON((JSONObject)leagueEntryInfo.get("miniSeries"));
final String IDStr = (String)leagueEntryInfo.get("playerOrTeamId");
try {
final Long ID = Long.parseLong(IDStr);
final Summoner player = API.getSummonerByID(ID);
if(player == null) {
throw new NumberFormatException("IDStr wasn't a summoner ID!");
}
return new LeagueEntry(player, division, playerOrTeamName, isFreshBlood, isHotStreak, isInactive, isVeteran, leaguePoints, wins, miniSeries);
}
catch(final NumberFormatException e) {
final Team team = API.getTeam(IDStr);
return new LeagueEntry(team, division, playerOrTeamName, isFreshBlood, isHotStreak, isInactive, isVeteran, leaguePoints, wins, miniSeries);
}
}
private LeagueEntry getLeagueEntryFromJSON(final Summoner player, final JSONObject leagueEntryInfo) {
if(leagueEntryInfo == null) {
return null;
}
final String division = (String)leagueEntryInfo.get("division");
final String playerOrTeamName = (String)leagueEntryInfo.get("playerOrTeamName");
final Boolean isFreshBlood = (Boolean)leagueEntryInfo.get("isFreshBlood");
final Boolean isHotStreak = (Boolean)leagueEntryInfo.get("isHotStreak");
final Boolean isInactive = (Boolean)leagueEntryInfo.get("isInactive");
final Boolean isVeteran = (Boolean)leagueEntryInfo.get("isVeteran");
final Integer leaguePoints = getInteger(leagueEntryInfo, "leaguePoints");
final Integer wins = getInteger(leagueEntryInfo, "wins");
final MiniSeries miniSeries = getMiniSeriesFromJSON((JSONObject)leagueEntryInfo.get("miniSeries"));
return new LeagueEntry(player, division, playerOrTeamName, isFreshBlood, isHotStreak, isInactive, isVeteran, leaguePoints, wins, miniSeries);
}
private LeagueEntry getLeagueEntryFromJSON(final Team team, final JSONObject leagueEntryInfo) {
if(leagueEntryInfo == null) {
return null;
}
final String division = (String)leagueEntryInfo.get("division");
final String playerOrTeamName = (String)leagueEntryInfo.get("playerOrTeamName");
final Boolean isFreshBlood = (Boolean)leagueEntryInfo.get("isFreshBlood");
final Boolean isHotStreak = (Boolean)leagueEntryInfo.get("isHotStreak");
final Boolean isInactive = (Boolean)leagueEntryInfo.get("isInactive");
final Boolean isVeteran = (Boolean)leagueEntryInfo.get("isVeteran");
final Integer leaguePoints = getInteger(leagueEntryInfo, "leaguePoints");
final Integer wins = getInteger(leagueEntryInfo, "wins");
final MiniSeries miniSeries = getMiniSeriesFromJSON((JSONObject)leagueEntryInfo.get("miniSeries"));
return new LeagueEntry(team, division, playerOrTeamName, isFreshBlood, isHotStreak, isInactive, isVeteran, leaguePoints, wins, miniSeries);
}
public League getLeagueFromJSON(final JSONObject leagueInfo) {
if(leagueInfo == null) {
return null;
}
final String name = (String)leagueInfo.get("name");
final LeagueType queue = LeagueType.valueOf((String)leagueInfo.get("queue"));
final Tier tier = Tier.valueOf((String)leagueInfo.get("tier"));
final List<LeagueEntry> entries = getAllLeagueEntriesFromJSON((JSONArray)leagueInfo.get("entries"));
return new League(entries, queue, name, tier);
}
public LevelTip getLevelTipFromJSON(final JSONObject levelTipInfo) {
if(levelTipInfo == null) {
return null;
}
final List<String> effect = getStringList(levelTipInfo, "effect");
final List<String> label = getStringList(levelTipInfo, "label");
return new LevelTip(effect, label);
}
public Mastery getMasteryFromJSON(final JSONObject masteryInfo) {
if(masteryInfo == null) {
return null;
}
final List<String> description = getStringList(masteryInfo, "description");
final List<String> sanitizedDescription = getStringList(masteryInfo, "sanitizedDescription");
final Integer ID = getInteger(masteryInfo, "id");
final Integer ranks = getInteger(masteryInfo, "ranks");
final Image image = getImageFromJSON((JSONObject)masteryInfo.get("image"));
final String name = (String)masteryInfo.get("name");
final String prereq = (String)masteryInfo.get("prereq");
return new Mastery(description, sanitizedDescription, ID, ranks, image, name, prereq);
}
public MasteryPage getMasteryPageFromJSON(final JSONObject masteryPageInfo, final MasteryTree masteryTree) {
if(masteryPageInfo == null) {
return null;
}
final Long ID = (Long)masteryPageInfo.get("id");
final Boolean current = (Boolean)masteryPageInfo.get("current");
final String name = (String)masteryPageInfo.get("name");
final List<MasterySlot> masteries = getList(masteryPageInfo, "masteries", m -> getMasterySlotFromJSON((JSONObject)m, masteryTree));
return new MasteryPage(current, ID, masteries, name);
}
public MasterySlot getMasterySlotFromJSON(final JSONObject masterySlotInfo, final MasteryTree masteryTree) {
if(masterySlotInfo == null) {
return null;
}
final Integer rank = getInteger(masterySlotInfo, "rank");
final Integer ID = getInteger(masterySlotInfo, "id");
final Mastery mastery = API.getMastery(ID);
return new MasterySlot(mastery, rank, masteryTree.typeOf(mastery));
}
public MasteryTree getMasteryTreeFromJSON(final JSONObject masteryTreeInfo) {
if(masteryTreeInfo == null) {
return null;
}
final List<MasteryTreeList> defense = getList(masteryTreeInfo, "Defense", l -> getMasteryTreeListFromJSON((JSONObject)l));
final List<MasteryTreeList> offense = getList(masteryTreeInfo, "Offense", l -> getMasteryTreeListFromJSON((JSONObject)l));
final List<MasteryTreeList> utility = getList(masteryTreeInfo, "Utility", l -> getMasteryTreeListFromJSON((JSONObject)l));
return new MasteryTree(defense, offense, utility);
}
public MasteryTreeItem getMasteryTreeItemFromJSON(final JSONObject masteryTreeItemInfo) {
if(masteryTreeItemInfo == null) {
return null;
}
final Mastery mastery = API.getMastery(getInteger(masteryTreeItemInfo, "masteryId"));
final String prereq = (String)masteryTreeItemInfo.get("prereq");
return new MasteryTreeItem(mastery, prereq);
}
public MasteryTreeList getMasteryTreeListFromJSON(final JSONObject masteryTreeListInfo) {
if(masteryTreeListInfo == null) {
return null;
}
final List<MasteryTreeItem> masteryTreeItems = getList(masteryTreeListInfo, "masteryTreeItems", i -> getMasteryTreeItemFromJSON((JSONObject)i));
return new MasteryTreeList(masteryTreeItems);
}
public List<MatchSummary> getMatchHistoryFromJSON(final JSONArray matchHistoryInfo) {
if(matchHistoryInfo == null) {
return null;
}
final List<String> summonerNames = new ArrayList<String>();
for(final Object msi : matchHistoryInfo) {
final JSONObject matchSummaryInfo = (JSONObject)msi;
final JSONArray participantIdentityList = (JSONArray)matchSummaryInfo.get("participantIdentities");
final List<JSONObject> plrs = getList(participantIdentityList, p -> (JSONObject)((JSONObject)p).get("player"));
final List<String> names = plrs.stream().map((plr) -> (String)plr.get("summonerName")).filter((name) -> name != null).collect(Collectors.toList());
summonerNames.addAll(names);
}
final List<Summoner> summoners = API.getSummoners(summonerNames);
final Map<String, Summoner> mapping = new HashMap<String, Summoner>();
for(final Summoner summoner : summoners) {
mapping.put(summoner.name, summoner);
}
return getList(matchHistoryInfo, (m) -> getMatchSummaryFromJSON(mapping, (JSONObject)m));
}
public MatchHistorySummary getMatchHistorySummaryFromJSON(final JSONObject matchHistorySummaryInfo) {
if(matchHistorySummaryInfo == null) {
return null;
}
final Integer assists = getInteger(matchHistorySummaryInfo, "assists");
final Integer deaths = getInteger(matchHistorySummaryInfo, "deaths");
final Integer kills = getInteger(matchHistorySummaryInfo, "kills");
final MatchMap map = getMap(getInteger(matchHistorySummaryInfo, "mapId"));
final Integer opposingTeamKills = getInteger(matchHistorySummaryInfo, "opposingTeamKills");
final LocalDateTime date = getDateTime(matchHistorySummaryInfo, "date");
final Long gameID = (Long)matchHistorySummaryInfo.get("gameId");
final String gameMode = (String)matchHistorySummaryInfo.get("gameMode");
final String opposingTeamName = (String)matchHistorySummaryInfo.get("opposingTeamName");
final Boolean invalid = (Boolean)matchHistorySummaryInfo.get("invalid");
final Boolean win = (Boolean)matchHistorySummaryInfo.get("win");
return new MatchHistorySummary(assists, deaths, kills, opposingTeamKills, map, date, gameID, gameMode, opposingTeamName, invalid, win);
}
public MatchSummary getMatchSummaryFromJSON(final JSONObject matchSummaryInfo) {
if(matchSummaryInfo == null) {
return null;
}
final JSONArray identities = (JSONArray)matchSummaryInfo.get("participantIdentities");
final List<JSONObject> plrs = getList(identities, p -> (JSONObject)((JSONObject)p).get("player"));
final List<String> summonerNames = plrs.stream().map((plr) -> (String)plr.get("summonerName")).filter((name) -> name != null)
.collect(Collectors.toList());
final List<Summoner> summoners = API.getSummoners(summonerNames);
final Map<String, Summoner> mapping = new HashMap<String, Summoner>();
for(final Summoner summoner : summoners) {
if(summoner != null) {
mapping.put(summoner.name, summoner);
}
}
return getMatchSummaryFromJSON(mapping, matchSummaryInfo);
}
private MatchSummary getMatchSummaryFromJSON(final Map<String, Summoner> summoners, final JSONObject matchSummaryInfo) {
if(matchSummaryInfo == null) {
return null;
}
final MatchMap map = getMap(getInteger(matchSummaryInfo, "mapId"));
final LocalDateTime creation = getDateTime(matchSummaryInfo, "matchCreation");
final Duration duration = getDuration(matchSummaryInfo, "matchDuration", ChronoUnit.SECONDS);
final Long ID = (Long)matchSummaryInfo.get("matchId");
final String version = (String)matchSummaryInfo.get("matchVersion");
final QueueType queueType = QueueType.valueOf((String)matchSummaryInfo.get("queueType"));
final Region region = Region.valueOf((String)matchSummaryInfo.get("region"));
final Season season = Season.valueOf((String)matchSummaryInfo.get("season"));
final List<MatchTeam> teams = getList(matchSummaryInfo, "teams", (t) -> getMatchTeamFromJSON((JSONObject)t));
final Map<Side, MatchTeam> teamColors = teams == null ? null : teams.stream().collect(Collectors.toMap((team) -> team.side, (team) -> team));
final JSONArray identities = (JSONArray)matchSummaryInfo.get("participantIdentities");
final Map<Integer, Player> participantPlayers = new HashMap<Integer, Player>();
for(final Object iden : identities) {
final JSONObject identity = (JSONObject)iden;
participantPlayers.put(getInteger(identity, "participantId"), getPlayerFromJSON((JSONObject)identity.get("player")));
}
final List<Participant> participants = getList(matchSummaryInfo, "participants",
(p) -> getParticipantFromJSON((JSONObject)p, teamColors, participantPlayers));
final Map<Integer, Participant> participantIDs = participants.stream().collect(
Collectors.toMap((participant) -> participant.ID, (participant) -> participant));
final MatchTimeline timeline = getMatchTimelineFromJSON((JSONObject)matchSummaryInfo.get("timeline"), participantIDs, teamColors);
return new MatchSummary(creation, duration, ID, map, participants, queueType, region, season, teams, timeline, version);
}
public MatchTeam getMatchTeamFromJSON(final JSONObject matchTeamInfo) {
if(matchTeamInfo == null) {
return null;
}
final List<BannedChampion> bans = getList(matchTeamInfo, "bans", (b) -> getBannedChampionFromJSON((JSONObject)b));
final Integer baronKills = getInteger(matchTeamInfo, "baronKills");
final Integer dragonKills = getInteger(matchTeamInfo, "dragonKills");
final Integer inhibitorKills = getInteger(matchTeamInfo, "inhibitorKills");
final Integer towerKills = getInteger(matchTeamInfo, "towerKills");
final Integer vilemawKills = getInteger(matchTeamInfo, "vilemawKills");
final Boolean firstBaron = (Boolean)matchTeamInfo.get("firstBaron");
final Boolean firstBlood = (Boolean)matchTeamInfo.get("firstBlood");
final Boolean firstDragon = (Boolean)matchTeamInfo.get("firstDragon");
final Boolean firstInhibitor = (Boolean)matchTeamInfo.get("firstInhibitor");
final Boolean firstTower = (Boolean)matchTeamInfo.get("firstTower");
final Boolean winner = (Boolean)matchTeamInfo.get("winner");
final Side side = getSide(matchTeamInfo, "teamId");
return new MatchTeam(bans, dragonKills, baronKills, inhibitorKills, towerKills, vilemawKills, firstBaron, firstBlood, firstDragon, firstInhibitor,
firstTower, winner, side);
}
public MatchTimeline getMatchTimelineFromJSON(final JSONObject matchTimelineInfo, final Map<Integer, Participant> participants,
final Map<Side, MatchTeam> teams) {
if(matchTimelineInfo == null) {
return null;
}
final Duration frameInterval = getDuration(matchTimelineInfo, "frameInterval", ChronoUnit.MILLIS);
final List<Frame> frames = getList(matchTimelineInfo, "frames", (f) -> getFrameFromJSON((JSONObject)f, participants, teams));
return new MatchTimeline(frameInterval, frames);
}
public MetaData getMetaDataFromJSON(final JSONObject metaDataInfo) {
if(metaDataInfo == null) {
return null;
}
final Boolean isRune = (Boolean)metaDataInfo.get("isRune");
final String tier = (String)metaDataInfo.get("tier");
final String type = (String)metaDataInfo.get("type");
return new MetaData(isRune, tier, RuneType.fromString(type));
}
public MiniSeries getMiniSeriesFromJSON(final JSONObject miniSeriesInfo) {
if(miniSeriesInfo == null) {
return null;
}
final Integer losses = getInteger(miniSeriesInfo, "losses");
final Integer target = getInteger(miniSeriesInfo, "target");
final Integer wins = getInteger(miniSeriesInfo, "wins");
final String progress = (String)miniSeriesInfo.get("progress");
return new MiniSeries(losses, target, wins, progress);
}
public ParticipantFrame getParticipantFrameFromJSON(final JSONObject participantFrameInfo, final Participant participant) {
if(participantFrameInfo == null) {
return null;
}
final Position position = getPositionFromJSON((JSONObject)participantFrameInfo.get("position"));
final Integer currentGold = getInteger(participantFrameInfo, "currentGold");
final Integer jungleMinionsKilled = getInteger(participantFrameInfo, "jungleMinionsKilled");
final Integer level = getInteger(participantFrameInfo, "level");
final Integer minionsKilled = getInteger(participantFrameInfo, "minionsKilled");
final Integer totalGold = getInteger(participantFrameInfo, "totalGold");
final Integer XP = getInteger(participantFrameInfo, "xp");
return new ParticipantFrame(currentGold, jungleMinionsKilled, level, minionsKilled, totalGold, XP, participant, position);
}
public Participant getParticipantFromJSON(final JSONObject participantInfo, final Map<Side, MatchTeam> teams, final Map<Integer, Player> players) {
if(participantInfo == null) {
return null;
}
final Champion champion = API.getChampion(getInteger(participantInfo, "championId"));
final Integer ID = getInteger(participantInfo, "participantId");
final SummonerSpell spell1 = API.getSummonerSpell(getInteger(participantInfo, "spell1Id"));
final SummonerSpell spell2 = API.getSummonerSpell(getInteger(participantInfo, "spell2Id"));
final ParticipantStats stats = getParticipantStatsFromJSON((JSONObject)participantInfo.get("stats"));
final ParticipantTimeline timeline = getParticipantTimelineFromJSON((JSONObject)participantInfo.get("timeline"));
final MatchTeam team = teams == null ? null : teams.get(getSide(participantInfo, "teamId"));
if(team != null) {
return new Participant(champion, ID, spell1, spell2, stats, team, timeline, players.get(ID));
}
else {
return new Participant(champion, ID, spell1, spell2, stats, getSide(participantInfo, "teamId"), timeline, players.get(ID));
}
}
public ParticipantStats getParticipantStatsFromJSON(final JSONObject participantStatsInfo) {
if(participantStatsInfo == null) {
return null;
}
final Long assists = (Long)participantStatsInfo.get("assists");
final Long champLevel = (Long)participantStatsInfo.get("champLevel");
final Long combatPlayerScore = (Long)participantStatsInfo.get("combatPlayerScore");
final Long deaths = (Long)participantStatsInfo.get("deaths");
final Long doubleKills = (Long)participantStatsInfo.get("doubleKills");
final Long goldEarned = (Long)participantStatsInfo.get("goldEarned");
final Long goldSpent = (Long)participantStatsInfo.get("goldSpent");
final Long inhibitorKills = (Long)participantStatsInfo.get("inhibitorKills");
final Long killingSpress = (Long)participantStatsInfo.get("killingSpress");
final Long kills = (Long)participantStatsInfo.get("kills");
final Long largestCriticalStrike = (Long)participantStatsInfo.get("largestCriticalStrike");
final Long largestKillingSpree = (Long)participantStatsInfo.get("largestKillingSpree");
final Long largestMultiKill = (Long)participantStatsInfo.get("largestMultiKill");
final Long magicDamageDealt = (Long)participantStatsInfo.get("magicDamageDealt");
final Long magicDamageDealtToChampions = (Long)participantStatsInfo.get("magicDamageDealtToChampions");
final Long magicDamageTaken = (Long)participantStatsInfo.get("magicDamageTaken");
final Long minionsKilled = (Long)participantStatsInfo.get("minionsKilled");
final Long neutralMinionsKilled = (Long)participantStatsInfo.get("neutralMinionsKilled");
final Long neutralMinionsKilledEnemyJungle = (Long)participantStatsInfo.get("neutralMinionsKilledEnemyJungle");
final Long neutralMinionsKilledTeamJungle = (Long)participantStatsInfo.get("neutralMinionsKilledTeamJungle");
final Long nodeCapture = (Long)participantStatsInfo.get("nodeCapture");
final Long nodeCaptureAssist = (Long)participantStatsInfo.get("nodeCaptureAssist");
final Long nodeNeutralize = (Long)participantStatsInfo.get("nodeNeutralize");
final Long nodeNeutralizeAssist = (Long)participantStatsInfo.get("nodeNeutralizeAssist");
final Long objectivePlayerScore = (Long)participantStatsInfo.get("objectivePlayerScore");
final Long pentaKills = (Long)participantStatsInfo.get("pentaKills");
final Long physicalDamageDealt = (Long)participantStatsInfo.get("physicalDamageDealt");
final Long physicalDamageDealtToChampions = (Long)participantStatsInfo.get("physicalDamageDealtToChampions");
final Long physicalDamageTaken = (Long)participantStatsInfo.get("physicalDamageTaken");
final Long quadraKills = (Long)participantStatsInfo.get("quadraKills");
final Long sightWardsBoughtInGame = (Long)participantStatsInfo.get("sightWardsBoughtInGame");
final Long teamObjective = (Long)participantStatsInfo.get("teamObjective");
final Long totalDamageDealt = (Long)participantStatsInfo.get("totalDamageDealt");
final Long totalDamageDealtToChampions = (Long)participantStatsInfo.get("totalDamageDealtToChampions");
final Long totalDamageTaken = (Long)participantStatsInfo.get("totalDamageTaken");
final Long totalHeal = (Long)participantStatsInfo.get("totalHeal");
final Long totalPlayerScore = (Long)participantStatsInfo.get("totalPlayerScore");
final Long totalScoreRank = (Long)participantStatsInfo.get("totalScoreRank");
final Long totalTimeCrowdControlDealt = (Long)participantStatsInfo.get("totalTimeCrowdControlDealt");
final Long totalUnitsHealed = (Long)participantStatsInfo.get("totalUnitsHealed");
final Long towerKills = (Long)participantStatsInfo.get("towerKills");
final Long tripleKills = (Long)participantStatsInfo.get("tripleKills");
final Long trueDamageDealt = (Long)participantStatsInfo.get("trueDamageDealt");
final Long trueDamageDealtToChampions = (Long)participantStatsInfo.get("trueDamageDealtToChampions");
final Long trueDamageTaken = (Long)participantStatsInfo.get("trueDamageTaken");
final Long unrealKills = (Long)participantStatsInfo.get("unrealKills");
final Long visionWardsBoughtInGame = (Long)participantStatsInfo.get("visionWardsBoughtInGame");
final Long wardsKilled = (Long)participantStatsInfo.get("wardsKilled");
final Long wardsPlaced = (Long)participantStatsInfo.get("wardsPlaced");
final Boolean firstBloodAssist = (Boolean)participantStatsInfo.get("firstBloodAssist");
final Boolean firstBloodKill = (Boolean)participantStatsInfo.get("firstBloodKill");
final Boolean firstInhibitorAssist = (Boolean)participantStatsInfo.get("firstInhibitorAssist");
final Boolean firstInhibitorKill = (Boolean)participantStatsInfo.get("firstInhibitorKill");
final Boolean firstTowerAssist = (Boolean)participantStatsInfo.get("firstTowerAssist");
final Boolean firstTowerKill = (Boolean)participantStatsInfo.get("firstTowerKill");
final Boolean winner = (Boolean)participantStatsInfo.get("winner");
Integer itemID = getInteger(participantStatsInfo, "item0");
final Item item0 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item1");
final Item item1 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item2");
final Item item2 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item3");
final Item item3 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item4");
final Item item4 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item5");
final Item item5 = itemID == 0 ? null : API.getItem(itemID);
itemID = getInteger(participantStatsInfo, "item6");
final Item item6 = itemID == 0 ? null : API.getItem(itemID);
return new ParticipantStats(assists, champLevel, combatPlayerScore, deaths, doubleKills, goldEarned, goldSpent, inhibitorKills, killingSpress, kills,
largestCriticalStrike, largestKillingSpree, largestMultiKill, magicDamageDealt, magicDamageDealtToChampions, magicDamageTaken, minionsKilled,
neutralMinionsKilled, neutralMinionsKilledEnemyJungle, neutralMinionsKilledTeamJungle, nodeCapture, nodeCaptureAssist, nodeNeutralize,
nodeNeutralizeAssist, objectivePlayerScore, pentaKills, physicalDamageDealt, physicalDamageDealtToChampions, physicalDamageTaken, quadraKills,
sightWardsBoughtInGame, teamObjective, totalDamageDealt, totalDamageDealtToChampions, totalDamageTaken, totalHeal, totalPlayerScore,
totalScoreRank, totalTimeCrowdControlDealt, totalUnitsHealed, towerKills, tripleKills, trueDamageDealt, trueDamageDealtToChampions,
trueDamageTaken, unrealKills, visionWardsBoughtInGame, wardsKilled, wardsPlaced, winner, firstBloodAssist, firstBloodKill,
firstInhibitorAssist, firstInhibitorKill, firstTowerAssist, firstTowerKill, item0, item1, item2, item3, item4, item5, item6);
}
public ParticipantTimelineData getParticipantTimelineDataFromJSON(final JSONObject participantTimelineDataInfo) {
if(participantTimelineDataInfo == null) {
return null;
}
final Double tenToTwenty = (Double)participantTimelineDataInfo.get("tenToTwenty");
final Double thirtyToEnd = (Double)participantTimelineDataInfo.get("thirtyToEnd");
final Double twentyToThirty = (Double)participantTimelineDataInfo.get("twentyToThirty");
final Double zeroToTen = (Double)participantTimelineDataInfo.get("zeroToTen");
return new ParticipantTimelineData(tenToTwenty, thirtyToEnd, twentyToThirty, zeroToTen);
}
public ParticipantTimeline getParticipantTimelineFromJSON(final JSONObject participantTimelineInfo) {
if(participantTimelineInfo == null) {
return null;
}
final ParticipantTimelineData ancientGolemAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("ancientGolemAssistsPerMinCounts"));
final ParticipantTimelineData ancientGolemKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("ancientGolemKillsPerMinCounts"));
final ParticipantTimelineData assistedLaneDeathsPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("assistedLaneDeathsPerMinDeltas"));
final ParticipantTimelineData assistedLaneKillsPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("assistedLaneKillsPerMinDeltas"));
final ParticipantTimelineData baronAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("baronAssistsPerMinCounts"));
final ParticipantTimelineData baronKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("baronKillsPerMinCounts"));
final ParticipantTimelineData creepsPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("creepsPerMinDeltas"));
final ParticipantTimelineData CSDiffPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("csDiffPerMinDeltas"));
final ParticipantTimelineData damageTakenDiffPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("damageTakenDiffPerMinDeltas"));
final ParticipantTimelineData damageTakenPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("damageTakenPerMinDeltas"));
final ParticipantTimelineData dragonAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("dragonAssistsPerMinCounts"));
final ParticipantTimelineData dragonKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("dragonKillsPerMinCounts"));
final ParticipantTimelineData elderLizardAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("elderLizardAssistsPerMinCounts"));
final ParticipantTimelineData elderLizardKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("elderLizardKillsPerMinCounts"));
final ParticipantTimelineData goldPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("goldPerMinDeltas"));
final ParticipantTimelineData inhibitorAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("inhibitorAssistsPerMinCounts"));
final ParticipantTimelineData inhibitorKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("inhibitorKillsPerMinCounts"));
final ParticipantTimelineData towerAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("towerAssistsPerMinCounts"));
final ParticipantTimelineData towerKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("towerKillsPerMinCounts"));
final ParticipantTimelineData towerKillsPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("towerKillsPerMinDeltas"));
final ParticipantTimelineData vilemawAssistsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("vilemawAssistsPerMinCounts"));
final ParticipantTimelineData vilemawKillsPerMinCounts = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo
.get("vilemawKillsPerMinCounts"));
final ParticipantTimelineData wardsPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("wardsPerMinDeltas"));
final ParticipantTimelineData XPDiffPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("xpDiffPerMinDeltas"));
final ParticipantTimelineData XPPerMinDeltas = getParticipantTimelineDataFromJSON((JSONObject)participantTimelineInfo.get("xpPerMinDeltas"));
final Lane lane = Lane.valueOf((String)participantTimelineInfo.get("lane"));
final Role role = Role.valueOf((String)participantTimelineInfo.get("role"));
return new ParticipantTimeline(ancientGolemAssistsPerMinCounts, ancientGolemKillsPerMinCounts, assistedLaneDeathsPerMinDeltas,
assistedLaneKillsPerMinDeltas, baronAssistsPerMinCounts, baronKillsPerMinCounts, creepsPerMinDeltas, CSDiffPerMinDeltas,
damageTakenDiffPerMinDeltas, damageTakenPerMinDeltas, dragonAssistsPerMinCounts, dragonKillsPerMinCounts, elderLizardAssistsPerMinCounts,
elderLizardKillsPerMinCounts, goldPerMinDeltas, inhibitorAssistsPerMinCounts, inhibitorKillsPerMinCounts, towerAssistsPerMinCounts,
towerKillsPerMinCounts, towerKillsPerMinDeltas, vilemawAssistsPerMinCounts, vilemawKillsPerMinCounts, wardsPerMinDeltas, XPDiffPerMinDeltas,
XPPerMinDeltas, lane, role);
}
public Passive getPassiveFromJSON(final JSONObject passiveInfo) {
if(passiveInfo == null) {
return null;
}
final String description = (String)passiveInfo.get("description");
final String name = (String)passiveInfo.get("name");
final String sanitizedDescription = (String)passiveInfo.get("sanitizedDescription");
final Image image = getImageFromJSON((JSONObject)passiveInfo.get("image"));
return new Passive(description, name, sanitizedDescription, image);
}
public Player getPlayerFromJSON(final JSONObject playerInfo) {
if(playerInfo == null) {
return null;
}
final String matchHistoryURI = (String)playerInfo.get("matchHistoryUri");
final Integer profileIconID = getInteger(playerInfo, "profileIcon");
final Summoner summoner = API.getSummoner((String)playerInfo.get("summonerName"));
return new Player(matchHistoryURI, summoner, profileIconID);
}
public PlayerStatsSummary getPlayerStatsSummaryFromJSON(final JSONObject playerStatsSummaryInfo) {
if(playerStatsSummaryInfo == null) {
return null;
}
final Integer losses = getInteger(playerStatsSummaryInfo, "losses");
final Integer wins = getInteger(playerStatsSummaryInfo, "wins");
final LocalDateTime modifyDate = getDateTime(playerStatsSummaryInfo, "modifyDate");
final AggregatedStats aggregatedStats = getAggregatedStatsFromJSON((JSONObject)playerStatsSummaryInfo.get("aggregatedStats"));
final PlayerStatsSummaryType playerStatSummaryType = PlayerStatsSummaryType.valueOf((String)playerStatsSummaryInfo.get("playerStatSummaryType"));
return new PlayerStatsSummary(aggregatedStats, playerStatSummaryType, modifyDate, wins, losses);
}
public Position getPositionFromJSON(final JSONObject positionInfo) {
if(positionInfo == null) {
return null;
}
final Integer x = getInteger(positionInfo, "x");
final Integer y = getInteger(positionInfo, "y");
return new Position(x, y);
}
public RawStats getRawStatsFromJSON(final JSONObject rawStatsInfo) {
if(rawStatsInfo == null) {
return null;
}
final Integer assists = getInteger(rawStatsInfo, "assists");
final Integer barracksKilled = getInteger(rawStatsInfo, "barracksKilled");
final Integer championsKilled = getInteger(rawStatsInfo, "championsKilled");
final Integer combatPlayerScore = getInteger(rawStatsInfo, "combatPlayerScore");
final Integer consumablesPurchased = getInteger(rawStatsInfo, "consumablesPurchased");
final Integer damageDealtPlayer = getInteger(rawStatsInfo, "damageDealtPlayer");
final Integer doubleKills = getInteger(rawStatsInfo, "doubleKills");
final Integer firstBlood = getInteger(rawStatsInfo, "firstBlood");
final Integer gold = getInteger(rawStatsInfo, "gold");
final Integer goldEarned = getInteger(rawStatsInfo, "goldEarned");
final Integer goldSpent = getInteger(rawStatsInfo, "goldSpent");
final Integer itemsPurchased = getInteger(rawStatsInfo, "itemsPurchased");
final Integer killingSprees = getInteger(rawStatsInfo, "killingSprees");
final Integer largestCriticalStrike = getInteger(rawStatsInfo, "largestCriticalStrike");
final Integer largestKillingSpree = getInteger(rawStatsInfo, "largestKillingSpree");
final Integer largestMultiKill = getInteger(rawStatsInfo, "largestMultiKill");
final Integer legendaryItemsCreated = getInteger(rawStatsInfo, "legendaryItemsCreated");
final Integer level = getInteger(rawStatsInfo, "level");
final Integer magicDamageDealtPlayer = getInteger(rawStatsInfo, "magicDamageDealtPlayer");
final Integer magicDamageDealtToChampions = getInteger(rawStatsInfo, "magicDamageDealtToChampions");
final Integer magicDamageTaken = getInteger(rawStatsInfo, "magicDamageTaken");
final Integer minionsDenied = getInteger(rawStatsInfo, "minionsDenied");
final Integer minionsKilled = getInteger(rawStatsInfo, "minionsKilled");
final Integer neutralMinionsKilled = getInteger(rawStatsInfo, "neutralMinionsKilled");
final Integer neutralMinionsKilledEnemyJungle = getInteger(rawStatsInfo, "neutralMinionsKilledEnemyJungle");
final Integer neutralMinionsKilledYourJungle = getInteger(rawStatsInfo, "neutralMinionsKilledYourJungle");
final Integer nodeCapture = getInteger(rawStatsInfo, "nodeCapture");
final Integer nodeCaptureAssist = getInteger(rawStatsInfo, "nodeCaptureAssist");
final Integer nodeNeutralize = getInteger(rawStatsInfo, "nodeNeutralize");
final Integer nodeNeutralizeAssist = getInteger(rawStatsInfo, "nodeNeutralizeAssist");
final Integer numDeaths = getInteger(rawStatsInfo, "numDeaths");
final Integer numItemsBought = getInteger(rawStatsInfo, "numItemsBought");
final Integer objectivePlayerScore = getInteger(rawStatsInfo, "objectivePlayerScore");
final Integer pentaKills = getInteger(rawStatsInfo, "pentaKills");
final Integer physicalDamageDealtPlayer = getInteger(rawStatsInfo, "physicalDamageDealtPlayer");
final Integer physicalDamageDealtToChampions = getInteger(rawStatsInfo, "physicalDamageDealtToChampions");
final Integer physicalDamageTaken = getInteger(rawStatsInfo, "physicalDamageTaken");
final Integer quadraKills = getInteger(rawStatsInfo, "quadraKills");
final Integer sightWardsBought = getInteger(rawStatsInfo, "sightWardsBought");
final Integer spell1Cast = getInteger(rawStatsInfo, "spell1Cast");
final Integer spell2Cast = getInteger(rawStatsInfo, "spell2Cast");
final Integer spell3Cast = getInteger(rawStatsInfo, "spell3Cast");
final Integer spell4Cast = getInteger(rawStatsInfo, "spell4Cast");
final Integer summonSpell1Cast = getInteger(rawStatsInfo, "summonSpell1Cast");
final Integer summonSpell2Cast = getInteger(rawStatsInfo, "summonSpell2Cast");
final Integer superMonsterKilled = getInteger(rawStatsInfo, "superMonsterKilled");
final Integer team = getInteger(rawStatsInfo, "team");
final Integer teamObjective = getInteger(rawStatsInfo, "teamObjective");
final Integer timePlayed = getInteger(rawStatsInfo, "timePlayed");
final Integer totalDamageDealt = getInteger(rawStatsInfo, "totalDamageDealt");
final Integer totalDamageDealtToChampions = getInteger(rawStatsInfo, "totalDamageDealtToChampions");
final Integer totalDamageTaken = getInteger(rawStatsInfo, "totalDamageTaken");
final Integer totalHeal = getInteger(rawStatsInfo, "totalHeal");
final Integer totalPlayerScore = getInteger(rawStatsInfo, "totalPlayerScore");
final Integer totalScoreRank = getInteger(rawStatsInfo, "totalScoreRank");
final Integer totalTimeCrowdControlDealt = getInteger(rawStatsInfo, "totalTimeCrowdControlDealt");
final Integer totalUnitsHealed = getInteger(rawStatsInfo, "totalUnitsHealed");
final Integer tripleKills = getInteger(rawStatsInfo, "tripleKills");
final Integer trueDamageDealtPlayer = getInteger(rawStatsInfo, "trueDamageDealtPlayer");
final Integer trueDamageDealtToChampions = getInteger(rawStatsInfo, "trueDamageDealtToChampions");
final Integer trueDamageTaken = getInteger(rawStatsInfo, "trueDamageTaken");
final Integer turretsKilled = getInteger(rawStatsInfo, "turretsKilled");
final Integer unrealKills = getInteger(rawStatsInfo, "unrealKills");
final Integer victoryPointTotal = getInteger(rawStatsInfo, "victoryPointTotal");
final Integer visionWardsBought = getInteger(rawStatsInfo, "visionWardsBought");
final Integer wardKilled = getInteger(rawStatsInfo, "wardKilled");
final Integer wardPlaced = getInteger(rawStatsInfo, "wardPlaced");
final Boolean nexusKilled = (Boolean)rawStatsInfo.get("nexusKilled");
final Boolean win = (Boolean)rawStatsInfo.get("win");
final Item item0 = getItem(rawStatsInfo, "item0");
final Item item1 = getItem(rawStatsInfo, "item1");
final Item item2 = getItem(rawStatsInfo, "item2");
final Item item3 = getItem(rawStatsInfo, "item3");
final Item item4 = getItem(rawStatsInfo, "item4");
final Item item5 = getItem(rawStatsInfo, "item5");
final Item item6 = getItem(rawStatsInfo, "item6");
return new RawStats(nexusKilled, win, assists, barracksKilled, championsKilled, combatPlayerScore, consumablesPurchased, damageDealtPlayer,
doubleKills, firstBlood, gold, goldEarned, goldSpent, itemsPurchased, killingSprees, largestCriticalStrike, largestKillingSpree,
largestMultiKill, legendaryItemsCreated, level, magicDamageDealtPlayer, magicDamageDealtToChampions, magicDamageTaken, minionsDenied,
minionsKilled, neutralMinionsKilled, neutralMinionsKilledEnemyJungle, neutralMinionsKilledYourJungle, nodeCapture, nodeCaptureAssist,
nodeNeutralize, nodeNeutralizeAssist, numDeaths, numItemsBought, objectivePlayerScore, pentaKills, physicalDamageDealtPlayer,
physicalDamageDealtToChampions, physicalDamageTaken, quadraKills, sightWardsBought, spell1Cast, spell2Cast, spell3Cast, spell4Cast,
summonSpell1Cast, summonSpell2Cast, superMonsterKilled, team, teamObjective, timePlayed, totalDamageDealt, totalDamageDealtToChampions,
totalDamageTaken, totalHeal, totalPlayerScore, totalScoreRank, totalTimeCrowdControlDealt, totalUnitsHealed, tripleKills,
trueDamageDealtPlayer, trueDamageDealtToChampions, trueDamageTaken, turretsKilled, unrealKills, victoryPointTotal, visionWardsBought,
wardKilled, wardPlaced, item0, item1, item2, item3, item4, item5, item6);
}
@SuppressWarnings("unchecked")
public Realm getRealmFromJSON(final JSONObject realmInfo) {
if(realmInfo == null) {
return null;
}
final String cdn = (String)realmInfo.get("cdn");
final String css = (String)realmInfo.get("css");
final String dd = (String)realmInfo.get("dd");
final String l = (String)realmInfo.get("l");
final String lg = (String)realmInfo.get("lg");
final String store = (String)realmInfo.get("store");
final String v = (String)realmInfo.get("v");
final Integer profileIconMax = getInteger(realmInfo, "profileiconmax");
Map<String, String> n = (Map<String, String>)realmInfo.get("n");
if(n != null) {
n = Collections.unmodifiableMap(n);
}
return new Realm(cdn, css, dd, l, lg, store, v, profileIconMax, n);
}
public Recommended getRecommendedFromJSON(final JSONObject recommendedInfo) {
if(recommendedInfo == null) {
return null;
}
final String champion = (String)recommendedInfo.get("champion");
final String map = (String)recommendedInfo.get("map");
final String mode = (String)recommendedInfo.get("mode");
final String title = (String)recommendedInfo.get("title");
final String type = (String)recommendedInfo.get("type");
final Boolean priority = (Boolean)recommendedInfo.get("priority");
final List<Block> blocks = getList(recommendedInfo, "blocks", b -> getBlockFromJSON((JSONObject)b));
return new Recommended(blocks, champion, map, mode, title, type, priority);
}
public Roster getRosterFromJSON(final JSONObject rosterInfo) {
if(rosterInfo == null) {
return null;
}
final JSONArray members = (JSONArray)rosterInfo.get("memberList");
final List<TeamMemberInformation> memberList = getAllTeamMemberInfoFromJSON(members);
final Summoner owner = API.getSummonerByID((Long)rosterInfo.get("ownerId"));
return new Roster(memberList, owner);
}
public Roster getRosterFromJSON(final List<Summoner> roster, final JSONObject rosterInfo) {
if(rosterInfo == null) {
return null;
}
final JSONArray members = (JSONArray)rosterInfo.get("memberList");
final List<TeamMemberInformation> memberList = getAllTeamMemberInfoFromJSON(roster, members);
final Summoner owner = API.getSummonerByID((Long)rosterInfo.get("ownerId"));
return new Roster(memberList, owner);
}
@SuppressWarnings("unchecked")
public Rune getRuneFromJSON(final JSONObject runeInfo) {
if(runeInfo == null) {
return null;
}
final String colloq = (String)runeInfo.get("colloq");
final String description = (String)runeInfo.get("description");
final String group = (String)runeInfo.get("group");
final String name = (String)runeInfo.get("name");
final String plaintext = (String)runeInfo.get("plaintext");
final String requiredChampion = (String)runeInfo.get("requiredChampion");
final String sanitizedDescription = (String)runeInfo.get("sanitizedDescription");
final Boolean consumeOnFull = (Boolean)runeInfo.get("consumeOnFull");
final Boolean consumed = (Boolean)runeInfo.get("consumed");
final Boolean hideFromAll = (Boolean)runeInfo.get("hideFromAll");
final Boolean inStore = (Boolean)runeInfo.get("inStore");
final Integer depth = getInteger(runeInfo, "depth");
final Integer ID = getInteger(runeInfo, "id");
final Integer specialRecipe = getInteger(runeInfo, "specialRecipe");
final Integer stacks = getInteger(runeInfo, "stacks");
final List<String> from = getStringList(runeInfo, "from");
final List<String> into = getStringList(runeInfo, "into");
final List<String> tags = getStringList(runeInfo, "tags");
final Gold gold = getGoldFromJSON((JSONObject)runeInfo.get("gold"));
final Image image = getImageFromJSON((JSONObject)runeInfo.get("image"));
final MetaData rune = getMetaDataFromJSON((JSONObject)runeInfo.get("rune"));
final BasicDataStats stats = getBasicDataStatsFromJSON((JSONObject)runeInfo.get("stats"));
Map<String, Boolean> maps = (Map<String, Boolean>)runeInfo.get("maps");
if(maps != null) {
maps = Collections.unmodifiableMap(maps);
}
return new Rune(colloq, description, group, name, plaintext, requiredChampion, sanitizedDescription, consumeOnFull, consumed, hideFromAll, inStore,
depth, ID, specialRecipe, stacks, from, into, tags, gold, image, maps, rune, stats);
}
public RunePage getRunePageFromJSON(final JSONObject runePageInfo) {
if(runePageInfo == null) {
return null;
}
final Boolean current = (Boolean)runePageInfo.get("current");
final Long ID = (Long)runePageInfo.get("id");
final String name = (String)runePageInfo.get("name");
final List<RuneSlot> slots = getList(runePageInfo, "slots", s -> getRuneSlotFromJSON((JSONObject)s));
return new RunePage(current, ID, name, slots);
}
public RuneSlot getRuneSlotFromJSON(final JSONObject runeSlotInfo) {
if(runeSlotInfo == null) {
return null;
}
final Integer runeSlotID = getInteger(runeSlotInfo, "runeSlotId");
final Integer ID = getInteger(runeSlotInfo, "runeId");
final Rune rune = API.getRune(ID);
return new RuneSlot(runeSlotID, rune);
}
public Skin getSkinFromJSON(final JSONObject skinInfo) {
if(skinInfo == null) {
return null;
}
final Integer ID = getInteger(skinInfo, "id");
final Integer num = getInteger(skinInfo, "num");
final String name = (String)skinInfo.get("name");
return new Skin(ID, num, name);
}
public SpellVariables getSpellVariablesFromJSON(final JSONObject spellVarsInfo) {
if(spellVarsInfo == null) {
return null;
}
final List<Double> coeff = getDoubleList(spellVarsInfo, "coeff");
final String dyn = (String)spellVarsInfo.get("dyn");
final String key = (String)spellVarsInfo.get("key");
final String link = (String)spellVarsInfo.get("link");
final String ranksWith = (String)spellVarsInfo.get("ranksWith");
return new SpellVariables(dyn, key, link, ranksWith, coeff);
}
public Stats getStatsFromJSON(final JSONObject statsInfo) {
if(statsInfo == null) {
return null;
}
final Double armor = (Double)statsInfo.get("armor");
final Double armorPerLevel = (Double)statsInfo.get("armorperlevel");
final Double attackDamage = (Double)statsInfo.get("attackdamage");
final Double attackDamagePerLevel = (Double)statsInfo.get("attackdamageperlevel");
final Double attackRange = (Double)statsInfo.get("attackrange");
final Double attackSpeedOffset = (Double)statsInfo.get("attackspeedoffset");
final Double attackSpeedPerLevel = (Double)statsInfo.get("attackspeedperlevel");
final Double crit = (Double)statsInfo.get("crit");
final Double critPerLevel = (Double)statsInfo.get("critperlevel");
final Double HP = (Double)statsInfo.get("hp");
final Double HPPerLevel = (Double)statsInfo.get("hpperlevel");
final Double HPRegen = (Double)statsInfo.get("hpregen");
final Double HPRegenPerLevel = (Double)statsInfo.get("hpregenperlevel");
final Double moveSpeed = (Double)statsInfo.get("movespeed");
final Double MP = (Double)statsInfo.get("mp");
final Double MPPerLevel = (Double)statsInfo.get("mpperlevel");
final Double MPRegen = (Double)statsInfo.get("mpregen");
final Double MPRegenPerLevel = (Double)statsInfo.get("mpregenperlevel");
final Double spellBlock = (Double)statsInfo.get("spellblock");
final Double spellBlockPerLevel = (Double)statsInfo.get("spellblockperlevel");
return new Stats(armor, armorPerLevel, attackDamage, attackDamagePerLevel, attackRange, attackSpeedOffset, attackSpeedPerLevel, crit, critPerLevel, HP,
HPPerLevel, HPRegen, HPRegenPerLevel, moveSpeed, MP, MPPerLevel, MPRegen, MPRegenPerLevel, spellBlock, spellBlockPerLevel);
}
public Summoner getSummonerFromJSON(final JSONObject summonerInfo) {
if(summonerInfo == null) {
return null;
}
final Long ID = (Long)summonerInfo.get("id");
final Long summonerLevel = (Long)summonerInfo.get("summonerLevel");
final Integer profileIconID = getInteger(summonerInfo, "profileIconId");
final LocalDateTime revisionDate = getDateTime(summonerInfo, "revisionDate");
final String name = (String)summonerInfo.get("name");
return new Summoner(ID, summonerLevel, name, profileIconID, revisionDate);
}
public SummonerSpell getSummonerSpellFromJSON(final JSONObject summonerSpellInfo) {
final List<Double> cooldown = getDoubleList(summonerSpellInfo, "cooldown");
final String cooldownBurn = (String)summonerSpellInfo.get("cooldownBurn");
final String costBurn = (String)summonerSpellInfo.get("costBurn");
final String costType = (String)summonerSpellInfo.get("costType");
final String description = (String)summonerSpellInfo.get("description");
final String key = (String)summonerSpellInfo.get("key");
final String name = (String)summonerSpellInfo.get("name");
final String rangeBurn = (String)summonerSpellInfo.get("rangeBurn");
final String resource = (String)summonerSpellInfo.get("resource");
final String sanitizedDescription = (String)summonerSpellInfo.get("sanitizedDescription");
final String sanitizedTooltip = (String)summonerSpellInfo.get("sanitizedTooltip");
final String tooltip = (String)summonerSpellInfo.get("tooltip");
final List<Integer> cost = getIntegerList(summonerSpellInfo, "cost");
final List<List<Double>> effect = getList(summonerSpellInfo, "effect", l -> getDoubleList((JSONArray)l));
final List<String> effectBurn = getStringList(summonerSpellInfo, "effectBurn");
final List<String> modes = getStringList(summonerSpellInfo, "modes");
final Integer ID = getInteger(summonerSpellInfo, "id");
final Integer maxRank = getInteger(summonerSpellInfo, "maxrank");
final Integer summonerLevel = getInteger(summonerSpellInfo, "summonerLevel");
final Image image = getImageFromJSON((JSONObject)summonerSpellInfo.get("image"));
final LevelTip levelTip = getLevelTipFromJSON((JSONObject)summonerSpellInfo.get("leveltip"));
final List<SpellVariables> vars = getList(summonerSpellInfo, "vars", v -> getSpellVariablesFromJSON((JSONObject)v));
List<Integer> range;
final Object val = summonerSpellInfo.get("range");
if(val instanceof String) {
range = null;
}
else {
range = getIntegerList((JSONArray)val);
}
return new SummonerSpell(cooldownBurn, costBurn, costType, description, key, name, rangeBurn, resource, sanitizedDescription, sanitizedTooltip,
tooltip, cooldown, cost, range, effect, effectBurn, modes, ID, maxRank, summonerLevel, image, levelTip, vars);
}
public Team getTeamFromJSON(final JSONObject teamInfo) {
if(teamInfo == null) {
return null;
}
final LocalDateTime createDate = getDateTime(teamInfo, "createDate");
final LocalDateTime lastGameDate = getDateTime(teamInfo, "lastGameDate");
final LocalDateTime lastJoinDate = getDateTime(teamInfo, "lastJoinDate");
final LocalDateTime lastJoinedRankedTeamQueueDate = getDateTime(teamInfo, "lastJoinedRankedTeamQueueDate");
final LocalDateTime modifyDate = getDateTime(teamInfo, "modifyDate");
final LocalDateTime secondLastJoinDate = getDateTime(teamInfo, "secondLastDate");
final LocalDateTime thirdLastJoinDate = getDateTime(teamInfo, "thirdLastDate");
final String ID = (String)teamInfo.get("fullId");
final String name = (String)teamInfo.get("name");
final String status = (String)teamInfo.get("status");
final String tag = (String)teamInfo.get("tag");
final Roster roster = getRosterFromJSON((JSONObject)teamInfo.get("roster"));
final List<MatchHistorySummary> matchHistory = getList(teamInfo, "matchHistory", m -> getMatchHistorySummaryFromJSON((JSONObject)m));
final List<TeamStatDetail> teamStatDetails = getList(teamInfo, "teamStatDetails", t -> getTeamStatDetailFromJSON((JSONObject)t));
return new Team(createDate, lastGameDate, lastJoinDate, lastJoinedRankedTeamQueueDate, modifyDate, secondLastJoinDate, thirdLastJoinDate, ID, name,
status, tag, matchHistory, roster, teamStatDetails);
}
private Team getTeamFromJSON(final List<Summoner> rosterSummoners, final JSONObject teamInfo) {
if(teamInfo == null) {
return null;
}
final LocalDateTime createDate = getDateTime(teamInfo, "createDate");
final LocalDateTime lastGameDate = getDateTime(teamInfo, "lastGameDate");
final LocalDateTime lastJoinDate = getDateTime(teamInfo, "lastJoinDate");
final LocalDateTime lastJoinedRankedTeamQueueDate = getDateTime(teamInfo, "lastJoinedRankedTeamQueueDate");
final LocalDateTime modifyDate = getDateTime(teamInfo, "modifyDate");
final LocalDateTime secondLastJoinDate = getDateTime(teamInfo, "secondLastDate");
final LocalDateTime thirdLastJoinDate = getDateTime(teamInfo, "thirdLastDate");
final String ID = (String)teamInfo.get("fullId");
final String name = (String)teamInfo.get("name");
final String status = (String)teamInfo.get("status");
final String tag = (String)teamInfo.get("tag");
final Roster roster = getRosterFromJSON(rosterSummoners, (JSONObject)teamInfo.get("roster"));
final List<MatchHistorySummary> matchHistory = getList(teamInfo, "matchHistory", m -> getMatchHistorySummaryFromJSON((JSONObject)m));
final List<TeamStatDetail> teamStatDetails = getList(teamInfo, "teamStatDetails", t -> getTeamStatDetailFromJSON((JSONObject)t));
return new Team(createDate, lastGameDate, lastJoinDate, lastJoinedRankedTeamQueueDate, modifyDate, secondLastJoinDate, thirdLastJoinDate, ID, name,
status, tag, matchHistory, roster, teamStatDetails);
}
public TeamMemberInformation getTeamMemberInfoFromJSON(final JSONObject teamMemberInfo) {
if(teamMemberInfo == null) {
return null;
}
return getTeamMemberInfoFromJSON(API.getSummonerByID((Long)teamMemberInfo.get("playerId")), teamMemberInfo);
}
private TeamMemberInformation getTeamMemberInfoFromJSON(final Summoner player, final JSONObject teamMemberInfo) {
if(teamMemberInfo == null) {
return null;
}
final String status = (String)teamMemberInfo.get("status");
final LocalDateTime inviteDate = getDateTime(teamMemberInfo, "inviteDate");
final LocalDateTime joinDate = getDateTime(teamMemberInfo, "joinDate");
return new TeamMemberInformation(inviteDate, joinDate, player, status);
}
public TeamStatDetail getTeamStatDetailFromJSON(final JSONObject teamStatDetailInfo) {
if(teamStatDetailInfo == null) {
return null;
}
final String teamStatType = (String)teamStatDetailInfo.get("teamStatType");
final Integer averageGamesPlayed = getInteger(teamStatDetailInfo, "averageGamesPlayed");
final Integer losses = getInteger(teamStatDetailInfo, "losses");
final Integer wins = getInteger(teamStatDetailInfo, "wins");
return new TeamStatDetail(averageGamesPlayed, losses, wins, teamStatType);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.