answer
stringlengths 17
10.2M
|
|---|
package org.chromium.chrome.test.util;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.infobar.InfoBar;
import org.chromium.content.browser.test.util.TouchCommon;
/**
* Utility functions for dealing with InfoBars.
*/
public class InfoBarUtil {
/**
* Finds, and optionally clicks, the button with the specified ID in the given InfoBar.
* @return True if the View was found.
*/
private static boolean findButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar, int buttonId, boolean click) {
View button = infoBar.getContentWrapper().findViewById(buttonId);
if (button == null) return false;
if (click) new TouchCommon(test).singleClickView(button);
return true;
}
/**
* Checks if the primary button exists on the InfoBar.
* @return True if the View was found.
*/
public static boolean hasPrimaryButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar) {
return findButton(test, infoBar, R.id.button_primary, false);
}
/**
* Checks if the secondary button exists on the InfoBar.
* @return True if the View was found.
*/
public static boolean hasSecondaryButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar) {
return findButton(test, infoBar, R.id.button_secondary, false);
}
/**
* Simulates clicking the Close button in the specified infobar.
* @return True if the View was found.
*/
public static boolean clickCloseButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar) {
return findButton(test, infoBar, R.id.infobar_close_button, true);
}
/**
* Simulates clicking the primary button in the specified infobar.
* @return True if the View was found.
*/
public static boolean clickPrimaryButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar) {
return findButton(test, infoBar, R.id.button_primary, true);
}
/**
* Simulates clicking the secondary button in the specified infobar.
* @return True if the View was found.
*/
public static boolean clickSecondaryButton(ActivityInstrumentationTestCase2<?> test,
InfoBar infoBar) {
return findButton(test, infoBar, R.id.button_secondary, true);
}
}
|
package org.honton.chas.datadog.apm.jaxrs;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import org.honton.chas.datadog.apm.SpanBuilder;
import org.honton.chas.datadog.apm.TraceOperation;
import org.honton.chas.datadog.apm.Tracer;
/**
* Trace export for jaxrs implementations
*/
@Provider
public class TraceContainerFilter implements ContainerRequestFilter, ContainerResponseFilter {
private Tracer tracer;
@Inject
void setTracer(Tracer tracer) {
this.tracer = tracer;
}
@Context
ResourceInfo resourceInfo;
private boolean shouldTrace() {
Method resourceMethod = resourceInfo.getResourceMethod();
TraceOperation traceOperation = resourceMethod.getAnnotation(TraceOperation.class);
return traceOperation == null || traceOperation.value();
}
@Override
public void filter(final ContainerRequestContext req) throws IOException {
if (shouldTrace()) {
SpanBuilder sb = tracer.importSpan(new Tracer.HeaderAccessor() {
@Override public String getValue(String name) {
return req.getHeaderString(name);
}
});
UriInfo uriInfo = req.getUriInfo();
URI uri = uriInfo.getRequestUri();
sb.resource(req.getMethod() + ' ' + uriInfo.getPath())
.operation(uri.getHost() + ':' + uri.getPort());
}
}
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext resp) throws IOException {
if (shouldTrace()) {
SpanBuilder currentSpan = tracer.getCurrentSpan();
int status = resp.getStatus();
if (status < 200 || status >= 400) {
currentSpan.error(true);
}
tracer.closeSpan(currentSpan);
}
}
}
|
package org.jetel.connection.jdbc.specific.conn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.jetel.database.sql.DBConnection;
import org.jetel.database.sql.JdbcSpecific.OperationType;
import org.jetel.exception.JetelException;
public class SybaseConnection extends BasicSqlConnection {
/**
* @param dbConnection
* @param operationType
* @param autoGeneratedKeysType
* @throws JetelException
*/
public SybaseConnection(DBConnection dbConnection, Connection connection, OperationType operationType) throws JetelException {
super(dbConnection, connection, operationType);
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.conn.DefaultConnection#prepareStatement(java.lang.String, int[])
*/
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
logger.warn("Postgre driver doesn't support auto generated columns");
return super.prepareStatement(sql, columnIndexes);
}
/* (non-Javadoc)
* @see org.jetel.connection.jdbc.specific.conn.DefaultConnection#prepareStatement(java.lang.String, java.lang.String[])
*/
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
logger.warn("Postgre driver doesn't support auto generated columns");
return super.prepareStatement(sql, columnNames);
}
@Override
protected void optimizeConnection(OperationType operationType) throws Exception {
switch (operationType) {
case READ:
connection.setAutoCommit(false);
connection.setReadOnly(true);
connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
break;
case WRITE:
case CALL:
connection.setAutoCommit(false);
connection.setReadOnly(false);
connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
break;
case TRANSACTION:
connection.setAutoCommit(true);
connection.setReadOnly(false);
connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
break;
}
}
@Override
public List<String> getSchemas() throws SQLException {
return getMetaCatalogs();
}
@Override
public ResultSet getTables(String schema) throws SQLException {
Statement s = connection.createStatement();
s.execute("USE " + schema);
return s.executeQuery("EXECUTE sp_tables @table_type = \"'TABLE', 'VIEW'\"");
}
@Override
public ResultSetMetaData getColumns(String schema, String owner, String table) throws SQLException {
Statement s = connection.createStatement();
s.execute("USE " + schema);
return super.getColumns(schema, owner, table);
}
}
|
package org.jetel.connection.jdbc.specific.impl;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collection;
import java.util.Properties;
import org.jetel.connection.jdbc.AbstractCopySQLData.CopyBoolean;
import org.jetel.connection.jdbc.specific.conn.MSAccessConnection;
import org.jetel.data.BooleanDataField;
import org.jetel.data.DataRecord;
import org.jetel.database.sql.CopySQLData;
import org.jetel.database.sql.DBConnection;
import org.jetel.database.sql.SqlConnection;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.graph.Node;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
public class MSAccessSpecific extends GenericODBCSpecific {
private static final MSAccessSpecific INSTANCE = new MSAccessSpecific();
private static final String CONVERT_STRING = "Convert the field to another type or use another matching field type.";
protected MSAccessSpecific() {
super();
}
public static MSAccessSpecific getInstance() {
return INSTANCE;
}
@Override
public Connection connect(Driver driver, String url, Properties info) throws SQLException {
if (!System.getProperty("os.name").toLowerCase().contains("windows")) {
// prevent JVM crash on Linux due missing .so library - see CLO-2707
throw new SQLException("Connection to MS Access is supported on MS Windows only.");
}
return super.connect(driver, url, info);
}
@Override
public SqlConnection createSQLConnection(DBConnection dbConnection, Connection connection, OperationType operationType) throws JetelException {
return new MSAccessConnection(dbConnection, connection, operationType);
}
@Override
public CopySQLData createCopyObject(int sqlType, DataFieldMetadata fieldMetadata, DataRecord record, int fromIndex,
int toIndex) {
switch(sqlType) {
case Types.BOOLEAN:
case Types.BIT:
if (fieldMetadata.getDataType() == DataFieldType.BOOLEAN) {
return new ODBCCopyBoolean(record, fromIndex, toIndex);
}
}
return super.createCopyObject(sqlType, fieldMetadata, record, fromIndex, toIndex);
}
@Override
public String getDbFieldPattern() {
//allows white spaces
return "([\\s\\p{Alnum}\\._]+)|([\"\'][\\s\\p{Alnum}\\._ ]+[\"\'])";
}
@Override
public String quoteString(String string) {
return quoteIdentifier(string);
}
@Override
public String quoteIdentifier(String identifier) {
return ('[' + identifier + ']');
}
@Override
public ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata, Node node) {
for (DataRecordMetadata dataRecordMetadata: metadata) {
for (DataFieldMetadata dataField: dataRecordMetadata.getFields()) {
switch (dataField.getDataType()) {
case LONG:
status.add(new ConfigurationProblem("Metadata on input port must not use field of type long " +
"because of restrictions of used driver." + CONVERT_STRING,
ConfigurationStatus.Severity.ERROR, node, ConfigurationStatus.Priority.NORMAL));
break;
case DECIMAL:
status.add(new ConfigurationProblem("Metadata on input port must not use field of type decimal " +
"because of restrictions of used driver. " + CONVERT_STRING,
ConfigurationStatus.Severity.ERROR, node, ConfigurationStatus.Priority.NORMAL));
break;
}
}
}
return status;
}
@Override
public String sqlType2str(int sqlType) {
switch(sqlType) {
case Types.TIMESTAMP :
return "DATETIME";
case Types.BOOLEAN :
return "BIT";
case Types.INTEGER :
return "INT";
case Types.NUMERIC :
case Types.DOUBLE :
return "FLOAT";
}
return super.sqlType2str(sqlType);
}
@Override
public int jetelType2sql(DataFieldMetadata field) {
switch (field.getDataType()) {
case BOOLEAN:
return Types.BIT;
case NUMBER:
return Types.DOUBLE;
default:
return super.jetelType2sql(field);
}
}
@Override
public char sqlType2jetel(int sqlType) {
switch (sqlType) {
case Types.BIT:
return DataFieldType.BOOLEAN.getShortName();
default:
return super.sqlType2jetel(sqlType);
}
}
@Override
public String getTablePrefix(String schema, String owner,
boolean quoteIdentifiers) {
String tablePrefix;
String notNullOwner = (owner == null) ? "" : owner;
if(quoteIdentifiers) {
tablePrefix = quoteIdentifier(schema);
//in case when owner is empty or null skip adding
if(!notNullOwner.isEmpty())
tablePrefix += quoteIdentifier(notNullOwner);
} else {
tablePrefix = notNullOwner.isEmpty() ? schema : (schema+"."+notNullOwner);
}
return tablePrefix;
}
private class ODBCCopyBoolean extends CopyBoolean {
public ODBCCopyBoolean(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
@Override
public void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
boolean value = ((BooleanDataField) field).getBoolean();
pStatement.setBoolean(fieldSQL, value);
} else {
//null value cannot be set to the boolean field -> set false
pStatement.setBoolean(fieldSQL, false);
}
}
}
}
|
package com.eclipsesource.json;
import static com.eclipsesource.json.TestUtil.assertException;
import static com.eclipsesource.json.TestUtil.serializeAndDeserialize;
import static org.junit.Assert.*;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import java.io.StringReader;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import com.eclipsesource.json.JsonObject.HashIndexTable;
import com.eclipsesource.json.JsonObject.Member;
public class JsonObject_Test {
private JsonObject object;
@Before
public void setUp() {
object = new JsonObject();
}
@Test
public void copyConstructor_failsWithNull() {
assertException(NullPointerException.class, "object is null", new Runnable() {
public void run() {
new JsonObject(null);
}
});
}
@Test
public void copyConstructor_hasSameValues() {
object.add("foo", 23);
JsonObject copy = new JsonObject(object);
assertEquals(object.names(), copy.names());
assertSame(object.get("foo"), copy.get("foo"));
}
@Test
public void copyConstructor_worksOnSafeCopy() {
JsonObject copy = new JsonObject(object);
object.add("foo", 23);
assertTrue(copy.isEmpty());
}
@Test
public void unmodifiableObject_hasSameValues() {
object.add("foo", 23);
JsonObject unmodifiableObject = JsonObject.unmodifiableObject(object);
assertEquals(object.names(), unmodifiableObject.names());
assertSame(object.get("foo"), unmodifiableObject.get("foo"));
}
@Test
public void unmodifiableObject_reflectsChanges() {
JsonObject unmodifiableObject = JsonObject.unmodifiableObject(object);
object.add("foo", 23);
assertEquals(object.names(), unmodifiableObject.names());
assertSame(object.get("foo"), unmodifiableObject.get("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void unmodifiableObject_preventsModification() {
JsonObject unmodifiableObject = JsonObject.unmodifiableObject(object);
unmodifiableObject.add("foo", 23);
}
@Test
@SuppressWarnings("deprecation")
public void readFrom_reader() throws IOException {
assertEquals(new JsonObject(), JsonObject.readFrom(new StringReader("{}")));
assertEquals(new JsonObject().add("a", 23),
JsonObject.readFrom(new StringReader("{ \"a\": 23 }")));
}
@Test
@SuppressWarnings("deprecation")
public void readFrom_string() {
assertEquals(new JsonObject(), JsonObject.readFrom("{}"));
assertEquals(new JsonObject().add("a", 23), JsonObject.readFrom("{ \"a\": 23 }"));
}
@Test(expected = ParseException.class)
@SuppressWarnings("deprecation")
public void readFrom_illegalJson() {
JsonObject.readFrom("This is not JSON");
}
@Test(expected = UnsupportedOperationException.class)
@SuppressWarnings("deprecation")
public void readFrom_wrongJsonType() {
JsonObject.readFrom("\"This is not a JSON object\"");
}
@Test
public void isEmpty_trueAfterCreation() {
assertTrue(object.isEmpty());
}
@Test
public void isEmpty_falseAfterAdd() {
object.add("a", true);
assertFalse(object.isEmpty());
}
@Test
public void size_zeroAfterCreation() {
assertEquals(0, object.size());
}
@Test
public void size_oneAfterAdd() {
object.add("a", true);
assertEquals(1, object.size());
}
@Test
public void allowsMultipleEntriesWithRepeatedNames() {
object.add("a", true);
object.add("a", "value");
assertEquals(2, object.size());
}
@Test
public void getsLastEntryWithRepeatedNames() {
object.add("a", true);
object.add("a", "value");
assertEquals("value", object.getString("a", "missing"));
}
@Test
public void names_emptyAfterCreation() {
assertTrue(object.names().isEmpty());
}
@Test
public void names_containsNameAfterAdd() {
object.add("foo", true);
List<String> names = object.names();
assertEquals(1, names.size());
assertEquals("foo", names.get(0));
}
@Test
public void names_reflectsChanges() {
List<String> names = object.names();
object.add("foo", true);
assertEquals(1, names.size());
assertEquals("foo", names.get(0));
}
@Test(expected = UnsupportedOperationException.class)
public void names_preventsModification() {
List<String> names = object.names();
names.add("foo");
}
@Test
public void iterator_isEmptyAfterCreation() {
assertFalse(object.iterator().hasNext());
}
@Test
public void iterator_hasNextAfterAdd() {
object.add("a", true);
Iterator<Member> iterator = object.iterator();
assertTrue(iterator.hasNext());
}
@Test
public void iterator_nextReturnsActualValue() {
object.add("a", true);
Iterator<Member> iterator = object.iterator();
assertEquals(new Member("a", Json.TRUE), iterator.next());
}
@Test
public void iterator_nextProgressesToNextValue() {
object.add("a", true);
object.add("b", false);
Iterator<Member> iterator = object.iterator();
iterator.next();
assertTrue(iterator.hasNext());
assertEquals(new Member("b", Json.FALSE), iterator.next());
}
@Test(expected = NoSuchElementException.class)
public void iterator_nextFailsAtEnd() {
Iterator<Member> iterator = object.iterator();
iterator.next();
}
@Test(expected = UnsupportedOperationException.class)
public void iterator_doesNotAllowModification() {
object.add("a", 23);
Iterator<Member> iterator = object.iterator();
iterator.next();
iterator.remove();
}
@Test(expected = ConcurrentModificationException.class)
public void iterator_detectsConcurrentModification() {
Iterator<Member> iterator = object.iterator();
object.add("a", 23);
iterator.next();
}
@Test
public void get_failsWithNullName() {
assertException(NullPointerException.class, "name is null", new Runnable() {
public void run() {
object.get(null);
}
});
}
@Test
public void get_returnsNullForNonExistingMember() {
assertNull(object.get("foo"));
}
@Test
public void get_returnsValueForName() {
object.add("foo", true);
assertEquals(Json.TRUE, object.get("foo"));
}
@Test
public void get_returnsLastValueForName() {
object.add("foo", false).add("foo", true);
assertEquals(Json.TRUE, object.get("foo"));
}
@Test
public void get_int_returnsValueFromMember() {
object.add("foo", 23);
assertEquals(23, object.getInt("foo", 42));
}
@Test
public void get_int_returnsDefaultForMissingMember() {
assertEquals(23, object.getInt("foo", 23));
}
@Test
public void get_long_returnsValueFromMember() {
object.add("foo", 23l);
assertEquals(23l, object.getLong("foo", 42l));
}
@Test
public void get_long_returnsDefaultForMissingMember() {
assertEquals(23l, object.getLong("foo", 23l));
}
@Test
public void get_float_returnsValueFromMember() {
object.add("foo", 3.14f);
assertEquals(3.14f, object.getFloat("foo", 1.41f), 0);
}
@Test
public void get_float_returnsDefaultForMissingMember() {
assertEquals(3.14f, object.getFloat("foo", 3.14f), 0);
}
@Test
public void get_double_returnsValueFromMember() {
object.add("foo", 3.14);
assertEquals(3.14, object.getDouble("foo", 1.41), 0);
}
@Test
public void get_double_returnsDefaultForMissingMember() {
assertEquals(3.14, object.getDouble("foo", 3.14), 0);
}
@Test
public void get_boolean_returnsValueFromMember() {
object.add("foo", true);
assertTrue(object.getBoolean("foo", false));
}
@Test
public void get_boolean_returnsDefaultForMissingMember() {
assertFalse(object.getBoolean("foo", false));
}
@Test
public void get_string_returnsValueFromMember() {
object.add("foo", "bar");
assertEquals("bar", object.getString("foo", "default"));
}
@Test
public void get_string_returnsDefaultForMissingMember() {
assertEquals("default", object.getString("foo", "default"));
}
@Test
public void add_failsWithNullName() {
assertException(NullPointerException.class, "name is null", new Runnable() {
public void run() {
object.add(null, 23);
}
});
}
@Test
public void add_int() {
object.add("a", 23);
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void add_int_enablesChaining() {
assertSame(object, object.add("a", 23));
}
@Test
public void add_long() {
object.add("a", 23l);
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void add_long_enablesChaining() {
assertSame(object, object.add("a", 23l));
}
@Test
public void add_float() {
object.add("a", 3.14f);
assertEquals("{\"a\":3.14}", object.toString());
}
@Test
public void add_float_enablesChaining() {
assertSame(object, object.add("a", 3.14f));
}
@Test
public void add_double() {
object.add("a", 3.14d);
assertEquals("{\"a\":3.14}", object.toString());
}
@Test
public void add_double_enablesChaining() {
assertSame(object, object.add("a", 3.14d));
}
@Test
public void add_boolean() {
object.add("a", true);
assertEquals("{\"a\":true}", object.toString());
}
@Test
public void add_boolean_enablesChaining() {
assertSame(object, object.add("a", true));
}
@Test
public void add_string() {
object.add("a", "foo");
assertEquals("{\"a\":\"foo\"}", object.toString());
}
@Test
public void add_string_toleratesNull() {
object.add("a", (String)null);
assertEquals("{\"a\":null}", object.toString());
}
@Test
public void add_string_enablesChaining() {
assertSame(object, object.add("a", "foo"));
}
@Test
public void add_jsonNull() {
object.add("a", Json.NULL);
assertEquals("{\"a\":null}", object.toString());
}
@Test
public void add_jsonArray() {
object.add("a", new JsonArray());
assertEquals("{\"a\":[]}", object.toString());
}
@Test
public void add_jsonObject() {
object.add("a", new JsonObject());
assertEquals("{\"a\":{}}", object.toString());
}
@Test
public void add_json_enablesChaining() {
assertSame(object, object.add("a", Json.NULL));
}
@Test
public void add_json_failsWithNull() {
assertException(NullPointerException.class, "value is null", new Runnable() {
public void run() {
object.add("a", (JsonValue)null);
}
});
}
@Test
public void add_json_nestedArray() {
JsonArray innerArray = new JsonArray();
innerArray.add(23);
object.add("a", innerArray);
assertEquals("{\"a\":[23]}", object.toString());
}
@Test
public void add_json_nestedArray_modifiedAfterAdd() {
JsonArray innerArray = new JsonArray();
object.add("a", innerArray);
innerArray.add(23);
assertEquals("{\"a\":[23]}", object.toString());
}
@Test
public void add_json_nestedObject() {
JsonObject innerObject = new JsonObject();
innerObject.add("a", 23);
object.add("a", innerObject);
assertEquals("{\"a\":{\"a\":23}}", object.toString());
}
@Test
public void add_json_nestedObject_modifiedAfterAdd() {
JsonObject innerObject = new JsonObject();
object.add("a", innerObject);
innerObject.add("a", 23);
assertEquals("{\"a\":{\"a\":23}}", object.toString());
}
@Test
public void set_int() {
object.set("a", 23);
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void set_int_enablesChaining() {
assertSame(object, object.set("a", 23));
}
@Test
public void set_long() {
object.set("a", 23l);
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void set_long_enablesChaining() {
assertSame(object, object.set("a", 23l));
}
@Test
public void set_float() {
object.set("a", 3.14f);
assertEquals("{\"a\":3.14}", object.toString());
}
@Test
public void set_float_enablesChaining() {
assertSame(object, object.set("a", 3.14f));
}
@Test
public void set_double() {
object.set("a", 3.14d);
assertEquals("{\"a\":3.14}", object.toString());
}
@Test
public void set_double_enablesChaining() {
assertSame(object, object.set("a", 3.14d));
}
@Test
public void set_boolean() {
object.set("a", true);
assertEquals("{\"a\":true}", object.toString());
}
@Test
public void set_boolean_enablesChaining() {
assertSame(object, object.set("a", true));
}
@Test
public void set_string() {
object.set("a", "foo");
assertEquals("{\"a\":\"foo\"}", object.toString());
}
@Test
public void set_string_enablesChaining() {
assertSame(object, object.set("a", "foo"));
}
@Test
public void set_jsonNull() {
object.set("a", Json.NULL);
assertEquals("{\"a\":null}", object.toString());
}
@Test
public void set_jsonArray() {
object.set("a", new JsonArray());
assertEquals("{\"a\":[]}", object.toString());
}
@Test
public void set_jsonObject() {
object.set("a", new JsonObject());
assertEquals("{\"a\":{}}", object.toString());
}
@Test
public void set_json_enablesChaining() {
assertSame(object, object.set("a", Json.NULL));
}
@Test
public void set_addsElementIfMissing() {
object.set("a", Json.TRUE);
assertEquals("{\"a\":true}", object.toString());
}
@Test
public void set_modifiesElementIfExisting() {
object.add("a", Json.TRUE);
object.set("a", Json.FALSE);
assertEquals("{\"a\":false}", object.toString());
}
@Test
public void set_modifiesLastElementIfMultipleExisting() {
object.add("a", 1);
object.add("a", 2);
object.set("a", Json.TRUE);
assertEquals("{\"a\":1,\"a\":true}", object.toString());
}
@Test
public void remove_failsWithNullName() {
assertException(NullPointerException.class, "name is null", new Runnable() {
public void run() {
object.remove(null);
}
});
}
@Test
public void remove_removesMatchingMember() {
object.add("a", 23);
object.remove("a");
assertEquals("{}", object.toString());
}
@Test
public void remove_removesOnlyMatchingMember() {
object.add("a", 23);
object.add("b", 42);
object.add("c", true);
object.remove("b");
assertEquals("{\"a\":23,\"c\":true}", object.toString());
}
@Test
public void remove_removesOnlyLastMatchingMember() {
object.add("a", 23);
object.add("a", 42);
object.remove("a");
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void remove_removesOnlyLastMatchingMember_afterRemove() {
object.add("a", 23);
object.remove("a");
object.add("a", 42);
object.add("a", 47);
object.remove("a");
assertEquals("{\"a\":42}", object.toString());
}
@Test
public void remove_doesNotModifyObjectWithoutMatchingMember() {
object.add("a", 23);
object.remove("b");
assertEquals("{\"a\":23}", object.toString());
}
@Test
public void merge_failsWithNull() {
assertException(NullPointerException.class, "object is null", new Runnable() {
public void run() {
object.merge(null);
}
});
}
@Test
public void merge_appendsMembers() {
object.add("a", 1).add("b", 1);
object.merge(Json.object().add("c", 2).add("d", 2));
assertEquals(Json.object().add("a", 1).add("b", 1).add("c", 2).add("d", 2), object);
}
@Test
public void merge_replacesMembers() {
object.add("a", 1).add("b", 1).add("c", 1);
object.merge(Json.object().add("b", 2).add("d", 2));
assertEquals(Json.object().add("a", 1).add("b", 2).add("c", 1).add("d", 2), object);
}
@Test
public void write_empty() throws IOException {
JsonWriter writer = mock(JsonWriter.class);
object.write(writer);
InOrder inOrder = inOrder(writer);
inOrder.verify(writer).writeObjectOpen();
inOrder.verify(writer).writeObjectClose();
inOrder.verifyNoMoreInteractions();
}
@Test
public void write_withSingleValue() throws IOException {
JsonWriter writer = mock(JsonWriter.class);
object.add("a", 23);
object.write(writer);
InOrder inOrder = inOrder(writer);
inOrder.verify(writer).writeObjectOpen();
inOrder.verify(writer).writeMemberName("a");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeNumber("23");
inOrder.verify(writer).writeObjectClose();
inOrder.verifyNoMoreInteractions();
}
@Test
public void write_withMultipleValues() throws IOException {
JsonWriter writer = mock(JsonWriter.class);
object.add("a", 23);
object.add("b", 3.14f);
object.add("c", "foo");
object.add("d", true);
object.add("e", (String)null);
object.write(writer);
InOrder inOrder = inOrder(writer);
inOrder.verify(writer).writeObjectOpen();
inOrder.verify(writer).writeMemberName("a");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeNumber("23");
inOrder.verify(writer).writeObjectSeparator();
inOrder.verify(writer).writeMemberName("b");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeNumber("3.14");
inOrder.verify(writer).writeObjectSeparator();
inOrder.verify(writer).writeMemberName("c");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeString("foo");
inOrder.verify(writer).writeObjectSeparator();
inOrder.verify(writer).writeMemberName("d");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeLiteral("true");
inOrder.verify(writer).writeObjectSeparator();
inOrder.verify(writer).writeMemberName("e");
inOrder.verify(writer).writeMemberSeparator();
inOrder.verify(writer).writeLiteral("null");
inOrder.verify(writer).writeObjectClose();
inOrder.verifyNoMoreInteractions();
}
@Test
public void isObject() {
assertTrue(object.isObject());
}
@Test
public void asObject() {
assertSame(object, object.asObject());
}
@Test
public void equals_trueForSameInstance() {
assertTrue(object.equals(object));
}
@Test
public void equals_trueForEqualObjects() {
assertTrue(object().equals(object()));
assertTrue(object("a", "1", "b", "2").equals(object("a", "1", "b", "2")));
}
@Test
public void equals_falseForDifferentObjects() {
assertFalse(object("a", "1").equals(object("a", "2")));
assertFalse(object("a", "1").equals(object("b", "1")));
assertFalse(object("a", "1", "b", "2").equals(object("b", "2", "a", "1")));
}
@Test
public void equals_falseForNull() {
assertFalse(new JsonObject().equals(null));
}
@Test
public void equals_falseForSubclass() {
JsonObject jsonObject = new JsonObject();
assertFalse(jsonObject.equals(new JsonObject(jsonObject) {}));
}
@Test
public void hashCode_equalsForEqualObjects() {
assertTrue(object().hashCode() == object().hashCode());
assertTrue(object("a", "1").hashCode() == object("a", "1").hashCode());
}
@Test
public void hashCode_differsForDifferentObjects() {
assertFalse(object().hashCode() == object("a", "1").hashCode());
assertFalse(object("a", "1").hashCode() == object("a", "2").hashCode());
assertFalse(object("a", "1").hashCode() == object("b", "1").hashCode());
}
@Test
public void indexOf_returnsNoIndexIfEmpty() {
assertEquals(-1, object.indexOf("a"));
}
@Test
public void indexOf_returnsIndexOfMember() {
object.add("a", true);
assertEquals(0, object.indexOf("a"));
}
@Test
public void indexOf_returnsIndexOfLastMember() {
object.add("a", true);
object.add("a", true);
assertEquals(1, object.indexOf("a"));
}
@Test
public void indexOf_returnsIndexOfLastMember_afterRemove() {
object.add("a", true);
object.add("a", true);
object.remove("a");
assertEquals(0, object.indexOf("a"));
}
@Test
public void indexOf_returnsUpdatedIndexAfterRemove() {
// See issue
object.add("a", true);
object.add("b", true);
object.remove("a");
assertEquals(0, object.indexOf("b"));
}
@Test
public void indexOf_returnsIndexOfLastMember_forBigObject() {
object.add("a", true);
// for indexes above 255, the hash index table does not return a value
for (int i = 0; i < 256; i++) {
object.add("x-" + i, 0);
}
object.add("a", true);
assertEquals(257, object.indexOf("a"));
}
@Test
public void hashIndexTable_copyConstructor() {
HashIndexTable original = new HashIndexTable();
original.add("name", 23);
HashIndexTable copy = new HashIndexTable(original);
assertEquals(23, copy.get("name"));
}
@Test
public void hashIndexTable_add() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("name-0", 0);
indexTable.add("name-1", 1);
indexTable.add("name-fe", 0xfe);
indexTable.add("name-ff", 0xff);
assertEquals(0, indexTable.get("name-0"));
assertEquals(1, indexTable.get("name-1"));
assertEquals(0xfe, indexTable.get("name-fe"));
assertEquals(-1, indexTable.get("name-ff"));
}
@Test
public void hashIndexTable_add_overwritesPreviousValue() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("name", 23);
indexTable.add("name", 42);
assertEquals(42, indexTable.get("name"));
}
@Test
public void hashIndexTable_add_clearsPreviousValueIfIndexExceeds0xff() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("name", 23);
indexTable.add("name", 300);
assertEquals(-1, indexTable.get("name"));
}
@Test
public void hashIndexTable_remove() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("name", 23);
indexTable.remove(23);
assertEquals(-1, indexTable.get("name"));
}
@Test
public void hashIndexTable_remove_updatesSubsequentElements() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("foo", 23);
indexTable.add("bar", 42);
indexTable.remove(23);
assertEquals(41, indexTable.get("bar"));
}
@Test
public void hashIndexTable_remove_doesNotChangePrecedingElements() {
HashIndexTable indexTable = new HashIndexTable();
indexTable.add("foo", 23);
indexTable.add("bar", 42);
indexTable.remove(42);
assertEquals(23, indexTable.get("foo"));
}
@Test
public void canBeSerializedAndDeserialized() throws Exception {
object.add("foo", 23).add("bar", new JsonObject().add("a", 3.14d).add("b", true));
assertEquals(object, serializeAndDeserialize(object));
}
@Test
public void deserializedObjectCanBeAccessed() throws Exception {
object.add("foo", 23);
JsonObject deserializedObject = serializeAndDeserialize(object);
assertEquals(23, deserializedObject.get("foo").asInt());
}
@Test
public void member_returnsNameAndValue() {
Member member = new Member("a", Json.TRUE);
assertEquals("a", member.getName());
assertEquals(Json.TRUE, member.getValue());
}
@Test
public void member_equals_trueForSameInstance() {
Member member = new Member("a", Json.TRUE);
assertTrue(member.equals(member));
}
@Test
public void member_equals_trueForEqualObjects() {
Member member = new Member("a", Json.TRUE);
assertTrue(member.equals(new Member("a", Json.TRUE)));
}
@Test
public void member_equals_falseForDifferingObjects() {
Member member = new Member("a", Json.TRUE);
assertFalse(member.equals(new Member("b", Json.TRUE)));
assertFalse(member.equals(new Member("a", Json.FALSE)));
}
@Test
public void member_equals_falseForNull() {
Member member = new Member("a", Json.TRUE);
assertFalse(member.equals(null));
}
@Test
public void member_equals_falseForSubclass() {
Member member = new Member("a", Json.TRUE);
assertFalse(member.equals(new Member("a", Json.TRUE) {}));
}
@Test
public void member_hashCode_equalsForEqualObjects() {
Member member = new Member("a", Json.TRUE);
assertTrue(member.hashCode() == new Member("a", Json.TRUE).hashCode());
}
@Test
public void member_hashCode_differsForDifferingobjects() {
Member member = new Member("a", Json.TRUE);
assertFalse(member.hashCode() == new Member("b", Json.TRUE).hashCode());
assertFalse(member.hashCode() == new Member("a", Json.FALSE).hashCode());
}
private static JsonObject object(String... namesAndValues) {
JsonObject object = new JsonObject();
for (int i = 0; i < namesAndValues.length; i += 2) {
object.add(namesAndValues[i], namesAndValues[i + 1]);
}
return object;
}
}
|
package com.salesforce.ide.core.services;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.osgi.service.prefs.BackingStoreException;
import com.google.common.base.Preconditions;
import com.salesforce.ide.core.ForceIdeCorePlugin;
import com.salesforce.ide.core.compatibility.auth.IAuthorizationService;
import com.salesforce.ide.core.factories.FactoryException;
import com.salesforce.ide.core.internal.utils.*;
import com.salesforce.ide.core.model.*;
import com.salesforce.ide.core.project.*;
import com.salesforce.ide.core.remote.*;
import com.salesforce.ide.core.remote.metadata.*;
import com.sforce.soap.metadata.DeployMessage;
import com.sforce.soap.metadata.RetrieveMessage;
/**
*
* @author cwall
*/
public class ProjectService extends BaseService {
private static final Logger logger = Logger.getLogger(ProjectService.class);
private static final String AUTH_URL = "http:
private static final String AUTH_TYPE = "Basic";
private String ideBrandName = null;
private String platformBrandName = null;
private String ideReleaseName = null;
private TreeSet<String> supportedEndpointVersions = null;
private final IAuthorizationService authService;
public ProjectService() {
this(new AuthorizationServicePicker());
}
public ProjectService(AuthorizationServicePicker factory) {
this.authService = factory.makeAuthorizationService();
}
public String getIdeBrandName() {
return ideBrandName;
}
public void setIdeBrandName(String ideBrandName) {
this.ideBrandName = ideBrandName;
}
public String getPlatformBrandName() {
return platformBrandName;
}
public void setPlatformBrandName(String platformBrandName) {
this.platformBrandName = platformBrandName;
}
public String getIdeReleaseName() {
return ideReleaseName;
}
public void setIdeReleaseName(String ideReleaseName) {
this.ideReleaseName = ideReleaseName;
}
public TreeSet<String> getSupportedEndpointVersions() {
return supportedEndpointVersions;
}
public void setSupportedEndpointVersions(TreeSet<String> supportedEndpointVersions) {
this.supportedEndpointVersions = supportedEndpointVersions;
}
public boolean isSupportedEndpointVersion(String endpointVersion) {
if (Utils.isNotEmpty(supportedEndpointVersions) && Utils.isNotEmpty(endpointVersion)) {
endpointVersion = extractEndpointVersion(endpointVersion);
return supportedEndpointVersions.contains(endpointVersion);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Endpoint version [" + endpointVersion + "] is not supported");
}
return false;
}
}
private static String extractEndpointVersion(String endpoint) {
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.length() - 1);
}
if (endpoint.contains("/")) {
endpoint = endpoint.substring(endpoint.lastIndexOf("/") + 1);
}
return endpoint;
}
public String getLastSupportedEndpointVersion() {
return Utils.isNotEmpty(supportedEndpointVersions) ? supportedEndpointVersions.last() : "";
}
// C R E A T E P R O J E C T
public IProject createProject(String projectName, String[] natures, IProgressMonitor monitor) throws CoreException {
if (projectName == null) {
throw new IllegalArgumentException("Project name cannot be null");
}
if (logger.isDebugEnabled()) {
logger.debug("Create new project '" + projectName + "'");
}
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject newProject = root.getProject(projectName);
// if project doesn't exist, create
IProjectDescription projectDescription = workspace.newProjectDescription(projectName);
if (!newProject.exists()) {
projectDescription = workspace.newProjectDescription(projectName);
newProject.create(projectDescription, monitor);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Existing project '" + projectName
+ "' found in workspace - will attempt to apply Force.com");
}
projectDescription = newProject.getDescription();
}
// open project
newProject.open(monitor);
// create project w/ natures does not configure builds like the following does
if (Utils.isNotEmpty(natures) && newProject.isOpen()) {
BaseNature.addNature(newProject, natures, monitor);
} else {
logger.warn("Applying no nature to new project '" + projectName + "'");
}
flagProjectAsNew(newProject);
return newProject;
}
public void flagProjectAsNew(IProject project) throws CoreException {
// set project property identifying this project as brand new
// property is used downstream to skip building of new projects
flagSkipBuilder(project);
}
public void flagSkipBuilder(IProject project) throws CoreException {
if (project == null) {
logger.error("Unable to set skip builder flag - project is null");
return;
}
project.setSessionProperty(QualifiedNames.QN_SKIP_BUILDER, true);
}
public ProjectPackageList getProjectContents(IResource resource, IProgressMonitor monitor) throws CoreException,
InterruptedException, FactoryException {
if (resource == null) {
throw new IllegalArgumentException("Resource cannot be null");
}
List<IResource> resources = new ArrayList<>(1);
resources.add(resource);
return getProjectContents(resources, monitor);
}
public ProjectPackageList getProjectContents(List<IResource> resources, IProgressMonitor monitor)
throws CoreException, InterruptedException, FactoryException {
return getProjectContents(resources, false, monitor);
}
public ProjectPackageList getProjectContents(List<IResource> resources, boolean includeAssociated,
IProgressMonitor monitor) throws CoreException, InterruptedException, FactoryException {
if (Utils.isEmpty(resources)) {
throw new IllegalArgumentException("Resources cannot be null");
}
ProjectPackageList projectPackageList = getProjectPackageListInstance();
projectPackageList.setProject(resources.get(0).getProject());
for (IResource resource : resources) {
if (resource.getType() == IResource.PROJECT) {
projectPackageList = getProjectContents(resource.getProject(), monitor);
} else if (isSourceFolder(resource)) {
projectPackageList = getProjectContents(resource.getProject(), monitor);
} else if (isComponentFolder(resource)) {
ComponentList componentList = getComponentsForComponentFolder((IFolder) resource, true, true);
projectPackageList.addComponents(componentList, false);
} else if (isSubComponentFolder(resource)) {
ComponentList componentList = getComponentsForSubComponentFolder((IFolder) resource, true);
projectPackageList.addComponents(componentList, false);
} else if (isManagedFile(resource)) { //if we're in a force.com project. "isManaged" is misleading.
Component component = getComponentFactory().getComponentFromFile((IFile) resource);
projectPackageList.addComponent(component, true);
// add dependent or associated components such as folder metadata component if component is sub-folder component
if (includeAssociated) {
ComponentList componentList = getComponentFactory().getAssociatedComponents(component);
if (Utils.isNotEmpty(componentList)) {
projectPackageList.addComponents(componentList, false);
}
}
}
}
//filter out any built in folder stuff.
// if component subfolder is built-in subfolder, then this subfolder will be available in dest org (also this subfolder is not retrievable/deployable)
// so no need to add subfolder component to deploy list. W-623512
ComponentList allComponentsList = getComponentFactory().getComponentListInstance();
allComponentsList.addAll(projectPackageList.getAllComponents());
for (Component component : allComponentsList) {
if (Utils.isNotEmpty(component.getBuiltInSubFolders())) {
for (String builtInSubFolder : component.getBuiltInSubFolders()) {
if (builtInSubFolder.equals(component.getName())) {
projectPackageList.removeComponent(component);
}
}
}
}
return projectPackageList;
}
public ProjectPackageList getProjectContents(IProject project, IProgressMonitor monitor) throws CoreException,
InterruptedException, FactoryException {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
monitorCheck(monitor);
// initialize container to holder contents
ProjectPackageList projectPackageList = getProjectPackageListInstance();
projectPackageList.setProject(project);
// ensure project is not empty
if (isProjectEmpty(project)) {
return projectPackageList;
}
// get src folder; discontinue if not found or empty
IResource sourceResource = project.findMember(Constants.SOURCE_FOLDER_NAME);
if (sourceResource == null || !sourceResource.exists() || sourceResource.getType() != IResource.FOLDER
|| Utils.isEmpty(((IFolder) sourceResource).members())) {
if (logger.isInfoEnabled()) {
logger.info(Constants.SOURCE_FOLDER_NAME
+ " not found, does not exist, or does not contain package folders in project '"
+ project.getName() + "'");
}
return projectPackageList;
}
List<IFolder> componentFolders = getComponentFolders((IFolder) sourceResource);
for (IFolder componentFolder : componentFolders) {
monitorCheck(monitor);
if (Utils.isEmpty(componentFolder.members())) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping folder " + project.getName() + "' - no components found");
}
continue;
}
// find components in componet folder
ComponentList componentList = getComponentsForComponentFolder(componentFolder, true, true);
if (componentList.isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Component folder '" + componentFolder.getName()
+ "' is does not contain components for enabled object types");
}
continue;
}
// add components to project package list instance including reference to package manifest
projectPackageList.addComponents(componentList, false);
if (logger.isDebugEnabled()) {
logger.debug("Added '" + componentFolder.getName() + "' folder containing [" + componentList.size()
+ "] components to project package list");
}
}
return projectPackageList;
}
// R E S O U R C E F I N D E R S
/**
* Get Force.com projects
*
* @param includeOnline
* include all projects with online nature vs. only base nature
* @return
*/
public List<IProject> getForceProjects() {
List<IProject> forceProjects = new ArrayList<>();
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
if (Utils.isNotEmpty(projects)) {
for (IProject project : projects) {
try {
if (project.isOpen() && project.hasNature(DefaultNature.NATURE_ID)) {
forceProjects.add(project);
}
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to determine project nature: " + logMessage);
}
}
}
return forceProjects;
}
/**
* This method supports getting component file within sub-component folder (only 1 level down - not recursive)
*
* @param project
* @param componentName
* @param componentTypes
* @return
* @throws CoreException
*/
public IFile getComponentFileByNameType(IProject project, String componentName, String[] componentTypes)
throws CoreException {
if (Utils.isEmpty(componentName) || project == null || Utils.isEmpty(componentTypes)) {
throw new IllegalArgumentException("Component name, types, and/or project cannot be null");
}
IFile file = null;
for (String componentType : componentTypes) {
file = getComponentFileByNameType(project, componentName, componentType);
if (file != null) {
return file;
}
}
if (logger.isInfoEnabled()) {
logger.info("File for '" + componentName + "' not found");
}
return file;
}
public IFile getComponentFileByNameType(IProject project, String componentName, String componentType)
throws CoreException {
if (Utils.isEmpty(componentName) || project == null || Utils.isEmpty(componentType)) {
throw new IllegalArgumentException("Package name, type, and/or project cannot be null");
}
IFolder componentFolder = getComponentFolderByComponentType(project, componentType);
if (componentFolder == null || !componentFolder.exists()) {
if (logger.isInfoEnabled()) {
logger.info("Did not find folder for type '" + componentType);
}
return null;
}
Component componentTypeInfo = getComponentFactory().getComponentByComponentType(componentType);
IResource[] resources = componentFolder.members();
for (IResource resource : resources) {
String fullName = componentName;
if (!componentName.contains(componentTypeInfo.getFileExtension())) {
fullName = componentName + "." + componentTypeInfo.getFileExtension();
}
// because trigger and class may have the same name, so need to match the file extension as well
if (resource.getType() == IResource.FILE && ((IFile) resource).getName().equalsIgnoreCase(fullName)) {
if (logger.isInfoEnabled()) {
StringBuilder stringBuilder = new StringBuilder("File '");
stringBuilder.append(resource.getProjectRelativePath().toPortableString())
.append(" found for component type '").append(componentType).append("', component '")
.append(componentName).append("'");
logger.info(stringBuilder.toString());
}
return (IFile) resource;
} else if (resource.getType() == IResource.FOLDER) {
IResource[] subFolderResources = ((IFolder) resource).members();
for (IResource subFolderResource : subFolderResources) {
// because trigger and class may have the same name, so need to match the file extension as well
if (subFolderResource.getType() == IResource.FILE
&& ((IFile) subFolderResource).getName().equalsIgnoreCase(fullName)) {
if (logger.isInfoEnabled()) {
StringBuilder stringBuilder = new StringBuilder("File '");
stringBuilder.append(subFolderResource.getProjectRelativePath().toPortableString())
.append(" found for component type '").append(componentType)
.append("', component '").append(componentName).append("'");
logger.info(stringBuilder.toString());
}
return (IFile) subFolderResource;
}
}
}
}
if (logger.isInfoEnabled()) {
logger.info("File not found for component '" + componentName + "'");
}
return null;
}
public IFile getCompositeFileResource(IFile file) {
// check is file is a component and is a metadata composite, if so add composite
Component component = null;
try {
component = getComponentFactory().getComponentFromFile(file, true);
} catch (FactoryException e) {
logger.warn("Unable to detemine if file '" + file.getName() + "' is a component");
return null;
}
if (component.isPackageManifest() || !component.isMetadataComposite()) {
return null;
}
// load component composite
String compositeComponentFilePath = component.getCompositeMetadataFilePath();
if (Utils.isEmpty(compositeComponentFilePath)) {
logger.warn("Component metadata path is null for " + component.getFullDisplayName());
return null;
}
return getComponentFileForFilePath(file.getProject(), compositeComponentFilePath);
}
public List<IFolder> getComponentFolders(IFolder sourceFolder) throws CoreException {
if (sourceFolder == null) {
throw new IllegalArgumentException("Source folder cannot be null");
}
if (!sourceFolder.exists() || !isSourceFolder(sourceFolder)) {
if (logger.isInfoEnabled()) {
logger.info("Did not find '" + Constants.SOURCE_FOLDER_NAME + " folder");
}
return null;
}
if (logger.isInfoEnabled()) {
logger.info("Found '" + sourceFolder.getName() + "' folder");
}
IResource[] sourceFolderResources = sourceFolder.members();
if (Utils.isEmpty(sourceFolderResources)) {
if (logger.isInfoEnabled()) {
logger.info("Did not any package folders in '" + Constants.SOURCE_FOLDER_NAME + " folder");
}
return null;
}
List<IFolder> componentFolders = new ArrayList<>();
for (IResource sourceFolderResource : sourceFolderResources) {
if (sourceFolderResource.getType() != IResource.FOLDER) {
continue;
}
if (isComponentFolder(sourceFolderResource)) {
componentFolders.add((IFolder) sourceFolderResource);
}
}
if (logger.isInfoEnabled()) {
logger.info("Found [" + componentFolders.size() + "] component folders");
}
return componentFolders;
}
public IFolder getComponentFolderByComponentType(IProject project, String componentType) throws CoreException {
Component component = getComponentFactory().getComponentByComponentType(componentType);
if (component == null) {
logger.warn("Unable to find component for type '" + componentType + "'");
return null;
}
return getComponentFolderByName(project, component.getDefaultFolder(), false, new NullProgressMonitor());
}
public IFolder getComponentFolderByName(IProject project, String componentFolderName, boolean create,
IProgressMonitor monitor) throws CoreException {
if (Utils.isEmpty(componentFolderName) || project == null) {
throw new IllegalArgumentException("Folder name and/or project cannot be null");
}
IFolder sourceFolder = getSourceFolder(project);
if (sourceFolder == null || !sourceFolder.exists() || Utils.isEmpty(sourceFolder.members())) {
if (logger.isInfoEnabled()) {
logger.info("Did not find '" + Constants.SOURCE_FOLDER_NAME + " folder or folder is empty");
}
return null;
}
IFolder componentFolder = sourceFolder.getFolder(componentFolderName);
if (componentFolder == null || !componentFolder.exists()) {
if (logger.isInfoEnabled()) {
logger.info("Did not find component folder '" + componentFolderName + "'");
}
return null;
}
return componentFolder;
}
public ProjectPackageList getComponentsForComponentTypes(IProject project, String[] componentTypes)
throws CoreException, FactoryException {
ProjectPackageList projectPackageList = getProjectPackageFactory().getProjectPackageListInstance(project);
if (Utils.isNotEmpty(componentTypes)) {
for (String componentType : componentTypes) {
IFolder componentFolder = getComponentFolderByComponentType(project, componentType);
if (componentFolder != null && componentFolder.exists()) {
ComponentList componentList = getComponentFactory().getComponentListInstance();
componentList.addAll(getComponentsForFolder(componentFolder, true));
projectPackageList.addComponents(componentList, true);
}
}
}
return projectPackageList;
}
public ComponentList getComponentsForComponentType(IProject project, String componentType) throws CoreException,
FactoryException {
IFolder componentFolder = getComponentFolderByComponentType(project, componentType);
ComponentList componentList = getComponentFactory().getComponentListInstance();
componentList.addAll(getComponentsForFolder(componentFolder, true));
return componentList;
}
public ComponentList getComponentsForFolder(IFolder folder, boolean traverse) throws CoreException,
FactoryException {
return getComponentsForFolder(folder, traverse, true);
}
public ComponentList getComponentsForFolder(IFolder folder, boolean traverse, boolean includeManifest)
throws CoreException, FactoryException {
return getComponentsForFolder(folder, null, traverse, includeManifest);
}
public ComponentList getComponentsForFolder(IFolder folder, String[] enabledComponentTypes, boolean traverse)
throws CoreException, FactoryException {
return getComponentsForFolder(folder, enabledComponentTypes, traverse, true);
}
public ComponentList getComponentsForFolder(IFolder folder, String[] enabledComponentTypes, boolean traverse,
boolean includeManifest) throws CoreException, FactoryException {
if (folder == null || !folder.exists()) {
throw new IllegalArgumentException("Folder cannot be null");
}
// initialize component
ComponentList componentList = getComponentFactory().getComponentListInstance();
// convert for contains access
List<String> enabledComponentTypesList = null;
if (enabledComponentTypes != null) {
enabledComponentTypesList = Arrays.asList(enabledComponentTypes);
}
if (isSourceFolder(folder)) {
// loop thru registered component list inspecting respective folder and folder contents
ComponentList registeredComponents =
getComponentFactory().getEnabledRegisteredComponents(enabledComponentTypes);
for (IComponent registeredComponent : registeredComponents) {
if (null != enabledComponentTypesList
&& !enabledComponentTypesList.contains(registeredComponent.getComponentType())) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping component type '" + registeredComponent.getComponentType()
+ "' - type not a selected object type");
}
continue;
}
String componentFolderPath =
Constants.SOURCE_FOLDER_NAME + "/" + registeredComponent.getDefaultFolder();
IFolder componentFolder = folder.getProject().getFolder(componentFolderPath);
if (componentFolder == null || !componentFolder.exists()) {
continue;
}
ComponentList tmpComponentList = getComponentsForComponentFolder(componentFolder, traverse, true);
if (Utils.isNotEmpty(tmpComponentList)) {
componentList.addAll(tmpComponentList);
}
}
} else if (isComponentFolder(folder)) {
ComponentList tmpComponentList = getComponentsForComponentFolder(folder, traverse, true);
if (Utils.isNotEmpty(tmpComponentList)) {
componentList.addAll(tmpComponentList);
}
} else if (isSubComponentFolder(folder)) {
ComponentList tmpComponentList = getComponentsForComponentFolder(folder, traverse, true);
if (Utils.isNotEmpty(tmpComponentList)) {
componentList.addAll(tmpComponentList);
}
}
return componentList;
}
public ComponentList getComponentsForComponentFolder(IFolder folder, boolean traverse, boolean includeBody)
throws CoreException, FactoryException {
if (null == folder) return null;
if (!folder.exists() || Utils.isEmpty(folder.members())) {
if (logger.isDebugEnabled()) {
logger.debug("Component folder '" + folder.getName() + "' does not exist or does not "
+ "contain components");
}
return null;
}
// initialize component
ComponentList componentList = getComponentFactory().getComponentListInstance();
IResource[] componentFolderResources = folder.members();
for (IResource componentFolderResource : componentFolderResources) {
if (traverse && IResource.FOLDER == componentFolderResource.getType()) {
IFolder componentFolderWithSub = (IFolder) componentFolderResource;
ComponentList tmpComponentList = getComponentsForSubComponentFolder(componentFolderWithSub, traverse);
componentList.addAll(tmpComponentList);
} else if (IResource.FILE == componentFolderResource.getType()) {
IFile componentFile = (IFile) componentFolderResource;
try {
Component tmpComponent = getComponentFactory().getComponentFromFile(componentFile, includeBody);
componentList.add(tmpComponent, false, true);
if (logger.isDebugEnabled()) {
logger.debug("Added component '"
+ componentFolderResource.getProjectRelativePath().toPortableString() + "' to list");
}
} catch (FactoryException e) {
logger.error("Unable to create component from filepath "
+ componentFile.getProjectRelativePath().toPortableString());
}
}
}
return componentList;
}
/**
* This method is used to retrieve components under sub-componentfolder including sub-componentfolder itself in the
* returned list. Assumption: the subComponentFolder's metadata file is located under componentFolder and naming as
* <subComponentFolderName>-meta.xml
*
* @param folder
* - subComponentFolder
* @param traverse
* @return
* @throws CoreException
* @throws FactoryException
*/
public ComponentList getComponentsForSubComponentFolder(IFolder folder, boolean traverse) throws CoreException,
FactoryException {
ComponentList componentList = getComponentsForComponentFolder(folder, traverse, true);
if (componentList == null) {
componentList = getComponentFactory().getComponentListInstance();
}
Component component = getComponentFactory().getComponentFromSubFolder(folder, false);
componentList.add(component);
return componentList;
}
public IFile getComponentFileForFilePath(IProject project, String filePath) {
if (Utils.isEmpty(filePath) || project == null) {
throw new IllegalArgumentException("Filepath and/or project cannot be null");
}
String tmpFilePath = filePath;
if (!filePath.startsWith(Constants.SOURCE_FOLDER_NAME)) {
IFolder packageSourceFolder = getSourceFolder(project);
if (packageSourceFolder == null || !packageSourceFolder.exists()) {
logger.warn("Unable to find package source folder. Discontinuing search of file '" + filePath + "'");
return null;
}
tmpFilePath = packageSourceFolder.getProjectRelativePath().toPortableString() + "/" + filePath;
}
IResource resource = project.findMember(tmpFilePath);
if (resource == null || !resource.exists() || resource.getType() != IResource.FILE) {
logger.warn("Resource not found or not a file for filepath '" + tmpFilePath + "'");
return null;
}
if (logger.isInfoEnabled()) {
logger.info("Found resource for filepath '" + tmpFilePath + "'");
}
return (IFile) resource;
}
public List<IResource> filterChildren(List<IResource> selectedResources) {
if (Utils.isEmpty(selectedResources) || selectedResources.size() == 1) {
return selectedResources;
}
for (Iterator<IResource> iterator = selectedResources.iterator(); iterator.hasNext();) {
IResource resource = iterator.next();
if (hasParent(selectedResources, resource)) {
iterator.remove();
}
}
return selectedResources;
}
private boolean hasParent(List<IResource> selectedResources, IResource resource) {
if (resource == null || resource.getParent() == null || resource.getType() == IResource.ROOT
|| Utils.isEmpty(selectedResources)) {
return false;
}
if (resource.getParent() != null && selectedResources.contains(resource.getParent())) {
return true;
}
return hasParent(selectedResources, resource.getParent());
}
/**
* filters out only IFiles from a list of IResources
*
* @param allResources
* @return
* @throws CoreException
*/
public List<IResource> getAllFilesOnly(List<IResource> allResources) throws CoreException {
if (Utils.isEmpty(allResources)
|| (allResources.size() == 1 && allResources.get(0).getType() == IResource.FILE)) {
return allResources;
}
List<IResource> ret_filesList = new ArrayList<>();
for (IResource resource : allResources) {
if (resource.getType() == IResource.PROJECT) {
addAllFilesOnly((IProject) resource, ret_filesList);
} else if (resource.getType() == IResource.FOLDER) {
addAllFilesOnly((IFolder) resource, ret_filesList);
} else if (resource.getType() == IResource.FILE && isBuildableResource(resource)) {
ret_filesList.add(resource);
}
}
return ret_filesList;
}
/**
* filters out files from a list of resource given a IProject
*
* @param project
* the project in which these files belong
* @param resourcesList
* a list of all resources that will be populated with IFiles
* @throws CoreException
*/
private void addAllFilesOnly(IProject project, List<IResource> resourcesList) throws CoreException {
if (Utils.isEmpty(project.members())) {
if (logger.isDebugEnabled()) {
logger.debug("Project does not have members");
}
return;
}
for (IResource member : project.members()) {
if (member.getType() == IResource.FOLDER) {
addAllFilesOnly((IFolder) member, resourcesList);
} else if (member.getType() == IResource.FILE && isBuildableResource(member)) {
resourcesList.add(member);
}
}
}
/**
* filters out files from a list of resources given a Ifolder
*
* @param folder
* the folder to work on.
* @param resourcesList
* a list of resources which will be populated.
* @throws CoreException
*/
private void addAllFilesOnly(IFolder folder, List<IResource> resourcesList) throws CoreException {
if (Utils.isEmpty(folder.members())) {
if (logger.isDebugEnabled()) {
logger.debug("Folder does not have members");
}
return;
}
for (IResource member : folder.members()) {
if (member.getType() == IResource.FOLDER) {
addAllFilesOnly((IFolder) member, resourcesList);
} else if (member.getType() == IResource.FILE && isBuildableResource(member)) {
resourcesList.add(member);
}
}
}
public List<IResource> getResourcesByType(List<IResource> resources, int type) {
if (Utils.isEmpty(resources)) {
return null;
}
List<IResource> specificResources = new ArrayList<>(resources.size());
for (IResource resource : resources) {
if (resource.getType() == type) {
specificResources.add(resource);
}
}
return specificResources;
}
public IFolder getFolder(List<IResource> resources, String name) {
if (Utils.isEmpty(resources)) {
return null;
}
for (IResource resource : resources) {
if (resource.getType() == IResource.FOLDER && resource.getName().endsWith(name)) {
return (IFolder) resource;
}
}
return null;
}
public boolean isProjectEmpty(IProject project) throws CoreException {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
IResource[] resources = project.members();
if (Utils.isEmpty(resources)) {
if (logger.isInfoEnabled()) {
logger.info("No resources found in project '" + project.getName() + "'");
}
return true;
}
return false;
}
public IFolder getSourceFolder(IProject project) {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
IResource packageSourceFolder = project.findMember(Constants.SOURCE_FOLDER_NAME);
if (packageSourceFolder == null || !packageSourceFolder.exists()
|| packageSourceFolder.getType() != IResource.FOLDER) {
if (logger.isInfoEnabled()) {
logger.info("Did not find '" + Constants.SOURCE_FOLDER_NAME + " folder");
}
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("Found '" + packageSourceFolder.getName() + "' folder");
}
return (IFolder) packageSourceFolder;
}
public IFolder getReferencedPackagesFolder(IProject project) {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
IResource referencedPackageFolder = project.findMember(Constants.REFERENCED_PACKAGE_FOLDER_NAME);
if (referencedPackageFolder == null || !referencedPackageFolder.exists()
|| referencedPackageFolder.getType() != IResource.FOLDER) {
if (logger.isInfoEnabled()) {
logger.info("Did not find '" + Constants.REFERENCED_PACKAGE_FOLDER_NAME + " folder");
}
return null;
}
if (logger.isDebugEnabled()) {
logger.debug("Found '" + referencedPackageFolder.getName() + "' folder");
}
return (IFolder) referencedPackageFolder;
}
public boolean hasSourceFolderContents(IProject project) throws CoreException {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
IResource packageSourceFolder = project.findMember(Constants.SOURCE_FOLDER_NAME);
if (packageSourceFolder == null || !packageSourceFolder.exists()
|| packageSourceFolder.getType() != IResource.FOLDER) {
if (logger.isInfoEnabled()) {
logger.info("Did not find '" + Constants.SOURCE_FOLDER_NAME + " folder");
}
return false;
}
if (Utils.isEmpty(((IFolder) packageSourceFolder).members())) {
return false;
}
if (logger.isInfoEnabled()) {
logger.info("Project '" + project.getName() + "' has contents in package folders");
}
return true;
}
// N A T U R E S
public void applyDefaultNature(IProject project, IProgressMonitor monitor) throws CoreException {
DefaultNature.addNature(project, monitor);
monitorWork(monitor);
}
public void applyOnlineNature(IProject project, IProgressMonitor monitor) throws CoreException {
OnlineNature.addNature(project, monitor);
monitorWork(monitor);
}
public void applyNatures(IProject project, IProgressMonitor monitor) throws CoreException {
applyDefaultNature(project, monitor);
applyOnlineNature(project, monitor);
}
public void removeNatures(IProject project, IProgressMonitor monitor) {
OnlineNature.removeNature(project, monitor);
monitorWork(monitor);
DefaultNature.removeNature(project, monitor);
monitorWork(monitor);
}
// I D E M A N A G E D R E S O U R C E C H E C K S
public boolean isManagedResources(List<IResource> resources) {
if (Utils.isEmpty(resources)) {
return false;
}
for (IResource resource : resources) {
if (!isManagedResource(resource)) {
return false;
}
}
return true;
}
public boolean isManagedResource(IResource resource) {
if (resource == null) {
return false;
}
if (resource.getType() == IResource.FILE) {
return isManagedFile(resource);
} else if (resource.getType() == IResource.FOLDER) {
return isManagedFolder(resource);
} else if (resource.getType() == IResource.PROJECT) {
return isManagedProject(resource);
} else {
if (logger.isInfoEnabled()) {
logger.info("Resource type '" + resource.getType() + "' not managed by force");
}
return false;
}
}
public boolean isManagedFile(IResource resource) {
if (resource == null || resource.getType() != IResource.FILE) {
return false;
}
return isManagedFile((IFile) resource);
}
public boolean isManagedFile(IFile file) {
if (file == null || file.getType() != IResource.FILE) {
return false;
}
if (!isInManagedProject(file)) {
return false;
}
if (Utils.isEmpty(file.getProjectRelativePath().toPortableString())) {
if (logger.isInfoEnabled()) {
logger.info("Filepath not found for file '" + file + "'");
}
return false;
}
Component component = null;
component = getComponentFactory().getComponentByFilePath(file.getProjectRelativePath().toPortableString());
if (component != null) {
if (logger.isDebugEnabled()) {
logger.debug("Component found for filepath '" + file.getProjectRelativePath().toPortableString() + "'");
}
return true;
}
logger.warn("Component not found for filepath '" + file.getProjectRelativePath().toPortableString() + "'");
return false;
}
public boolean isManagedFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isManagedFolder(((IFolder) resource));
}
public boolean isManagedFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
if (isSourceFolder(folder)) {
return true;
}
if (isComponentFolder(folder)) {
return true;
}
if (isSubComponentFolder(folder)) {
return true;
}
if (isPackageFolder(folder)) {
return true;
}
if (isReferencedPackagesFolder(folder)) {
return true;
}
if (logger.isInfoEnabled()) {
logger.info("Folder '" + folder.getProjectRelativePath().toPortableString() + "' is not "
+ Constants.PLUGIN_NAME + " managed");
}
return false;
}
public boolean isManagedProject(IResource resource) {
if (resource == null || resource.getType() != IResource.PROJECT) {
return false;
}
IProject project = resource.getProject();
try {
boolean hasNature = project.hasNature(DefaultNature.NATURE_ID);
if (logger.isDebugEnabled()) {
logger.debug("Project '" + project.getName() + "' is " + (hasNature ? Constants.EMPTY_STRING : "not")
+ " " + Constants.PLUGIN_NAME + " managed");
}
return hasNature;
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to determine if project is " + Constants.PLUGIN_NAME + " managed with exception: "
+ logMessage);
return false;
}
}
public boolean isManagedOnlineProject(IResource resource) {
if (resource == null || resource.getType() != IResource.PROJECT) {
return false;
}
IProject project = resource.getProject();
try {
boolean hasNature = project.hasNature(OnlineNature.NATURE_ID);
if (logger.isDebugEnabled()) {
logger.debug("Project '" + project.getName() + "' is " + (hasNature ? Constants.EMPTY_STRING : "not")
+ " " + Constants.PLUGIN_NAME + " managed");
}
return hasNature;
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to determine if project is " + Constants.PLUGIN_NAME + " managed: " + logMessage);
return false;
}
}
/**
* @return true is the resource is in a managed project (that has an force nature )
*/
public boolean isInManagedProject(IResource resource) {
if (resource == null
|| (resource.getType() != IResource.PROJECT && resource.getType() != IResource.FOLDER && resource
.getType() != IResource.FILE)) {
return false;
}
IProject project = resource.getProject();
if (!project.isOpen()) {
return false;
}
try {
return project.hasNature(DefaultNature.NATURE_ID);
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to determine if resource '" + resource.getName() + "' is force managed: " + logMessage);
return false;
}
}
public boolean isSourceFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isSourceFolder((IFolder) resource);
}
public boolean isSourceFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
String folderName = folder.getName();
if (folderName.equals(Constants.SOURCE_FOLDER_NAME) && isAtProjectRoot(folder)) {
return true;
}
return false;
}
public boolean isSourceResource(IResource resource) {
if (resource == null) {
return false;
}
if (!isInManagedProject(resource)) {
return false;
}
if (resource.getType() == IResource.FOLDER && isSourceFolder(resource)) {
return true;
}
if (resource.getProjectRelativePath().toPortableString().startsWith(Constants.SOURCE_FOLDER_NAME)) {
if (logger.isDebugEnabled()) {
logger.debug("Resource '" + resource.getProjectRelativePath().toPortableString()
+ "' is a package resource");
}
return true;
}
return false;
}
public boolean hasPackageManifest(IResource resource) {
if (resource == null || !resource.exists()) {
return false;
}
IFile packageManifest =
resource.getProject()
.getFile(Constants.SOURCE_FOLDER_NAME + "/" + Constants.PACKAGE_MANIFEST_FILE_NAME);
return packageManifest != null && packageManifest.exists();
}
public boolean isPackageFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isPackageFolder((IFolder) resource);
}
public boolean isPackageFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
IResource[] members = null;
try {
members = folder.members();
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to get members of folder '" + folder.getProjectRelativePath().toPortableString()
+ "': " + logMessage);
}
if (null == members || 0 == members.length) {
if (logger.isInfoEnabled()) {
logger.info("Package manifest not found in folder '"
+ folder.getProjectRelativePath().toPortableString() + "'");
}
return false;
}
for (IResource tmpResource : members) {
if (tmpResource.getType() == IResource.FILE
&& Constants.PACKAGE_MANIFEST_FILE_NAME.equals(tmpResource.getName())) {
if (logger.isDebugEnabled()) {
logger.debug("Found '" + Constants.PACKAGE_MANIFEST_FILE_NAME + "' in folder '"
+ folder.getProjectRelativePath().toPortableString() + "'");
}
return true;
}
}
return false;
}
public boolean isReferencedPackagesFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isReferencedPackagesFolder((IFolder) resource);
}
public boolean isReferencedPackagesFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
IResource parentResource = folder.getParent();
if (parentResource != null && Constants.REFERENCED_PACKAGE_FOLDER_NAME.equals(folder.getName())
&& parentResource.getType() == IResource.PROJECT) {
return true;
}
if (parentResource == null || !Constants.REFERENCED_PACKAGE_FOLDER_NAME.equals(parentResource.getName())) {
if (logger.isDebugEnabled()) {
logger.debug("'" + Constants.REFERENCED_PACKAGE_FOLDER_NAME + "' is not parent of '"
+ folder.getProjectRelativePath().toPortableString() + "'");
}
return false;
}
return true;
}
/** Individual package folder under "Reference Packages" folder */
public boolean isReferencedPackageFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isReferencedPackageFolder((IFolder) resource);
}
/** Individual package folder under "Reference Packages" folder */
public boolean isReferencedPackageFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
IResource parentResource = folder.getParent();
if (parentResource == null || !isReferencedPackagesFolder(parentResource)) {
return false;
}
return true;
}
public boolean isReferencedPackageResource(IResource resource) {
if (resource == null) {
return false;
}
if (!isInManagedProject(resource)) {
return false;
}
if (resource.getType() == IResource.FOLDER && isReferencedPackagesFolder(resource)) {
return true;
}
if (resource.getProjectRelativePath().toPortableString().contains(Constants.REFERENCED_PACKAGE_FOLDER_NAME)) {
return true;
}
return false;
}
public boolean isSubComponentFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isSubComponentFolder((IFolder) resource);
}
public boolean isSubComponentFolder(IFolder folder) {
return folder.getParent().getType() == IResource.FOLDER && isComponentFolder((IFolder) folder.getParent());
}
public boolean isComponentFolder(IResource resource) {
if (resource == null || resource.getType() != IResource.FOLDER) {
return false;
}
return isComponentFolder((IFolder) resource);
}
public boolean isComponentFolder(IFolder folder) {
if (folder == null || folder.getType() != IResource.FOLDER) {
return false;
}
if (!isInManagedProject(folder)) {
return false;
}
IResource parentFolder = folder.getParent();
if (parentFolder == null || parentFolder.getType() != IResource.FOLDER || !isSourceFolder(parentFolder)) {
if (logger.isDebugEnabled()) {
logger.debug("Parent resource of folder name '" + folder.getProjectRelativePath().toPortableString()
+ "' is not a src folder - folder deemed not a component folder");
}
return false;
}
String folderName = folder.getName();
Component component = null;
component = getComponentFactory().getComponentByFolderName(folderName);
if (component != null) {
if (logger.isDebugEnabled()) {
logger.debug("Component found for folder name '" + folderName + "'");
}
return true;
}
if (logger.isInfoEnabled()) {
logger.info("Component not found for folder name '" + folderName + "'");
}
return false;
}
public boolean isPackageManifestFile(IResource resource) {
if (resource == null || resource.getType() != IResource.FILE) {
return false;
}
if (!isInManagedProject(resource)) {
return false;
}
if (resource.getName().equals(Constants.PACKAGE_MANIFEST_FILE_NAME)) {
if (logger.isDebugEnabled()) {
logger.debug("File '" + resource.getProjectRelativePath().toPortableString()
+ "' is a package manifest file");
}
return true;
}
return false;
}
public boolean isDefaultPackageManifestFile(IResource resource) {
if (resource == null || resource.getType() != IResource.FILE) {
return false;
}
if (!isInManagedProject(resource)) {
return false;
}
if (resource.getProjectRelativePath().toPortableString()
.endsWith(Constants.DEFAULT_PACKAGED_NAME + "/" + Constants.PACKAGE_MANIFEST_FILE_NAME)) {
if (logger.isDebugEnabled()) {
logger.debug("File '" + resource.getProjectRelativePath().toPortableString()
+ "' is the defauult package manifest file");
}
return true;
}
return false;
}
/**
* @return true is the resource is at the root of a project
*/
private static boolean isAtProjectRoot(IResource resource) {
return resource.getParent() instanceof IProject;
}
public boolean hasManagedComponents(List<IResource> resources) {
if (Utils.isEmpty(resources)) {
return false;
}
for (IResource resource : resources) {
if (hasManagedComponents(resource)) {
return true;
}
}
return false;
}
public boolean hasManagedComponents(IResource resource) {
if (resource == null) {
return false;
}
if (resource.getType() == IResource.FILE) {
return isManagedFile(resource);
}
IFolder rootFolder = null;
if (resource.getType() == IResource.PROJECT) {
rootFolder = getSourceFolder(resource.getProject());
if (rootFolder == null || !rootFolder.exists()) {
return false;
}
} else {
rootFolder = (IFolder) resource;
}
ComponentList componentList = null;
try {
componentList = getComponentsForFolder(rootFolder, true, true);
} catch (Exception e) {
logger.error("Unable to get components for source folder");
return false;
}
if (Utils.isEmpty(componentList)) {
return false;
}
return true;
}
public boolean isBuildableResource(IResource resource) {
// why isn't the formatter wrapping this???
return (resource.getType() == IResource.FILE
&& !resource.getProjectRelativePath().toPortableString().contains(Constants.PROJECT_SETTINGS_DIR)
&& !resource.getProjectRelativePath().toPortableString().contains(Constants.PROJECT_FILE)
/* not sure how else to do this, because isHidden() doesn't work for "." files and directories */
&& !resource.getProjectRelativePath().toPortableString().contains(Constants.SVN_DIR)
&& !resource.getProjectRelativePath().toPortableString().endsWith(Constants.SCHEMA_FILENAME) && (isManagedResource(resource) && (!isReferencedPackageResource(resource) && !isPackageManifestFile(resource))));
}
// F I L E P R O P E R T I E S
protected int getInt(IProject project, String propertyName, int defaultvalue) {
IEclipsePreferences node = getPreferences(project);
return node != null ? node.getInt(propertyName, defaultvalue) : defaultvalue;
}
protected boolean getBoolean(IProject project, String propertyName, boolean defaultvalue) {
IEclipsePreferences node = getPreferences(project);
return node != null ? node.getBoolean(propertyName, defaultvalue) : defaultvalue;
}
protected void setInt(IProject project, String propertyName, int value) {
IEclipsePreferences node = getPreferences(project);
if (node != null) {
node.putInt(propertyName, value);
try {
node.flush();
} catch (BackingStoreException e) {
// TODO: no error, just a log
Utils.openError(new InvocationTargetException(e), true, "Unable to set int.");
}
}
}
protected void setBoolean(IProject project, String propertyName, boolean value) {
IEclipsePreferences node = getPreferences(project);
if (node != null) {
node.putBoolean(propertyName, value);
try {
node.flush();
} catch (BackingStoreException e) {
// TODO: no error, just a log
Utils.openError(new InvocationTargetException(e), true, "Unable to set boolean.");
}
}
}
protected void setString(IProject project, String propertyName, String value) {
IEclipsePreferences node = getPreferences(project);
if (node != null) {
node.put(propertyName, (value != null ? value : Constants.EMPTY_STRING));
try {
node.flush();
} catch (BackingStoreException e) {
// TODO: no error, just a log
Utils.openError(new InvocationTargetException(e), true, "Unable to set string.");
}
}
}
protected String getString(IProject project, String key, String defaultvalue) {
IEclipsePreferences node = getPreferences(project);
return node != null ? node.get(key, (defaultvalue != null ? defaultvalue : Constants.EMPTY_STRING))
: defaultvalue;
}
protected IEclipsePreferences getPreferences(IProject project) {
ProjectScope projectScope = new ProjectScope(project);
IEclipsePreferences node = projectScope.getNode(ForceIdeCorePlugin.getPluginId());
return node;
}
public ForceProject getForceProject(IProject project) {
ForceProject forceProject = new ForceProject();
IEclipsePreferences preferences = getPreferences(project);
if (preferences == null) {
return forceProject;
}
forceProject.setProject(project);
forceProject.setUserName(preferences.get(Constants.PROP_USERNAME, null));
forceProject.setNamespacePrefix(preferences.get(Constants.PROP_NAMESPACE_PREFIX, null));
// previous versions (<154) stored the full endpoint
String endpoint = preferences.get(Constants.PROP_ENDPOINT, null);
String endpointServer = preferences.get(Constants.PROP_ENDPOINT_SERVER, null);
if (Utils.isNotEmpty(endpoint) && Utils.isEmpty(endpointServer)) {
endpointServer = Utils.getServerNameFromUrl(endpoint);
}
forceProject.setPackageName(preferences.get(Constants.PROP_PACKAGE_NAME, null));
forceProject.setEndpointServer(endpointServer);
forceProject.setEndpointEnvironment(preferences.get(Constants.PROP_ENDPOINT_ENVIRONMENT, null));
forceProject.setEndpointApiVersion(preferences.get(Constants.PROP_ENDPOINT_API_VERSION,
getLastSupportedEndpointVersion()));
forceProject.setMetadataFormatVersion(preferences.get(Constants.PROP_METADATA_FORMAT_VERSION,
getLastSupportedEndpointVersion()));
forceProject.setIdeVersion(preferences.get(Constants.PROP_IDE_VERSION, Constants.EMPTY_STRING));
forceProject.setProjectIdentifier(preferences.get(Constants.PROP_PROJECT_IDENTIFIER, Constants.EMPTY_STRING));
forceProject.setKeepEndpoint(preferences.getBoolean(Constants.PROP_KEEP_ENDPOINT, false));
forceProject.setPreferToolingDeployment(preferences.getBoolean(Constants.PROP_PREFER_TOOLING_DEPLOYMENT, true));
forceProject.setHttpsProtocol(preferences.getBoolean(Constants.PROP_HTTPS_PROTOCOL, true));
forceProject.setReadTimeoutSecs(preferences.getInt(Constants.PROP_READ_TIMEOUT,
Constants.READ_TIMEOUT_IN_SECONDS_DEFAULT));
if (Utils.isEmpty(forceProject.getEndpointServer())) {
logger.warn("Unable to get authorization info - endpoint is null or empty");
return forceProject;
}
URL url = null;
try {
url = new URL(AUTH_URL);
} catch (MalformedURLException e) {
logger.error("Invalid URL ", e);
}
Map<String, String> credentialMap = getAuthorizationService().getCredentialMap(url, project.getName(), AUTH_TYPE);
if (credentialMap != null) {
String password = credentialMap.get(Constants.PROP_PASSWORD);
String token = credentialMap.get(Constants.PROP_TOKEN);
// identification of old storage
if (password.equals("") && token.equals("")) {
Map<String, String> oldCrendtialMap = migrateOldAuthInfoAndGetNewCredentials(url, project, AUTH_TYPE);
if (oldCrendtialMap != null) {
password = oldCrendtialMap.get(Constants.PROP_PASSWORD);
token = oldCrendtialMap.get(Constants.PROP_TOKEN);
}
}
forceProject.setPassword(password);
forceProject.setToken(token);
}
defaultApiVersionCheck(forceProject);
return forceProject;
}
@SuppressWarnings("deprecation")
private Map<String, String> migrateOldAuthInfoAndGetNewCredentials(URL url, IProject project, String authType) {
//get the existing password and security token
@SuppressWarnings("unchecked")
Map<String, String> authorizationInfo = Platform.getAuthorizationInfo(url, project.getName(), authType);
//This adds the authorization information to new migrated project using default mechanism
if (authorizationInfo != null) {
getAuthorizationService().addAuthorizationInfo(url.toString(), project, authType, authorizationInfo);
try {
Platform.flushAuthorizationInfo(url, project.getName(), authType);
} catch (CoreException e) {
logger.error("Unable to delete old preferences", e);
}
return authorizationInfo;
}
return null;
}
private void defaultApiVersionCheck(ForceProject forceProject) {
String endpointApiVesion = forceProject.getEndpointApiVersion();
String lastSupportEndpointVersion = getLastSupportedEndpointVersion();
if (Utils.isNotEmpty(endpointApiVesion) && endpointApiVesion.equals(lastSupportEndpointVersion)) {
return;
}
StringBuilder stringBuilder = new StringBuilder("API version '");
stringBuilder.append(endpointApiVesion)
.append("' is not supported by this Force.com IDE release. Project will be updated to ")
.append("latest supported API version: ").append(lastSupportEndpointVersion);
logger.warn(stringBuilder.toString());
getMetadataFactory().removeMetadataStubExt(forceProject);
getConnectionFactory().removeConnection(forceProject);
getConnectionFactory().getDescribeObjectRegistry().remove(forceProject.getProject().getName());
forceProject.setEndpointApiVersion(lastSupportEndpointVersion);
saveForceProject(forceProject);
if (logger.isInfoEnabled()) {
logger.info("Remove all cached connections and objects related to unsupported API version");
}
}
public void saveForceProject(ForceProject forceProject) {
saveForceProject(forceProject.getProject(), forceProject);
}
public void saveForceProject(IProject project, ForceProject forceProject) {
setString(project, Constants.PROP_USERNAME, forceProject.getUserName());
setString(project, Constants.PROP_NAMESPACE_PREFIX, forceProject.getNamespacePrefix());
setString(project, Constants.PROP_PACKAGE_NAME, forceProject.getPackageName());
setString(project, Constants.PROP_ENDPOINT_SERVER, forceProject.getEndpointServer());
setString(project, Constants.PROP_ENDPOINT_ENVIRONMENT, forceProject.getEndpointEnvironment());
setString(project, Constants.PROP_ENDPOINT_API_VERSION, forceProject.getEndpointApiVersion());
setString(project, Constants.PROP_METADATA_FORMAT_VERSION, forceProject.getMetadataFormatVersion());
setString(project, Constants.PROP_IDE_VERSION, forceProject.getIdeVersion());
setString(project, Constants.PROP_PROJECT_IDENTIFIER, forceProject.getProjectIdentifier());
setBoolean(project, Constants.PROP_KEEP_ENDPOINT, forceProject.isKeepEndpoint());
setBoolean(project, Constants.PROP_HTTPS_PROTOCOL, forceProject.isHttpsProtocol());
setBoolean(project, Constants.PROP_PREFER_TOOLING_DEPLOYMENT, forceProject.getPreferToolingDeployment());
setInt(project, Constants.PROP_READ_TIMEOUT, forceProject.getReadTimeoutSecs());
Map<String, String> credentialMap = new HashMap<>();
credentialMap.put(Constants.PROP_PASSWORD, forceProject.getPassword());
credentialMap.put(Constants.PROP_TOKEN, forceProject.getToken());
getAuthorizationService().addAuthorizationInfo(AUTH_URL, project, AUTH_TYPE, credentialMap);
}
public int getReadTimeout(IProject project) {
return getInt(project, Constants.PROP_READ_TIMEOUT, Constants.READ_TIMEOUT_IN_SECONDS_DEFAULT);
}
public int getReadTimeoutInMilliSeconds(IProject project) {
return (getInt(project, Constants.PROP_READ_TIMEOUT, Constants.READ_TIMEOUT_IN_SECONDS_DEFAULT) * Constants.SECONDS_TO_MILISECONDS);
}
public String getUsername(IProject project) {
return getString(project, Constants.PROP_USERNAME, Constants.EMPTY_STRING);
}
public String getPassword(IProject project) {
return getAuthorizationService().getPassword(project, AUTH_URL, AUTH_TYPE);
}
public boolean hasCredentials(IProject project) {
return Utils.isNotEmpty(getUsername(project)) && Utils.isNotEmpty(getPassword(project));
}
public String getPackageName(IProject project) {
String packageName = getString(project, Constants.PROP_PACKAGE_NAME, Constants.EMPTY_STRING);
if (Utils.isEmpty(packageName)) {
// attempt to infer via package.xml
try {
packageName = getPackageManifestFactory().getPackageNameFromPackageManifest(project);
} catch (FactoryException e) {
logger.warn("Unable to get package name from project's package manifest");
}
}
return Utils.isNotEmpty(packageName) ? packageName : Constants.DEFAULT_PACKAGED_NAME;
}
public String getNamespacePrefix(IProject project) {
return getString(project, Constants.PROP_NAMESPACE_PREFIX, Constants.EMPTY_STRING);
}
public String getSoapEndPoint(IProject project) {
return getString(project, Constants.PROP_ENDPOINT_SERVER, Constants.EMPTY_STRING);
}
public String getIdeVersion(IProject project) {
return getString(project, Constants.PROP_IDE_VERSION, Constants.EMPTY_STRING);
}
public void setIdeVersion(IProject project, String ideVersion) {
setString(project, Constants.PROP_IDE_VERSION, ideVersion);
}
public String getInstalledIdeVersion() {
String version = ForceIdeCorePlugin.getBundleVersion(true);
if (version.split("\\.").length > 2) {
version = version.substring(0, version.lastIndexOf("."));
}
return version;
}
public void updateIdeVersion(IProject project) {
updateIdeVersion(project, getInstalledIdeVersion());
}
public void updateIdeVersion(IProject project, String version) {
if (Utils.isEmpty(version) || version.indexOf(".") < 1) {
version = ForceIdeCorePlugin.getBundleVersion(true);
}
if (version.split("\\.").length > 2) {
version = version.substring(0, version.lastIndexOf("."));
}
setString(project, Constants.PROP_IDE_VERSION, version);
setString(project, Constants.PROP_METADATA_FORMAT_VERSION, version);
setString(project, Constants.PROP_ENDPOINT_API_VERSION, version);
if (logger.isDebugEnabled()) {
logger.debug("Updated project's ide version to " + version);
}
}
public boolean isProjectUpgradeable(IProject project) {
return Utils.isEqual(getIdeVersion(project), getInstalledIdeVersion());
}
// R E S O U R C E H E L P E R S
public IProject getProject(ISelection selection) {
if (selection == null || selection.isEmpty() || selection instanceof IStructuredSelection == false) {
return null;
}
IStructuredSelection ss = (IStructuredSelection) selection;
Object obj = ss.getFirstElement();
if (obj == null || obj instanceof IResource == false) {
return null;
}
IResource resource = (IResource) obj;
return resource.getProject();
}
public void setResourceAttributes(IFile file) {
try {
Component component = getComponentFactory().getComponentFromFile(file, false);
if (component.isInstalled()) {
ResourceAttributes resourceAttributes = new ResourceAttributes();
resourceAttributes.setReadOnly(true);
}
} catch (Exception e) {
logger.error("Unable to set read-only access son file " + file.getName(), e);
}
}
public IFile saveToFile(IFile file, String content, IProgressMonitor monitor) throws CoreException {
if (file == null || file.getType() != IResource.FILE || Utils.isEmpty(content)) {
logger.warn("Unable to save file - file and/or content is null or empty");
return null;
}
// save or update contents
try (final QuietCloseable<ByteArrayInputStream> c = QuietCloseable.make(new ByteArrayInputStream(content.getBytes()))) {
final ByteArrayInputStream stream = c.get();
if (file.exists()) {
file.setContents(stream, true, true, new SubProgressMonitor(monitor, 1));
} else {
file.create(stream, true, new SubProgressMonitor(monitor, 1));
}
}
if (logger.isDebugEnabled()) {
logger.debug("Saved file [" + content.length() + "] to file '"
+ file.getProjectRelativePath().toPortableString() + "'");
}
return file;
}
// H A N D L E R E T U R N E D C O N T E N T & M E S S A G E S
public boolean handleDeployResult(ProjectPackageList projectPackageList, DeployResultExt deployResultHandler,
boolean save, IProgressMonitor monitor) throws CoreException, InterruptedException, IOException,
Exception {
if (deployResultHandler == null || Utils.isEmpty(projectPackageList)) {
throw new IllegalArgumentException("Project package list and/or deploy result cannot be null");
}
monitorCheck(monitor);
monitorSubTask(monitor, "Handling save result...");
List<IResource> resources = projectPackageList.getAllComponentResources(false);
if (deployResultHandler.isSuccess()) {
if (logger.isInfoEnabled()) {
logger.info("Save succeeded!");
}
MarkerUtils.getInstance().clearDirty(resources.toArray(new IResource[resources.size()]));
} else {
logger.warn("Save failed!");
MarkerUtils.getInstance().applyDirty(resources.toArray(new IResource[resources.size()]));
}
// clear all existing save markers on deployed resources
MarkerUtils.getInstance().clearSaveMarkers(projectPackageList.getAllComponentResources(false).toArray(new IResource[0]));
DeployMessageExtractor messageExtractor = new DeployMessageExtractor(deployResultHandler);
handleDeployErrorMessages(projectPackageList, messageExtractor.getDeployFailures(), monitor);
// retrieve result will clear markers for successfully saved files, so it must be
// done before adding the deploy warning messages
handleRetrieveResult(projectPackageList, deployResultHandler.getRetrieveResultHandler(), save, monitor);
handleDeployWarningMessages(projectPackageList, messageExtractor.getDeployWarnings(), monitor);
handleRunTestResult(projectPackageList, deployResultHandler.getRunTestsResultHandler(), monitor);
monitorWork(monitor);
// represents rolled up status of retrieve, test, etc events
return deployResultHandler.isSuccess();
}
protected void handleDeployWarningMessages(ProjectPackageList projectPackageList,
Collection<DeployMessage> deployWarnings, IProgressMonitor monitor) throws InterruptedException {
if (deployWarnings.size() == 0) {
if (logger.isInfoEnabled()) {
logger.info("No deploy warnings found");
}
} else {
monitorSubTask(monitor, "Evaluating warning messages...");
for (DeployMessage warningMessage : deployWarnings) {
monitorCheck(monitor);
Component component = projectPackageList.getComponentByMetadataFilePath(warningMessage.getFileName());
applySaveWarningMarker(component.getFileResource(), warningMessage);
applyWarningsToAssociatedComponents(projectPackageList, component);
}
}
}
public void handleDeployErrorMessages(ProjectPackageList projectPackageList,
Collection<DeployMessage> errorMessages, IProgressMonitor monitor) throws InterruptedException {
if (Utils.isEmpty(projectPackageList)) {
throw new IllegalArgumentException("Project package list and/or message handler cannot be null");
}
if (errorMessages.size() == 0) {
if (logger.isInfoEnabled()) {
logger.info("No deploy errors found");
}
} else {
monitorSubTask(monitor, "Evaluating error messages...");
for (DeployMessage deployMessage : errorMessages) {
monitorCheck(monitor);
// get resource (file, usually) to associate a message/project/failure/warning and displayed in problems
// view
Component component = projectPackageList.getComponentByMetadataFilePath(deployMessage.getFileName());
if (component == null) {
handleMessageForNullComponent(projectPackageList, deployMessage);
} else {
applySaveErrorMarker(component.getFileResource(), deployMessage);
applyWarningsToAssociatedComponents(projectPackageList, component);
}
}
monitorWork(monitor);
}
}
private void handleMessageForNullComponent(ProjectPackageList projectPackageList, DeployMessage deployMessage) {
if (logger.isInfoEnabled()) {
logger.warn("Unable to handle deploy message - could not find component '" + deployMessage.getFileName()
+ "' in list. Will attempt to find w/in project");
}
IFile file = getComponentFileForFilePath(projectPackageList.getProject(), deployMessage.getFileName());
if (file != null) {
if (deployMessage.isSuccess()) {
if (logger.isInfoEnabled()) {
logger.info(deployMessage.getFileName() + " successfully saved");
}
MarkerUtils.getInstance().clearSaveMarkers(file);
} else {
applySaveErrorMarker(file, deployMessage);
}
} else {
// didn't find associated resource
logger.warn("Unable to get file resource for '" + deployMessage.getFileName() + "' for message "
+ deployMessage.getProblem());
}
}
private void applySaveErrorMarker(IResource resource, DeployMessage deployMessage) {
if (deployMessage == null) {
logger.error("Unable to mark resource with deploy message - deploy message is null");
return;
}
MarkerUtils.getInstance().applyDirty(resource);
boolean componentHasSubType = false;
try {
componentHasSubType =
(resource instanceof IFile) ? getComponentFactory().getComponentFromFile((IFile) resource)
.hasSubComponentTypes() : false;
} catch (FactoryException e) {
logger.debug("Unable to determine whether component " + resource.getName() + " has a subtype", e);
}
// Bug #221065: display fullname info only for components that have subtypes:
String problemStr =
(componentHasSubType) ? deployMessage.getFullName() + " : " + deployMessage.getProblem()
: deployMessage.getProblem();
MarkerUtils.getInstance().applySaveErrorMarker(resource, deployMessage.getLineNumber(),
deployMessage.getColumnNumber(), deployMessage.getColumnNumber(), problemStr);
}
private void applySaveWarningMarker(IResource resource, DeployMessage deployMessage) {
Preconditions.checkNotNull(deployMessage);
boolean componentHasSubType = false;
try {
componentHasSubType =
(resource instanceof IFile) ? getComponentFactory().getComponentFromFile((IFile) resource)
.hasSubComponentTypes() : false;
} catch (FactoryException e) {
logger.debug("Unable to determine whether component " + resource.getName() + " has a subtype", e);
}
// Bug #221065: display fullname info only for components that have subtypes:
String problemStr =
(componentHasSubType) ? deployMessage.getFullName() + " : " + deployMessage.getProblem()
: deployMessage.getProblem();
MarkerUtils.getInstance().applySaveWarningMarker(resource, deployMessage.getLineNumber(),
deployMessage.getColumnNumber(), deployMessage.getColumnNumber(), problemStr);
}
public boolean handleRetrieveResult(RetrieveResultExt retrieveResultHandler, boolean save, IProgressMonitor monitor)
throws InterruptedException, CoreException, IOException, Exception {
if (retrieveResultHandler == null) {
throw new IllegalArgumentException("Retrieve result cannot be null");
}
return handleRetrieveResult(retrieveResultHandler.getProjectPackageList(), retrieveResultHandler, save, monitor);
}
public boolean handleRetrieveResult(ProjectPackageList projectPackageList, RetrieveResultExt retrieveResultHandler,
boolean save, IProgressMonitor monitor) throws InterruptedException, CoreException, IOException {
return handleRetrieveResult(projectPackageList, retrieveResultHandler, save, null, monitor);
}
public boolean handleRetrieveResult(final ProjectPackageList projectPackageList,
RetrieveResultExt retrieveResultHandler, boolean save, final String[] toSaveComponentTypes,
IProgressMonitor monitor) throws InterruptedException, CoreException, IOException {
if (projectPackageList == null) {
throw new IllegalArgumentException("Project package list cannot be null");
}
//Can't handler the results if there isn't one.
if (retrieveResultHandler == null) {
return false;
}
// save results to project
if (save) {
if (retrieveResultHandler.getZipFileCount() == 0) {
logger.warn("Nothing to save to project - retrieve result is empty");
return true;
}
if (logger.isDebugEnabled()) {
logger.debug("Saving returned content to project");
}
monitorCheckSubTask(monitor, Messages.getString("Components.Generating"));
// clean then load clean project package list to be saved to project
projectPackageList.removeAllComponents();
projectPackageList.generateComponentsForComponentTypes(retrieveResultHandler.getZipFile(),
retrieveResultHandler.getFileMetadataHandler(), toSaveComponentTypes, monitor);
retrieveResultHandler.setProjectPackageList(projectPackageList);
monitorWork(monitor);
// flag builder to not build and save
flagSkipBuilder(projectPackageList.getProject());
monitorCheckSubTask(monitor, Messages.getString("Components.Saving"));
ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor monitor) throws CoreException {
try {
projectPackageList.saveResources(toSaveComponentTypes, monitor);
} catch (Exception e) {
throw new CoreException(new Status(IStatus.ERROR, Constants.FORCE_PLUGIN_PREFIX, 0,
e.getMessage(), e));
}
}
}, null, IResource.NONE, monitor);
monitorWork(monitor);
} else {
logger.warn("Save intentionally skipped; may be handled later downstream by client");
}
if (retrieveResultHandler.getMessageHandler() != null) {
monitorSubTask(monitor, "Applying retrieve result messages to components...");
handleRetrieveMessages(projectPackageList, retrieveResultHandler.getMessageHandler(), toSaveComponentTypes,
monitor);
monitorWork(monitor);
}
return true;
}
/**
* @param projectPackageList
* @param messageHandler
* @param toSaveComponentTypes
* : This param will be value only specific component folder is selected, ex. refresh from server on
* layout folder
* @param monitor
* @throws InterruptedException
*/
public void handleRetrieveMessages(ProjectPackageList projectPackageList, RetrieveMessageExt messageHandler,
String[] toSaveComponentTypes, IProgressMonitor monitor) throws InterruptedException {
if (messageHandler == null || projectPackageList == null) {
throw new IllegalArgumentException("Project package list and/or message handler cannot be null");
}
monitorCheck(monitor);
// clear problem marker for specific object type package.xml stanza when object types is specified
if (Utils.isNotEmpty(toSaveComponentTypes)) {
IFile packageManifestFile =
getPackageManifestFactory().getPackageManifestFile(projectPackageList.getProject());
MarkerUtils.getInstance().clearRetrieveMarkers(packageManifestFile, toSaveComponentTypes);
}
if (Utils.isEmpty(messageHandler.getMessages())) {
if (logger.isInfoEnabled()) {
logger.info("No retrieve messages returned");
}
return;
}
monitorSubTask(monitor, "Evaluating retrieve messages...");
// loop thru handling each messages and associated resource
RetrieveMessage[] retrieveMessages = messageHandler.getMessages();
for (RetrieveMessage retrieveMessage : retrieveMessages) {
monitorCheck(monitor);
Component component = projectPackageList.getComponentByMetadataFilePath(retrieveMessage.getFileName());
if (component == null) {
logger.warn("Unable to handle retrieve message - could not find component '"
+ retrieveMessage.getFileName() + "' for message '" + retrieveMessage.getProblem() + "'");
continue;
} else if (component.isPackageManifest() && Utils.isNotEmpty(toSaveComponentTypes)) {
// look for package.xml in f/s because refresh from server at component folder level doesn't included in
// projectpackagelist
IFile file =
getComponentFileForFilePath(projectPackageList.getProject(), retrieveMessage.getFileName());
if (file != null) {
MarkerUtils.getInstance().applyRetrieveWarningMarker(file, toSaveComponentTypes,
retrieveMessage.getProblem());
} else {
logger.warn("Unable to get file resource for '" + retrieveMessage.getFileName() + "' for message "
+ retrieveMessage.getProblem());
}
continue;
}
MarkerUtils.getInstance().applyRetrieveWarningMarker(component.getFileResource(),
retrieveMessage.getProblem());
applyWarningsToAssociatedComponents(projectPackageList, component);
}
monitorWork(monitor);
}
// REVIEWME: a deploy message should be sent for aborted source/metadata saves
private static void applyWarningsToAssociatedComponents(ProjectPackageList projectPackageList, Component component) {
if (!component.isMetadataComposite()) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Applying error message to associated metadata component");
}
String compositeComponentFilePath = component.getCompositeMetadataFilePath();
if (Utils.isEmpty(compositeComponentFilePath)) {
logger.warn("Unable to handle composite deploy message for '" + component.getMetadataFilePath()
+ "' - composite filepath is null or empty");
return;
}
Component componentComposite = projectPackageList.getComponentByFilePath(compositeComponentFilePath);
if (componentComposite == null) {
logger.warn("Unable to set error marker - composite component is null");
return;
}
MarkerUtils.getInstance().clearDirty(componentComposite.getFileResource());
MarkerUtils.getInstance().applySaveWarningMarker(componentComposite.getFileResource(),
Messages.getString("Markers.CompositeNotSave.message"));
}
public void handleRunTestResult(ProjectPackageList projectPackageList, RunTestsResultExt runTestResultHandler,
IProgressMonitor monitor) throws InterruptedException {
// handle run tests
handleRunTestMessages(projectPackageList, runTestResultHandler, monitor);
// handle code coverage warnings
handleCodeCoverageWarnings(projectPackageList, runTestResultHandler, monitor);
}
public void handleRunTestMessages(ProjectPackageList projectPackageList, RunTestsResultExt runTestResultHandler,
IProgressMonitor monitor) throws InterruptedException {
if (Utils.isEmpty(projectPackageList)) {
throw new IllegalArgumentException("Project package list cannot be null");
}
monitorCheck(monitor);
monitorSubTask(monitor, "Evaluating run test results...");
// clear all existing run test failure markers on deployed resources
MarkerUtils.getInstance().clearRunTestFailureMarkers(
projectPackageList.getComponentResourcesForComponentTypes(new String[] { Constants.APEX_CLASS,
Constants.APEX_TRIGGER }));
if (runTestResultHandler == null || runTestResultHandler.getNumFailures() == 0) {
if (logger.isInfoEnabled()) {
logger.info("No test failure results found");
}
return;
}
IRunTestFailureExt[] runTestFailures = runTestResultHandler.getFailures();
if (logger.isInfoEnabled()) {
logger.info("Found [" + runTestResultHandler.getNumFailures() + "] run test failures");
}
// loop thru handling each messages and associated resource
for (IRunTestFailureExt runTestFailure : runTestFailures) {
monitorCheck(monitor);
// get resource (file, usually) to associate a message/project/failure/warning and displayed in problems
// view
Component component =
projectPackageList.getComponentByNameType(runTestFailure.getName(), Constants.APEX_CLASS);
if (component == null) {
logger.warn("Unable to handle run test message - could not find component '" + runTestFailure.getName()
+ "' in list. Will attempt to find w/in project");
try {
IFile file =
getComponentFileByNameType(projectPackageList.getProject(), runTestFailure.getName(),
new String[] { Constants.APEX_CLASS });
if (file != null) {
setRunTestFailureMarker(file, runTestFailure);
} else if (projectPackageList.getProject() != null) {
StringBuffer strBuff = new StringBuffer();
strBuff.append("Unable to get file resource for '").append(runTestFailure.getName())
.append("' for code coverage warning '").append(runTestFailure.getMessage())
.append("'. Assigning failure to project.");
logger.warn(strBuff.toString());
MarkerUtils.getInstance().applyRunTestFailureMarker(projectPackageList.getProject(),
runTestFailure.getMessage());
} else {
logger.warn("Unable to get file resource for '" + runTestFailure.getName()
+ "' for run test failure " + runTestFailure.getMessage());
}
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable to get file resource for '" + runTestFailure.getName() + "' for failure "
+ runTestFailure.getMessage() + ": " + logMessage, e);
}
continue;
}
MarkerUtils.getInstance().applyDirty(component.getFileResource());
setRunTestFailureMarker(component.getFileResource(), runTestFailure);
applyWarningsToAssociatedComponents(projectPackageList, component);
try {
component.getFileResource().findMarkers(MarkerUtils.MARKER_RUN_TEST_FAILURE, true,
IResource.DEPTH_INFINITE);
} catch (CoreException e) {
String logMessage = Utils.generateCoreExceptionLog(e);
logger.warn("Unable apply run test marker on component resource: " + logMessage, e);
}
}
monitorWork(monitor);
}
private void setRunTestFailureMarker(IResource resource, IRunTestFailureExt runTestFailure) {
if (runTestFailure == null) {
logger.warn("Unable to set error marker - run test failure is null");
return;
}
ApexCodeLocation apexCodeLocation =
getLocationFromStackLine(runTestFailure.getName(), runTestFailure.getStackTrace());
int line = apexCodeLocation != null ? apexCodeLocation.getLine() : 0;
int charStart = apexCodeLocation != null ? apexCodeLocation.getColumn() : 0;
int charEnd = charStart + 1;
MarkerUtils.getInstance().clearRunTestFailureMarkers(resource);
MarkerUtils.getInstance().applyRunTestFailureMarker(resource, line, charStart, charEnd,
runTestFailure.getMessage());
}
protected ApexCodeLocation getLocationFromStackLine(String name, String stackTrace) {
if (Utils.isEmpty(name) || Utils.isEmpty(stackTrace)) {
logger.warn("Unable to get location from stacktrace - name and/or stacktrace is null");
return null;
}
final Pattern pattern =
Pattern.compile(".*line ([0-9]+?), column ([0-9]+?).*", Pattern.DOTALL | Pattern.MULTILINE
| Pattern.CASE_INSENSITIVE);
final Matcher matcher = pattern.matcher(stackTrace);
matcher.find();
String line = matcher.group(1);
String column = matcher.group(2);
return new ApexCodeLocation(name, line, column);
}
public void handleCodeCoverageWarnings(ProjectPackageList projectPackageList,
RunTestsResultExt runTestResultHandler, IProgressMonitor monitor) throws InterruptedException {
if (Utils.isEmpty(projectPackageList)) {
throw new IllegalArgumentException("Project package list cannot be null");
}
IProject project = projectPackageList.getProject();
//clear all markers on the project
clearAllWarningMarkers(project);
if (runTestResultHandler == null || Utils.isEmpty(runTestResultHandler.getCodeCoverageWarnings())) {
if (logger.isInfoEnabled()) {
logger.info("No code coverage warnings returned");
}
return;
}
monitorCheck(monitor);
monitorSubTask(monitor, "Evaluating code coverage warnings...");
if (logger.isInfoEnabled()) {
logger.info("Found [" + runTestResultHandler.getCodeCoverageWarnings().length + "] code coverage warnings");
}
// loop thru handling each messages and associated resource
for (ICodeCoverageWarningExt codeCoverageWarning : runTestResultHandler.getCodeCoverageWarnings()) {
monitorCheck(monitor);
// if name is not provided, attach warning at the project level
if (Utils.isEmpty(codeCoverageWarning.getName())) {
StringBuffer strBuff = new StringBuffer();
strBuff.append("Unable to get file resource for '").append(codeCoverageWarning.getName())
.append("' for code coverage warning '").append(codeCoverageWarning.getMessage())
.append("'. Applying warning to project.");
logger.warn(strBuff.toString());
applyCodeCoverageWarningMarker(project, codeCoverageWarning.getMessage());
continue;
}
// get resource (file, usually) to associate a message/project/failure/warning and displayed in problems
// view
Component component =
projectPackageList.getApexCodeComponent(codeCoverageWarning.getName(),
codeCoverageWarning.getMessage());
if (component == null) {
logger.warn("Unable to handle code coverage warning - could not find component '"
+ codeCoverageWarning.getName() + "' in list. Will attempt to find w/in project");
try {
IFile file =
getComponentFileByNameType(project, codeCoverageWarning.getName(), new String[] {
Constants.APEX_CLASS, Constants.APEX_TRIGGER });
if (file != null) {
applyCodeCoverageWarningMarker(file, codeCoverageWarning.getMessage());
} else if (project != null) {
StringBuffer strBuff = new StringBuffer("Unable to get file resource for '");
strBuff.append(codeCoverageWarning.getName()).append("' for code coverage warning '")
.append(codeCoverageWarning.getMessage()).append("'. Assigning warning to project.");
logger.warn(strBuff.toString());
applyCodeCoverageWarningMarker(project, codeCoverageWarning.getMessage());
} else {
logger.warn("Unable to get file resource for '" + codeCoverageWarning.getName()
+ "' for code coverage warning " + codeCoverageWarning.getMessage());
}
} catch (Exception e) {
logger.error("Unable to get file resource for '" + codeCoverageWarning.getName()
+ "' for code coverage warning " + codeCoverageWarning.getMessage(), e);
}
continue;
}
applyCodeCoverageWarningMarker(component.getFileResource(), codeCoverageWarning.getMessage());
}
monitorWork(monitor);
}
void clearAllWarningMarkers(IProject project) {
MarkerUtils.getInstance().clearCodeCoverageWarningMarkers(project);
}
private void applyCodeCoverageWarningMarker(IResource resource, String message) {
clearAllWarningMarkers(resource.getProject());
MarkerUtils.getInstance().applyCodeCoverageWarningMarker(resource, message);
}
public boolean isResourceInSync(IResource resource, IProgressMonitor monitor) throws CoreException,
ForceConnectionException, FactoryException, IOException, ServiceException, ForceRemoteException,
InterruptedException {
if (resource == null) {
throw new IllegalArgumentException("IResource cannot be null");
}
if (resource.getType() == IResource.PROJECT) {
return isProjectInSync((IProject) resource, monitor);
} else if (getProjectService().isReferencedPackageResource(resource)) {
logger.warn("Resource '" + resource.getName() + "' is not support by in sync check");
return true;
} else if (resource.getType() == IResource.FOLDER) {
return isFolderInSync((IFolder) resource, monitor);
} else if (resource.getType() == IResource.FILE) {
return isFileInSync((IFile) resource, monitor);
} else {
logger.warn("Resource '" + resource.getName() + "' is not support by in sync check");
return true;
}
}
/**
* Check if project contents have been update remotely.
*
* @param project
* @param monitor
* @return
* @throws CoreException
* @throws ForceConnectionException
* @throws FactoryException
* @throws InterruptedException
* @throws IOException
* @throws ServiceException
*/
public boolean isProjectInSync(IProject project, IProgressMonitor monitor) throws CoreException,
ForceConnectionException, FactoryException, IOException, ServiceException, ForceRemoteException,
InterruptedException {
if (project == null) {
throw new IllegalArgumentException("Project cannot be null");
}
// get local and remote components
ProjectPackageList localProjectPackageList = getProjectService().getProjectContents(project, monitor);
if (localProjectPackageList == null) {
logger.warn("Unable to check in sync for project '" + project.getName()
+ "' - local local project package list is null");
return true;
}
monitorCheck(monitor);
monitor.subTask("Retrieving remote compontents...");
RetrieveResultExt retrieveResultExt =
getPackageRetrieveService().retrieveSelective(localProjectPackageList, true, monitor);
monitorWork(monitor);
if (retrieveResultExt == null) {
logger.warn("Unable to check in sync for project '" + project.getName() + "' - retrieve result is null");
return false;
}
return evaluateLocalAndRemote(localProjectPackageList, retrieveResultExt, monitor);
}
public boolean isFolderInSync(IFolder folder, IProgressMonitor monitor) throws CoreException,
ForceConnectionException, FactoryException, IOException, ServiceException, ForceRemoteException,
InterruptedException {
if (folder == null || folder.getProject() == null) {
throw new IllegalArgumentException("Folder and/or folder's project cannot be null");
}
// get local components
monitorCheck(monitor);
monitor.subTask("Retrieving local project contents...");
ProjectPackageList localProjectPackageList = null;
if (getProjectService().isPackageFolder(folder) || getProjectService().isSourceFolder(folder)) {
localProjectPackageList = getProjectPackageFactory().loadProjectPackageList(folder, monitor);
} else if (getProjectService().isComponentFolder(folder) || getProjectService().isSubComponentFolder(folder)) {
localProjectPackageList = getProjectPackageFactory().loadProjectPackageList(folder, monitor);
} else if (getProjectService().isReferencedPackageResource(folder)) {
logger.warn("Folder '" + folder.getName() + "' is not support by in sync check");
return true;
}
monitor.worked(1);
if (localProjectPackageList == null) {
logger.warn("Unable to check in sync for folder '" + folder.getName()
+ "' - local local project package list is null");
return true;
}
localProjectPackageList.setProject(folder.getProject());
monitorCheck(monitor);
monitor.subTask("Retrieving remote contents...");
RetrieveResultExt retrieveResultExt =
getPackageRetrieveService().retrieveSelective(localProjectPackageList, true, monitor);
if (retrieveResultExt == null) {
logger.warn("Unable to check in sync for folder '" + folder.getName() + "' - retrieve result is null");
return false;
}
monitor.worked(1);
return evaluateLocalAndRemote(localProjectPackageList, retrieveResultExt, monitor);
}
public boolean isFileInSync(IFile file, IProgressMonitor monitor) throws ForceConnectionException,
IOException, ServiceException, ForceRemoteException, InterruptedException {
if (file == null || file.getProject() == null) {
throw new IllegalArgumentException("File and/or file's project cannot be null");
}
// get local components
monitorWorkCheck(monitor, "Retrieving local project contents...");
monitorCheck(monitor);
ProjectPackageList localProjectPackageList = null;
Component component = null;
try {
component = getComponentFactory().getComponentFromFile(file, true);
} catch (FactoryException e) {
logger.warn("Unable to check in sync for file '" + file.getName()
+ "' - unable to create component from file");
return true;
}
if (component.isPackageManifest()) {
logger.warn("Component is a package manifest - skipping as sync file resource");
// REVIEWME: what if the user wants to sync a package manifest?
return true;
}
localProjectPackageList = getProjectPackageListInstance();
localProjectPackageList.setProject(file.getProject());
localProjectPackageList.addComponent(component, true);
monitorWorkCheck(monitor, "Retrieving remote contents...");
RetrieveResultExt retrieveResultExt =
getPackageRetrieveService().retrieveSelective(localProjectPackageList, true, monitor);
if (retrieveResultExt == null) {
logger.warn("Unable to check in sync for file '" + file.getName() + "' - retrieve result is null");
return false;
}
return evaluateLocalAndRemote(localProjectPackageList, retrieveResultExt, monitor);
}
private boolean evaluateLocalAndRemote(ProjectPackageList localProjectPackageList,
RetrieveResultExt retrieveResultExt, IProgressMonitor monitor) throws InterruptedException, IOException {
// get remote package list to evaluate
ProjectPackageList remoteProjectPackageList = retrieveResultExt.getProjectPackageList();
monitorCheckSubTask(monitor, Messages.getString("Components.Generating"));
remoteProjectPackageList.generateComponents(retrieveResultExt.getZipFile(),
retrieveResultExt.getFileMetadataHandler(), monitor);
monitorWork(monitor);
monitorCheck(monitor);
// if either local or remote are empty, assume project is out-of-sync
if ((localProjectPackageList.isEmpty() && remoteProjectPackageList.isNotEmpty())
|| (localProjectPackageList.isNotEmpty() && remoteProjectPackageList.isEmpty())) {
return false;
}
monitorSubTask(monitor, Messages.getString("Components.Evaluating"));
// test either project package
for (ProjectPackage localProjectPackage : localProjectPackageList) {
monitorCheck(monitor);
// local package does not exist remotely, assume project is out-of-sync
if (!remoteProjectPackageList.hasPackage(localProjectPackage.getName())) {
logger.warn("Project package '" + localProjectPackage.getName()
+ "' does not exist remotely - assuming project is out of sync");
return false;
}
// deep equal check on same-named project package
ProjectPackage remoteProjectPackage =
remoteProjectPackageList.getProjectPackage(localProjectPackage.getName());
if (!localProjectPackage.hasChanged(remoteProjectPackage)) {
logger.warn("Project package '" + localProjectPackage.getName()
+ "' does not jive with remote package - assuming project is out of sync");
return false;
}
monitorCheck(monitor);
}
monitorWork(monitor);
// sweet, project contents are up-to-date
return true;
}
private IAuthorizationService getAuthorizationService() {
return authService;
}
}
|
package com.FXplayer;
import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.*;
import javafx.application.Platform;
import javafx.beans.*;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.value.*;
import javafx.fxml.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.media.*;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.paint.Color;
import javafx.stage.*;
import javafx.util.Duration;
public class PlayerController implements Initializable {
private String lastDirectory;
@FXML
private VBox controls;
@FXML
private Button buttonPlay;
@FXML
private Button buttonStop;
@FXML
private Button buttonRepeat;
@FXML
private Slider slider;
@FXML
private Slider volume;
@FXML
private MediaView mediaView;
@FXML
private Label totalTime;
@FXML
private Label currentTime;
@FXML
private HBox player;
@FXML
private VBox root;
private MediaPlayer mediaPlayer;
@Override
public void initialize(URL url, ResourceBundle rb) {
if (Util.controls != null) {
returnToWindowMode();
}
adjustSize();
}
private void adjustSize() {
double height = player.getPrefHeight();
double width = 1067 * height / 600;
mediaView.setFitHeight(height);
mediaView.setFitWidth(width);
}
private void returnToWindowMode() {
Platform.runLater(new Runnable() {
@Override
public void run() {
syncronizeControl();
}
});
mediaPlayer = Util.mediaView.getMediaPlayer();
mediaView.setMediaPlayer(mediaPlayer);
mediaPlayer.play();
mediaView.setDisable(false);
}
private void syncronizeControl() {
buttonPlay.setDisable(false);
if(mediaPlayer.getStatus() == Status.PLAYING)
buttonPlay.setStyle("-fx-graphic: url(\"pause.png\");");
else
mediaPlayer.pause();
buttonRepeat.setDisable(false);
if(Util.repeat)
{
buttonRepeat.setStyle("-fx-background-color: #C3C3C3;");
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.seek(Duration.ZERO);
});
}
buttonStop.setDisable(false);
slider.setDisable(false);
slider.setMax(mediaPlayer.getTotalDuration().toSeconds());
totalTime.setText(Util.getPrettyDurationString(mediaPlayer.getTotalDuration().toSeconds()));
volume.setDisable(false);
volume.setValue(mediaPlayer.getVolume());
root.setOnKeyPressed((KeyEvent event) -> {
if (event.getCode() == KeyCode.SPACE) {
buttonPlay.fire();
}
});
mediaPlayer.currentTimeProperty().addListener((Observable observable) -> {
if (!slider.isValueChanging()) {
slider.setValue(mediaPlayer.getCurrentTime().toSeconds());
currentTime.setText(Util.getPrettyDurationString(mediaPlayer.getCurrentTime().toSeconds()));
}
});
slider.valueProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
if (!slider.isValueChanging()) {
double ct = mediaPlayer.getCurrentTime().toSeconds();
if (Math.abs(ct - newValue.doubleValue()) > MIN_CHANGE) {
mediaPlayer.seek(Duration.seconds(newValue.doubleValue()));
currentTime.setText(Util.getPrettyDurationString(mediaPlayer.getCurrentTime().toSeconds()));
}
}
});
volume.valueProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
mediaPlayer.setVolume(volume.getValue());
});
}
@FXML
public void openFile() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose a Media File");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("All Media Types", "*.mp4", "*.mp3"),
new FileChooser.ExtensionFilter("MP4", "*.mp4"),
new FileChooser.ExtensionFilter("MP3", "*.mp3")
);
if (lastDirectory != null) {
fileChooser.setInitialDirectory(new File(lastDirectory));
}
File file = fileChooser.showOpenDialog(null);
lastDirectory = file.getParent();
if (file != null) {
mediaView.setDisable(false);
initPlayer(file);
}
}
private void initPlayer(File file) {
String uri = file.toURI().toString();
if (uri == null) {
return;
}
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer = null;
}
prepareMedia(uri);
setComponentEvents(uri);
if (Util.repeat) {
Util.repeat = false;
buttonRepeat.setStyle("-fx-background-color: transparent;");
}
}
private void prepareMedia(String uri) {
Media media = new Media(uri);
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
mediaView.setMediaPlayer(mediaPlayer);
mediaPlayer.setVolume(volume.getValue());
volume.setDisable(false);
}
private static final double MIN_CHANGE = 0.5;
private void setComponentEvents(String uri) {
root.setOnKeyPressed((KeyEvent event) -> {
if (event.getCode() == KeyCode.SPACE) {
buttonPlay.fire();
}
});
mediaPlayer.setOnReady(() -> {
String title = new File(uri).getName().replace("%20", " ");
((Stage) mediaView.getScene().getWindow()).setTitle(title);
Util.title = title;
totalTime.setText(Util.getPrettyDurationString(mediaPlayer.getTotalDuration().toSeconds()));
slider.setDisable(false);
slider.setMax(mediaPlayer.getTotalDuration().toSeconds());
buttonStop.setDisable(false);
buttonPlay.setDisable(false);
buttonRepeat.setDisable(false);
buttonPlay.setStyle("-fx-graphic: url(\"pause.png\");");
});
mediaPlayer.currentTimeProperty().addListener((Observable observable) -> {
if (!slider.isValueChanging()) {
slider.setValue(mediaPlayer.getCurrentTime().toSeconds());
currentTime.setText(Util.getPrettyDurationString(mediaPlayer.getCurrentTime().toSeconds()));
}
});
slider.valueProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
//if (!slider.isValueChanging()) {
double ct = mediaPlayer.getCurrentTime().toSeconds();
if (Math.abs(ct - newValue.doubleValue()) > MIN_CHANGE) {
mediaPlayer.seek(Duration.seconds(newValue.doubleValue()));
currentTime.setText(Util.getPrettyDurationString(mediaPlayer.getCurrentTime().toSeconds()));
}
});
volume.valueProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
mediaPlayer.setVolume(volume.getValue());
});
}
@FXML
public void changeMouseIconToHand() {
mediaView.getScene().setCursor(Cursor.HAND);
}
@FXML
public void changeMouseIconToPointer() {
mediaView.getScene().setCursor(Cursor.DEFAULT);
}
@FXML
public void stop() {
mediaPlayer.stop();
buttonPlay.setStyle("-fx-graphic: url(\"play.png\");");
slider.setValue(0);
}
@FXML
public void pause() {
boolean playing = mediaPlayer.getStatus().equals(Status.PLAYING);
if (playing) {
mediaPlayer.pause();
buttonPlay.setStyle("-fx-graphic: url(\"play.png\");");
} else {
mediaPlayer.play();
buttonPlay.setStyle("-fx-graphic: url(\"pause.png\");");
}
}
@FXML
public void changeTime() {
Duration d = new Duration(slider.getValue());
mediaPlayer.seek(d);
currentTime.setText(Util.getPrettyDurationString(slider.getValue()));
}
@FXML
public void repeat() {
if (!Util.repeat) {
buttonRepeat.setStyle("-fx-background-color: #C3C3C3;");
Util.repeat = true;
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.seek(Duration.ZERO);
});
} else {
buttonRepeat.setStyle("-fx-background-color: transparent;");
Util.repeat = false;
mediaPlayer.setOnEndOfMedia(() -> {
});
}
}
@FXML
public void changeViewMode(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
changeToFullScreenMode();
Util.root = root;
Util.controls = controls;
Util.mediaView = mediaView;
}
}
}
private void changeToFullScreenMode() {
StackPane root = new StackPane();
root.setStyle("-fx-background-color: black;");
root.getChildren().add(mediaView);
root.getChildren().add(controls);
final Scene scene = new Scene(root, 960, 540);
mediaView.setPreserveRatio(true);
scene.setFill(Color.BLACK);
Main.s.setScene(scene);
Main.s.setFullScreen(true);
controls.setTranslateY(Main.s.getHeight() - 80);
final DoubleProperty width = mediaView.fitWidthProperty();
final DoubleProperty height = mediaView.fitHeightProperty();
width.bind(Bindings.selectDouble(mediaView.sceneProperty(), "width"));
height.bind(Bindings.selectDouble(mediaView.sceneProperty(), "height"));
Main.s.show();
controls.setOpacity(0);
controls.setOnMouseEntered(e -> {
controls.setOpacity(1);
});
controls.setOnMouseExited(e -> {
controls.setOpacity(0);
});
mediaView.setOnMouseClicked((MouseEvent e) -> {
if (e.getButton().equals(MouseButton.PRIMARY)) {
if (e.getClickCount() == 2) {
try {
Scene s = Main.s.getScene();
Parent r = FXMLLoader.load(getClass().getResource("Player.fxml"));
Scene scene1 = new Scene(r);
double h = Main.s.getHeight();
double w = Main.s.getWidth();
Main.s.setScene(scene1);
Main.s.getIcons().add(new Image("icon.png"));
Main.s.setTitle(Util.title);
Main.s.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
Main.s.setMaximized(true);
Main.s.setHeight(h);
Main.s.setWidth(w);
} catch (IOException ex) {
Logger.getLogger(PlayerController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
}
|
package gngh;
/*
BenjaminWilcox
Nov 17, 2016
GNGH_2
*/
public class DebugInfo
{
private boolean debug = false;
public void toggleDebug()
{
if (debug)
debug = false;
else
debug = true;
}
public boolean getDebug()
{
return debug;
}
public void setDebug(boolean b)
{
debug = b;
}
}
|
package urlshortener.common.repository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import java.util.List;
import urlshortener.common.domain.ShortURL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.HSQL;
import static urlshortener.common.repository.fixture.ShortURLFixture.badUrl;
import static urlshortener.common.repository.fixture.ShortURLFixture.url1;
import static urlshortener.common.repository.fixture.ShortURLFixture.url1modified;
import static urlshortener.common.repository.fixture.ShortURLFixture.url2;
import static urlshortener.common.repository.fixture.ShortURLFixture.url3;
import static urlshortener.common.repository.fixture.ShortURLFixture.urlSafe;
import static urlshortener.common.repository.fixture.ShortURLFixture.urlSponsor;
public class ShortURLRepositoryTests {
private EmbeddedDatabase db;
private ShortURLRepository repository;
private JdbcTemplate jdbc;
@Before
public void setup() {
db = new EmbeddedDatabaseBuilder().setType(HSQL)
.addScript("schema-hsqldb.sql").build();
jdbc = new JdbcTemplate(db);
repository = new ShortURLRepositoryImpl(jdbc);
}
@Test
public void thatSavePersistsTheShortURL() {
assertNotNull(repository.save(url1()));
assertSame(jdbc.queryForObject("select count(*) from SHORTURL",
Integer.class), 1);
}
@Test
public void thatSaveSponsor() {
assertNotNull(repository.save(urlSponsor()));
assertSame(jdbc.queryForObject("select sponsor from SHORTURL",
String.class), urlSponsor().getSponsor());
}
@Test
public void thatSaveSafe() {
assertNotNull(repository.save(urlSafe()));
assertSame(
jdbc.queryForObject("select safe from SHORTURL", Boolean.class),
true);
repository.mark(urlSafe(), false);
assertSame(
jdbc.queryForObject("select safe from SHORTURL", Boolean.class),
false);
repository.mark(urlSafe(), true);
assertSame(
jdbc.queryForObject("select safe from SHORTURL", Boolean.class),
true);
}
@Test
public void thatSaveADuplicateHashIsSafelyIgnored() {
repository.save(url1());
assertNotNull(repository.save(url1()));
assertSame(jdbc.queryForObject("select count(*) from SHORTURL",
Integer.class), 1);
}
@Test
public void thatErrorsInSaveReturnsNull() {
assertNull(repository.save(badUrl()));
assertSame(jdbc.queryForObject("select count(*) from SHORTURL",
Integer.class), 0);
}
@Test
public void thatFindByKeyReturnsAURL() {
repository.save(url1());
repository.save(url2());
ShortURL su = repository.findByKey(url1().getHash());
assertNotNull(su);
assertSame(su.getHash(), url1().getHash());
}
@Test
public void thatFindByKeyReturnsNullWhenFails() {
repository.save(url1());
assertNull(repository.findByKey(url2().getHash()));
}
@Test
public void thatFindByTargetReturnsURLs() {
repository.save(url1());
repository.save(url2());
repository.save(url3());
List<ShortURL> sul = repository.findByTarget(url1().getTarget());
assertEquals(sul.size(), 2);
sul = repository.findByTarget(url3().getTarget());
assertEquals(sul.size(), 1);
sul = repository.findByTarget("dummy");
assertEquals(sul.size(), 0);
}
@Test
public void thatDeleteDelete() {
repository.save(url1());
repository.save(url2());
repository.delete(url1().getHash());
assertEquals(repository.count().intValue(), 1);
repository.delete(url2().getHash());
assertEquals(repository.count().intValue(), 0);
}
@Test
public void thatUpdateUpdate() {
repository.save(url1());
ShortURL su = repository.findByKey(url1().getHash());
assertEquals(su.getTarget(), "http:
repository.update(url1modified());
su = repository.findByKey(url1().getHash());
assertEquals(su.getTarget(), "http:
}
@After
public void shutdown() {
db.shutdown();
}
}
|
package algorithms.sparsevgs;
import grid.GridGraph;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import algorithms.anya.Fraction;
import algorithms.datatypes.SnapshotItem;
/**
* Singleton. Do not make multiple simultaneous copies of this class or use in parallel code.
*/
public final class LineOfSightScanner {
public static ArrayList<List<SnapshotItem>> snapshotList = new ArrayList<>();
private static ArrayList<SnapshotItem> snapshots = new ArrayList<>();
private static int snapshot_sx;
private static int snapshot_sy;
private final GridGraph graph;
private final int sizeX;
private final int sizeY;
private static int[][] rightDownExtents;
private static int[][] leftDownExtents;
private static LOSInterval[] intervalStack;
private static int intervalStackSize;
public static int[] successorsX;
public static int[] successorsY;
public static int nSuccessors;
private static void initialiseExtents(GridGraph graph) {
// Don't reinitialise if graph is the same size as the last time.
if (rightDownExtents != null && graph.sizeY+2 == rightDownExtents.length && graph.sizeX+1 == rightDownExtents[0].length) return;
rightDownExtents = new int[graph.sizeY+2][];
leftDownExtents = new int[graph.sizeY+2][];
for (int y=0;y<graph.sizeY+2;++y) {
rightDownExtents[y] = new int[graph.sizeX+1];
leftDownExtents[y] = new int[graph.sizeX+1];
}
}
private static void initialiseStack() {
if (intervalStack != null) return;
intervalStack = new LOSInterval[11];
intervalStackSize = 0;
}
private static void initialiseSuccessorList() {
if (successorsX != null) return;
successorsX = new int[11];
successorsY = new int[11];
nSuccessors = 0;
}
private static final void clearSuccessors() {
nSuccessors = 0;
}
private static final void stackPush(LOSInterval interval) {
if (intervalStackSize >= intervalStack.length) {
intervalStack = Arrays.copyOf(intervalStack, intervalStack.length*2);
}
intervalStack[intervalStackSize] = interval;
++intervalStackSize;
//addToSnapshot(interval); // Uncomment for debugging.
}
private static final void addToSnapshot(LOSInterval interval) {
snapshots.add(SnapshotItem.generate(new Integer[]{interval.y, interval.xL.n, interval.xL.d, interval.xR.n, interval.xR.d, snapshot_sx, snapshot_sy}, Color.GREEN));
snapshotList.add(new ArrayList<SnapshotItem>(snapshots));
}
public static final void clearSnapshots() {
snapshotList.clear();
snapshots.clear();
}
private static final LOSInterval stackPop() {
LOSInterval temp = intervalStack[intervalStackSize-1];
--intervalStackSize;
intervalStack[intervalStackSize] = null;
return temp;
}
private static final void clearStack() {
intervalStackSize = 0;
}
private static final void addSuccessor(int x, int y) {
if (nSuccessors >= successorsX.length) {
successorsX = Arrays.copyOf(successorsX, successorsX.length*2);
successorsY = Arrays.copyOf(successorsY, successorsY.length*2);
}
successorsX[nSuccessors] = x;
successorsY[nSuccessors] = y;
++nSuccessors;
}
public LineOfSightScanner(GridGraph gridGraph) {
initialiseExtents(gridGraph);
initialiseSuccessorList();
initialiseStack();
graph = gridGraph;
sizeX = graph.sizeX;
sizeY = graph.sizeY;
computeExtents();
}
private void computeExtents() {
// graph.isBlocked(x,y) is the same as graph.bottomLeftOfBlockedTile(x,y)
LineOfSightScanner.initialiseExtents(graph);
for (int y=0;y<sizeY+2;++y) {
boolean lastIsBlocked = true;
int lastX = -1;
for (int x=0;x<=sizeX;++x) {
leftDownExtents[y][x] = lastX;
if (graph.isBlocked(x, y-1) != lastIsBlocked) {
lastX = x;
lastIsBlocked = !lastIsBlocked;
}
}
lastIsBlocked = true;
lastX = sizeX+1;
for (int x=sizeX;x>=0;--x) {
rightDownExtents[y][x] = lastX;
if (graph.isBlocked(x-1, y-1) != lastIsBlocked) {
lastX = x;
lastIsBlocked = !lastIsBlocked;
}
}
}
}
/**
* Stores results in successorsX, successorsY and nSuccessors.
*/
public final void computeAllVisibleTautSuccessors(int sx, int sy) {
snapshot_sx=sx;snapshot_sy=sy;
clearSuccessors();
clearStack();
generateStartingStates(sx, sy);
exploreStates(sx, sy);
}
/**
* Stores results in successorsX, successorsY and nSuccessors.
*/
public final void computeAllVisibleTwoWayTautSuccessors(int sx, int sy) {
snapshot_sx=sx;snapshot_sy=sy;
clearSuccessors();
clearStack();
generateTwoWayTautStartingStates(sx, sy);
exploreStates(sx, sy);
}
/**
* Stores results in successorsX, successorsY and nSuccessors.
* We are moving in direction dx, dy
*/
public final void computeAllVisibleIncrementalTautSuccessors(int sx, int sy, int dx, int dy) {
snapshot_sx=sx;snapshot_sy=sy;
clearSuccessors();
clearStack();
generateIncrementalTautStartingStates(sx, sy, dx, dy);
exploreStates(sx, sy);
}
private final void generateIncrementalTautStartingStates(int sx, int sy, int dx, int dy) {
boolean rightwardsSearch = false;
boolean leftwardsSearch = false;
if (dx > 0) {
// Moving rightwards
if (dy > 0) {
boolean brOfBlocked = graph.bottomRightOfBlockedTile(sx, sy);
boolean tlOfBlocked = graph.topLeftOfBlockedTile(sx, sy);
int rightBound = rightUpExtent(sx,sy);
Fraction leftExtent;
Fraction rightExtent;
if (brOfBlocked && tlOfBlocked) {
leftExtent = new Fraction(sx);
rightExtent = new Fraction(rightBound);
rightwardsSearch = true;
} else if (brOfBlocked) {
leftExtent = new Fraction(sx);
rightExtent = new Fraction(sx*dy + dx, dy);
if (!rightExtent.isLessThanOrEqual(rightBound)) { // rightBound < rightExtent
rightExtent = new Fraction(rightBound);
}
} else { // tlOfBlocked
leftExtent = new Fraction(sx*dy + dx, dy);
rightExtent = new Fraction(rightBound);
rightwardsSearch = true;
}
if (leftExtent.isLessThanOrEqual(rightExtent)) {
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
} else if (dy < 0) {
boolean trOfBlocked = graph.topRightOfBlockedTile(sx, sy);
boolean blOfBlocked = graph.bottomLeftOfBlockedTile(sx, sy);
int rightBound = rightDownExtent(sx,sy);
Fraction leftExtent;
Fraction rightExtent;
if (trOfBlocked && blOfBlocked) {
leftExtent = new Fraction(sx);
rightExtent = new Fraction(rightBound);
rightwardsSearch = true;
} else if (trOfBlocked) {
leftExtent = new Fraction(sx);
rightExtent = new Fraction(sx*-dy + dx, -dy);
if (!rightExtent.isLessThanOrEqual(rightBound)) { // rightBound < rightExtent
rightExtent = new Fraction(rightBound);
}
} else { // blOfBlocked
leftExtent = new Fraction(sx*-dy + dx, -dy);
rightExtent = new Fraction(rightBound);
rightwardsSearch = true;
}
if (leftExtent.isLessThanOrEqual(rightExtent)) {
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
} else { // dy == 0
if (graph.bottomRightOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightUpExtent(sx,sy));
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
} else if (graph.topRightOfBlockedTile(sx, sy)) { // topRightOfBlockedTile
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightDownExtent(sx,sy));
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
rightwardsSearch = true;
}
} else if (dx < 0) {
// Moving leftwards
if (dy > 0) {
boolean blOfBlocked = graph.bottomLeftOfBlockedTile(sx, sy);
boolean trOfBlocked = graph.topRightOfBlockedTile(sx, sy);
int leftBound = leftUpExtent(sx,sy);
Fraction leftExtent;
Fraction rightExtent;
if (blOfBlocked && trOfBlocked) {
leftExtent = new Fraction(leftBound);
rightExtent = new Fraction(sx);
leftwardsSearch = true;
} else if (blOfBlocked) {
leftExtent = new Fraction(sx*dy + dx, dy);
rightExtent = new Fraction(sx);
if (leftExtent.isLessThan(leftBound)) { // leftExtent < leftBound
leftExtent = new Fraction(leftBound);
}
} else { // trOfBlocked
leftExtent = new Fraction(leftBound);
rightExtent = new Fraction(sx*dy + dx, dy);
leftwardsSearch = true;
}
if (leftExtent.isLessThanOrEqual(rightExtent)) {
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
} else if (dy < 0) {
boolean tlOfBlocked = graph.topLeftOfBlockedTile(sx, sy);
boolean brOfBlocked = graph.bottomRightOfBlockedTile(sx, sy);
int leftBound = leftDownExtent(sx,sy);
Fraction leftExtent;
Fraction rightExtent;
if (tlOfBlocked && brOfBlocked) {
leftExtent = new Fraction(leftBound);
rightExtent = new Fraction(sx);
leftwardsSearch = true;
} else if (tlOfBlocked) {
leftExtent = new Fraction(sx*-dy + dx, -dy);
rightExtent = new Fraction(sx);
if (leftExtent.isLessThan(leftBound)) { // leftExtent < leftBound
leftExtent = new Fraction(leftBound);
}
} else { // brOfBlocked
leftExtent = new Fraction(leftBound);
rightExtent = new Fraction(sx*-dy + dx, -dy);
leftwardsSearch = true;
}
if (leftExtent.isLessThanOrEqual(rightExtent)) {
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
} else { // dy == 0
if (graph.bottomLeftOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(leftUpExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
} else if (graph.topLeftOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(leftDownExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
leftwardsSearch = true;
}
} else { // dx == 0
// Direct upwards or direct downwards.
if (dy > 0) {
// Direct upwards
if (graph.topLeftOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightUpExtent(sx,sy));
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
rightwardsSearch = true;
} else if (graph.topRightOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(leftUpExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
leftwardsSearch = true;
} else {
Fraction x = new Fraction(sx);
stackPush(new LOSInterval(sy+1, x, x, LOSInterval.BOTH_INCLUSIVE));
}
} else { // dy < 0
// Direct downwards
if (graph.bottomLeftOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightDownExtent(sx,sy));
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
rightwardsSearch = true;
} else if (graph.bottomRightOfBlockedTile(sx, sy)) {
Fraction leftExtent = new Fraction(leftDownExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
leftwardsSearch = true;
} else {
Fraction x = new Fraction(sx);
stackPush(new LOSInterval(sy-1, x, x, LOSInterval.BOTH_INCLUSIVE));
}
}
}
// Direct Search Left
if (leftwardsSearch) {
// Direct Search Left
// Assumption: Not blocked towards left.
addSuccessor(leftAnyExtent(sx, sy),sy);
}
if (rightwardsSearch) {
// Direct Search Right
// Assumption: Not blocked towards right.
addSuccessor(rightAnyExtent(sx, sy),sy);
}
}
private final void generateTwoWayTautStartingStates(int sx, int sy) {
boolean bottomLeftOfBlocked = graph.bottomLeftOfBlockedTile(sx, sy);
boolean bottomRightOfBlocked = graph.bottomRightOfBlockedTile(sx, sy);
boolean topLeftOfBlocked = graph.topLeftOfBlockedTile(sx, sy);
boolean topRightOfBlocked = graph.topRightOfBlockedTile(sx, sy);
// Generate up-left direction
if (topRightOfBlocked || bottomLeftOfBlocked) {
Fraction leftExtent = new Fraction(leftUpExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Generate up-right direction
if (bottomRightOfBlocked || topLeftOfBlocked) {
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightUpExtent(sx,sy));
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Generate down-left direction
if (bottomRightOfBlocked || topLeftOfBlocked) {
Fraction leftExtent = new Fraction(leftDownExtent(sx,sy));
Fraction rightExtent = new Fraction(sx);
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Generate down-right direction
if (topRightOfBlocked || bottomLeftOfBlocked) {
Fraction leftExtent = new Fraction(sx);
Fraction rightExtent = new Fraction(rightDownExtent(sx,sy));
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Search leftwards
if (!topRightOfBlocked || !bottomRightOfBlocked) {
int x = leftAnyExtent(sx, sy);
int y = sy;
if (!(graph.topRightOfBlockedTile(x, y) && graph.bottomRightOfBlockedTile(x, y))) {
addSuccessor(x,y);
}
}
// Search rightwards
if (!topLeftOfBlocked || !bottomLeftOfBlocked) {
int x = rightAnyExtent(sx, sy);
int y = sy;
if (!(graph.topLeftOfBlockedTile(x, y) && graph.bottomLeftOfBlockedTile(x, y))) {
addSuccessor(x,y);
}
}
}
private final void generateStartingStates(int sx, int sy) {
boolean bottomLeftOfBlocked = graph.bottomLeftOfBlockedTile(sx, sy);
boolean bottomRightOfBlocked = graph.bottomRightOfBlockedTile(sx, sy);
boolean topLeftOfBlocked = graph.topLeftOfBlockedTile(sx, sy);
boolean topRightOfBlocked = graph.topRightOfBlockedTile(sx, sy);
// Generate up
if (!bottomLeftOfBlocked || !bottomRightOfBlocked) {
Fraction leftExtent, rightExtent;
if (bottomLeftOfBlocked) {
// Explore up-left
leftExtent = new Fraction(leftUpExtent(sx, sy));
rightExtent = new Fraction(sx);
} else if (bottomRightOfBlocked) {
// Explore up-right
leftExtent = new Fraction(sx);
rightExtent = new Fraction(rightUpExtent(sx, sy));
} else {
// Explore up-left-right
leftExtent = new Fraction(leftUpExtent(sx, sy));
rightExtent = new Fraction(rightUpExtent(sx, sy));
}
this.generateUpwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Generate down
if (!topLeftOfBlocked || !topRightOfBlocked) {
Fraction leftExtent, rightExtent;
if (topLeftOfBlocked) {
// Explore down-left
leftExtent = new Fraction(leftDownExtent(sx, sy));
rightExtent = new Fraction(sx);
} else if (topRightOfBlocked) {
// Explore down-right
leftExtent = new Fraction(sx);
rightExtent = new Fraction(rightDownExtent(sx, sy));
} else {
// Explore down-left-right
leftExtent = new Fraction(leftDownExtent(sx, sy));
rightExtent = new Fraction(rightDownExtent(sx, sy));
}
this.generateDownwards(leftExtent, rightExtent, sx, sy, sy, true, true);
}
// Search leftwards
if (!topRightOfBlocked || !bottomRightOfBlocked) {
int x = leftAnyExtent(sx, sy);
int y = sy;
if (!(graph.topRightOfBlockedTile(x, y) && graph.bottomRightOfBlockedTile(x, y))) {
addSuccessor(x,y);
}
}
// Search rightwards
if (!topLeftOfBlocked || !bottomLeftOfBlocked) {
int x = rightAnyExtent(sx, sy);
int y = sy;
if (!(graph.topLeftOfBlockedTile(x, y) && graph.bottomLeftOfBlockedTile(x, y))) {
addSuccessor(x,y);
}
}
}
private final void exploreStates(int sx, int sy) {
while (intervalStackSize > 0) {
LOSInterval currState = stackPop();
boolean leftInclusive = (currState.inclusive & LOSInterval.LEFT_INCLUSIVE) != 0;
boolean rightInclusive = (currState.inclusive & LOSInterval.RIGHT_INCLUSIVE) != 0;
//System.out.println("POP " + currState);
boolean zeroLengthInterval = currState.xR.isEqualTo(currState.xL);
if (currState.y > sy) {
// Upwards
// Insert endpoints if integer.
if (leftInclusive && currState.xL.isWholeNumber()) {
/* The two cases _
* _ |X|
* |X|'. ,'
* '. ,'
* B B
*/
int x = currState.xL.n;
int y = currState.y;
boolean topRightOfBlockedTile = graph.topRightOfBlockedTile(x, y);
boolean bottomRightOfBlockedTile = graph.bottomRightOfBlockedTile(x, y);
if (x <= sx && topRightOfBlockedTile && !bottomRightOfBlockedTile) {
addSuccessor(x, y);
leftInclusive = false;
}
else if (sx <= x && bottomRightOfBlockedTile && !topRightOfBlockedTile) {
addSuccessor(x, y);
leftInclusive = false;
}
}
if (rightInclusive && currState.xR.isWholeNumber()) {
/* _ The two cases
* |X| _
* '. ,'|X|
* '. ,'
* B B
*/
int x = currState.xR.n;
int y = currState.y;
boolean bottomLeftOfBlockedTile = graph.bottomLeftOfBlockedTile(x, y);
boolean topLeftOfBlockedTile = graph.topLeftOfBlockedTile(x, y);
if (x <= sx && bottomLeftOfBlockedTile && !topLeftOfBlockedTile) {
if (leftInclusive || !zeroLengthInterval) {
addSuccessor(x, y);
rightInclusive = false;
}
}
else if (sx <= x && topLeftOfBlockedTile && !bottomLeftOfBlockedTile) {
if (leftInclusive || !zeroLengthInterval) {
addSuccessor(x, y);
rightInclusive = false;
}
}
}
// Generate Upwards
// (Px-Bx)*(Py-By+1)/(Py-By) + Bx
int dy = currState.y - sy;
Fraction leftProjection = currState.xL.minus(sx).multiplyDivide(dy+1, dy).plus(sx);
int leftBound = leftUpExtent(currState.xL.ceil(), currState.y);
if (currState.xL.isWholeNumber() && graph.bottomRightOfBlockedTile(currState.xL.n, currState.y)) leftBound = currState.xL.n;
if (leftProjection.isLessThan(leftBound)) { // leftProjection < leftBound
leftProjection = new Fraction(leftBound);
leftInclusive = true;
}
// (Px-Bx)*(Py-By+1)/(Py-By) + Bx
Fraction rightProjection = currState.xR.minus(sx).multiplyDivide(dy+1, dy).plus(sx);
int rightBound = rightUpExtent(currState.xR.floor(), currState.y);
if (currState.xR.isWholeNumber() && graph.bottomLeftOfBlockedTile(currState.xR.n, currState.y)) rightBound = currState.xR.n;
if (!rightProjection.isLessThanOrEqual(rightBound)) { // rightBound < rightProjection
rightProjection = new Fraction(rightBound);
rightInclusive = true;
}
// Call Generate
if (leftInclusive && rightInclusive) {
if (leftProjection.isLessThanOrEqual(rightProjection)) {
generateUpwards(leftProjection, rightProjection, sx, sy, currState.y, true, true);
}
}
else if (leftProjection.isLessThan(rightProjection)) {
generateUpwards(leftProjection, rightProjection, sx, sy, currState.y, leftInclusive, rightInclusive);
}
}
else {
// Upwards
// Insert endpoints if integer.
if (leftInclusive && currState.xL.isWholeNumber()) {
/* The two cases
* B B
* _ ,' '.
* |X|.' '.
* |X|
*/
int x = currState.xL.n;
int y = currState.y;
boolean bottomRightOfBlockedTile = graph.bottomRightOfBlockedTile(x, y);
boolean topRightOfBlockedTile = graph.topRightOfBlockedTile(x, y);
if (x <= sx && bottomRightOfBlockedTile && !topRightOfBlockedTile) {
addSuccessor(x, y);
leftInclusive = false;
}
else if (sx <= x && topRightOfBlockedTile && !bottomRightOfBlockedTile) {
addSuccessor(x, y);
leftInclusive = false;
}
}
if (rightInclusive && currState.xR.isWholeNumber()) {
/* The two cases
* B B
* .' '. _
* .' '.|X|
* |X|
*/
int x = currState.xR.n;
int y = currState.y;
boolean topLeftOfBlockedTile = graph.topLeftOfBlockedTile(x, y);
boolean bottomLeftOfBlockedTile = graph.bottomLeftOfBlockedTile(x, y);
if (x <= sx && topLeftOfBlockedTile && !bottomLeftOfBlockedTile) {
if (leftInclusive || !zeroLengthInterval) {
addSuccessor(x, y);
rightInclusive = false;
}
}
else if (sx <= x && bottomLeftOfBlockedTile && !topLeftOfBlockedTile) {
if (leftInclusive || !zeroLengthInterval) {
addSuccessor(x, y);
rightInclusive = false;
}
}
}
// Generate downwards
// (Px-Bx)*(Py-By+1)/(Py-By) + Bx
int dy = sy - currState.y;
Fraction leftProjection = currState.xL.minus(sx).multiplyDivide(dy+1, dy).plus(sx);
int leftBound = leftDownExtent(currState.xL.ceil(), currState.y);
if (currState.xL.isWholeNumber() && graph.topRightOfBlockedTile(currState.xL.n, currState.y)) leftBound = currState.xL.n;
if (leftProjection.isLessThan(leftBound)) { // leftProjection < leftBound
leftProjection = new Fraction(leftBound);
leftInclusive = true;
}
// (Px-Bx)*(Py-By+1)/(Py-By) + Bx
Fraction rightProjection = currState.xR.minus(sx).multiplyDivide(dy+1, dy).plus(sx);
int rightBound = rightDownExtent(currState.xR.floor(), currState.y);
if (currState.xR.isWholeNumber() && graph.topLeftOfBlockedTile(currState.xR.n, currState.y)) rightBound = currState.xR.n;
if (!rightProjection.isLessThanOrEqual(rightBound)) { // rightBound < rightProjection
rightProjection = new Fraction(rightBound);
rightInclusive = true;
}
// Call Generate
if (leftInclusive && rightInclusive) {
if (leftProjection.isLessThanOrEqual(rightProjection)) {
generateDownwards(leftProjection, rightProjection, sx, sy, currState.y, true, true);
}
}
else if (leftProjection.isLessThan(rightProjection)) {
generateDownwards(leftProjection, rightProjection, sx, sy, currState.y, leftInclusive, rightInclusive);
}
}
}
}
private final int leftUpExtent(int xL, int y) {
return xL > sizeX ? sizeX : leftDownExtents[y+1][xL];
}
private final int leftDownExtent(int xL, int y) {
return xL > sizeX ? sizeX : leftDownExtents[y][xL];
}
private final int leftAnyExtent(int xL, int y) {
return Math.max(leftDownExtents[y][xL], leftDownExtents[y+1][xL]);
}
private final int rightUpExtent(int xR, int y) {
return xR < 0 ? 0 : rightDownExtents[y+1][xR];
}
private final int rightDownExtent(int xR, int y) {
return xR < 0 ? 0 : rightDownExtents[y][xR];
}
private final int rightAnyExtent(int xR, int y) {
return Math.min(rightDownExtents[y][xR], rightDownExtents[y+1][xR]);
}
private final void generateUpwards(Fraction leftBound, Fraction rightBound, int sx, int sy, int currY, boolean leftInclusive, boolean rightInclusive) {
generateAndSplitIntervals(
currY + 2, currY + 1,
sx, sy,
leftBound, rightBound,
leftInclusive, rightInclusive);
}
private final void generateDownwards(Fraction leftBound, Fraction rightBound, int sx, int sy, int currY, boolean leftInclusive, boolean rightInclusive) {
generateAndSplitIntervals(
currY - 1, currY - 1,
sx, sy,
leftBound, rightBound,
leftInclusive, rightInclusive);
}
/**
* Called by generateUpwards / Downwards.
* Note: Unlike Anya, 0-length intervals are possible.
*/
private final void generateAndSplitIntervals(int checkY, int newY, int sx, int sy, Fraction leftBound, Fraction rightBound, boolean leftInclusive, boolean rightInclusive) {
Fraction left = leftBound;
int leftFloor = left.floor();
// Up: !bottomRightOfBlockedTile && bottomLeftOfBlockedTile
if (leftInclusive && left.isWholeNumber() && !graph.isBlocked(leftFloor-1, checkY-1) && graph.isBlocked(leftFloor, checkY-1)) {
stackPush(new LOSInterval(newY, left, left, LOSInterval.BOTH_INCLUSIVE));
}
// Divide up the intervals.
while(true) {
int right = rightDownExtents[checkY][leftFloor]; // it's actually rightDownExtents for exploreDownwards. (thus we use checkY = currY - 2)
if (rightBound.isLessThanOrEqual(right)) break; // right < rightBound
// Only push unblocked ( bottomRightOfBlockedTile )
if (!graph.isBlocked(right-1, checkY-1)) {
stackPush(new LOSInterval(newY, left, new Fraction(right), leftInclusive ? LOSInterval.BOTH_INCLUSIVE : LOSInterval.RIGHT_INCLUSIVE));
}
leftFloor = right;
left = new Fraction(leftFloor);
leftInclusive = true;
}
// The last interval will always be here.
// if !bottomLeftOfBlockedTile(leftFloor, checkY)
if (!graph.isBlocked(leftFloor, checkY-1)) {
int inclusive = (leftInclusive ? LOSInterval.LEFT_INCLUSIVE : 0) | (rightInclusive ? LOSInterval.RIGHT_INCLUSIVE : 0);
stackPush(new LOSInterval(newY, left, rightBound, inclusive));
} else {
// The possibility of there being one degenerate interval at the end. ( !bottomLeftOfBlockedTile(xR, checkY) )
if (rightInclusive && rightBound.isWholeNumber() && !graph.isBlocked(rightBound.n, checkY-1)) {
stackPush(new LOSInterval(newY, rightBound, rightBound, LOSInterval.BOTH_INCLUSIVE));
}
}
}
public static void clearMemory() {
snapshotList.clear();
snapshots.clear();
rightDownExtents = null;
leftDownExtents = null;
intervalStack = null;
successorsX = null;
successorsY = null;
System.gc();
}
}
final class LOSInterval {
public static final int BOTH_EXCLUSIVE = 0x0;
public static final int LEFT_INCLUSIVE = 0x1;
public static final int RIGHT_INCLUSIVE = 0x2;
public static final int BOTH_INCLUSIVE = 0x3; // LEFT_INCLUSIVE | RIGHT_INCLUSIVE
final int y;
final Fraction xL;
final Fraction xR;
final int inclusive;
public LOSInterval(int y, Fraction xL, Fraction xR, int inclusive) {
this.y = y;
this.xL = xL;
this.xR = xR;
this.inclusive = inclusive;
}
@Override
public final String toString() {
return ((inclusive & LEFT_INCLUSIVE) == 0 ? "(" : "[") + xL + ", " + xR + ((inclusive & RIGHT_INCLUSIVE) == 0 ? ")" : "]") + "|" + y;
}
}
|
package com.plugin.gcm;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.util.Random;
import com.google.android.gcm.GCMBaseIntentService;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try {
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
} catch( JSONException e) {
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
// if we are in the foreground, just surface the payload, else post it to the statusbar
if (PushPlugin.isInForeground()) {
Log.d(TAG, "onMessage - pushing extras because we're in the foreground");
extras.putBoolean("foreground", true);
PushPlugin.sendExtras(extras);
} else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
Log.d(TAG, "onMessage - create notification because we're in the background");
createNotification(context, extras);
//PushPlugin.sendExtras(extras); uncomment for the ecb to fire even if the app is not in foreground
}
}
}
}
public void createNotification(Context context, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
int requestCode = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int defaults = Notification.DEFAULT_ALL;
if (extras.getString("defaults") != null) {
try {
defaults = Integer.parseInt(extras.getString("defaults"));
} catch (NumberFormatException e) {}
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(context.getResources().getIdentifier("secondary_icon", "drawable", context.getPackageName()))
setNotificationIconColor(extras.getString("color"), mBuilder);
} else {
mBuilder.setSmallIcon(context.getApplicationInfo().icon);
}
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
int notId = 0;
try {
notId = Integer.parseInt(extras.getString("notId"));
}
catch(NumberFormatException e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage());
}
catch(Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
mNotificationManager.notify((String) appName, notId, mBuilder.build());
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
private void setNotificationIconColor(String color, NotificationCompat.Builder mBuilder) {
int iconColor = 0;
if (color != null) {
try {
iconColor = Color.parseColor(color);
} catch (IllegalArgumentException e) {
Log.e(TAG, "couldn't parse color from android options");
}
}
if (iconColor != 0) {
// Not setting color because of error in PGB:
/*
[javac] Compiling 43 source files to /project/bin/classes
[javac] /project/src/com/plugin/gcm/GCMIntentService.java:168: error: cannot find symbol
[javac] mBuilder.setColor(iconColor);
*/
//mBuilder.setColor(iconColor);
}
}
}
|
package org.alohalytics;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import java.util.HashMap;
public class SystemInfo {
private static final String TAG = "Alohalytics.SystemInfo";
private static void handleException(Exception ex) {
if (Statistics.debugMode()) {
if (ex.getMessage() != null) {
Log.w(TAG, ex.getMessage());
}
ex.printStackTrace();
}
}
public static void getDeviceInfoAsync(final Context context) {
// Collect all information on a separate thread, because:
// - Google Advertising ID should be requested in a separate thread.
// - Do not block UI thread while querying many properties.
new Thread(new Runnable() {
@Override
public void run() {
collectIds(context);
collectDeviceDetails(context);
}
}).start();
}
// Used for convenient null-checks.
private static class KeyValueWrapper {
public HashMap<String, String> mPairs = new HashMap<>();
public void put(String key, String value) {
if (key != null && value != null) {
mPairs.put(key, value);
}
}
public void put(String key, float value) {
if (key != null) {
mPairs.put(key, String.valueOf(value));
}
}
public void put(String key, boolean value) {
if (key != null) {
mPairs.put(key, String.valueOf(value));
}
}
public void put(String key, int value) {
if (key != null) {
mPairs.put(key, String.valueOf(value));
}
}
}
private static void collectIds(final Context context) {
final KeyValueWrapper ids = new KeyValueWrapper();
// Retrieve GoogleAdvertisingId.
try {
ids.put("google_advertising_id", AdvertisingIdClient.getAdvertisingIdInfo(context.getApplicationContext()).getId());
} catch (Exception ex) {
handleException(ex);
}
try {
final String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
if (!android_id.equals("9774d56d682e549c")) {
ids.put("android_id", android_id);
}
} catch (Exception ex) {
handleException(ex);
}
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
ids.put("device_id", tm.getDeviceId());
ids.put("sim_serial_number", tm.getSimSerialNumber());
} catch (Exception ex) {
handleException(ex);
}
Statistics.logEvent("$androidIds", ids.mPairs);
// Force statistics uploading as if user immediately uninstalls the app we won't even know about installation.
Statistics.forceUpload();
}
private static void collectDeviceDetails(Context context) {
final KeyValueWrapper kvs = new KeyValueWrapper();
final WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
final DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
kvs.put("display_density", metrics.density);
kvs.put("display_density_dpi", metrics.densityDpi);
kvs.put("display_scaled_density", metrics.scaledDensity);
kvs.put("display_width_pixels", metrics.widthPixels);
kvs.put("display_height_pixels", metrics.heightPixels);
kvs.put("display_xdpi", metrics.xdpi);
kvs.put("display_ydpi", metrics.ydpi);
}
final Configuration config = context.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
kvs.put("dpi", config.densityDpi); // int value
}
kvs.put("font_scale", config.fontScale);
kvs.put("locale_country", config.locale.getCountry());
kvs.put("locale_language", config.locale.getLanguage());
kvs.put("locale_variant", config.locale.getVariant());
kvs.put("mcc", config.mcc);
kvs.put("mnc", config.mnc == Configuration.MNC_ZERO ? 0 : config.mnc);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
kvs.put("screen_width_dp", config.screenWidthDp);
kvs.put("screen_height_dp", config.screenHeightDp);
}
final ContentResolver cr = context.getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
kvs.put(Settings.Global.AIRPLANE_MODE_ON, Settings.Global.getString(cr, Settings.Global.AIRPLANE_MODE_ON)); // 1 or 0
kvs.put(Settings.Global.ALWAYS_FINISH_ACTIVITIES, Settings.Global.getString(cr, Settings.Global.ALWAYS_FINISH_ACTIVITIES)); // 1 or 0
kvs.put(Settings.Global.AUTO_TIME, Settings.Global.getString(cr, Settings.Global.AUTO_TIME)); // 1 or 0
kvs.put(Settings.Global.AUTO_TIME_ZONE, Settings.Global.getString(cr, Settings.Global.AUTO_TIME_ZONE)); // 1 or 0
kvs.put(Settings.Global.BLUETOOTH_ON, Settings.Global.getString(cr, Settings.Global.BLUETOOTH_ON)); // 1 or 0
kvs.put(Settings.Global.DATA_ROAMING, Settings.Global.getString(cr, Settings.Global.DATA_ROAMING)); // 1 or 0
kvs.put(Settings.Global.HTTP_PROXY, Settings.Global.getString(cr, Settings.Global.HTTP_PROXY)); // host:port
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
kvs.put(Settings.System.AUTO_TIME_ZONE, Settings.System.getString(cr, Settings.System.AUTO_TIME_ZONE));
} else {
kvs.put(Settings.System.AIRPLANE_MODE_ON, Settings.System.getString(cr, Settings.System.AIRPLANE_MODE_ON));
kvs.put(Settings.System.ALWAYS_FINISH_ACTIVITIES, Settings.System.getString(cr, Settings.System.ALWAYS_FINISH_ACTIVITIES));
kvs.put(Settings.System.AUTO_TIME, Settings.System.getString(cr, Settings.System.AUTO_TIME));
kvs.put(Settings.Secure.BLUETOOTH_ON, Settings.Secure.getString(cr, Settings.Secure.BLUETOOTH_ON));
kvs.put(Settings.Secure.DATA_ROAMING, Settings.Secure.getString(cr, Settings.Secure.DATA_ROAMING));
kvs.put(Settings.Secure.HTTP_PROXY, Settings.Secure.getString(cr, Settings.Secure.HTTP_PROXY));
}
kvs.put(Settings.Secure.ACCESSIBILITY_ENABLED, Settings.Secure.getString(cr, Settings.Secure.ACCESSIBILITY_ENABLED)); // 1 or 0
kvs.put(Settings.Secure.INSTALL_NON_MARKET_APPS, Settings.Secure.getString(cr, Settings.Secure.INSTALL_NON_MARKET_APPS)); // 1 or 0
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
kvs.put(Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, Settings.Secure.getString(cr, Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED)); // 1 or 0
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
kvs.put(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Settings.Global.getString(cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED));
}
kvs.put(Settings.System.DATE_FORMAT, Settings.System.getString(cr, Settings.System.DATE_FORMAT)); // dd/mm/yyyy
kvs.put(Settings.System.SCREEN_OFF_TIMEOUT, Settings.System.getString(cr, Settings.System.SCREEN_OFF_TIMEOUT)); // milliseconds
kvs.put(Settings.System.TIME_12_24, Settings.System.getString(cr, Settings.System.TIME_12_24)); // 12 or 24
kvs.put(Settings.Secure.ALLOW_MOCK_LOCATION, Settings.Secure.getString(cr, Settings.Secure.ALLOW_MOCK_LOCATION)); // 1 or 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
kvs.put(Settings.Secure.LOCATION_MODE, Settings.Secure.getString(cr, Settings.Secure.LOCATION_MODE)); // Int values 0 - 3
}
// Most build params are never changed, others are changed only after firmware upgrade.
kvs.put("build_version_sdk", Build.VERSION.SDK_INT);
kvs.put("build_brand", Build.BRAND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < Build.SUPPORTED_ABIS.length; ++i)
kvs.put("build_cpu_abi" + (i + 1), Build.SUPPORTED_ABIS[i]);
} else {
kvs.put("build_cpu_abi1", Build.CPU_ABI);
kvs.put("build_cpu_abi2", Build.CPU_ABI2);
}
kvs.put("build_device", Build.DEVICE);
kvs.put("build_display", Build.DISPLAY);
kvs.put("build_fingerprint", Build.FINGERPRINT);
kvs.put("build_hardware", Build.HARDWARE);
kvs.put("build_host", Build.HOST);
kvs.put("build_id", Build.ID);
kvs.put("build_manufacturer", Build.MANUFACTURER);
kvs.put("build_model", Build.MODEL);
kvs.put("build_product", Build.PRODUCT);
kvs.put("build_serial", Build.SERIAL);
kvs.put("build_tags", Build.TAGS);
kvs.put("build_time", Build.TIME);
kvs.put("build_type", Build.TYPE);
kvs.put("build_user", Build.USER);
Statistics.logEvent("$androidDeviceInfo", kvs.mPairs);
}
}
|
package dk.netarkivet.archive.arcrepository;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.netarkivet.archive.ArchiveSettings;
import dk.netarkivet.archive.arcrepository.bitpreservation.AdminDataMessage;
import dk.netarkivet.archive.arcrepository.bitpreservation.ChecksumJob;
import dk.netarkivet.archive.arcrepository.distribute.ArcRepositoryServer;
import dk.netarkivet.archive.arcrepository.distribute.StoreMessage;
import dk.netarkivet.archive.arcrepositoryadmin.UpdateableAdminData;
import dk.netarkivet.archive.bitarchive.distribute.BatchReplyMessage;
import dk.netarkivet.archive.bitarchive.distribute.BitarchiveClient;
import dk.netarkivet.archive.bitarchive.distribute.RemoveAndGetFileMessage;
import dk.netarkivet.archive.bitarchive.distribute.UploadMessage;
import dk.netarkivet.archive.checksum.distribute.ChecksumClient;
import dk.netarkivet.archive.checksum.distribute.GetAllChecksumMessage;
import dk.netarkivet.archive.checksum.distribute.GetChecksumMessage;
import dk.netarkivet.archive.distribute.ReplicaClient;
import dk.netarkivet.common.distribute.ChannelID;
import dk.netarkivet.common.distribute.Channels;
import dk.netarkivet.common.distribute.JMSConnectionFactory;
import dk.netarkivet.common.distribute.NetarkivetMessage;
import dk.netarkivet.common.distribute.NullRemoteFile;
import dk.netarkivet.common.distribute.RemoteFile;
import dk.netarkivet.common.distribute.arcrepository.BitArchiveStoreState;
import dk.netarkivet.common.distribute.arcrepository.Replica;
import dk.netarkivet.common.distribute.arcrepository.ReplicaType;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.exceptions.IllegalState;
import dk.netarkivet.common.exceptions.UnknownID;
import dk.netarkivet.common.utils.CleanupIF;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.NotificationsFactory;
import dk.netarkivet.common.utils.Settings;
/**
* The Arcrepository handles the communication with the different replicas.
* This class ensures that arc files are stored in all available
* replica and verifies that the storage process succeeded. Retrieval of
* data from a replica goes through the JMSArcRepositoryClient that contacts
* the appropriate (typically nearest) replica and retrieves data from this
* archive. Batch execution is sent to the replica(s). Correction operations
* are typically only allowed on one replica.
*/
public class ArcRepository implements CleanupIF {
private final Log log = LogFactory.getLog(getClass().getName());
/**
* The unique instance (singleton) of this class.
*/
private static ArcRepository instance;
/**
* The administration data associated with the arcrepository.
*/
private UpdateableAdminData ad;
/**
* The class which listens to messages sent to this instance of
* Arcrepository or its subclasses.
*/
private ArcRepositoryServer arcReposhandler;
/**
* A Map of a Replica and their corresponding ReplicaClient.
* From this Map the relevant channels can be found.
*/
private final Map<Replica, ReplicaClient> connectedReplicas =
new HashMap<Replica, ReplicaClient>();
/**
* Map from MessageId to arcfiles for which there are outstanding checksum
* jobs.
*/
private final Map<String, String> outstandingChecksumFiles =
new HashMap<String, String>();
/**
* Map from filenames to remote files. Used for retrieving a remote file
* reference while a store operation is in process.
*/
private final Map<String, RemoteFile> outstandingRemoteFiles =
new HashMap<String, RemoteFile>();
/**
* Map from bitarchive names to Map from filenames to the number of times a
* file has been attempted uploaded to the the bitarchive.
*/
private final Map<String, Map<String, Integer>> uploadRetries =
new HashMap<String, Map<String, Integer>>();
private ArcRepository() throws IOFailure, IllegalState {
//UpdateableAdminData Throws IOFailure
this.ad = UpdateableAdminData.getUpdateableInstance();
this.arcReposhandler = new ArcRepositoryServer(this);
initialiseReplicaClients();
log.info("Starting the ArcRepository");
}
public static synchronized ArcRepository getInstance()
throws IllegalState, IOFailure {
if (instance == null) {
instance = new ArcRepository();
}
return instance;
}
/**
* Method for initialising the replica clients.
*
*/
private void initialiseReplicaClients() {
// Get channels
String[] replicaIds = Channels.getUsedReplicaIds();
ChannelID[] allBas = Channels.getAllArchives_ALL_BAs();
ChannelID[] anyBas = Channels.getAllArchives_ANY_BAs();
ChannelID[] theBamons = Channels.getAllArchives_BAMONs();
ChannelID[] theCrs = Channels.getAllArchives_CRs();
// Checks equal number of channels
checkChannels(allBas, anyBas, theBamons);
for (int i = 0; i < allBas.length; i++) {
Replica rep = Replica.getReplicaFromId(replicaIds[i]);
if(rep.getType() == ReplicaType.BITARCHIVE) {
connectedReplicas.put(rep, connectToBitarchive(
allBas[i], anyBas[i], theBamons[i]));
} else { // checksum replica
connectedReplicas.put(rep, connectToChecksum(theCrs[i]));
}
}
}
private void checkChannels(ChannelID[] allBas, ChannelID[] anyBas,
ChannelID[] theBamons) throws IllegalState {
if (theBamons.length != allBas.length
|| theBamons.length != anyBas.length) {
StringBuilder values = new StringBuilder(
"Inconsistent data found in "
+ "construction of ArcRepository: \n");
values.append("\nALL_BAs: ");
values.append(Arrays.toString(allBas));
values.append("\nANY_BAs: ");
values.append(Arrays.toString(anyBas));
values.append("\nTHE_BAMONs: ");
values.append(Arrays.toString(theBamons));
throw new IllegalState(values.toString());
}
}
private BitarchiveClient connectToBitarchive(ChannelID allBa, ChannelID anyBa,
ChannelID theBamon) throws IOFailure {
return BitarchiveClient.getInstance(allBa, anyBa, theBamon);
}
/**
* Establish a connection to a new checksum replica.
* @param theCr The THE_CR channel to the given checksum replica.
* @return The Client to the Checksum replica.
* @throws IOFailure If error occurs during the connection to the checksum
* replica.
*/
private ChecksumClient connectToChecksum(ChannelID theCr) throws IOFailure {
return ChecksumClient.getInstance(theCr);
}
/**
* Stores a file in all known Bitarchives. This runs asynchronously, and
* returns immediately. Side effects:
* 1) The RemoteFile added to List outstandingRemoteFiles, where overwrite
* is allowed.
* 2) TODO: Check, if other sideeffects exist, and document them.
*
* @param rf A remotefile to be stored.
* @param replyInfo A StoreMessage used to reply with success or failure.
* @throws IOFailure If file couldn't be stored.
* @throws ArgumentNotValid If a input parameter is null
*/
public synchronized void store(RemoteFile rf, StoreMessage replyInfo)
throws IOFailure {
ArgumentNotValid.checkNotNull(rf, "rf");
ArgumentNotValid.checkNotNull(replyInfo, "replyInfo");
final String filename = rf.getName();
log.warn("Store started: '" + filename + "'");
// Record, that store of this filename is in progress
// needed for retrying uploads.
if (outstandingRemoteFiles.containsKey(filename)) {
log.info("File: '" + filename + "' was outstanding from the start.");
}
outstandingRemoteFiles.put(filename, rf);
if (ad.hasEntry(filename)) {
// Any valid entry (and all existing entries are now
// known to be valid) by definition has a checksum.
if (!rf.getChecksum().equals(ad.getCheckSum(filename))) {
String msg = "Attempting to store file '" + filename
+ "' with a different checksum than before: "
+ "Old checksum: " + ad.getCheckSum(filename)
+ ", new checksum: " + rf.getChecksum();
log.warn(msg);
replyNotOK(filename, replyInfo);
return;
}
log.debug("Retrying store of already known file '" + filename + "',"
+ " Already completed: " + isStoreCompleted(filename));
ad.setReplyInfo(filename, replyInfo);
} else {
ad.addEntry(filename, replyInfo, rf.getChecksum());
}
for (Map.Entry<Replica, ReplicaClient> entry : connectedReplicas
.entrySet()) {
startUpload(rf, entry.getValue(), entry.getKey());
}
// Check state and reply if needed
considerReplyingOnStore(filename);
}
/**
* Initiate uploading of file to a specific bitarchive. The corresponding
* upload record in admin data is created.
*
* @param rf Remotefile to upload to bitarchive.
* @param replicaClient The bitarchive client to upload to.
* @param replica The replica where RemoteFile is to be stored.
*/
private synchronized void startUpload(RemoteFile rf,
ReplicaClient replicaClient, Replica replica) {
final String filename = rf.getName();
log.debug("Upload started of file '" + filename + "' at '"
+ replica.getId() + "'");
String replicaChannelId = replica.getChannelID().getName();
if (!ad.hasState(filename, replicaChannelId)) {
// New upload
ad.setState(filename, replicaChannelId,
BitArchiveStoreState.UPLOAD_STARTED);
replicaClient.upload(rf);
} else {
// Recovery from old upload
BitArchiveStoreState storeState = ad.getState(filename,
replicaChannelId);
log.trace("Recovery from old upload. StoreState: " + storeState);
switch (storeState) {
case UPLOAD_FAILED:
case UPLOAD_STARTED:
case DATA_UPLOADED:
// Unknown condition in bitarchive. Test with checksum job.
if (storeState == BitArchiveStoreState.UPLOAD_FAILED) {
ad.setState(filename, replicaChannelId,
BitArchiveStoreState.UPLOAD_STARTED);
}
sendChecksumRequestForFile(filename, replicaClient);
break;
case UPLOAD_COMPLETED:
break;
default:
throw new UnknownID("Unknown state: '" + storeState + "'");
}
}
}
/**
* Method for retrieving the checksum of a specific file from the archive
* of a specific replica.
* If the replica is a BitArchive, then a Batch message with the
* ChecksumJob is sent.
* If the replica is a ChecksumArchive, then a GetChecksumMessage is sent.
*
* @param filename The file to checksum.
* @param replicaClient The client to retrieve the checksum of the file
* from.
*/
private void sendChecksumRequestForFile(String filename,
ReplicaClient replicaClient) {
NetarkivetMessage msg;
if(replicaClient.getType() == ReplicaType.BITARCHIVE) {
// Retrieve the checksum from the BitarchiveReplica
ChecksumJob checksumJob = new ChecksumJob();
checksumJob.processOnlyFileNamed(filename);
msg = replicaClient.batch(Channels.getTheRepos(),
checksumJob);
} else if (replicaClient.getType() == ReplicaType.CHECKSUM) {
// Retrieve the checskum from the ChecksumReplica
msg = replicaClient.getChecksum(Channels.getTheRepos(), filename);
} else {
// Unknown replica type
String errMsg = "Unknown replica type form replica client '"
+ replicaClient + "'. Cannot retrieve checksum for file '"
+ filename + "'.";
log.error(errMsg);
throw new IllegalState(errMsg);
// msg = null;
}
outstandingChecksumFiles.put(msg.getID(), filename);
log.debug("Checksum job submitted for: '" + filename + "'");
}
/**
* Test whether the current state is such that we may send a reply for the
* file we are currently processing, and send the reply if it is. We reply
* only when there is an outstanding message to reply to, and a) The file is
* reported complete in all bitarchives or b) No bitarchive has outstanding
* reply messages AND some bitarchive has reported failure.
*
* @param arcFileName The arcfile we consider replying to.
*/
private synchronized void considerReplyingOnStore(String arcFileName) {
if (ad.hasReplyInfo(arcFileName)) {
if (isStoreCompleted(arcFileName)) {
replyOK(arcFileName, ad.removeReplyInfo(arcFileName));
} else if (oneBitArchiveHasFailed(arcFileName)
&& noBitArchiveInStateUploadStarted(arcFileName)) {
replyNotOK(arcFileName, ad.removeReplyInfo(arcFileName));
}
}
}
/**
* Reply to a store message with status Ok.
*
* @param arcFileName The file for which we are replying.
* @param msg The message to reply to.
*/
private synchronized void replyOK(String arcFileName, StoreMessage msg) {
outstandingRemoteFiles.remove(arcFileName);
clearRetries(arcFileName);
log.info("Store OK: '" + arcFileName + "'");
log.debug("Sending store OK reply to message '" + msg + "'");
JMSConnectionFactory.getInstance().reply(msg);
}
/**
* Reply to a store message with status NotOk.
*
* @param arcFileName The file for which we are replying.
* @param msg The message to reply to.
*/
private synchronized void replyNotOK(String arcFileName, StoreMessage msg) {
outstandingRemoteFiles.remove(arcFileName);
clearRetries(arcFileName);
msg.setNotOk("Failure while trying to store ARC file: " + arcFileName);
log.warn("Store NOT OK: '" + arcFileName + "'");
log.debug("Sending store NOT OK reply to message '" + msg + "'");
JMSConnectionFactory.getInstance().reply(msg);
}
/**
* Check if all bitarchives have reported that storage has been successfully
* completed. If this is the case return true else false.
*
* @param arcfileName The file being stored.
* @return true only if all bitarchives report UPLOAD_COMPLETED.
*/
private boolean isStoreCompleted(String arcfileName) {
// TODO: remove quadratic scaling hidden here!!
for (Replica rep : connectedReplicas.keySet()) {
try {
// retrieve the replica channel and check upload status.
if (ad.getState(arcfileName, rep.getChannelID().getName())
!= BitArchiveStoreState.UPLOAD_COMPLETED) {
return false;
}
} catch (UnknownID e) {
// Since no upload status exists, then it cannot be completed!
log.warn("Non-fatal error! A replica does not have a upload "
+ "status for the file '" + arcfileName + "'.", e);
return false;
}
}
// Since no replica has a storestate differing from 'UPLOAD_COMPLETED'
// and no errors, then the store is completed for the entire system.
return true;
}
/**
* Checks if there are at least one BitarchiveReplica that has reported
* that storage has failed. If this is the case return true else false.
* This does not handle the ChecksumReplica, only the BitarchiveReplicas.
*
* @param arcFileName the name of file being stored.
* @return true only if at least one BitarchiveReplica report UPLOAD_FAILED.
*/
private boolean oneBitArchiveHasFailed(String arcFileName) {
for (Replica rep : connectedReplicas.keySet()) {
try {
// retrieve the replica channel and check upload status.
String repChannel = rep.getChannelID().getName();
if (ad.getState(arcFileName, repChannel)
== BitArchiveStoreState.UPLOAD_FAILED) {
return true;
}
} catch (UnknownID e) {
// TODO upload cannot have failed, when it has not even started.
log.warn("Non-fatal error. One replica does not have a upload "
+ "status for the file '" + arcFileName + "'.", e);
return true;
}
}
return false;
}
/**
* Checks if no BitarchiveReplicas which has reported that upload is in
* started state. If this is the case return true else false.
* This does not include the ChecksumReplicas.
*
* @param arcFileName The name of the file being stored.
* @return true only if no BitarchiveReplica report UPLOAD_STARTED.
*/
private boolean noBitArchiveInStateUploadStarted(String arcFileName) {
for (Replica rep : connectedReplicas.keySet()) {
try {
// retrieve the replica channel and check upload status.
String repChannel = rep.getChannelID().getName();
if (ad.getState(arcFileName, repChannel)
== BitArchiveStoreState.UPLOAD_STARTED) {
return false;
}
} catch (UnknownID e) {
// When no upload exists, then upload cannot have started.
log.warn("Non-fatal error! A replica does not have a upload "
+ "status for the file '" + arcFileName + "'.", e);
}
}
return true;
}
/**
* Returns a bitarchive client based on a replica id.
*
* @param replicaId the replica id
* @return a bitarchive client a bitarchive client
* @throws ArgumentNotValid
* if replicaId parameter is null
*/
public ReplicaClient getReplicaClientFromReplicaId(
String replicaId) throws ArgumentNotValid {
ArgumentNotValid.checkNotNullOrEmpty(replicaId, "replicaId");
// retrieve the replica client.
ReplicaClient rc = connectedReplicas.get(Replica.getReplicaFromId(replicaId));
if (rc == null) {
throw new UnknownID("Unknown ReplicaClient for replicaId: " + replicaId);
}
return rc;
}
/**
* Finds the identification channel for the replica. If the replica is a
* BitArchive then the channel to the BitArchiveMonitor is returned, and if
* the replica is a ChecksumArchive then the checksum replica channel is
* returned.
* This means that only the channels for the bitarchive should be changed
* into the bamon channel, e.g. replacing the ALL_BA and ANY_BA identifiers
* with THE_BAMON.
* This change does not affect the checksum channel, and is therefore also
* performed on it.
*
* @param channel A channel to the replica.
* @return The name of the channel which identifies the replica.
*/
private String resolveReplicaChannel(String channel) {
return channel.replaceAll("ALL_BA", "THE_BAMON").replaceAll("ANY_BA",
"THE_BAMON");
}
/**
* Event handler for upload messages reporting the upload result.
* Checks the success status of the upload and updates admin data
* accordingly.
*
* @param msg an UploadMessage.
*/
public synchronized void onUpload(UploadMessage msg) {
ArgumentNotValid.checkNotNull(msg, "msg");
log.debug("Received upload reply: " + msg.toString());
String repChannelName = resolveReplicaChannel(msg.getTo().getName());
if (msg.isOk()) {
processDataUploaded(msg.getArcfileName(), repChannelName);
} else {
processUploadFailed(msg.getArcfileName(), repChannelName);
}
}
/**
* Process the report by a bitarchive that a file was correctly uploaded.
* 1. Update the upload, and store states appropriately.
* 2. Verify that data are correctly stored in the archive by running a
* batch job on the archived file to perform a MD5 checksum comparison.
* 3. Check if store operation is completed and update admin data if so.
*
* @param arcfileName The arcfile that was uploaded.
* @param replicaChannelName The name of the identification channel for
* the replica that uploaded it (THE_BAMON for bitarchive and THE_CR for
* checksum).
*/
private synchronized void processDataUploaded(String arcfileName,
String replicaChannelName) {
log.debug("Data uploaded '" + arcfileName + "' ," + replicaChannelName);
ad.setState(arcfileName, replicaChannelName,
BitArchiveStoreState.DATA_UPLOADED);
// retrieve the replica
Replica rep = Channels.retrieveReplicaFromIdentifierChannel(
replicaChannelName);
sendChecksumRequestForFile(arcfileName, connectedReplicas.get(rep));
}
/**
* Update admin data with the information that upload to a replica failed.
* The replica record is set to UPLOAD_FAILED.
*
* @param arcfileName The file that resulted in an upload failure.
* @param replicaChannelName The name of the idenfiticaiton channel for
* the replica that could not upload the file.
*/
private void processUploadFailed(String arcfileName,
String replicaChannelName) {
log.warn("Upload failed for ARC file '" + arcfileName
+ "' to bit archive '" + replicaChannelName + "'");
// Update state to reflect upload failure
ad.setState(arcfileName, replicaChannelName,
BitArchiveStoreState.UPLOAD_FAILED);
considerReplyingOnStore(arcfileName);
}
/**
* Called when we receive replies on our checksum batch jobs.
*
* This does not handle checksum replicas.
*
* @param msg a BatchReplyMessage.
*/
public synchronized void onBatchReply(BatchReplyMessage msg) {
ArgumentNotValid.checkNotNull(msg, "msg");
log.debug("BatchReplyMessage received: '" + msg + "'");
if (!outstandingChecksumFiles.containsKey(msg.getReplyOfId())) {
// Message was NOT expected
log.warn("Received batchreply message with unknown originating "
+ "ID " + msg.getReplyOfId() + "\n" + msg.toString()
+ "\n. Known IDs are: "
+ outstandingChecksumFiles.keySet().toString());
return;
}
String arcfileName = outstandingChecksumFiles
.remove(msg.getReplyOfId());
// Check incoming message
if (!msg.isOk()) {
//Checksum job has ended with errors, but can contain checksum
//anyway, therefore it is logged - but we try to go on
log.warn("Message '" + msg.getID()
+ "' is reported not okay"
+ "\nReported error: '" + msg.getErrMsg() + "'"
+ "\nTrying to process anyway.");
}
// Parse results
RemoteFile checksumResFile = msg.getResultFile();
String reportedChecksum = "";
boolean checksumReadOk = false;
if (checksumResFile == null ||
checksumResFile instanceof NullRemoteFile) {
log.debug("Message '" + msg.getID()
+ "' returned no results"
+ (checksumResFile == null ? " (was null)" : "")
+ "\nNo checksum to use for file '"
+ arcfileName + "'");
} else {
//Read checksum
// Copy result to a local file
File outputFile = new File(FileUtils.getTempDir(),
msg.getReplyTo().getName()
+ "_" + arcfileName + "_checksumOutput.txt");
try {
checksumResFile.copyTo(outputFile);
// Read checksum from local file
reportedChecksum = readChecksum(outputFile, arcfileName);
checksumReadOk = true;
} catch (IOFailure e) {
log.warn("Couldn't read checksumjob "
+ "output for '" + arcfileName + "'", e);
} catch (IllegalState e) {
log.warn("Couldn't read result of checksumjob "
+ "in '" + arcfileName + "'", e);
}
// Clean up output file and remote file
// clean up does NOT result in general error, i.e.
// reportedChecksum is NOT set to "" in case of errors
try {
FileUtils.removeRecursively(outputFile);
} catch (IOFailure e) {
log.warn("Couldn't clean up checksumjob "
+ "output file '" + outputFile + "'", e);
}
try {
checksumResFile.cleanup();
} catch (IOFailure e) {
log.warn("Couldn't clean up checksumjob "
+ "remote file '" + checksumResFile.getName() + "'", e);
}
}
// Process result
String orgCheckSum = ad.getCheckSum(arcfileName);
String repChannel = resolveReplicaChannel(msg.getReplyTo().getName());
processCheckSum(arcfileName, repChannel, orgCheckSum,
reportedChecksum, msg.isOk() && checksumReadOk);
}
/**
* The message for handling the results of the GetChecksumMessage.
*
* @param msg The message containing the checksum of a specific file.
*/
public void onChecksumReply(GetChecksumMessage msg) {
ArgumentNotValid.checkNotNull(msg, "msg");
log.debug("Received the GetChecksumMessage, which should be a reply: "
+ msg.toString());
// handle the case when unwanted reply.
if(!outstandingChecksumFiles.containsKey(msg.getID())) {
log.warn("Received GetChecksumMessage with unknown originating "
+ "ID " + msg.getReplyOfId() + "\n" + msg.toString()
+ "\n. Known IDs are: "
+ outstandingChecksumFiles.keySet().toString());
return;
}
String arcfileName = outstandingChecksumFiles.remove(
msg.getID());
// Check incoming message
if (!msg.isOk()) {
//Checksum job has ended with errors, but can contain checksum
//anyway, therefore it is logged - but we try to go on
log.warn("Message '" + msg.getID()
+ "' is reported not okay"
+ "\nReported error: '" + msg.getErrMsg() + "'"
+ "\nTrying to process anyway.");
}
String orgChecksum = ad.getCheckSum(arcfileName);
String repChannelName = resolveReplicaChannel(msg.getReplyTo().getName());
String reportedChecksum = msg.getChecksum();
// Validate the checksum and set the upload state in admin.data.
if (orgChecksum.equals(reportedChecksum)
&& !reportedChecksum.isEmpty() ) {
// Checksum is valid and job matches expected results
ad.setState(arcfileName, repChannelName,
BitArchiveStoreState.UPLOAD_COMPLETED);
} else {
// Handle the case when the checksum is invalid.
log.warn("The arcfile '" + arcfileName + "' has a bad checksum. "
+ "Should have seen '" + orgChecksum + "', but saw '"
+ reportedChecksum + "'.");
ad.setState(arcfileName, repChannelName,
BitArchiveStoreState.UPLOAD_FAILED);
}
considerReplyingOnStore(arcfileName);
log.debug("Finished processing of GetChecksumMessage.");
}
private String readChecksum(File outputFile, String arcfileName) {
//List of lines in batch (checksum job) output file
List<String> lines = FileUtils.readListFromFile(outputFile);
//List of checksums found in batch (checksum job) output file
List<String> checksumList = new ArrayList<String>();
//Extract checksums for arcfile from lines
//If errors occurs then throw exception
for (String line : lines) {
String readFileName = "";
String checksum = "";
String[] tokens = line.split(
dk.netarkivet.archive.arcrepository
.bitpreservation.Constants.STRING_FILENAME_SEPARATOR);
boolean ignoreLine = false;
//Check line format
ignoreLine = (tokens.length == 0 || line.isEmpty());
if (tokens.length != 2 && !ignoreLine) { //wrong format
throw new IllegalState("Read checksum line had unexpected "
+ "format '" + line + "'");
}
//Check checksum and arc-file name in line
if (!ignoreLine) {
readFileName = tokens[0];
checksum = tokens[1];
if (checksum.length() == 0) { //wrong format of checksum
//do not exit - there may be more checksums
ignoreLine = true;
log.warn("There were an empty checksum in result for "
+ "checksums to arc-file '" + arcfileName
+ "(line: '" + line + "')");
} else {
if (!readFileName.equals(arcfileName)) { //wrong arcfile
// do not exit - there may be more checksums
ignoreLine = true;
log.warn("There were an unexpected arc-file name in "
+ "checksum result for arc-file '"
+ arcfileName
+ "'" + "(line: '" + line + "')");
}
}
}
//Check against earlier readen checksums, if more than one
if (checksumList.size() > 0 && !ignoreLine) {
//Ignore if the checksums are the same
if (!checksum.equals(
checksumList.get(checksumList.size() - 1))) {
String errMsg = "The arc-file '" + arcfileName
+ "' was found with two different checksums: "
+ checksumList.get(0) + " and " + checksum
+ ". Last line: '" + line + "'.";
log.warn(errMsg);
throw new IllegalState(errMsg);
}
}
//Add error free non-empty found checksum in list
if (!ignoreLine) {
checksumList.add(checksum);
}
}
// Check that checksum list contain a result,
// log if it has more than one result
if (checksumList.size() > 1) {
//Log and proceed - the checksums are equal
log.warn("Arcfile '" + arcfileName + "' was found with "
+ checksumList.size() + " occurences of the checksum: "
+ checksumList.get(0));
}
if (checksumList.size() == 0) {
log.debug("Arcfile '" + arcfileName
+ "' not found in lines of checksum output file '"
+ outputFile
+ "': " + FileUtils.readListFromFile(outputFile));
return "";
} else {
return checksumList.get(0);
}
}
/**
* Process reporting of a checksum from a bitarchive for a specific file as
* part of a store operation for the file. Verify that the checksum is
* correct, update the BitArchiveStoreState state.
* Invariant: upload-state is changed or retry count is increased.
*
* @param arcFileName
* The file being stored.
* @param replicaChannelName
* The id of the replica reporting a checksum.
* @param orgChecksum
* The original checksum.
* @param reportedChecksum
* The checksum calculated by the replica. This value is "",
* if an error has occured (except reply NOT ok from replica).
* @param checksumReadOk
* Tells whether the checksum was read ok by batch job.
*/
private synchronized void processCheckSum(String arcFileName,
String replicaChannelName, String orgChecksum,
String reportedChecksum,
boolean checksumReadOk) {
log.debug("Checksum received ... processing");
ArgumentNotValid.checkNotNullOrEmpty(arcFileName, "String arcfileName");
ArgumentNotValid.checkNotNullOrEmpty(replicaChannelName,
"String replicaId");
ArgumentNotValid.checkNotNullOrEmpty(orgChecksum, "String orgChecksum");
ArgumentNotValid.checkNotNull(reportedChecksum,
"String reportedChecksum");
//Log if we do not find file outstanding
//we proceed anyway in order to be sure to update stae of file
if (!outstandingRemoteFiles.containsKey(arcFileName)) {
log.warn("Could not find arc-file as outstanding "
+ "remote file: '" + arcFileName + "'");
}
//If everything works fine complete process of this checksum
if (orgChecksum.equals(reportedChecksum)
&& !reportedChecksum.isEmpty() ) {
// Checksum is valid and job matches expected results
ad.setState(arcFileName, replicaChannelName,
BitArchiveStoreState.UPLOAD_COMPLETED);
// Find out if and how to make general reply on store()
// remove file from outstandingRemoteFiles if a reply is given
considerReplyingOnStore(arcFileName);
return;
}
//Log error or retry upload
if (reportedChecksum.isEmpty()) { //no checksum found
if (checksumReadOk) { //no errors in finding no checksum
if (retryOk(replicaChannelName, arcFileName)) { // we can retry
if (outstandingRemoteFiles.containsKey(arcFileName)) {
RemoteFile rf = outstandingRemoteFiles.get(arcFileName);
//Retry upload only if allowed and in case we are sure
//that the empty checksum means that the arcfile is not
//in the archive
log.debug("Retrying upload of '" + arcFileName + "'");
ad.setState(rf.getName(), replicaChannelName,
BitArchiveStoreState.UPLOAD_STARTED);
// retrieve the replica from the name of the channel.
Replica rep =
Channels.retrieveReplicaFromIdentifierChannel(
replicaChannelName);
connectedReplicas.get(rep).upload(rf);
incRetry(replicaChannelName, arcFileName);
return;
} //else logning was done allready above
} else { //cannot retry
log.warn("Cannot do more retry upload of "
+ "remote file: '" + arcFileName + "' to '"
+ replicaChannelName + "', reported checksum='"
+ reportedChecksum + "'" );
}
} else { //error in getting checksum
log.warn("Cannot retry upload of "
+ "remote file: '" + arcFileName + "' to '"
+ replicaChannelName + "', reported checksum='"
+ reportedChecksum + "' due to earlier batchjob"
+ " error." );
}
} else { //non empty checksum
if (!orgChecksum.equals(reportedChecksum)) {
log.warn("Cannot upload (wrong checksum) '" + arcFileName
+ "' to '"+ replicaChannelName + "', reported checksum='"
+ reportedChecksum + "'");
} else {
log.warn("Cannot upload (unknown reason) '" + arcFileName
+ "' to '"+ replicaChannelName + "', reported checksum='"
+ reportedChecksum + "'");
}
}
// This point is reached if there is some kind of (logged) error, i.e.
// - the file has not been accepted as completed
// - the file has not been sent to retry of upload
ad.setState(arcFileName, replicaChannelName,
BitArchiveStoreState.UPLOAD_FAILED);
considerReplyingOnStore(arcFileName);
}
/**
* Keep track of upload retries of an arcfile to an archive.
*
* @param replicaId The name of a given bitarchive
* @param arcfileName The name of a given ARC file
* @return true if it is ok to retry an upload of arcfileName to
* bitarchiveName
*/
private boolean retryOk(String replicaId, String arcfileName) {
Map<String, Integer> bitarchiveRetries = uploadRetries
.get(replicaId);
if (bitarchiveRetries == null) {
return true;
}
Integer retryCount = bitarchiveRetries.get(arcfileName);
if (retryCount == null) {
return true;
}
if (retryCount >= Settings.getInt(
ArchiveSettings.ARCREPOSITORY_UPLOAD_RETRIES)) {
return false;
}
return true;
}
/**
* Increment the number of upload retries.
*
* @param replicaChannelName The name of the identification channel
* for the replica.
* @param arcfileName The name of a given ARC file.
*/
private void incRetry(String replicaChannelName, String arcfileName) {
Map<String, Integer> bitarchiveRetries = uploadRetries
.get(replicaChannelName);
if (bitarchiveRetries == null) {
bitarchiveRetries = new HashMap<String, Integer>();
uploadRetries.put(replicaChannelName, bitarchiveRetries);
}
Integer retryCount = bitarchiveRetries.get(arcfileName);
if (retryCount == null) {
bitarchiveRetries.put(arcfileName, new Integer(1));
return;
}
bitarchiveRetries.put(arcfileName, new Integer(retryCount + 1));
}
/**
* Remove all retry tracking information for the arcfile.
*
* @param arcfileName The name of a given ARC file
*/
private void clearRetries(String arcfileName) {
for (String replicaChannelName : uploadRetries.keySet()) {
Map<String, Integer> baretries = uploadRetries.get(
replicaChannelName);
baretries.remove(arcfileName);
}
}
/**
* Change admin data entry for a given file.
*
* The following information is contained in the given AdminDataMessage:
* 1) The name of the given file to change the entry for,
* 2) the name of the bitarchive to modify the entry for,
* 3) a boolean that says whether or not to replace the checksum for the
* entry for the given file in AdminData,
* 4) a replacement for the case where the former value is true.
*
* @param msg an AdminDataMessage object
*/
public void updateAdminData(AdminDataMessage msg) {
if (!ad.hasEntry(msg.getFileName())) {
throw new ArgumentNotValid("No admin entry exists for the file '"
+ msg.getFileName() + "'");
}
String message = "Handling request to change admin data for '" +
msg.getFileName() + "'. "
+ (msg.isChangeStoreState() ?
"Change store state to " + msg.getNewvalue() : "")
+ (msg.isChangeChecksum() ?
"Change checksum to " + msg.getChecksum() : "");
log.warn(message);
NotificationsFactory.getInstance().errorEvent(message);
if (msg.isChangeStoreState()) {
String replicaChannelName = Replica.getReplicaFromId(
msg.getBitarchiveId()).getChannelID().getName();
ad.setState(msg.getFileName(), replicaChannelName,
msg.getNewvalue());
}
if (msg.isChangeChecksum()) {
ad.setCheckSum(msg.getFileName(), msg.getChecksum());
}
}
/**
* Forwards a RemoveAndGetFileMessage to the designated bitarchive. Before
* forwarding the message it is verified that the checksum of the file to
* remove differs from the registered checksum of the file to remove. If no
* registration exists for the file to remove the message is always
* forwarded.
*
* @param msg
* the message to forward to a bitarchive
*/
public void removeAndGetFile(RemoveAndGetFileMessage msg) {
// Prevent removal of files with correct checksum
if (ad.hasEntry(msg.getArcfileName())) {
String refchecksum = ad.getCheckSum(msg.getArcfileName());
if (msg.getCheckSum().equals(refchecksum)) {
throw new ArgumentNotValid(
"Attempting to remove file with correct checksum. File="
+ msg.getArcfileName() + "; with checksum:"
+ msg.getCheckSum() + ";");
}
}
// checksum ok - try to remove the file
log.warn("Requesting remove of file '" + msg.getArcfileName()
+ "' with checksum '" + msg.getCheckSum()
+ "' from: '" + msg.getReplicaId() + "'");
NotificationsFactory.getInstance().errorEvent(
"Requesting remove of file '"
+ msg.getArcfileName()
+ "' with checksum '" + msg.getCheckSum()
+ "' from: '" + msg.getReplicaId() + "'");
ReplicaClient rc = getReplicaClientFromReplicaId(msg
.getReplicaId());
rc.removeAndGetFile(msg);
}
/**
* Close all bitarchive connections, open loggers, and the ArcRepository
* handler.
*/
public void close() {
log.info("Closing down ArcRepository");
cleanup();
log.info("Closed ArcRepository");
}
/**
* Closes all connections and nulls the instance.
* The ArcRepositoryHandler, the AdminData and the ReplicaClients are
* closed along with all their connections.
*/
public void cleanup() {
if (arcReposhandler != null) {
arcReposhandler.close();
arcReposhandler = null;
}
if (connectedReplicas != null) {
for (ReplicaClient cba : connectedReplicas.values()) {
cba.close();
}
connectedReplicas.clear();
}
if (ad != null) {
ad.close();
ad = null;
}
instance = null;
}
}
|
/**
* EditEntityScreen
*
* Class representing the screen that allows users to edit properties of
* grid entities, including triggers and appearance.
*
* @author Willy McHie
* Wheaton College, CSCI 335, Spring 2013
*/
package edu.wheaton.simulator.gui.screen;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.gui.BoxLayoutAxis;
import edu.wheaton.simulator.gui.FileMenu;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.HorizontalAlignment;
import edu.wheaton.simulator.gui.IconGridPanel;
import edu.wheaton.simulator.gui.MaxSize;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.ScreenManager;
import edu.wheaton.simulator.gui.SimulatorFacade;
public class EditEntityScreen extends Screen {
private static final long serialVersionUID = 4021299442173260142L;
private Boolean editing;
private Prototype prototype;
private JPanel cards;
private String currentCard;
private JPanel generalPanel;
private JTextField nameField;
private JColorChooser colorTool;
private ArrayList<JTextField> fieldNames;
private ArrayList<JTextField> fieldValues;
private ArrayList<JButton> fieldDeleteButtons;
private ArrayList<JPanel> fieldSubPanels;
private JButton addFieldButton;
private boolean[][] buttons;
private JPanel fieldListPanel;
private HashSet<Integer> removedFields;
private JButton nextButton;
private JButton previousButton;
private JButton finishButton;
private GridBagConstraints c;
private TriggerScreen triggerScreen;
public EditEntityScreen(final SimulatorFacade gm) {
super(gm);
this.setLayout(new BorderLayout());
editing = false;
removedFields = new HashSet<Integer>();
nameField = new JTextField(25);
colorTool = Gui.makeColorChooser();
fieldNames = new ArrayList<JTextField>();
fieldValues = new ArrayList<JTextField>();
fieldSubPanels = new ArrayList<JPanel>();
fieldDeleteButtons = new ArrayList<JButton>();
buttons = new boolean[7][7];
currentCard = "General";
fieldListPanel = Gui.makePanel(BoxLayoutAxis.Y_AXIS, MaxSize.NULL,
PrefSize.NULL);
cards = new JPanel(new CardLayout());
generalPanel = new JPanel(new GridBagLayout());
addFieldButton = Gui.makeButton("Add Field",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addField();
}
});
final IconGridPanel iconPanel = new IconGridPanel(gm);
initIconDesignObject(iconPanel);
JPanel colorPanel = Gui.makeColorChooserPanel(colorTool);
colorTool.getSelectionModel().addChangeListener( new ChangeListener(){
@Override
public void stateChanged(ChangeEvent ce) {
iconPanel.repaint();
}
});
JLabel agentName = Gui.makeLabel("Agent Name: ",PrefSize.NULL, HorizontalAlignment.RIGHT);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
generalPanel.add(
Gui.makeLabel("General Info",
PrefSize.NULL,
HorizontalAlignment.CENTER),c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
generalPanel.add(agentName, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 1;
generalPanel.add(nameField, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
generalPanel.add(colorPanel, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weighty = 1.0;
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 2;
generalPanel.add(iconPanel, c);
addField();
// TODO make sure components line up
fieldSubPanels.get(0).setLayout(
new BoxLayout(fieldSubPanels.get(0), BoxLayout.X_AXIS));
fieldSubPanels.get(0).add(fieldNames.get(0));
fieldSubPanels.get(0).add(fieldValues.get(0));
fieldSubPanels.get(0).add(fieldDeleteButtons.get(0));
fieldListPanel.add(fieldSubPanels.get(0));
fieldListPanel.add(addFieldButton);
fieldListPanel.add(Box.createVerticalGlue());
cards.add(generalPanel, "General");
cards.add(makeFieldMainPanel(fieldListPanel), "Fields");
triggerScreen = new TriggerScreen(gm);
cards.add(triggerScreen, "Triggers");
finishButton = Gui.makeButton("Finish",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (sendInfo()) {
Gui.getScreenManager().load(Gui.getScreenManager().getScreen("View Simulation"));
reset();
}
}
});
previousButton = Gui.makeButton("Previous", null,
new PreviousListener());
nextButton = Gui.makeButton("Next", null, new NextListener());
this.add(new JLabel("Edit Entities", SwingConstants.CENTER),
BorderLayout.NORTH);
this.add(cards, BorderLayout.CENTER);
this.add(Gui.makePanel(
previousButton,
Gui.makeButton("Cancel",null,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ScreenManager sm = getScreenManager();
sm.load(sm.getScreen("View Simulation"));
FileMenu fm = Gui.getFileMenu();
fm.setSaveSim(true);
if (!editing)
Prototype.removePrototype(nameField.getText());
reset();
}
}), finishButton, nextButton),
BorderLayout.SOUTH );
}
private void initIconDesignObject(IconGridPanel iconPanel){
//Creates the icon design object.
iconPanel.setIcon(buttons);
}
private static JPanel makeFieldMainPanel(JPanel fieldListPanel){
JPanel fieldMainPanel = Gui.makePanel(new GridBagLayout(),MaxSize.NULL,PrefSize.NULL);
GridBagConstraints constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 0;
constraint.gridwidth = 2;
fieldMainPanel.add(
Gui.makeLabel("Field Info",PrefSize.NULL,HorizontalAlignment.CENTER),
constraint);
constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 1;
constraint.gridwidth = 1;
JLabel fieldNameLabel = Gui.makeLabel("Field Name", PrefSize.NULL, HorizontalAlignment.LEFT);
fieldNameLabel.setAlignmentX(LEFT_ALIGNMENT);
fieldMainPanel.add(fieldNameLabel, constraint);
constraint.gridx = 1;
JLabel fieldValueLabel = Gui.makeLabel("Field Initial Value",
PrefSize.NULL, HorizontalAlignment.LEFT);
fieldValueLabel.setAlignmentX(LEFT_ALIGNMENT);
fieldMainPanel.add(fieldValueLabel, constraint);
constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 2;
constraint.gridwidth = 3;
constraint.weighty = 1.0;
constraint.anchor = GridBagConstraints.PAGE_START;
fieldMainPanel.add(fieldListPanel, constraint);
return fieldMainPanel;
}
public void load(String str) {
reset();
prototype = gm.getPrototype(str);
nameField.setText(prototype.getName());
colorTool.setColor(prototype.getColor());
byte[] designBytes = prototype.getDesign();
byte byter = Byte.parseByte("0000001", 2);
for (int i = 0; i < 7; i++)
for (int j = 0; j < 7; j++)
if ((designBytes[i] & (byter << j)) != Byte.parseByte("0000000", 2))
buttons[i][6-j] = true;
Map<String, String> fields = prototype.getCustomFieldMap();
int i = 0;
for (String s : fields.keySet()) {
addField();
fieldNames.get(i).setText(s);
fieldValues.get(i).setText(fields.get(s));
i++;
}
}
public void reset() {
prototype = null;
currentCard = "General";
((CardLayout) cards.getLayout()).first(cards);
nameField.setText("");
colorTool.setColor(Color.WHITE);
for (int x = 0; x < 7; x++) {
for (int y = 0; y < 7; y++) {
buttons[x][y] = false;
}
}
fieldNames.clear();
fieldValues.clear();
fieldDeleteButtons.clear();
fieldSubPanels.clear();
removedFields.clear();
fieldListPanel.removeAll();
fieldListPanel.add(addFieldButton);
triggerScreen.reset();
previousButton.setEnabled(false);
//previousButton.setVisible(false);
nextButton.setEnabled(true);
//nextButton.setVisible(true);
finishButton.setEnabled(false);
//finishButton.setVisible(false);
FileMenu fm = Gui.getFileMenu();
fm.setSaveSim(false);
}
public boolean sendInfo() {
sendGeneralInfo();
prototype = triggerScreen.sendInfo();
return sendFieldInfo();
}
public boolean sendGeneralInfo() {
boolean toReturn = false;
try {
if (nameField.getText().equals("")) {
throw new Exception("Please enter an Agent name");
}
if (!editing) {
gm.createPrototype(nameField.getText(), colorTool.getColor(), generateBytes());
prototype = gm.getPrototype(nameField.getText());
} else {
prototype.setPrototypeName(prototype.getName(), nameField.getText());
prototype.setColor(colorTool.getColor());
prototype.setDesign(generateBytes());
Prototype.addPrototype(prototype);
}
toReturn = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public boolean sendFieldInfo() {
boolean toReturn = false;
try {
for (int i = 0; i < fieldNames.size(); i++)
if (!removedFields.contains(i)
&& (fieldNames.get(i).getText().equals("")
|| fieldValues.get(i).getText().equals("")))
throw new Exception("All fields must have input");
for (int i = 0; i < fieldNames.size(); i++) {
if (removedFields.contains(i)
&& (prototype.hasField(fieldNames.get(i).getText())))
prototype.removeField(fieldNames.get(i).toString());
else {
if (prototype.hasField(fieldNames.get(i).getText()))
prototype.updateField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
else {
try {
if (!removedFields.contains(i))
prototype.addField(fieldNames.get(i).getText(),
fieldValues.get(i).getText());
} catch (ElementAlreadyContainedException e) {
e.printStackTrace();
}
}
}
}
toReturn = true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return toReturn;
}
public void setEditing(Boolean b) {
editing = b;
}
public Color getColor() {
return colorTool.getColor();
}
private void addField() {
JTextField newName = Gui.makeTextField(null,25,MaxSize.NULL,null);
fieldNames.add(newName);
JTextField newValue = Gui.makeTextField(null,25,MaxSize.NULL,null);
fieldValues.add(newValue);
JButton newButton = Gui.makeButton("Delete",null,
new DeleteFieldListener());
fieldDeleteButtons.add(newButton);
newButton.setActionCommand(fieldDeleteButtons.indexOf(newButton) + "");
JPanel newPanel = Gui.makePanel(BoxLayoutAxis.X_AXIS, null, null);
newPanel.add(newName);
newPanel.add(newValue);
newPanel.add(newButton);
fieldSubPanels.add(newPanel);
fieldListPanel.add(newPanel);
fieldListPanel.add(addFieldButton);
fieldListPanel.add(Box.createVerticalGlue());
validate();
repaint();
}
private byte[] generateBytes() {
String str = "";
byte[] toReturn = new byte[7];
for (int column = 0; column < 7; column++) {
for (int row = 0; row < 7; row++) {
if (buttons[column][row] == true)
str += "1";
else
str += "0";
}
str += ":";
}
String[] byteStr = str.substring(0, str.lastIndexOf(':')).split(":");
for (int i = 0; i < 7; i++)
toReturn[i] = Byte.parseByte(byteStr[i], 2);
return toReturn;
}
private class DeleteFieldListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
removedFields.add(Integer.parseInt(e.getActionCommand()));
fieldListPanel.remove(fieldSubPanels.get(Integer.parseInt(e
.getActionCommand())));
validate();
}
}
private class NextListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout) cards.getLayout();
if (currentCard == "General") {
if (sendGeneralInfo()) {
previousButton.setEnabled(true);
//previousButton.setVisible(true);
c1.next(cards);
currentCard = "Fields";
}
} else if (currentCard == "Fields") {
if (sendFieldInfo()) {
triggerScreen.load(prototype);
c1.next(cards);
nextButton.setEnabled(false);
//nextButton.setVisible(false);
finishButton.setEnabled(true);
//finishButton.setVisible(true);
currentCard = "Triggers";
}
}
validate();
}
}
private class PreviousListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout c1 = (CardLayout) cards.getLayout();
if (currentCard == "Fields") {
if (sendFieldInfo()) {
previousButton.setEnabled(false);
//previousButton.setVisible(false);
c1.previous(cards);
currentCard = "General";
}
} else if (currentCard == "Triggers") {
prototype = triggerScreen.sendInfo();
c1.previous(cards);
nextButton.setEnabled(true);
//nextButton.setVisible(true);
currentCard = "Fields";
}
validate();
}
}
@Override
public void load() {
reset();
addField();
}
}
|
package fitnesse.responders.search;
import util.RegexTestCase;
import fitnesse.FitNesseContext;
import fitnesse.testutil.FitNesseUtil;
import fitnesse.http.MockRequest;
import fitnesse.http.MockResponseSender;
import fitnesse.http.Response;
import fitnesse.wiki.InMemoryPage;
import fitnesse.wiki.PageCrawler;
import fitnesse.wiki.PathParser;
import fitnesse.wiki.WikiPage;
public class WhereUsedResponderTest extends RegexTestCase {
private WikiPage root;
private WikiPage pageTwo;
public void setUp() throws Exception {
root = InMemoryPage.makeRoot("RooT");
FitNesseContext context = FitNesseUtil.makeTestContext(root);
PageCrawler crawler = root.getPageCrawler();
crawler.addPage(root, PathParser.parse("PageOne"), "PageOne");
pageTwo = crawler.addPage(root, PathParser.parse("PageTwo"), "PageOne");
crawler.addPage(pageTwo, PathParser.parse("ChildPage"), ".PageOne");
}
public void testResponse() throws Exception {
MockRequest request = new MockRequest();
request.setResource("PageOne");
WhereUsedResponder responder = new WhereUsedResponder();
Response response = responder.makeResponse(new FitNesseContext(root), request);
MockResponseSender sender = new MockResponseSender();
response.readyToSend(sender);
sender.waitForClose(5000);
String content = sender.sentData();
assertEquals(200, response.getStatus());
assertHasRegexp("Where Used", content);
assertHasRegexp(">PageOne<", content);
assertHasRegexp(">PageTwo<", content);
assertHasRegexp(">PageTwo\\.ChildPage<", content);
}
}
|
package org.voltdb.messaging;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google_voltpatches.common.collect.ImmutableSet;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.Subject;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.utils.CoreUtils;
import org.voltdb.ParameterSet;
import org.voltdb.VoltDB;
import org.voltdb.common.Constants;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.LogKeys;
import com.google_voltpatches.common.base.Charsets;
/**
* Message from a stored procedure coordinator to an execution site
* which is participating in the transaction. This message specifies
* which planfragment to run and with which parameters.
*
*/
public class FragmentTaskMessage extends TransactionInfoBaseMessage
{
protected static final VoltLogger hostLog = new VoltLogger("HOST");
public static final byte USER_PROC = 0;
public static final byte SYS_PROC_PER_PARTITION = 1;
public static final byte SYS_PROC_PER_SITE = 2;
public static final byte[] EMPTY_HASH;
static {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.exit(-1); // this means the jvm is broke
}
md.update("".getBytes(Constants.UTF8ENCODING));
EMPTY_HASH = md.digest();
}
private static class FragmentData {
byte[] m_planHash = null;
ByteBuffer m_parameterSet = null;
Integer m_outputDepId = null;
ArrayList<Integer> m_inputDepIds = null;
// For unplanned item
byte[] m_fragmentPlan = null;
public FragmentData() {
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("FRAGMENT PLAN HASH: %s\n", Encoder.hexEncode(m_planHash)));
if (m_parameterSet != null) {
ParameterSet pset = null;
try {
pset = ParameterSet.fromByteBuffer(m_parameterSet.asReadOnlyBuffer());
} catch (IOException e) {
e.printStackTrace();
}
assert(pset != null);
sb.append("\n ").append(pset.toString());
}
if (m_outputDepId != null) {
sb.append("\n");
sb.append(" OUTPUT_DEPENDENCY_ID ");
sb.append(m_outputDepId);
}
if ((m_inputDepIds != null) && (m_inputDepIds.size() > 0)) {
sb.append("\n");
sb.append(" INPUT_DEPENDENCY_IDS ");
for (long id : m_inputDepIds)
sb.append(id).append(", ");
sb.setLength(sb.lastIndexOf(", "));
}
if ((m_fragmentPlan != null) && (m_fragmentPlan.length != 0)) {
sb.append("\n");
sb.append(" FRAGMENT_PLAN ");
sb.append(m_fragmentPlan);
}
return sb.toString();
}
}
List<FragmentData> m_items = new ArrayList<FragmentData>();
boolean m_isFinal = false;
byte m_taskType = 0;
// We use this flag to generate a null FragmentTaskMessage that returns a
// response for a dependency but doesn't try to execute anything on the EE.
// This is a hack to serialize CompleteTransactionMessages and
// BorrowTaskMessages when the first fragment of the restarting transaction
// is a short-circuited replicated table read.
// If this flag is set, the message should contain a single fragment with the
// desired output dep ID, but no real work to do.
boolean m_emptyForRestart = false;
int m_inputDepCount = 0;
Iv2InitiateTaskMessage m_initiateTask;
ByteBuffer m_initiateTaskBuffer;
// Partitions involved in this multipart, set in the first fragment
Set<Integer> m_involvedPartitions = ImmutableSet.of();
// context for long running fragment status log messages
byte[] m_procedureName = null;
int m_currentBatchIndex = 0;
public int getCurrentBatchIndex() {
return m_currentBatchIndex;
}
/** Empty constructor for de-serialization */
FragmentTaskMessage() {
m_subject = Subject.DEFAULT.getId();
}
/**
*
* @param initiatorHSId
* @param coordinatorHSId
* @param txnId
* @param isReadOnly
* @param isFinal
*/
public FragmentTaskMessage(long initiatorHSId,
long coordinatorHSId,
long txnId,
long uniqueId,
boolean isReadOnly,
boolean isFinal,
boolean isForReplay) {
super(initiatorHSId, coordinatorHSId, txnId, uniqueId, isReadOnly, isForReplay);
m_isFinal = isFinal;
m_subject = Subject.DEFAULT.getId();
assert(selfCheck());
}
// If you add a new field to the message and you don't want to lose information at all point,
// remember to add it to the constructor below, Because this constructor is used to copy a message at some place.
// for example, in SpScheduler.handleFragmentTaskMessage()
// The parameter sets are .duplicate()'d in flattenToBuffer,
// so we can make a shallow copy here and still be thread-safe
// when we serialize the copy.
public FragmentTaskMessage(long initiatorHSId,
long coordinatorHSId,
FragmentTaskMessage ftask)
{
super(initiatorHSId, coordinatorHSId, ftask);
setSpHandle(ftask.getSpHandle());
m_taskType = ftask.m_taskType;
m_isFinal = ftask.m_isFinal;
m_subject = ftask.m_subject;
m_inputDepCount = ftask.m_inputDepCount;
m_items = ftask.m_items;
m_initiateTask = ftask.m_initiateTask;
m_emptyForRestart = ftask.m_emptyForRestart;
m_procedureName = ftask.m_procedureName;
m_currentBatchIndex = ftask.m_currentBatchIndex;
m_involvedPartitions = ftask.m_involvedPartitions;
if (ftask.m_initiateTaskBuffer != null) {
m_initiateTaskBuffer = ftask.m_initiateTaskBuffer.duplicate();
}
assert(selfCheck());
}
public void setProcedureName(String procedureName) {
Iv2InitiateTaskMessage it = getInitiateTask();
if (it != null) {
assert(it.getStoredProcedureName().equals(procedureName));
}
else {
m_procedureName = procedureName.getBytes(Charsets.UTF_8);
}
}
public void setBatch(int batchIndex) {
m_currentBatchIndex = batchIndex;
}
/**
* Add a pre-planned fragment.
*
* @param fragmentId
* @param outputDepId
* @param parameterSet
*/
public void addFragment(byte[] planHash, int outputDepId, ByteBuffer parameterSet) {
FragmentData item = new FragmentData();
item.m_planHash = planHash;
item.m_outputDepId = outputDepId;
item.m_parameterSet = parameterSet;
m_items.add(item);
}
/**
* Add an unplanned fragment.
*
* @param fragmentId
* @param outputDepId
* @param parameterSet
* @param fragmentPlan
*/
public void addCustomFragment(byte[] planHash, int outputDepId, ByteBuffer parameterSet, byte[] fragmentPlan) {
FragmentData item = new FragmentData();
item.m_planHash = planHash;
item.m_outputDepId = outputDepId;
item.m_parameterSet = parameterSet;
item.m_fragmentPlan = fragmentPlan;
m_items.add(item);
}
/**
* Convenience factory method to replace constructor that includes arrays of stuff.
*
* @param initiatorHSId
* @param coordinatorHSId
* @param txnId
* @param isReadOnly
* @param fragmentId
* @param outputDepId
* @param parameterSet
* @param isFinal
*
* @return new FragmentTaskMessage
*/
public static FragmentTaskMessage createWithOneFragment(long initiatorHSId,
long coordinatorHSId,
long txnId,
long uniqueId,
boolean isReadOnly,
byte[] planHash,
int outputDepId,
ParameterSet params,
boolean isFinal,
boolean isForReplay) {
ByteBuffer parambytes = null;
if (params != null) {
parambytes = ByteBuffer.allocate(params.getSerializedSize());
try {
params.flattenToBuffer(parambytes);
parambytes.flip();
}
catch (IOException e) {
VoltDB.crashLocalVoltDB("Failed to serialize parameter for fragment: " + params.toString(), true, e);
}
}
FragmentTaskMessage ret = new FragmentTaskMessage(initiatorHSId, coordinatorHSId,
txnId, uniqueId, isReadOnly, isFinal, isForReplay);
ret.addFragment(planHash, outputDepId, parambytes);
return ret;
}
private boolean selfCheck() {
for (FragmentData item : m_items) {
if (item == null) {
return false;
}
if (item.m_parameterSet == null) {
return false;
}
}
return true;
}
public void addInputDepId(int index, int depId) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
if (item.m_inputDepIds == null)
item.m_inputDepIds = new ArrayList<Integer>();
item.m_inputDepIds.add(depId);
m_inputDepCount++;
}
public ArrayList<Integer> getInputDepIds(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
return item.m_inputDepIds;
}
public int getOnlyInputDepId(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
if (item.m_inputDepIds == null)
return -1;
assert(item.m_inputDepIds.size() == 1);
return item.m_inputDepIds.get(0);
}
public int[] getAllUnorderedInputDepIds() {
int[] retval = new int[m_inputDepCount];
int i = 0;
for (FragmentData item : m_items) {
if (item.m_inputDepIds != null) {
for (int depId : item.m_inputDepIds) {
retval[i++] = depId;
}
}
}
assert(i == m_inputDepCount);
return retval;
}
public void setFragmentTaskType(byte value) {
m_taskType = value;
}
public boolean isFinalTask() {
return m_isFinal;
}
public boolean isSysProcTask() {
return (m_taskType != USER_PROC);
}
public byte getFragmentTaskType() {
return m_taskType;
}
public int getFragmentCount() {
return m_items.size();
}
// We're going to use this fragment task to generate a null distributed
// fragment to serialize Completion and Borrow messages. Create an empty
// fragment with the provided outputDepId
public void setEmptyForRestart(int outputDepId) {
m_emptyForRestart = true;
ParameterSet blank = ParameterSet.emptyParameterSet();
ByteBuffer mt = ByteBuffer.allocate(blank.getSerializedSize());
try {
blank.flattenToBuffer(mt);
}
catch (IOException ioe) {
// Shouldn't ever happen, just bail out to not-obviously equivalent behavior
mt = ByteBuffer.allocate(2);
mt.putShort((short)0);
}
addFragment(EMPTY_HASH, outputDepId, mt);
}
public boolean isEmptyForRestart() {
return m_emptyForRestart;
}
public String getProcedureName() {
Iv2InitiateTaskMessage initMsg = getInitiateTask();
if (initMsg != null) {
return initMsg.m_invocation.getProcName();
}
else if (m_procedureName != null) {
return new String(m_procedureName, Charsets.UTF_8);
}
else {
return null;
}
}
/*
* The first fragment contains the initiate task and the involved partitions set
* for a multi-part txn for command logging.
*
* Involved partitions set is a set of partition IDs that are involved in this
* multi-part txn.
*/
public void setStateForDurability(Iv2InitiateTaskMessage initiateTask,
Collection<Integer> involvedPartitions) {
m_initiateTask = initiateTask;
m_involvedPartitions = ImmutableSet.copyOf(involvedPartitions);
m_initiateTaskBuffer = ByteBuffer.allocate(initiateTask.getSerializedSize());
try {
initiateTask.flattenToBuffer(m_initiateTaskBuffer);
m_initiateTaskBuffer.flip();
} catch (IOException e) {
//Executive decision, don't throw a checked exception. Let it burn.
throw new RuntimeException(e);
}
}
public Iv2InitiateTaskMessage getInitiateTask() {
return m_initiateTask;
}
public Set<Integer> getInvolvedPartitions() { return m_involvedPartitions; }
public byte[] getPlanHash(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
return item.m_planHash;
}
public int getOutputDepId(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
return item.m_outputDepId;
}
public ByteBuffer getParameterDataForFragment(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
return item.m_parameterSet.asReadOnlyBuffer();
}
public ParameterSet getParameterSetForFragment(int index) {
ParameterSet params = null;
final ByteBuffer paramData = m_items.get(index).m_parameterSet.asReadOnlyBuffer();
if (paramData != null) {
try {
params = ParameterSet.fromByteBuffer(paramData);
}
catch (final IOException e) {
hostLog.l7dlog(Level.FATAL,
LogKeys.host_ExecutionSite_FailedDeserializingParamsForFragmentTask.name(), e);
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
}
else {
params = ParameterSet.emptyParameterSet();
}
return params;
}
public byte[] getFragmentPlan(int index) {
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
assert(item != null);
return item.m_fragmentPlan;
}
/*
* Serialization Format [description: type: byte count]
*
* Fixed header:
* item count (nitems): short: 2
* unplanned item count (nunplanned): short: 2
* final flag: byte: 1
* task type: byte: 1
* should undo flag: byte: 1
* output dependencies flag (outdep): byte: 1
* input dependencies flag (indep): byte: 1
*
* Fragment ID block (1 per item):
* fragment ID: long: 8 * nitems
*
* Procedure name: byte: length of the name string.
*
* voltExecuteIndex: short: 2
*
* batchIndexBase: short: 2
*
* Parameter set block (1 per item):
* parameter buffer size: int: 4 * nitems
* parameter buffer: bytes: ? * nitems
*
* Output dependency block (1 per item if outdep == 1):
* output dependency ID: int: 4 * nitems
*
* Input dependency block (1 per item if indep == 1):
* ID count: short: 2 * nitems
* input dependency ID sub-block (1 per ID):
* input dependency ID: int: 4 * ? * nitems
*
* Unplanned block (1 of each per unplanned item):
* item index: short: 2 * nunplanned
* fragment plan string length: int: 4 * nunplanned
* fragment plan string: bytes: ? * nunplanned
*/
@Override
public int getSerializedSize()
{
assert(m_items != null);
assert(!m_items.isEmpty());
int msgsize = super.getSerializedSize();
// Fixed header
msgsize += 2 + 2 + 1 + 1 + 1 + 1 + 1;
// Fragment ID block (20 bytes per sha1-hash)
msgsize += 20 * m_items.size();
// short + str for proc name
msgsize += 2;
if (m_procedureName != null) {
msgsize += m_procedureName.length;
}
// int for which batch (4)
msgsize += 4;
// Involved partitions
msgsize += 2 + m_involvedPartitions.size() * 4;
//nested initiate task message length prefix
msgsize += 4;
if (m_initiateTaskBuffer != null) {
msgsize += m_initiateTaskBuffer.remaining();
}
// Make a pass through the fragment data items to account for the
// optional output and input dependency blocks, plus the unplanned block.
boolean foundOutputDepId = false;
boolean foundInputDepIds = false;
for (FragmentData item : m_items) {
// Account for parameter sets
msgsize += 4 + item.m_parameterSet.remaining();
// Account for the optional output dependency block, if needed.
if (!foundOutputDepId && item.m_outputDepId != null) {
msgsize += 4 * m_items.size();
foundOutputDepId = true;
}
// Account for the optional input dependency block, if needed.
if (item.m_inputDepIds != null) {
if (!foundInputDepIds) {
// Account for the size short for each item now that we know
// that the optional block is needed.
msgsize += 2 * m_items.size();
foundInputDepIds = true;
}
// Account for the input dependency IDs themselves, if any.
msgsize += 4 * item.m_inputDepIds.size();
}
// Each unplanned item gets an index (2) and a size (4) and buffer for
// the fragment plan string.
if (item.m_fragmentPlan != null) {
msgsize += 2 + 4 + item.m_fragmentPlan.length;
}
}
return msgsize;
}
@Override
public void flattenToBuffer(ByteBuffer buf) throws IOException
{
flattenToSubMessageBuffer(buf);
assert(buf.capacity() == buf.position());
buf.limit(buf.position());
}
/**
* Used directly by {@link FragmentTaskLogMessage} to embed FTMs
*/
void flattenToSubMessageBuffer(ByteBuffer buf) throws IOException
{
// See Serialization Format comment above getSerializedSize().
assert(m_items != null);
assert(!m_items.isEmpty());
buf.put(VoltDbMessageFactory.FRAGMENT_TASK_ID);
super.flattenToBuffer(buf);
// Get useful statistics for the header and optional blocks.
short nInputDepIds = 0;
short nOutputDepIds = 0;
short nUnplanned = 0;
for (FragmentData item : m_items) {
if (item.m_inputDepIds != null) {
// Supporting only one input dep id for now.
nInputDepIds++;
}
if (item.m_outputDepId != null) {
nOutputDepIds++;
}
if (item.m_fragmentPlan != null) {
nUnplanned++;
}
}
// Header block
buf.putShort((short) m_items.size());
buf.putShort(nUnplanned);
buf.put(m_isFinal ? (byte) 1 : (byte) 0);
buf.put(m_taskType);
buf.put(m_emptyForRestart ? (byte) 1 : (byte) 0);
buf.put(nOutputDepIds > 0 ? (byte) 1 : (byte) 0);
buf.put(nInputDepIds > 0 ? (byte) 1 : (byte) 0);
// Plan Hash block
for (FragmentData item : m_items) {
buf.put(item.m_planHash);
}
// Parameter set block
for (FragmentData item : m_items) {
buf.putInt(item.m_parameterSet.remaining());
buf.put(item.m_parameterSet.asReadOnlyBuffer());
}
// Optional output dependency ID block
if (nOutputDepIds > 0) {
for (FragmentData item : m_items) {
buf.putInt(item.m_outputDepId);
}
}
// Optional input dependency ID block
if (nInputDepIds > 0) {
for (FragmentData item : m_items) {
if (item.m_inputDepIds == null || item.m_inputDepIds.size() == 0) {
buf.putShort((short) 0);
} else {
buf.putShort((short) item.m_inputDepIds.size());
for (Integer inputDepId : item.m_inputDepIds) {
buf.putInt(inputDepId);
}
}
}
}
// write procedure name
if (m_procedureName == null) {
buf.putShort((short) -1);
}
else {
assert(m_procedureName.length <= Short.MAX_VALUE);
buf.putShort((short) m_procedureName.length);
buf.put(m_procedureName);
}
// ints for batch context
buf.putInt(m_currentBatchIndex);
buf.putShort((short) m_involvedPartitions.size());
for (int pid : m_involvedPartitions) {
buf.putInt(pid);
}
if (m_initiateTaskBuffer != null) {
ByteBuffer dup = m_initiateTaskBuffer.duplicate();
buf.putInt(dup.remaining());
buf.put(dup);
} else {
buf.putInt(0);
}
// Unplanned item block
for (short index = 0; index < m_items.size(); index++) {
// Each unplanned item gets an index (2) and a size (4) and buffer for
// the fragment plan string.
FragmentData item = m_items.get(index);
if (item.m_fragmentPlan != null) {
buf.putShort(index);
buf.putInt(item.m_fragmentPlan.length);
buf.put(item.m_fragmentPlan);
}
}
}
@Override
public void initFromBuffer(ByteBuffer buf) throws IOException
{
initFromSubMessageBuffer(buf);
assert(buf.capacity() == buf.position());
}
/**
* Used directly by {@link FragmentTaskLogMessage} to embed FTMs
*/
void initFromSubMessageBuffer(ByteBuffer buf) throws IOException
{
// See Serialization Format comment above getSerializedSize().
super.initFromBuffer(buf);
// Header block
short fragCount = buf.getShort();
assert(fragCount > 0);
short unplannedCount = buf.getShort();
assert(unplannedCount >= 0 && unplannedCount <= fragCount);
m_isFinal = buf.get() != 0;
m_taskType = buf.get();
m_emptyForRestart = buf.get() != 0;
boolean haveOutputDependencies = buf.get() != 0;
boolean haveInputDependencies = buf.get() != 0;
m_items = new ArrayList<FragmentData>(fragCount);
// Fragment ID block (creates the FragmentData objects)
for (int i = 0; i < fragCount; i++) {
FragmentData item = new FragmentData();
item.m_planHash = new byte[20]; // sha1 is 20b
buf.get(item.m_planHash);
m_items.add(item);
}
// Parameter set block
for (FragmentData item : m_items) {
int paramsbytecount = buf.getInt();
item.m_parameterSet = ByteBuffer.allocate(paramsbytecount);
int cachedLimit = buf.limit();
buf.limit(buf.position() + item.m_parameterSet.remaining());
item.m_parameterSet.put(buf);
item.m_parameterSet.flip();
buf.limit(cachedLimit);
}
// Optional output dependency block
if (haveOutputDependencies) {
for (FragmentData item : m_items) {
item.m_outputDepId = buf.getInt();
}
}
// Optional input dependency block
if (haveInputDependencies) {
for (FragmentData item : m_items) {
short count = buf.getShort();
if (count > 0) {
item.m_inputDepIds = new ArrayList<Integer>(count);
for (int j = 0; j < count; j++) {
item.m_inputDepIds.add(buf.getInt());
m_inputDepCount++;
}
}
}
}
// read procedure name if there
short procNameLen = buf.getShort();
if (procNameLen >= 0) {
m_procedureName = new byte[procNameLen];
buf.get(m_procedureName);
}
else {
m_procedureName = null;
}
// ints for batch context
m_currentBatchIndex = buf.getInt();
// Involved partition
short involvedPartitionCount = buf.getShort();
ImmutableSet.Builder<Integer> involvedPartitionsBuilder = ImmutableSet.builder();
for (int i = 0; i < involvedPartitionCount; i++) {
involvedPartitionsBuilder.add(buf.getInt());
}
m_involvedPartitions = involvedPartitionsBuilder.build();
int initiateTaskMessageLength = buf.getInt();
if (initiateTaskMessageLength > 0) {
int startPosition = buf.position();
Iv2InitiateTaskMessage message = new Iv2InitiateTaskMessage();
// EHGAWD: init task was serialized with flatten which added
// the message type byte. deserialization expects the message
// factory to have stripped that byte. but ... that's not the
// way we do it here. So read the message type byte...
byte messageType = buf.get();
assert(messageType == VoltDbMessageFactory.IV2_INITIATE_TASK_ID);
message.initFromBuffer(buf);
m_initiateTask = message;
if (m_initiateTask != null && m_initiateTaskBuffer == null) {
m_initiateTaskBuffer = ByteBuffer.allocate(m_initiateTask.getSerializedSize());
try {
m_initiateTask.flattenToBuffer(m_initiateTaskBuffer);
m_initiateTaskBuffer.flip();
} catch (IOException e) {
//Executive decision, don't throw a checked exception. Let it burn.
throw new RuntimeException(e);
}
}
/*
* There is an assertion that all bytes of the message are consumed.
* Initiate task lazily deserializes the parameter buffer and doesn't consume
* all the bytes so do it here so the assertion doesn't trip
*/
buf.position(startPosition + initiateTaskMessageLength);
}
// Unplanned block
for (int iUnplanned = 0; iUnplanned < unplannedCount; iUnplanned++) {
short index = buf.getShort();
assert(index >= 0 && index < m_items.size());
FragmentData item = m_items.get(index);
int fragmentPlanLength = buf.getInt();
if (fragmentPlanLength > 0) {
item.m_fragmentPlan = new byte[fragmentPlanLength];
buf.get(item.m_fragmentPlan);
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("FRAGMENT_TASK (FROM ");
sb.append(CoreUtils.hsIdToString(m_coordinatorHSId));
sb.append(") FOR TXN ");
sb.append(m_txnId);
sb.append(" FOR REPLAY ").append(isForReplay());
sb.append(", SP HANDLE: ").append(getSpHandle());
sb.append("\n");
if (m_isReadOnly)
sb.append(" READ, COORD ");
else
sb.append(" WRITE, COORD ");
sb.append(CoreUtils.hsIdToString(m_coordinatorHSId));
if (!m_emptyForRestart) {
for (FragmentData item : m_items) {
sb.append("\n=====\n");
sb.append(item.toString());
}
}
else {
sb.append("\n=====\n");
sb.append(" FRAGMENT EMPTY FOR RESTART SERIALIZATION");
}
if (m_isFinal)
sb.append("\n THIS IS THE FINAL TASK");
if (m_taskType == USER_PROC)
{
sb.append("\n THIS IS A USER TASK");
}
else if (m_taskType == SYS_PROC_PER_PARTITION)
{
sb.append("\n THIS IS A SYSPROC RUNNING PER PARTITION");
}
else if (m_taskType == SYS_PROC_PER_SITE)
{
sb.append("\n THIS IS A SYSPROC TASK RUNNING PER EXECUTION SITE");
}
else
{
sb.append("\n UNKNOWN FRAGMENT TASK TYPE");
}
if (m_emptyForRestart)
sb.append("\n THIS IS A NULL FRAGMENT TASK USED FOR RESTART");
return sb.toString();
}
public boolean isEmpty() {
return m_items.isEmpty();
}
}
|
package com.streamsets.pipeline.creation;
import com.streamsets.pipeline.api.ConfigDef;
import com.streamsets.pipeline.api.ConfigGroups;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.ValueChooser;
import com.streamsets.pipeline.config.DeliveryGuarantee;
import com.streamsets.pipeline.config.DeliveryGuaranteeChooserValues;
import com.streamsets.pipeline.config.ErrorHandlingChooserValues;
import com.streamsets.pipeline.config.ExecutionModeChooserValues;
import com.streamsets.pipeline.config.MemoryLimitExceeded;
import com.streamsets.pipeline.config.MemoryLimitExceededChooserValues;
import com.streamsets.pipeline.config.PipelineGroups;
import java.util.Collections;
import java.util.List;
import java.util.Map;
// we are using the annotation for reference purposes only.
// the annotation processor does not work on this maven project
// we have a hardcoded 'datacollector-resource-bundles.json' file in resources
@GenerateResourceBundle
@StageDef(version = "1.0.0", label = "Pipeline")
@ConfigGroups(PipelineGroups.class)
public class PipelineConfigBean implements Stage {
@ConfigDef(
required = true,
type = ConfigDef.Type.MODEL,
label = "Execution Mode",
defaultValue= "STANDALONE",
displayPosition = 10
)
@ValueChooser(ExecutionModeChooserValues.class)
public ExecutionMode executionMode;
@ConfigDef(
required = true,
type = ConfigDef.Type.MODEL,
defaultValue="AT_LEAST_ONCE",
label = "Delivery Guarantee",
displayPosition = 20
)
@ValueChooser(DeliveryGuaranteeChooserValues.class)
public DeliveryGuarantee deliveryGuarantee;
@ConfigDef(
required = true,
type = ConfigDef.Type.MODEL,
defaultValue="STOP_PIPELINE",
label = "Memory Limit Exceeded",
description = "Behavior when a pipeline has exceeded the " +
"memory limit. Use Metric Alerts to alert before this limit has been exceeded." ,
displayPosition = 30,
group = ""
)
@ValueChooser(MemoryLimitExceededChooserValues.class)
public MemoryLimitExceeded memoryLimitExceeded;
@ConfigDef(
required = true,
type = ConfigDef.Type.NUMBER,
label = "Memory Limit (MB)",
defaultValue = "${jvm:maxMemoryMB() * 0.65}",
description = "Maximum memory in MB a pipeline will be allowed to " +
"consume. Maximum and minimum values are based on SDC Java heap size.",
displayPosition = 40,
min = 128,
group = ""
)
public long memoryLimit;
@ConfigDef(
required = false,
type = ConfigDef.Type.MAP,
label = "Constants",
displayPosition = 10,
group = "CONSTANTS"
)
public Map<String, Object> constants;
@ConfigDef(
required = true,
type = ConfigDef.Type.MODEL,
label = "Error Records",
displayPosition = 10,
group = "BAD_RECORDS"
)
@ValueChooser(ErrorHandlingChooserValues.class)
public String badRecordsHandling;
@ConfigDef(
required = true,
type = ConfigDef.Type.NUMBER,
label = "Worker Memory (MB)",
defaultValue = "1024",
displayPosition = 10,
group = "CLUSTER",
dependsOn = "executionMode",
triggeredByValue = "CLUSTER"
)
public long clusterSlaveMemory;
@ConfigDef(
required = true,
type = ConfigDef.Type.STRING,
label = "Worker Java Options",
defaultValue = "-XX:PermSize=128M -XX:MaxPermSize=256M",
displayPosition = 20,
group = "CLUSTER",
dependsOn = "executionMode",
triggeredByValue = "CLUSTER"
)
public String clusterSlaveJavaOpts;
@ConfigDef(
required = true,
type = ConfigDef.Type.BOOLEAN,
label = "Kerberos Authentication",
defaultValue = "false",
displayPosition = 30,
group = "CLUSTER",
dependsOn = "executionMode",
triggeredByValue = "CLUSTER"
)
public boolean clusterKerberos;
@ConfigDef(
required = true,
type = ConfigDef.Type.STRING,
label = "Kerberos Principal",
displayPosition = 40,
group = "CLUSTER",
dependsOn = "clusterKerberos",
triggeredByValue = "true"
)
public String kerberosPrincipal;
@ConfigDef(
required = true,
type = ConfigDef.Type.STRING,
label = "Kerberos Keytab (file)",
displayPosition = 50,
group = "CLUSTER",
dependsOn = "clusterKerberos",
triggeredByValue = "true"
)
public String kerberosKeytab;
@ConfigDef(
required = false,
type = ConfigDef.Type.MAP,
label = "Launcher ENV",
description = "Sets additional environment variables for the cluster launcher",
displayPosition = 60,
group = "CLUSTER",
dependsOn = "executionMode",
triggeredByValue = "CLUSTER"
)
public Map clusterLauncherEnv;
@Override
public List<ConfigIssue> validateConfigs(Info info, Context context) throws StageException {
return Collections.emptyList();
}
@Override
public void init(Info info, Context context) throws StageException {
}
@Override
public void destroy() {
}
}
|
package org.xins.common.service;
import java.util.Iterator;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.TimeOutController;
import org.xins.common.TimeOutException;
/**
* Abstraction of a service caller for a TCP-based service. Service caller
* implementations can be used to perform a call to a service, and potentially
* fail-over to other back-ends if one is not available. Additionally,
* load-balancing and different types of time-outs are supported.
*
* <p>Back-ends are
* represented by {@link TargetDescriptor} instances. Groups of back-ends are
* represented by {@link GroupDescriptor} instances.
*
* <a name="section-lbfo"></a>
* <h2>Load-balancing and fail-over</h2>
*
* <p>TODO: Describe load-balancing and fail-over.
*
* <a name="section-timeouts"></a>
* <h2>Time-outs</h2>
*
* <p>TODO: Describe time-outs.
*
* <a name="section-callconfig"></a>
* <h2>Call configuration</h2>
*
* <p>Some aspects of a call can be configured using a {@link CallConfig}
* object. For example, the <code>CallConfig</code> base class indicates
* whether fail-over is unconditionally allowed. Like this, some aspects of
* the behaviour of the caller can be tweaked.
*
* <p>There are different places where a <code>CallConfig</code> can be
* applied:
*
* <ul>
* <li>stored in a <code>ServiceCaller</code>;
* <li>stored in a <code>CallRequest</code>;
* <li>passed with the call method.
* </ul>
*
* <p>First of all, each <code>ServiceCaller</code> instance will have a
* fall-back <code>CallConfig</code>.
*
* <p>Secondly, a {@link CallRequest} instance may have a
* <code>CallConfig</code> associated with it as well. If it does, then this
* overrides the one on the <code>ServiceCaller</code> instance.
*
* <p>Finally, a <code>CallConfig</code> can be passed as an argument to the
* call method. If it is, then this overrides any other settings.
*
* <a name="section-implementations"></a>
* <h2>Implementations</h2>
*
* <p>This class is abstract and is intended to be have service-specific
* subclasses, e.g. for HTTP, FTP, JDBC, etc.
*
* <p>Normally, a subclass should be stick to the following rules:
*
* <ol>
* <li>There should be a constructor that accepts only a {@link Descriptor}
* object. This constructor should call
* <code>super(descriptor, null)</code>.
* <li>There should be a constructor that accepts both a
* {@link Descriptor} and a service-specific call config object
* (derived from {@link CallConfig}). This constructor should call
* <code>super(descriptor, callConfig)</code>.
* <li>There should be a <code>call</code> method that accepts only a
* service-specific request object (derived from {@link CallRequest}).
* It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, null)</code>.
* <li>There should be a <code>call</code> method that accepts both a
* service-specific request object (derived from {@link CallRequest}).
* and a service-specific call config object (derived from
* {@link CallConfig}). It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, callConfig)</code>.
* <li>There should be a <code>call</code> method that accepts both a
* service-specific request object (derived from {@link CallRequest}).
* and a service-specific call config object (derived from
* {@link CallConfig}). It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, callConfig)</code>.
* <li>The method
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} must
* be implemented as specified.
* <li>The {@link #createCallResult(CallRequest,TargetDescriptor,long,CallExceptionList,Object) createCallResult}
* method must be implemented as specified.
* <li>To control when fail-over is applied, the method
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* may also be implemented. The implementation can assume that
* the passed {@link CallRequest} object is an instance of the
* service-specific call request class and that the passed
* {@link CallConfig} object is an instance of the service-specific
* call config class.
* </ol>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
public abstract class ServiceCaller extends Object {
// TODO: Describe typical implementation scenario, e.g. a
// SpecificCallResult call(SpecificCallRequest, SpecificCallConfig)
// method that calls doCall(CallRequest,CallConfig).
// Class fields
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = ServiceCaller.class.getName();
// Class functions
// Constructors
protected ServiceCaller(Descriptor descriptor)
throws IllegalArgumentException {
this(descriptor, null);
}
protected ServiceCaller(Descriptor descriptor, CallConfig callConfig)
throws IllegalArgumentException {
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("descriptor", descriptor);
// If no CallConfig is specified, then use a default one
if (callConfig == null) {
String actualClass = getClass().getName();
// Get the default config
try {
callConfig = getDefaultCallConfig();
// No exception should be thrown by getDefaultCallConfig()
} catch (Throwable t) {
Log.log_1052(t, actualClass, "getDefaultCallConfig()");
throw new Error(actualClass + ".getDefaultCallConfig() has thrown an unexpected " + t.getClass().getName() + '.', t);
}
// And getDefaultCallConfig() should never return null
if (callConfig == null) {
String detail = "Method returned null, although that is disallowed by the ServiceCaller.getDefaultCallConfig() contract.";
Log.log_1050(actualClass, "getDefaultCallConfig()", detail);
throw new Error(detail);
}
}
// Set fields
_descriptor = descriptor;
_callConfig = callConfig;
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
// Fields
/**
* The descriptor for this service. Cannot be <code>null</code>.
*/
private final Descriptor _descriptor;
/**
* The fall-back call config object for this service caller. Cannot be
* <code>null</code>.
*/
private final CallConfig _callConfig;
// Methods
/**
* Returns the descriptor.
*
* @return
* the descriptor for this service, never <code>null</code>.
*/
public final Descriptor getDescriptor() {
return _descriptor;
}
/**
* Returns the <code>CallConfig</code> associated with this service caller.
*
* @return
* the fall-back {@link CallConfig} object for this service caller,
* never <code>null</code>.
*
* @since XINS 1.1.0
*/
public final CallConfig getCallConfig() {
return _callConfig;
}
/**
* Returns a default <code>CallConfig</code> object. This method is called
* by the <code>ServiceCaller</code> constructor if no
* <code>CallConfig</code> object was given.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns a standard {@link CallConfig} object which has unconditional
* fail-over disabled.
*
* <p>Subclasses are free to override this method to return a more suitable
* <code>CallConfig</code> instance.
*
* @return
* a new {@link CallConfig} instance, never <code>null</code>.
*
* @since XINS 1.1.0
*/
protected CallConfig getDefaultCallConfig() {
return new CallConfig();
}
protected final CallResult doCall(CallRequest request,
CallConfig callConfig)
throws IllegalArgumentException, CallException {
final String METHODNAME = "doCall(CallRequest,CallConfig)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, METHODNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Determine what config to use. The argument has priority, then the one
// associated with the request and the fall-back is the one associated
// with this service caller.
if (callConfig == null) {
callConfig = request.getCallConfig();
if (callConfig == null) {
callConfig = _callConfig;
}
}
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// There should be at least one target
if (! iterator.hasNext()) {
String message = "Unexpected situation: " + _descriptor.getClass().getName() + " contains no target descriptors.";
Log.log_1050(_descriptor.getClass().getName(), "iterateTargets()", message);
throw new Error(message);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, callConfig, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
Log.log_1050(getClass().getName(), "doCallImpl(CallRequest,CallConfig,TargetDescriptor)", "The method is not implemented although it should be.");
throw new Error(getClass().getName() + ".doCallImpl(CallRequest,CallConfig,TargetDescriptor) is not implemented although it should be, according to the ServiceCaller class contract.");
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, exception);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, METHODNAME, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, METHODNAME, null);
throw first;
}
protected final CallResult doCall(CallRequest request)
throws IllegalArgumentException, CallException {
final String METHODNAME = "doCall(CallRequest)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, METHODNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// There should be at least one target
if (! iterator.hasNext()) {
String message = "Unexpected situation: " + _descriptor.getClass().getName() + " contains no target descriptors.";
Log.log_1050(_descriptor.getClass().getName(), "iterateTargets()", message);
throw new Error(message);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
Log.log_1050(getClass().getName(), "doCallImpl(CallRequest,CallConfig,TargetDescriptor)", "The method is not implemented although it should be.");
throw new Error(getClass().getName() + ".doCallImpl(CallRequest,TargetDescriptor) is not implemented although it should be, according to the ServiceCaller class contract.");
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, exception);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, METHODNAME, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, METHODNAME, null);
throw first;
}
protected Object doCallImpl(CallRequest request,
CallConfig callConfig,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
protected Object doCallImpl(CallRequest request,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
/**
* Constructs an appropriate <code>CallResult</code> object for a
* successful call attempt. This method is called from
* {@link #doCall(CallRequest)}.
*
* @param request
* the {@link CallRequest} that was to be executed, never
* <code>null</code> when called from {@link #doCall(CallRequest)}.
*
* @param succeededTarget
* the {@link TargetDescriptor} for the service that was successfully
* called, never <code>null</code> when called from
* {@link #doCall(CallRequest)}.
*
* @param duration
* the call duration in milliseconds, guaranteed to be a non-negative
* number when called from {@link #doCall(CallRequest)}.
*
* @param exceptions
* the list of {@link CallException} instances, or <code>null</code> if
* there were no call failures.
*
* @param result
* the result from the call, which is the object returned by
* {@link #doCallImpl(CallRequest,TargetDescriptor)}, can be
* <code>null</code>.
*
* @return
* a {@link CallResult} instance, never <code>null</code>.
*
* @throws ClassCastException
* if <code>request</code> and/or <code>result</code> are not of the
* correct class.
*/
protected abstract CallResult createCallResult(CallRequest request,
TargetDescriptor succeededTarget,
long duration,
CallExceptionList exceptions,
Object result)
throws ClassCastException;
protected final void controlTimeOut(Runnable task,
TargetDescriptor descriptor)
throws IllegalArgumentException,
IllegalThreadStateException,
SecurityException,
TimeOutException {
// Check preconditions
MandatoryArgumentChecker.check("task", task,
"descriptor", descriptor);
// Determine the total time-out
int totalTimeOut = descriptor.getTotalTimeOut();
// If there is no total time-out, then execute the task on this thread
if (totalTimeOut < 1) {
task.run();
// Otherwise a time-out controller will be used
} else {
TimeOutController.execute(task, totalTimeOut);
}
}
/**
* Determines whether a call should fail-over to the next selected target.
* This method should only be called from {@link #doCall(CallRequest)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if <code>exception instanceof
* {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param exception
* the exception caught while calling the most recently called target,
* should not be <code>null</code>.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @deprecated
* Deprecated since XINS 1.1.0. Implement
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* instead of this method. Although deprecated, this method still works
* the same as in XINS 1.0.x.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected boolean shouldFailOver(CallRequest request,
Throwable exception) {
return (exception instanceof ConnectionCallException);
}
/**
* Determines whether a call should fail-over to the next selected target
* based on a request, call configuration and exception list.
* This method should only be called from
* {@link #doCall(CallRequest,CallConfig)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if
* <code>callConfig.{@link CallConfig#isFailOverAllowed() isFailOverAllowed()} || exception instanceof {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param callConfig
* the call config that is currently in use, never <code>null</code>.
*
* @param exceptions
* the current list of {@link CallException}s; never
* <code>null</code>; get the most recent one by calling
* <code>exceptions.</code>{@link CallExceptionList#last() last()}.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @since XINS 1.1.0
*/
protected boolean shouldFailOver(CallRequest request,
CallConfig callConfig,
CallExceptionList exceptions) {
return callConfig.isFailOverAllowed()
|| (exceptions.last() instanceof ConnectionCallException);
}
// Inner classes
/**
* Error used to indicate a method should be implemented in a subclass, but
* is not. Specifically, this is used for the
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} method.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
private static final class MethodNotImplementedError extends Error {
// Constructors
/**
* Constructs a new <code>MethodNotImplementedError</code>.
*/
private MethodNotImplementedError() {
// empty
}
// Fields
// Methods
}
}
|
package org.xins.server;
import javax.servlet.ServletRequest;
import org.xins.types.TypeValueException;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.io.FastStringWriter;
import org.xins.util.text.FastStringBuffer;
import org.znerd.xmlenc.XMLOutputter;
import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
/**
* Context for a function call. Objects of this kind are passed with a
* function call.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public final class CallContext
extends Object
implements Responder, Log {
// Class fields
/**
* The fully-qualified name of this class.
*/
private static final String FQCN = CallContext.class.getName();
// Class functions
/**
* Returns the text to prefix to all log messages for the specified
* function and the specified call identifier.
*
* @param functionName
* the name of the function, should not be <code>null</code>.
*
* @param callID
* the call identifier.
*
* @return
* the prefix for log messages, never <code>null</code>.
*/
static final String getLogPrefix(String functionName, int callID) {
FastStringBuffer buffer = new FastStringBuffer(50);
buffer.append("Call ");
buffer.append(functionName);
buffer.append(':');
buffer.append(callID);
buffer.append(": ");
return buffer.toString();
}
// Constructors
CallContext(ServletRequest request, long start, Function function, int callID, Session session)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("request", request, "function", function);
// Initialize fields
_request = request;
_start = start;
_api = function.getAPI();
_function = function;
_functionName = function.getName();
_session = session;
_state = BEFORE_START;
_builder = new CallResultBuilder();
// Determine the function object, logger, call ID and log prefix
_logger = _function.getLogger();
_callID = callID;
_logPrefix = getLogPrefix(_functionName, _callID);
}
// Fields
/**
* The API for which this CallContext is used. This field is initialized by
* the constructor and can never be <code>null</code>.
*/
private final API _api;
/**
* The original servlet request.
*/
private final ServletRequest _request;
/**
* The call result builder. Cannot be <code>null</code>.
*/
private final CallResultBuilder _builder;
/**
* The start time of the call, as a number of milliseconds since midnight
* January 1, 1970 UTC.
*/
private final long _start;
/**
* The current state.
*/
private ResponderState _state;
/**
* The number of element tags currently open within the data section.
*/
private int _elementDepth;
/**
* The name of the function currently being called. Can be set to
* <code>null</code>.
*/
private final String _functionName;
/**
* The function currently being called. Can be set to <code>null</code>.
*/
private final Function _function;
/**
* The logger associated with the function. This field is set if and only
* if {@link #_function} is set.
*/
private final Logger _logger;
/**
* The log prefix for log messages.
*/
private final String _logPrefix;
/**
* The session for this call.
*/
private Session _session;
/**
* Flag that indicates if the session ID should be added as a parameter to
* the response.
*/
private boolean _returnSessionID;
/**
* The call ID, unique in the context of the pertaining function.
*/
private final int _callID;
// Methods
// TODO: Document
// TODO: Probably take a different approach
CallResult getCallResult() {
if (_builder.isSuccess() && _returnSessionID) {
_builder.param("_session", _session.getIDString());
_returnSessionID = false;
}
return _builder;
}
/**
* Returns the start time of the call.
*
* @return
* the timestamp indicating when the call was started, as a number of
* milliseconds since midnight January 1, 1970 UTC.
*/
public long getStart() {
return _start;
}
/**
* Returns the stored success indication. The default is <code>true</code>
* and it will <em>only</em> be set to <code>false</code> if and only if
* {@link #startResponse(boolean,String)} is called with the first
* parameter (<em>success</em>) set to <code>false</code>.
*
* @return
* the success indication.
*
* @since XINS 0.128
*/
public final boolean isSuccess() {
return _builder.isSuccess();
}
/**
* Returns the stored return code. The default is <code>null</code>
* and it will <em>only</em> be set to something else if and only if
* {@link #startResponse(boolean,String)} is called with the second
* parameter (<em>code</em>) set to a non-<code>null</code>, non-empty
* value.
*
* @return
* the return code, can be <code>null</code>.
*/
final String getCode() {
return _builder.getCode();
}
public Session getSession() throws IllegalStateException {
// Check preconditions
if (_function.isSessionBased() == false) {
throw new IllegalStateException("The function " + _functionName + " is not session-based.");
}
// Get the session
return _session;
}
/**
* Creates a session, stores it and remembers that it will have to be
* returned in the result.
*
* @return
* the constructed session, cannot be <code>null</code>.
*/
public Session createSession() {
// Create the session
Session session = _api.createSession();
// Store the session and remember that we have to send it down
_session = session;
_returnSessionID = true;
return session;
}
public String getParameter(String name)
throws IllegalArgumentException {
// Check arguments
if (name == null) {
throw new IllegalArgumentException("name == null");
}
// XXX: In a later version, support a parameter named 'function'
if (_request != null && name.length() > 0 && !"function".equals(name) && name.charAt(0) != '_') {
String value = _request.getParameter(name);
return "".equals(value) ? null : value;
}
return null;
}
/**
* Returns the assigned call ID. This ID is unique within the context of
* the pertaining function. If no call ID is assigned, then <code>-1</code>
* is returned.
*
* @return
* the assigned call ID for the function, or <code>-1</code> if none is
* assigned.
*/
public int getCallID() {
return _callID;
}
public final void startResponse(ResultCode resultCode)
throws IllegalStateException, InvalidResponseException {
if (resultCode == null) {
startResponse(true, null);
} else {
startResponse(false, resultCode.getValue());
}
}
public final void startResponse(boolean success)
throws IllegalStateException, InvalidResponseException {
startResponse(success, null);
}
public final void startResponse(boolean success, String returnCode)
throws IllegalStateException, InvalidResponseException {
// Check state
if (_state != BEFORE_START) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Temporarily enter the ERROR state
_state = ERROR;
_builder.startResponse(success, returnCode);
// Add the session ID, if any
if (success && _returnSessionID) {
_builder.param("_session", _session.getIDString());
_returnSessionID = false;
}
// Reset the state
_state = WITHIN_PARAMS;
}
public final void param(String name, String value)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException {
// Check state
if (_state != BEFORE_START && _state != WITHIN_PARAMS) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Check arguments
MandatoryArgumentChecker.check("name", name, "value", value);
// TODO: Disallow parameters that start with an underscore?
// Start the response if necesary
if (_state == BEFORE_START) {
startResponse(true, null);
}
// Temporarily enter the ERROR state
_state = ERROR;
// Set the parameter
_builder.param(name, value);
// Reset the state
_state = WITHIN_PARAMS;
}
public final void startTag(String type)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException {
// Check state
if (_state == AFTER_END) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Check argument
if (type == null) {
throw new IllegalArgumentException("type == null");
} else if (type.length() == 0) {
throw new IllegalArgumentException("type.equals(\"\")");
}
// Start the response if necesary
if (_state == BEFORE_START) {
startResponse(true, null);
}
// Temporarily enter the ERROR state
_state = ERROR;
// Write the start tag
_builder.startTag(type);
_elementDepth++;
// Reset the state
_state = START_TAG_OPEN;
}
public final void attribute(String name, String value)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException {
// Check state
if (_state != START_TAG_OPEN) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Temporarily enter the ERROR state
_state = ERROR;
// Write the attribute
_builder.attribute(name, value);
// Reset the state
_state = START_TAG_OPEN;
}
public final void pcdata(String text)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException {
// Check state
if (_state != START_TAG_OPEN && _state != WITHIN_ELEMENT) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Temporarily enter the ERROR state
_state = ERROR;
// Write the PCDATA
_builder.pcdata(text);
// Reset the state
_state = WITHIN_ELEMENT;
}
public final void endTag()
throws IllegalStateException, InvalidResponseException {
// Check state
if (_state != START_TAG_OPEN && _state != WITHIN_ELEMENT) {
throw new IllegalStateException("The state is " + _state + '.');
}
if (_elementDepth == 0) {
throw new IllegalStateException("There are no more elements in the data section to close.");
}
// Temporarily enter the ERROR state
_state = ERROR;
// End the tag
_builder.endTag();
_elementDepth
// Reset the state
_state = WITHIN_ELEMENT;
}
public void fail(ResultCode resultCode)
throws IllegalArgumentException, IllegalStateException, InvalidResponseException {
fail(resultCode, null);
}
public void fail(ResultCode resultCode, String message)
throws IllegalArgumentException, IllegalStateException, InvalidResponseException {
// Check state
if (_state != BEFORE_START) {
throw new IllegalStateException("The state is " + _state + '.');
}
// Start response
if (resultCode == null) {
startResponse(false);
} else {
startResponse(resultCode);
}
// Include the message, if any
if (message != null) {
param("_message", message);
}
// End response
endResponse();
}
public final void endResponse() throws InvalidResponseException {
// Short-circuit if the response is already ended
if (_state == AFTER_END) {
return;
}
// Start the response if necesary
if (_state == BEFORE_START) {
startResponse(true, null);
}
// Temporarily enter the ERROR state
_state = ERROR;
// Close all open elements
_builder.endResponse();
// Set the state
_state = AFTER_END;
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void trace(Object message) {
_logger.log(FQCN, Priority.DEBUG, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void trace(Object message, Throwable t) {
_logger.log(FQCN, Priority.DEBUG, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void debug(Object message) {
_logger.log(FQCN, Priority.DEBUG, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void debug(Object message, Throwable t) {
_logger.log(FQCN, Priority.DEBUG, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void info(Object message) {
_logger.log(FQCN, Priority.INFO, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void info(Object message, Throwable t) {
_logger.log(FQCN, Priority.INFO, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void warn(Object message) {
_logger.log(FQCN, Priority.WARN, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void warn(Object message, Throwable t) {
_logger.log(FQCN, Priority.WARN, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void error(Object message) {
_logger.log(FQCN, Priority.ERROR, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void error(Object message, Throwable t) {
_logger.log(FQCN, Priority.ERROR, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void fatal(Object message) {
_logger.log(FQCN, Priority.FATAL, _logPrefix + message, null);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public void fatal(Object message, Throwable t) {
_logger.log(FQCN, Priority.FATAL, _logPrefix + message, t);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isDebugEnabled() {
return _logger.isDebugEnabled();
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isErrorEnabled() {
return _logger.isEnabledFor(Priority.ERROR);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isFatalEnabled() {
return _logger.isEnabledFor(Priority.FATAL);
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isInfoEnabled() {
return _logger.isInfoEnabled();
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isTraceEnabled() {
return _logger.isDebugEnabled();
}
/**
* @deprecated
* Deprecated since XINS 0.157 with no replacement. Use <em>logdoc</em>
* instead.
*/
public boolean isWarnEnabled() {
return _logger.isEnabledFor(Priority.WARN);
}
}
|
package com.cbien.android.sdk;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import com.cbien.sdk.CBienSDk;
public class CBienKit extends CordovaPlugin {
String clientId;
String clientSecret;
boolean inproduction;
String uniqueIdentifier;
String refreshToken;
String primaryColor;
String secondaryColor;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
clientId = preferences.getString("cbien-android-clientid", null);
clientSecret = preferences.getString("cbien-android-clientsecret", null);
inproduction = Boolean.valueOf(preferences.getString("cbien-android-inproduction", "false"));
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
callbackContext.success();
if (action.equals("initialize")) {
this.uniqueIdentifier = args.getJSONObject(0).getString("uniqueIdentifier");
}
else if (action.equals("refreshTokenNeeded")) {
callbackContext.success(CBienSDk.needToken(cordova.getActivity()) ? 1 : 0);
}
else if (action.equals("setRefreshToken")) {
this.refreshToken = args.getJSONObject(0).getString("refreshToken");
}
else if (action.equals("configure")) {
this.primaryColor = args.getJSONObject(0).getString("primaryColor");
this.secondaryColor = args.getJSONObject(0).getString("secondaryColor");
}
else if (action.equals("show")) {
if(primaryColor == null || secondaryColor == null) {
CBienSDk.start(cordova.getActivity(),
clientId,
clientSecret,
inproduction,
uniqueIdentifier,
refreshToken);
}
else {
CBienSDk.start(cordova.getActivity(),
clientId,
clientSecret,
inproduction,
uniqueIdentifier,
refreshToken,
primaryColor,
secondaryColor);
}
}
return true;
}
}
|
package io.lumify.core.model.termMention;
import io.lumify.core.model.properties.LumifyProperties;
import io.lumify.core.security.LumifyVisibility;
import io.lumify.core.security.VisibilityTranslator;
import io.lumify.core.util.ClientApiConverter;
import io.lumify.web.clientapi.model.VisibilityJson;
import org.securegraph.*;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
public class TermMentionBuilder {
private static final String TERM_MENTION_VERTEX_ID_PREFIX = "TM_";
private Vertex sourceVertex;
private String propertyKey;
private long start = -1;
private long end = -1;
private String title;
private String conceptIri;
private VisibilityJson visibilityJson;
private String process;
private Vertex resolvedToVertex;
private Edge resolvedEdge;
public TermMentionBuilder() {
}
/**
* Copy an existing term mention.
*
* @param existingTermMention The term mention you would like to copy.
* @param sourceVertex The vertex that contains this term mention (ie Document, Html page, etc).
*/
public TermMentionBuilder(Vertex existingTermMention, Vertex sourceVertex) {
this.sourceVertex = sourceVertex;
this.propertyKey = LumifyProperties.TERM_MENTION_PROPERTY_KEY.getPropertyValue(existingTermMention);
this.start = LumifyProperties.TERM_MENTION_START_OFFSET.getPropertyValue(existingTermMention, 0);
this.end = LumifyProperties.TERM_MENTION_END_OFFSET.getPropertyValue(existingTermMention, 0);
this.title = LumifyProperties.TERM_MENTION_TITLE.getPropertyValue(existingTermMention, "");
this.conceptIri = LumifyProperties.TERM_MENTION_CONCEPT_TYPE.getPropertyValue(existingTermMention, "");
this.visibilityJson = LumifyProperties.TERM_MENTION_VISIBILITY_JSON.getPropertyValue(existingTermMention, "");
}
/**
* The start offset within the property text that this term mention appears.
*/
public TermMentionBuilder start(long start) {
this.start = start;
return this;
}
/**
* The end offset within the property text that this term mention appears.
*/
public TermMentionBuilder end(long end) {
this.end = end;
return this;
}
/**
* The property key of the {@link io.lumify.core.model.properties.LumifyProperties#TEXT} that this term mention references.
*/
public TermMentionBuilder propertyKey(String propertyKey) {
this.propertyKey = propertyKey;
return this;
}
/**
* Visibility JSON string. This will be applied to the newly created term.
*/
public TermMentionBuilder visibilityJson(String visibilityJsonString) {
return visibilityJson(visibilityJsonStringToJson(visibilityJsonString));
}
/**
* Visibility JSON object. This will be applied to the newly created term.
*/
public TermMentionBuilder visibilityJson(VisibilityJson visibilitySource) {
this.visibilityJson = visibilitySource;
return this;
}
private static VisibilityJson visibilityJsonStringToJson(String visibilityJsonString) {
if (visibilityJsonString == null) {
return new VisibilityJson();
}
if (visibilityJsonString.length() == 0) {
return new VisibilityJson();
}
return ClientApiConverter.toClientApi(visibilityJsonString, VisibilityJson.class);
}
/**
* If this is a resolved term mention. This allows setting that information.
*
* @param resolvedToVertex The vertex this term mention resolves to.
* @param resolvedEdge The edge that links the source vertex to the resolved vertex.
*/
public TermMentionBuilder resolvedTo(Vertex resolvedToVertex, Edge resolvedEdge) {
this.resolvedToVertex = resolvedToVertex;
this.resolvedEdge = resolvedEdge;
return this;
}
/**
* The process that created this term mention.
*/
public TermMentionBuilder process(String process) {
this.process = process;
return this;
}
/**
* The vertex that contains this term mention (ie Document, Html page, etc).
*/
public TermMentionBuilder sourceVertex(Vertex sourceVertex) {
this.sourceVertex = sourceVertex;
return this;
}
/**
* The title/text of this term mention. (ie Job Ferner, Paris, etc).
*/
public TermMentionBuilder title(String title) {
this.title = title;
return this;
}
/**
* The concept type of this term mention.
*/
public TermMentionBuilder conceptIri(String conceptIri) {
this.conceptIri = conceptIri;
return this;
}
/**
* Saves the term mention to the graph.
* <p/>
* The resulting graph for non-resolved terms will be:
* <p/>
* Source -- Has --> Term
* Vertex Mention
* <p/>
* The resulting graph for resolved terms will be:
* <p/>
* Source -- Has --> Term -- Resolved To --> Resolved
* Vertex Mention Vertex
*/
public Vertex save(Graph graph, VisibilityTranslator visibilityTranslator, Authorizations authorizations) {
checkNotNull(sourceVertex, "sourceVertex cannot be null");
checkNotNull(propertyKey, "propertyKey cannot be null");
checkNotNull(title, "title cannot be null");
checkArgument(title.length() > 0, "title cannot be an empty string");
checkNotNull(conceptIri, "conceptIri cannot be null");
checkArgument(conceptIri.length() > 0, "conceptIri cannot be an empty string");
checkNotNull(visibilityJson, "visibilityJson cannot be null");
checkNotNull(process, "process cannot be null");
checkArgument(process.length() > 0, "process cannot be an empty string");
checkArgument(start >= 0, "start must be greater than or equal to 0");
checkArgument(end >= 0, "start must be greater than or equal to 0");
String vertexId = createVertexId();
Visibility visibility = LumifyVisibility.and(visibilityTranslator.toVisibility(this.visibilityJson).getVisibility(), TermMentionRepository.VISIBILITY);
VertexBuilder vertexBuilder = graph.prepareVertex(vertexId, visibility);
LumifyProperties.TERM_MENTION_VISIBILITY_JSON.setProperty(vertexBuilder, this.visibilityJson, visibility);
LumifyProperties.TERM_MENTION_CONCEPT_TYPE.setProperty(vertexBuilder, this.conceptIri, visibility);
LumifyProperties.TERM_MENTION_TITLE.setProperty(vertexBuilder, this.title, visibility);
LumifyProperties.TERM_MENTION_START_OFFSET.setProperty(vertexBuilder, this.start, visibility);
LumifyProperties.TERM_MENTION_END_OFFSET.setProperty(vertexBuilder, this.end, visibility);
if (this.process != null) {
LumifyProperties.TERM_MENTION_PROCESS.setProperty(vertexBuilder, this.process, visibility);
}
if (this.propertyKey != null) {
LumifyProperties.TERM_MENTION_PROPERTY_KEY.setProperty(vertexBuilder, this.propertyKey, visibility);
}
if (this.resolvedEdge != null) {
LumifyProperties.TERM_MENTION_RESOLVED_EDGE_ID.setProperty(vertexBuilder, this.resolvedEdge.getId(), visibility);
}
Vertex termMentionVertex = vertexBuilder.save(authorizations);
String hasTermMentionId = vertexId + "_hasTermMention";
Edge termMentionEdge = graph.addEdge(hasTermMentionId, this.sourceVertex, termMentionVertex, LumifyProperties.TERM_MENTION_LABEL_HAS_TERM_MENTION, visibility, authorizations);
LumifyProperties.TERM_MENTION_VISIBILITY_JSON.setProperty(termMentionEdge, this.visibilityJson, visibility, authorizations);
if (this.resolvedToVertex != null) {
String resolvedToId = vertexId + "_resolvedTo";
Edge resolvedToEdge = graph.addEdge(resolvedToId, termMentionVertex, this.resolvedToVertex, LumifyProperties.TERM_MENTION_LABEL_RESOLVED_TO, visibility, authorizations);
LumifyProperties.TERM_MENTION_VISIBILITY_JSON.setProperty(resolvedToEdge, this.visibilityJson, visibility, authorizations);
}
return termMentionVertex;
}
private String createVertexId() {
return TERM_MENTION_VERTEX_ID_PREFIX
+ "-"
+ this.propertyKey
+ "-"
+ this.start
+ "-"
+ this.end
+ "-"
+ this.process;
}
}
|
package at.modalog.cordova.plugin.html2pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import android.R.bool;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.print.PrintDocumentAdapter.LayoutResultCallback;
import android.print.PrintAttributes.MediaSize;
//import android.print.PrintDocumentInfo;
//import android.print.PrintDocumentInfo.Builder;
import android.print.PrintDocumentAdapter.WriteResultCallback;
import android.os.CancellationSignal;
import android.os.Bundle;
import android.print.PageRange;
import android.os.ParcelFileDescriptor;
import android.print.pdf.PrintedPdfDocument;
import android.util.SparseIntArray;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;
import android.print.PrintAttributes.Resolution;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.printservice.PrintJob;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
@TargetApi(19)
public class Html2pdf extends CordovaPlugin
{
private static final String LOG_TAG = "Html2Pdf";
private CallbackContext callbackContext;
// change your path on the sdcard here
private String publicTmpDir = ".at.modalog.cordova.plugin.html2pdf"; // prepending a dot "." would make it hidden
private String tmpPdfName = "print.pdf";
// set to true to see the webview (useful for debugging)
private final boolean showWebViewForDebugging = true;
PrintedPdfDocument mPdfDocument;
WebView page;
int totalPages = 1;
/**
* Constructor.
*/
public Html2pdf() {
}
@Override
public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
try
{
if( action.equals("create") )
{
if( showWebViewForDebugging )
{
Log.v(LOG_TAG,"java create pdf from html called");
Log.v(LOG_TAG, "File: " + args.getString(1));
// Log.v(LOG_TAG, "Html: " + args.getString(0));
Log.v(LOG_TAG, "Html start:" + args.getString(0).substring(0, 30));
Log.v(LOG_TAG, "Html end:" + args.getString(0).substring(args.getString(0).length() - 30));
}
if( args.getString(1) != null && args.getString(1) != "null" )
this.tmpPdfName = args.getString(1);
final Html2pdf self = this;
final String content = args.optString(0, "<html></html>");
this.callbackContext = callbackContext;
cordova.getActivity().runOnUiThread( new Runnable() {
public void run()
{
if( Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ) // Android 4.4
{
/*
* None-Kitkat pdf creation (Android < 4.4)
* it will be a image based pdf
*/
self.loadContentIntoWebView(content);
}
else
{
/*
* Kitkat pdf creation by using the android print framework (Android >= 4.4)
*/
// Create a WebView object specifically for printing
page = new WebView(cordova.getActivity());
page.getSettings().setJavaScriptEnabled(false);
page.setDrawingCacheEnabled(true);
// Auto-scale the content to the webview's width.
page.getSettings().setLoadWithOverviewMode(true);
page.getSettings().setUseWideViewPort(true);
page.setInitialScale(0);
// Disable android text auto fit behaviour
page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
if( showWebViewForDebugging )
{
page.setVisibility(View.VISIBLE);
}
else {
page.setVisibility(View.INVISIBLE);
}
// self.cordova.getActivity().addContentView(webView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
page.setWebViewClient( new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView webView, String url)
{
/*PrintAttributes pdfPrintAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_MONOCHROME).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER.asLandscape()).
setResolution(new Resolution("zooey", Context.PRINT_SERVICE, 300, 300)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(self.cordova.getActivity(),pdfPrintAttrs);*/
PdfDocument documento = new PdfDocument();
PageInfo pageInfo = new PageInfo.Builder(595,842, 1).create();
Page pagina = documento.startPage(pageInfo);
pagina.getCanvas().setDensity(200);
//View content = (View) webView;
webView.draw(pagina.getCanvas());
documento.finishPage(pagina);
try{
File root = Environment.getExternalStorageDirectory();
File file = new File(root,"webview.pdf");
FileOutputStream out = new FileOutputStream(file);
doc.writeTo(out);
out.close();
doc.close();
} catch(Exception e){
throw new RuntimeException("Error generating file", e);
} finally {
//documento.close();
//documento = null;
}
// send success result to cordova
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
});//end webview client
// Reverse engineer base url (assets/www) from the cordova webView url
String baseURL = self.webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
// Load content into the print webview
if( showWebViewForDebugging )
{
cordova.getActivity().addContentView(page, new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null);
}
}
});
// send "no-result" result to delay result handling
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
return false;
}
catch (JSONException e)
{
// TODO: signal JSON problem to JS
//callbackContext.error("Problem with JSON");
return false;
}
}
/**
*
* Clean up and close all open files.
*
*/
@Override
public void onDestroy()
{
// ToDo: clean up.
}
// LOCAL METHODS
private void loadContentIntoWebView (String content)
{
Activity ctx = cordova.getActivity();
final WebView page = new Html2PdfWebView(ctx);
final Html2pdf self = this;
if( showWebViewForDebugging )
{
page.setVisibility(View.VISIBLE);
} else {
page.setVisibility(View.INVISIBLE);
}
page.getSettings().setJavaScriptEnabled(false);
page.setDrawingCacheEnabled(true);
page.getSettings().setLoadWithOverviewMode(false);
page.getSettings().setUseWideViewPort(false);
page.setInitialScale(100);
// Disable android text auto fit behaviour
page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
page.setWebViewClient( new WebViewClient() {
@Override
public void onPageFinished(final WebView page, String url) {
new Handler().postDelayed( new Runnable() {
@Override
public void run()
{
// slice the web screenshot into pages and save as pdf
Bitmap b = getWebViewAsBitmap(page);
if( b != null )
{
File tmpFile = self.saveWebViewAsPdf(b);
b.recycle();
// add pdf as stream to the print intent
Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW);
pdfViewIntent.setDataAndNormalize(Uri.fromFile(tmpFile));
pdfViewIntent.setType("application/pdf");
// remove the webview
if( !self.showWebViewForDebugging )
{
ViewGroup vg = (ViewGroup)(page.getParent());
vg.removeView(page);
}
// add file to media scanner
MediaScannerConnection.scanFile(
self.cordova.getActivity(),
new String[]{tmpFile.getAbsolutePath()},
null,
new OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.v(LOG_TAG, "file '" + path + "' was scanned seccessfully: " + uri);
}
}
);
// start the pdf viewer app (trigger the pdf view intent)
PluginResult result;
boolean success = false;
if( self.canHandleIntent(self.cordova.getActivity(), pdfViewIntent) )
{
try
{
self.cordova.startActivityForResult(self, pdfViewIntent, 0);
success = true;
}
catch( ActivityNotFoundException e )
{
success = false;
}
}
if( success )
{
// send success result to cordova
result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
else
{
// send error
result = new PluginResult(PluginResult.Status.ERROR, "activity_not_found");
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
}
}
}, 500);
}
});
// Set base URI to the assets/www folder
String baseURL = webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
/** We make it this small on purpose (is resized after page load has finished).
* Making it small in the beginning has some effects on the html <body> (body
* width will always remain 100 if not set explicitly).
*/
if( !showWebViewForDebugging )
{
ctx.addContentView(page, new ViewGroup.LayoutParams(100, 100));
}
else
{
ctx.addContentView(page, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null);
}
public static final String MIME_TYPE_PDF = "application/pdf";
/**
* Check if the supplied context can handle the given intent.
*
* @param context
* @param intent
* @return boolean
*/
public boolean canHandleIntent(Context context, Intent intent)
{
PackageManager packageManager = context.getPackageManager();
return (packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0);
}
/**
* Takes a WebView and returns a Bitmap representation of it (takes a "screenshot").
* @param WebView
* @return Bitmap
*/
public Bitmap getWebViewAsBitmap(WebView view)
{
Bitmap b;
// prepare drawing cache
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
//Get the dimensions of the view so we can re-layout the view at its current size
//and create a bitmap of the same size
int width = ((Html2PdfWebView) view).getContentWidth();
int height = view.getContentHeight();
if( width == 0 || height == 0 )
{
// return error answer to cordova
String msg = "Width or height of webview content is 0. Webview to bitmap conversion failed.";
Log.e(LOG_TAG, msg );
PluginResult result = new PluginResult(PluginResult.Status.ERROR, msg);
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return null;
}
Log.v(LOG_TAG, "Html2Pdf.getWebViewAsBitmap -> Content width: " + width + ", height: " + height );
//Cause the view to re-layout
view.measure(width, height);
view.layout(0, 0, width, height);
//Create a bitmap backed Canvas to draw the view into
b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
// draw the view into the canvas
view.draw(c);
return b;
}
/**
* Slices the screenshot into pages, merges those into a single pdf
* and saves it in the public accessible /sdcard dir.
*/
private File saveWebViewAsPdf(Bitmap screenshot) {
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/");
dir.mkdirs();
File file;
FileOutputStream stream;
// creat nomedia file to avoid indexing tmp files
File noMediaFile = new File(dir.getAbsolutePath() + "/", ".nomedia");
if( !noMediaFile.exists() )
{
noMediaFile.createNewFile();
}
double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page
double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page
double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3)
Bitmap currPage;
int totalSize = screenshot.getHeight();
int currPos = 0;
int currPageCount = 0;
int sliceWidth = screenshot.getWidth();
int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation);
while( totalSize > currPos && currPageCount < 100 ) // max 100 pages
{
currPageCount++;
Log.v(LOG_TAG, "Creating page nr. " + currPageCount );
// slice bitmap
currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth, (int) Math.min( sliceHeight, totalSize - currPos ));
// save page as png
stream = new FileOutputStream( new File(dir, "pdf-page-"+currPageCount+".png") );
currPage.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
// move current position indicator
currPos += sliceHeight;
currPage.recycle();
}
// create pdf
Document document = new Document();
File filePdf = new File(sdCard.getAbsolutePath() + "/" + this.tmpPdfName); // change the output name of the pdf here
// create dirs if necessary
if( this.tmpPdfName.contains("/") )
{
File filePdfDir = new File(filePdf.getAbsolutePath().substring(0, filePdf.getAbsolutePath().lastIndexOf("/"))); // get the dir portion
filePdfDir.mkdirs();
}
PdfWriter.getInstance(document,new FileOutputStream(filePdf));
document.open();
for( int i=1; i<=currPageCount; ++i )
{
file = new File(dir, "pdf-page-"+i+".png");
Image image = Image.getInstance (file.getAbsolutePath());
image.scaleToFit( (float)pageWidth, 9999);
image.setAlignment(Element.ALIGN_CENTER);
document.add(image);
document.newPage();
}
document.close();
// delete tmp image files
for( int i=1; i<=currPageCount; ++i )
{
file = new File(dir, "pdf-page-"+i+".png");
file.delete();
}
return filePdf;
} catch (IOException e) {
Log.e(LOG_TAG, "ERROR: " + e.getMessage());
e.printStackTrace();
// return error answer to cordova
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
} catch (DocumentException e) {
Log.e(LOG_TAG, "ERROR: " + e.getMessage());
e.printStackTrace();
// return error answer to cordova
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
}
Log.v(LOG_TAG, "Uncaught ERROR!");
return null;
}
}
class Html2PdfWebView extends WebView {
public Html2PdfWebView(Context context) {
super(context);
}
public int getContentWidth()
{
return this.computeHorizontalScrollRange();
}
}
|
package org.eclipse.birt.core.format;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.ibm.icu.util.ULocale;
/**
*
*
* Defines a number formatting class. It does the following: 1. In constructor,
* convert format string to Java format string. 2. Expose a format function,
* which does the following: a. Format number using Java format string b. Do
* some post-processing, i.e., e or E, minus sign handling, etc.
*/
public class NumberFormatter implements IFormatter
{
private static final String DIGIT_SUBSTITUTION = "DigitSubstitution";
private static final String ROUNDING_MODE = "RoundingMode";
/**
* logger used to log syntax errors.
*/
static protected Logger logger = Logger.getLogger( NumberFormatter.class
.getName( ) );
/**
* the format pattern
*/
protected String formatPattern;
/**
* Flag whether to parse numbers and return BigDecimal values.
*/
protected boolean parseBigDecimal;
/**
* the locale used for formatting
*/
protected ULocale locale = ULocale.getDefault( );
/**
* a java.text.NumberFormat format object. We want to use the
* createNumberFormat() and format() methods
*/
protected NumberFormat numberFormat;
protected DecimalFormat decimalFormat;
/**
* The default format of Double is Double.toString(); need to localize the
* result of Double.toString() to get the final result.
*
* decimalSeparator is the localized decimal separator.
*
* currently the exponential character isnt exposed by JDK, so just leave it
* for future
*
* @see definition of java.text.DecimalFormatSymbols#exponential
*/
protected char decimalSeparator;
/**
* Do we use hex pattern?
*/
private boolean hexFlag;
private int roundPrecision;
private String realPattern;
/**
* used to indicate whether to use ICU symbols
*/
private boolean digitSubstitution;
private RoundingMode roundingMode = RoundingMode.HALF_UP;
/**
* constructor with no argument
*/
public NumberFormatter( )
{
applyPattern( null );
}
/**
* constructor with a format string as parameter
*
* @param format
* format string
*/
public NumberFormatter( String format )
{
applyPattern( format );
}
/**
* @param locale
* the locale used for numer format
*/
public NumberFormatter( ULocale locale )
{
this.locale = locale;
applyPattern( null );
}
/**
* @deprecated since 2.1
* @return
*/
public NumberFormatter( Locale locale )
{
this( ULocale.forLocale( locale ) );
}
/**
* constructor that takes a format pattern and a locale
*
* @param pattern
* numeric format pattern
* @param locale
* locale used to format the number
*/
public NumberFormatter( String pattern, ULocale locale )
{
this.locale = locale;
this.parseBigDecimal = false;
applyPattern( pattern );
}
/**
* @deprecated since 2.1
* @return
*/
public NumberFormatter( String pattern, Locale locale )
{
this( pattern, ULocale.forLocale( locale ) );
}
/**
* returns the original format string.
*/
public String getPattern( )
{
return this.formatPattern;
}
public String getFormatCode( )
{
return realPattern;
}
/**
* initializes numeric format pattern
*
* @param patternStr
* ths string used for formatting numeric data
*/
public void applyPattern( String patternStr )
{
try
{
patternStr = processPatternAttributes( patternStr );
this.formatPattern = patternStr;
hexFlag = false;
roundPrecision = -1;
realPattern = formatPattern;
// null format String
if ( this.formatPattern == null )
{
numberFormat = NumberFormat.getInstance( locale.toLocale( ) );
numberFormat.setGroupingUsed( false );
DecimalFormatSymbols symbols = new DecimalFormatSymbols( locale
.toLocale( ) );
decimalSeparator = symbols.getDecimalSeparator( );
decimalFormat = new DecimalFormat( "", //$NON-NLS-1$
new DecimalFormatSymbols( locale.toLocale( ) ) );
decimalFormat.setMinimumIntegerDigits( 1 );
decimalFormat.setGroupingUsed( false );
roundPrecision = getRoundPrecision( numberFormat );
applyPatternAttributes( );
return;
}
// Single character format string
if ( patternStr.length( ) == 1 )
{
handleSingleCharFormatString( patternStr.charAt( 0 ) );
roundPrecision = getRoundPrecision( numberFormat );
applyPatternAttributes( );
return;
}
// Named formats and arbitrary format string
handleNamedFormats( patternStr );
roundPrecision = getRoundPrecision( numberFormat );
applyPatternAttributes( );
}
catch ( Exception illeagueE )
{
logger.log( Level.WARNING, illeagueE.getMessage( ), illeagueE );
}
}
private String processPatternAttributes( String pattern )
{
if ( pattern == null || pattern.length( ) <= 3 ) // pattern must have {?}
return pattern;
int length = pattern.length( );
if ( pattern.charAt( length - 1 ) == '}' )
{
// end up with '}'
int begin = pattern.lastIndexOf( '{' );
if ( begin >= 0 )
{
ArrayList<String> names = new ArrayList<String>( );
ArrayList<String> values = new ArrayList<String>( );
String properties = pattern.substring( begin + 1, length - 1 );
String[] attributes = properties.split( ";" );
boolean wellForm = true;
for ( String attribute : attributes )
{
int delimit = attribute.indexOf( '=' );
if ( delimit == -1 )
{
wellForm = false;
break;
}
names.add( attribute.substring( 0, delimit ) );
values.add( attribute.substring( delimit + 1 ) );
}
if ( wellForm )
{
// process attributes
int size = names.size( );
for ( int index = 0; index < size; index++ )
{
if ( DIGIT_SUBSTITUTION.equalsIgnoreCase( names.get(
index ).trim( ) ) )
{
String value = values.get( index ).trim( );
digitSubstitution = Boolean.valueOf( value );
}
if ( ROUNDING_MODE.equalsIgnoreCase( names.get( index )
.trim( ) ) )
{
String value = values.get( index ).trim( );
if ( value.equalsIgnoreCase( "HALF_EVEN" ) )
roundingMode = RoundingMode.HALF_EVEN;
else if ( value.equalsIgnoreCase( "HALF_UP" ) )
roundingMode = RoundingMode.HALF_UP;
else if ( value.equalsIgnoreCase( "HALF_DOWN" ) )
roundingMode = RoundingMode.HALF_DOWN;
else if ( value.equalsIgnoreCase( "UP" ) )
roundingMode = RoundingMode.UP;
else if ( value.equalsIgnoreCase( "DOWN" ) )
roundingMode = RoundingMode.DOWN;
else if ( value.equalsIgnoreCase( "FLOOR" ) )
roundingMode = RoundingMode.FLOOR;
else if ( value.equalsIgnoreCase( "CEILING" ) )
roundingMode = RoundingMode.CEILING;
else if ( value.equalsIgnoreCase( "UNNECESSARY" ) )
roundingMode = RoundingMode.UNNECESSARY;
}
}
if ( begin == 0 )
return null;
return pattern.substring( 0, begin );
}
}
}
return pattern;
}
/**
* @param num
* the number to be formatted
* @return the formatted string
*/
public String format( double num )
{
try
{
if ( Double.isNaN( num ) )
{
return "NaN"; //$NON-NLS-1$
}
if ( hexFlag == true )
{
return Long.toHexString( new Double( num ).longValue( ) );
}
if ( num == 0 )
{
num = 0;
}
if ( this.formatPattern == null )
{
long longValue = Math.round( num );
if( longValue == num )
{
return Long.toString( longValue );
}
String result = Double.toString( num );
return result.replace( '.', decimalSeparator );
}
num = roundValue( num );
return numberFormat.format( num );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
/**
* format(BigDecimal) method, return the format string for the BigDecimal
* parameter.
*/
/**
* formats a BigDecimal value into a string
*
* @param big
* decimal value
* @return formatted string
*/
public String format( BigDecimal bigDecimal )
{
try
{
if ( hexFlag == true )
{
return Long.toHexString( bigDecimal.longValue( ) );
}
if ( this.formatPattern == null )
{
return decimalFormat.format( bigDecimal );
}
bigDecimal = roundValue( bigDecimal );
return numberFormat.format( bigDecimal );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
public String format( Number number )
{
try
{
if ( Double.isNaN( number.doubleValue( ) ) )
{
return "NaN";
}
if ( hexFlag == true )
{
return Long.toHexString( number.longValue( ) );
}
if ( number instanceof Double || number instanceof Float )
{
return format( number.doubleValue( ) );
}
if ( number instanceof BigDecimal )
{
return format( (BigDecimal) number );
}
return numberFormat.format( number );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
/**
* formats a long integer
*
* @param num
* the number to be formatted
* @return the formatted string
*/
public String format( long num )
{
if ( hexFlag == true )
{
return Long.toHexString( num );
}
return numberFormat.format( num );
}
private void handleSingleCharFormatString( char c )
{
switch ( c )
{
case 'G' :
case 'g' :
case 'D' :
case 'd' :
numberFormat = NumberFormat.getInstance( locale.toLocale( ) );
return;
case 'C' :
case 'c' :
numberFormat = NumberFormat.getCurrencyInstance( locale.toLocale( ) );
return;
case 'F' :
case 'f' :
realPattern = "#0.00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern,
new DecimalFormatSymbols( locale.toLocale( ) ) );
return;
case 'N' :
case 'n' :
realPattern = "###,##0.00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern,
new DecimalFormatSymbols( locale.toLocale( ) ) );
return;
case 'P' :
case 'p' :
realPattern = "###,##0.00 %"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern,
new DecimalFormatSymbols( locale.toLocale( ) ) );
return;
case 'E' :
case 'e' :
realPattern = "0.000000E00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern,
new DecimalFormatSymbols( locale.toLocale( ) ) );
roundPrecision = -2;
return;
case 'X' :
case 'x' :
hexFlag = true;
return;
default :
{
char data[] = new char[1];
data[0] = c;
String str = new String( data );
numberFormat = new DecimalFormat( str,
new DecimalFormatSymbols( locale.toLocale( ) ) );
return;
}
}
}
private DecimalFormatSymbols getICUDecimalSymbols( Locale locale )
{
DecimalFormatSymbols symbols = new DecimalFormatSymbols( locale );
com.ibm.icu.text.DecimalFormatSymbols icuSymbols = new com.ibm.icu.text.DecimalFormatSymbols(
locale );
symbols.setCurrencySymbol( icuSymbols.getCurrencySymbol( ) );
symbols.setDecimalSeparator( icuSymbols.getDecimalSeparator( ) );
symbols.setDigit( icuSymbols.getDigit( ) );
symbols.setGroupingSeparator( icuSymbols.getGroupingSeparator( ) );
symbols.setInfinity( icuSymbols.getInfinity( ) );
symbols.setInternationalCurrencySymbol( icuSymbols
.getInternationalCurrencySymbol( ) );
symbols.setMinusSign( icuSymbols.getMinusSign( ) );
symbols.setMonetaryDecimalSeparator( icuSymbols
.getMonetaryDecimalSeparator( ) );
symbols.setNaN( icuSymbols.getNaN( ) );
symbols.setPatternSeparator( icuSymbols.getPatternSeparator( ) );
symbols.setPercent( icuSymbols.getPercent( ) );
symbols.setPerMill( icuSymbols.getPerMill( ) );
symbols.setZeroDigit( icuSymbols.getZeroDigit( ) );
return symbols;
}
private void applyPatternAttributes( )
{
if ( digitSubstitution )
{
DecimalFormatSymbols symbols = getICUDecimalSymbols( locale
.toLocale( ) );
if ( decimalFormat != null )
{
( (DecimalFormat) decimalFormat ).setDecimalFormatSymbols( symbols );
}
if ( numberFormat instanceof DecimalFormat )
{
( (DecimalFormat) numberFormat )
.setDecimalFormatSymbols( symbols );
}
}
}
private void handleNamedFormats( String patternStr )
{
if ( patternStr.equals( "General Number" ) || patternStr.equals( "Unformatted" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
numberFormat = NumberFormat.getInstance( locale.toLocale( ) );
numberFormat.setGroupingUsed( false );
return;
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols( locale.toLocale( ) );
if ( patternStr.equals( "Fixed" ) ) //$NON-NLS-1$
{
realPattern = "#0.00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern, symbols );
return;
}
if ( patternStr.equals( "Percent" ) ) //$NON-NLS-1$
{
realPattern = "0.00%"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern, symbols );
return;
}
if ( patternStr.equals( "Scientific" ) ) //$NON-NLS-1$
{
realPattern = "0.00E00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern, symbols );
roundPrecision = -2;
return;
}
if ( patternStr.equals( "Standard" ) ) //$NON-NLS-1$
{
realPattern = "###,##0.00"; //$NON-NLS-1$
numberFormat = new DecimalFormat( realPattern, symbols );
return;
}
try
{
numberFormat = new DecimalFormat( patternStr, symbols );
}
catch ( java.lang.IllegalArgumentException e )
{
// if the pattern is invalid, create a default decimal
numberFormat = new DecimalFormat( "", symbols );//$NON-NLS-1$
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
/**
* Returns whether decimal numbers are returned as BigDecimal instances.
* @return the parseBigDecimal
*/
public boolean isParseBigDecimal( )
{
return parseBigDecimal;
}
/**
* Sets whether decimal numbers must be returned as BigDecimal instances.
* @param parseBigDecimal the parseBigDecimal to set
*/
public void setParseBigDecimal( boolean parseBigDecimal )
{
this.parseBigDecimal = parseBigDecimal;
}
/**
* Parses the input string into a formatted date type.
*
* @param number
* the input string to parse
* @return the formatted date
* @throws ParseException
* if the beginning of the specified string cannot be parsed.
*/
public Number parse( String number ) throws ParseException
{
if ( numberFormat instanceof DecimalFormat )
{
( (DecimalFormat) numberFormat ).setParseBigDecimal( this.parseBigDecimal );
}
return numberFormat.parse( number );
}
BigDecimal roundValue( BigDecimal bd )
{
if ( roundPrecision >= 0 )
{
int scale = bd.scale( );
try
{
if ( scale > roundPrecision )
{
bd = bd.setScale( roundPrecision, roundingMode );
}
}
catch ( ArithmeticException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
}
}
return bd;
}
double roundValue( double value )
{
if ( roundPrecision >= 0 )
{
BigDecimal bd = BigDecimal.valueOf( value );
int scale = bd.scale( );
try
{
if ( scale > roundPrecision )
{
bd = bd.setScale( roundPrecision, roundingMode );
return bd.doubleValue( );
}
}
catch ( ArithmeticException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ), e );
return value;
}
}
return value;
}
int getRoundPrecision( NumberFormat format )
{
if ( realPattern != null && realPattern.indexOf( 'E' ) != -1 )
{
return -1;
}
int precision = numberFormat.getMaximumFractionDigits( );
if ( numberFormat instanceof DecimalFormat )
{
int formatMultiplier = ( (DecimalFormat) numberFormat ).getMultiplier( );
precision += (int) Math.log10( formatMultiplier );
}
return precision;
}
public String formatValue( Object value )
{
assert value instanceof Number;
return format( (Number) value );
}
}
|
package at.modalog.cordova.plugin.html2pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import android.R.bool;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.print.pdf;
import android.print.PrintDocumentInfo;
import android.printservice.PrintJob;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;
@TargetApi(19)
public class Html2pdf extends CordovaPlugin
{
private static final String LOG_TAG = "Html2Pdf";
private CallbackContext callbackContext;
// change your path on the sdcard here
private String publicTmpDir = ".at.modalog.cordova.plugin.html2pdf"; // prepending a dot "." would make it hidden
private String tmpPdfName = "print.pdf";
// set to true to see the webview (useful for debugging)
private final boolean showWebViewForDebugging = false;
/**
* Constructor.
*/
public Html2pdf() {
}
@Override
public boolean execute (String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
try
{
if( action.equals("create") )
{
if( showWebViewForDebugging )
{
Log.v(LOG_TAG,"java create pdf from html called");
Log.v(LOG_TAG, "File: " + args.getString(1));
// Log.v(LOG_TAG, "Html: " + args.getString(0));
Log.v(LOG_TAG, "Html start:" + args.getString(0).substring(0, 30));
Log.v(LOG_TAG, "Html end:" + args.getString(0).substring(args.getString(0).length() - 30));
}
if( args.getString(1) != null && args.getString(1) != "null" )
this.tmpPdfName = args.getString(1);
final Html2pdf self = this;
final String content = args.optString(0, "<html></html>");
this.callbackContext = callbackContext;
cordova.getActivity().runOnUiThread( new Runnable() {
public void run()
{
if( Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT1==1 ) // Android 4.4
{
/*
* None-Kitkat pdf creation (Android < 4.4)
* it will be a image based pdf
*/
self.loadContentIntoWebView(content);
}
else
{
/*
* Kitkat pdf creation by using the android print framework (Android >= 4.4)
*/
// Create a WebView object specifically for printing
WebView page = new WebView(cordova.getActivity());
page.getSettings().setJavaScriptEnabled(false);
page.setDrawingCacheEnabled(true);
// Auto-scale the content to the webview's width.
page.getSettings().setLoadWithOverviewMode(true);
page.getSettings().setUseWideViewPort(true);
page.setInitialScale(0);
// Disable android text auto fit behaviour
page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
if( showWebViewForDebugging )
{
page.setVisibility(View.VISIBLE);
}
else {
page.setVisibility(View.INVISIBLE);
}
// self.cordova.getActivity().addContentView(webView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
page.setWebViewClient( new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView view, String url)
{
// Get a PrintManager instance
PrintManager printManager = (PrintManager) self.cordova.getActivity()
.getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = view.createPrintDocumentAdapter();
// Get a print builder attributes instance
/*PrintAttributes.Builder builder = new PrintAttributes.Builder();
builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS);
// builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
// builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
// builder.setResolution(new PrintAttributes.Resolution("default", self.tmpPdfName, 600, 600));
*/
// send success result to cordova
PluginResult result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
// Create & send a print job
File filePdf = new File(self.tmpPdfName);
printManager.print(filePdf.getName(), printAdapter, /*builder.build()*/null);
}
});
// Reverse engineer base url (assets/www) from the cordova webView url
String baseURL = self.webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
// Load content into the print webview
if( showWebViewForDebugging )
{
cordova.getActivity().addContentView(page, new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null);
}
}
});
// send "no-result" result to delay result handling
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
return true;
}
return false;
}
catch (JSONException e)
{
// TODO: signal JSON problem to JS
//callbackContext.error("Problem with JSON");
return false;
}
}
/**
*
* Clean up and close all open files.
*
*/
@Override
public void onDestroy()
{
// ToDo: clean up.
}
// LOCAL METHODS
private void loadContentIntoWebView (String content)
{
Activity ctx = cordova.getActivity();
final WebView page = new Html2PdfWebView(ctx);
final Html2pdf self = this;
if( showWebViewForDebugging )
{
page.setVisibility(View.VISIBLE);
} else {
page.setVisibility(View.INVISIBLE);
}
page.getSettings().setJavaScriptEnabled(false);
page.setDrawingCacheEnabled(true);
page.getSettings().setLoadWithOverviewMode(false);
page.getSettings().setUseWideViewPort(false);
page.setInitialScale(100);
// Disable android text auto fit behaviour
page.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
page.setWebViewClient( new WebViewClient() {
@Override
public void onPageFinished(final WebView page, String url) {
new Handler().postDelayed( new Runnable() {
@Override
public void run()
{
// slice the web screenshot into pages and save as pdf
Bitmap b = getWebViewAsBitmap(page);
if( b != null )
{
File tmpFile = self.saveWebViewAsPdf(b);
b.recycle();
// add pdf as stream to the print intent
Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW);
pdfViewIntent.setDataAndNormalize(Uri.fromFile(tmpFile));
pdfViewIntent.setType("application/pdf");
// remove the webview
if( !self.showWebViewForDebugging )
{
ViewGroup vg = (ViewGroup)(page.getParent());
vg.removeView(page);
}
// add file to media scanner
MediaScannerConnection.scanFile(
self.cordova.getActivity(),
new String[]{tmpFile.getAbsolutePath()},
null,
new OnScanCompletedListener() {
@Override
public void onScanCompleted(String path, Uri uri) {
Log.v(LOG_TAG, "file '" + path + "' was scanned seccessfully: " + uri);
}
}
);
// start the pdf viewer app (trigger the pdf view intent)
PluginResult result;
boolean success = false;
if( self.canHandleIntent(self.cordova.getActivity(), pdfViewIntent) )
{
try
{
self.cordova.startActivityForResult(self, pdfViewIntent, 0);
success = true;
}
catch( ActivityNotFoundException e )
{
success = false;
}
}
if( success )
{
// send success result to cordova
result = new PluginResult(PluginResult.Status.OK);
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
else
{
// send error
result = new PluginResult(PluginResult.Status.ERROR, "activity_not_found");
result.setKeepCallback(false);
self.callbackContext.sendPluginResult(result);
}
}
}
}, 500);
}
});
// Set base URI to the assets/www folder
String baseURL = webView.getUrl();
baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);
/** We make it this small on purpose (is resized after page load has finished).
* Making it small in the beginning has some effects on the html <body> (body
* width will always remain 100 if not set explicitly).
*/
if( !showWebViewForDebugging )
{
ctx.addContentView(page, new ViewGroup.LayoutParams(100, 100));
}
else
{
ctx.addContentView(page, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
page.loadDataWithBaseURL(baseURL, content, "text/html", "utf-8", null);
}
public static final String MIME_TYPE_PDF = "application/pdf";
/**
* Check if the supplied context can handle the given intent.
*
* @param context
* @param intent
* @return boolean
*/
public boolean canHandleIntent(Context context, Intent intent)
{
PackageManager packageManager = context.getPackageManager();
return (packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0);
}
/**
* Takes a WebView and returns a Bitmap representation of it (takes a "screenshot").
* @param WebView
* @return Bitmap
*/
public Bitmap getWebViewAsBitmap(WebView view)
{
Bitmap b;
// prepare drawing cache
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
//Get the dimensions of the view so we can re-layout the view at its current size
//and create a bitmap of the same size
int width = ((Html2PdfWebView) view).getContentWidth();
int height = view.getContentHeight();
if( width == 0 || height == 0 )
{
// return error answer to cordova
String msg = "Width or height of webview content is 0. Webview to bitmap conversion failed.";
Log.e(LOG_TAG, msg );
PluginResult result = new PluginResult(PluginResult.Status.ERROR, msg);
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
return null;
}
Log.v(LOG_TAG, "Html2Pdf.getWebViewAsBitmap -> Content width: " + width + ", height: " + height );
//Cause the view to re-layout
view.measure(width, height);
view.layout(0, 0, width, height);
//Create a bitmap backed Canvas to draw the view into
b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
// draw the view into the canvas
view.draw(c);
return b;
}
/**
* Slices the screenshot into pages, merges those into a single pdf
* and saves it in the public accessible /sdcard dir.
*/
private File saveWebViewAsPdf(Bitmap screenshot) {
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/");
dir.mkdirs();
File file;
FileOutputStream stream;
// creat nomedia file to avoid indexing tmp files
File noMediaFile = new File(dir.getAbsolutePath() + "/", ".nomedia");
if( !noMediaFile.exists() )
{
noMediaFile.createNewFile();
}
double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page
double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page
double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3)
Bitmap currPage;
int totalSize = screenshot.getHeight();
int currPos = 0;
int currPageCount = 0;
int sliceWidth = screenshot.getWidth();
int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation);
while( totalSize > currPos && currPageCount < 100 ) // max 100 pages
{
currPageCount++;
Log.v(LOG_TAG, "Creating page nr. " + currPageCount );
// slice bitmap
currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth, (int) Math.min( sliceHeight, totalSize - currPos ));
// save page as png
stream = new FileOutputStream( new File(dir, "pdf-page-"+currPageCount+".png") );
currPage.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
// move current position indicator
currPos += sliceHeight;
currPage.recycle();
}
// create pdf
Document document = new Document();
File filePdf = new File(sdCard.getAbsolutePath() + "/" + this.tmpPdfName); // change the output name of the pdf here
// create dirs if necessary
if( this.tmpPdfName.contains("/") )
{
File filePdfDir = new File(filePdf.getAbsolutePath().substring(0, filePdf.getAbsolutePath().lastIndexOf("/"))); // get the dir portion
filePdfDir.mkdirs();
}
PdfWriter.getInstance(document,new FileOutputStream(filePdf));
document.open();
for( int i=1; i<=currPageCount; ++i )
{
file = new File(dir, "pdf-page-"+i+".png");
Image image = Image.getInstance (file.getAbsolutePath());
image.scaleToFit( (float)pageWidth, 9999);
image.setAlignment(Element.ALIGN_CENTER);
document.add(image);
document.newPage();
}
document.close();
// delete tmp image files
for( int i=1; i<=currPageCount; ++i )
{
file = new File(dir, "pdf-page-"+i+".png");
file.delete();
}
return filePdf;
} catch (IOException e) {
Log.e(LOG_TAG, "ERROR: " + e.getMessage());
e.printStackTrace();
// return error answer to cordova
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
} catch (DocumentException e) {
Log.e(LOG_TAG, "ERROR: " + e.getMessage());
e.printStackTrace();
// return error answer to cordova
PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
result.setKeepCallback(false);
callbackContext.sendPluginResult(result);
}
Log.v(LOG_TAG, "Uncaught ERROR!");
return null;
}
/*
* PRINTER ADAPTER METHODS
*/
@Override
public void onLayout(PrintAttributes oldAttributes,
PrintAttributes newAttributes,
CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
// Create a new PdfDocument with the requested page attributes
mPdfDocument = new PrintedPdfDocument(getActivity(), newAttributes);
// Respond to cancellation request
if (cancellationSignal.isCancelled() ) {
callback.onLayoutCancelled();
return;
}
// Compute the expected number of printed pages
int pages = computePageCount(newAttributes);
if (pages > 0) {
// Return print information to print framework
PrintDocumentInfo info = new PrintDocumentInfo
.Builder("print_output.pdf")
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(pages);
.build();
// Content layout reflow is complete
callback.onLayoutFinished(info, true);
} else {
// Otherwise report an error to the print framework
callback.onLayoutFailed("Page count calculation failed.");
}
}
private int computePageCount(PrintAttributes printAttributes) {
int itemsPerPage = 4; // default item count for portrait mode
MediaSize pageSize = printAttributes.getMediaSize();
if (!pageSize.isPortrait()) {
// Six items per page in landscape orientation
itemsPerPage = 6;
}
// Determine number of print items
int printItemCount = getPrintItemCount();
return (int) Math.ceil(printItemCount / itemsPerPage);
}
@Override
public void onWrite(final PageRange[] pageRanges,
final ParcelFileDescriptor destination,
final CancellationSignal cancellationSignal,
final WriteResultCallback callback) {
// Iterate over each page of the document,
// check if it's in the output range.
for (int i = 0; i < totalPages; i++) {
// Check to see if this page is in the output range.
if (containsPage(pageRanges, i)) {
// If so, add it to writtenPagesArray. writtenPagesArray.size()
// is used to compute the next output page index.
writtenPagesArray.append(writtenPagesArray.size(), i);
PdfDocument.Page page = mPdfDocument.startPage(i);
// check for cancellation
if (cancellationSignal.isCancelled()) {
callback.onWriteCancelled();
mPdfDocument.close();
mPdfDocument = null;
return;
}
// Draw page content for printing
drawPage(page);
// Rendering is complete, so page can be finalized.
mPdfDocument.finishPage(page);
}
}
// Write PDF document to file
try {
mPdfDocument.writeTo(new FileOutputStream(
destination.getFileDescriptor()));
} catch (IOException e) {
callback.onWriteFailed(e.toString());
return;
} finally {
mPdfDocument.close();
mPdfDocument = null;
}
PageRange[] writtenPages = computeWrittenPages();
// Signal the print framework the document is complete
callback.onWriteFinished(writtenPages);
}
}
class Html2PdfWebView extends WebView {
public Html2PdfWebView(Context context) {
super(context);
}
public int getContentWidth()
{
return this.computeHorizontalScrollRange();
}
}
|
package org.eclipse.birt.core.format;
import java.math.BigDecimal;
import com.ibm.icu.text.DecimalFormat;
import com.ibm.icu.text.DecimalFormatSymbols;
import com.ibm.icu.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import com.ibm.icu.util.ULocale;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NumberFormatter
{
/**
* logger used to log syntax errors.
*/
static protected Logger logger = Logger.getLogger( NumberFormatter.class
.getName( ) );
/**
* the format pattern
*/
protected String formatPattern;
/**
* the locale used for formatting
*/
protected ULocale locale = ULocale.getDefault( );
/**
* a java.text.NumberFormat format object. We want to use the
* createNumberFormat() and format() methods
*/
protected NumberFormat numberFormat;
protected NumberFormat decimalFormat;
/**
* Do we use hex pattern?
*/
private boolean hexFlag;
/**
* constructor with no argument
*/
public NumberFormatter( )
{
applyPattern( null );
}
/**
* constructor with a format string as parameter
*
* @param format
* format string
*/
public NumberFormatter( String format )
{
applyPattern( format );
}
/**
* @param locale
* the locale used for numer format
*/
public NumberFormatter( ULocale locale )
{
this.locale = locale;
applyPattern( null );
}
/**
* @deprecated since 2.1
* @return
*/
public NumberFormatter( Locale locale )
{
this(ULocale.forLocale(locale));
}
/**
* constructor that takes a format pattern and a locale
*
* @param pattern
* numeric format pattern
* @param locale
* locale used to format the number
*/
public NumberFormatter( String pattern, ULocale locale )
{
this.locale = locale;
applyPattern( pattern );
}
/**
* @deprecated since 2.1
* @return
*/
public NumberFormatter( String pattern, Locale locale )
{
this(pattern, ULocale.forLocale(locale));
}
/**
* returns the original format string.
*/
public String getPattern( )
{
return this.formatPattern;
}
/**
* initializes numeric format pattern
*
* @param patternStr
* ths string used for formatting numeric data
*/
public void applyPattern( String patternStr )
{
try
{
this.formatPattern = patternStr;
hexFlag = false;
// null format String
if ( this.formatPattern == null )
{
numberFormat = NumberFormat.getInstance( locale );
numberFormat.setGroupingUsed( false );
decimalFormat = new DecimalFormat( "", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
decimalFormat.setGroupingUsed( false );
return;
}
// Single character format string
if ( patternStr.length( ) == 1 )
{
handleSingleCharFormatString( patternStr.charAt( 0 ) );
return;
}
// Named formats and arbitrary format string
handleNamedFormats( patternStr );
}
catch ( Exception illeagueE )
{
logger.log( Level.WARNING, illeagueE.getMessage( ), illeagueE );
}
}
/**
* @param num
* the number to be formatted
* @return the formatted string
*/
public String format( double num )
{
try
{
if ( Double.isNaN( num ) )
{
return "NaN"; //$NON-NLS-1$
}
if ( hexFlag == true )
{
return Long.toHexString( new Double( num ).longValue());
}
return numberFormat.format( num );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
/**
* format(BigDecimal) method, return the format string for the BigDecimal
* parameter.
*/
/**
* formats a BigDecimal value into a string
*
* @param big
* decimal value
* @return formatted string
*/
public String format( BigDecimal bigDecimal )
{
try
{
if ( hexFlag == true )
{
return Long.toHexString( bigDecimal.longValue( ) );
}
if ( this.formatPattern == null )
{
return decimalFormat.format( bigDecimal );
}
return numberFormat.format( bigDecimal );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
public String format( Number number )
{
try
{
if ( Double.isNaN( number.doubleValue( ) ) )
{
return "NaN";
}
if ( hexFlag == true )
{
return Long.toHexString( number.longValue());
}
if ( this.formatPattern == null && number instanceof BigDecimal )
{
return decimalFormat.format( number );
}
return numberFormat.format( number );
}
catch ( Exception e )
{
logger.log( Level.WARNING, e.getMessage( ), e ); //$NON-NLS-1$
return null;
}
}
/**
* formats a long integer
*
* @param num
* the number to be formatted
* @return the formatted string
*/
public String format( long num )
{
if ( hexFlag == true )
{
return Long.toHexString( num );
}
return numberFormat.format( num );
}
private void handleSingleCharFormatString( char c )
{
switch ( c )
{
case 'G' :
case 'g' :
case 'D' :
case 'd' :
numberFormat = NumberFormat.getInstance( locale );
return;
case 'C' :
case 'c' :
numberFormat = NumberFormat.getCurrencyInstance( locale );
return;
case 'F' :
case 'f' :
numberFormat = new DecimalFormat( "#0.00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
case 'N' :
case 'n' :
numberFormat = new DecimalFormat( "###,##0.00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
case 'P' :
case 'p' :
numberFormat = new DecimalFormat( "###,##0.00 %", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
case 'E' :
case 'e' :
numberFormat = new DecimalFormat( "0.000000E00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
case 'X' :
case 'x' :
hexFlag = true;
return;
default :
{
char data[] = new char[1];
data[0] = c;
String str = new String( data );
numberFormat = new DecimalFormat( str,
new DecimalFormatSymbols( locale ) );
return;
}
}
}
private void handleNamedFormats( String patternStr )
{
if ( patternStr.equals( "General Number" ) || patternStr.equals( "Unformatted" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
numberFormat = NumberFormat.getInstance( locale );
numberFormat.setGroupingUsed( false );
return;
}
if ( patternStr.equals( "Fixed" ) ) //$NON-NLS-1$
{
numberFormat = new DecimalFormat( "#0.00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
}
if ( patternStr.equals( "Percent" ) ) //$NON-NLS-1$
{
numberFormat = new DecimalFormat( "0.00%", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
}
if ( patternStr.equals( "Scientific" ) ) //$NON-NLS-1$
{
numberFormat = new DecimalFormat( "0.00E00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
}
if ( patternStr.equals( "Standard" ) ) //$NON-NLS-1$
{
numberFormat = new DecimalFormat( "###,##0.00", //$NON-NLS-1$
new DecimalFormatSymbols( locale ) );
return;
}
numberFormat = new DecimalFormat( patternStr, new DecimalFormatSymbols(
locale ) );
}
/**
* Parses the input string into a formatted date type.
*
* @param number
* the input string to parse
* @return the formatted date
* @throws ParseException
* if the beginning of the specified string cannot be parsed.
*/
public Number parse( String number ) throws ParseException
{
if ( number != null )
{
number = number.toUpperCase( );
}
return numberFormat.parse( number );
}
}
|
package cpw.mods.fml.common.launcher;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.NonOptionArgumentSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
public class FMLTweaker implements ITweaker {
private List<String> args;
private File gameDir;
private File assetsDir;
private String profile;
private Map<String, String> launchArgs;
private List<String> standaloneArgs;
private static URI jarLocation;
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile)
{
this.gameDir = (gameDir == null ? new File(".") : gameDir);
this.assetsDir = assetsDir;
this.profile = profile;
this.args = args;
this.launchArgs = (Map<String, String>)Launch.blackboard.get("launchArgs");
this.standaloneArgs = Lists.newArrayList();
if (this.launchArgs == null)
{
this.launchArgs = Maps.newHashMap();
Launch.blackboard.put("launchArgs", this.launchArgs);
}
String classifier = null;
for (String arg : args)
{
if (arg.startsWith("-"))
{
if (classifier != null)
{
classifier = launchArgs.put(classifier, "");
}
else if (arg.contains("="))
{
classifier = launchArgs.put(arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1));
}
else
{
classifier = arg;
}
}
else
{
if (classifier != null)
{
classifier = launchArgs.put(classifier, arg);
}
else
{
this.standaloneArgs.add(arg);
}
}
}
if (!this.launchArgs.containsKey("--version"))
{
launchArgs.put("--version", profile != null ? profile : "UnknownFMLProfile");
}
if (!this.launchArgs.containsKey("--gameDir") && gameDir != null)
{
launchArgs.put("--gameDir", gameDir.getAbsolutePath());
}
if (!this.launchArgs.containsKey("--assetsDir") && assetsDir != null)
{
launchArgs.put("--assetsDir", assetsDir.getAbsolutePath());
}
try
{
jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
}
catch (URISyntaxException e)
{
Logger.getLogger("FMLTWEAK").log(Level.SEVERE, "Missing URI information for FML tweak");
throw Throwables.propagate(e);
}
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader)
{
classLoader.addTransformerExclusion("cpw.mods.fml.repackage.");
classLoader.addTransformerExclusion("cpw.mods.fml.relauncher.");
classLoader.addTransformerExclusion("cpw.mods.fml.common.asm.transformers.");
classLoader.addClassLoaderExclusion("LZMA.");
FMLLaunchHandler.configureForClientLaunch(classLoader, this);
FMLLaunchHandler.appendCoreMods();
}
@Override
public String getLaunchTarget()
{
return "net.minecraft.client.main.Main";
}
@Override
public String[] getLaunchArguments()
{
List<String> args = Lists.newArrayList();
args.addAll(standaloneArgs);
for (Entry<String, String> arg : launchArgs.entrySet())
{
args.add(arg.getKey());
args.add(arg.getValue());
}
launchArgs.clear();
return args.toArray(new String[args.size()]);
}
public File getGameDir()
{
return gameDir;
}
public static URI getJarLocation()
{
return jarLocation;
}
public void injectCascadingTweak(String tweakClassName)
{
List<String> tweakClasses = (List<String>) Launch.blackboard.get("TweakClasses");
tweakClasses.add(tweakClassName);
}
}
|
package imagej.core.plugins.debug;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.ext.module.Module;
import imagej.ext.module.ModuleService;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;
import imagej.ext.plugin.PluginService;
import imagej.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
/**
* A test of {@link PluginService#run}. The source code demonstrates two
* different ways of invoking a plugin programmatically: with a list of
* arguments, or by declaring them in a {@link Map}. The latter mechanism is
* more flexible in that you can provide any subset of input values of your
* choice, leaving the rest to be harvested in other ways.
*
* @author Grant Harris
* @author Curtis Rueden
*/
@Plugin(menuPath = "Plugins>Sandbox>Invoke Plugin Test", headless = true)
public class InvokePluginTest implements ImageJPlugin {
@Parameter(persist = false)
private ModuleService moduleService;
@Parameter(persist = false)
private PluginService pluginService;
@Override
public void run() {
final Future<Module> future = invokeWithArgs(); // or invokeWithMap()
final Module module = moduleService.waitFor(future);
final Dataset dataset = (Dataset) module.getOutput("dataset");
Log.info("InvokePluginTest: dataset = " + dataset);
}
public Future<Module> invokeWithArgs() {
final DatasetService datasetService = null; // will be autofilled
final String name = "Untitled";
final String bitDepth = "8-bit";
final boolean signed = false;
final boolean floating = false;
final String fillType = "Ramp";
final long width = 512;
final long height = 512;
return pluginService.run("imagej.io.plugins.NewImage", datasetService,
name, bitDepth, signed, floating, fillType, width, height);
}
public Future<Module> invokeWithMap() {
final Map<String, Object> inputMap = new HashMap<String, Object>();
inputMap.put("name", "Untitled");
inputMap.put("bitDepth", "8-bit");
inputMap.put("signed", false);
inputMap.put("floating", false);
inputMap.put("fillType", "Ramp");
inputMap.put("width", 512L);
inputMap.put("height", 512L);
return pluginService.run("imagej.io.plugins.NewImage", inputMap);
}
}
|
package de.danoeh.antennapod.core.service;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.SafeJobIntentService;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RemoteViews;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import de.danoeh.antennapod.core.R;
import de.danoeh.antennapod.core.glide.ApGlideSettings;
import de.danoeh.antennapod.core.receiver.MediaButtonReceiver;
import de.danoeh.antennapod.core.receiver.PlayerWidget;
import de.danoeh.antennapod.core.service.playback.PlaybackService;
import de.danoeh.antennapod.core.service.playback.PlayerStatus;
import de.danoeh.antennapod.core.util.Converter;
import de.danoeh.antennapod.core.util.playback.Playable;
/**
* Updates the state of the player widget
*/
public class PlayerWidgetJobService extends SafeJobIntentService {
private static final String TAG = "PlayerWidgetJobService";
private PlaybackService playbackService;
private final Object waitForService = new Object();
private static final int JOB_ID = -17001;
public static void updateWidget(Context context) {
enqueueWork(context, PlayerWidgetJobService.class, JOB_ID, new Intent(context, PlayerWidgetJobService.class));
}
@Override
protected void onHandleWork(@NonNull Intent intent) {
if (!PlayerWidget.isEnabled(getApplicationContext())) {
return;
}
synchronized (waitForService) {
if (PlaybackService.isRunning && playbackService == null) {
bindService(new Intent(this, PlaybackService.class), mConnection, 0);
while (playbackService == null) {
try {
waitForService.wait();
} catch (InterruptedException e) {
return;
}
}
}
}
updateViews();
if (playbackService != null) {
try {
unbindService(mConnection);
} catch (IllegalArgumentException e) {
Log.w(TAG, "IllegalArgumentException when trying to unbind service");
}
}
}
/**
* Returns number of cells needed for given size of the widget.
*
* @param size Widget size in dp.
* @return Size in number of cells.
*/
private static int getCellsForSize(int size) {
int n = 2;
while (70 * n - 30 < size) {
++n;
}
return n - 1;
}
private void updateViews() {
ComponentName playerWidget = new ComponentName(this, PlayerWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
int[] widgetIds = manager.getAppWidgetIds(playerWidget);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.player_widget);
PendingIntent startMediaplayer = PendingIntent.getActivity(this, 0,
PlaybackService.getPlayerActivityIntent(this), 0);
final PendingIntent startAppPending = PendingIntent.getActivity(this, 0,
PlaybackService.getPlayerActivityIntent(this),
PendingIntent.FLAG_UPDATE_CURRENT);
boolean nothingPlaying = false;
Playable media;
PlayerStatus status;
if (playbackService != null) {
media = playbackService.getPlayable();
status = playbackService.getStatus();
} else {
media = Playable.PlayableUtils.createInstanceFromPreferences(getApplicationContext());
status = PlayerStatus.STOPPED;
}
if (media != null) {
views.setOnClickPendingIntent(R.id.layout_left, startMediaplayer);
try {
Bitmap icon = null;
int iconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
icon = Glide.with(PlayerWidgetJobService.this)
.asBitmap()
.load(media.getImageLocation())
.apply(RequestOptions.diskCacheStrategyOf(ApGlideSettings.AP_DISK_CACHE_STRATEGY))
.submit(iconSize, iconSize)
.get();
views.setImageViewBitmap(R.id.imgvCover, icon);
} catch (Throwable tr) {
Log.e(TAG, "Error loading the media icon for the widget", tr);
}
views.setTextViewText(R.id.txtvTitle, media.getEpisodeTitle());
String progressString;
if (playbackService != null) {
progressString = getProgressString(playbackService.getCurrentPosition(), playbackService.getDuration());
} else {
progressString = getProgressString(media.getPosition(), media.getDuration());
}
if (progressString != null) {
views.setViewVisibility(R.id.txtvProgress, View.VISIBLE);
views.setTextViewText(R.id.txtvProgress, progressString);
}
if (status == PlayerStatus.PLAYING) {
views.setImageViewResource(R.id.butPlay, R.drawable.ic_pause_white_24dp);
if (Build.VERSION.SDK_INT >= 15) {
views.setContentDescription(R.id.butPlay, getString(R.string.pause_label));
}
} else {
views.setImageViewResource(R.id.butPlay, R.drawable.ic_play_arrow_white_24dp);
if (Build.VERSION.SDK_INT >= 15) {
views.setContentDescription(R.id.butPlay, getString(R.string.play_label));
}
}
views.setOnClickPendingIntent(R.id.butPlay, createMediaButtonIntent());
} else {
nothingPlaying = true;
}
if (nothingPlaying) {
// start the app if they click anything
views.setOnClickPendingIntent(R.id.layout_left, startAppPending);
views.setOnClickPendingIntent(R.id.butPlay, startAppPending);
views.setViewVisibility(R.id.txtvProgress, View.INVISIBLE);
views.setImageViewResource(R.id.imgvCover, R.drawable.ic_stat_antenna_default);
views.setTextViewText(R.id.txtvTitle,
this.getString(R.string.no_media_playing_label));
views.setImageViewResource(R.id.butPlay, R.drawable.ic_play_arrow_white_24dp);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
for (int id : widgetIds) {
Bundle options = manager.getAppWidgetOptions(id);
int minWidth = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
int columns = getCellsForSize(minWidth);
if(columns < 3) {
views.setViewVisibility(R.id.layout_center, android.view.View.INVISIBLE);
} else {
views.setViewVisibility(R.id.layout_center, android.view.View.VISIBLE);
}
manager.updateAppWidget(id, views);
}
} else {
manager.updateAppWidget(playerWidget, views);
}
}
/**
* Creates an intent which fakes a mediabutton press
*/
private PendingIntent createMediaButtonIntent() {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
Intent startingIntent = new Intent(getBaseContext(), MediaButtonReceiver.class);
startingIntent.setAction(MediaButtonReceiver.NOTIFY_BUTTON_RECEIVER);
startingIntent.putExtra(Intent.EXTRA_KEY_EVENT, event);
return PendingIntent.getBroadcast(this, 0, startingIntent, 0);
}
private String getProgressString(int position, int duration) {
if (position > 0 && duration > 0) {
return Converter.getDurationStringLong(position) + " / "
+ Converter.getDurationStringLong(duration);
} else {
return null;
}
}
private final ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d(TAG, "Connection to service established");
if (service instanceof PlaybackService.LocalBinder) {
synchronized (waitForService) {
playbackService = ((PlaybackService.LocalBinder) service).getService();
waitForService.notifyAll();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
playbackService = null;
Log.d(TAG, "Disconnected from service");
}
};
}
|
package de.secondsystem.game01.impl.editor.curser;
import org.jsfml.graphics.Color;
import org.jsfml.graphics.RectangleShape;
import org.jsfml.graphics.RenderTarget;
import org.jsfml.system.Vector2f;
import de.secondsystem.game01.impl.map.ILayerObject;
import de.secondsystem.game01.impl.map.IMapProvider;
import de.secondsystem.game01.model.Attributes;
abstract class AbstractCurser implements IEditorCurser {
private static final int MIN_SIZE = 5;
protected final IMapProvider mapProvider;
private Float width;
private Float height;
protected float zoom = 1.f;
protected boolean dragged = false;
protected Vector2f dragOffset = Vector2f.ZERO;
protected final RectangleShape shapeMarker = new RectangleShape();
public AbstractCurser(IMapProvider mapProvider, Color outlineColor) {
this.mapProvider = mapProvider;
shapeMarker.setFillColor(Color.TRANSPARENT);
shapeMarker.setOutlineThickness(2);
shapeMarker.setOutlineColor(outlineColor);
}
protected abstract ILayerObject getLayerObject();
protected float getWidth() {
if( width==null )
width = getLayerObject().getWidth();
return width;
}
protected float getHeight() {
if( height==null )
height = getLayerObject().getHeight();
return height;
}
@Override
public void zoom(float factor) {
zoom*=factor;
getLayerObject().setDimensions(getWidth()*zoom, getHeight()*zoom);
}
@Override
public void rotate(float degrees) {
getLayerObject().setRotation(getLayerObject().getRotation()+degrees);
}
@Override
public void resize(float widthDiff, float heightDiff) {
width= Math.max(MIN_SIZE, getWidth()+widthDiff);
height= Math.max(MIN_SIZE, getHeight()+heightDiff);
getLayerObject().setDimensions(width*zoom, height*zoom);
}
@Override
public Attributes getAttributes() {
return getLayerObject().serialize();
}
@Override
public abstract void setAttributes(Attributes attributes);
@Override
public boolean inside(Vector2f point) {
return getLayerObject().inside(point);
}
@Override
public void draw(RenderTarget renderTarget) {
if( getLayerObject()!=null ) {
shapeMarker.setSize(new Vector2f(getLayerObject().getWidth(), getLayerObject().getHeight()));
shapeMarker.setOrigin(getLayerObject().getWidth()/2.f, getLayerObject().getHeight()/2.f);
shapeMarker.setRotation(getLayerObject().getRotation());
shapeMarker.setPosition(getLayerObject().getPosition());
renderTarget.draw(shapeMarker);
}
}
@Override
public boolean isDragged() {
return dragged;
}
@Override
public void onDragged(Vector2f point) {
dragged = true;
dragOffset = Vector2f.sub(getLayerObject().getPosition(), point);
}
@Override
public void onMouseMoved(Vector2f point) {
if( dragged )
getLayerObject().setPosition(Vector2f.add(point, dragOffset));
}
@Override
public void onDragFinished(Vector2f point) {
dragged = false;
}
@Override
public void onDestroy() {
}
}
|
package org.wyona.cms.scheduler;
import org.apache.log4j.Category;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author Michael Wechner
* @version 2002.10.8
*/
public class HelloWorldJob implements Job{
static Category log = Category.getInstance(HelloWorldJob.class);
public void execute(JobExecutionContext context) throws JobExecutionException{
JobDetail jobDetail = context.getJobDetail();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
String sentence = jobDataMap.getString("sentence");
log.debug(".execute(): "+sentence);
}
}
|
package org.formic.wizard.impl.models;
import java.util.Stack;
import org.pietschy.wizard.WizardStep;
import org.pietschy.wizard.models.Path;
import org.pietschy.wizard.models.SimplePath;
/**
* Extension to original MultiPathModel that supports paths containing no steps.
*
* @author Eric Van Dewoestine (ervandew@yahoo.com)
* @version $Revision$
*/
public class MultiPathModel
extends org.pietschy.wizard.models.MultiPathModel
{
private Stack history = new Stack();
private Path firstPath = null;
public MultiPathModel(Path firstPath)
{
super(firstPath);
this.firstPath = firstPath;
}
/**
* {@inheritDoc}
*/
public void nextStep()
{
WizardStep currentStep = getActiveStep();
Path currentPath = getPathForStep(currentStep);
// CHANGE
// NEW CODE
if (currentPath.getSteps().size() == 0 ||
currentPath.isLastStep(currentStep))
{
Path nextPath = getNextPath(currentPath);
while(nextPath.getSteps().size() == 0){
nextPath = getNextPath(nextPath);
}
setActiveStep(nextPath.firstStep());
}
// OLD CODE
/*if (currentPath.isLastStep(currentStep))
{
Path nextPath = currentPath.getNextPath(this);
setActiveStep(nextPath.firstStep());
}*/
// END CHANGE
else
{
setActiveStep(currentPath.nextStep(currentStep));
}
history.push(currentStep);
}
/**
* Gets the next path.
*/
private Path getNextPath (Path path)
{
if(path instanceof SimplePath){
return ((SimplePath)path).getNextPath();
}
return ((BranchingPath)path).getNextPath(this);
}
/**
* {@inheritDoc}
*/
public void previousStep()
{
WizardStep step = (WizardStep) history.pop();
setActiveStep(step);
}
/**
* {@inheritDoc}
*/
public void lastStep()
{
history.push(getActiveStep());
WizardStep lastStep = getLastPath().lastStep();
setActiveStep(lastStep);
}
/**
* {@inheritDoc}
* @see org.pietschy.wizard.WizardModel#isLastVisible()
*/
public boolean isLastVisible ()
{
return false;
}
/**
* Determines if the supplied step is the first step.
*
* @param step The step.
* @return true if the first step, false otherwise.
*/
public boolean isFirstStep (WizardStep step)
{
Path path = getPathForStep(step);
return path.equals(getFirstPath()) && path.isFirstStep(step);
}
/**
* {@inheritDoc}
*/
public void reset()
{
history.clear();
WizardStep firstStep = firstPath.firstStep();
setActiveStep(firstStep);
history.push(firstStep);
}
/**
* {@inheritDoc}
* @see org.pietschy.wizard.AbstractWizardModel#setPreviousAvailable(boolean)
*/
public void setPreviousAvailable (boolean available)
{
super.setPreviousAvailable(available);
}
/**
* {@inheritDoc}
* @see org.pietschy.wizard.AbstractWizardModel#setCancelAvailable(boolean)
*/
public void setCancelAvailable (boolean available)
{
super.setCancelAvailable(available);
}
}
|
package org.hisp.dhis.android.core.relationship;
import android.database.Cursor;
import android.support.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.gabrielittner.auto.value.cursor.ColumnAdapter;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.common.Model;
import org.hisp.dhis.android.core.data.database.DbRelationshipConstraintTypeColumnAdapter;
import org.hisp.dhis.android.core.data.database.RelationshipItemEnrollmentColumnAdapter;
import org.hisp.dhis.android.core.data.database.RelationshipItemEventColumnAdapter;
import org.hisp.dhis.android.core.data.database.RelationshipItemTrackedEntityInstanceColumnAdapter;
import org.hisp.dhis.android.core.data.database.RelationshipWithUidColumnAdapter;
@AutoValue
@JsonDeserialize(builder = AutoValue_RelationshipItem.Builder.class)
public abstract class RelationshipItem implements Model {
@Nullable
@JsonIgnore()
@ColumnAdapter(RelationshipWithUidColumnAdapter.class)
public abstract Relationship relationship();
@Nullable
@JsonIgnore()
@ColumnAdapter(DbRelationshipConstraintTypeColumnAdapter.class)
public abstract RelationshipConstraintType relationshipItemType();
@Nullable
@JsonProperty()
@ColumnAdapter(RelationshipItemTrackedEntityInstanceColumnAdapter.class)
public abstract RelationshipItemTrackedEntityInstance trackedEntityInstance();
@Nullable
@JsonProperty()
@ColumnAdapter(RelationshipItemEnrollmentColumnAdapter.class)
public abstract RelationshipItemEnrollment enrollment();
@Nullable
@JsonProperty()
@ColumnAdapter(RelationshipItemEventColumnAdapter.class)
public abstract RelationshipItemEvent event();
public boolean hasTrackedEntityInstance() {
return trackedEntityInstance() != null;
}
public boolean hasEnrollment() {
return enrollment() != null;
}
public boolean hasEvent() {
return event() != null;
}
public String elementUid() {
if (hasTrackedEntityInstance()) {
return trackedEntityInstance().trackedEntityInstance();
} else if (hasEnrollment()) {
return enrollment().enrollment();
} else {
return event().event();
}
}
public static Builder builder() {
return new AutoValue_RelationshipItem.Builder();
}
static RelationshipItem create(Cursor cursor) {
return $AutoValue_RelationshipItem.createFromCursor(cursor);
}
public abstract Builder toBuilder();
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
public abstract static class Builder {
public abstract Builder id(Long id);
public abstract Builder trackedEntityInstance(RelationshipItemTrackedEntityInstance trackedEntityInstance);
public abstract Builder enrollment(RelationshipItemEnrollment enrollment);
public abstract Builder event(RelationshipItemEvent event);
public abstract Builder relationship(Relationship relationship);
public abstract Builder relationshipItemType(RelationshipConstraintType relationshipItemType);
protected abstract RelationshipItem autoBuild();
@SuppressWarnings("PMD.NPathComplexity")
public RelationshipItem build() {
RelationshipItem item = autoBuild();
int teiCount = item.trackedEntityInstance() == null ? 0 : 1;
int enrollmentCount = item.enrollment() == null ? 0 : 1;
int eventCount = item.event() == null ? 0 : 1;
if (teiCount + enrollmentCount + eventCount == 1) {
return item;
} else {
throw new IllegalArgumentException("Item must have either a TEI, enrollment or event");
}
}
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
/**
* <p>A fun Painter that paints pinstripes. You can specify the Paint to paint
* those pinstripes in (could even be a texture paint!), the angle at which
* to paint the pinstripes, and the spacing between stripes.</p>
*
* <p>The default PinstripePainter configuration will paint the pinstripes
* using the foreground color of the component (the default behavior if a
* Paint is not specified) at a 45 degree angle with 8 pixels between stripes</p>
*
* <p>Here is a custom code snippet that paints Color.GRAY pinstripes at a 135
* degree angle:
* <pre><code>
* PinstripePainter p = new PinstripePainter();
* p.setAngle(135);
* p.setPaint(Color.GRAY);
* </code></pre>
*
* @author rbair
*/
public class PinstripePainter<T> extends AbstractPainter<T> {
/**
* The angle in degrees to paint the pinstripes at. The default
* value is 45. The value will be between 0 and 360 inclusive. The
* setAngle method will ensure this.
*/
private double angle = 45;
/**
* The spacing between pinstripes
*/
private double spacing = 8;
/**
* The stroke width of the pinstripes
*/
private double stripeWidth = 1;
/**
* The Paint to use when drawing the pinstripes
*/
private Paint paint;
/**
* Create a new PinstripePainter. By default the angle with be 45 degrees,
* the spacing will be 8 pixels, and the color will be the Component foreground
* color.
*/
public PinstripePainter() {
}
/**
* Create a new PinstripePainter using an angle of 45, 8 pixel spacing,
* and the given Paint.
*
* @param paint the paint used when drawing the stripes
*/
public PinstripePainter(Paint paint) {
this(paint, 45);
}
/**
* Create a new PinstripePainter using the given angle, 8 pixel spacing,
* and the given Paint
*
* @param paint the paint used when drawing the stripes
* @param angle the angle, in degrees, in which to paint the pinstripes
*/
public PinstripePainter(Paint paint, double angle) {
this.paint = paint;
this.angle = angle;
}
/**
* Create a new PinstripePainter using the given angle, 8 pixel spacing,
* and the foreground color of the Component
*
* @param angle the angle, in degrees, in which to paint the pinstripes
*/
public PinstripePainter(double angle) {
this.angle = angle;
}
/**
* Create a new PinstripePainter with the specified paint, angle, stripe width, and stripe spacing.
* @param paint
* @param angle
* @param stripeWidth
* @param spacing
*/
public PinstripePainter(Paint paint, double angle, double stripeWidth, double spacing) {
this.paint = paint;
this.angle = angle;
this.stripeWidth = stripeWidth;
this.spacing = spacing;
}
/**
* Set the paint to use for drawing the pinstripes
*
* @param p the Paint to use. May be a Color.
*/
public void setPaint(Paint p) {
Paint old = getPaint();
this.paint = p;
firePropertyChange("paint", old, getPaint());
}
/**
* Get the current paint used for drawing the pinstripes
* @return the Paint to use to draw the pinstripes
*/
public Paint getPaint() {
return paint;
}
/**
* Sets the angle, in degrees, at which to paint the pinstripes. If the
* given angle is < 0 or > 360, it will be appropriately constrained. For
* example, if a value of 365 is given, it will result in 5 degrees. The
* conversion is not perfect, but "a man on a galloping horse won't be
* able to tell the difference".
*
* @param angle the Angle in degrees at which to paint the pinstripes
*/
public void setAngle(double angle) {
if (angle > 360) {
angle = angle % 360;
}
if (angle < 0) {
angle = 360 - ((angle * -1) % 360);
}
double old = getAngle();
this.angle = angle;
firePropertyChange("angle", old, getAngle());
}
/**
* Gets the current angle of the pinstripes
* @return the angle, in degrees, at which the pinstripes are painted
*/
public double getAngle() {
return angle;
}
/**
* Sets the spacing between pinstripes
*
* @param spacing spacing between pinstripes
*/
public void setSpacing(double spacing) {
double old = getSpacing();
this.spacing = spacing;
firePropertyChange("spacing", old, getSpacing());
}
/**
* Get the current spacing between the stripes
* @return the spacing between pinstripes
*/
public double getSpacing() {
return spacing;
}
/**
* @inheritDoc
*/
public void doPaint(Graphics2D g, T component, int width, int height) {
//draws pinstripes at the angle specified in this class
//and at the given distance apart
Shape oldClip = g.getClip();
Area area = new Area(new Rectangle(0,0,width,height));
if(oldClip != null) {
area = new Area(oldClip);
}
area.intersect(new Area(new Rectangle(0,0,width,height)));
g.setClip(area);
//g.setClip(oldClip.intersection(new Rectangle(0,0,width,height)));
Paint p = getPaint();
if (p == null) {
if(component instanceof JComponent) {
g.setColor(((JComponent)component).getForeground());
}
} else {
g.setPaint(p);
}
g.setStroke(new BasicStroke((float)getStripeWidth()));
double hypLength = Math.sqrt((width * width) +
(height * height));
double radians = Math.toRadians(getAngle());
g.rotate(radians);
double spacing = getSpacing();
spacing += getStripeWidth();
int numLines = (int)(hypLength / spacing);
for (int i=0; i<numLines; i++) {
double x = i * spacing;
Line2D line = new Line2D.Double(x, -hypLength, x, hypLength);
g.draw(line);
}
g.setClip(oldClip);
}
/**
* Gets the current width of the pinstripes
* @return the current pinstripe width
*/
public double getStripeWidth() {
return stripeWidth;
}
/**
* Set the width of the pinstripes
* @param stripeWidth a new width for the pinstripes
*/
public void setStripeWidth(double stripeWidth) {
double oldSripeWidth = getStripeWidth();
this.stripeWidth = stripeWidth;
firePropertyChange("stripWidth",new Double(oldSripeWidth),new Double(stripeWidth));
}
}
|
package org.jivesoftware.messenger.launcher;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import javax.swing.*;
import org.jivesoftware.messenger.JiveGlobals;
import org.jivesoftware.util.XMLProperties;
import org.jdesktop.jdic.tray.TrayIcon;
import org.jdesktop.jdic.tray.SystemTray;
/**
* Graphical launcher for Jive Messenger.
*
* @author Matt Tucker
*/
public class Launcher {
private Process messengerd = null;
private String configFile = JiveGlobals.getMessengerHome() + File.separator + "conf" + File.separator + "jive-messenger.xml";
private JPanel toolbar = new JPanel();
private ImageIcon offIcon;
private ImageIcon onIcon;
private TrayIcon trayIcon;
/**
* Creates a new Launcher object.
*/
public Launcher() {
// Initialize the SystemTray now (to avoid a bug!)
final SystemTray tray = SystemTray.getDefaultSystemTray();
// Use the native look and feel.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.printStackTrace();
}
String title = "Jive Messenger";
final JFrame frame = new JFrame(title);
ImageIcon splash = null;
JLabel splashLabel = null;
// Set the icon.
try {
splash = new ImageIcon(getClass().getClassLoader().getResource("splash.gif"));
splashLabel = new JLabel("", splash, JLabel.LEFT);
onIcon = new ImageIcon(getClass().getClassLoader().getResource("messenger_on-16x16.gif"));
offIcon = new ImageIcon(getClass().getClassLoader().getResource("messenger_off-16x16.gif"));
frame.setIconImage(offIcon.getImage());
}
catch (Exception e) {
}
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Add buttons
final JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
final JButton stopButton = new JButton("Stop");
stopButton.setActionCommand("Stop");
final JButton browserButton = new JButton("Launch Admin");
browserButton.setActionCommand("Launch Admin");
final JButton quitButton = new JButton("Quit");
quitButton.setActionCommand("Quit");
toolbar.setLayout(new GridBagLayout());
toolbar.add(startButton, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
toolbar.add(stopButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
toolbar.add(browserButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
toolbar.add(quitButton, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
if (splashLabel != null) {
mainPanel.add(splashLabel, BorderLayout.CENTER);
}
mainPanel.add(toolbar, BorderLayout.SOUTH);
// create the main menu of the system tray icon
JPopupMenu menu = new JPopupMenu("Messenger Menu");
final JMenuItem showMenuItem = new JMenuItem("Hide");
showMenuItem.setActionCommand("Hide/Show");
menu.add(showMenuItem);
final JMenuItem startMenuItem = new JMenuItem("Start");
startMenuItem.setActionCommand("Start");
menu.add(startMenuItem);
final JMenuItem stopMenuItem = new JMenuItem("Stop");
stopMenuItem.setActionCommand("Stop");
menu.add(stopMenuItem);
final JMenuItem browserMenuItem = new JMenuItem("Launch Admin");
browserMenuItem.setActionCommand("Launch Admin");
menu.add(browserMenuItem);
menu.addSeparator();
final JMenuItem quitMenuItem = new JMenuItem("Quit");
quitMenuItem.setActionCommand("Quit");
menu.add(quitMenuItem);
browserButton.setEnabled(false);
stopButton.setEnabled(false);
browserMenuItem.setEnabled(false);
stopMenuItem.setEnabled(false);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Start")) {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Adjust button and menu items.
startApplication();
startButton.setEnabled(false);
stopButton.setEnabled(true);
startMenuItem.setEnabled(false);
stopMenuItem.setEnabled(true);
// Change to the "on" icon.
frame.setIconImage(onIcon.getImage());
trayIcon.setIcon(onIcon);
// Start a thread to enable the admin button after 8 seconds.
Thread thread = new Thread() {
public void run() {
try { sleep(8000); }
catch (Exception e) { }
// Enable the Launch Admin button/menu item only if the
// server has started.
if (stopButton.isEnabled()) {
browserButton.setEnabled(true);
browserMenuItem.setEnabled(true);
frame.setCursor(Cursor.getDefaultCursor());
}
}
};
thread.start();
}
else if (e.getActionCommand().equals("Stop")) {
stopApplication();
// Change to the "off" button.
frame.setIconImage(offIcon.getImage());
trayIcon.setIcon(offIcon);
// Adjust buttons and menu items.
frame.setCursor(Cursor.getDefaultCursor());
browserButton.setEnabled(false);
startButton.setEnabled(true);
stopButton.setEnabled(false);
browserMenuItem.setEnabled(false);
startMenuItem.setEnabled(true);
stopMenuItem.setEnabled(false);
}
else if (e.getActionCommand().equals("Launch Admin")) {
launchBrowser();
}
else if (e.getActionCommand().equals("Quit")) {
stopApplication();
System.exit(0);
}
else if (e.getActionCommand().equals("Hide/Show") || e.getActionCommand().equals("PressAction")) {
// Hide/Unhide the window if the user clicked in the system tray icon or
// selected the menu option
if (frame.isVisible()) {
frame.setVisible(false);
frame.setState(Frame.ICONIFIED);
showMenuItem.setText("Show");
}
else {
frame.setVisible(true);
frame.setState(Frame.NORMAL);
showMenuItem.setText("Hide");
}
}
}
};
// Register a listener for the radio buttons.
startButton.addActionListener(actionListener);
stopButton.addActionListener(actionListener);
browserButton.addActionListener(actionListener);
quitButton.addActionListener(actionListener);
// Register a listener for the menu items.
quitMenuItem.addActionListener(actionListener);
browserMenuItem.addActionListener(actionListener);
stopMenuItem.addActionListener(actionListener);
startMenuItem.addActionListener(actionListener);
showMenuItem.addActionListener(actionListener);
// Set the system tray icon with the menu
trayIcon = new TrayIcon(offIcon, "Jive Messenger", menu);
trayIcon.setIconAutoSize(true);
trayIcon.addActionListener(actionListener);
tray.addTrayIcon(trayIcon);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
stopApplication();
System.exit(0);
}
public void windowIconified(WindowEvent e) {
// Make the window disappear when minimized
frame.setVisible(false);
showMenuItem.setText("Show");
}
});
frame.getContentPane().add(mainPanel);
frame.pack();
// frame.setSize(539,418);
frame.setResizable(false);
GraphicUtils.centerWindowOnScreen(frame);
frame.setVisible(true);
// Start the app.
startButton.doClick();
}
/**
* Creates a new GUI launcher instance.
*/
public static void main(String[] args) {
new Launcher();
}
private synchronized void startApplication() {
if (messengerd == null) {
try {
File windowsExe = new File(new File("").getAbsoluteFile(), "messengerd.exe");
File unixExe = new File(new File("").getAbsoluteFile(), "messengerd");
if (windowsExe.exists()) {
messengerd = Runtime.getRuntime().exec(new String[] { windowsExe.toString() });
}
else if (unixExe.exists()) {
messengerd = Runtime.getRuntime().exec(new String[] { unixExe.toString() });
}
else {
throw new FileNotFoundException();
}
}
catch (Exception e) {
e.printStackTrace();
// Try one more time using the jar and hope java is on the path
try {
File libDir = new File("../lib").getAbsoluteFile();
messengerd = Runtime.getRuntime().exec(new String[]{
"java", "-jar", new File(libDir, "startup.jar").toString()
});
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null,
"Launcher could not start,\nJive Messenger",
"File not found", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private synchronized void stopApplication() {
if (messengerd != null) {
try {
messengerd.destroy();
messengerd.waitFor();
}
catch (Exception e) {
e.printStackTrace();
}
}
messengerd = null;
}
private synchronized void launchBrowser() {
try {
XMLProperties props = new XMLProperties(configFile);
String port = props.getProperty("adminConsole.port");
BrowserLauncher.openURL("http://127.0.0.1:" + port + "/index.html");
}
catch (Exception e) {
JOptionPane.showMessageDialog(new JFrame(), configFile + " " + e.getMessage());
}
}
}
|
package org.javarosa.core.services.storage.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.naming.NamingException;
import org.javarosa.core.services.PrototypeManager;
import org.javarosa.core.services.storage.EntityFilter;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.IStorageIterator;
import org.javarosa.core.services.storage.IStorageUtilityIndexed;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.services.storage.StorageFullException;
import org.javarosa.core.util.DataUtil;
import org.javarosa.core.util.InvalidIndexException;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.Externalizable;
/**
* @author ctsims
*
*/
public class DummyIndexedStorageUtility<T extends Persistable> implements IStorageUtilityIndexed<T> {
private Hashtable<String, Hashtable<Object, Vector<Integer>>> meta;
private Hashtable<Integer, T> data;
int curCount;
Class<T> prototype;
public DummyIndexedStorageUtility(Class<T> prototype) {
meta = new Hashtable<String, Hashtable<Object, Vector<Integer>>>();
data = new Hashtable<Integer, T>();
curCount = 0;
this.prototype = prototype;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtilityIndexed#getIDsForValue(java.lang.String, java.lang.Object)
*/
public Vector getIDsForValue(String fieldName, Object value) {
if(meta.get(fieldName) == null || meta.get(fieldName).get(value) == null) {
return new Vector<Integer>();
}
return meta.get(fieldName).get(value);
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtilityIndexed#getRecordForValue(java.lang.String, java.lang.Object)
*/
public T getRecordForValue(String fieldName, Object value) throws NoSuchElementException, InvalidIndexException {
if(meta.get(fieldName) == null) {
throw new NoSuchElementException("No record matching meta index " + fieldName + " with value " + value);
}
Vector<Integer> matches = meta.get(fieldName).get(value);
if(matches == null || matches.size() == 0) {
throw new NoSuchElementException("No record matching meta index " + fieldName + " with value " + value);
}
if(matches.size() > 1) {
throw new InvalidIndexException("Multiple records matching meta index " + fieldName + " with value " + value, fieldName);
}
return data.get(matches.elementAt(0));
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#add(org.javarosa.core.util.externalizable.Externalizable)
*/
public int add(T e) throws StorageFullException {
data.put(DataUtil.integer(curCount),e);
//This is not a legit pair of operations;
curCount++;
syncMeta();
return curCount - 1;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#close()
*/
public void close() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#exists(int)
*/
public boolean exists(int id) {
if(data.containsKey(DataUtil.integer(id))) {
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#getAccessLock()
*/
public Object getAccessLock() {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#getNumRecords()
*/
public int getNumRecords() {
return data.size();
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#getRecordSize(int)
*/
public int getRecordSize(int id) {
//serialize and test blah blah.
return 0;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#getTotalSize()
*/
public int getTotalSize() {
//serialize and test blah blah.
return 0;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#isEmpty()
*/
public boolean isEmpty() {
if(data.size() > 0) {
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#iterate()
*/
public IStorageIterator<T> iterate() {
//We should really find a way to invalidate old iterators first here
return new DummyStorageIterator<T>(data);
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#read(int)
*/
public T read(int id) {
//return data.get(DataUtil.integer(id));
try {
T t = prototype.newInstance();
t.readExternal(new DataInputStream(new ByteArrayInputStream(readBytes(id))), PrototypeManager.getDefault());
return t;
} catch (InstantiationException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (DeserializationException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#readBytes(int)
*/
public byte[] readBytes(int id) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
data.get(DataUtil.integer(id)).writeExternal(new DataOutputStream(stream));
return stream.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Couldn't serialize data to return to readBytes");
}
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#remove(int)
*/
public void remove(int id) {
data.remove(DataUtil.integer(id));
syncMeta();
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#remove(org.javarosa.core.services.storage.Persistable)
*/
public void remove(Persistable p) {
this.read(p.getID());
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#removeAll()
*/
public void removeAll() {
data.clear();
meta.clear();
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#removeAll(org.javarosa.core.services.storage.EntityFilter)
*/
public Vector<Integer> removeAll(EntityFilter ef) {
Vector<Integer> removed = new Vector<Integer>();
for(Enumeration en = data.keys(); en.hasMoreElements() ;) {
Integer i = (Integer)en.nextElement();
switch(ef.preFilter(i.intValue(),null)) {
case EntityFilter.PREFILTER_INCLUDE:
removed.addElement(i);
break;
case EntityFilter.PREFILTER_EXCLUDE:
continue;
}
if(ef.matches(data.get(i))) {
removed.addElement(i);
}
}
for(Integer i : removed) {
data.remove(i);
}
syncMeta();
return removed;
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#repack()
*/
public void repack() {
//Unecessary!
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#repair()
*/
public void repair() {
//Unecessary!
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#update(int, org.javarosa.core.util.externalizable.Externalizable)
*/
public void update(int id, T e) throws StorageFullException {
data.put(DataUtil.integer(id), e);
syncMeta();
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.IStorageUtility#write(org.javarosa.core.services.storage.Persistable)
*/
public void write(Persistable p) throws StorageFullException {
if(p.getID() != -1) {
this.data.put(DataUtil.integer(p.getID()), (T)p);
syncMeta();
} else {
p.setID(curCount);
this.add((T)p);
}
}
private void syncMeta() {
meta.clear();
for(Enumeration en = data.keys(); en.hasMoreElements() ; ) {
Integer i = (Integer)en.nextElement();
Externalizable e = (Externalizable)data.get(i);
if( e instanceof IMetaData ) {
IMetaData m = (IMetaData)e;
for(String key : m.getMetaDataFields()) {
if(!meta.containsKey(key)) {
meta.put(key, new Hashtable<Object,Vector<Integer>>());
}
}
for(String key : dynamicIndices) {
if(!meta.containsKey(key)) {
meta.put(key, new Hashtable<Object,Vector<Integer>>());
}
}
for(Enumeration keys = meta.keys() ; keys.hasMoreElements();) {
String key = (String)keys.nextElement();
Object value = m.getMetaData(key);
Hashtable<Object,Vector<Integer>> records = meta.get(key);
if(!records.containsKey(value)) {
records.put(value, new Vector<Integer>());
}
Vector<Integer> indices = records.get(value);
if(!indices.contains(i)) {
records.get(value).addElement(i);
}
}
}
}
}
public void setReadOnly() {
//TODO: This should have a clear contract.
}
Vector<String> dynamicIndices = new Vector<String>();
public void registerIndex(String filterIndex) {
dynamicIndices.addElement(filterIndex);
}
}
|
package org.jivesoftware.spark.ui.rooms;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromMatchesFilter;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.MessageEventManager;
import org.jivesoftware.smackx.packet.MessageEvent;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomButton;
import org.jivesoftware.spark.ui.ContactItem;
import org.jivesoftware.spark.ui.ContactList;
import org.jivesoftware.spark.ui.MessageEventListener;
import org.jivesoftware.spark.ui.RosterDialog;
import org.jivesoftware.spark.ui.VCardPanel;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscript;
import org.jivesoftware.sparkimpl.plugin.transcripts.ChatTranscripts;
import org.jivesoftware.sparkimpl.plugin.transcripts.HistoryMessage;
import org.jivesoftware.sparkimpl.profile.VCardManager;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import javax.swing.Icon;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;
/**
* This is the Person to Person implementation of <code>ChatRoom</code>
* This room only allows for 1 to 1 conversations.
*/
public class ChatRoomImpl extends ChatRoom {
private List messageEventListeners = new ArrayList();
private String roomname;
private Icon tabIcon;
private String roomTitle;
private String tabTitle;
private String participantJID;
private String participantNickname;
private Presence presence;
private boolean offlineSent;
private Roster roster;
private long lastTypedCharTime;
private boolean sendNotification;
private TimerTask typingTimerTask;
private boolean sendTypingNotification;
private String threadID;
private long lastActivity;
/**
* Constructs a 1-to-1 ChatRoom.
*
* @param participantJID the participants jid to chat with.
* @param participantNickname the nickname of the participant.
* @param title the title of the room.
*/
public ChatRoomImpl(final String participantJID, String participantNickname, String title) {
this.participantJID = participantJID;
this.participantNickname = participantNickname;
// Loads the current history for this user.
loadHistory();
// Register PacketListeners
PacketFilter fromFilter = new FromMatchesFilter(participantJID);
PacketFilter orFilter = new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class));
PacketFilter andFilter = new AndFilter(orFilter, fromFilter);
SparkManager.getConnection().addPacketListener(this, andFilter);
// The roomname will be the participantJID
this.roomname = participantJID;
// Use the agents username as the Tab Title
this.tabTitle = title;
// The name of the room will be the node of the user jid + conversation.
final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
this.roomTitle = participantNickname;
// Add RoomInfo
this.getSplitPane().setRightComponent(null);
getSplitPane().setDividerSize(0);
presence = PresenceManager.getPresence(participantJID);
roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(participantJID);
tabIcon = PresenceManager.getIconFromPresence(presence);
// Create toolbar buttons.
ChatRoomButton infoButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_24x24));
infoButton.setToolTipText(Res.getString("message.view.information.about.this.user"));
// Create basic toolbar.
getToolBar().addChatRoomButton(infoButton);
// If the user is not in the roster, then allow user to add them.
if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) {
ChatRoomButton addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24));
addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster"));
getToolBar().addChatRoomButton(addToRosterButton);
addToRosterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RosterDialog rosterDialog = new RosterDialog();
rosterDialog.setDefaultJID(participantJID);
rosterDialog.setDefaultNickname(getParticipantNickname());
rosterDialog.showRosterDialog(SparkManager.getChatManager().getChatContainer().getChatFrame());
}
});
}
// Show VCard.
infoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
VCardManager vcard = SparkManager.getVCardManager();
vcard.viewProfile(participantJID, SparkManager.getChatManager().getChatContainer());
}
});
// If this is a private chat from a group chat room, do not show toolbar.
if (StringUtils.parseResource(participantJID).equals(participantNickname)) {
getToolBar().setVisible(false);
}
typingTimerTask = new TimerTask() {
public void run() {
if (!sendTypingNotification) {
return;
}
long now = System.currentTimeMillis();
if (now - lastTypedCharTime > 2000) {
if (!sendNotification) {
// send cancel
SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID);
sendNotification = true;
}
}
}
};
TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000);
lastActivity = System.currentTimeMillis();
}
public void closeChatRoom() {
super.closeChatRoom();
// Send a cancel notification event on closing if listening.
if (!sendNotification) {
// send cancel
SparkManager.getMessageEventManager().sendCancelledNotification(getParticipantJID(), threadID);
sendNotification = true;
}
SparkManager.getChatManager().removeChat(this);
SparkManager.getConnection().removePacketListener(this);
typingTimerTask.cancel();
}
public void sendMessage() {
String text = getChatInputEditor().getText();
sendMessage(text);
}
public void sendMessage(String text) {
final Message message = new Message();
if (threadID == null) {
threadID = StringUtils.randomString(6);
}
message.setThread(threadID);
// Set the body of the message using typedMessage
message.setBody(text);
// IF there is no body, just return and do nothing
if (!ModelUtil.hasLength(text)) {
return;
}
// Fire Message Filters
SparkManager.getChatManager().filterOutgoingMessage(this, message);
// Fire Global Filters
SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);
sendMessage(message);
sendNotification = true;
}
/**
* Sends a message to the appropriate jid. The message is automatically added to the transcript.
*
* @param message the message to send.
*/
public void sendMessage(Message message) {
lastActivity = System.currentTimeMillis();
try {
getTranscriptWindow().insertMessage(getNickname(), message, ChatManager.TO_COLOR);
getChatInputEditor().selectAll();
getTranscriptWindow().validate();
getTranscriptWindow().repaint();
getChatInputEditor().clear();
}
catch (Exception ex) {
Log.error("Error sending message", ex);
}
// Before sending message, let's add our full jid for full verification
message.setType(Message.Type.chat);
message.setTo(participantJID);
message.setFrom(SparkManager.getSessionManager().getJID());
// Notify users that message has been sent
fireMessageSent(message);
addToTranscript(message, false);
getChatInputEditor().setCaretPosition(0);
getChatInputEditor().requestFocusInWindow();
scrollToBottom();
// No need to request displayed or delivered as we aren't doing anything with this
// information.
MessageEventManager.addNotificationsRequests(message, true, false, false, true);
// Send the message that contains the notifications request
try {
fireOutgoingMessageSending(message);
SparkManager.getConnection().sendPacket(message);
}
catch (Exception ex) {
Log.error("Error sending message", ex);
}
}
public String getRoomname() {
return roomname;
}
public Icon getTabIcon() {
return tabIcon;
}
public void setTabIcon(Icon icon) {
this.tabIcon = icon;
}
public String getTabTitle() {
return tabTitle;
}
public void setTabTitle(String tabTitle) {
this.tabTitle = tabTitle;
}
public void setRoomTitle(String roomTitle) {
this.roomTitle = roomTitle;
}
public String getRoomTitle() {
return roomTitle;
}
public Message.Type getChatType() {
return Message.Type.chat;
}
public void leaveChatRoom() {
// There really is no such thing in Agent to Agent
}
public boolean isActive() {
return true;
}
public String getParticipantJID() {
return participantJID;
}
/**
* Returns the users full jid (ex. macbeth@jivesoftware.com/spark).
*
* @return the users Full JID.
*/
public String getJID() {
presence = PresenceManager.getPresence(getParticipantJID());
return presence.getFrom();
}
/**
* Process incoming packets.
*
* @param packet - the packet to process
*/
public void processPacket(final Packet packet) {
final Runnable runnable = new Runnable() {
public void run() {
if (packet instanceof Presence) {
presence = (Presence)packet;
final Presence presence = (Presence)packet;
ContactList list = SparkManager.getWorkspace().getContactList();
ContactItem contactItem = list.getContactItemByJID(getParticipantJID());
final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
String time = formatter.format(new Date());
if (presence.getType() == Presence.Type.unavailable && contactItem != null) {
if (isOnline()) {
getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.went.offline", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
}
}
else if (presence.getType() == Presence.Type.available) {
if (!isOnline()) {
getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.came.online", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
}
}
}
else if (packet instanceof Message) {
lastActivity = System.currentTimeMillis();
// Do something with the incoming packet here.
final Message message = (Message)packet;
if (message.getError() != null) {
if (message.getError().getCode() == 404) {
// Check to see if the user is online to recieve this message.
RosterEntry entry = roster.getEntry(participantJID);
if (!presence.isAvailable() && !offlineSent && entry != null) {
getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline.error"), ChatManager.ERROR_COLOR);
offlineSent = true;
}
}
return;
}
// Check to see if the user is online to recieve this message.
RosterEntry entry = roster.getEntry(participantJID);
if (!presence.isAvailable() && !offlineSent && entry != null) {
getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline"), ChatManager.ERROR_COLOR);
offlineSent = true;
}
if (threadID == null) {
threadID = message.getThread();
if (threadID == null) {
threadID = StringUtils.randomString(6);
}
}
boolean broadcast = message.getProperty("broadcast") != null;
// If this is a group chat message, discard
if (message.getType() == Message.Type.groupchat || broadcast) {
return;
}
// Do not accept Administrative messages.
final String host = SparkManager.getSessionManager().getServerAddress();
if (host.equals(message.getFrom())) {
return;
}
// If the message is not from the current agent. Append to chat.
if (message.getBody() != null) {
participantJID = message.getFrom();
insertMessage(message);
showTyping(false);
}
}
}
};
SwingUtilities.invokeLater(runnable);
}
/**
* Returns the nickname of the user chatting with.
*
* @return the nickname of the chatting user.
*/
public String getParticipantNickname() {
return participantNickname;
}
/**
* The current SendField has been updated somehow.
*
* @param e - the DocumentEvent to respond to.
*/
public void insertUpdate(DocumentEvent e) {
checkForText(e);
if (!sendTypingNotification) {
return;
}
lastTypedCharTime = System.currentTimeMillis();
// If the user pauses for more than two seconds, send out a new notice.
if (sendNotification) {
try {
SparkManager.getMessageEventManager().sendComposingNotification(getParticipantJID(), threadID);
sendNotification = false;
}
catch (Exception exception) {
Log.error("Error updating", exception);
}
}
}
public void insertMessage(Message message) {
// Debug info
super.insertMessage(message);
MessageEvent messageEvent = (MessageEvent)message.getExtension("x", "jabber:x:event");
if (messageEvent != null) {
checkEvents(message.getFrom(), message.getPacketID(), messageEvent);
}
getTranscriptWindow().insertMessage(participantNickname, message, ChatManager.FROM_COLOR);
// Set the participant jid to their full JID.
participantJID = message.getFrom();
}
private void checkEvents(String from, String packetID, MessageEvent messageEvent) {
if (messageEvent.isDelivered() || messageEvent.isDisplayed()) {
// Create the message to send
Message msg = new Message(from);
// Create a MessageEvent Package and add it to the message
MessageEvent event = new MessageEvent();
if (messageEvent.isDelivered()) {
event.setDelivered(true);
}
if (messageEvent.isDisplayed()) {
event.setDisplayed(true);
}
event.setPacketID(packetID);
msg.addExtension(event);
// Send the packet
SparkManager.getConnection().sendPacket(msg);
}
}
public void addMessageEventListener(MessageEventListener listener) {
messageEventListeners.add(listener);
}
public void removeMessageEventListener(MessageEventListener listener) {
messageEventListeners.remove(listener);
}
public Collection getMessageEventListeners() {
return messageEventListeners;
}
public void fireOutgoingMessageSending(Message message) {
Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator();
while (messageEventListeners.hasNext()) {
((MessageEventListener)messageEventListeners.next()).sendingMessage(message);
}
}
public void fireReceivingIncomingMessage(Message message) {
Iterator messageEventListeners = new ArrayList(getMessageEventListeners()).iterator();
while (messageEventListeners.hasNext()) {
((MessageEventListener)messageEventListeners.next()).receivingMessage(message);
}
}
/**
* Show the typing notification.
*
* @param typing true if the typing notification should show, otherwise hide it.
*/
public void showTyping(boolean typing) {
if (typing) {
String isTypingText = Res.getString("message.is.typing.a.message", participantNickname);
getNotificationLabel().setText(isTypingText);
getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE));
}
else {
// Remove is typing text.
getNotificationLabel().setText("");
getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.BLANK_IMAGE));
}
}
/**
* The last time this chat room sent or received a message.
*
* @return the last time this chat room sent or receieved a message.
*/
public long getLastActivity() {
return lastActivity;
}
/**
* Returns the current presence of the client this room was created for.
*
* @return the presence
*/
public Presence getPresence() {
return presence;
}
public void setSendTypingNotification(boolean isSendTypingNotification) {
this.sendTypingNotification = isSendTypingNotification;
}
public void connectionClosed() {
handleDisconnect();
String message = Res.getString("message.disconnected.error");
getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR);
}
public void connectionClosedOnError(Exception ex) {
handleDisconnect();
String message = Res.getString("message.disconnected.error");
if (ex instanceof XMPPException) {
XMPPException xmppEx = (XMPPException)ex;
StreamError error = xmppEx.getStreamError();
String reason = error.getCode();
if ("conflict".equals(reason)) {
message = Res.getString("message.disconnected.conflict.error");
}
}
getTranscriptWindow().insertNotificationMessage(message, ChatManager.ERROR_COLOR);
}
public void reconnectionSuccessful() {
Presence usersPresence = PresenceManager.getPresence(getParticipantJID());
if (usersPresence.isAvailable()) {
presence = usersPresence;
}
SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this);
getChatInputEditor().setEnabled(true);
getSendButton().setEnabled(true);
}
private void handleDisconnect() {
presence = new Presence(Presence.Type.unavailable);
getChatInputEditor().setEnabled(false);
getSendButton().setEnabled(false);
SparkManager.getChatManager().getChatContainer().fireChatRoomStateUpdated(this);
}
private void loadHistory() {
// Add VCard Panel
final VCardPanel vcardPanel = new VCardPanel(participantJID);
getToolBar().add(vcardPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 0, 2), 0, 0));
final LocalPreferences localPreferences = SettingsManager.getLocalPreferences();
if (!localPreferences.isChatHistoryEnabled()) {
return;
}
final String bareJID = StringUtils.parseBareAddress(getParticipantJID());
final ChatTranscript chatTranscript = ChatTranscripts.getCurrentChatTranscript(bareJID);
final String personalNickname = SparkManager.getUserManager().getNickname();
for (HistoryMessage message : chatTranscript.getMessages()) {
String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
String messageBody = message.getBody();
if (nickname.equals(message.getFrom())) {
String otherJID = StringUtils.parseBareAddress(message.getFrom());
String myJID = SparkManager.getSessionManager().getBareAddress();
if (otherJID.equals(myJID)) {
nickname = personalNickname;
}
else {
nickname = StringUtils.parseName(nickname);
}
}
if (ModelUtil.hasLength(messageBody) && messageBody.startsWith("/me ")) {
messageBody = messageBody.replaceAll("/me", nickname);
}
final Date messageDate = message.getDate();
getTranscriptWindow().insertHistoryMessage(nickname, messageBody, messageDate);
}
}
private boolean isOnline() {
Presence presence = roster.getPresence(getParticipantJID());
return presence.isAvailable();
}
}
|
package cruise.umple.statemachine.implementation;
import java.lang.reflect.Field;
import org.junit.*;
import cruise.umple.compiler.Event;
public class StateMachineTest extends StateMachineTemplateTest
{
// SIMPLE STATES
@Test
public void NoStates()
{
assertUmpleTemplateFor("SimpleStateMachine.ump",languagePath + "/SimpleStateMachine."+ languagePath +".txt","Mentor");
}
@Test
public void OneState()
{
assertUmpleTemplateFor("SimpleStateMachine.ump",languagePath + "/SimpleStateMachine_OneState."+ languagePath +".txt","Student");
}
@Test
public void TwoState()
{
assertUmpleTemplateFor("SimpleStateMachine.ump",languagePath + "/SimpleStateMachine_TwoStates."+ languagePath +".txt","Course");
}
// TRANSITIONS
@Test
public void EventTransitionSameState()
{
assertUmpleTemplateFor("EventTransition.ump",languagePath + "/EventTransition."+ languagePath +".txt","Course");
}
@Test
public void EventTransitionNewState()
{
assertUmpleTemplateFor("EventTransition.ump",languagePath + "/EventTransition_NewState."+ languagePath +".txt","Light");
}
@Test
public void EmptyAndNonEmptyStates()
{
assertUmpleTemplateFor("EmptyAndNonEmptyStates.ump",languagePath + "/EmptyAndNonEmptyStates."+ languagePath +".txt","Light");
}
// GUARDS
@Test
public void oneGuard()
{
assertUmpleTemplateFor("oneGuard.ump",languagePath + "/oneGuard."+ languagePath +".txt","LightFixture");
}
@Test
public void multipleGuardsSameEvent()
{
assertUmpleTemplateFor("multipleGuardsSameEvent.ump",languagePath + "/multipleGuardsSameEvent."+ languagePath +".txt","LightFixture");
}
@Test
public void multipleGuardsSameEventWithDefaultNoGuard()
{
assertUmpleTemplateFor("multipleGuardsSameEventWithDefaultNoGuard.ump",languagePath + "/multipleGuardsSameEventWithDefaultNoGuard."+ languagePath +".txt","LightFixture");
}
// SPACING
// Spacing of state transaction actions
@Test // Test the spacing problems in issue 155
public void guardSpacing() {
assertUmpleTemplateFor("guardSpacing.ump",languagePath + "/guardSpacing."+ languagePath +".txt","Garage");
}
@Test //Test the spacing problems in issues 154
public void stateMachineSpacing() {
assertUmpleTemplateFor("stateMachineSpacing1.ump",languagePath + "/stateMachineSpacing1."+ languagePath +".txt","Garage");
assertUmpleTemplateFor("stateMachineSpacing2.ump",languagePath + "/stateMachineSpacing2."+ languagePath +".txt","Garage");
}
// Spacing of state names (issue 399)
/**
* Tests spacing issues by changing the spacing in the test file for <{@link #NoStates()}.
* Changing the spacing should have no effect on the output and so this method compares to the same
* output files as {@link #NoStates()}.
* <p>This test case addresses <b>issue 399</b>.
* @author Kenan Kigunda
* @since September 20, 2013
*/
@Test
public void stateNameSpacingForNoStates() {
assertUmpleTemplateFor("SimpleStateMachineSpacing.ump",languagePath + "/SimpleStateMachine."+ languagePath +".txt","Mentor");
}
/**
* Test spacing issues by changing the spacing in the test file for {@link #OneState()}.
* @see #stateNameSpacingForNoStates()
*/
@Test
public void stateNameSpacingForOneState() {
assertUmpleTemplateFor("SimpleStateMachineSpacing.ump",languagePath + "/SimpleStateMachine_OneState."+ languagePath +".txt","Student");
}
/**
* Test spacing issues by changing the spacing in the test file for {@link #TwoState()}.
* @see #stateNameSpacingForNoStates()
*/
@Test
public void stateNameSpacingForTwoStates() {
assertUmpleTemplateFor("SimpleStateMachineSpacing.ump",languagePath + "/SimpleStateMachine_TwoStates."+ languagePath +".txt","Course");
}
/**
* Test spacing issues by changing the spacing in the test file for {@link #EventTransitionSameState()}.
* @see #stateNameSpacingForNoStates()
*/
@Test
public void stateNameSpacingForEventTransitionSameState() {
assertUmpleTemplateFor("EventTransitionSpacing.ump",languagePath + "/EventTransition_NewState."+ languagePath +".txt","Light");
}
/**
* Test spacing issues by changing the spacing in the test file for {@link #EventTransitionNewState()}.
* @see #stateNameSpacingForNoStates()
*/
@Test
public void stateNameSpacingForEventTransitionNewState() {
assertUmpleTemplateFor("EventTransitionSpacing.ump",languagePath + "/EventTransition."+ languagePath +".txt","Course");
}
// ACTIONS
@Test
public void transitionAction()
{
assertUmpleTemplateFor("transitionAction.ump",languagePath + "/transitionAction."+ languagePath +".txt","Course");
}
@Test
public void entryAction()
{
assertUmpleTemplateFor("entryAction.ump",languagePath + "/entryAction."+ languagePath +".txt","Light");
}
@Test
public void doActivity()
{
assertUmpleTemplateFor("doActivity.ump",languagePath + "/doActivity."+ languagePath +".txt","Switch");
}
@Test
public void doActivity_Multiple()
{
assertUmpleTemplateFor("doActivity.ump",languagePath + "/doActivityMultiple."+ languagePath +".txt","Lamp");
}
@Test
public void doActivityNestedStateMachine()
{
assertUmpleTemplateFor("doActivityNestedStateMachine.ump",languagePath + "/doActivityNestedStateMachine."+ languagePath +".txt","Course");
}
@Test
public void exitAction()
{
assertUmpleTemplateFor("exitAction.ump",languagePath + "/exitAction."+ languagePath +".txt","LightFixture");
}
@Test
public void entryExitTransitionAction()
{
assertUmpleTemplateFor("entryExitTransitionAction.ump",languagePath + "/entryExitTransitionAction."+ languagePath +".txt","LightFixture");
}
@Test
public void entryExitTransitionActionWithGuard()
{
assertUmpleTemplateFor("entryExitTransitionActionWithGuard.ump",languagePath + "/entryExitTransitionActionWithGuard."+ languagePath +".txt","LightFixture");
}
@Test
public void externalStateMachine()
{
assertUmpleTemplateFor("externalStateMachine.ump",languagePath + "/externalStateMachine."+ languagePath +".txt","Course");
}
@Test
public void timedEvent()
{
assertUmpleTemplateFor("timedEvent.ump",languagePath + "/timedEvent."+ languagePath +".txt","Mentor");
}
@Test
public void sameEvent_twoStates_differentStatemachines()
{
assertUmpleTemplateFor("sameEvent_twoStates_differentStateMachines.ump",languagePath + "/sameEvent_twoStates_differentStatemachines."+ languagePath +".txt","LightFixture");
}
@Test
public void nestedStates()
{
assertUmpleTemplateFor("nestedStates.ump",languagePath + "/nestedStates."+ languagePath +".txt","LightFixture");
}
@Test
public void nestedStates_exitInnerBeforeOutter()
{
assertUmpleTemplateFor("nestedStates_exitInnerBeforeOutter.ump",languagePath + "/nestedStates_exitInnerBeforeOutter."+ languagePath +".txt","LightFixture");
}
@Test
public void concurrentStates()
{
assertUmpleTemplateFor("concurrentStates_normal.ump",languagePath + "/concurrentStates_normal."+ languagePath +".txt","LightFixture");
}
@Test
public void before_after_setMethod()
{
assertUmpleTemplateFor("BeforeAndAfter_StateMachineSet.ump",languagePath + "/BeforeAndAfter_StateMachineSet."+ languagePath +".txt","LightFixture");
}
@Test
public void activeObject()
{
assertUmpleTemplateFor("activeObject.ump", languagePath + "/activeObject."+ languagePath + ".txt", "Lamp");
}
@Test
public void finalState()
{
assertUmpleTemplateFor("FinalState.ump",languagePath + "/FinalState."+ languagePath +".txt","Mentor");
}
@Test
public void eventWithArguments(){
assertUmpleTemplateFor("eventWithArguments.ump",languagePath + "/eventWithArguments."+ languagePath +".txt","LightFixture");
}
@Test
public void eventWithArguments_1(){
assertUmpleTemplateFor("eventWithArguments_1.ump",languagePath + "/eventWithArguments_1."+ languagePath +".txt","LightFixture");
}
@Test
public void eventWithArguments_2(){
assertUmpleTemplateFor("eventWithArguments_2.ump",languagePath + "/eventWithArguments_2."+ languagePath +".txt","Course");
}
@Test
public void twoEventsWithArguments(){
assertUmpleTemplateFor("twoEventsWithArguments.ump",languagePath + "/twoEventsWithArguments."+ languagePath +".txt","Course");
}
@Test
public void autoEventTransition() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
{
Field f1 = Event.class.getDeclaredField("nextAutoTransitionId");
f1.setAccessible(true);
f1.setInt(null, 1);
assertUmpleTemplateFor("AutoEventTransition.ump",languagePath + "/AutoEventTransition."+ languagePath +".txt","Light");
}
@Test
public void queuedStateMachine()
{
assertUmpleTemplateFor("queuedStateMachine.ump",languagePath + "/queuedStateMachine."+ languagePath +".txt","Course");
}
@Test
public void queuedStateMachine_2()
{
assertUmpleTemplateFor("queuedStateMachine_2.ump",languagePath + "/queuedStateMachine_2."+ languagePath +".txt","GarageDoor");
}
@Test
public void queuedStateMachine_withParameters()
{
assertUmpleTemplateFor("queuedStateMachine_withParameters.ump",languagePath + "/queuedStateMachine_withParameters."+ languagePath +".txt","LightFixture");
}
@Test
public void queuedStateMachine_withParameters_1()
{
assertUmpleTemplateFor("queuedStateMachine_withParameters_1.ump",languagePath + "/queuedStateMachine_withParameters_1."+ languagePath +".txt","LightFixture");
}
@Test
public void queuedWithNestingStateMachines()
{
assertUmpleTemplateFor("queuedWithNestedStateMachines.ump",languagePath + "/queuedWithNestedStateMachines."+ languagePath +".txt","QueuedWithNestedStateMachines");
}
@Test
public void queuedWithConcurrentStateMachines()
{
assertUmpleTemplateFor("queuedWithConcurrentStateMachines.ump",languagePath + "/queuedWithConcurrentStateMachines."+ languagePath +".txt","QueuedWithConcurrentStateMachines");
}
@Test
public void queuedSMwithConcurrentStatesTest()
{
assertUmpleTemplateFor("queuedSMwithConcurrentStatesTest.ump",languagePath + "/queuedSMwithConcurrentStatesTest."+ languagePath +".txt","QueuedSMwithConcurrentStates");
}
@Test
public void queuedSMwithConcurrentStatesTest_2()
{
assertUmpleTemplateFor("queuedSMwithConcurrentStatesTest_2.ump",languagePath + "/queuedSMwithConcurrentStatesTest_2."+ languagePath +".txt","QueuedSMwithConcurrentStates_2");
}
@Test
public void queuedWithConcurrensStatesCourseAttempt()
{
assertUmpleTemplateFor("queuedWithConcurrensStatesCourseAttempt.ump",languagePath + "/queuedWithConcurrensStatesCourseAttempt."+ languagePath +".txt","CourseAttempt");
}
@Test
public void queuedWithNestingStatesATM()
{
assertUmpleTemplateFor("queuedWithNestingStatesATM.ump",languagePath + "/queuedWithNestingStatesATM."+ languagePath +".txt","AutomatedTellerMachine");
}
@Test
public void nestedStatesOfQSMwithSameEventNames()
{
assertUmpleTemplateFor("nestedStatesOfQSMwithSameEventNames.ump",languagePath + "/nestedStatesOfQSMwithSameEventNames."+ languagePath +".txt","NestedStatesWthSameEventNames");
}
@Test
public void queuedStateMachine_autoTransition()
{
assertUmpleTemplateFor("queuedStateMachine_autoTransition.ump",languagePath + "/queuedStateMachine_autoTransition."+ languagePath +".txt","Light");
}
@Test
public void queuedStateMachine_timedEvents()
{
assertUmpleTemplateFor("queuedStateMachine_timedEvents.ump",languagePath + "/queuedStateMachine_timedEvents."+ languagePath +".txt","Mentor");
}
@Test
public void pooledStateMachine_timedEvents()
{
assertUmpleTemplateFor("pooledStateMachine_timedEvents.ump",languagePath + "/pooledStateMachine_timedEvents."+ languagePath +".txt","Mentor");
}
@Test
public void pooledStateMachine()
{
assertUmpleTemplateFor("pooledStateMachine.ump",languagePath + "/pooledStateMachine."+ languagePath +".txt","Course");
}
@Test
public void pooledStateMachine_withParameters()
{
assertUmpleTemplateFor("pooledStateMachine_withParameters.ump",languagePath + "/pooledStateMachine_withParameters."+ languagePath +".txt","LightFixture");
}
@Test
public void pooledStateMachine_autoTransition()
{
assertUmpleTemplateFor("pooledStateMachine_autoTransition.ump",languagePath + "/pooledStateMachine_autoTransition."+ languagePath +".txt","Light");
}
@Test
public void pooledStateMachineWithConcurrentStates_autoTransition()
{
assertUmpleTemplateFor("pooledStateMachineWithConcurrentStates_autoTransition.ump",languagePath + "/pooledStateMachineWithConcurrentStates_autoTransition."+ languagePath +".txt","CourseAttempt");
}
@Test @Ignore
public void queuedStateMachine_timedEvents_and_autoTansitions()
{
assertUmpleTemplateFor("queuedStateMachine_timedEvents_and_autoTansitions.ump",languagePath + "/queuedStateMachine_timedEvents_and_autoTansitions."+ languagePath +".txt","X");
}
@Test @Ignore
public void pooledStateMachine_timedEvents_and_autoTansitions()
{
assertUmpleTemplateFor("pooledStateMachine_timedEvents_and_autoTansitions.ump",languagePath + "/pooledStateMachine_timedEvents_and_autoTansitions."+ languagePath +".txt","X");
}
@Test @Ignore
public void stateMachine_UnspecifiedReception()
{
assertUmpleTemplateFor("stateMachine_UnspecifiedReception.ump",languagePath + "/stateMachine_UnspecifiedReception."+ languagePath +".txt","Course");
}
@Test
public void stateMachine_unSpecifiedReception_QSM()
{
assertUmpleTemplateFor("stateMachine_unSpecifiedReception_QSM.ump",languagePath + "/stateMachine_unSpecifiedReception_QSM."+ languagePath +".txt","QSMwithUnspecifiedRecep");
}
@Test
public void queuedSM_UnspecifiedReception()
{
assertUmpleTemplateFor("queuedSM_UnspecifiedRecep.ump",languagePath + "/queuedSM_UnspecifiedRecep."+ languagePath +".txt","AutomatedTellerMachine");
}
@Test
public void nestedStates_UnspecifiedReception()
{
assertUmpleTemplateFor("nestedStates_UnspecifiedReception.ump",languagePath + "/nestedStates_UnspecifiedReception."+ languagePath +".txt","NestedStatesWthSameEventNames");
}
}
|
package de.alpharogroup.crypto.key.writer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import de.alpharogroup.file.write.WriteFileExtensions;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
/**
* The class {@link PrivateKeyWriter} is a utility class for write public keys in files or streams.
*/
@UtilityClass
public class PrivateKeyWriter
{
/**
* Write the given {@link PrivateKey} into the given {@link File}.
*
* @param privateKey
* the private key
* @param file
* the file to write in
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void write(final PrivateKey privateKey, final @NonNull File file)
throws IOException
{
write(privateKey, new FileOutputStream(file));
}
/**
* Write the given {@link PrivateKey} into the given {@link OutputStream}.
*
* @param privateKey
* the private key
* @param outputStream
* the output stream to write in
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void write(final PrivateKey privateKey, final @NonNull OutputStream outputStream)
throws IOException
{
final byte[] privateKeyBytes = privateKey.getEncoded();
final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
outputStream.write(keySpec.getEncoded());
outputStream.close();
}
/**
* Write the given {@link PrivateKey} into the given {@link File}.
*
* @param privateKey
* the private key
* @param file
* the file to write in
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void writeInPemFormat(final PrivateKey privateKey, final @NonNull File file)
throws IOException
{
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
pemWriter.writeObject(privateKey);
pemWriter.close();
String pemFormat = stringWriter.toString();
pemFormat = pemFormat.replaceAll("\\r\\n", "\\\n");
WriteFileExtensions.string2File(file, pemFormat);
}
}
|
package jp.gr.java_conf.neko_daisuki.nexec_x.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import jp.gr.java_conf.neko_daisuki.android.nexec.client.util.NexecClient;
public class XView extends View {
private interface ActionUpProc {
public void run();
}
private interface TouchEventHandler {
public class Nop implements TouchEventHandler {
@Override
public boolean run(MotionEvent event) {
return false;
}
}
public boolean run(MotionEvent event);
}
private class ActionDownHandler implements TouchEventHandler {
@Override
public boolean run(MotionEvent event) {
xMotionNotify(event);
mDownTime = SystemClock.uptimeMillis();
return true;
}
}
private class ActionUpHandler implements TouchEventHandler {
private class NopActionUpProc implements ActionUpProc {
@Override
public void run() {
}
}
private class ClickingActionUpProc implements ActionUpProc {
@Override
public void run() {
mClient.xLeftButtonPress();
mClient.xLeftButtonRelease();
}
}
private ActionUpProc mNop = new NopActionUpProc();
private ActionUpProc mClickingProc = new ClickingActionUpProc();
@Override
public boolean run(MotionEvent event) {
long deltaT = mDownTime - SystemClock.uptimeMillis();
ActionUpProc proc = deltaT < 400 ? mClickingProc : mNop;
proc.run();
return true;
}
}
private class ActionMoveHandler implements TouchEventHandler {
@Override
public boolean run(MotionEvent event) {
xMotionNotify(event);
return true;
}
}
private NexecClient mClient;
private long mDownTime;
// helpers
private SparseArray<TouchEventHandler> mHandlers;
private TouchEventHandler mNopHandler = new TouchEventHandler.Nop();
public XView(Context context) {
super(context);
initialize();
}
public XView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public XView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
public void setNexecClient(NexecClient client) {
mClient = client;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
TouchEventHandler handler = mHandlers.get(event.getActionMasked());
return (handler != null ? handler : mNopHandler).run(event);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap bitmap = mClient.xDraw();
if (bitmap == null) {
return;
}
canvas.drawBitmap(bitmap, 0.0f, 0.0f, null);
}
private void initialize() {
mHandlers = new SparseArray<TouchEventHandler>();
mHandlers.put(MotionEvent.ACTION_DOWN, new ActionDownHandler());
mHandlers.put(MotionEvent.ACTION_MOVE, new ActionMoveHandler());
mHandlers.put(MotionEvent.ACTION_UP, new ActionUpHandler());
}
private void xMotionNotify(MotionEvent event) {
mClient.xMotionNotify((int)event.getX(), (int)event.getY());
}
}
|
/// TODO : consider symbols that don't appear in the SRS?
package logicrepository.plugins.srs;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Set;
//This uses a slightly modified Aho-Corasick automaton
public class PatternMatchAutomaton extends LinkedHashMap<State, HashMap<Symbol, ActionState>> {
private State s0 = new State(0);
private ArrayList<Set<State>> depthMap = new ArrayList<Set<State>>();
private HashMap<State, State> fail;
public PatternMatchAutomaton(SRS srs){
mkGotoMachine(srs, srs.getTerminals());
addFailureTransitions(srs.getTerminals());
}
public PatternMatchAutomaton(SRS srs, Set<Symbol> extraTerminals){
Set<Symbol> terminals = new HashSet<Symbol>();
terminals.addAll(srs.getTerminals());
terminals.addAll(extraTerminals);
mkGotoMachine(srs, terminals);
addFailureTransitions(terminals);
}
private void mkGotoMachine(SRS srs, Set<Symbol> terminals){
State currentState;
put(s0, new HashMap<Symbol, ActionState>());
Set<State> depthStates = new HashSet<State>();
depthStates.add(s0);
depthMap.add(depthStates);
//compute one path through the tree for each lhs
for(Rule r : srs){
currentState = s0;
Sequence pattern = r.getLhs();
int patternRemaining = pattern.size() - 1;
for(Symbol s : pattern){
HashMap<Symbol, ActionState> transition = get(currentState);
ActionState nextActionState = transition.get(s);
State nextState;
if(nextActionState == null){
int nextDepth = currentState.getDepth() + 1;
nextState =
new State(nextDepth);
nextActionState = new ActionState(0, nextState);
transition.put(s, nextActionState);
put(nextState, new HashMap<Symbol, ActionState>());
if(nextDepth == depthMap.size()){
depthStates = new HashSet<State>();
depthMap.add(depthStates);
}
else{
depthStates = depthMap.get(nextDepth);
}
depthStates.add(nextState);
}
else{
nextState = nextActionState.getState();
}
if(patternRemaining == 0){
nextState.setMatch(r);
}
currentState = nextState;
--patternRemaining;
}
}
//now add self transitions on s0 for any symbols that don't
//exit from s0 already
HashMap<Symbol, ActionState> s0transition = get(s0);
for(Symbol s : terminals){
if(!s0transition.containsKey(s)){
s0transition.put(s, new ActionState(0, s0));
}
}
}
private void addFailureTransitions(Set<Symbol> terminals){
fail = new HashMap<State, State>();
if(depthMap.size() == 1) return;
//handle all depth 1
for(State state : depthMap.get(1)){
HashMap<Symbol, ActionState> transition = get(state);
fail.put(state, s0);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
transition.put(symbol, new ActionState(1, s0));
}
}
}
if(depthMap.size() == 2) return;
//handle depth d > 1
for(int i = 2; i < depthMap.size(); ++i){
for(State state : depthMap.get(i)){
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
State failState = findState(state, depthMap.get(i - 1), fail,
terminals);
transition.put(symbol,
new ActionState(state.getDepth() - failState.getDepth(),
failState));
fail.put(state, failState);
}
}
}
}
//System.out.println("!!!!!!!!!!");
//System.out.println(fail);
//System.out.println("!!!!!!!!!!");
}
private State findState(State state, Set<State> shallowerStates,
HashMap<State, State> fail, Set<Symbol> terminals){
for(State shallowerState : shallowerStates){
HashMap<Symbol, ActionState> transition = get(shallowerState);
for(Symbol symbol : terminals){
ActionState destination = transition.get(symbol);
if(destination.getState() == state){
// System.out.println(state + " " + destination.getState());
State failState = fail.get(shallowerState);
while(failState != s0 && get(failState).get(symbol).getAction() != 0){
failState = fail.get(failState);
}
return get(failState).get(symbol).getState();
}
}
}
return s0;
}
public void rewrite(SinglyLinkedList<Symbol> l){
System.out.println("rewriting:");
if(l.size() == 0) return;
Iterator<Symbol> first = l.iterator();
first.next(); //make sure first points to an element
Iterator<Symbol> second = l.iterator();
Iterator<Symbol> lastRepl;
State currentState = s0;
ActionState as;
Symbol symbol = second.next();
while(true){
as = get(currentState).get(symbol);
//System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
//System.out.println("false 0 transition");
if(!first.hasNext()) break;
first.next();
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
//System.out.println("in: " + l);
l.nonDestructiveReplace(first, second, (Sequence) repl);
if(l.isEmpty()) break;
first = l.iterator();
//System.out.println("out: " + l);
//System.out.println("out: " + first);
//lastRepl = l.iterator(second);
//System.out.println("lastRepl: " + lastRepl);
symbol = first.next();
second = l.iterator(first);
//System.out.println("first: " + first);
//System.out.println("second: " + second);
currentState = s0;
continue;
}
}
if(!second.hasNext()) break;
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
symbol = second.next();
}
//fail transition, need to reconsider he same symbol in next state
}
System.out.println("substituted form = " + l.toString());
}
public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
while(true){
as = get(currentState).get(symbol);
//System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
//System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
atOrPastLastChange = false;
//System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
//System.out.println("out: " + l);
//System.out.println("out: " + first);
lastRepl = second;
//System.out.println("lastRepl: " + lastRepl);
second = first.copy();
//System.out.println("first: " + first);
//System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
if(!second.next()) break;
if(!changed){
if(second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
//System.out.println("early exit at symbol " + second);
break DONE;
}
}
symbol = second.get();
}
//fail transition, need to reconsider he same symbol in next state
}
} while(changed);
System.out.println("substituted form = " + l.toString());
}
@Override public String toString(){
StringBuilder sb = new StringBuilder();
for(State state : keySet()){
sb.append(state);
sb.append("\n[");
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : transition.keySet()){
sb.append(" ");
sb.append(symbol);
sb.append(" -> ");
sb.append(transition.get(symbol));
sb.append("\n");
}
sb.append("]\n");
}
return sb.toString();
}
public String toDotString(){
StringBuilder sb = new StringBuilder("digraph A");
sb.append((long) (Math.random()* 2e61d));
sb.append("{\n rankdir=TB;\n node [shape=circle];\n");
// sb.append(" edge [style=\">=stealth' ,shorten >=1pt\"];\n");
for(State state : keySet()){
sb.append(" ");
sb.append(state.toFullDotString());
sb.append("\n");
}
for(State state : keySet()){
HashMap<Symbol, ActionState> transition = get(state);
sb.append(transitionToDotString(state, transition));
}
sb.append("}");
return sb.toString();
}
private static void getStateImpl(StringBuilder sb){
sb.append("class StateImpl {\n");
sb.append(" int number;\n");
sb.append(" int[] replacement;\n");
sb.append(" int category;\n\n");
sb.append(" public StateImpl(int number){\n");
sb.append(" this.number = number;\n");
sb.append(" this.replacement = null;\n");
sb.append(" this.category = -1;\n");
sb.append(" }\n\n");
sb.append(" public StateImpl(int number, int[] replacement){\n");
sb.append(" this.number = number;\n");
sb.append(" this.replacement = replacement;\n");
sb.append(" this.category = -1;\n");
sb.append(" }\n\n");
sb.append(" public StateImpl(int number, int category){\n");
sb.append(" this.number = number;\n");
sb.append(" this.replacement = null;\n");
sb.append(" this.category = category;\n");
sb.append(" }\n");
sb.append("}\n");
}
private static void getTransitionImpl(StringBuilder sb){
sb.append("class TransitionImpl {\n");
sb.append(" int action;\n");
sb.append(" StateImpl state;\n\n");
sb.append(" public TransitionImpl(int action, StateImpl state){\n");
sb.append(" this.action = action;\n");
sb.append(" this.state = state;\n");
sb.append(" }\n");
sb.append("}\n");
}
public String toImplString(){
StringBuilder sb = new StringBuilder();
getStateImpl(sb);
getTransitionImpl(sb);
sb.append("static TransitionImpl [][] arr = {");
for(State state : keySet()){
sb.append("{");
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : transition.keySet()){
ActionState astate = transition.get(symbol);
State s = astate.getState();
sb.append("new TransitionImpl(");
sb.append(astate.getAction());
sb.append(", new StateImpl(");
sb.append(s.getNumber());
if(s.getMatch() != null){
}
}
sb.append("}");
}
sb.append("};");
return sb.toString();
}
public StringBuilder transitionToDotString(State state, Map<Symbol, ActionState> transition){
Map<ActionState, ArrayList<Symbol>> edgeCondensingMap = new
LinkedHashMap<ActionState, ArrayList<Symbol>>();
for(Symbol symbol : transition.keySet()){
ActionState next = transition.get(symbol);
ArrayList<Symbol> edges = edgeCondensingMap.get(next);
if(edges == null){
edges = new ArrayList<Symbol>();
edgeCondensingMap.put(next, edges);
}
edges.add(symbol);
}
// System.out.println(edgeCondensingMap);
// if(true) throw new RuntimeException();
StringBuilder sb = new StringBuilder();
for(ActionState next : edgeCondensingMap.keySet()){
sb.append(" ");
sb.append(state.toNameDotString());
sb.append(" -> ");
sb.append(next.getState().toNameDotString());
sb.append(" [label=\"");
StringBuilder label = new StringBuilder();
for(Symbol symbol : edgeCondensingMap.get(next)){
label.append(symbol.toString());
label.append(", ");
}
label.setCharAt(label.length() - 1, '/');
label.setCharAt(label.length() - 2, ' ');
label.append(" ");
label.append(next.getAction());
sb.append(label);
sb.append("\"];\n");
}
return sb;
// for(Symbol symbol : transition.keySet()){
// sb.append(" ");
// sb.append(state.toNameDotString());
// sb.append(" -> ");
// ActionState next = transition.get(symbol);
// sb.append(next.getState().toNameDotString());
// sb.append(" [texlbl=\"$");
// sb.append(symbol.toDotString());
// sb.append(" / ");
// sb.append(next.getAction());
// sb.append("$\"];\n");
}
}
class ActionState {
private int action;
private State state;
public int getAction(){
return action;
}
public State getState(){
return state;
}
public ActionState(int action, State state){
this.action = action;
this.state = state;
}
@Override public String toString(){
return "[" + action + "] " + state.toString();
}
@Override
public int hashCode(){
return action ^ state.hashCode();
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof ActionState)) return false;
ActionState as = (ActionState) o;
return(as.action == action && state.equals(as.state));
}
}
class State {
private static int counter = 0;
private int number;
private int depth;
private Rule matchedRule = null;
public State(int depth){
number = counter++;
this.depth = depth;
}
public int getNumber(){
return number;
}
public int getDepth(){
return depth;
}
public Rule getMatch(){
return matchedRule;
}
public void setMatch(Rule r){
matchedRule = r;
}
//matched rule must always be equal if number is equal
//ditto with depth
@Override
public int hashCode(){
return number;
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof State)) return false;
State s = (State) o;
return s.number == number;
}
@Override
public String toString(){
return "<" + number
+ " @ "
+ depth
+ ((matchedRule == null)?
""
: " matches " + matchedRule.toString()
)
+ ">";
}
public String toFullDotString(){
String name = toNameDotString();
String ruleStr;
int ruleLen;
if(matchedRule == null){
ruleStr = "";
ruleLen = 0;
}
else {
ruleStr = "\\\\ (" + matchedRule.toDotString() + ")";
ruleLen = matchedRule.dotLength() + 4; //add a bit extra padding
}
String texlbl= number + " : " + depth
+ ruleStr;
return name + " [texlbl=\"$\\begin{array}{c}" + texlbl
+ "\\end{array}$\" label=\""
+ mkSpaces(Math.max(new Integer(number).toString().length()
+ new Integer(depth).toString().length() + 5,
ruleLen)) + "\"];";
}
static String mkSpaces(int len){
StringBuilder sb = new StringBuilder();
for(; len > 0; --len){
sb.append(' ');
}
return sb.toString();
}
public String toNameDotString(){
return "s_" + number;
}
}
|
package org.deeplearning4j.nn.conf.layers;
import lombok.*;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.ParamInitializer;
import org.deeplearning4j.nn.conf.InputPreProcessor;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.params.DefaultParamInitializer;
import org.deeplearning4j.nn.params.EmptyParamInitializer;
import org.deeplearning4j.optimize.api.IterationListener;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.linalg.lossfunctions.impl.LossMCXENT;
import java.util.Collection;
import java.util.Map;
/**
* LossLayer is a flexible output "layer" that performs a loss function on
* an input without MLP logic.
*
* @author Justin Long (crockpotveggies)
*/
@Data
@NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class LossLayer extends FeedForwardLayer {
protected ILossFunction lossFn;
private LossLayer(Builder builder) {
super(builder);
this.lossFn = builder.lossFn;
}
@Override
public Layer instantiate(NeuralNetConfiguration conf, Collection<IterationListener> iterationListeners, int layerIndex, INDArray layerParamsView, boolean initializeParams) {
org.deeplearning4j.nn.layers.OutputLayer ret
= new org.deeplearning4j.nn.layers.OutputLayer(conf);
ret.setListeners(iterationListeners);
ret.setIndex(layerIndex);
ret.setParamsViewArray(layerParamsView);
Map<String, INDArray> paramTable = initializer().init(conf, layerParamsView, initializeParams);
ret.setParamTable(paramTable);
ret.setConf(conf);
return ret;
}
@Override
public ParamInitializer initializer() {
return DefaultParamInitializer.getInstance();
}
public static class Builder extends BaseOutputLayer.Builder<Builder> {
protected ILossFunction lossFn = new LossMCXENT();
protected int nIn = 0;
protected int nOut = 0;
public Builder() {}
public Builder(LossFunctions.LossFunction lossFunction) {
lossFunction(lossFunction);
}
public Builder(ILossFunction lossFunction) {
this.lossFn = lossFunction;
}
@Override
@SuppressWarnings("unchecked")
public Builder nIn(int nIn) {
throw new UnsupportedOperationException("Ths layer has no parameters, thus nIn will always equal nOut.");
}
@Override
@SuppressWarnings("unchecked")
public Builder nOut(int nOut) {
throw new UnsupportedOperationException("Ths layer has no parameters, thus nIn will always equal nOut.");
}
@Override
@SuppressWarnings("unchecked")
public LossLayer build() {
return new LossLayer(this);
}
}
}
|
package io.dropwizard.servlets.assets;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/**
* Helper methods for dealing with {@link URL} objects for local resources.
*/
public class ResourceURL {
private ResourceURL() { /* singleton */ }
/**
* Returns true if the URL passed to it corresponds to a directory. This is slightly tricky due to some quirks
* of the {@link JarFile} API. Only jar:// and file:// URLs are supported.
*
* @param resourceURL the URL to check
* @return true if resource is a directory
*/
public static boolean isDirectory(URL resourceURL) throws URISyntaxException {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final JarEntry entry = jarConnection.getJarEntry();
if (entry.isDirectory()) {
return true;
}
// WARNING! Heuristics ahead.
// It turns out that JarEntry#isDirectory() really just tests whether the filename ends in a '/'.
// what you want. We try to get around this by calling getInputStream() on the file inside the jar.
// This seems to return null for directories (though that behavior is undocumented as far as I
// can tell). If you have a better idea, please improve this.
final String fileName = resourceURL.getFile();
// leaves just the relative file path inside the jar
final String relativeFilePath = fileName.substring(fileName.lastIndexOf('!') + 2);
final JarFile jarFile = jarConnection.getJarFile();
final ZipEntry zipEntry = jarFile.getEntry(relativeFilePath);
final InputStream inputStream = jarFile.getInputStream(zipEntry);
return (inputStream == null);
} catch (IOException e) {
throw new ResourceNotFoundException(e);
}
case "file":
return new File(resourceURL.toURI()).isDirectory();
default:
throw new IllegalArgumentException("Unsupported protocol " + resourceURL.getProtocol() +
" for resource " + resourceURL);
}
}
/**
* Appends a trailing '/' to a {@link URL} object. Does not append a slash if one is already present.
*
* @param originalURL The URL to append a slash to
* @return a new URL object that ends in a slash
*/
public static URL appendTrailingSlash(URL originalURL) {
try {
return originalURL.getPath().endsWith("/") ? originalURL :
new URL(originalURL.getProtocol(),
originalURL.getHost(),
originalURL.getPort(),
originalURL.getFile() + '/');
} catch (MalformedURLException ignored) { // shouldn't happen
throw new IllegalArgumentException("Invalid resource URL: " + originalURL);
}
}
public static long getLastModified(URL resourceURL) {
final String protocol = resourceURL.getProtocol();
switch (protocol) {
case "jar":
try {
final JarURLConnection jarConnection = (JarURLConnection) resourceURL.openConnection();
final JarEntry entry = jarConnection.getJarEntry();
return entry.getTime();
} catch (IOException ignored) {
return 0;
}
case "file":
URLConnection connection = null;
try {
connection = resourceURL.openConnection();
return connection.getLastModified();
} catch (IOException ignored) {
return 0;
} finally {
if (connection != null) {
try {
connection.getInputStream().close();
} catch (IOException ignored) {
// do nothing.
}
}
}
default:
throw new IllegalArgumentException("Unsupported protocol " + resourceURL.getProtocol() + " for resource " + resourceURL);
}
}
}
|
package com.alibaba.excel.analysis.v07;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.alibaba.excel.analysis.ExcelReadExecutor;
import com.alibaba.excel.analysis.v07.handlers.sax.SharedStringsTableHandler;
import com.alibaba.excel.analysis.v07.handlers.sax.XlsxRowHandler;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.context.xlsx.XlsxReadContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.read.metadata.holder.xlsx.XlsxReadWorkbookHolder;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.util.SheetUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.CommentsTable;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* @author jipengfei
*/
@Slf4j
public class XlsxSaxAnalyser implements ExcelReadExecutor {
private XlsxReadContext xlsxReadContext;
private List<ReadSheet> sheetList;
private Map<Integer, InputStream> sheetMap;
/**
* excel comments key: sheetNo value: CommentsTable
*/
private Map<Integer, CommentsTable> commentsTableMap;
public XlsxSaxAnalyser(XlsxReadContext xlsxReadContext, InputStream decryptedStream) throws Exception {
this.xlsxReadContext = xlsxReadContext;
// Initialize cache
XlsxReadWorkbookHolder xlsxReadWorkbookHolder = xlsxReadContext.xlsxReadWorkbookHolder();
OPCPackage pkg = readOpcPackage(xlsxReadWorkbookHolder, decryptedStream);
xlsxReadWorkbookHolder.setOpcPackage(pkg);
ArrayList<PackagePart> packageParts = pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
if (!CollectionUtils.isEmpty(packageParts)) {
PackagePart sharedStringsTablePackagePart = packageParts.get(0);
// Specify default cache
defaultReadCache(xlsxReadWorkbookHolder, sharedStringsTablePackagePart);
// Analysis sharedStringsTable.xml
analysisSharedStringsTable(sharedStringsTablePackagePart.getInputStream(), xlsxReadWorkbookHolder);
}
XSSFReader xssfReader = new XSSFReader(pkg);
analysisUse1904WindowDate(xssfReader, xlsxReadWorkbookHolder);
// set style table
setStylesTable(xlsxReadWorkbookHolder, xssfReader);
sheetList = new ArrayList<>();
sheetMap = new HashMap<>();
commentsTableMap = new HashMap<>();
XSSFReader.SheetIterator ite = (XSSFReader.SheetIterator)xssfReader.getSheetsData();
int index = 0;
if (!ite.hasNext()) {
throw new ExcelAnalysisException("Can not find any sheet!");
}
while (ite.hasNext()) {
InputStream inputStream = ite.next();
sheetList.add(new ReadSheet(index, ite.getSheetName()));
sheetMap.put(index, inputStream);
if (xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.COMMENT)) {
CommentsTable commentsTable = ite.getSheetComments();
if (null != commentsTable) {
commentsTableMap.put(index, commentsTable);
}
}
index++;
}
}
private void setStylesTable(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, XSSFReader xssfReader) {
try {
xlsxReadWorkbookHolder.setStylesTable(xssfReader.getStylesTable());
} catch (Exception e) {
log.warn(
"Currently excel cannot get style information, but it doesn't affect the data analysis.You can try to"
+ " save the file with office again or ignore the current error.",
e);
}
}
private void defaultReadCache(XlsxReadWorkbookHolder xlsxReadWorkbookHolder,
PackagePart sharedStringsTablePackagePart) {
ReadCache readCache = xlsxReadWorkbookHolder.getReadCacheSelector().readCache(sharedStringsTablePackagePart);
xlsxReadWorkbookHolder.setReadCache(readCache);
readCache.init(xlsxReadContext);
}
private void analysisUse1904WindowDate(XSSFReader xssfReader, XlsxReadWorkbookHolder xlsxReadWorkbookHolder)
throws Exception {
if (xlsxReadWorkbookHolder.globalConfiguration().getUse1904windowing() != null) {
return;
}
InputStream workbookXml = xssfReader.getWorkbookData();
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null && prefix.getDate1904()) {
xlsxReadWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.TRUE);
} else {
xlsxReadWorkbookHolder.getGlobalConfiguration().setUse1904windowing(Boolean.FALSE);
}
}
private void analysisSharedStringsTable(InputStream sharedStringsTableInputStream,
XlsxReadWorkbookHolder xlsxReadWorkbookHolder) throws Exception {
ContentHandler handler = new SharedStringsTableHandler(xlsxReadWorkbookHolder.getReadCache());
parseXmlSource(sharedStringsTableInputStream, handler);
xlsxReadWorkbookHolder.getReadCache().putFinished();
}
private OPCPackage readOpcPackage(XlsxReadWorkbookHolder xlsxReadWorkbookHolder, InputStream decryptedStream)
throws Exception {
if (decryptedStream == null && xlsxReadWorkbookHolder.getFile() != null) {
return OPCPackage.open(xlsxReadWorkbookHolder.getFile());
}
if (xlsxReadWorkbookHolder.getMandatoryUseInputStream()) {
if (decryptedStream != null) {
return OPCPackage.open(decryptedStream);
} else {
return OPCPackage.open(xlsxReadWorkbookHolder.getInputStream());
}
}
File readTempFile = FileUtils.createCacheTmpFile();
xlsxReadWorkbookHolder.setTempFile(readTempFile);
File tempFile = new File(readTempFile.getPath(), UUID.randomUUID().toString() + ".xlsx");
if (decryptedStream != null) {
FileUtils.writeToFile(tempFile, decryptedStream, false);
} else {
FileUtils.writeToFile(tempFile, xlsxReadWorkbookHolder.getInputStream(),
xlsxReadWorkbookHolder.getAutoCloseStream());
}
return OPCPackage.open(tempFile, PackageAccess.READ);
}
@Override
public List<ReadSheet> sheetList() {
return sheetList;
}
private void parseXmlSource(InputStream inputStream, ContentHandler handler) {
InputSource inputSource = new InputSource(inputStream);
try {
SAXParserFactory saxFactory;
String xlsxSAXParserFactoryName = xlsxReadContext.xlsxReadWorkbookHolder().getSaxParserFactoryName();
if (StringUtils.isEmpty(xlsxSAXParserFactoryName)) {
saxFactory = SAXParserFactory.newInstance();
} else {
saxFactory = SAXParserFactory.newInstance(xlsxSAXParserFactoryName, null);
}
try {
saxFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (Throwable ignore) {}
try {
saxFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (Throwable ignore) {}
try {
saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (Throwable ignore) {}
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(inputSource);
inputStream.close();
} catch (IOException | ParserConfigurationException | SAXException e) {
throw new ExcelAnalysisException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new ExcelAnalysisException("Can not close 'inputStream'!");
}
}
}
}
@Override
public void execute() {
for (ReadSheet readSheet : sheetList) {
readSheet = SheetUtils.match(readSheet, xlsxReadContext);
if (readSheet != null) {
xlsxReadContext.currentSheet(readSheet);
parseXmlSource(sheetMap.get(readSheet.getSheetNo()), new XlsxRowHandler(xlsxReadContext));
// Read comments
readComments(readSheet);
// The last sheet is read
xlsxReadContext.analysisEventProcessor().endSheet(xlsxReadContext);
}
}
}
private void readComments(ReadSheet readSheet) {
if (!xlsxReadContext.readWorkbookHolder().getExtraReadSet().contains(CellExtraTypeEnum.COMMENT)) {
return;
}
CommentsTable commentsTable = commentsTableMap.get(readSheet.getSheetNo());
if (commentsTable == null) {
return;
}
Iterator<CellAddress> cellAddresses = commentsTable.getCellAddresses();
while (cellAddresses.hasNext()) {
CellAddress cellAddress = cellAddresses.next();
XSSFComment cellComment = commentsTable.findCellComment(cellAddress);
CellExtra cellExtra = new CellExtra(CellExtraTypeEnum.COMMENT, cellComment.getString().toString(),
cellAddress.getRow(), cellAddress.getColumn());
xlsxReadContext.readSheetHolder().setCellExtra(cellExtra);
xlsxReadContext.analysisEventProcessor().extra(xlsxReadContext);
}
}
}
|
package com.exedio.cope.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.exedio.cope.Model;
public final class ConnectToken
{
private final Manciple manciple;
private final Model model;
private final int id;
private final long issueDate = System.currentTimeMillis();
private final String name;
private final boolean didConnect;
private volatile boolean returned = false;
private final Object returnedLock = new Object();
private ConnectToken(
final Manciple manciple,
final Model model,
final int id,
final String name,
final boolean didConnect)
{
assert manciple!=null;
assert model!=null;
assert id>=0;
this.manciple = manciple;
this.model = model;
this.id = id;
this.name = name;
this.didConnect = didConnect;
}
public Model getModel()
{
return model;
}
public int getID()
{
return id;
}
public Date getIssueDate()
{
return new Date(issueDate);
}
public String getName()
{
return name;
}
public boolean didConnect()
{
return didConnect;
}
public boolean isReturned()
{
return returned;
}
public boolean returnIt()
{
synchronized(returnedLock)
{
if(returned)
throw new IllegalStateException("connect token " + id + " already returned");
returned = true;
}
return manciple.returnIt(this);
}
private static final class Manciple
{
private final ArrayList<ConnectToken> tokens = new ArrayList<ConnectToken>();
private int nextId = 0;
private final Object lock = new Object();
private ConnectToken issue(
final Model model,
final com.exedio.cope.ConnectProperties properties,
final String tokenName)
{
synchronized(lock)
{
final boolean connect = tokens.isEmpty();
if(connect)
model.connect(properties);
else
model.getProperties().ensureEquality(properties);
final ConnectToken result = new ConnectToken(this, model, nextId++, tokenName, connect);
tokens.add(result);
if(Model.isLoggingEnabled())
System.out.println(
"ConnectToken " + Integer.toString(System.identityHashCode(model), 36) +
": issued " + result.id + (tokenName!=null ? (" (" + tokenName + ')') : "") +
(connect ? " CONNECT" : ""));
return result;
}
}
private boolean returnIt(final ConnectToken token)
{
synchronized(lock)
{
final boolean removed = tokens.remove(token);
assert removed;
final boolean disconnect = tokens.isEmpty();
if(disconnect)
token.model.disconnect();
if(Model.isLoggingEnabled())
System.out.println(
"ConnectToken " + Integer.toString(System.identityHashCode(token.model), 36) +
": returned " + token.id + (token.name!=null ? (" (" + token.name + ')') : "") +
(disconnect ? " DISCONNECT" : ""));
return disconnect;
}
}
List<ConnectToken> getTokens()
{
final ConnectToken[] result;
synchronized(lock)
{
result = tokens.toArray(new ConnectToken[tokens.size()]);
}
return Collections.unmodifiableList(Arrays.asList(result));
}
}
private static final HashMap<Model, Manciple> manciples = new HashMap<Model, Manciple>();
private static final Manciple manciple(final Model model)
{
synchronized(manciples)
{
Manciple result = manciples.get(model);
if(result!=null)
return result;
result = new Manciple();
manciples.put(model, result);
return result;
}
}
public static final ConnectToken issue(
final Model model,
final com.exedio.cope.ConnectProperties properties,
final String tokenName)
{
return manciple(model).issue(model, properties, tokenName);
}
/**
* Returns the collection of open {@link ConnectToken}s
* on the model.
* <p>
* Returns an unmodifiable snapshot of the actual data,
* so iterating over the collection on a live server cannot cause
* {@link java.util.ConcurrentModificationException}s.
*/
public static final List<ConnectToken> getTokens(final Model model)
{
return manciple(model).getTokens();
}
}
|
package jolie.embedding.js;
import jolie.Interpreter;
import jolie.runtime.AndJarDeps;
import jolie.runtime.embedding.EmbeddedServiceLoader;
import jolie.runtime.embedding.EmbeddedServiceLoaderCreationException;
import jolie.runtime.embedding.EmbeddedServiceLoaderFactory;
import jolie.runtime.expression.Expression;
/**
* An embedding extension for JavaScript programs.
*
* @author Fabrizio Montesi
*/
@AndJarDeps({"jolie-js.jar","json_simple.jar"})
public class JavaScriptServiceLoaderFactory implements EmbeddedServiceLoaderFactory
{
@Override
public EmbeddedServiceLoader createLoader( Interpreter interpreter, String type, String servicePath, Expression channelDest )
throws EmbeddedServiceLoaderCreationException
{
return new JavaScriptServiceLoader( channelDest, servicePath );
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package org.capnproto;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
public final class Serialize {
static ByteBuffer makeByteBuffer(int bytes) {
ByteBuffer result = ByteBuffer.allocate(bytes);
result.order(ByteOrder.LITTLE_ENDIAN);
result.mark();
return result;
}
public static void fillBuffer(ByteBuffer buffer, ReadableByteChannel bc) throws IOException {
while(buffer.hasRemaining()) {
int r = bc.read(buffer);
if (r < 0) {
throw new IOException("premature EOF");
}
// TODO check for r == 0 ?.
}
}
public static MessageReader read(ReadableByteChannel bc) throws IOException {
return read(bc, ReaderOptions.DEFAULT_READER_OPTIONS);
}
public static MessageReader read(ReadableByteChannel bc, ReaderOptions options) throws IOException {
ByteBuffer firstWord = makeByteBuffer(Constants.BYTES_PER_WORD);
fillBuffer(firstWord, bc);
int segmentCount = 1 + firstWord.getInt(0);
int segment0Size = 0;
if (segmentCount > 0) {
segment0Size = firstWord.getInt(4);
}
int totalWords = segment0Size;
if (segmentCount > 512) {
throw new IOException("too many segments");
}
// in words
ArrayList<Integer> moreSizes = new ArrayList<Integer>();
if (segmentCount > 1) {
ByteBuffer moreSizesRaw = makeByteBuffer(4 * (segmentCount & ~1));
fillBuffer(moreSizesRaw, bc);
for (int ii = 0; ii < segmentCount - 1; ++ii) {
int size = moreSizesRaw.getInt(ii * 4);
moreSizes.add(size);
totalWords += size;
}
}
if (totalWords > options.traversalLimitInWords) {
throw new DecodeException("Message size exceeds traversal limit.");
}
ByteBuffer allSegments = makeByteBuffer(totalWords * Constants.BYTES_PER_WORD);
fillBuffer(allSegments, bc);
ByteBuffer[] segmentSlices = new ByteBuffer[segmentCount];
allSegments.rewind();
segmentSlices[0] = allSegments.slice();
segmentSlices[0].limit(segment0Size * Constants.BYTES_PER_WORD);
segmentSlices[0].order(ByteOrder.LITTLE_ENDIAN);
int offset = segment0Size;
for (int ii = 1; ii < segmentCount; ++ii) {
allSegments.position(offset * Constants.BYTES_PER_WORD);
segmentSlices[ii] = allSegments.slice();
segmentSlices[ii].limit(moreSizes.get(ii - 1) * Constants.BYTES_PER_WORD);
segmentSlices[ii].order(ByteOrder.LITTLE_ENDIAN);
offset += moreSizes.get(ii - 1);
}
return new MessageReader(segmentSlices, options);
}
public static MessageReader read(ByteBuffer bb) throws IOException {
return read(bb, ReaderOptions.DEFAULT_READER_OPTIONS);
}
public static MessageReader read(ByteBuffer bb, ReaderOptions options) throws IOException {
bb.order(ByteOrder.LITTLE_ENDIAN);
int segmentCount = 1 + bb.getInt();
if (segmentCount > 512) {
throw new IOException("too many segments");
}
ByteBuffer[] segmentSlices = new ByteBuffer[segmentCount];
int segmentSizesBase = bb.position();
int segmentSizesSize = segmentCount * 4;
int align = Constants.BYTES_PER_WORD - 1;
int segmentBase = (segmentSizesBase + segmentSizesSize + align) & ~align;
int totalWords = 0;
for (int ii = 0; ii < segmentCount; ++ii) {
int segmentSize = bb.getInt(segmentSizesBase + ii * 4);
bb.position(segmentBase + totalWords * Constants.BYTES_PER_WORD);
segmentSlices[ii] = bb.slice();
segmentSlices[ii].limit(segmentSize * Constants.BYTES_PER_WORD);
segmentSlices[ii].order(ByteOrder.LITTLE_ENDIAN);
totalWords += segmentSize;
}
if (totalWords > options.traversalLimitInWords) {
throw new DecodeException("Message size exceeds traversal limit.");
}
return new MessageReader(segmentSlices, options);
}
public static long computeSerializedSizeInWords(MessageBuilder message) {
final ByteBuffer[] segments = message.getSegmentsForOutput();
// From the capnproto documentation:
// "When transmitting over a stream, the following should be sent..."
long bytes = 0;
// "(4 bytes) The number of segments, minus one..."
bytes += 4;
// "(N * 4 bytes) The size of each segment, in words."
bytes += segments.length * 4;
// "(0 or 4 bytes) Padding up to the next word boundary."
if (bytes % 8 != 0) {
bytes += 4;
}
// The content of each segment, in order.
for (int i = 0; i < segments.length; ++i) {
final ByteBuffer s = segments[i];
bytes += s.limit();
}
return bytes / Constants.BYTES_PER_WORD;
}
public static void write(WritableByteChannel outputChannel,
MessageBuilder message) throws IOException {
ByteBuffer[] segments = message.getSegmentsForOutput();
int tableSize = (segments.length + 2) & (~1);
ByteBuffer table = ByteBuffer.allocate(4 * tableSize);
table.order(ByteOrder.LITTLE_ENDIAN);
table.putInt(0, segments.length - 1);
for (int i = 0; i < segments.length; ++i) {
table.putInt(4 * (i + 1), segments[i].limit() / 8);
}
// Any padding is already zeroed.
while (table.hasRemaining()) {
outputChannel.write(table);
}
for (ByteBuffer buffer : segments) {
while(buffer.hasRemaining()) {
outputChannel.write(buffer);
}
}
}
}
|
package net.openl10n.flies.rest.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import net.openl10n.flies.rest.MediaTypes;
import net.openl10n.flies.rest.MediaTypes.Format;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import org.codehaus.jackson.annotate.JsonWriteNullProperties;
@XmlType(name = "projectIterationType", propOrder = { "links" })
@XmlRootElement(name = "project-iteration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonWriteNullProperties(false)
@JsonPropertyOrder({ "id", "links" })
public class ProjectIteration implements Serializable, HasCollectionSample<ProjectIteration>, HasMediaType
{
private static final long serialVersionUID = 1L;
private String id;
private Links links;
public ProjectIteration()
{
}
public ProjectIteration(String id)
{
this.id = id;
}
@XmlAttribute(name = "id", required = true)
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
/**
* Set of links managed by this resource
*
* This field is ignored in PUT/POST operations
*
* @return set of Links managed by this resource
*/
@XmlElement(name = "link", required = false)
public Links getLinks()
{
return links;
}
public void setLinks(Links links)
{
this.links = links;
}
public Links getLinks(boolean createIfNull)
{
if (createIfNull && links == null)
links = new Links();
return links;
}
@Override
public ProjectIteration createSample()
{
ProjectIteration entity = new ProjectIteration("sample-iteration");
return entity;
}
@Override
public Collection<ProjectIteration> createSamples()
{
Collection<ProjectIteration> entities = new ArrayList<ProjectIteration>();
entities.add(createSample());
ProjectIteration entity = new ProjectIteration("another-iteration");
entities.add(entity);
return entities;
}
@Override
public String getMediaType(Format format)
{
return MediaTypes.APPLICATION_FLIES_PROJECT_ITERATION + format;
}
@Override
public String toString()
{
return DTOUtil.toXML(this);
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((links == null) ? 0 : links.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof ProjectIteration))
{
return false;
}
ProjectIteration other = (ProjectIteration) obj;
if (id == null)
{
if (other.id != null)
{
return false;
}
}
else if (!id.equals(other.id))
{
return false;
}
if (links == null)
{
if (other.links != null)
{
return false;
}
}
else if (!links.equals(other.links))
{
return false;
}
return true;
}
}
|
package org.grobid.core.engines.patent;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.xml.parsers.SAXParserFactory;
import org.chasen.crfpp.Tagger;
import org.grobid.core.GrobidModels;
import org.grobid.core.data.BibDataSet;
import org.grobid.core.data.BiblioItem;
import org.grobid.core.data.BiblioSet;
import org.grobid.core.data.PatentItem;
import org.grobid.core.document.OPSService;
import org.grobid.core.document.PatentDocument;
import org.grobid.core.engines.AbstractParser;
import org.grobid.core.engines.CitationParser;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.exceptions.GrobidResourceException;
import org.grobid.core.features.FeaturesVectorReference;
import org.grobid.core.lexicon.Lexicon;
import org.grobid.core.sax.PatentAnnotationSaxParser;
import org.grobid.core.sax.TextSaxParser;
import org.grobid.core.utilities.Consolidation;
import org.grobid.core.utilities.GrobidProperties;
import org.grobid.core.utilities.OffsetPosition;
import org.grobid.core.utilities.TextUtilities;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Extraction of patent and NPL references from the content body of patent document with Conditional
* Random Fields.
*
* @author Patrice Lopez
*/
public class ReferenceExtractor implements Closeable {
private Tagger taggerPatent = null;
private Tagger taggerNPL = null;
private Tagger taggerAll = null;
private CitationParser nplParser = null;
private PatentRefParser patentParser = null;
private Consolidation consolidator = null;
private String tmpPath = null;
private String pathXML = null;
public boolean debug = true;
public Lexicon lexicon = Lexicon.getInstance();
public String currentPatentNumber = null;
public OPSService ops = null;
private String description = null;
public ArrayList<org.grobid.core.data.BibDataSet> resBib = null; // identified current parsed
// bibliographical items and related information
private String path = null; // path where the patent file is stored
private static String delimiters = " \n\t" + TextUtilities.fullPunctuations;
public void setDocumentPath(String dirName) {
path = dirName;
}
// constructors
public ReferenceExtractor() {
taggerNPL = AbstractParser.createTagger(GrobidModels.PATENT_NPL);
taggerAll = AbstractParser.createTagger(GrobidModels.PATENT_ALL);
taggerPatent = AbstractParser.createTagger(GrobidModels.PATENT_PATENT);
}
/**
* Extract all reference from the full text retrieve via OPS.
*/
public int extractAllReferencesOPS(boolean filterDuplicate,
boolean consolidate,
List<PatentItem> patents,
List<BibDataSet> articles) {
try {
if (description != null) {
return extractAllReferencesString(description,
filterDuplicate,
consolidate,
patents,
articles);
}
} catch (Exception e) {
throw new GrobidException(e);
}
return 0;
}
/**
* Extract all reference from a patent in XML ST.36 like.
*/
public int extractPatentReferencesXMLFile(String pathXML,
boolean filterDuplicate,
boolean consolidate,
List<PatentItem> patents) {
return extractAllReferencesXMLFile(pathXML,
filterDuplicate,
consolidate,
patents,
null);
}
/**
* Extract all reference from an XML file in ST.36 or MAREC format.
*/
public int extractAllReferencesXMLFile(String pathXML,
boolean filterDuplicate,
boolean consolidate,
List<PatentItem> patents,
List<BibDataSet> articles) {
try {
if (patents == null) {
System.out.println("Warning patents List is null!");
}
TextSaxParser sax = new TextSaxParser();
sax.setFilter("description");
// get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setFeature("http://xml.org/sax/features/namespaces", false);
spf.setFeature("http://xml.org/sax/features/validation", false);
//get a new instance of parser
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(
new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes()));
}
});
reader.setContentHandler(sax);
InputSource input = new InputSource(pathXML);
input.setEncoding("UTF-8");
reader.parse(input);
description = sax.getText();
currentPatentNumber = sax.currentPatentNumber;
consolidate = false;
filterDuplicate = true;
if (description != null) {
return extractAllReferencesString(description,
filterDuplicate,
consolidate,
patents,
articles);
} else
return 0;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* Extract all reference from the PDF file of a patent publication.
*/
public int extractAllReferencesPDFFile(String inputFile,
boolean filterDuplicate,
boolean consolidate,
List<PatentItem> patents,
List<BibDataSet> articles) {
try {
PatentDocument doc = new PatentDocument();
int startPage = -1;
int endPage = -1;
tmpPath = GrobidProperties.getTempPath().getAbsolutePath();
pathXML = doc.pdf2xml(true, false, startPage, endPage, inputFile, tmpPath, false); //with timeout,
//no force pdf reloading
// inputFile is the pdf file, tmpPath is the tmp directory for the lxml file,
// and we do not extract images in the PDF file
if (pathXML == null) {
throw new GrobidException("PDF parsing fails");
}
doc.setPathXML(pathXML);
if (doc.getBlocks() == null) {
throw new GrobidException("PDF parsing resulted in empty content");
}
description = doc.getAllBlocksClean(25, -1);
if (description != null) {
return extractAllReferencesString(description,
filterDuplicate,
consolidate,
patents,
articles);
} else
return 0;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* Extract all reference from a simple piece of text.
*/
public int extractAllReferencesString(String text,
boolean filterDuplicate,
boolean consolidate,
List<PatentItem> patents,
List<BibDataSet> articles) {
try {
// parser for patent references
if ((patentParser == null) && (patents != null)) {
patentParser = new PatentRefParser();
}
// parser for non patent references
if ((nplParser == null) && (articles != null)) {
nplParser = new CitationParser();
}
// for keeping track of the original string (including spaces)
ArrayList<String> tokenizations = new ArrayList<String>();
// tokenisation for the parser (with punctuation as tokens)
ArrayList<String> patentBlocks = new ArrayList<String>();
//text = TextUtilities.dehyphenize(text); // to be reviewed!
text = text.replace("\n", " ");
text = text.replace("\t", " ");
text = text.replace(" ", " ");
//StringTokenizer st = new StringTokenizer(text, "(["+ TextUtilities.punctuations, true);
StringTokenizer st = new StringTokenizer(text, delimiters, true);
int offset = 0;
if (st.countTokens() == 0) {
return 0;
}
while (st.hasMoreTokens()) {
String tok = st.nextToken();
tokenizations.add(tok);
}
List<OffsetPosition> journalPositions = null;
List<OffsetPosition> abbrevJournalPositions = null;
List<OffsetPosition> conferencePositions = null;
List<OffsetPosition> publisherPositions = null;
//if (articles != null)
{
journalPositions = lexicon.inJournalNames(text);
abbrevJournalPositions = lexicon.inAbbrevJournalNames(text);
conferencePositions = lexicon.inConferenceNames(text);
publisherPositions = lexicon.inPublisherNames(text);
}
boolean isJournalToken = false;
boolean isAbbrevJournalToken = false;
boolean isConferenceToken = false;
boolean isPublisherToken = false;
int currentJournalPositions = 0;
int currentAbbrevJournalPositions = 0;
int currentConferencePositions = 0;
int currentPublisherPositions = 0;
boolean skipTest = false;
//st = new StringTokenizer(text, " (["+ TextUtilities.punctuations, true);
st = new StringTokenizer(text, delimiters, true);
int posit = 0;
while (st.hasMoreTokens()) {
isJournalToken = false;
isAbbrevJournalToken = false;
isConferenceToken = false;
isPublisherToken = false;
skipTest = false;
String tok = st.nextToken();
if (tok.trim().length() == 0) {
continue;
}
// check the position of matches for journals
if (journalPositions != null) {
if (currentJournalPositions == journalPositions.size() - 1) {
if (journalPositions.get(currentJournalPositions).end < posit) {
skipTest = true;
}
}
if (!skipTest) {
for (int i = currentJournalPositions; i < journalPositions.size(); i++) {
if ((journalPositions.get(i).start <= posit) &&
(journalPositions.get(i).end >= posit)) {
isJournalToken = true;
currentJournalPositions = i;
break;
} else if (journalPositions.get(i).start > posit) {
isJournalToken = false;
currentJournalPositions = i;
break;
}
}
}
}
// check the position of matches for abbreviated journals
skipTest = false;
if (abbrevJournalPositions != null) {
if (currentAbbrevJournalPositions == abbrevJournalPositions.size() - 1) {
if (abbrevJournalPositions.get(currentAbbrevJournalPositions).end < posit) {
skipTest = true;
}
}
if (!skipTest) {
for (int i = currentAbbrevJournalPositions; i < abbrevJournalPositions.size(); i++) {
if ((abbrevJournalPositions.get(i).start <= posit) &&
(abbrevJournalPositions.get(i).end >= posit)) {
isAbbrevJournalToken = true;
currentAbbrevJournalPositions = i;
break;
} else if (abbrevJournalPositions.get(i).start > posit) {
isAbbrevJournalToken = false;
currentAbbrevJournalPositions = i;
break;
}
}
}
}
// check the position of matches for conference names
skipTest = false;
if (conferencePositions != null) {
if (currentConferencePositions == conferencePositions.size() - 1) {
if (conferencePositions.get(currentConferencePositions).end < posit) {
skipTest = true;
}
}
if (!skipTest) {
for (int i = currentConferencePositions; i < conferencePositions.size(); i++) {
if ((conferencePositions.get(i).start <= posit) &&
(conferencePositions.get(i).end >= posit)) {
isConferenceToken = true;
currentConferencePositions = i;
break;
} else if (conferencePositions.get(i).start > posit) {
isConferenceToken = false;
currentConferencePositions = i;
break;
}
}
}
}
// check the position of matches for publisher names
skipTest = false;
if (publisherPositions != null) {
if (currentPublisherPositions == publisherPositions.size() - 1) {
if (publisherPositions.get(currentPublisherPositions).end < posit) {
skipTest = true;
}
}
if (!skipTest) {
for (int i = currentPublisherPositions; i < publisherPositions.size(); i++) {
if ((publisherPositions.get(i).start <= posit) &&
(publisherPositions.get(i).end >= posit)) {
isPublisherToken = true;
currentPublisherPositions = i;
break;
} else if (publisherPositions.get(i).start > posit) {
isPublisherToken = false;
currentPublisherPositions = i;
break;
}
}
}
}
FeaturesVectorReference featureVector =
FeaturesVectorReference.addFeaturesPatentReferences(tok,
tokenizations.size(),
posit,
isJournalToken,
isAbbrevJournalToken,
isConferenceToken,
isPublisherToken);
patentBlocks.add(featureVector.printVector());
posit++;
}
patentBlocks.add("\n");
String theResult = null;
if (articles == null) {
theResult = taggerRun(patentBlocks, taggerPatent);
} else if (patents == null) {
theResult = taggerRun(patentBlocks, taggerNPL);
} else {
theResult = taggerRun(patentBlocks, taggerAll);
}
//System.out.println(theResult);
StringTokenizer stt = new StringTokenizer(theResult, "\n");
ArrayList<String> referencesPatent = new ArrayList<String>();
ArrayList<String> referencesNPL = new ArrayList<String>();
ArrayList<Integer> offsets_patent = new ArrayList<Integer>();
ArrayList<Integer> offsets_NPL = new ArrayList<Integer>();
boolean currentPatent = true; // type of current reference
String reference = null;
offset = 0;
int currentOffset = 0;
String label = null; // label
String actual = null; // token
int p = 0; // iterator for the tokenizations for restauring the original tokenization with
// respect to spaces
while (stt.hasMoreTokens()) {
String line = stt.nextToken();
if (line.trim().length() == 0) {
continue;
}
StringTokenizer st2 = new StringTokenizer(line, "\t");
boolean start = true;
boolean addSpace = false;
label = null;
actual = null;
while (st2.hasMoreTokens()) {
if (start) {
actual = st2.nextToken().trim();
start = false;
boolean strop = false;
while ((!strop) && (p < tokenizations.size())) {
String tokOriginal = tokenizations.get(p);
if (tokOriginal.equals(" ")) {
addSpace = true;
} else if (tokOriginal.equals(actual)) {
strop = true;
}
p++;
}
} else {
label = st2.nextToken().trim();
}
}
if (label == null) {
continue;
}
if (actual != null) {
if (label.endsWith("<refPatent>")) {
if (reference == null) {
reference = actual;
currentOffset = offset;
currentPatent = true;
} else {
if (currentPatent) {
if (label.equals("I-<refPatent>")) {
referencesPatent.add(reference);
offsets_patent.add(currentOffset);
currentPatent = true;
reference = actual;
currentOffset = offset;
} else {
//if (offsets.contains(new Integer(offset))) {
if (addSpace) {
reference += " " + actual;
} else
reference += actual;
}
} else {
referencesNPL.add(reference);
offsets_NPL.add(currentOffset);
currentPatent = true;
reference = actual;
currentOffset = offset;
}
}
} else if (label.endsWith("<refNPL>")) {
if (reference == null) {
reference = actual;
currentOffset = offset;
currentPatent = false;
} else {
if (currentPatent) {
referencesPatent.add(reference);
offsets_patent.add(currentOffset);
currentPatent = false;
reference = actual;
currentOffset = offset;
} else {
if (label.equals("I-<refNPL>")) {
referencesNPL.add(reference);
offsets_NPL.add(currentOffset);
currentPatent = false;
reference = actual;
currentOffset = offset;
} else {
//if (offsets.contains(new Integer(offset))) {
if (addSpace) {
reference += " " + actual;
} else
reference += actual;
}
}
}
} else if (label.equals("<other>")) {
if (reference != null) {
if (currentPatent) {
referencesPatent.add(reference);
offsets_patent.add(currentOffset);
} else {
referencesNPL.add(reference);
offsets_NPL.add(currentOffset);
}
currentPatent = false;
}
reference = null;
}
}
offset++;
}
// run reference patent parser in isolation, and produce some traces
int j = 0;
for (String ref : referencesPatent) {
patentParser.setRawRefText(ref);
patentParser.setRawRefTextOffset(offsets_patent.get(j).intValue());
ArrayList<PatentItem> patents0 = patentParser.processRawRefText();
for (PatentItem pat : patents0) {
pat.setContext(ref);
patents.add(pat);
if (pat.getApplication()) {
if (pat.getProvisional()) {
if (debug) {
System.out.println(pat.getAuthority() + " " + pat.getNumber()
+ " P application " + pat.getOffsetBegin()
+ ":" + pat.getOffsetEnd() + "\n");
}
} else {
if (debug) {
System.out.println(pat.getAuthority() + " " + pat.getNumber()
+ " application " + pat.getOffsetBegin()
+ ":" + pat.getOffsetEnd() + "\n");
}
}
} else if (pat.getReissued()) {
if (pat.getAuthority().equals("US")) {
if (debug) {
System.out.println(pat.getAuthority() + "RE" + pat.getNumber() + " E "
+ pat.getOffsetBegin() + ":" + pat.getOffsetEnd() + "\n");
}
}
} else if (pat.getPlant()) {
if (pat.getAuthority().equals("US")) {
if (debug)
System.out.println(pat.getAuthority() + "PP" + pat.getNumber() + " " +
pat.getOffsetBegin() + ":" + pat.getOffsetEnd() + "\n");
}
} else {
if (debug) {
if (pat.getKindCode() != null) {
System.out.println(pat.getAuthority() + " " + pat.getNumber() + " "
+ pat.getKindCode() + " "
+ pat.getOffsetBegin() + ":" + pat.getOffsetEnd() + "\n");
} else {
System.out.println(pat.getAuthority() + " " + pat.getNumber() + " " +
pat.getOffsetBegin() + ":" + pat.getOffsetEnd() + "\n");
}
System.out.println(pat.getContext());
}
}
}
j++;
}
// list for filtering duplicates, if we want to ignore the duplicate numbers
ArrayList<String> numberListe = new ArrayList<String>();
if (filterDuplicate) {
// list for filtering duplicates, if we want to ignore the duplicate numbers
ArrayList<PatentItem> toRemove = new ArrayList<PatentItem>();
for (PatentItem pat : patents) {
if (!numberListe.contains(pat.getNumber())) {
numberListe.add(pat.getNumber());
} else {
toRemove.add(pat);
}
}
for (PatentItem pat : toRemove) {
patents.remove(pat);
}
}
/*System.out.println("\nRFAP:");
for (PatentItem pat : patents) {
if (!numberListe.contains(pat.getNumber())) {
if (pat.getApplication()) {
if (pat.getProvisional()) {
System.out.println(" "+pat.getAuthority() + pat.getNumber() + "P");
nbRes++;
}
else {
System.out.println(" "+pat.getAuthority() + pat.getNumber());
nbRes++;
}
numberListe.add(pat.getNumber());
}
}
}*/
/*System.out.println("\nRF:");
for (PatentItem pat : patents) {
if (!numberListe.contains(pat.getNumber())) {
if (pat.getReissued()) {
if (pat.getAuthority().equals("US")) {
System.out.println(" "+ pat.getAuthority() + pat.getNumber() + "E");
nbRes++;
}
}
else if (pat.getPlant()) {
if (pat.getAuthority().equals("US")) {
System.out.println(" "+pat.getAuthority() + "PP" + pat.getNumber());
nbRes++;
}
}
else {
System.out.println(" "+pat.getAuthority() + pat.getNumber());
nbRes++;
}
numberListe.add(pat.getNumber());
}
}*/
if (articles != null) {
int k = 0;
for (String ref : referencesNPL) {
BiblioItem result = nplParser.processing(ref, consolidate);
BibDataSet bds = new BibDataSet();
bds.setResBib(result);
bds.setRawBib(ref);
bds.addOffset(offsets_NPL.get(k).intValue());
//bds.setConfidence(result.conf);
/*System.out.println(bds.getRawBib());
if (bds.getOffsets() != null) {
for(Integer val : bds.getOffsets()) {
System.out.println(val.toString() + " " + (val.intValue() + ref.length()) );
}
}
System.out.println(bds.getResBib().toTEI(0));
System.out.println("\n");*/
articles.add(bds);
k++;
}
}
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid.", e);
}
int nbs = 0;
if (patents != null) {
nbs = patents.size();
}
if (articles != null)
nbs += articles.size();
return nbs;
}
private String taggerRun(ArrayList<String> ress, Tagger tagger) throws Exception {
// clear internal context
tagger.clear();
// add context
for (String piece : ress) {
tagger.add(piece);
tagger.add("\n");
}
// parse and change internal stated as 'parsed'
if (!tagger.parse()) {
// throw an exception
throw new Exception("CRF++ parsing failed.");
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < tagger.size(); i++) {
for (int j = 0; j < tagger.xsize(); j++) {
res.append(tagger.x(i, j)).append("\t");
}
res.append(tagger.y2(i));
res.append("\n");
}
return res.toString();
}
/**
* Get the TEI XML string corresponding to the recognized citation section
*/
public String references2TEI2() {
String result = "<tei>\n";
BiblioSet bs = new BiblioSet();
for (BibDataSet bib : resBib) {
BiblioItem bit = bib.getResBib();
if (path != null) {
bit.buildBiblioSet(bs, path);
}
}
result += bs.toTEI();
result += "<listbibl>\n";
for (BibDataSet bib : resBib) {
BiblioItem bit = bib.getResBib();
result += "\n" + bit.toTEI2(bs);
}
result += "\n</listbibl>\n</tei>\n";
return result;
}
/**
* Get the TEI XML string corresponding to the recognized citation section for
* a particular citation
*/
public String reference2TEI(int i) {
String result = "";
if (resBib != null) {
if (i <= resBib.size()) {
BibDataSet bib = resBib.get(i);
BiblioItem bit = bib.getResBib();
if (path != null) {
bit.setPath(path);
}
result += bit.toTEI(i);
}
}
return result;
}
/**
* Get the BibTeX string corresponding to the recognized citation section
*/
public String references2BibTeX() {
String result = "";
for (BibDataSet bib : resBib) {
BiblioItem bit = bib.getResBib();
if (path != null) {
bit.setPath(path);
}
result += "\n" + bit.toBibTeX();
}
return result;
}
/**
* Get the TEI XML string corresponding to the recognized citation section,
* with pointers and advanced structuring
*/
public String references2TEI() {
String result = "<listbibl>\n";
int p = 0;
for (BibDataSet bib : resBib) {
BiblioItem bit = bib.getResBib();
if (path == null) {
bit.setPath(path);
}
result += "\n" + bit.toTEI(p);
p++;
}
result += "\n</listbibl>\n";
return result;
}
/**
* Get the BibTeX string corresponding to the recognized citation section
* for a given citation
*/
public String reference2BibTeX(int i) {
String result = "";
if (resBib != null) {
if (i <= resBib.size()) {
BibDataSet bib = resBib.get(i);
BiblioItem bit = bib.getResBib();
if (path == null) {
bit.setPath(path);
}
result += bit.toBibTeX();
}
}
return result;
}
/**
* Annotate XML files with extracted reference results. Not used.
*/
private void annotate(File file,
ArrayList<PatentItem> patents,
ArrayList<BibDataSet> articles) {
try {
// we simply rewrite lines based on identified reference strings without parsing
// special care for line breaks in the middle of a reference
ArrayList<String> sources = new ArrayList<String>();
ArrayList<String> targets = new ArrayList<String>();
for (PatentItem pi : patents) {
String context = pi.getContext();
String source = context;
sources.add(source);
String target = " <patcit>" + context + "</patcit> ";
targets.add(target);
System.out.println(source + " -> " + target);
}
for (BibDataSet bi : articles) {
String context = bi.getRawBib();
// we compile the corresponding regular expression
String source = context; //.replace(" ", "( |\\n)");
sources.add(source);
String target = " <nplcit>" + context + "</nplcit> ";
targets.add(target);
System.out.println(source + " -> " + target);
}
FileInputStream fileIn = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fileIn, "UTF-8");
BufferedReader bufReader = new BufferedReader(reader);
String line;
StringBuffer content = new StringBuffer();
content.append("");
while ((line = bufReader.readLine()) != null) {
content.append(line);
content.append("\n");
}
bufReader.close();
reader.close();
int i = 0;
String contentString = content.toString();
for (String source : sources) {
String target = targets.get(i);
contentString = contentString.replace(source, target);
i++;
}
System.out.println(contentString);
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
/**
* Annotate a new XML patent document based on training data format with the current model.
*
* @param documentPath is the path to the file to be processed
* @param newTrainingPath new training path
*/
public void generateTrainingData(String documentPath, String newTrainingPath) {
if (documentPath == null) {
throw new GrobidResourceException("Cannot process the patent file, because the document path is null.");
}
if (!documentPath.endsWith(".xml")) {
throw new GrobidResourceException("Only patent XML files (ST.36 or Marec) can be processed to " +
"generate traning data.");
}
File documentFile = new File(documentPath);
if (!documentFile.exists()) {
throw new GrobidResourceException("Cannot process the patent file, because path '" +
documentFile.getAbsolutePath() + "' does not exists.");
}
if (newTrainingPath == null) {
GrobidProperties.getInstance();
newTrainingPath = GrobidProperties.getTempPath().getAbsolutePath();
}
File newTrainingFile = new File(newTrainingPath);
if (!newTrainingFile.exists()) {
throw new GrobidResourceException("Cannot process the patent file, because path '" +
newTrainingFile.getAbsolutePath() + "' does not exists.");
}
try {
// first pass: we get the text to be processed
TextSaxParser sax = new TextSaxParser();
sax.setFilter("description");
// get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setFeature("http://xml.org/sax/features/namespaces", false);
spf.setFeature("http://xml.org/sax/features/validation", false);
//get a new instance of parser
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(
new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes()));
}
});
reader.setContentHandler(sax);
InputSource input = new InputSource(documentPath);
input.setEncoding("UTF-8");
reader.parse(input);
String description = sax.getText();
String currentPatentNumber = sax.currentPatentNumber;
ArrayList<PatentItem> patents = new ArrayList<PatentItem>();
ArrayList<BibDataSet> articles = new ArrayList<BibDataSet>();
// we process the patent description
if (description != null) {
extractAllReferencesString(description, false, false, patents, articles);
// second pass: we add annotations corresponding to identified citation chunks based on
// stored offsets
Writer writer = new OutputStreamWriter(
new FileOutputStream(new File(newTrainingPath + "/" + currentPatentNumber + ".training.xml"),
false), "UTF-8");
PatentAnnotationSaxParser saxx = new PatentAnnotationSaxParser();
saxx.setWriter(writer);
saxx.setPatents(patents);
saxx.setArticles(articles);
spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setFeature("http://xml.org/sax/features/namespaces", false);
spf.setFeature("http://xml.org/sax/features/validation", false);
//get a new instance of parser
reader = XMLReaderFactory.createXMLReader();
reader.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(
new ByteArrayInputStream("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes()));
}
});
reader.setContentHandler(saxx);
input = new InputSource(documentPath);
input.setEncoding("UTF-8");
reader.parse(input);
writer.close();
// last, we generate the training data corresponding to the parsing of the identified NPL citations
// buffer for the reference block
StringBuffer allBufferReference = new StringBuffer();
ArrayList<String> inputs = new ArrayList<String>();
for (BibDataSet article : articles) {
String refString = article.getRawBib();
if (refString.trim().length() > 1) {
inputs.add(refString.trim());
}
}
if (inputs.size() > 0) {
if (nplParser == null) {
nplParser = new CitationParser();
}
for (String inpu : inputs) {
ArrayList<String> inpus = new ArrayList<String>();
inpus.add(inpu);
StringBuilder bufferReference = nplParser.trainingExtraction(inpus);
if (bufferReference != null) {
allBufferReference.append(bufferReference.toString() + "\n");
}
}
}
if (allBufferReference != null) {
if (allBufferReference.length() > 0) {
Writer writerReference = new OutputStreamWriter(new FileOutputStream(
new File(newTrainingPath + "/" + currentPatentNumber +
".tranining.references.xml"), false), "UTF-8");
writerReference.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writerReference.write("<citations>\n");
writerReference.write(allBufferReference.toString());
writerReference.write("</citations>\n");
writerReference.close();
}
}
}
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
/**
* Get a patent description by its number and OPS
*/
public boolean getDocOPS(String number) {
try {
if (ops == null)
ops = new OPSService();
description = ops.descriptionRetrieval(number);
if (description == null)
return false;
else if (description.length() < 600)
return false;
else
return true;
} catch (Exception e) {
// e.printStackTrace();
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
/**
* Write the list of extracted references in an XML file
*/
public void generateXMLReport(File file,
ArrayList<PatentItem> patents,
ArrayList<BibDataSet> articles) {
try {
OutputStream tos = new FileOutputStream(file, false);
Writer writer = new OutputStreamWriter(tos, "UTF-8");
StringBuffer content = new StringBuffer();
// header
content.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
if ((patents.size() > 0) || (articles.size() > 0))
content.append("<citations>\n");
if (patents.size() > 0)
content.append("<patent-citations>\n");
int i = 0;
for (PatentItem pi : patents) {
String dnum = pi.getAuthority() + pi.getNumber();
if (pi.getKindCode() != null)
dnum += pi.getKindCode();
content.append("<patcit if=\"pcit" + i + " dnum=\"" + dnum + "\">" +
"<text>" + pi.getContext() + "</text></patcit>");
content.append("\n");
i++;
}
if (patents.size() > 0)
content.append("</patent-citations>\n");
if (articles.size() > 0)
content.append("<npl-citations>\n");
i = 0;
for (BibDataSet bds : articles) {
content.append("<nplcit if=\"ncit" + i + "\">");
content.append(bds.getResBib().toTEI(i));
content.append("<text>" + bds.getRawBib() + "</text></nplcit>");
content.append("\n");
i++;
}
if (articles.size() > 0)
content.append("</npl-citations>\n");
if ((patents.size() > 0) || (articles.size() > 0))
content.append("</citations>\n");
writer.write(content.toString());
writer.close();
tos.close();
} catch (Exception e) {
throw new GrobidException("An exception occured while running Grobid.", e);
}
}
/**
* not used...
*/
private static boolean checkPositionRange(int currentPosition,
int posit,
List<OffsetPosition> positions) {
boolean isInRange = false;
boolean skipTest = false;
if (currentPosition == positions.size() - 1) {
if (positions.get(currentPosition).end < posit) {
skipTest = true;
}
}
if (!skipTest) {
for (int i = currentPosition; i < positions.size(); i++) {
if ((positions.get(i).start <= posit) &&
(positions.get(i).end >= posit)) {
isInRange = true;
currentPosition = i;
break;
} else if (positions.get(i).start > posit) {
isInRange = false;
currentPosition = i;
break;
}
}
}
return isInRange;
}
@Override
public void close() throws IOException {
taggerAll.clear();
taggerNPL.clear();
taggerPatent.clear();
taggerAll.delete();
taggerNPL.delete();
taggerPatent.delete();
taggerAll = null;
taggerNPL = null;
taggerPatent = null;
if (nplParser != null) {
nplParser.close();
nplParser = null;
}
}
}
|
package uk.co.vurt.hakken.domain.task.pageitem;
import java.util.List;
import java.util.Map;
public class PageItem {
String name;
String label;
String type;
String value;
List<LabelledValue> values;
Map<String, String> attributes;
public PageItem(){}
public PageItem(String name, String label, String type, String value) {
super();
this.name = name;
this.label = label;
this.type = type;
this.value = value;
}
public PageItem(String name, String label, String type, String value, Map<String, String> attributes) {
this(name, label, type, value);
this.attributes = attributes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public List<LabelledValue> getValues() {
return values;
}
public void setValues(List<LabelledValue> values) {
this.values = values;
}
@Override
public String toString() {
return "PageItem [name=" + name + ", label=" + label + ", type=" + type
+ ", value=" + value + ", values=" + values + ", attributes="
+ attributes + "]";
}
// @Override
// public String toString() {
// return "Item [name=" + name + ", type=" + type + ", label=" + label
// + ", value=" + value + "]";
}
|
package org.hamcrest.collection;
import org.hamcrest.Factory;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
import org.hamcrest.core.IsEqual;
import java.util.Collection;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* Matches if collection size satisfies a nested matcher.
*/
public class IsCollectionWithSize<E> extends FeatureMatcher<Collection<? extends E>, Integer> {
public IsCollectionWithSize(Matcher<? super Integer> sizeMatcher) {
super(sizeMatcher, "a collection with size", "collection size");
}
@Override
protected Integer featureValueOf(Collection<? extends E> actual) {
return actual.size();
}
/**
* Creates a matcher for {@link java.util.Collection}s that matches when the <code>size()</code> method returns
* a value that satisfies the specified matcher.
* <p/>
* For example:
* <pre>assertThat(Arrays.asList("foo", "bar"), hasSize(equalTo(2)))</pre>
*
* @param sizeMatcher
* a matcher for the size of an examined {@link java.util.Collection}
*/
@Factory
public static <E> Matcher<Collection<? extends E>> hasSize(Matcher<? super Integer> sizeMatcher) {
return new IsCollectionWithSize<E>(sizeMatcher);
}
/**
* Creates a matcher for {@link java.util.Collection}s that matches when the <code>size()</code> method returns
* a value equal to the specified <code>size</code>.
* <p/>
* For example:
* <pre>assertThat(Arrays.asList("foo", "bar"), hasSize(2))</pre>
*
* @param size
* the expected size of an examined {@link java.util.Collection}
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Factory
public static <E> Matcher<Collection<? extends E>> hasSize(int size) {
return (Matcher)IsCollectionWithSize.hasSize(IsEqual.<Integer>equalTo(size));
}
}
|
package org.motechproject.nms.imi.service.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.datanucleus.store.rdbms.query.ForwardQueryResult;
import org.motechproject.alerts.contract.AlertService;
import org.motechproject.alerts.domain.AlertStatus;
import org.motechproject.alerts.domain.AlertType;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventRelay;
import org.motechproject.event.listener.annotations.MotechListener;
import org.motechproject.mds.query.SqlQueryExecution;
import org.motechproject.metrics.service.Timer;
import org.motechproject.nms.imi.domain.CallDetailRecord;
import org.motechproject.nms.imi.domain.CallSummaryRecord;
import org.motechproject.nms.imi.domain.ChunkAuditRecord;
import org.motechproject.nms.imi.domain.FileAuditRecord;
import org.motechproject.nms.imi.domain.FileProcessedStatus;
import org.motechproject.nms.imi.domain.FileType;
import org.motechproject.nms.imi.exception.ChunkingException;
import org.motechproject.nms.imi.exception.ExecException;
import org.motechproject.nms.imi.exception.InternalException;
import org.motechproject.nms.imi.exception.InvalidCallRecordFileException;
import org.motechproject.nms.imi.repository.CallDetailRecordDataService;
import org.motechproject.nms.imi.repository.CallSummaryRecordDataService;
import org.motechproject.nms.imi.repository.ChunkAuditRecordDataService;
import org.motechproject.nms.imi.repository.FileAuditRecordDataService;
import org.motechproject.nms.imi.service.CdrFileService;
import org.motechproject.nms.imi.service.contract.CdrFileProcessedNotification;
import org.motechproject.nms.imi.web.contract.CdrFileNotificationRequest;
import org.motechproject.nms.imi.web.contract.FileInfo;
import org.motechproject.nms.kilkari.domain.CallRetry;
import org.motechproject.nms.kilkari.dto.CallSummaryRecordDto;
import org.motechproject.nms.kilkari.exception.InvalidCallRecordDataException;
import org.motechproject.nms.kilkari.service.CallRetryService;
import org.motechproject.nms.kilkari.service.CsrService;
import org.motechproject.nms.kilkari.service.CsrVerifierService;
import org.motechproject.server.config.SettingsFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.jdo.Query;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Math.min;
/**
* Implementation of the {@link CdrFileService} interface.
*/
@Service("cdrFileService")
public class CdrFileServiceImpl implements CdrFileService {
public static final String DISPLAYING_THE_FIRST_N_ERRORS = "%s: %d errors - only displaying the first %d";
private static final String DISTRIBUTED_CSR_PROCESSING = "imi.distributed_csr_processing";
private static final String CSR_CHUNK_SIZE = "imi.csr_chunk_size";
private static final int CSR_CHUNK_SIZE_DEFAULT = 1000;
private static final Boolean DISTRIBUTED_CSR_PROCESSING_DEFAULT = false;
private static final String CDR_FILE_NOTIFICATION_URL = "imi.cdr_file_notification_url";
private static final String LOCAL_CDR_DIR = "imi.local_cdr_dir";
private static final String CDR_CSR_RETENTION_DURATION = "imi.cdr_csr.retention.duration";
private static final int MIN_CALL_DATA_RETENTION_DURATION_IN_DAYS = 5;
private static final String CDR_CSR_CLEANUP_SUBJECT = "nms.imi.cdr_csr.cleanup";
private static final String CDR_TABLE_NAME = "motech_data_services.nms_imi_cdrs";
private static final String NMS_IMI_KK_PROCESS_CSR = "nms.imi.kk.process_csr";
private static final String NMS_IMI_PROCESS_CHUNK = "nms.imi.process_chunk";
private static final String CDR_PHASE_2 = "nms.imi.kk.cdr_phase_2";
private static final String CDR_PHASE_3 = "nms.imi.kk.cdr_phase_3";
private static final String CDR_PHASE_4 = "nms.imi.kk.cdr_phase_4";
private static final String CDR_PHASE_5 = "nms.imi.kk.cdr_phase_5";
private static final String OBD_FILE_PARAM_KEY = "obdFile";
private static final String CSR_FILE_PARAM_KEY = "csrFile";
private static final String CSR_CHECKSUM_PARAM_KEY = "csrChecksum";
private static final String CSR_COUNT_PARAM_KEY = "csrCount";
private static final String CDR_FILE_PARAM_KEY = "cdrFile";
private static final String CDR_CHECKSUM_PARAM_KEY = "cdrChecksum";
private static final String CDR_COUNT_PARAM_KEY = "cdrCount";
private static final String LOG_TEMPLATE = "Found %d records in table %s";
private static final String CDR_DETAIL_FILE = "CDR Detail File";
private static final String IGNORING_CSR_ROW = "Ignoring CSR error - %s(%d): %s";
private static final String IGNORING_CDR_HDR = "Ignoring CDR Hhader error - %s: %s";
private static final String IGNORING_CSR_HDR = "Ignoring CSR Hhader error - %s: %s";
private static final String IGNORING_CDR_ROW = "Ignoring CDR error - %s(%d): %s";
private static final String FILE_LINE_ERROR = "%s(%d): %s";
private static final String UNABLE_TO_READ = "Unable to read %s: %s";
private static final String UNABLE_TO_READ_HEADER = "Unable to read header %s: %s";
private static final int CDR_PROGRESS_REPORT_CHUNK = 10000;
private static final String MAX_CDR_ERROR_COUNT = "imi.max_cdr_error_count";
private static final String CSR_TABLE_NAME = "motech_data_services.nms_imi_csrs";
private static final int MAX_CDR_ERROR_COUNT_DEFAULT = 100;
private static final int MAX_CHAR_ALERT = 4500;
private static final String INVALID_CDR_P4 = "The CDR should be readable & valid in Phase 4, this is an internal MOTECH error and must be investigated - ";
private static final String INVALID_CSR_P5 = "The CSR should be readable & valid in Phase 5, this is an internal MOTECH error and must be investigated - ";
private static final String INVALID_CDR_HEADER_P2 = "The CDR header should be valid in Phase 2, this is an internal MOTECH error and must be investigated - ";
private static final String INVALID_CDR_P2 = "The CDR should be readable & valid in Phase 2, this is an internal MOTECH error and must be investigated - ";
private static final String INVALID_CSR_HEADER_P2 = "The CSR header should be valid in Phase 2, this is an internal MOTECH error and must be investigated - ";
private static final String INVALID_CSR_P2 = "The CSR should be readable & valid in Phase 2, this is an internal MOTECH error and must be investigated - ";
private static final String COPY_ERROR = "Copy Error";
private static final String ENTIRE_LINE_FMT = "%s [%s]";
private static final String MOTECH_BUG = "!!!MOTECH BUG!!! Unexpected Exception in %s: %s";
private static final Logger LOGGER = LoggerFactory.getLogger(CdrFileServiceImpl.class);
public static final double HALF = 0.5;
private SettingsFacade settingsFacade;
private EventRelay eventRelay;
private FileAuditRecordDataService fileAuditRecordDataService;
private AlertService alertService;
private CallDetailRecordDataService callDetailRecordDataService;
private CallSummaryRecordDataService callSummaryRecordDataService;
private CsrService csrService;
private CallRetryService callRetryService;
private CsrVerifierService csrVerifierService;
private ChunkAuditRecordDataService chunkAuditRecordDataService;
@Autowired
public CdrFileServiceImpl(@Qualifier("imiSettings") // NO CHECKSTYLE More than 7 parameters
SettingsFacade settingsFacade, EventRelay eventRelay,
FileAuditRecordDataService fileAuditRecordDataService, AlertService alertService,
CallDetailRecordDataService callDetailRecordDataService,
CallSummaryRecordDataService callSummaryRecordDataService, CsrService csrService,
CsrVerifierService csrVerifierService, CallRetryService callRetryService,
ChunkAuditRecordDataService chunkAuditRecordDataService) {
this.settingsFacade = settingsFacade;
this.eventRelay = eventRelay;
this.fileAuditRecordDataService = fileAuditRecordDataService;
this.alertService = alertService;
this.callDetailRecordDataService = callDetailRecordDataService;
this.callSummaryRecordDataService = callSummaryRecordDataService;
this.csrService = csrService;
this.csrVerifierService = csrVerifierService;
this.callRetryService = callRetryService;
this.chunkAuditRecordDataService = chunkAuditRecordDataService;
}
private void alertAndAudit(String file, List<String> errors) {
for (String error : errors) {
alertAndAudit(file, error);
}
}
private void alertAndAudit(String file, String error) {
LOGGER.error(error);
alertService.create(file, CDR_DETAIL_FILE, error, AlertType.CRITICAL, AlertStatus.NEW, 0, null);
fileAuditRecordDataService.create(new FileAuditRecord(FileType.CDR_DETAIL_FILE, file, false, error,
null, null));
}
private void sendNotificationRequest(CdrFileProcessedNotification cfpn) {
String notificationUrl = settingsFacade.getProperty(CDR_FILE_NOTIFICATION_URL);
LOGGER.debug("Sending {} to {}", cfpn, notificationUrl);
ExponentialRetrySender sender = new ExponentialRetrySender(settingsFacade, alertService);
HttpPost httpPost = new HttpPost(notificationUrl);
ObjectMapper mapper = new ObjectMapper();
try {
String requestJson = mapper.writeValueAsString(cfpn);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(requestJson));
} catch (IOException e) {
throw new InternalException(String.format("Unable to create cdrFile notification request: %s",
e.getMessage()), e);
}
sender.sendNotificationRequest(httpPost, HttpStatus.SC_OK, cfpn.getFileName(), "cdrFile Notification Request");
}
/**
* Verifies the checksum & record count provided in fileInfo match the checksum & record count of file
* also verifies all csv rows are valid.
*
* @param fileInfo file information provided about the file (ie: expected checksum & recordCount)
*
* @return a list of errors (failure) or an empty list (success)
*/
@Override
public List<String> verifyChecksumAndCountAndCsv(FileInfo fileInfo, Boolean isDetailFile) {
File file = new File(localCdrDir(), fileInfo.getCdrFile());
List<String> errors = new ArrayList<>();
int lineNumber = 1;
String thisChecksum = "";
String fileName = file.getName();
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
String line = reader.readLine();
try {
if (isDetailFile) {
CdrHelper.validateHeader(line);
} else {
CsrHelper.validateHeader(line);
}
} catch (IllegalArgumentException e) {
String error = String.format("Unable to read header %s: %s", fileName, e.getMessage());
errors.add(error);
}
while ((line = reader.readLine()) != null) {
try {
// Parse the CSV line into a CDR or CSR (which we actually discard in this phase)
if (isDetailFile) {
CdrHelper.validateCsv(line);
} else {
CsrHelper.validateCsv(line);
}
} catch (IllegalArgumentException e) {
errors.add(String.format(FILE_LINE_ERROR, fileName, lineNumber, e.getMessage()));
}
lineNumber++;
}
reader.close();
isr.close();
fis.close();
thisChecksum = ChecksumHelper.checksum(file);
if (!thisChecksum.equalsIgnoreCase(fileInfo.getChecksum())) {
String error = String.format("Checksum mismatch for %s: provided checksum: %s, calculated checksum: %s",
fileName, fileInfo.getChecksum(), thisChecksum);
errors.add(error);
}
if (lineNumber - 1 != fileInfo.getRecordsCount()) {
String error = String.format("Record count mismatch, provided count: %d, actual count: %d",
fileInfo.getRecordsCount(), lineNumber - 1);
errors.add(error);
}
} catch (IOException e) {
String error = String.format(UNABLE_TO_READ, fileName, e.getMessage());
errors.add(error);
}
return errors;
}
/**
* Save detail records for reporting
*
* @param file file to process
* @return a list of errors (failure) or an empty list (success)
*/
@Override
public void saveDetailRecords(File file) {
int lineNumber = 1;
int saveCount = 0;
String fileName = file.getName();
LOGGER.info("saveDetailRecords({})", fileName);
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
String line;
try {
line = reader.readLine();
CdrHelper.validateHeader(line);
} catch (IllegalArgumentException e) {
//errors here should have been reported in Phase 2, let's just ignore them
//todo remove following line to not over confuse ops?
LOGGER.debug(String.format(IGNORING_CDR_HDR, fileName, e.getMessage()));
}
Timer timer = new Timer("cdr", "cdrs");
while ((line = reader.readLine()) != null) {
try {
CallDetailRecord cdr = CdrHelper.csvLineToCdr(line);
// Save a copy of the CDR into CallDetailRecord for reporting - but no dupes
if (callDetailRecordDataService.countFindByRequestId(cdr.getRequestId()) == 0) {
callDetailRecordDataService.create(cdr);
saveCount++;
}
} catch (InvalidCallRecordDataException | IllegalArgumentException e) {
//errors here should have been reported in Phase 2, let's just ignore them
//todo remove following line to not over confuse ops?
LOGGER.debug(String.format(IGNORING_CDR_ROW, fileName, lineNumber, e.getMessage()));
}
if (lineNumber % CDR_PROGRESS_REPORT_CHUNK == 0) {
LOGGER.debug("Saved {}", timer.frequency(lineNumber));
}
lineNumber++;
}
LOGGER.info("Read {}", timer.frequency(lineNumber));
LOGGER.info("Actually saved {}", saveCount);
} catch (IOException e) {
String error = INVALID_CDR_P4 + String.format(UNABLE_TO_READ, fileName, e.getMessage());
LOGGER.error(error);
alertService.create(fileName, "Invalid CDR in Phase 4", error, AlertType.CRITICAL, AlertStatus.NEW, 0,
null);
} catch (Exception e) {
String msg = String.format(MOTECH_BUG, "P4 - saveDetailRecords", ExceptionUtils.getFullStackTrace(e));
LOGGER.error(msg);
alertService.create(fileName, "saveDetailRecords", msg.substring(0, min(msg.length(), MAX_CHAR_ALERT)),
AlertType.CRITICAL, AlertStatus.NEW, 0, null);
}
}
private boolean shouldDistributeCsrProcessing() {
try {
return Boolean.valueOf(settingsFacade.getProperty(DISTRIBUTED_CSR_PROCESSING));
} catch (Exception e) {
LOGGER.info("Unable to read {}, returning default value {}", DISTRIBUTED_CSR_PROCESSING,
DISTRIBUTED_CSR_PROCESSING_DEFAULT);
return DISTRIBUTED_CSR_PROCESSING_DEFAULT;
}
}
private int csrChunkSize() {
try {
return Integer.valueOf(settingsFacade.getProperty(CSR_CHUNK_SIZE));
} catch (Exception e) {
LOGGER.info("Unable to read {}, returning default value {}", CSR_CHUNK_SIZE, CSR_CHUNK_SIZE_DEFAULT);
return CSR_CHUNK_SIZE_DEFAULT;
}
}
private void processOneCsr(CallSummaryRecordDto csrDto, boolean distributed) {
Map<String, Object> params = CallSummaryRecordDto.toParams(csrDto);
MotechEvent motechEvent = new MotechEvent(NMS_IMI_KK_PROCESS_CSR, params);
if (distributed) {
eventRelay.sendEventMessage(motechEvent);
} else {
csrService.processCallSummaryRecord(motechEvent);
}
}
private void distributeChunk(String file, String name, List<CallSummaryRecordDto> csrDtos) {
ObjectMapper mapper = new ObjectMapper();
String chunk;
try {
chunk = mapper.writeValueAsString(csrDtos);
} catch (IOException e) {
throw new ChunkingException(String.format("Exception packaging CSR chunk: %s", e.getMessage()), e);
}
Map<String, Object> params = new HashMap<>();
params.put("file", file);
params.put("name", name);
params.put("chunk", chunk);
MotechEvent motechEvent = new MotechEvent(NMS_IMI_PROCESS_CHUNK, params);
eventRelay.sendEventMessage(motechEvent);
}
private String hostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "
}
}
private void reportAllChunksProcessed(final String file) {
@SuppressWarnings("unchecked")
SqlQueryExecution<List<ChunkAuditRecord>> queryExecution = new SqlQueryExecution<List<ChunkAuditRecord>>() {
@Override
public String getSqlQuery() {
String query = String.format("SELECT * FROM nms_imi_chunk_audit_record WHERE file = '%s' AND " +
"node IS NULL LIMIT 1", file);
LOGGER.debug("SQL QUERY: {}", query);
return query;
}
@Override
public List<ChunkAuditRecord> execute(Query query) {
query.setClass(CallRetry.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
return (List<ChunkAuditRecord>) fqr;
}
};
List<ChunkAuditRecord> records = chunkAuditRecordDataService.executeSQLQuery(queryExecution);
if (records.size() == 0) {
LOGGER.info("All chunk(s) of {} were processed.", file);
}
}
@MotechListener(subjects = { NMS_IMI_PROCESS_CHUNK })
@Transactional
public void processChunk(MotechEvent event) {
Timer timer = new Timer("csr", "csrs");
String file = (String) event.getParameters().get("file");
String name = (String) event.getParameters().get("name");
String json = (String) event.getParameters().get("chunk");
ObjectMapper mapper = new ObjectMapper();
List<CallSummaryRecordDto> csrDtos;
try {
try {
csrDtos = mapper.readValue(json, new TypeReference<List<CallSummaryRecordDto>>() { });
} catch (IOException e) {
throw new ChunkingException(String.format("Exception unpacking packaging CSR chunk %s: %s", name,
e.getMessage()), e);
}
LOGGER.info("Processing {} ({} csrs)", name, csrDtos.size());
for (CallSummaryRecordDto csrDto : csrDtos) {
Map<String, Object> params = CallSummaryRecordDto.toParams(csrDto);
MotechEvent motechEvent = new MotechEvent(NMS_IMI_KK_PROCESS_CSR, params);
csrService.processCallSummaryRecord(motechEvent);
}
ChunkAuditRecord record = chunkAuditRecordDataService.findByFileAndChunk(file, name);
if (record != null) {
record.setCsrProcessed(csrDtos.size());
record.setNode(hostName());
chunkAuditRecordDataService.update(record);
}
reportAllChunksProcessed(file);
} catch (Exception e) {
String msg = String.format(MOTECH_BUG, "P5 - processChunk - " + name, ExceptionUtils.getFullStackTrace(e));
LOGGER.error(msg);
alertService.create(name, "processCsrs", msg.substring(0, min(msg.length(), MAX_CHAR_ALERT)),
AlertType.CRITICAL, AlertStatus.NEW, 0, null);
// We want to fail this event to we get retried
throw e;
}
LOGGER.info("Processed {} {}", name, timer.frequency(csrDtos.size()));
}
/**
* Send summary records for processing as CallSummaryRecordDto in MOTECH events or process them directly,
* depending on the imi.distributed_csr_processing setting
* Additionally stores a copy of the provided CSR in the CallSummaryRecord table, for reporting
*
* @param file file to process
* @return a list of errors (failure) or an empty list (success)
*/
@Override //NO CHECKSTYLE Cyclomatic Complexity
public void processCsrs(File file, int lineCount) { //NOPMD NcssMethodCount
int lineNumber = 1;
int saveCount = 0;
int processCount = 0;
int chunkCount = 0;
int chunkNumber = 0;
String fileName = file.getName();
LOGGER.info("processCsrs({}, {})", fileName, lineCount);
boolean distributedProcessing = shouldDistributeCsrProcessing();
String verb = distributedProcessing ? "distributed" : "enqueued";
List<CallSummaryRecordDto> chunk = new ArrayList<>();
int chunkSize = csrChunkSize();
if (chunkSize > 1) {
LOGGER.info("CSRs will be distributed in chunks of {} csrs", chunkSize);
chunkCount = (int) Math.round((lineCount / chunkSize) + HALF);
chunkNumber = 1;
LOGGER.info("{} CSRs will be distributed in {} chunk(s)", lineCount, chunkCount);
verb = "distributed";
} else {
LOGGER.info("CSR processing will be {}", distributedProcessing ? "distributed" : "local");
}
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
String line;
try {
line = reader.readLine();
CsrHelper.validateHeader(line);
} catch (IllegalArgumentException e) {
//errors here should have been reported in Phase 2, let's just ignore them
//todo remove following line to not over confuse ops?
LOGGER.debug(String.format(IGNORING_CSR_HDR, fileName, e.getMessage()));
}
Timer timer = new Timer("csr", "csrs");
Timer chunkTimer = new Timer("chunk", "chunks");
while ((line = reader.readLine()) != null) {
try {
CallSummaryRecord csr = CsrHelper.csvLineToCsr(line);
if (callSummaryRecordDataService.countFindByRequestId(csr.getRequestId()) == 0) {
callSummaryRecordDataService.create(csr);
saveCount++;
}
if (chunkSize > 1) {
chunk.add(csr.toDto());
if (chunk.size() >= chunkSize || lineNumber >= lineCount) {
LOGGER.info(String.format("Distributing chunk %d of %d (%d csrs): %s", chunkNumber,
chunkCount, chunk.size(), chunkTimer.frequency(chunkNumber)));
String chunkName = String.format("Chunk%d/%d", chunkNumber, chunkCount);
distributeChunk(fileName, chunkName, chunk);
chunkAuditRecordDataService.createOrUpdate(new ChunkAuditRecord(fileName, chunkName,
chunk.size(), 0, null));
chunk = new ArrayList<>();
chunkNumber++;
}
} else {
processOneCsr(csr.toDto(), distributedProcessing);
processCount++;
}
} catch (InvalidCallRecordDataException | IllegalArgumentException e) {
// All errors here should have been reported in Phase 2, let's just ignore them
//todo remove following line to not over confuse ops?
LOGGER.debug(String.format(IGNORING_CSR_ROW, fileName, lineNumber, e.getMessage()));
}
if (lineNumber % CDR_PROGRESS_REPORT_CHUNK == 0) {
LOGGER.debug("Read {}", timer.frequency(lineNumber));
}
if (lineNumber % CDR_PROGRESS_REPORT_CHUNK == 0) {
LOGGER.debug("Processed {}", timer.frequency(processCount));
}
lineNumber++;
}
LOGGER.info(String.format("Read %s", timer.frequency(lineNumber)));
LOGGER.info(String.format("Saved %d, %s %d", saveCount, verb, processCount));
} catch (IOException e) {
String error = INVALID_CSR_P5 + String.format(UNABLE_TO_READ, fileName, e.getMessage());
LOGGER.error(error);
alertService.create(fileName, "Invalid CSR in Phase 5", error, AlertType.CRITICAL, AlertStatus.NEW, 0,
null);
} catch (Exception e) {
String msg = String.format(MOTECH_BUG, "P5 - processCsrs", ExceptionUtils.getFullStackTrace(e));
LOGGER.error(msg);
alertService.create(fileName, "processCsrs", msg.substring(0, min(msg.length(), MAX_CHAR_ALERT)),
AlertType.CRITICAL, AlertStatus.NEW, 0, null);
}
}
private CdrFileNotificationRequest requestFromParams(Map<String, Object> params) {
return new CdrFileNotificationRequest(
(String) params.get(OBD_FILE_PARAM_KEY),
new FileInfo(
(String) params.get(CSR_FILE_PARAM_KEY),
(String) params.get(CSR_CHECKSUM_PARAM_KEY),
(int) params.get(CSR_COUNT_PARAM_KEY)
),
new FileInfo(
(String) params.get(CDR_FILE_PARAM_KEY),
(String) params.get(CDR_CHECKSUM_PARAM_KEY),
(int) params.get(CDR_COUNT_PARAM_KEY)
)
);
}
private Map<String, Object> paramsFromRequest(CdrFileNotificationRequest request) {
Map<String, Object> params = new HashMap<>();
params.put(OBD_FILE_PARAM_KEY, request.getFileName());
params.put(CSR_FILE_PARAM_KEY, request.getCdrSummary().getCdrFile());
params.put(CSR_CHECKSUM_PARAM_KEY, request.getCdrSummary().getChecksum());
params.put(CSR_COUNT_PARAM_KEY, request.getCdrSummary().getRecordsCount());
params.put(CDR_FILE_PARAM_KEY, request.getCdrDetail().getCdrFile());
params.put(CDR_CHECKSUM_PARAM_KEY, request.getCdrDetail().getChecksum());
params.put(CDR_COUNT_PARAM_KEY, request.getCdrDetail().getRecordsCount());
return params;
}
private void sendPhaseEvent(String subject, CdrFileNotificationRequest request) {
MotechEvent motechEvent = new MotechEvent(subject, paramsFromRequest(request));
eventRelay.sendEventMessage(motechEvent);
}
private File localCdrDir() {
return new File(settingsFacade.getProperty(LOCAL_CDR_DIR));
}
// Phase 1: verify the file exists, the csv is valid and its record count and checksum match the provided info
// while collecting a list of errors on the go.
// Does not proceed to phase 2 if any error occurred and returns an error
@Override //NO CHECKSTYLE Cyclomatic Complexity
public void cdrProcessingPhase1(CdrFileNotificationRequest request) {
LOGGER.info("CDR Processing - Phase 1 - Start");
List<String> cdrErrors = verifyChecksumAndCountAndCsv(request.getCdrDetail(), true);
alertAndAudit(request.getCdrDetail().getCdrFile(), cdrErrors);
List<String> csrErrors = verifyChecksumAndCountAndCsv(request.getCdrSummary(), false);
alertAndAudit(request.getCdrSummary().getCdrFile(), csrErrors);
if (cdrErrors.size() > 0 || csrErrors.size() > 0) {
List<String> returnedErrors = new ArrayList<>();
int maxErrors = getMaxErrorCount();
LOGGER.debug("Phase 1 - Error");
if (cdrErrors.size() > 0) {
List<String> maxCdrErrors = cdrErrors.subList(0, min(maxErrors, cdrErrors.size()));
if (cdrErrors.size() > maxErrors) {
String error = String.format(DISPLAYING_THE_FIRST_N_ERRORS, request.getCdrDetail().getCdrFile(),
cdrErrors.size(), maxErrors);
LOGGER.error(error);
alertService.create(request.getCdrDetail().getCdrFile(), "Phase 1 - Too many errors in CDR", error,
AlertType.HIGH, AlertStatus.NEW, 0, null);
returnedErrors.add(error);
}
returnedErrors.addAll(maxCdrErrors);
}
if (csrErrors.size() > 0) {
List<String> maxCsrErrors = csrErrors.subList(0, min(maxErrors, csrErrors.size()));
if (csrErrors.size() > maxErrors) {
String error = String.format(DISPLAYING_THE_FIRST_N_ERRORS, request.getCdrSummary().getCdrFile(),
csrErrors.size(), maxErrors);
LOGGER.error(error);
alertService.create(request.getCdrSummary().getCdrFile(), "Phase 1 - Too many errors in CSR", error,
AlertType.HIGH, AlertStatus.NEW, 0, null);
returnedErrors.add(error);
}
returnedErrors.addAll(maxCsrErrors);
}
if (cdrErrors.size() > 0) {
fileAuditRecordDataService.create(new FileAuditRecord(FileType.CDR_DETAIL_FILE,
request.getCdrDetail().getCdrFile(), false,
String.format("%d invalid CDR rows, see tomcat log", cdrErrors.size()), null, null));
}
if (csrErrors.size() > 0) {
fileAuditRecordDataService.create(new FileAuditRecord(FileType.CDR_SUMMARY_FILE,
request.getCdrSummary().getCdrFile(), false,
String.format("%d invalid CSR rows, see tomcat log", csrErrors.size()), null, null));
}
throw new InvalidCallRecordFileException(returnedErrors);
}
// Send a MOTECH event to continue to phase 2 (without timing out the POST from IMI)
LOGGER.info("Phase 1 - Sending Phase 2 event");
sendPhaseEvent(CDR_PHASE_2, request);
LOGGER.info("Phase 1 - Success");
}
// Runs the copy command stored in the imi.scp.from_command entry of the imi.properties file
// Likely scp, but could be something else
private void copyFile(File file) throws ExecException {
LOGGER.debug("Copying {} from IMI...", file.getName());
ScpHelper scpHelper = new ScpHelper(settingsFacade);
scpHelper.scpCdrFromRemote(file.getName());
}
private List<String> verifyDetailFile(CdrFileNotificationRequest request) {
List<String> errors = new ArrayList<>();
File file = new File(localCdrDir(), request.getCdrDetail().getCdrFile());
String fileName = file.getName();
int lineNumber = 1;
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
String line;
try {
line = reader.readLine();
CdrHelper.validateHeader(line);
} catch (IllegalArgumentException e) {
String error = INVALID_CDR_HEADER_P2 + String.format(UNABLE_TO_READ_HEADER, fileName, e.getMessage());
errors.add(error);
LOGGER.error(error);
alertService.create(fileName, "Invalid CDR Header in Phase 2", error, AlertType.CRITICAL,
AlertStatus.NEW, 0, null);
return errors;
}
while ((line = reader.readLine()) != null) {
try {
CdrHelper.csvLineToCdrDto(line);
} catch (InvalidCallRecordDataException e) {
String error = String.format(FILE_LINE_ERROR, fileName, lineNumber, e.getMessage());
LOGGER.debug(String.format(ENTIRE_LINE_FMT, error, line));
errors.add(error);
}
lineNumber++;
}
} catch (IOException e) {
String error = INVALID_CDR_P2 + String.format(UNABLE_TO_READ, fileName, e.getMessage());
errors.add(error);
LOGGER.error(error);
alertService.create(fileName, "Invalid CDR in Phase 2", error, AlertType.CRITICAL, AlertStatus.NEW, 0,
null);
return errors;
}
return errors;
}
private List<String> verifySummaryFile(CdrFileNotificationRequest request) {
List<String> errors = new ArrayList<>();
File file = new File(localCdrDir(), request.getCdrSummary().getCdrFile());
String fileName = file.getName();
int lineNumber = 1;
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
String line;
try {
line = reader.readLine();
CsrHelper.validateHeader(line);
} catch (IllegalArgumentException e) {
String error = INVALID_CSR_HEADER_P2 + String.format(UNABLE_TO_READ_HEADER,
fileName, e.getMessage());
errors.add(error);
LOGGER.error(error);
alertService.create(fileName, "Invalid CSR Header in Phase 2", error, AlertType.CRITICAL,
AlertStatus.NEW, 0, null);
return errors;
}
while ((line = reader.readLine()) != null) {
try {
CallSummaryRecord csr = CsrHelper.csvLineToCsr(line);
CallSummaryRecordDto csrDto = csr.toDto();
csrVerifierService.verify(csrDto);
} catch (InvalidCallRecordDataException e) {
String error = String.format(FILE_LINE_ERROR, fileName, lineNumber, e.getMessage());
LOGGER.debug(String.format(ENTIRE_LINE_FMT, error, line));
errors.add(error);
}
lineNumber++;
}
} catch (IOException e) {
String error = INVALID_CSR_P2 + String.format(UNABLE_TO_READ, fileName, e.getMessage());
errors.add(error);
LOGGER.error(error);
alertService.create(fileName, "Invalid File in Phase 2", error, AlertType.CRITICAL, AlertStatus.NEW, 0,
null);
return errors;
}
return errors;
}
private int getMaxErrorCount() {
try {
return Integer.parseInt(settingsFacade.getProperty(MAX_CDR_ERROR_COUNT));
} catch (NumberFormatException e) {
return MAX_CDR_ERROR_COUNT_DEFAULT;
}
}
// Phase 2: Verify files a little mode deeply than t=in phase 1 (ie: check csv field values are valid)
// Send list on invalid CDR/CSR rows in CdrFileProcessedNotification HTTP POST back to IMI and dispatches
// messages for Phase 3 & 4 processing to any node.
@Override //NO CHECKSTYLE Cyclomatic Complexity
@MotechListener(subjects = { CDR_PHASE_2 })
@Transactional
public List<String> cdrProcessPhase2(MotechEvent event) { //NOPMD NcssMethodCount
LOGGER.info("Phase 2 - Start");
CdrFileNotificationRequest request = requestFromParams(event.getParameters());
LOGGER.debug("Phase 2 - cdrFileNotificationRequest: {}", request);
// Detail File
LOGGER.info("Phase 2 - copy detail File");
File cdrFile = new File(localCdrDir(), request.getCdrDetail().getCdrFile());
try {
copyFile(cdrFile);
} catch (ExecException e) {
String error = String.format("Error copying CDR file %s: %s", cdrFile.getName(), e.getMessage());
LOGGER.error(error);
alertService.create(cdrFile.getName(), COPY_ERROR, error, AlertType.CRITICAL, AlertStatus.NEW, 0, null);
return Arrays.asList(error);
}
LOGGER.info("Phase 2 - verify detail File");
List<String> detailErrors = verifyDetailFile(request);
// Summary File
LOGGER.info("Phase 2 - copy detail File");
File csrFile = new File(localCdrDir(), request.getCdrSummary().getCdrFile());
try {
copyFile(csrFile);
} catch (ExecException e) {
String error = String.format("Error copying CSR file %s: %s", csrFile.getName(), e.getMessage());
LOGGER.error(error);
alertService.create(csrFile.getName(), COPY_ERROR, error, AlertType.CRITICAL, AlertStatus.NEW, 0, null);
// This is a monster error, let's not even bother talking about the potential errors in detailErrors
return Arrays.asList(error);
}
LOGGER.info("Phase 2 - verifySummaryFile");
List<String> summaryErrors = verifySummaryFile(request);
List<String> returnedErrors = new ArrayList<>();
FileProcessedStatus status = FileProcessedStatus.FILE_PROCESSED_SUCCESSFULLY;
String failure = null;
if (detailErrors.size() > 0 || summaryErrors.size() > 0) {
int maxErrors = getMaxErrorCount();
LOGGER.debug("Phase 2 - Error");
status = FileProcessedStatus.FILE_ERROR_IN_FILE_FORMAT;
if (detailErrors.size() > 0) {
List<String> maxDetailErrors = detailErrors.subList(0, min(maxErrors, detailErrors.size()));
if (detailErrors.size() > maxErrors) {
String error = String.format(DISPLAYING_THE_FIRST_N_ERRORS, cdrFile.getName(), detailErrors.size(),
maxErrors);
LOGGER.error(error);
alertService.create(request.getCdrDetail().getCdrFile(), "Too many errors in CDR", error,
AlertType.HIGH, AlertStatus.NEW, 0, null);
returnedErrors.add(error);
}
returnedErrors.addAll(maxDetailErrors);
}
if (summaryErrors.size() > 0) {
List<String> maxSummaryErrors = summaryErrors.subList(0, min(maxErrors, summaryErrors.size()));
if (summaryErrors.size() > maxErrors) {
String error = String.format(DISPLAYING_THE_FIRST_N_ERRORS, csrFile.getName(), summaryErrors.size(),
maxErrors);
LOGGER.error(error);
alertService.create(request.getCdrSummary().getCdrFile(), "Too many errors in CSR", error,
AlertType.HIGH, AlertStatus.NEW, 0, null);
returnedErrors.add(error);
}
returnedErrors.addAll(maxSummaryErrors);
}
failure = StringUtils.join(returnedErrors, ",");
if (detailErrors.size() > 0) {
fileAuditRecordDataService.create(new FileAuditRecord(FileType.CDR_DETAIL_FILE,
request.getCdrDetail().getCdrFile(), false,
String.format("%d invalid CDR rows, see tomcat log", detailErrors.size()), null, null));
}
if (summaryErrors.size() > 0) {
fileAuditRecordDataService.create(new FileAuditRecord(FileType.CDR_SUMMARY_FILE,
request.getCdrSummary().getCdrFile(), false,
String.format("%d invalid CSR rows, see tomcat log", summaryErrors.size()), null, null));
}
}
LOGGER.info("Phase 2 - sendNotificationRequest");
sendNotificationRequest(new CdrFileProcessedNotification(status.getValue(), request.getFileName(), failure));
// Distribute Phase 3 & 4 & 5
// Delete old IMI CSR & IMI CDR & KK CSR
LOGGER.info("Phase 2 - Sending Phase 3 event");
sendPhaseEvent(CDR_PHASE_3, request);
// Save CDRs
LOGGER.info("Phase 2 - Sending Phase 4 event");
sendPhaseEvent(CDR_PHASE_4, request);
// Send CSRs for processing
LOGGER.info("Phase 2 - Sending Phase 5 event");
sendPhaseEvent(CDR_PHASE_5, request);
LOGGER.info("Phase 2 - End");
return returnedErrors;
}
// Phase 3: Deletes old IMI CSR & IMI CDR & KK CSR
@MotechListener(subjects = { CDR_PHASE_3 })
@Transactional
public void cdrProcessPhase3(MotechEvent event) {
Timer timer = new Timer();
LOGGER.info("Phase 3 - Start");
LOGGER.info("Phase 3 - cleanOldCallRecords");
cleanOldCallRecords();
LOGGER.info("Phase 3 - End {}", timer.time());
}
// Phase 4: Save CDRs for reporting
@MotechListener(subjects = { CDR_PHASE_4 })
@Transactional
public void cdrProcessPhase4(MotechEvent event) {
Timer timer = new Timer();
LOGGER.info("Phase 4 - Start");
CdrFileNotificationRequest request = requestFromParams(event.getParameters());
// Copy detail file, if needed
LOGGER.info("Phase 4 - copying CDR");
File cdrFile = new File(localCdrDir(), request.getCdrDetail().getCdrFile());
String cdrFileName = cdrFile.getName();
try {
copyFile(cdrFile);
} catch (ExecException e) {
String error = String.format("Error copying CDR file %s: %s", cdrFileName, e.getMessage());
LOGGER.error(error);
alertService.create(cdrFileName, COPY_ERROR, error, AlertType.CRITICAL, AlertStatus.NEW, 0, null);
return;
}
LOGGER.info("Phase 4 - saveDetailRecords");
saveDetailRecords(cdrFile);
LOGGER.info("Phase 4 - End {}", timer.time());
}
// Phase 5: Sends CSR rows for processing on any node
@MotechListener(subjects = { CDR_PHASE_5 })
@Transactional
public void cdrProcessPhase5(MotechEvent event) {
Timer timer = new Timer();
LOGGER.info("Phase 5 - Start");
CdrFileNotificationRequest request = requestFromParams(event.getParameters());
File csrFile = new File(localCdrDir(), request.getCdrSummary().getCdrFile());
String csrFileName = csrFile.getName();
// Copy summary file, if needed
LOGGER.info("Phase 5 - copying CSR");
try {
copyFile(csrFile);
} catch (ExecException e) {
String error = String.format("Error copying CDR file %s: %s", csrFileName, e.getMessage());
LOGGER.error(error);
alertService.create(csrFileName, COPY_ERROR, error, AlertType.CRITICAL, AlertStatus.NEW, 0, null);
return;
}
LOGGER.info("Phase 5 - processCsrs");
processCsrs(csrFile, request.getCdrSummary().getRecordsCount());
LOGGER.info("Phase 5 - End {}", timer.time());
}
@Override
@MotechListener(subjects = { CDR_CSR_CLEANUP_SUBJECT })
@Transactional
public void cleanOldCallRecords() {
LOGGER.info("cleanOldCallRecords() called");
int cdrDuration = MIN_CALL_DATA_RETENTION_DURATION_IN_DAYS;
try {
int durationFromConfig = Integer.parseInt(settingsFacade.getProperty(CDR_CSR_RETENTION_DURATION));
if (durationFromConfig < cdrDuration) {
LOGGER.debug(String.format("Discarding retention property from config since it is less than MIN: %d",
cdrDuration));
} else {
cdrDuration = durationFromConfig;
LOGGER.debug(String.format("Using retention property from config: %d", cdrDuration));
}
} catch (NumberFormatException ne) {
LOGGER.debug(String.format("Unable to get property from config: %s", CDR_CSR_RETENTION_DURATION));
}
LOGGER.debug(String.format(LOG_TEMPLATE, callDetailRecordDataService.count(), CDR_TABLE_NAME));
LOGGER.debug(String.format(LOG_TEMPLATE, callSummaryRecordDataService.count(), CSR_TABLE_NAME));
deleteRecords(cdrDuration, CDR_TABLE_NAME);
deleteRecords(cdrDuration, CSR_TABLE_NAME);
LOGGER.debug(String.format(LOG_TEMPLATE, callDetailRecordDataService.count(), CDR_TABLE_NAME));
LOGGER.debug(String.format(LOG_TEMPLATE, callSummaryRecordDataService.count(), CSR_TABLE_NAME));
callRetryService.deleteOldRetryRecords(cdrDuration);
}
/**
* Helper to clean out the CDR table with the given retention policy
* @param retentionInDays min days to keep CDR for
* @param tableName name of the cdr or csr table
*/
private void deleteRecords(final int retentionInDays, final String tableName) {
@SuppressWarnings("unchecked")
SqlQueryExecution<Long> queryExecution = new SqlQueryExecution<Long>() {
@Override
public String getSqlQuery() {
String query = String.format(
"DELETE FROM %s where creationDate < now() - INTERVAL %d DAY", tableName, retentionInDays);
LOGGER.debug("SQL QUERY: {}", query);
return query;
}
@Override
public Long execute(Query query) {
return (Long) query.execute();
}
};
// FYI: doesn't matter what data service we use since it is just used as a vehicle to execute the custom query
Long rowCount = callDetailRecordDataService.executeSQLQuery(queryExecution);
LOGGER.debug(String.format("Table %s cleaned up and deleted %d rows", tableName, rowCount));
// evict caches for the changes to be read again
if (tableName.equalsIgnoreCase(CDR_TABLE_NAME)) {
callDetailRecordDataService.evictEntityCache(false);
}
if (tableName.equalsIgnoreCase(CSR_TABLE_NAME)) {
callSummaryRecordDataService.evictEntityCache(false);
}
}
}
|
package com.hashnot.csv.sage.importTypes;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.hashnot.csv.sage.convert.LocalDateDeserializer;
import com.hashnot.csv.sage.convert.LocalDateSerializer;
import com.hashnot.csv.sage.convert.PlainStringBigDecimalSerializer;
import java.math.BigDecimal;
import java.time.LocalDate;
import static com.hashnot.csv.sage.CommonField.*;
@JsonPropertyOrder({H_STOCK_CODE, H_DATE, H_REFERENCE, H_ACTUAL})
public class StockTakeEntry {
@JsonProperty(value = H_STOCK_CODE, required = true)
private String stockCode;
@JsonProperty(value = H_DATE, required = true)
@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate date;
@JsonProperty(H_REFERENCE)
private String reference;
@JsonProperty(value = H_ACTUAL, required = true)
@JsonSerialize(using = PlainStringBigDecimalSerializer.class)
private BigDecimal actual;
public StockTakeEntry() {
}
public StockTakeEntry(String stockCode, LocalDate date, BigDecimal actual) {
this.stockCode = stockCode;
this.date = date;
this.actual = actual;
}
public StockTakeEntry(String stockCode, LocalDate date, String reference, BigDecimal actual) {
this.stockCode = stockCode;
this.date = date;
this.reference = reference;
this.actual = actual;
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public BigDecimal getActual() {
return actual;
}
public void setActual(BigDecimal actual) {
this.actual = actual;
}
}
|
package org.xtreemfs.foundation.pbrpc.server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.xtreemfs.foundation.LifeCycleThread;
import org.xtreemfs.foundation.SSLOptions;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.channels.ChannelIO;
import org.xtreemfs.foundation.pbrpc.channels.SSLChannelIO;
import org.xtreemfs.foundation.pbrpc.channels.SSLHandshakeOnlyChannelIO;
import org.xtreemfs.foundation.util.OutputUtils;
/**
*
* @author bjko
*/
public class RPCNIOSocketServer extends LifeCycleThread implements RPCServerInterface {
/**
* Maximum number of record fragments supported.
*/
public static final int MAX_FRAGMENTS = 1;
/**
* Maximum fragment size to accept. If the size is larger, the connection is
* closed.
*/
public static final int MAX_FRAGMENT_SIZE = 1024 * 1024 * 32;
/**
* the server socket
*/
private final ServerSocketChannel socket;
/**
* Selector for server socket
*/
private final Selector selector;
/**
* If set to true thei main loop will exit upon next invocation
*/
private volatile boolean quit;
/**
* The receiver that gets all incoming requests.
*/
private volatile RPCServerRequestListener receiver;
/**
* sslOptions if SSL is enabled, null otherwise
*/
private final SSLOptions sslOptions;
/**
* Connection count
*/
private final AtomicInteger numConnections;
/**
* Number of requests received but not answered
*/
private long pendingRequests;
/**
* Port on which the server listens for incoming connections.
*/
private final int bindPort;
private final List<RPCNIOSocketServerConnection> connections;
/**
* maximum number of pending client requests to allow
*/
private final int maxClientQLength;
/**
* if the Q was full we need at least CLIENT_Q_THR spaces before we start
* reading from the client again. This is to prevent it from oscillating
*/
private final int clientQThreshold;
public static final int DEFAULT_MAX_CLIENT_Q_LENGTH = 100;
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions) throws IOException {
this(bindPort, bindAddr, rl, sslOptions, -1);
}
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions, int receiveBufferSize) throws IOException {
this(bindPort, bindAddr, rl, sslOptions, receiveBufferSize, DEFAULT_MAX_CLIENT_Q_LENGTH);
}
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions, int receiveBufferSize,
int maxClientQLength) throws IOException {
super("PBRPCSrv@" + bindPort);
// open server socket
socket = ServerSocketChannel.open();
socket.configureBlocking(false);
if (receiveBufferSize != -1) {
socket.socket().setReceiveBufferSize(receiveBufferSize);
try {
if (socket.socket().getReceiveBufferSize() != receiveBufferSize) {
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"could not set socket receive buffer size to " + receiveBufferSize
+ ", using default size of " + socket.socket().getReceiveBufferSize());
}
} catch (SocketException exc) {
Logging.logMessage(Logging.LEVEL_WARN, this,
"could not check whether receive buffer size was successfully set to %d bytes", receiveBufferSize);
}
} else {
socket.socket().setReceiveBufferSize(256 * 1024);
}
socket.socket().setReuseAddress(true);
socket.socket().bind(
bindAddr == null ? new InetSocketAddress(bindPort) : new InetSocketAddress(bindAddr, bindPort));
this.bindPort = bindPort;
// create a selector and register socket
selector = Selector.open();
socket.register(selector, SelectionKey.OP_ACCEPT);
// server is ready to accept connections now
this.receiver = rl;
this.sslOptions = sslOptions;
this.numConnections = new AtomicInteger(0);
this.connections = new LinkedList<RPCNIOSocketServerConnection>();
this.maxClientQLength = maxClientQLength;
this.clientQThreshold = (maxClientQLength/2 >= 0) ? maxClientQLength/2 : 0;
if (maxClientQLength <= 1) {
Logging.logMessage(Logging.LEVEL_WARN, this, "max client queue length is 1, pipelining is disabled.");
}
}
/**
* Stop the server and close all connections.
*/
public void shutdown() {
this.quit = true;
this.interrupt();
}
/**
* sends a response.
*
* @param request
* the request
*/
public void sendResponse(RPCServerRequest request, RPCServerResponse response) {
assert (response != null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "response sent");
final RPCNIOSocketServerConnection connection = (RPCNIOSocketServerConnection)request.getConnection();
try {
request.freeBuffers();
} catch (AssertionError ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this, "Caught an AssertionError while trying to free buffers:");
Logging.logError(Logging.LEVEL_INFO, this, ex);
}
}
assert (connection.getServer() == this);
if (!connection.isConnectionClosed()) {
synchronized (connection) {
boolean isEmpty = connection.getPendingResponses().isEmpty();
connection.addPendingResponse(response);
if (isEmpty) {
final SelectionKey key = connection.getChannel().keyFor(selector);
if (key != null) {
try {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} catch (CancelledKeyException e) {
// Ignore it since the timeout mechanism will deal with it.
}
}
selector.wakeup();
}
}
} else {
// ignore and free bufers
response.freeBuffers();
}
}
public void run() {
notifyStarted();
if (Logging.isInfo()) {
String sslMode = "";
if (sslOptions != null) {
if (sslOptions.isFakeSSLMode()) {
sslMode = "GRID SSL mode enabled (SSL handshake only)";
} else {
sslMode = "SSL enabled";
}
}
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this, "PBRPC Srv %d ready %s", bindPort,sslMode);
}
try {
while (!quit) {
// try to select events...
int numKeys = 0;
try {
numKeys = selector.select();
} catch (CancelledKeyException ex) {
// who cares
} catch (IOException ex) {
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"Exception while selecting: %s", ex.toString());
continue;
}
if (numKeys > 0) {
// fetch events
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
// process all events
while (iter.hasNext()) {
SelectionKey key = iter.next();
// remove key from the list
iter.remove();
try {
if (key.isAcceptable()) {
acceptConnection(key);
}
if (key.isReadable()) {
readConnection(key);
}
if (key.isWritable()) {
writeConnection(key);
}
} catch (CancelledKeyException ex) {
// nobody cares...
continue;
}
}
}
}
for (RPCNIOSocketServerConnection con : connections) {
try {
con.getChannel().close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// close socket
selector.close();
socket.close();
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"PBRPC Server %d shutdown complete", bindPort);
notifyStopped();
} catch (Throwable thr) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this, "PBRPC Server %d CRASHED!", bindPort);
notifyCrashed(thr);
}
}
/**
* read data from a readable connection
*
* @param key
* a readable key
*/
private void readConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
try {
if (!channel.isShutdownInProgress()) {
if (channel.doHandshake(key)) {
while (true) {
if (con.getOpenRequests().get() > maxClientQLength) {
key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"client sent too many requests... not accepting new requests from %s, q=%d", con
.getChannel().socket().getRemoteSocketAddress().toString(), con.getOpenRequests().get());
return;
}
ByteBuffer buf = null;
switch (con.getReceiveState()) {
case RECORD_MARKER: {
buf = con.getReceiveRecordMarker(); break;
}
case RPC_MESSAGE: {
buf = con.getReceiveBuffers()[1].getBuffer(); break;
}
case RPC_HEADER: {
buf = con.getReceiveBuffers()[0].getBuffer(); break;
}
case DATA: {
buf = con.getReceiveBuffers()[2].getBuffer(); break;
}
}
// read fragment header
final int numBytesRead = readData(key, channel, buf);
if (numBytesRead == -1) {
// connection closed
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"client closed connection (EOF): %s", channel.socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
return;
}
if (buf.hasRemaining()) {
// not enough data...
break;
}
switch (con.getReceiveState()) {
case RECORD_MARKER: {
buf.position(0);
final int hdrLen = buf.getInt();
final int msgLen = buf.getInt();
final int dataLen = buf.getInt();
if ((hdrLen <= 0) || (hdrLen >= MAX_FRAGMENT_SIZE)
|| (msgLen < 0) || (msgLen >= MAX_FRAGMENT_SIZE)
|| (dataLen < 0) || (dataLen >= MAX_FRAGMENT_SIZE)) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this,
"invalid record marker size (%d/%d/%d) received, closing connection to client %s",
hdrLen,msgLen,dataLen,channel.socket()
.getRemoteSocketAddress().toString());
closeConnection(key);
return;
}
final ReusableBuffer[] buffers = new ReusableBuffer[]{BufferPool.allocate(hdrLen),
((msgLen > 0) ? BufferPool.allocate(msgLen) : null),
((dataLen > 0) ? BufferPool.allocate(dataLen) : null) };
con.setReceiveBuffers(buffers);
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_HEADER);
continue;
}
case RPC_HEADER: {
if (con.getReceiveBuffers()[1] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_MESSAGE);
continue;
} else {
if (con.getReceiveBuffers()[2] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
continue;
} else {
break;
}
}
}
case RPC_MESSAGE: {
if (con.getReceiveBuffers()[2] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
continue;
} else {
break;
}
}
}
//assemble ServerRequest
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RECORD_MARKER);
con.getReceiveRecordMarker().clear();
ReusableBuffer[] receiveBuffers = con.getReceiveBuffers();
receiveBuffers[0].flip();
if (receiveBuffers[1] != null)
receiveBuffers[1].flip();
if (receiveBuffers[2] != null)
receiveBuffers[2].flip();
con.setReceiveBuffers(null);
RPCServerRequest rq = null;
try {
rq = new RPCServerRequest(con, receiveBuffers[0], receiveBuffers[1], receiveBuffers[2]);
} catch (IOException ex) {
// close connection if the header cannot be parsed
Logging.logMessage(Logging.LEVEL_ERROR, Category.net,this,"invalid PBRPC header received: "+ex);
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
}
closeConnection(key);
BufferPool.free(receiveBuffers[1]);
BufferPool.free(receiveBuffers[2]);
return;
}
// request is
// complete... send to receiver
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, rq
.toString());
}
con.getOpenRequests().incrementAndGet();
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"request received");
pendingRequests++;
if (!receiveRequest(key, rq, con)) {
closeConnection(key);
return;
}
}
}
}
} catch (CancelledKeyException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (CancelledKeyException): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
closeConnection(key);
} catch (ClosedByInterruptException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils
.stackTraceToString(ex));
}
closeConnection(key);
}
}
/**
* write data to a writeable connection
*
* @param key
* the writable key
*/
private void writeConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
try {
if (!channel.isShutdownInProgress()) {
if (channel.doHandshake(key)) {
while (true) {
// final ByteBuffer fragmentHeader =
// con.getSendFragHdr();
ByteBuffer[] response = con.getSendBuffers();
if (response == null) {
synchronized (con) {
RPCServerResponse rq = con.getPendingResponses().peek();
if (rq == null) {
// no more responses, stop writing...
con.setSendBuffers(null);
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
break;
}
response = rq.packBuffers(con.getSendFragHdr());
con.setSendBuffers(response);
}
}
/*
* if (fragmentHeader.hasRemaining()) { final int
* numBytesWritten = writeData(key, channel,
* fragmentHeader); if (numBytesWritten == -1) {
* //connection closed closeConnection(key); return; }
* if (fragmentHeader.hasRemaining()) { //not enough
* data... break; } //finished sending... send fragment
* data now... } else {
*/
// send fragment data
assert(response != null);
final long numBytesWritten = channel.write(response);
if (numBytesWritten == -1) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket()
.getRemoteSocketAddress().toString());
}
// connection closed
closeConnection(key);
return;
}
if (response[response.length-1].hasRemaining()) {
// not enough data...
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
break;
}
// finished sending fragment
// clean up :-) request finished
pendingRequests
RPCServerResponse rq = con.getPendingResponses().poll();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"sent response for %s", rq.toString());
}
rq.freeBuffers();
con.setSendBuffers(null);
con.getSendFragHdr().clear();
int numRq = con.getOpenRequests().decrementAndGet();
if ((key.interestOps() & SelectionKey.OP_READ) == 0) {
if (numRq < clientQThreshold) {
// read from client again
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"client allowed to send data again: %s, q=%d", con.getChannel().socket()
.getRemoteSocketAddress().toString(), numRq);
}
}
continue;
}
}
}
} catch (CancelledKeyException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (CancelledKeyException): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
closeConnection(key);
} catch (ClosedByInterruptException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils
.stackTraceToString(ex));
}
closeConnection(key);
}
}
/**
* Reads data from the socket, ensures that SSL connection is ready
*
* @param key
* the SelectionKey
* @param channel
* the channel to read from
* @param buf
* the buffer to read to
* @return number of bytes read, -1 on EOF
* @throws java.io.IOException
*/
public static int readData(SelectionKey key, ChannelIO channel, ByteBuffer buf) throws IOException {
return channel.read(buf);
/*
* if (!channel.isShutdownInProgress()) { if (channel.doHandshake(key))
* { return channel.read(buf); } else { return 0; } } else { return 0; }
*/
}
public static int writeData(SelectionKey key, ChannelIO channel, ByteBuffer buf) throws IOException {
return channel.write(buf);
/*
* if (!channel.isShutdownInProgress()) { if (channel.doHandshake(key))
* { return channel.write(buf); } else { return 0; } } else { return 0;
* }
*/
}
/**
* close a connection
*
* @param key
* matching key
*/
private void closeConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
// remove the connection from the selector and close socket
try {
connections.remove(con);
con.setConnectionClosed(true);
key.cancel();
channel.close();
} catch (Exception ex) {
} finally {
// adjust connection count and make sure buffers are freed
numConnections.decrementAndGet();
con.freeBuffers();
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "closing connection to %s", channel
.socket().getRemoteSocketAddress().toString());
}
}
/**
* accept a new incomming connection
*
* @param key
* the acceptable key
*/
private void acceptConnection(SelectionKey key) {
SocketChannel client = null;
RPCNIOSocketServerConnection con = null;
ChannelIO channelIO = null;
// FIXME: Better exception handling!
try {
// accept that connection
client = socket.accept();
if (sslOptions == null) {
channelIO = new ChannelIO(client);
} else {
if (sslOptions.isFakeSSLMode()) {
channelIO = new SSLHandshakeOnlyChannelIO(client, sslOptions, false);
} else {
channelIO = new SSLChannelIO(client, sslOptions, false);
}
}
con = new RPCNIOSocketServerConnection(this,channelIO);
// and configure it to be non blocking
// IMPORTANT!
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, con);
client.socket().setTcpNoDelay(true);
numConnections.incrementAndGet();
this.connections.add(con);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connect from client at %s",
client.socket().getRemoteSocketAddress().toString());
}
} catch (ClosedChannelException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection during accept");
}
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
if (channelIO != null) {
try {
channelIO.close();
} catch (IOException ex2) {
}
}
} catch (IOException ex) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
if (channelIO != null) {
try {
channelIO.close();
} catch (IOException ex2) {
}
}
}
}
/**
*
* @param key
* @param request
* @param con
* @return true on success, false on error
*/
private boolean receiveRequest(SelectionKey key, RPCServerRequest request, RPCNIOSocketServerConnection con) {
try {
request.getHeader();
receiver.receiveRecord(request);
return true;
} catch (IllegalArgumentException ex) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net,this,"invalid PBRPC header received: "+ex);
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
}
return false;
//closeConnection(key);
}
}
public int getNumConnections() {
return this.numConnections.get();
}
public long getPendingRequests() {
return this.pendingRequests;
}
/**
* Updates the listener. Handle with care.
*
* @param rl
*/
public void updateRequestDispatcher(RPCServerRequestListener rl) {
this.receiver = rl;
}
}
|
package org.piwik.sdk;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.util.Log;
import org.piwik.sdk.tools.Checksum;
import org.piwik.sdk.tools.DeviceHelper;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Main tracking class
* This class is not Thread safe and should be externally synchronized or multiple instances used.
*/
public class Tracker implements Dispatchable<Integer> {
protected static final String LOGGER_TAG = Piwik.LOGGER_PREFIX + "Tracker";
// Piwik default parameter values
private static final String DEFAULT_UNKNOWN_VALUE = "unknown";
private static final String defaultTrueValue = "1";
private static final String defaultRecordValue = defaultTrueValue;
private static final String defaultAPIVersionValue = "1";
// Default dispatcher values
private static final int piwikDefaultSessionTimeout = 30 * 60;
private static final int piwikDefaultDispatchTimer = 120;
private static final int piwikHTTPRequestTimeout = 5;
private static final int piwikQueryDefaultCapacity = 14;
/**
* The ID of the website we're tracking a visit/action for.
*/
private final int mSiteId;
private final URL mApiUrl;
/**
* Defines the User ID for this request.
* User ID is any non empty unique string identifying the user (such as an email address or a username).
* To access this value, users must be logged-in in your system so you can
* fetch this user ID from your system, and pass it to Piwik.
* <p/>
* When specified, the User ID will be "enforced".
* This means that if there is no recent visit with this User ID, a new one will be created.
* If a visit is found in the last 30 minutes with your specified User ID,
* then the new action will be recorded to this existing visit.
*/
private String mUserId;
/**
* The unique visitor ID, must be a 16 characters hexadecimal string.
* Every unique visitor must be assigned a different ID and this ID must not change after it is assigned.
* If this value is not set Piwik will still track visits, but the unique visitors metric might be less accurate.
*/
private String mVisitorId;
/**
* 32 character authorization key used to authenticate the API request.
* Should be equals `token_auth` value of the Super User
* or a user with admin access to the website visits are being tracked for.
*/
private final String mAuthToken;
private final Piwik mPiwik;
private String lastEvent;
private boolean isDispatching = false;
private int dispatchInterval = piwikDefaultDispatchTimer;
private DispatchingHandler dispatchingHandler;
private String applicationDomain;
private static String mScreenResolution;
private static String userAgent;
private static String userLanguage;
private static String userCountry;
private long sessionTimeoutMillis;
private long sessionStartedMillis;
private final ArrayList<String> queue = new ArrayList<String>(20);
private final HashMap<String, String> queryParams = new HashMap<String, String>(piwikQueryDefaultCapacity);
private final HashMap<String, CustomVariables> customVariables = new HashMap<String, CustomVariables>(2);
private final Random randomObject = new Random(new Date().getTime());
protected Tracker(@NonNull final String url, int siteId, String authToken, @NonNull Piwik piwik) throws MalformedURLException {
if (url == null)
throw new MalformedURLException("You must provide the Piwik Tracker URL! e.g. http://piwik.website.org/piwik.php");
String checkUrl = url;
if (checkUrl.endsWith("piwik.php") || checkUrl.endsWith("piwik-proxy.php")) {
mApiUrl = new URL(checkUrl);
} else {
if (!checkUrl.endsWith("/")) {
checkUrl += "/";
}
mApiUrl = new URL(checkUrl + "piwik.php");
}
mSiteId = siteId;
setNewSession();
setSessionTimeout(piwikDefaultSessionTimeout);
mAuthToken = authToken;
mPiwik = piwik;
}
protected URL getAPIUrl() {
return mApiUrl;
}
protected int getSiteId() {
return mSiteId;
}
/**
* Processes all queued events in background thread
*
* @return true if there are any queued events and opt out is inactive
*/
public boolean dispatch() {
if (!mPiwik.isOptOut() && queue.size() > 0) {
ArrayList<String> events = new ArrayList<String>(queue);
queue.clear();
TrackerBulkURLProcessor worker =
new TrackerBulkURLProcessor(this, piwikHTTPRequestTimeout, mPiwik.isDryRun());
worker.processBulkURLs(mApiUrl, events, mAuthToken);
return true;
}
return false;
}
/**
* Does dispatch immediately if dispatchInterval == 0
* if dispatchInterval is greater than zero auto dispatching will be launched
*/
private void tryDispatch() {
if (dispatchInterval == 0) {
dispatch();
} else if (dispatchInterval > 0) {
ensureAutoDispatching();
}
}
/**
* Starts infinity loop of dispatching process
* Auto invoked when any Tracker.track* method is called and dispatchInterval > 0
*/
private void ensureAutoDispatching() {
if (dispatchingHandler == null) {
dispatchingHandler = new DispatchingHandler(this);
}
dispatchingHandler.start();
}
/**
* Auto invoked when negative interval passed in setDispatchInterval
* or Activity is paused
*/
private void stopAutoDispatching() {
if (dispatchingHandler != null) {
dispatchingHandler.stop();
}
}
/**
* Set the interval to 0 to dispatch events as soon as they are queued.
* If a negative value is used the dispatch timer will never run, a manual dispatch must be used.
*
* @param dispatchInterval in seconds
*/
public Tracker setDispatchInterval(int dispatchInterval) {
this.dispatchInterval = dispatchInterval;
if (dispatchInterval < 1) {
stopAutoDispatching();
}
return this;
}
public int getDispatchInterval() {
return dispatchInterval;
}
@Override
public long getDispatchIntervalMillis() {
if (dispatchInterval > 0) {
return dispatchInterval * 1000;
}
return -1;
}
@Override
public void dispatchingCompleted(Integer count) {
isDispatching = false;
Log.d(Tracker.LOGGER_TAG, String.format("dispatched %s url(s)", count));
}
@Override
public void dispatchingStarted() {
isDispatching = true;
}
@Override
public boolean isDispatching() {
return isDispatching;
}
/**
* You can set any additional Tracking API Parameters within the SDK.
* This includes for example the local time (parameters h, m and s).
* <pre>
* tracker.set(QueryParams.HOURS, "10");
* tracker.set(QueryParams.MINUTES, "45");
* tracker.set(QueryParams.SECONDS, "30");
* </pre>
*
* @param key query params name
* @param value value
* @return tracker instance
*/
public Tracker set(QueryParams key, String value) {
if (value != null && value.length() > 0) {
queryParams.put(key.toString(), value);
}
return this;
}
public Tracker set(QueryParams key, Integer value) {
if (value != null) {
set(key, Integer.toString(value));
}
return this;
}
/**
* Sets a User ID to this user (such as an email address or a username)
*
* @param userId this parameter can be set to any string.
* The string will be hashed, and used as "User ID".
*/
public Tracker setUserId(String userId) {
if (userId != null && userId.length() > 0) {
this.mUserId = userId;
}
return this;
}
public Tracker setUserId(long userId) {
return setUserId(Long.toString(userId));
}
public Tracker clearUserId() {
mUserId = null;
return this;
}
public Tracker setVisitorId(String visitorId) throws IllegalArgumentException {
if (confirmVisitorIdFormat(visitorId)) {
this.mVisitorId = visitorId;
}
return this;
}
private static final Pattern PATTERN_VISITOR_ID = Pattern.compile("^[0-9a-f]{16}$");
private boolean confirmVisitorIdFormat(String visitorId) throws IllegalArgumentException {
Matcher visitorIdMatcher = PATTERN_VISITOR_ID.matcher(visitorId);
if (visitorIdMatcher.matches()) {
return true;
}
throw new IllegalArgumentException("VisitorId: " + visitorId + " is not of valid format, " +
" the format must match the regular expression: " + PATTERN_VISITOR_ID.pattern());
}
public Tracker setApplicationDomain(String domain) {
applicationDomain = domain;
return this;
}
protected String getApplicationDomain() {
return applicationDomain != null ? applicationDomain : mPiwik.getApplicationDomain();
}
/**
* Sets the screen resolution of the browser which sends the request.
*
* @param width the screen width as an int value
* @param height the screen height as an int value
*/
public Tracker setResolution(final int width, final int height) {
return set(QueryParams.SCREEN_RESOLUTION, formatResolution(width, height));
}
private String formatResolution(final int width, final int height) {
return String.format("%sx%s", width, height);
}
public String getResolution() {
if (queryParams.containsKey(QueryParams.SCREEN_RESOLUTION.toString())) {
return queryParams.get(QueryParams.SCREEN_RESOLUTION.toString());
} else {
if (mScreenResolution == null) {
int[] resolution = DeviceHelper.getResolution(mPiwik.getContext());
if (resolution != null) {
mScreenResolution = formatResolution(resolution[0], resolution[1]);
} else {
mScreenResolution = DEFAULT_UNKNOWN_VALUE;
}
}
return mScreenResolution;
}
}
public Tracker setUserCustomVariable(int index, String name, String value) {
return setCustomVariable(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES, index, name, value);
}
/**
* Does exactly the same as setUserCustomVariable but use screen scope
* You can track up to 5 custom variables for each screen view.
*/
public Tracker setScreenCustomVariable(int index, String name, String value) {
return setCustomVariable(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, index, name, value);
}
/**
* Correspondents to action_name of Piwik Tracking API
*
* @param title string The title of the action being tracked. It is possible to use
* slashes / to set one or several categories for this action.
* For example, Help / Feedback will create the Action Feedback in the category Help.
*/
public Tracker setScreenTitle(String title) {
return set(QueryParams.ACTION_NAME, title);
}
/**
* Returns android system user agent
*
* @return well formatted user agent
*/
public String getUserAgent() {
if (userAgent == null) {
userAgent = System.getProperty("http.agent");
}
return userAgent;
}
/**
* Sets custom UserAgent
*
* @param userAgent your custom UserAgent String
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
/**
* Returns user language
*
* @return language
*/
public String getLanguage() {
if (userLanguage == null) {
userLanguage = Locale.getDefault().getLanguage();
}
return userLanguage;
}
/**
* Returns user country
*
* @return country
*/
public String getCountry() {
if (userCountry == null) {
userCountry = Locale.getDefault().getCountry();
}
return userCountry;
}
/**
* Session handling
*/
public void setNewSession() {
touchSession();
set(QueryParams.SESSION_START, defaultTrueValue);
}
private void touchSession() {
sessionStartedMillis = System.currentTimeMillis();
}
public void setSessionTimeout(int seconds) {
sessionTimeoutMillis = seconds * 1000;
}
protected void checkSessionTimeout() {
if (isExpired()) {
setNewSession();
}
}
protected boolean isExpired() {
return System.currentTimeMillis() - sessionStartedMillis > sessionTimeoutMillis;
}
public int getSessionTimeout() {
return (int) sessionTimeoutMillis / 1000;
}
/**
* Tracking methods
*
* @param path required tracking param, for example: "/user/settings/billing"
*/
public Tracker trackScreenView(String path) {
set(QueryParams.URL_PATH, path);
return doTrack();
}
/**
* @param path view path for example: "/user/settings/billing" or just empty string ""
* @param title string The title of the action being tracked. It is possible to use
* slashes / to set one or several categories for this action.
* For example, Help / Feedback will create the Action Feedback in the category Help.
*/
public Tracker trackScreenView(String path, String title) {
setScreenTitle(title);
return trackScreenView(path);
}
public Tracker trackEvent(String category, String action, String label, Integer value) {
if (category != null && action != null) {
set(QueryParams.EVENT_ACTION, action);
set(QueryParams.EVENT_CATEGORY, category);
set(QueryParams.EVENT_NAME, label);
set(QueryParams.EVENT_VALUE, value);
doTrack();
}
return this;
}
public Tracker trackEvent(String category, String action, String label) {
return trackEvent(category, action, label, null);
}
public Tracker trackEvent(String category, String action) {
return trackEvent(category, action, null, null);
}
/**
* By default, Goals in Piwik are defined as "matching" parts of the screen path or screen title.
* In this case a conversion is logged automatically. In some situations, you may want to trigger
* a conversion manually on other types of actions, for example:
* when a user submits a form
* when a user has stayed more than a given amount of time on the page
* when a user does some interaction in your Android application
*
* @param idGoal id of goal as defined in piwik goal settings
*/
public Tracker trackGoal(Integer idGoal) {
if (idGoal != null && idGoal > 0) {
set(QueryParams.GOAL_ID, idGoal);
return doTrack();
}
return this;
}
/**
* Tracking request will trigger a conversion for the goal of the website being tracked with this ID
*
* @param idGoal id of goal as defined in piwik goal settings
* @param revenue a monetary value that was generated as revenue by this goal conversion.
*/
public Tracker trackGoal(Integer idGoal, int revenue) {
set(QueryParams.REVENUE, revenue);
return trackGoal(idGoal);
}
public Tracker trackAppDownload() {
SharedPreferences prefs = mPiwik.getSharedPreferences();
try {
PackageInfo pkgInfo = mPiwik.getContext().getPackageManager().getPackageInfo(mPiwik.getContext().getPackageName(), 0);
String firedKey = "downloaded:" + pkgInfo.packageName + ":" + pkgInfo.versionCode;
if (!prefs.getBoolean(firedKey, false)) {
trackNewAppDownload(mPiwik.getContext(), ExtraIdentifier.INSTALLER_PACKAGENAME);
prefs.edit().putBoolean(firedKey, true).commit();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return this;
}
public enum ExtraIdentifier {
APK_CHECKSUM, INSTALLER_PACKAGENAME
}
public Tracker trackNewAppDownload(Context app, ExtraIdentifier extra) {
StringBuilder installIdentifier = new StringBuilder();
try {
String pkg = app.getPackageName();
installIdentifier.append("http://").append(pkg); // Identifies the app
PackageManager packMan = app.getPackageManager();
PackageInfo pkgInfo = packMan.getPackageInfo(pkg, 0);
installIdentifier.append(":").append(pkgInfo.versionCode);
String extraIdentifier = null;
if (extra == ExtraIdentifier.APK_CHECKSUM) {
ApplicationInfo appInfo = packMan.getApplicationInfo(pkg, 0);
if (appInfo.sourceDir != null) {
try {
extraIdentifier = Checksum.getMD5Checksum(new File(appInfo.sourceDir));
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (extra == ExtraIdentifier.INSTALLER_PACKAGENAME) {
String installer = packMan.getInstallerPackageName(pkg);
if (installer.length() < 200)
extraIdentifier = packMan.getInstallerPackageName(pkg);
}
installIdentifier.append("/").append(extraIdentifier == null ? DEFAULT_UNKNOWN_VALUE : extraIdentifier);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return this;
}
set(QueryParams.DOWNLOAD, installIdentifier.toString());
set(QueryParams.ACTION_NAME, "application/downloaded");
set(QueryParams.URL_PATH, "/application/downloaded");
return trackEvent("Application", "downloaded");
}
/**
* Tracking the impressions
*
* @param contentName The name of the content. For instance 'Ad Foo Bar'
* @param contentPiece The actual content. For instance the path to an image, video, audio, any text
* @param contentTarget (optional) The target of the content. For instance the URL of a landing page.
*/
public Tracker trackContentImpression(String contentName, String contentPiece, String contentTarget) {
if (contentName != null && contentName.length() > 0) {
set(QueryParams.CONTENT_NAME, contentName);
set(QueryParams.CONTENT_PIECE, contentPiece);
set(QueryParams.CONTENT_TARGET, contentTarget);
return doTrack();
}
return this;
}
/**
* Tracking the interactions
*
* @param interaction The name of the interaction with the content. For instance a 'click'
* @param contentName The name of the content. For instance 'Ad Foo Bar'
* @param contentPiece The actual content. For instance the path to an image, video, audio, any text
* @param contentTarget (optional) The target the content leading to when an interaction occurs. For instance the URL of a landing page.
*/
public Tracker trackContentInteraction(String interaction, String contentName, String contentPiece, String contentTarget) {
if (interaction != null && interaction.length() > 0) {
set(QueryParams.CONTENT_INTERACTION, interaction);
return trackContentImpression(contentName, contentPiece, contentTarget);
}
return this;
}
/**
* Caught exceptions are errors in your app for which you've defined exception handling code,
* such as the occasional timeout of a network connection during a request for data.
* <p/>
* This is just a different way to define an event.
* Keep in mind Piwik is not a crash tracker, use this sparingly.
* <p/>
* For this to be useful you should ensure that proguard does not remove all classnames and line numbers.
* Also note that if this is used across different app versions and obfuscation is used, the same exception might be mapped to different obfuscated names by proguard.
* This would mean the same exception (event) is tracked as different events by Piwik.
*
* @param ex exception instance
* @param description exception message
* @param isFatal true if it's fatal exception
*/
public void trackException(Throwable ex, String description, boolean isFatal) {
String className;
try {
StackTraceElement trace = ex.getStackTrace()[0];
className = trace.getClassName() + "/" + trace.getMethodName() + ":" + trace.getLineNumber();
} catch (Exception e) {
Log.w(Tracker.LOGGER_TAG, "Couldn't get stack info", e);
className = ex.getClass().getName();
}
String actionName = "exception/" + (isFatal ? "fatal/" : "") + (className + "/") + description;
set(QueryParams.ACTION_NAME, actionName);
trackEvent("Exception", className, description, isFatal ? 1 : 0);
}
/**
* Set up required params
*/
protected void beforeTracking() {
set(QueryParams.API_VERSION, defaultAPIVersionValue);
set(QueryParams.SEND_IMAGE, "0");
set(QueryParams.SITE_ID, mSiteId);
set(QueryParams.RECORD, defaultRecordValue);
set(QueryParams.RANDOM_NUMBER, randomObject.nextInt(100000));
set(QueryParams.SCREEN_RESOLUTION, getResolution());
set(QueryParams.URL_PATH, getParamURL());
set(QueryParams.USER_AGENT, getUserAgent());
set(QueryParams.LANGUAGE, getLanguage());
set(QueryParams.COUNTRY, getCountry());
set(QueryParams.VISITOR_ID, getVisitorId());
set(QueryParams.USER_ID, getUserId());
set(QueryParams.DATETIME_OF_REQUEST, getCurrentDatetime());
set(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES, getCustomVariables(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES).toString());
set(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES, getCustomVariables(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES).toString());
checkSessionTimeout();
touchSession();
}
/**
* Builds URL, adds event to queue, clean all params after url was added
*/
protected Tracker doTrack() {
beforeTracking();
String event = getQuery();
if (mPiwik.isOptOut()) {
lastEvent = event;
Log.d(Tracker.LOGGER_TAG, String.format("URL omitted due to opt out: %s", event));
} else {
Log.d(Tracker.LOGGER_TAG, String.format("URL added to the queue: %s", event));
queue.add(event);
tryDispatch();
}
afterTracking();
return this;
}
/**
* Clean up params
*/
protected void afterTracking() {
clearQueryParams();
clearAllCustomVariables();
}
/**
*
* HELPERS
*
*/
/**
* Gets all custom vars from screen or visit scope
*
* @param namespace `_cvar` or `cvar` stored in
* QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES and
* QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES
* @return CustomVariables HashMap
*/
private CustomVariables getCustomVariables(String namespace) {
if (namespace == null) {
return null;
}
CustomVariables vars = customVariables.get(namespace);
if (vars == null) {
vars = new CustomVariables();
customVariables.put(namespace, vars);
}
return vars;
}
private CustomVariables getCustomVariables(QueryParams namespace) {
if (namespace == null) {
return null;
}
return getCustomVariables(namespace.toString());
}
private void clearAllCustomVariables() {
getCustomVariables(QueryParams.SCREEN_SCOPE_CUSTOM_VARIABLES).clear();
getCustomVariables(QueryParams.VISIT_SCOPE_CUSTOM_VARIABLES).clear();
}
private Tracker setCustomVariable(QueryParams namespace, int index, String name, String value) {
getCustomVariables(namespace.toString()).put(index, name, value);
return this;
}
private void clearQueryParams() {
// To avoid useless shrinking and resizing of the Map
// the capacity is held the same when clear() is called.
queryParams.clear();
}
private String getCurrentDatetime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").format(new Date());
}
protected String getQuery() {
return TrackerBulkURLProcessor.urlEncodeUTF8(queryParams);
}
/**
* For testing purposes
*
* @return query of the event ?r=1&sideId=1..
*/
protected String getLastEvent() {
return lastEvent;
}
protected void clearLastEvent() {
lastEvent = null;
}
protected String getApplicationBaseURL() {
return String.format("http://%s", getApplicationDomain());
}
protected String getParamURL() {
String url = queryParams.get(QueryParams.URL_PATH.toString());
if (url == null) {
url = "/";
} else if (url.startsWith("http:
return url;
} else if (!url.startsWith("/")) {
url = "/" + url;
}
return getApplicationBaseURL() + url;
}
protected String getUserId() {
return mUserId;
}
protected String getVisitorId() {
if (mVisitorId == null)
mVisitorId = getRandomVisitorId();
return mVisitorId;
}
private String getRandomVisitorId() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
}
public SharedPreferences getSharedPreferences() {
return mPiwik.getSharedPreferences();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tracker tracker = (Tracker) o;
return mSiteId == tracker.mSiteId && mApiUrl.equals(tracker.mApiUrl);
}
@Override
public int hashCode() {
int result = mSiteId;
result = 31 * result + mApiUrl.hashCode();
return result;
}
}
|
package com.mapswithme.maps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mapswithme.country.DownloadActivity;
import com.mapswithme.maps.Ads.AdsManager;
import com.mapswithme.maps.Ads.MenuAd;
import com.mapswithme.maps.Framework.OnBalloonListener;
import com.mapswithme.maps.LocationButtonImageSetter.ButtonState;
import com.mapswithme.maps.MapStorage.Index;
import com.mapswithme.maps.api.ParsedMmwRequest;
import com.mapswithme.maps.background.WorkerService;
import com.mapswithme.maps.bookmarks.BookmarkActivity;
import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity;
import com.mapswithme.maps.bookmarks.data.Bookmark;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;
import com.mapswithme.maps.bookmarks.data.MapObject;
import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint;
import com.mapswithme.maps.bookmarks.data.ParcelablePoint;
import com.mapswithme.maps.location.LocationService;
import com.mapswithme.maps.search.SearchController;
import com.mapswithme.maps.settings.SettingsActivity;
import com.mapswithme.maps.settings.StoragePathManager;
import com.mapswithme.maps.settings.StoragePathManager.SetStoragePathListener;
import com.mapswithme.maps.settings.UnitLocale;
import com.mapswithme.maps.widget.MapInfoView;
import com.mapswithme.maps.widget.MapInfoView.OnVisibilityChangedListener;
import com.mapswithme.maps.widget.MapInfoView.State;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.Constants;
import com.mapswithme.util.LocationUtils;
import com.mapswithme.util.ShareAction;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.Yota;
import com.mapswithme.util.statistics.Statistics;
import com.nvidia.devtech.NvEventQueueActivity;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
public class MWMActivity extends NvEventQueueActivity
implements LocationService.LocationListener,
OnBalloonListener,
OnVisibilityChangedListener, OnClickListener
{
public static final String EXTRA_TASK = "map_task";
private final static String TAG = "MWMActivity";
private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed";
private final static String EXTRA_SCREENSHOTS_TASK = "screenshots_task";
private final static String SCREENSHOTS_TASK_LOCATE = "locate_task";
private final static String SCREENSHOTS_TASK_PPP = "show_place_page";
private final static String EXTRA_LAT = "lat";
private final static String EXTRA_LON = "lon";
private final static String EXTRA_COUNTRY_INDEX = "country_index";
// Need it for search
private static final String EXTRA_SEARCH_RES_SINGLE = "search_res_index";
// Map tasks that we run AFTER rendering initialized
private final Stack<MapTask> mTasks = new Stack<>();
private BroadcastReceiver mExternalStorageReceiver = null;
private StoragePathManager mPathManager = new StoragePathManager();
private AlertDialog mStorageDisconnectedDialog = null;
private ImageButton mLocationButton;
// Info box (place page).
private MapInfoView mInfoView;
private SearchController mSearchController;
private boolean mNeedCheckUpdate = true;
private boolean mRenderingInitialized = false;
private int mCompassStatusListenerID = -1;
// Initialized to invalid combination to force update on the first check
private boolean mStorageAvailable = false;
private boolean mStorageWritable = true;
private ViewGroup mVerticalToolbar;
private ViewGroup mToolbar;
private static final String IS_KML_MOVED = "KmlBeenMoved";
private static final String IS_KITKAT_MIGRATION_COMPLETED = "KitKatMigrationCompleted";
// ads in vertical toolbar
private BroadcastReceiver mUpdateAdsReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
updateToolbarAds();
}
};
private boolean mAreToolbarAdsUpdated;
public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload)
{
return new Intent(context, DownloadResourcesActivity.class)
.putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index)
.putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_CONTRY, doAutoDownload);
}
public static void startWithSearchResult(Context context, boolean single)
{
final Intent mapIntent = new Intent(context, MWMActivity.class);
mapIntent.putExtra(EXTRA_SEARCH_RES_SINGLE, single);
context.startActivity(mapIntent);
// Next we need to handle intent
}
private native void deactivatePopup();
private void startLocation()
{
MWMApplication.get().getLocationState().onStartLocation();
resumeLocation();
}
private void stopLocation()
{
MWMApplication.get().getLocationState().onStopLocation();
pauseLocation();
}
private void pauseLocation()
{
MWMApplication.get().getLocationService().stopUpdate(this);
// Enable automatic turning screen off while app is idle
Utils.automaticIdleScreen(true, getWindow());
}
private void resumeLocation()
{
MWMApplication.get().getLocationService().startUpdate(this);
// Do not turn off the screen while displaying position
Utils.automaticIdleScreen(false, getWindow());
}
public void checkShouldResumeLocationService()
{
final LocationState state = MWMApplication.get().getLocationState();
final boolean hasPosition = state.hasPosition();
final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW);
if (hasPosition || state.isFirstPosition())
{
if (hasPosition && isFollowMode)
{
state.startCompassFollowing();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
}
else
{
LocationButtonImageSetter.setButtonViewFromState(
hasPosition
? ButtonState.HAS_LOCATION
: ButtonState.WAITING_LOCATION, mLocationButton
);
}
resumeLocation();
}
else
{
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
}
public void OnDownloadCountryClicked()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
nativeDownloadCountry();
}
});
}
private void checkUserMarkActivation()
{
final Intent intent = getIntent();
if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK))
{
final String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK);
if (value.equals(SCREENSHOTS_TASK_PPP))
{
final double lat = Double.parseDouble(intent.getStringExtra(EXTRA_LAT));
final double lon = Double.parseDouble(intent.getStringExtra(EXTRA_LON));
mToolbar.getHandler().postDelayed(new Runnable()
{
@Override
public void run()
{
Framework.nativeActivateUserMark(lat, lon);
}
}, 1000);
}
}
}
@Override
public void OnRenderingInitialized()
{
mRenderingInitialized = true;
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Run all checks in main thread after rendering is initialized.
checkMeasurementSystem();
checkUpdateMaps();
checkKitkatMigrationMove();
checkLiteMapsInPro();
checkFacebookDialog();
checkBuyProDialog();
checkUserMarkActivation();
}
});
runTasks();
}
private void runTasks()
{
// Task are not UI-thread bounded,
// if any task need UI-thread it should implicitly
// use Activity.runOnUiThread().
while (!mTasks.isEmpty())
mTasks.pop().run(this);
}
private Activity getActivity() { return this; }
@Override
public void ReportUnsupported()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.unsupported_phone))
.setCancelable(false)
.setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
getActivity().moveTaskToBack(true);
dlg.dismiss();
}
})
.create()
.show();
}
});
}
private void checkMeasurementSystem()
{
UnitLocale.initializeCurrentUnits();
}
private native void nativeScale(double k);
public void onPlusClicked(View v)
{
nativeScale(3.0 / 2);
}
public void onMinusClicked(View v)
{
nativeScale(2.0 / 3);
}
public void onBookmarksClicked(View v)
{
if (!MWMApplication.get().hasBookmarks())
showProVersionBanner(getString(R.string.bookmarks_in_pro_version));
else
startActivity(new Intent(this, BookmarkCategoriesActivity.class));
}
public void onMyPositionClicked(View v)
{
final LocationState state = MWMApplication.get().getLocationState();
if (state.hasPosition())
{
if (state.isCentered())
{
if (MWMApplication.get().isProVersion() && state.hasCompass())
{
final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW);
if (isFollowMode)
{
state.stopCompassFollowingAndRotateMap();
}
else
{
state.startCompassFollowing();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
return;
}
}
}
else
{
state.animateToPositionAndEnqueueLocationProcessMode(LocationState.LOCATION_CENTER_ONLY);
mLocationButton.setSelected(true);
return;
}
}
else
{
if (!state.isFirstPosition())
{
LocationButtonImageSetter.setButtonViewFromState(ButtonState.WAITING_LOCATION, mLocationButton);
startLocation();
return;
}
}
// Stop location observing first ...
stopLocation();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
private void ShowAlertDlg(int tittleID)
{
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(tittleID)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); }
})
.create()
.show();
}
private void checkKitkatMigrationMove()
{
final boolean kmlMoved = MWMApplication.get().nativeGetBoolean(IS_KML_MOVED, false);
final boolean mapsCpy = MWMApplication.get().nativeGetBoolean(IS_KITKAT_MIGRATION_COMPLETED, false);
if (!kmlMoved)
if (mPathManager.moveBookmarks())
MWMApplication.get().nativeSetBoolean(IS_KML_MOVED, true);
else
{
ShowAlertDlg(R.string.bookmark_move_fail);
return;
}
if (!mapsCpy)
mPathManager.checkWritableDir(this,
new SetStoragePathListener()
{
@Override
public void moveFilesFinished(String newPath)
{
MWMApplication.get().nativeSetBoolean(IS_KITKAT_MIGRATION_COMPLETED, true);
ShowAlertDlg(R.string.kitkat_migrate_ok);
}
@Override
public void moveFilesFailed()
{
ShowAlertDlg(R.string.kitkat_migrate_failed);
}
}
);
}
/**
* Checks if PRO version is running on KITKAT or greater sdk.
* If so - checks whether LITE version is installed and contains maps on sd card and then copies them to own directory on sdcard.
*/
private void checkLiteMapsInPro()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
MWMApplication.get().isProVersion() &&
(Utils.isAppInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isAppInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE)))
{
if (!mPathManager.containsLiteMapsOnSdcard())
return;
mPathManager.moveMapsLiteToPro(this,
new SetStoragePathListener()
{
@Override
public void moveFilesFinished(String newPath)
{
ShowAlertDlg(R.string.move_lite_maps_to_pro_ok);
}
@Override
public void moveFilesFailed()
{
ShowAlertDlg(R.string.move_lite_maps_to_pro_failed);
}
}
);
}
}
private void checkUpdateMaps()
{
// do it only once
if (mNeedCheckUpdate)
{
mNeedCheckUpdate = false;
MWMApplication.get().getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor()
{
@Override
public void doUpdate()
{
runDownloadActivity();
}
@Override
public void doCancel()
{
}
});
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
alignControls();
}
private void showDialogImpl(final int dlgID, int resMsg, DialogInterface.OnClickListener okListener)
{
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(getString(resMsg))
.setPositiveButton(getString(R.string.ok), okListener)
.setNeutralButton(getString(R.string.never), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
MWMApplication.get().submitDialogResult(dlgID, MWMApplication.NEVER);
}
})
.setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
MWMApplication.get().submitDialogResult(dlgID, MWMApplication.LATER);
}
})
.create()
.show();
}
private boolean isChinaISO(String iso)
{
final String arr[] = {"CN", "CHN", "HK", "HKG", "MO", "MAC"};
for (final String s : arr)
if (iso.equalsIgnoreCase(s))
return true;
return false;
}
private boolean isChinaRegion()
{
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA)
{
final String iso = tm.getNetworkCountryIso();
Log.i(TAG, "TelephonyManager country ISO = " + iso);
if (isChinaISO(iso))
return true;
}
else
{
final Location l = MWMApplication.get().getLocationService().getLastKnown();
if (l != null && nativeIsInChina(l.getLatitude(), l.getLongitude()))
return true;
else
{
final String code = Locale.getDefault().getCountry();
Log.i(TAG, "Locale country ISO = " + code);
if (isChinaISO(code))
return true;
}
}
return false;
}
private void checkFacebookDialog()
{
if (ConnectionState.isConnected(this) &&
MWMApplication.get().shouldShowDialog(MWMApplication.FACEBOOK) &&
!isChinaRegion())
{
showDialogImpl(MWMApplication.FACEBOOK, R.string.share_on_facebook_text,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
MWMApplication.get().submitDialogResult(MWMApplication.FACEBOOK, MWMApplication.OK);
dlg.dismiss();
UiUtils.showFacebookPage(MWMActivity.this);
}
}
);
}
}
private void showProVersionBanner(final String message)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
UiUtils.showBuyProDialog(MWMActivity.this, message);
}
});
}
private void checkBuyProDialog()
{
if (!MWMApplication.get().isProVersion() &&
(ConnectionState.isConnected(this)) &&
MWMApplication.get().shouldShowDialog(MWMApplication.BUYPRO))
{
showDialogImpl(MWMApplication.BUYPRO, R.string.pro_version_available,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
MWMApplication.get().submitDialogResult(MWMApplication.BUYPRO, MWMApplication.OK);
dlg.dismiss();
UiUtils.runProMarketActivity(MWMActivity.this);
}
}
);
}
}
private void runSearchActivity()
{
startActivity(new Intent(this, SearchActivity.class));
}
public void onSearchClicked(View v)
{
if (!MWMApplication.get().isProVersion())
{
showProVersionBanner(getString(R.string.search_available_in_pro_version));
}
else if (!MWMApplication.get().getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor()
{
@Override
public void doUpdate()
{
runDownloadActivity();
}
@Override
public void doCancel()
{
runSearchActivity();
}
}))
{
runSearchActivity();
}
}
@Override
public boolean onSearchRequested()
{
onSearchClicked(null);
return false;
}
public void onMoreClicked(View v)
{
UiUtils.show(mVerticalToolbar);
UiUtils.hide(mToolbar);
}
private void shareMyLocation()
{
final Location loc = MWMApplication.get().getLocationService().getLastKnown();
if (loc != null)
{
final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), "");
final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), "");
final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl);
// we use shortest message we can have here
ShareAction.getAnyShare().shareWithText(getActivity(), body, "");
}
else
{
new AlertDialog.Builder(MWMActivity.this)
.setMessage(R.string.unknown_current_position)
.setCancelable(true)
.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create()
.show();
}
}
private void runDownloadActivity()
{
startActivity(new Intent(this, DownloadActivity.class));
}
@Override
public void onCreate(Bundle savedInstanceState)
{
// Use full-screen on Kindle Fire only
if (Utils.isAmazonDevice())
{
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
setContentView(R.layout.map);
super.onCreate(savedInstanceState);
// Log app start events - successful installation means that user has passed DownloadResourcesActivity
MWMApplication.get().onMwmStart(this);
// Do not turn off the screen while benchmarking
if (MWMApplication.get().nativeIsBenchmarking())
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
nativeConnectDownloadButton();
// Set up view
mLocationButton = (ImageButton) findViewById(R.id.map_button_myposition);
yotaSetup();
setUpInfoBox();
Framework.nativeConnectBalloonListeners(this);
final Intent intent = getIntent();
// We need check for tasks both in onCreate and onNewIntent
addTask(intent);
// Initialize location service
MWMApplication.get().getLocationService();
mSearchController = SearchController.getInstance();
mSearchController.onCreate(this);
setUpToolbars();
if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK))
{
String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK);
if (value.equals(SCREENSHOTS_TASK_LOCATE))
onMyPositionClicked(null);
}
updateToolbarAds();
LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateAdsReceiver, new IntentFilter(WorkerService.ACTION_UPDATE_MENU_ADS));
}
private void updateToolbarAds()
{
final List<MenuAd> ads = AdsManager.getMenuAds();
if (ads != null && !mAreToolbarAdsUpdated)
{
mAreToolbarAdsUpdated = true;
int startAdMenuPosition = 7;
for (final MenuAd ad : ads)
{
final View view = getLayoutInflater().inflate(R.layout.item_bottom_toolbar, mVerticalToolbar, false);
final TextView textView = (TextView) view.findViewById(R.id.tv__bottom_item_text);
textView.setText(ad.getTitle());
try
{
textView.setTextColor(Color.parseColor(ad.getHexColor()));
} catch (IllegalArgumentException e)
{
e.printStackTrace();
}
final ImageView imageView = (ImageView) view.findViewById(R.id.iv__bottom_icon);
imageView.setImageBitmap(ad.getIcon());
view.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final Intent it = new Intent(Intent.ACTION_VIEW);
it.setData(Uri.parse(ad.getAppUrl()));
startActivity(it);
}
});
mVerticalToolbar.addView(view, startAdMenuPosition++);
}
}
}
private void setUpToolbars()
{
mToolbar = (ViewGroup) findViewById(R.id.map_bottom_toolbar);
mVerticalToolbar = (ViewGroup) findViewById(R.id.map_bottom_vertical_toolbar);
mVerticalToolbar.findViewById(R.id.btn_buy_pro).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_download_maps).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_share).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_settings).setOnClickListener(this);
View moreApps = mVerticalToolbar.findViewById(R.id.btn_more_apps);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || Framework.getGuideIds().length == 0)
{
UiUtils.hide(moreApps);
}
else
{
moreApps.setOnClickListener(this);
}
UiUtils.hide(mVerticalToolbar);
}
private void setUpInfoBox()
{
mInfoView = (MapInfoView) findViewById(R.id.info_box);
mInfoView.setOnVisibilityChangedListener(this);
mInfoView.bringToFront();
}
private void yotaSetup()
{
final View yopmeButton = findViewById(R.id.yop_it);
if (!Yota.isYota())
{
yopmeButton.setVisibility(View.INVISIBLE);
}
else
{
yopmeButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final double[] latLon = Framework.getScreenRectCenter();
final double zoom = Framework.getDrawScale();
final LocationState locState = MWMApplication.get().getLocationState();
if (locState.hasPosition() && locState.isCentered())
Yota.showLocation(getApplicationContext(), zoom);
else
Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locState.hasPosition());
Statistics.INSTANCE.trackBackscreenCall(getApplication(), "Map");
}
});
}
}
@Override
public void onDestroy()
{
Framework.nativeClearBalloonListeners();
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
if (intent != null)
{
if (intent.hasExtra(EXTRA_TASK))
addTask(intent);
else if (intent.hasExtra(EXTRA_SEARCH_RES_SINGLE))
{
final boolean singleResult = intent.getBooleanExtra(EXTRA_SEARCH_RES_SINGLE, false);
if (singleResult)
{
MapObject.SearchResult result = new MapObject.SearchResult(0);
onAdditionalLayerActivated(result.getName(), result.getPoiTypeName(), result.getLat(), result.getLon());
}
else
onDismiss();
}
}
}
private void addTask(Intent intent)
{
if (intent != null
&& !intent.getBooleanExtra(EXTRA_CONSUMED, false)
&& intent.hasExtra(EXTRA_TASK)
&& ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0))
{
final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK);
mTasks.add(mapTask);
intent.removeExtra(EXTRA_TASK);
if (mRenderingInitialized)
runTasks();
// mark intent as consumed
intent.putExtra(EXTRA_CONSUMED, true);
}
}
@Override
protected void onStop()
{
super.onStop();
mRenderingInitialized = false;
}
private void alignControls()
{
final View zoomPlusButton = findViewById(R.id.map_button_plus);
final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) zoomPlusButton.getLayoutParams();
final int margin = (int) getResources().getDimension(R.dimen.zoom_margin);
final int marginTop = (int) getResources().getDimension(R.dimen.zoom_plus_top_margin);
lp.setMargins(margin, marginTop, margin, margin);
}
/// @name From Location interface
@Override
public void onLocationError(int errorCode)
{
nativeOnLocationError(errorCode);
// Notify user about turned off location services
if (errorCode == LocationService.ERROR_DENIED)
{
MWMApplication.get().getLocationState().turnOff();
// Do not show this dialog on Kindle Fire - it doesn't have location services
// and even wifi settings can't be opened programmatically
if (!Utils.isAmazonDevice())
{
new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text)
.setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
try
{
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} catch (final Exception e1)
{
// On older Android devices location settings are merged with security
try
{
startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS));
} catch (final Exception e2)
{
Log.w(TAG, "Can't run activity" + e2);
}
}
dialog.dismiss();
}
})
.setNegativeButton(R.string.close, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create()
.show();
}
}
else if (errorCode == LocationService.ERROR_GPS_OFF)
{
Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationUpdated(final Location l)
{
if (MWMApplication.get().getLocationState().isFirstPosition())
LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton);
nativeLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy(), l.getAltitude(), l.getSpeed(), l.getBearing());
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateDistanceAndAzimut(l);
}
@SuppressWarnings("deprecation")
@Override
public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy)
{
final double angles[] = {magneticNorth, trueNorth};
LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), angles);
nativeCompassUpdated(time, angles[0], angles[1], accuracy);
final double north = (angles[1] >= 0.0 ? angles[1] : angles[0]);
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateAzimuth(north);
}
@Override
public void onDrivingHeadingUpdated(long time, double heading, double accuracy)
{
LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), new double[]{heading});
nativeCompassUpdated(time, heading, heading, accuracy);
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateAzimuth(heading);
}
public void onCompassStatusChanged(int newStatus)
{
if (newStatus == 1)
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
else if (MWMApplication.get().getLocationState().hasPosition())
LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton);
else
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
/// Callback from native compass GUI element processing.
public void OnCompassStatusChanged(int newStatus)
{
final int val = newStatus;
runOnUiThread(new Runnable()
{
@Override
public void run()
{
onCompassStatusChanged(val);
}
});
}
private void startWatchingCompassStatusUpdate()
{
mCompassStatusListenerID = MWMApplication.get().getLocationState().addCompassStatusListener(this);
}
private void stopWatchingCompassStatusUpdate()
{
MWMApplication.get().getLocationState().removeCompassStatusListener(mCompassStatusListenerID);
}
@Override
protected void onPause()
{
pauseLocation();
stopWatchingExternalStorage();
stopWatchingCompassStatusUpdate();
super.onPause();
}
@Override
protected void onResume()
{
super.onResume();
checkShouldResumeLocationService();
startWatchingCompassStatusUpdate();
startWatchingExternalStorage();
UiUtils.showIf(MWMApplication.get().nativeGetBoolean(SettingsActivity.ZOOM_BUTTON_ENABLED, true),
findViewById(R.id.map_button_plus),
findViewById(R.id.map_button_minus));
alignControls();
mSearchController.onResume();
mInfoView.onResume();
MWMApplication.get().onMwmResume(this);
}
private void updateExternalStorageState()
{
boolean available = false, writable = false;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
available = writable = true;
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
available = true;
if (mStorageAvailable != available || mStorageWritable != writable)
{
mStorageAvailable = available;
mStorageWritable = writable;
handleExternalStorageState(available, writable);
}
}
private void handleExternalStorageState(boolean available, boolean writeable)
{
if (available && writeable)
{
// Add local maps to the model
nativeStorageConnected();
// @TODO enable downloader button and dismiss blocking popup
if (mStorageDisconnectedDialog != null)
mStorageDisconnectedDialog.dismiss();
}
else if (available)
{
// Add local maps to the model
nativeStorageConnected();
// @TODO disable downloader button and dismiss blocking popup
if (mStorageDisconnectedDialog != null)
mStorageDisconnectedDialog.dismiss();
}
else
{
// Remove local maps from the model
nativeStorageDisconnected();
// @TODO enable downloader button and show blocking popup
if (mStorageDisconnectedDialog == null)
{
mStorageDisconnectedDialog = new AlertDialog.Builder(this)
.setTitle(R.string.external_storage_is_not_available)
.setMessage(getString(R.string.disconnect_usb_cable))
.setCancelable(false)
.create();
}
mStorageDisconnectedDialog.show();
}
}
private void startWatchingExternalStorage()
{
mExternalStorageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
updateExternalStorageState();
}
};
registerReceiver(mExternalStorageReceiver, StoragePathManager.getMediaChangesIntentFilter());
updateExternalStorageState();
}
private void stopWatchingExternalStorage()
{
mPathManager.stopExternalStorageWatching();
if (mExternalStorageReceiver != null)
{
unregisterReceiver(mExternalStorageReceiver);
mExternalStorageReceiver = null;
}
}
@Override
public void onBackPressed()
{
if (mInfoView.getState() != State.HIDDEN)
{
hideInfoView();
deactivatePopup();
}
else if (mVerticalToolbar.getVisibility() == View.VISIBLE)
{
UiUtils.show(mToolbar);
UiUtils.hide(mVerticalToolbar);
}
else
super.onBackPressed();
}
/// Callbacks from native map objects touch event.
@Override
public void onApiPointActivated(final double lat, final double lon, final String name, final String id)
{
if (ParsedMmwRequest.hasRequest())
{
final ParsedMmwRequest request = ParsedMmwRequest.getCurrentRequest();
request.setPointData(lat, lon, name, id);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final String poiType = ParsedMmwRequest.getCurrentRequest().getCallerName(MWMApplication.get()).toString();
final ApiPoint apiPoint = new ApiPoint(name, id, poiType, lat, lon);
if (!mInfoView.hasMapObject(apiPoint))
{
mInfoView.setMapObject(apiPoint);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
}
@Override
public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon)
{
final MapObject poi = new MapObject.Poi(name, lat, lon, type);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (!mInfoView.hasMapObject(poi))
{
mInfoView.setMapObject(poi);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onBookmarkActivated(final int category, final int bookmarkIndex)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final Bookmark b = BookmarkManager.getBookmarkManager().getBookmark(category, bookmarkIndex);
if (!mInfoView.hasMapObject(b))
{
mInfoView.setMapObject(b);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onMyPositionActivated(final double lat, final double lon)
{
final MapObject mypos = new MapObject.MyPosition(getString(R.string.my_position), lat, lon);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (!mInfoView.hasMapObject(mypos))
{
mInfoView.setMapObject(mypos);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final MapObject sr = new MapObject.SearchResult(name, type, lat, lon);
if (!mInfoView.hasMapObject(sr))
{
mInfoView.setMapObject(sr);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
private void hideInfoView()
{
mInfoView.setState(State.HIDDEN);
mInfoView.setMapObject(null);
UiUtils.show(findViewById(R.id.map_bottom_toolbar));
}
@Override
public void onDismiss()
{
if (!mInfoView.hasMapObject(null))
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
hideInfoView();
deactivatePopup();
}
});
}
}
private native void nativeStorageConnected();
private native void nativeStorageDisconnected();
private native void nativeConnectDownloadButton();
private native void nativeDownloadCountry();
private native void nativeOnLocationError(int errorCode);
private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy, double altitude, float speed, float bearing);
private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy);
private native boolean nativeIsInChina(double lat, double lon);
public native boolean showMapForUrl(String url);
@Override
public void onPreviewVisibilityChanged(boolean isVisible)
{
UiUtils.hide(mVerticalToolbar);
}
@Override
public void onPlacePageVisibilityChanged(boolean isVisible)
{
UiUtils.hide(mVerticalToolbar);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_buy_pro:
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
UiUtils.runProMarketActivity(MWMActivity.this);
break;
case R.id.btn_share:
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
shareMyLocation();
break;
case R.id.btn_settings:
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.btn_download_maps:
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
runDownloadActivity();
break;
case R.id.btn_more_apps:
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
startActivity(new Intent(this, MoreAppsActivity.class));
break;
default:
break;
}
}
@Override
public boolean onTouch(View view, MotionEvent event)
{
UiUtils.hide(mVerticalToolbar);
UiUtils.show(mToolbar);
if (mInfoView.getState() == State.FULL_PLACEPAGE)
{
deactivatePopup();
hideInfoView();
return true;
}
return super.onTouch(view, event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BookmarkActivity.REQUEST_CODE_EDIT_BOOKMARK && resultCode == RESULT_OK)
{
final Point bmk = ((ParcelablePoint) data.getParcelableExtra(BookmarkActivity.PIN)).getPoint();
onBookmarkActivated(bmk.x, bmk.y);
}
super.onActivityResult(requestCode, resultCode, data);
}
public interface MapTask extends Serializable
{
public boolean run(MWMActivity target);
}
public static class OpenUrlTask implements MapTask
{
private static final long serialVersionUID = 1L;
private final String mUrl;
public OpenUrlTask(String url)
{
Utils.checkNotNull(url);
mUrl = url;
}
@Override
public boolean run(MWMActivity target)
{
return target.showMapForUrl(mUrl);
}
}
public static class ShowCountryTask implements MapTask
{
private static final long serialVersionUID = 1L;
private final Index mIndex;
private final boolean mDoAutoDownload;
public ShowCountryTask(Index index, boolean doAutoDownload)
{
mIndex = index;
mDoAutoDownload = doAutoDownload;
}
@Override
public boolean run(MWMActivity target)
{
final MapStorage storage = MWMApplication.get().getMapStorage();
if (mDoAutoDownload)
{
storage.downloadCountry(mIndex);
// set zoom level so that download process is visible
Framework.nativeShowCountry(mIndex, true);
}
else
Framework.nativeShowCountry(mIndex, false);
return true;
}
}
}
|
package com.mapswithme.maps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mapswithme.country.DownloadActivity;
import com.mapswithme.maps.Ads.AdsManager;
import com.mapswithme.maps.Ads.MenuAd;
import com.mapswithme.maps.Framework.OnBalloonListener;
import com.mapswithme.maps.LocationButtonImageSetter.ButtonState;
import com.mapswithme.maps.MapStorage.Index;
import com.mapswithme.maps.api.ParsedMmwRequest;
import com.mapswithme.maps.background.WorkerService;
import com.mapswithme.maps.bookmarks.BookmarkActivity;
import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity;
import com.mapswithme.maps.bookmarks.data.Bookmark;
import com.mapswithme.maps.bookmarks.data.BookmarkManager;
import com.mapswithme.maps.bookmarks.data.MapObject;
import com.mapswithme.maps.bookmarks.data.MapObject.ApiPoint;
import com.mapswithme.maps.bookmarks.data.ParcelablePoint;
import com.mapswithme.maps.location.LocationService;
import com.mapswithme.maps.search.SearchController;
import com.mapswithme.maps.settings.SettingsActivity;
import com.mapswithme.maps.settings.StoragePathManager;
import com.mapswithme.maps.settings.StoragePathManager.SetStoragePathListener;
import com.mapswithme.maps.settings.UnitLocale;
import com.mapswithme.maps.widget.MapInfoView;
import com.mapswithme.maps.widget.MapInfoView.OnVisibilityChangedListener;
import com.mapswithme.maps.widget.MapInfoView.State;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.Constants;
import com.mapswithme.util.LocationUtils;
import com.mapswithme.util.ShareAction;
import com.mapswithme.util.UiUtils;
import com.mapswithme.util.Utils;
import com.mapswithme.util.Yota;
import com.mapswithme.util.statistics.Statistics;
import com.nvidia.devtech.NvEventQueueActivity;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
public class MWMActivity extends NvEventQueueActivity
implements LocationService.LocationListener,
OnBalloonListener,
OnVisibilityChangedListener, OnClickListener
{
public static final String EXTRA_TASK = "map_task";
private final static String TAG = "MWMActivity";
private final static String EXTRA_CONSUMED = "mwm.extra.intent.processed";
private final static String EXTRA_SCREENSHOTS_TASK = "screenshots_task";
private final static String SCREENSHOTS_TASK_LOCATE = "locate_task";
private final static String SCREENSHOTS_TASK_PPP = "show_place_page";
private final static String EXTRA_LAT = "lat";
private final static String EXTRA_LON = "lon";
private final static String EXTRA_COUNTRY_INDEX = "country_index";
// Need it for search
private static final String EXTRA_SEARCH_RES_SINGLE = "search_res_index";
// Map tasks that we run AFTER rendering initialized
private final Stack<MapTask> mTasks = new Stack<>();
private BroadcastReceiver mExternalStorageReceiver = null;
private StoragePathManager mPathManager = new StoragePathManager();
private AlertDialog mStorageDisconnectedDialog = null;
private ImageButton mLocationButton;
// Info box (place page).
private MapInfoView mInfoView;
private SearchController mSearchController;
private boolean mNeedCheckUpdate = true;
private boolean mRenderingInitialized = false;
private int mCompassStatusListenerID = -1;
// Initialized to invalid combination to force update on the first check
private boolean mStorageAvailable = false;
private boolean mStorageWritable = true;
// toolbars
private static final long VERT_TOOLBAR_ANIM_DURATION = 250;
private ViewGroup mVerticalToolbar;
private ViewGroup mToolbar;
private Animation mVerticalToolbarAnimation;
private static final float FADE_VIEW_ALPHA = 0.5f;
private View mFadeView;
private static final String IS_KML_MOVED = "KmlBeenMoved";
private static final String IS_KITKAT_MIGRATION_COMPLETED = "KitKatMigrationCompleted";
// ads in vertical toolbar
private BroadcastReceiver mUpdateAdsReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
updateToolbarAds();
}
};
private boolean mAreToolbarAdsUpdated;
public static Intent createShowMapIntent(Context context, Index index, boolean doAutoDownload)
{
return new Intent(context, DownloadResourcesActivity.class)
.putExtra(DownloadResourcesActivity.EXTRA_COUNTRY_INDEX, index)
.putExtra(DownloadResourcesActivity.EXTRA_AUTODOWNLOAD_CONTRY, doAutoDownload);
}
public static void startWithSearchResult(Context context, boolean single)
{
final Intent mapIntent = new Intent(context, MWMActivity.class);
mapIntent.putExtra(EXTRA_SEARCH_RES_SINGLE, single);
context.startActivity(mapIntent);
// Next we need to handle intent
}
private native void deactivatePopup();
private void startLocation()
{
MWMApplication.get().getLocationState().onStartLocation();
resumeLocation();
}
private void stopLocation()
{
MWMApplication.get().getLocationState().onStopLocation();
pauseLocation();
}
private void pauseLocation()
{
MWMApplication.get().getLocationService().stopUpdate(this);
// Enable automatic turning screen off while app is idle
Utils.automaticIdleScreen(true, getWindow());
}
private void resumeLocation()
{
MWMApplication.get().getLocationService().startUpdate(this);
// Do not turn off the screen while displaying position
Utils.automaticIdleScreen(false, getWindow());
}
public void checkShouldResumeLocationService()
{
final LocationState state = MWMApplication.get().getLocationState();
final boolean hasPosition = state.hasPosition();
final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW);
if (hasPosition || state.isFirstPosition())
{
if (hasPosition && isFollowMode)
{
state.startCompassFollowing();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
}
else
{
LocationButtonImageSetter.setButtonViewFromState(
hasPosition
? ButtonState.HAS_LOCATION
: ButtonState.WAITING_LOCATION, mLocationButton
);
}
resumeLocation();
}
else
{
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
}
public void OnDownloadCountryClicked()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
nativeDownloadCountry();
}
});
}
private void checkUserMarkActivation()
{
final Intent intent = getIntent();
if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK))
{
final String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK);
if (value.equals(SCREENSHOTS_TASK_PPP))
{
final double lat = Double.parseDouble(intent.getStringExtra(EXTRA_LAT));
final double lon = Double.parseDouble(intent.getStringExtra(EXTRA_LON));
mToolbar.getHandler().postDelayed(new Runnable()
{
@Override
public void run()
{
Framework.nativeActivateUserMark(lat, lon);
}
}, 1000);
}
}
}
@Override
public void OnRenderingInitialized()
{
mRenderingInitialized = true;
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Run all checks in main thread after rendering is initialized.
checkMeasurementSystem();
checkUpdateMaps();
checkKitkatMigrationMove();
checkLiteMapsInPro();
checkFacebookDialog();
checkBuyProDialog();
checkUserMarkActivation();
}
});
runTasks();
}
private void runTasks()
{
// Task are not UI-thread bounded,
// if any task need UI-thread it should implicitly
// use Activity.runOnUiThread().
while (!mTasks.isEmpty())
mTasks.pop().run(this);
}
private Activity getActivity() { return this; }
@Override
public void ReportUnsupported()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
new AlertDialog.Builder(getActivity())
.setMessage(getString(R.string.unsupported_phone))
.setCancelable(false)
.setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
getActivity().moveTaskToBack(true);
dlg.dismiss();
}
})
.create()
.show();
}
});
}
private void checkMeasurementSystem()
{
UnitLocale.initializeCurrentUnits();
}
private native void nativeScale(double k);
public void onPlusClicked(View v)
{
nativeScale(3.0 / 2);
}
public void onMinusClicked(View v)
{
nativeScale(2.0 / 3);
}
public void onBookmarksClicked(View v)
{
if (!MWMApplication.get().hasBookmarks())
showProVersionBanner(getString(R.string.bookmarks_in_pro_version));
else
startActivity(new Intent(this, BookmarkCategoriesActivity.class));
}
public void onMyPositionClicked(View v)
{
final LocationState state = MWMApplication.get().getLocationState();
if (state.hasPosition())
{
if (state.isCentered())
{
if (BuildConfig.IS_PRO && state.hasCompass())
{
final boolean isFollowMode = (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW);
if (isFollowMode)
{
state.stopCompassFollowingAndRotateMap();
}
else
{
state.startCompassFollowing();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
return;
}
}
}
else
{
state.animateToPositionAndEnqueueLocationProcessMode(LocationState.LOCATION_CENTER_ONLY);
mLocationButton.setSelected(true);
return;
}
}
else
{
if (!state.isFirstPosition())
{
LocationButtonImageSetter.setButtonViewFromState(ButtonState.WAITING_LOCATION, mLocationButton);
startLocation();
return;
}
}
// Stop location observing first ...
stopLocation();
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
private void ShowAlertDlg(int tittleID)
{
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(tittleID)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); }
})
.create()
.show();
}
private void checkKitkatMigrationMove()
{
final boolean kmlMoved = MWMApplication.get().nativeGetBoolean(IS_KML_MOVED, false);
final boolean mapsCpy = MWMApplication.get().nativeGetBoolean(IS_KITKAT_MIGRATION_COMPLETED, false);
if (!kmlMoved)
if (mPathManager.moveBookmarks())
MWMApplication.get().nativeSetBoolean(IS_KML_MOVED, true);
else
{
ShowAlertDlg(R.string.bookmark_move_fail);
return;
}
if (!mapsCpy)
mPathManager.checkWritableDir(this,
new SetStoragePathListener()
{
@Override
public void moveFilesFinished(String newPath)
{
MWMApplication.get().nativeSetBoolean(IS_KITKAT_MIGRATION_COMPLETED, true);
ShowAlertDlg(R.string.kitkat_migrate_ok);
}
@Override
public void moveFilesFailed()
{
ShowAlertDlg(R.string.kitkat_migrate_failed);
}
}
);
}
/**
* Checks if PRO version is running on KITKAT or greater sdk.
* If so - checks whether LITE version is installed and contains maps on sd card and then copies them to own directory on sdcard.
*/
private void checkLiteMapsInPro()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
BuildConfig.IS_PRO &&
(Utils.isAppInstalled(Constants.Package.MWM_LITE_PACKAGE) || Utils.isAppInstalled(Constants.Package.MWM_SAMSUNG_PACKAGE)))
{
if (!mPathManager.containsLiteMapsOnSdcard())
return;
mPathManager.moveMapsLiteToPro(this,
new SetStoragePathListener()
{
@Override
public void moveFilesFinished(String newPath)
{
ShowAlertDlg(R.string.move_lite_maps_to_pro_ok);
}
@Override
public void moveFilesFailed()
{
ShowAlertDlg(R.string.move_lite_maps_to_pro_failed);
}
}
);
}
}
private void checkUpdateMaps()
{
// do it only once
if (mNeedCheckUpdate)
{
mNeedCheckUpdate = false;
MWMApplication.get().getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor()
{
@Override
public void doUpdate()
{
runDownloadActivity();
}
@Override
public void doCancel()
{
}
});
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
alignControls();
// alpha from animation is lost on some devices after configuration changes.
// we should restore it manually.
if (mFadeView != null && mFadeView.getVisibility() == View.VISIBLE)
{
Animation alphaAnimation = new AlphaAnimation(FADE_VIEW_ALPHA, FADE_VIEW_ALPHA);
alphaAnimation.setFillAfter(true);
alphaAnimation.setDuration(0);
mFadeView.startAnimation(alphaAnimation);
}
}
private void showDialogImpl(final int dlgID, int resMsg, DialogInterface.OnClickListener okListener)
{
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage(getString(resMsg))
.setPositiveButton(getString(R.string.ok), okListener)
.setNeutralButton(getString(R.string.never), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
MWMApplication.get().submitDialogResult(dlgID, MWMApplication.NEVER);
}
})
.setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
dlg.dismiss();
MWMApplication.get().submitDialogResult(dlgID, MWMApplication.LATER);
}
})
.create()
.show();
}
private boolean isChinaISO(String iso)
{
final String arr[] = {"CN", "CHN", "HK", "HKG", "MO", "MAC"};
for (final String s : arr)
if (iso.equalsIgnoreCase(s))
return true;
return false;
}
private boolean isChinaRegion()
{
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA)
{
final String iso = tm.getNetworkCountryIso();
Log.i(TAG, "TelephonyManager country ISO = " + iso);
if (isChinaISO(iso))
return true;
}
else
{
final Location l = MWMApplication.get().getLocationService().getLastKnown();
if (l != null && nativeIsInChina(l.getLatitude(), l.getLongitude()))
return true;
else
{
final String code = Locale.getDefault().getCountry();
Log.i(TAG, "Locale country ISO = " + code);
if (isChinaISO(code))
return true;
}
}
return false;
}
private void checkFacebookDialog()
{
if (ConnectionState.isConnected(this) &&
MWMApplication.get().shouldShowDialog(MWMApplication.FACEBOOK) &&
!isChinaRegion())
{
showDialogImpl(MWMApplication.FACEBOOK, R.string.share_on_facebook_text,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
MWMApplication.get().submitDialogResult(MWMApplication.FACEBOOK, MWMApplication.OK);
dlg.dismiss();
UiUtils.showFacebookPage(MWMActivity.this);
}
}
);
}
}
private void showProVersionBanner(final String message)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
UiUtils.showBuyProDialog(MWMActivity.this, message);
}
});
}
private void checkBuyProDialog()
{
if (!BuildConfig.IS_PRO &&
(ConnectionState.isConnected(this)) &&
MWMApplication.get().shouldShowDialog(MWMApplication.BUYPRO))
{
showDialogImpl(MWMApplication.BUYPRO, R.string.pro_version_available,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dlg, int which)
{
MWMApplication.get().submitDialogResult(MWMApplication.BUYPRO, MWMApplication.OK);
dlg.dismiss();
UiUtils.openAppInMarket(MWMActivity.this, BuildConfig.PRO_URL);
}
}
);
}
}
private void runSearchActivity()
{
startActivity(new Intent(this, SearchActivity.class));
}
public void onSearchClicked(View v)
{
if (!BuildConfig.IS_PRO)
{
showProVersionBanner(getString(R.string.search_available_in_pro_version));
}
else if (!MWMApplication.get().getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor()
{
@Override
public void doUpdate()
{
runDownloadActivity();
}
@Override
public void doCancel()
{
runSearchActivity();
}
}))
{
runSearchActivity();
}
}
@Override
public boolean onSearchRequested()
{
onSearchClicked(null);
return false;
}
public void onMoreClicked(View v)
{
setVerticalToolbarVisible(true);
}
private void setVerticalToolbarVisible(boolean showVerticalToolbar)
{
if (mVerticalToolbarAnimation != null ||
(mVerticalToolbar.getVisibility() == View.VISIBLE && showVerticalToolbar) ||
(mVerticalToolbar.getVisibility() != View.VISIBLE && !showVerticalToolbar))
return;
int fromY, toY;
Animation.AnimationListener listener;
float fromAlpha, toAlpha;
if (showVerticalToolbar)
{
fromY = 1;
toY = 0;
fromAlpha = 0.0f;
toAlpha = FADE_VIEW_ALPHA;
listener = new UiUtils.SimpleAnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
mVerticalToolbar.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
mVerticalToolbarAnimation = null;
}
};
}
else
{
fromY = 0;
toY = 1;
fromAlpha = FADE_VIEW_ALPHA;
toAlpha = 0.0f;
listener = new UiUtils.SimpleAnimationListener()
{
@Override
public void onAnimationEnd(Animation animation)
{
mVerticalToolbar.setVisibility(View.INVISIBLE);
mFadeView.setVisibility(View.GONE);
mVerticalToolbarAnimation = null;
}
};
}
// slide vertical toolbar
mVerticalToolbarAnimation = UiUtils.generateSlideAnimation(0, 0, fromY, toY);
mVerticalToolbarAnimation.setDuration(VERT_TOOLBAR_ANIM_DURATION);
mVerticalToolbarAnimation.setAnimationListener(listener);
mVerticalToolbar.startAnimation(mVerticalToolbarAnimation);
// fade map
Animation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setFillBefore(true);
alphaAnimation.setFillAfter(true);
alphaAnimation.setDuration(VERT_TOOLBAR_ANIM_DURATION);
mFadeView.setVisibility(View.VISIBLE);
mFadeView.startAnimation(alphaAnimation);
}
private void shareMyLocation()
{
final Location loc = MWMApplication.get().getLocationService().getLastKnown();
if (loc != null)
{
final String geoUrl = Framework.nativeGetGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), "");
final String httpUrl = Framework.getHttpGe0Url(loc.getLatitude(), loc.getLongitude(), Framework.getDrawScale(), "");
final String body = getString(R.string.my_position_share_sms, geoUrl, httpUrl);
// we use shortest message we can have here
ShareAction.getAnyShare().shareWithText(getActivity(), body, "");
}
else
{
new AlertDialog.Builder(MWMActivity.this)
.setMessage(R.string.unknown_current_position)
.setCancelable(true)
.setPositiveButton(android.R.string.ok, new Dialog.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create()
.show();
}
}
private void runDownloadActivity()
{
startActivity(new Intent(this, DownloadActivity.class));
}
@Override
public void onCreate(Bundle savedInstanceState)
{
// Use full-screen on Kindle Fire only
if (Utils.isAmazonDevice())
{
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
setContentView(R.layout.map);
super.onCreate(savedInstanceState);
// Log app start events - successful installation means that user has passed DownloadResourcesActivity
MWMApplication.get().onMwmStart(this);
// Do not turn off the screen while benchmarking
if (MWMApplication.get().nativeIsBenchmarking())
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
nativeConnectDownloadButton();
// Set up view
mLocationButton = (ImageButton) findViewById(R.id.map_button_myposition);
yotaSetup();
setUpInfoBox();
Framework.nativeConnectBalloonListeners(this);
final Intent intent = getIntent();
// We need check for tasks both in onCreate and onNewIntent
addTask(intent);
// Initialize location service
MWMApplication.get().getLocationService();
mSearchController = SearchController.getInstance();
mSearchController.onCreate(this);
setUpToolbars();
if (intent != null && intent.hasExtra(EXTRA_SCREENSHOTS_TASK))
{
String value = intent.getStringExtra(EXTRA_SCREENSHOTS_TASK);
if (value.equals(SCREENSHOTS_TASK_LOCATE))
onMyPositionClicked(null);
}
updateToolbarAds();
LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateAdsReceiver, new IntentFilter(WorkerService.ACTION_UPDATE_MENU_ADS));
}
private void updateToolbarAds()
{
final List<MenuAd> ads = AdsManager.getMenuAds();
if (ads != null && !mAreToolbarAdsUpdated)
{
mAreToolbarAdsUpdated = true;
int startAdMenuPosition = 7;
for (final MenuAd ad : ads)
{
final View view = getLayoutInflater().inflate(R.layout.item_bottom_toolbar, mVerticalToolbar, false);
final TextView textView = (TextView) view.findViewById(R.id.tv__bottom_item_text);
textView.setText(ad.getTitle());
try
{
textView.setTextColor(Color.parseColor(ad.getHexColor()));
} catch (IllegalArgumentException e)
{
e.printStackTrace();
}
final ImageView imageView = (ImageView) view.findViewById(R.id.iv__bottom_icon);
imageView.setImageBitmap(ad.getIcon());
view.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final Intent it = new Intent(Intent.ACTION_VIEW);
it.setData(Uri.parse(ad.getAppUrl()));
startActivity(it);
}
});
mVerticalToolbar.addView(view, startAdMenuPosition++);
}
}
}
private void setUpToolbars()
{
mToolbar = (ViewGroup) findViewById(R.id.map_bottom_toolbar);
mVerticalToolbar = (ViewGroup) findViewById(R.id.map_bottom_vertical_toolbar);
mVerticalToolbar.findViewById(R.id.btn_buy_pro).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_download_maps).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_share).setOnClickListener(this);
mVerticalToolbar.findViewById(R.id.btn_settings).setOnClickListener(this);
View moreApps = mVerticalToolbar.findViewById(R.id.btn_more_apps);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || Framework.getGuideIds().length == 0)
UiUtils.hide(moreApps);
else
moreApps.setOnClickListener(this);
UiUtils.invisible(mVerticalToolbar);
mFadeView = findViewById(R.id.fade_view);
}
private void setUpInfoBox()
{
mInfoView = (MapInfoView) findViewById(R.id.info_box);
mInfoView.setOnVisibilityChangedListener(this);
mInfoView.bringToFront();
}
private void yotaSetup()
{
final View yopmeButton = findViewById(R.id.yop_it);
if (!Yota.isYota())
{
yopmeButton.setVisibility(View.INVISIBLE);
}
else
{
yopmeButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
final double[] latLon = Framework.getScreenRectCenter();
final double zoom = Framework.getDrawScale();
final LocationState locState = MWMApplication.get().getLocationState();
if (locState.hasPosition() && locState.isCentered())
Yota.showLocation(getApplicationContext(), zoom);
else
Yota.showMap(getApplicationContext(), latLon[0], latLon[1], zoom, null, locState.hasPosition());
Statistics.INSTANCE.trackBackscreenCall(getApplication(), "Map");
}
});
}
}
@Override
public void onDestroy()
{
Framework.nativeClearBalloonListeners();
super.onDestroy();
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
if (intent != null)
{
if (intent.hasExtra(EXTRA_TASK))
addTask(intent);
else if (intent.hasExtra(EXTRA_SEARCH_RES_SINGLE))
{
final boolean singleResult = intent.getBooleanExtra(EXTRA_SEARCH_RES_SINGLE, false);
if (singleResult)
{
MapObject.SearchResult result = new MapObject.SearchResult(0);
onAdditionalLayerActivated(result.getName(), result.getPoiTypeName(), result.getLat(), result.getLon());
}
else
onDismiss();
}
}
}
private void addTask(Intent intent)
{
if (intent != null
&& !intent.getBooleanExtra(EXTRA_CONSUMED, false)
&& intent.hasExtra(EXTRA_TASK)
&& ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0))
{
final MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK);
mTasks.add(mapTask);
intent.removeExtra(EXTRA_TASK);
if (mRenderingInitialized)
runTasks();
// mark intent as consumed
intent.putExtra(EXTRA_CONSUMED, true);
}
}
@Override
protected void onStop()
{
super.onStop();
mRenderingInitialized = false;
}
private void alignControls()
{
final View zoomPlusButton = findViewById(R.id.map_button_plus);
final RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) zoomPlusButton.getLayoutParams();
final int margin = (int) getResources().getDimension(R.dimen.zoom_margin);
final int marginTop = (int) getResources().getDimension(R.dimen.zoom_plus_top_margin);
lp.setMargins(margin, marginTop, margin, margin);
}
/// @name From Location interface
@Override
public void onLocationError(int errorCode)
{
nativeOnLocationError(errorCode);
// Notify user about turned off location services
if (errorCode == LocationService.ERROR_DENIED)
{
MWMApplication.get().getLocationState().turnOff();
// Do not show this dialog on Kindle Fire - it doesn't have location services
// and even wifi settings can't be opened programmatically
if (!Utils.isAmazonDevice())
{
new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text)
.setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
try
{
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} catch (final Exception e1)
{
// On older Android devices location settings are merged with security
try
{
startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS));
} catch (final Exception e2)
{
Log.w(TAG, "Can't run activity" + e2);
}
}
dialog.dismiss();
}
})
.setNegativeButton(R.string.close, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.create()
.show();
}
}
else if (errorCode == LocationService.ERROR_GPS_OFF)
{
Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationUpdated(final Location l)
{
if (MWMApplication.get().getLocationState().isFirstPosition())
LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton);
nativeLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy(), l.getAltitude(), l.getSpeed(), l.getBearing());
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateDistanceAndAzimut(l);
}
@SuppressWarnings("deprecation")
@Override
public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy)
{
final double angles[] = {magneticNorth, trueNorth};
LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), angles);
nativeCompassUpdated(time, angles[0], angles[1], accuracy);
final double north = (angles[1] >= 0.0 ? angles[1] : angles[0]);
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateAzimuth(north);
}
@Override
public void onDrivingHeadingUpdated(long time, double heading, double accuracy)
{
LocationUtils.correctCompassAngles(getWindowManager().getDefaultDisplay().getOrientation(), new double[]{heading});
nativeCompassUpdated(time, heading, heading, accuracy);
if (mInfoView.getState() != State.HIDDEN)
mInfoView.updateAzimuth(heading);
}
public void onCompassStatusChanged(int newStatus)
{
if (newStatus == 1)
LocationButtonImageSetter.setButtonViewFromState(ButtonState.FOLLOW_MODE, mLocationButton);
else if (MWMApplication.get().getLocationState().hasPosition())
LocationButtonImageSetter.setButtonViewFromState(ButtonState.HAS_LOCATION, mLocationButton);
else
LocationButtonImageSetter.setButtonViewFromState(ButtonState.NO_LOCATION, mLocationButton);
}
/// Callback from native compass GUI element processing.
public void OnCompassStatusChanged(int newStatus)
{
final int val = newStatus;
runOnUiThread(new Runnable()
{
@Override
public void run()
{
onCompassStatusChanged(val);
}
});
}
private void startWatchingCompassStatusUpdate()
{
mCompassStatusListenerID = MWMApplication.get().getLocationState().addCompassStatusListener(this);
}
private void stopWatchingCompassStatusUpdate()
{
MWMApplication.get().getLocationState().removeCompassStatusListener(mCompassStatusListenerID);
}
@Override
protected void onPause()
{
pauseLocation();
stopWatchingExternalStorage();
stopWatchingCompassStatusUpdate();
super.onPause();
}
@Override
protected void onResume()
{
super.onResume();
checkShouldResumeLocationService();
startWatchingCompassStatusUpdate();
startWatchingExternalStorage();
UiUtils.showIf(MWMApplication.get().nativeGetBoolean(SettingsActivity.ZOOM_BUTTON_ENABLED, true),
findViewById(R.id.map_button_plus),
findViewById(R.id.map_button_minus));
alignControls();
mSearchController.onResume();
mInfoView.onResume();
MWMApplication.get().onMwmResume(this);
}
private void updateExternalStorageState()
{
boolean available = false, writable = false;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
available = writable = true;
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
available = true;
if (mStorageAvailable != available || mStorageWritable != writable)
{
mStorageAvailable = available;
mStorageWritable = writable;
handleExternalStorageState(available, writable);
}
}
private void handleExternalStorageState(boolean available, boolean writeable)
{
if (available && writeable)
{
// Add local maps to the model
nativeStorageConnected();
// @TODO enable downloader button and dismiss blocking popup
if (mStorageDisconnectedDialog != null)
mStorageDisconnectedDialog.dismiss();
}
else if (available)
{
// Add local maps to the model
nativeStorageConnected();
// @TODO disable downloader button and dismiss blocking popup
if (mStorageDisconnectedDialog != null)
mStorageDisconnectedDialog.dismiss();
}
else
{
// Remove local maps from the model
nativeStorageDisconnected();
// @TODO enable downloader button and show blocking popup
if (mStorageDisconnectedDialog == null)
{
mStorageDisconnectedDialog = new AlertDialog.Builder(this)
.setTitle(R.string.external_storage_is_not_available)
.setMessage(getString(R.string.disconnect_usb_cable))
.setCancelable(false)
.create();
}
mStorageDisconnectedDialog.show();
}
}
private void startWatchingExternalStorage()
{
mExternalStorageReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
updateExternalStorageState();
}
};
registerReceiver(mExternalStorageReceiver, StoragePathManager.getMediaChangesIntentFilter());
updateExternalStorageState();
}
private void stopWatchingExternalStorage()
{
mPathManager.stopExternalStorageWatching();
if (mExternalStorageReceiver != null)
{
unregisterReceiver(mExternalStorageReceiver);
mExternalStorageReceiver = null;
}
}
@Override
public void onBackPressed()
{
if (mInfoView.getState() != State.HIDDEN)
{
hideInfoView();
deactivatePopup();
}
else if (mVerticalToolbar.getVisibility() == View.VISIBLE)
setVerticalToolbarVisible(false);
else
super.onBackPressed();
}
/// Callbacks from native map objects touch event.
@Override
public void onApiPointActivated(final double lat, final double lon, final String name, final String id)
{
if (ParsedMmwRequest.hasRequest())
{
final ParsedMmwRequest request = ParsedMmwRequest.getCurrentRequest();
request.setPointData(lat, lon, name, id);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final String poiType = ParsedMmwRequest.getCurrentRequest().getCallerName(MWMApplication.get()).toString();
final ApiPoint apiPoint = new ApiPoint(name, id, poiType, lat, lon);
if (!mInfoView.hasMapObject(apiPoint))
{
mInfoView.setMapObject(apiPoint);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
}
@Override
public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon)
{
final MapObject poi = new MapObject.Poi(name, lat, lon, type);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (!mInfoView.hasMapObject(poi))
{
mInfoView.setMapObject(poi);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onBookmarkActivated(final int category, final int bookmarkIndex)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final Bookmark b = BookmarkManager.getBookmarkManager().getBookmark(category, bookmarkIndex);
if (!mInfoView.hasMapObject(b))
{
mInfoView.setMapObject(b);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onMyPositionActivated(final double lat, final double lon)
{
final MapObject mypos = new MapObject.MyPosition(getString(R.string.my_position), lat, lon);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (!mInfoView.hasMapObject(mypos))
{
mInfoView.setMapObject(mypos);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
@Override
public void onAdditionalLayerActivated(final String name, final String type, final double lat, final double lon)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
final MapObject sr = new MapObject.SearchResult(name, type, lat, lon);
if (!mInfoView.hasMapObject(sr))
{
mInfoView.setMapObject(sr);
mInfoView.setState(State.PREVIEW_ONLY);
}
}
});
}
private void hideInfoView()
{
mInfoView.setState(State.HIDDEN);
mInfoView.setMapObject(null);
UiUtils.show(findViewById(R.id.map_bottom_toolbar));
}
@Override
public void onDismiss()
{
if (!mInfoView.hasMapObject(null))
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
hideInfoView();
deactivatePopup();
}
});
}
}
private native void nativeStorageConnected();
private native void nativeStorageDisconnected();
private native void nativeConnectDownloadButton();
private native void nativeDownloadCountry();
private native void nativeOnLocationError(int errorCode);
private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy, double altitude, float speed, float bearing);
private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy);
private native boolean nativeIsInChina(double lat, double lon);
public native boolean showMapForUrl(String url);
@Override
public void onPreviewVisibilityChanged(boolean isVisible)
{
setVerticalToolbarVisible(false);
}
@Override
public void onPlacePageVisibilityChanged(boolean isVisible)
{
setVerticalToolbarVisible(false);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_buy_pro:
setVerticalToolbarVisible(false);
UiUtils.openAppInMarket(MWMActivity.this, BuildConfig.PRO_URL);
break;
case R.id.btn_share:
setVerticalToolbarVisible(false);
shareMyLocation();
break;
case R.id.btn_settings:
setVerticalToolbarVisible(false);
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.btn_download_maps:
setVerticalToolbarVisible(false);
runDownloadActivity();
break;
case R.id.btn_more_apps:
setVerticalToolbarVisible(false);
startActivity(new Intent(this, MoreAppsActivity.class));
break;
default:
break;
}
}
@Override
public boolean onTouch(View view, MotionEvent event)
{
// if vertical toolbar is visible - hide it and ignore touch
if (mVerticalToolbar.getVisibility() == View.VISIBLE)
{
setVerticalToolbarVisible(false);
return true;
}
if (mInfoView.getState() == State.FULL_PLACEPAGE)
{
deactivatePopup();
hideInfoView();
return true;
}
return super.onTouch(view, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_MENU)
{
setVerticalToolbarVisible(true);
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == BookmarkActivity.REQUEST_CODE_EDIT_BOOKMARK && resultCode == RESULT_OK)
{
final Point bmk = ((ParcelablePoint) data.getParcelableExtra(BookmarkActivity.PIN)).getPoint();
onBookmarkActivated(bmk.x, bmk.y);
}
super.onActivityResult(requestCode, resultCode, data);
}
public interface MapTask extends Serializable
{
public boolean run(MWMActivity target);
}
public static class OpenUrlTask implements MapTask
{
private static final long serialVersionUID = 1L;
private final String mUrl;
public OpenUrlTask(String url)
{
Utils.checkNotNull(url);
mUrl = url;
}
@Override
public boolean run(MWMActivity target)
{
return target.showMapForUrl(mUrl);
}
}
public static class ShowCountryTask implements MapTask
{
private static final long serialVersionUID = 1L;
private final Index mIndex;
private final boolean mDoAutoDownload;
public ShowCountryTask(Index index, boolean doAutoDownload)
{
mIndex = index;
mDoAutoDownload = doAutoDownload;
}
@Override
public boolean run(MWMActivity target)
{
final MapStorage storage = MWMApplication.get().getMapStorage();
if (mDoAutoDownload)
{
storage.downloadCountry(mIndex);
// set zoom level so that download process is visible
Framework.nativeShowCountry(mIndex, true);
}
else
Framework.nativeShowCountry(mIndex, false);
return true;
}
}
}
|
package net.minecraftforge.fluids;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.Event;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableMap;
/**
* Handles Fluid registrations. Fluids MUST be registered in order to function.
*
* @author King Lemming, CovertJaguar (LiquidDictionary)
*
*/
public abstract class FluidRegistry
{
static int maxID = 0;
static HashMap<String, Fluid> fluids = new HashMap();
static BiMap<String, Integer> fluidIDs = HashBiMap.create();
public static final Fluid WATER = new Fluid("water").setBlockID(Block.waterStill.blockID).setUnlocalizedName(Block.waterStill.getUnlocalizedName());
public static final Fluid LAVA = new Fluid("lava").setBlockID(Block.lavaStill.blockID).setLuminosity(15).setDensity(3000).setViscosity(6000).setUnlocalizedName(Block.lavaStill.getUnlocalizedName());
public static int renderIdFluid = -1;
static
{
registerFluid(WATER);
registerFluid(LAVA);
}
private FluidRegistry(){}
/**
* Called by Forge to prepare the ID map for server -> client sync.
*/
static void initFluidIDs(BiMap<String, Integer> newfluidIDs)
{
maxID = newfluidIDs.size();
fluidIDs.clear();
fluidIDs.putAll(newfluidIDs);
}
/**
* Register a new Fluid. If a fluid with the same name already exists, registration is denied.
*
* @param fluid
* The fluid to register.
* @return True if the fluid was successfully registered; false if there is a name clash.
*/
public static boolean registerFluid(Fluid fluid)
{
if (fluidIDs.containsKey(fluid.getName()))
{
return false;
}
fluids.put(fluid.getName(), fluid);
fluidIDs.put(fluid.getName(), ++maxID);
MinecraftForge.EVENT_BUS.post(new FluidRegisterEvent(fluid.getName(), maxID));
return true;
}
public static boolean isFluidRegistered(Fluid fluid)
{
return fluidIDs.containsKey(fluid.getName());
}
public static boolean isFluidRegistered(String fluidName)
{
return fluidIDs.containsKey(fluidName);
}
public static Fluid getFluid(String fluidName)
{
return fluids.get(fluidName);
}
public static Fluid getFluid(int fluidID)
{
return fluids.get(getFluidName(fluidID));
}
public static String getFluidName(int fluidID)
{
return fluidIDs.inverse().get(fluidID);
}
public static String getFluidName(FluidStack stack)
{
return getFluidName(stack.fluidID);
}
public static int getFluidID(String fluidName)
{
return fluidIDs.get(fluidName);
}
public static FluidStack getFluidStack(String fluidName, int amount)
{
if (!fluidIDs.containsKey(fluidName))
{
return null;
}
return new FluidStack(getFluidID(fluidName), amount);
}
/**
* Returns a read-only map containing Fluid Names and their associated Fluids.
*/
public static Map<String, Fluid> getRegisteredFluids()
{
return ImmutableMap.copyOf(fluids);
}
/**
* Returns a read-only map containing Fluid Names and their associated IDs.
*/
public static Map<String, Integer> getRegisteredFluidIDs()
{
return ImmutableMap.copyOf(fluidIDs);
}
public static class FluidRegisterEvent extends Event
{
public final String fluidName;
public final int fluidID;
public FluidRegisterEvent(String fluidName, int fluidID)
{
this.fluidName = fluidName;
this.fluidID = fluidID;
}
}
}
|
package bisq.common.config;
import bisq.common.util.Utilities;
import joptsimple.AbstractOptionSpec;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.OptionSpecBuilder;
import joptsimple.util.PathConverter;
import joptsimple.util.PathProperties;
import joptsimple.util.RegexMatcher;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.File;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
public class Config {
private static final Logger log = LoggerFactory.getLogger(Config.class);
public static final int NULL_INT = Integer.MIN_VALUE;
public static final String APP_NAME = "appName";
public static final String BASE_CURRENCY_NETWORK = "baseCurrencyNetwork";
public static final String REFERRAL_ID = "referralId";
public static final String USE_DEV_MODE = "useDevMode";
public static final String TOR_DIR = "torDir";
public static final String STORAGE_DIR = "storageDir";
public static final String KEY_STORAGE_DIR = "keyStorageDir";
public static final String WALLET_DIR = "walletDir";
public static final String USE_DEV_PRIVILEGE_KEYS = "useDevPrivilegeKeys";
public static final String DUMP_STATISTICS = "dumpStatistics";
public static final String IGNORE_DEV_MSG = "ignoreDevMsg";
public static final String PROVIDERS = "providers";
public static final String LOG_LEVEL = "logLevel";
public static final String SEED_NODES = "seedNodes";
public static final String BAN_LIST = "banList";
public static final String NODE_PORT = "nodePort";
public static final String USE_LOCALHOST_FOR_P2P = "useLocalhostForP2P";
public static final String MAX_CONNECTIONS = "maxConnections";
public static final String SOCKS_5_PROXY_BTC_ADDRESS = "socks5ProxyBtcAddress";
public static final String SOCKS_5_PROXY_HTTP_ADDRESS = "socks5ProxyHttpAddress";
public static final String TORRC_FILE = "torrcFile";
public static final String TORRC_OPTIONS = "torrcOptions";
public static final String TOR_CONTROL_PORT = "torControlPort";
public static final String TOR_CONTROL_PASSWORD = "torControlPassword";
public static final String TOR_CONTROL_COOKIE_FILE = "torControlCookieFile";
public static final String TOR_CONTROL_USE_SAFE_COOKIE_AUTH = "torControlUseSafeCookieAuth";
public static final String TOR_STREAM_ISOLATION = "torStreamIsolation";
static final String DEFAULT_CONFIG_FILE_NAME = "bisq.properties";
public static File CURRENT_APP_DATA_DIR;
// default data dir properties
private final String defaultAppName;
private final File defaultAppDataDir;
private final File defaultConfigFile;
// cli options
private final File configFile;
private final String appName;
private final File userDataDir;
private final File appDataDir;
private final int nodePort;
private final List<String> bannedBtcNodes;
private final List<String> bannedPriceRelayNodes;
private final List<String> bannedSeedNodes;
private final BaseCurrencyNetwork baseCurrencyNetwork;
private final boolean ignoreLocalBtcNode;
private final String bitcoinRegtestHost;
private final boolean daoActivated;
private final boolean fullDaoNode;
private final String logLevel;
private final String referralId;
private final boolean useDevMode;
private final boolean useDevPrivilegeKeys;
private final boolean dumpStatistics;
private final int maxMemory;
private final boolean ignoreDevMsg;
private final List<String> providers;
private final List<String> seedNodes;
private final List<String> banList;
private final boolean useLocalhostForP2P;
private final int maxConnections;
private final String socks5ProxyBtcAddress;
private final String socks5ProxyHttpAddress;
private final File torrcFile;
private final String torrcOptions;
private final int torControlPort;
private final String torControlPassword;
private final File torControlCookieFile;
private final boolean useTorControlSafeCookieAuth;
private final boolean torStreamIsolation;
private final int msgThrottlePerSec;
private final int msgThrottlePer10Sec;
private final int sendMsgThrottleTrigger;
private final int sendMsgThrottleSleep;
// properties derived from cli options, but not exposed as cli options themselves
private boolean localBitcoinNodeIsRunning = false; // FIXME: eliminate mutable state
private final File torDir;
private final File walletDir;
private final File storageDir;
private final File keyStorageDir;
public Config(String defaultAppName) throws HelpRequested {
this(defaultAppName, new String[]{});
}
public Config(String defaultAppName, String[] args) throws HelpRequested {
File defaultUserDataDir = getDefaultUserDataDir();
this.defaultAppName = defaultAppName;
this.defaultAppDataDir = new File(defaultUserDataDir, this.defaultAppName);
this.defaultConfigFile = new File(defaultAppDataDir, DEFAULT_CONFIG_FILE_NAME);
OptionParser parser = new OptionParser();
parser.allowsUnrecognizedOptions();
AbstractOptionSpec<Void> helpOpt =
parser.accepts("help", "Print this help text")
.forHelp();
ArgumentAcceptingOptionSpec<String> configFileOpt =
parser.accepts("configFile", "Specify configuration file. " +
"Relative paths will be prefixed by appDataDir location.")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(DEFAULT_CONFIG_FILE_NAME);
ArgumentAcceptingOptionSpec<File> userDataDirOpt =
parser.accepts("userDataDir", "User data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultUserDataDir);
ArgumentAcceptingOptionSpec<String> appNameOpt =
parser.accepts(APP_NAME, "Application name")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(this.defaultAppName);
ArgumentAcceptingOptionSpec<File> appDataDirOpt =
parser.accepts("appDataDir", "Application data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultAppDataDir);
ArgumentAcceptingOptionSpec<Integer> nodePortOpt =
parser.accepts(NODE_PORT, "Port to listen on")
.withRequiredArg()
.ofType(Integer.class)
.defaultsTo(9999);
ArgumentAcceptingOptionSpec<String> bannedBtcNodesOpt =
parser.accepts("bannedBtcNodes", "List Bitcoin nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedPriceRelayNodesOpt =
parser.accepts("bannedPriceRelayNodes", "List Bisq price nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedSeedNodesOpt =
parser.accepts("bannedSeedNodes", "List Bisq seed nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<Enum> baseCurrencyNetworkOpt =
parser.accepts(BASE_CURRENCY_NETWORK, "Base currency network")
.withRequiredArg()
.ofType(BaseCurrencyNetwork.class)
.withValuesConvertedBy(new EnumValueConverter(BaseCurrencyNetwork.class))
.defaultsTo(BaseCurrencyNetwork.BTC_MAINNET);
ArgumentAcceptingOptionSpec<Boolean> ignoreLocalBtcNodeOpt =
parser.accepts("ignoreLocalBtcNode", "If set to true a Bitcoin Core node running locally will be ignored")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> bitcoinRegtestHostOpt =
parser.accepts("bitcoinRegtestHost", "Bitcoin Core node when using BTC_REGTEST network")
.withRequiredArg()
.ofType(String.class)
.describedAs("host[:port]")
.defaultsTo("localhost");
ArgumentAcceptingOptionSpec<Boolean> daoActivatedOpt =
parser.accepts("daoActivated", "Developer flag. If true it enables dao phase 2 features.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(true);
ArgumentAcceptingOptionSpec<Boolean> fullDaoNodeOpt =
parser.accepts("fullDaoNode", "If set to true the node requests the blockchain data via RPC requests " +
"from Bitcoin Core and provide the validated BSQ txs to the network. It requires that the " +
"other RPC properties are set as well.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> logLevelOpt =
parser.accepts(LOG_LEVEL, "Set logging level")
.withRequiredArg()
.ofType(String.class)
.describedAs("OFF|ALL|ERROR|WARN|INFO|DEBUG|TRACE")
.defaultsTo(Level.INFO.levelStr);
ArgumentAcceptingOptionSpec<String> referralIdOpt =
parser.accepts(REFERRAL_ID, "Optional Referral ID (e.g. for API users or pro market makers)")
.withRequiredArg()
.ofType(String.class)
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> useDevModeOpt =
parser.accepts(USE_DEV_MODE,
"Enables dev mode which is used for convenience for developer testing")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> useDevPrivilegeKeysOpt =
parser.accepts(USE_DEV_PRIVILEGE_KEYS, "If set to true all privileged features requiring a private " +
"key to be enabled are overridden by a dev key pair (This is for developers only!)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> dumpStatisticsOpt =
parser.accepts(DUMP_STATISTICS, "If set to true dump trade statistics to a json file in appDataDir")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Integer> maxMemoryOpt =
parser.accepts("maxMemory", "Max. permitted memory (used only by headless versions)")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(1200);
ArgumentAcceptingOptionSpec<Boolean> ignoreDevMsgOpt =
parser.accepts(IGNORE_DEV_MSG, "If set to true all signed " +
"network_messages from bisq developers are ignored (Global " +
"alert, Version update alert, Filters for offers, nodes or " +
"trading account data)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> providersOpt =
parser.accepts(PROVIDERS, "List custom providers")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> seedNodesOpt =
parser.accepts(SEED_NODES, "Override hard coded seed nodes as comma separated list e.g. " +
"'rxdkppp3vicnbgqt.onion:8002,mfla72c4igh5ta2t.onion:8002'")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> banListOpt =
parser.accepts(BAN_LIST, "Nodes to exclude from network connections.")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<Boolean> useLocalhostForP2POpt =
parser.accepts(USE_LOCALHOST_FOR_P2P, "Use localhost P2P network for development")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Integer> maxConnectionsOpt =
parser.accepts(MAX_CONNECTIONS, "Max. connections a peer will try to keep")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(12);
ArgumentAcceptingOptionSpec<String> socks5ProxyBtcAddressOpt =
parser.accepts(SOCKS_5_PROXY_BTC_ADDRESS, "A proxy address to be used for Bitcoin network.")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> socks5ProxyHttpAddressOpt =
parser.accepts(SOCKS_5_PROXY_HTTP_ADDRESS,
"A proxy address to be used for Http requests (should be non-Tor)")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torrcFileOpt =
parser.accepts(TORRC_FILE, "An existing torrc-file to be sourced for Tor. Note that torrc-entries, " +
"which are critical to Bisq's correct operation, cannot be overwritten.")
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
ArgumentAcceptingOptionSpec<String> torrcOptionsOpt =
parser.accepts(TORRC_OPTIONS, "A list of torrc-entries to amend to Bisq's torrc. Note that " +
"torrc-entries, which are critical to Bisq's flawless operation, cannot be overwritten. " +
"[torrc options line, torrc option, ...]")
.withRequiredArg()
.withValuesConvertedBy(RegexMatcher.regex("^([^\\s,]+\\s[^,]+,?\\s*)+$"))
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> torControlPortOpt =
parser.accepts(TOR_CONTROL_PORT,
"The control port of an already running Tor service to be used by Bisq.")
.availableUnless(TORRC_FILE, TORRC_OPTIONS)
.withRequiredArg()
.ofType(int.class)
.describedAs("port");
ArgumentAcceptingOptionSpec<String> torControlPasswordOpt =
parser.accepts(TOR_CONTROL_PASSWORD, "The password for controlling the already running Tor service.")
.availableIf(TOR_CONTROL_PORT)
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torControlCookieFileOpt =
parser.accepts(TOR_CONTROL_COOKIE_FILE, "The cookie file for authenticating against the already " +
"running Tor service. Use in conjunction with --" + TOR_CONTROL_USE_SAFE_COOKIE_AUTH)
.availableIf(TOR_CONTROL_PORT)
.availableUnless(TOR_CONTROL_PASSWORD)
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
OptionSpecBuilder torControlUseSafeCookieAuthOpt =
parser.accepts(TOR_CONTROL_USE_SAFE_COOKIE_AUTH,
"Use the SafeCookie method when authenticating to the already running Tor service.")
.availableIf(TOR_CONTROL_COOKIE_FILE);
OptionSpecBuilder torStreamIsolationOpt =
parser.accepts(TOR_STREAM_ISOLATION, "Use stream isolation for Tor [experimental!].");
ArgumentAcceptingOptionSpec<Integer> msgThrottlePerSecOpt =
parser.accepts("msgThrottlePerSec", "Message throttle per sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 40MB/sec or 5 mbit/sec
.defaultsTo(200);
ArgumentAcceptingOptionSpec<Integer> msgThrottlePer10SecOpt =
parser.accepts("msgThrottlePer10Sec", "Message throttle per 10 sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 20MB/sec or 2.5 mbit/sec
.defaultsTo(1000);
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleTriggerOpt =
parser.accepts("sendMsgThrottleTrigger", "Time in ms when we trigger a sleep if 2 messages are sent")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(20); // Time in ms when we trigger a sleep if 2 messages are sent
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleSleepOpt =
parser.accepts("sendMsgThrottleSleep", "Pause in ms to sleep if we get too many messages to send")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(50); // Pause in ms to sleep if we get too many messages to send
try {
OptionSet cliOpts = parser.parse(args);
if (cliOpts.has(helpOpt))
throw new HelpRequested(parser);
CompositeOptionSet options = new CompositeOptionSet();
options.addOptionSet(cliOpts);
File configFile = null;
final boolean cliHasConfigFileOpt = cliOpts.has(configFileOpt);
boolean configFileHasBeenProcessed = false;
if (cliHasConfigFileOpt) {
configFile = new File(cliOpts.valueOf(configFileOpt));
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
if (configFileOpts.isPresent()) {
options.addOptionSet(configFileOpts.get());
configFileHasBeenProcessed = true;
}
}
this.appName = options.valueOf(appNameOpt);
this.userDataDir = options.valueOf(userDataDirOpt);
this.appDataDir = options.has(appDataDirOpt) ?
options.valueOf(appDataDirOpt) :
new File(this.userDataDir, this.appName);
CURRENT_APP_DATA_DIR = appDataDir;
if (!configFileHasBeenProcessed) {
configFile = cliHasConfigFileOpt && !configFile.isAbsolute() ?
new File(this.appDataDir, configFile.getPath()) : // TODO: test
new File(this.appDataDir, DEFAULT_CONFIG_FILE_NAME);
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, parser, helpOpt, configFileOpt);
configFileOpts.ifPresent(options::addOptionSet);
}
this.configFile = configFile;
this.nodePort = options.valueOf(nodePortOpt);
this.bannedBtcNodes = options.valuesOf(bannedBtcNodesOpt);
this.bannedPriceRelayNodes = options.valuesOf(bannedPriceRelayNodesOpt);
this.bannedSeedNodes = options.valuesOf(bannedSeedNodesOpt);
this.baseCurrencyNetwork = (BaseCurrencyNetwork) options.valueOf(baseCurrencyNetworkOpt);
BaseCurrencyNetwork.CURRENT_NETWORK = baseCurrencyNetwork;
BaseCurrencyNetwork.CURRENT_PARAMETERS = baseCurrencyNetwork.getParameters();
this.ignoreLocalBtcNode = options.valueOf(ignoreLocalBtcNodeOpt);
this.bitcoinRegtestHost = options.valueOf(bitcoinRegtestHostOpt);
this.daoActivated = options.valueOf(daoActivatedOpt) || !baseCurrencyNetwork.isMainnet();
this.fullDaoNode = options.valueOf(fullDaoNodeOpt);
this.logLevel = options.valueOf(logLevelOpt);
this.torrcFile = options.has(torrcFileOpt) ? options.valueOf(torrcFileOpt).toFile() : null;
this.torrcOptions = options.valueOf(torrcOptionsOpt);
this.torControlPort = options.has(torControlPortOpt) ? options.valueOf(torControlPortOpt) : NULL_INT;
this.torControlPassword = options.valueOf(torControlPasswordOpt);
this.torControlCookieFile = options.has(torControlCookieFileOpt) ?
options.valueOf(torControlCookieFileOpt).toFile() : null;
this.useTorControlSafeCookieAuth = options.has(torControlUseSafeCookieAuthOpt);
this.torStreamIsolation = options.has(torStreamIsolationOpt);
this.referralId = options.valueOf(referralIdOpt);
this.useDevMode = options.valueOf(useDevModeOpt);
this.useDevPrivilegeKeys = options.valueOf(useDevPrivilegeKeysOpt);
this.dumpStatistics = options.valueOf(dumpStatisticsOpt);
this.maxMemory = options.valueOf(maxMemoryOpt);
this.ignoreDevMsg = options.valueOf(ignoreDevMsgOpt);
this.providers = options.valuesOf(providersOpt);
this.seedNodes = options.valuesOf(seedNodesOpt);
this.banList = options.valuesOf(banListOpt);
this.useLocalhostForP2P = options.valueOf(useLocalhostForP2POpt);
this.maxConnections = options.valueOf(maxConnectionsOpt);
this.socks5ProxyBtcAddress = options.valueOf(socks5ProxyBtcAddressOpt);
this.socks5ProxyHttpAddress = options.valueOf(socks5ProxyHttpAddressOpt);
this.msgThrottlePerSec = options.valueOf(msgThrottlePerSecOpt);
this.msgThrottlePer10Sec = options.valueOf(msgThrottlePer10SecOpt);
this.sendMsgThrottleTrigger = options.valueOf(sendMsgThrottleTriggerOpt);
this.sendMsgThrottleSleep = options.valueOf(sendMsgThrottleSleepOpt);
// Preserve log output from now-removed ConnectionConfig class TODO: remove
log.info("ConnectionConfig{\n" +
" msgThrottlePerSec={},\n msgThrottlePer10Sec={},\n" +
" sendMsgThrottleTrigger={},\n sendMsgThrottleSleep={}\n}",
msgThrottlePerSec, msgThrottlePer10Sec, sendMsgThrottleTrigger, sendMsgThrottleSleep);
} catch (OptionException ex) {
throw new ConfigException(format("problem parsing option '%s': %s",
ex.options().get(0),
ex.getCause() != null ?
ex.getCause().getMessage() :
ex.getMessage()));
}
File btcNetworkDir = new File(appDataDir, baseCurrencyNetwork.name().toLowerCase());
if (!btcNetworkDir.exists())
btcNetworkDir.mkdir();
this.torDir = new File(btcNetworkDir, "tor");
this.walletDir = btcNetworkDir;
this.storageDir = new File(btcNetworkDir, "db");
this.keyStorageDir = new File(btcNetworkDir, "keys");
}
private Optional<OptionSet> parseOptionsFrom(File file, OptionParser parser, OptionSpec<?>... disallowedOpts) {
if (!file.isAbsolute() || !file.exists())
return Optional.empty();
ConfigFileReader configFileReader = new ConfigFileReader(file);
String[] optionLines = configFileReader.getOptionLines().stream()
.map(o -> "--" + o) // prepend dashes expected by jopt parser below
.collect(toList())
.toArray(new String[]{});
OptionSet configFileOpts = parser.parse(optionLines);
for (OptionSpec<?> disallowedOpt : disallowedOpts)
if (configFileOpts.has(disallowedOpt))
throw new IllegalArgumentException(
format("The '%s' option is disallowed in config files", disallowedOpt.options().get(0)));
return Optional.of(configFileOpts);
}
public String getDefaultAppName() {
return defaultAppName;
}
public File getDefaultUserDataDir() {
if (Utilities.isWindows())
return new File(System.getenv("APPDATA"));
if (Utilities.isOSX())
return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toFile();
// *nix
return Paths.get(System.getProperty("user.home"), ".local", "share").toFile();
}
public File getDefaultAppDataDir() {
return defaultAppDataDir;
}
public File getDefaultConfigFile() {
return defaultConfigFile;
}
public File getConfigFile() {
return configFile;
}
public String getAppName() {
return appName;
}
public File getUserDataDir() {
return userDataDir;
}
public File getAppDataDir() {
return appDataDir;
}
public int getNodePort() {
return nodePort;
}
public List<String> getBannedBtcNodes() {
return bannedBtcNodes;
}
public List<String> getBannedPriceRelayNodes() {
return bannedPriceRelayNodes;
}
public List<String> getBannedSeedNodes() {
return bannedSeedNodes;
}
public BaseCurrencyNetwork getBaseCurrencyNetwork() {
return baseCurrencyNetwork;
}
public boolean isIgnoreLocalBtcNode() {
return ignoreLocalBtcNode;
}
public String getBitcoinRegtestHost() {
return bitcoinRegtestHost;
}
public boolean isDaoActivated() {
return daoActivated;
}
public boolean isFullDaoNode() {
return fullDaoNode;
}
public String getLogLevel() {
return logLevel;
}
public boolean isLocalBitcoinNodeIsRunning() {
return localBitcoinNodeIsRunning;
}
public void setLocalBitcoinNodeIsRunning(boolean value) {
this.localBitcoinNodeIsRunning = value;
}
public String getReferralId() {
return referralId;
}
public boolean isUseDevMode() {
return useDevMode;
}
public File getTorDir() {
return torDir;
}
public File getWalletDir() {
return walletDir;
}
public File getStorageDir() {
return storageDir;
}
public File getKeyStorageDir() {
return keyStorageDir;
}
public boolean isUseDevPrivilegeKeys() {
return useDevPrivilegeKeys;
}
public boolean isDumpStatistics() {
return dumpStatistics;
}
public int getMaxMemory() {
return maxMemory;
}
public boolean isIgnoreDevMsg() {
return ignoreDevMsg;
}
public List<String> getProviders() {
return providers;
}
public List<String> getSeedNodes() {
return seedNodes;
}
public List<String> getBanList() {
return banList;
}
public boolean isUseLocalhostForP2P() {
return useLocalhostForP2P;
}
public int getMaxConnections() {
return maxConnections;
}
public String getSocks5ProxyBtcAddress() {
return socks5ProxyBtcAddress;
}
public String getSocks5ProxyHttpAddress() {
return socks5ProxyHttpAddress;
}
public File getTorrcFile() {
return torrcFile;
}
public String getTorrcOptions() {
return torrcOptions;
}
public int getTorControlPort() {
return torControlPort;
}
public String getTorControlPassword() {
return torControlPassword;
}
public File getTorControlCookieFile() {
return torControlCookieFile;
}
public boolean isUseTorControlSafeCookieAuth() {
return useTorControlSafeCookieAuth;
}
public boolean isTorStreamIsolation() {
return torStreamIsolation;
}
public int getMsgThrottlePerSec() {
return msgThrottlePerSec;
}
public int getMsgThrottlePer10Sec() {
return msgThrottlePer10Sec;
}
public int getSendMsgThrottleTrigger() {
return sendMsgThrottleTrigger;
}
public int getSendMsgThrottleSleep() {
return sendMsgThrottleSleep;
}
}
|
package org.javers.core.diff.custom;
import org.javers.common.reflection.ReflectionUtil;
import org.javers.core.diff.ListCompareAlgorithm;
import org.javers.core.metamodel.object.InstanceId;
import org.javers.core.metamodel.type.ValueType;
public interface CustomValueComparator<T> {
/**
* Called by Javers to compare two Values.
*
* @param a not null if {@link #handlesNulls()} returns false
* @param b not null if {@link #handlesNulls()} returns false
*/
boolean equals(T a, T b);
String toString(T value);
/**
* This flag is used to indicate to Javers whether
* a comparator implementation wants to handle nulls.
* <br /><br />
*
* By default, the flag is <b>false</b> and Javers
* checks if both values are non-null before calling a comparator.
* <br/>
* If any of given values is null — Javers compares them using the
* standard Java logic:
* <ul>
* <li>null == null</li>
* <li>null != non-null</li>
* </ul>
*
* <br/>
*
* If the flag is <b>true</b> — Javers skips that logic and
* allows a comparator to handle nulls on its own.
* In that case, a comparator holds responsibility for null-safety.
*
* @see NullAsBlankStringComparator
*/
default boolean handlesNulls() {
return false;
}
}
|
package org.ccnx.ccn.test;
import java.security.DigestOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Random;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.UserConfiguration;
import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.impl.security.crypto.util.SignatureHelper;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.io.NullOutputStream;
import org.ccnx.ccn.profiles.SegmentationProfile;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* This is not a unit test designed to verify functionality.
* Instead, this test times some operations for basic benchmarking.
* @author jthornto
*
*/
public class BenchmarkTest {
public static final int NUM_ITER = 1000;
public static final int NUM_KEYGEN = 100; // Key generation is really slow
public static final double NanoToMilli = 1000000.0d;
public static CCNTestHelper testHelper = new CCNTestHelper(BenchmarkTest.class);
public static ContentName testName;
public static byte[] shortPayload;
public static byte[] longPayload;
public abstract class Operation<T> {
abstract Object execute(T input) throws Exception;
int size(T input) {
if (null == input) {
return -1;
} else if (input instanceof byte[]) {
return ((byte[])input).length;
} else if (input instanceof ContentObject) {
return ((ContentObject)input).content().length;
} else {
throw new RuntimeException("Unsupported input type " + input.getClass());
}
}
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ContentName namespace = testHelper.getTestNamespace("benchmarkTest");
testName = ContentName.fromNative(namespace, "BenchmarkObject");
testName = VersioningProfile.addVersion(testName);
shortPayload = ("this is sample segment content").getBytes();
longPayload = new byte[1000];
Random rnd = new Random();
rnd.nextBytes(longPayload);
System.out.println("Benchmark Test starting on " + System.getProperty("os.name"));
}
@SuppressWarnings("unchecked")
public void runBenchmark(String desc, Operation op, Object input) throws Exception {
runBenchmark(NUM_ITER, desc, op, input);
}
@SuppressWarnings("unchecked")
public void runBenchmark(int count, String desc, Operation op, Object input) throws Exception {
long start = System.nanoTime();
op.execute(input);
long dur = System.nanoTime() - start;
//System.out.println("Start " + start + " dur " + dur);
int size = op.size(input);
System.out.println("Initial time to " + desc + (size >= 0 ? " (payload " + op.size(input) + " bytes)" : "") + " = " + dur/NanoToMilli + " ms.");
start = System.nanoTime();
for (int i=0; i<count; i++) {
op.execute(input);
}
dur = System.nanoTime() - start;
System.out.println("Avg. to " + desc + " (" + count + " iterations) = " + dur/count/NanoToMilli + " ms.");
}
@Test
public void testDigest() throws Exception {
System.out.println("==== Digests");
Operation<byte[]> digest = new Operation<byte[]>() {
Object execute(byte[] input) throws Exception {
MessageDigest md = MessageDigest.getInstance(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM);
md.update(input);
return md.digest();
}
};
System.out.println("--- Raw = digest only of byte[]");
runBenchmark("raw digest short", digest, shortPayload);
runBenchmark("raw digest long", digest, longPayload);
ContentName segment = SegmentationProfile.segmentName(testName, 0);
Operation<ContentObject> digestObj = new Operation<ContentObject>() {
Object execute(ContentObject input) throws Exception {
MessageDigest md = MessageDigest.getInstance(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM);
DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), md);
input.encode(dos);
return md.digest();
}
};
System.out.println("--- Object = digest of ContentObject");
ContentObject shortObj = ContentObject.buildContentObject(segment, shortPayload, null, null, SegmentationProfile.getSegmentNumberNameComponent(0));
ContentObject longObj = ContentObject.buildContentObject(segment, longPayload, null, null, SegmentationProfile.getSegmentNumberNameComponent(0));
runBenchmark("obj digest short", digestObj, shortObj);
runBenchmark("obj digest long", digestObj, longObj);
}
@Test
public void testRawSigning() throws Exception {
Operation<byte[]> sign = new Operation<byte[]>() {
KeyManager keyManager = KeyManager.getDefaultKeyManager();
PrivateKey signingKey = keyManager.getDefaultSigningKey();
Object execute(byte[] input) throws Exception {
return SignatureHelper.sign(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, input, signingKey);
}
};
System.out.println("==== PK Signing");
runBenchmark("sign short", sign, shortPayload);
runBenchmark("sign long", sign, longPayload);
byte[] sigShort = (byte[])sign.execute(shortPayload);
byte[] sigLong = (byte[])sign.execute(longPayload);
Operation<Tuple<byte[],byte[]>> verify = new Operation<Tuple<byte[],byte[]>>() {
KeyManager keyManager = KeyManager.getDefaultKeyManager();
PublicKey pubKey = keyManager.getDefaultPublicKey();
Object execute(Tuple<byte[],byte[]> input) throws Exception {
return SignatureHelper.verify(input.first(), input.second(), CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, pubKey);
}
int size(Tuple<byte[], byte[]> input) {
return input.first().length;
}
};
System.out.println("==== PK Verifying");
runBenchmark("verify short", verify, new Tuple<byte[],byte[]>(shortPayload, sigShort));
runBenchmark("verify long", verify, new Tuple<byte[],byte[]>(longPayload, sigLong));
}
@Test
public void testKeyGen() throws Exception {
final KeyPairGenerator kpg = KeyPairGenerator.getInstance(UserConfiguration.defaultKeyAlgorithm());
kpg.initialize(UserConfiguration.defaultKeyLength());
Operation<Object> genpair = new Operation<Object>() {
Object execute(Object input) throws Exception {
KeyPair userKeyPair = kpg.generateKeyPair();
return userKeyPair;
}
};
System.out.println("==== Key Generation: " + UserConfiguration.defaultKeyLength() + "-bit " + UserConfiguration.defaultKeyAlgorithm() + " key.");
runBenchmark(NUM_KEYGEN, "generate keypair", genpair, null);
}
}
|
package com.googlecode.jslint4java;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
public class JSLintThreadSafetyTest {
private static final String JS = "var a = 'lint this'";
@Test
public void canRunSameInstanceInMultipleThreads() throws Exception {
final JSLint lint = new JSLintBuilder().fromDefault();
final AtomicReference<Exception> kaboom = new AtomicReference<Exception>();
// Check that the first one works.
lint.lint("foo1", JS);
Thread t = new Thread(new Runnable() {
public void run() {
try {
// Now check it still works in a different thread.
lint.lint("foo2", JS);
} catch (Exception e) {
kaboom.set(e);
}
}
});
t.start();
t.join();
if (kaboom.get() == null) {
assertTrue("LGTM", true);
} else {
// Wrap so that this test gets mentioned in the stack trace.
throw new RuntimeException(kaboom.get());
}
}
@Test
public void canBuildInDifferentThread() throws Exception {
final JSLintBuilder builder = new JSLintBuilder();
final AtomicReference<Exception> kaboom = new AtomicReference<Exception>();
Thread t = new Thread(new Runnable() {
public void run() {
try {
JSLint lint = builder.fromDefault();
lint.lint("blort.js", JS);
} catch (Exception e) {
kaboom.set(e);
}
}
});
t.start();
t.join();
if (kaboom.get() == null) {
assertTrue("LGTM", true);
} else {
// Wrap for stack trace.
throw new RuntimeException(kaboom.get());
}
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.plaf.basic.BasicProgressBarUI;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
JProgressBar progress1 = new JProgressBar() {
@Override public void updateUI() {
super.updateUI();
setUI(new ProgressCircleUI());
setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
}
};
progress1.setForeground(new Color(0xAA_FF_AA_AA, true));
JProgressBar progress2 = new JProgressBar() {
@Override public void updateUI() {
super.updateUI();
setUI(new ProgressCircleUI());
setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
}
};
progress2.setStringPainted(true);
progress2.setFont(progress2.getFont().deriveFont(24f));
JSlider slider = new JSlider();
slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE);
progress1.setModel(slider.getModel());
JButton button = new JButton("start");
button.addActionListener(e -> {
JButton b = (JButton) e.getSource();
b.setEnabled(false);
SwingWorker<String, Void> worker = new BackgroundTask() {
@Override public void done() {
if (b.isDisplayable()) {
b.setEnabled(true);
}
}
};
worker.addPropertyChangeListener(new ProgressListener(progress2));
worker.execute();
});
JPanel p = new JPanel(new GridLayout(1, 2));
p.add(progress1);
p.add(progress2);
add(slider, BorderLayout.NORTH);
add(p);
add(button, BorderLayout.SOUTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ProgressCircleUI extends BasicProgressBarUI {
@Override public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
@Override public void paint(Graphics g, JComponent c) {
// Insets b = progressBar.getInsets(); // area for border
// int barRectWidth = progressBar.getWidth() - b.right - b.left;
// int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
// if (barRectWidth <= 0 || barRectHeight <= 0) {
// return;
Rectangle rect = SwingUtilities.calculateInnerArea(progressBar, null);
if (rect.isEmpty()) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double degree = 360d * progressBar.getPercentComplete();
double sz = Math.min(rect.width, rect.height);
double cx = rect.getCenterX();
double cy = rect.getCenterY();
double or = sz * .5;
double ir = or * .5;
Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2d, ir * 2d);
Shape outer = new Ellipse2D.Double(cx - or, cy - or, sz, sz);
Shape sector = new Arc2D.Double(cx - or, cy - or, sz, sz, 90d - degree, degree, Arc2D.PIE);
Area foreground = new Area(sector);
Area background = new Area(outer);
Area hole = new Area(inner);
foreground.subtract(hole);
background.subtract(hole);
// draw the track
g2.setPaint(new Color(0xDD_DD_DD));
g2.fill(background);
// draw the circular sector
// AffineTransform at = AffineTransform.getScaleInstance(-1.0, 1.0);
// at.translate(-(barRectWidth + b.left * 2), 0);
// AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(degree), cx, cy);
// g2.fill(at.createTransformedShape(area));
g2.setPaint(progressBar.getForeground());
g2.fill(foreground);
g2.dispose();
// Deal with possible text painting
if (progressBar.isStringPainted()) {
Insets ins = progressBar.getInsets();
paintString(g, rect.x, rect.y, rect.width, rect.height, 0, ins);
}
}
// @Override protected Color getSelectionForeground() {
// return Color.GREEN; // Not used in ProgressCircleUI
// @Override protected Color getSelectionBackground() {
// return Color.RED; // a progress string color
}
class BackgroundTask extends SwingWorker<String, Void> {
@Override public String doInBackground() throws InterruptedException {
int current = 0;
int lengthOfTask = 100;
while (current <= lengthOfTask && !isCancelled()) {
Thread.sleep(50); // dummy task
setProgress(100 * current / lengthOfTask);
current++;
}
return "Done";
}
}
class ProgressListener implements PropertyChangeListener {
private final JProgressBar progressBar;
protected ProgressListener(JProgressBar progressBar) {
this.progressBar = progressBar;
this.progressBar.setValue(0);
}
@Override public void propertyChange(PropertyChangeEvent e) {
String strPropertyName = e.getPropertyName();
if ("progress".equals(strPropertyName)) {
progressBar.setIndeterminate(false);
int progress = (Integer) e.getNewValue();
progressBar.setValue(progress);
}
}
}
|
package com.annimon.jecp.me;
import com.annimon.jecp.ApplicationListener;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
/**
*
* @author aNNiMON
*/
public class JecpCanvas extends Canvas {
private final ApplicationListener listener;
private final DrawingThread thread;
private final Image image;
private final JecpGraphics graphics;
public JecpCanvas(ApplicationListener listener) {
this.listener = listener;
setFullScreenMode(true);
int width = getWidth();
int height = getHeight();
image = Image.createImage(width, height);
Graphics g = image.getGraphics();
graphics = new JecpGraphics(g);
listener.onStartApp(width, height);
thread = new DrawingThread();
thread.keepRunning = true;
thread.start();
}
protected void paint(Graphics g) {
listener.onPaint(graphics);
g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
}
protected void keyPressed(int keyCode) {
}
protected void keyReleased(int keyCode) {
}
protected void keyRepeated(int keyCode) {
}
protected void pointerDragged(int x, int y) {
}
protected void pointerPressed(int x, int y) {
}
protected void pointerReleased(int x, int y) {
}
private class DrawingThread extends Thread {
private boolean keepRunning = true;
public void run() {
while (keepRunning) {
repaint();
try {
Thread.sleep(5L);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
}
|
package org.junit.platform.runner;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static org.junit.platform.commons.meta.API.Usage.Maintained;
import static org.junit.platform.engine.discovery.ClassNameFilter.STANDARD_INCLUDE_PATTERN;
import static org.junit.platform.engine.discovery.ClassNameFilter.includeClassNamePatterns;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
import static org.junit.platform.engine.discovery.PackageNameFilter.excludePackageNames;
import static org.junit.platform.engine.discovery.PackageNameFilter.includePackageNames;
import static org.junit.platform.launcher.EngineFilter.excludeEngines;
import static org.junit.platform.launcher.EngineFilter.includeEngines;
import static org.junit.platform.launcher.TagFilter.excludeTags;
import static org.junit.platform.launcher.TagFilter.includeTags;
import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.junit.platform.commons.meta.API;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.Filterable;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
/**
* JUnit 4 based {@link Runner} which runs tests on the JUnit Platform in a
* JUnit 4 environment.
*
* <p>Annotating a class with {@code @RunWith(JUnitPlatform.class)} allows it
* to be run with IDEs and build systems that support JUnit 4 but do not yet
* support the JUnit Platform directly.
*
* <p>Consult the various annotations in this package for configuration options.
*
* <p>If you do not use any configuration annotations from this package, you
* can simply use this runner on a test class whose programming model is
* supported on the JUnit Platform — for example, a JUnit Jupiter test class.
* Note, however, that any test class run with this runner must be {@code public}
* in order to be picked up by IDEs and build tools.
*
* <p>When used on a class that serves as a test suite and the
* {@link IncludeClassNamePatterns @IncludeClassNamePatterns} annotation is not
* present, the default include pattern {@code "^.*Tests?$"} will be used in order
* to avoid loading classes unnecessarily (see {@link
* org.junit.platform.engine.discovery.ClassNameFilter#STANDARD_INCLUDE_PATTERN
* ClassNameFilter#STANDARD_INCLUDE_PATTERN}).
*
* @since 1.0
* @see SelectPackages
* @see SelectClasses
* @see IncludeClassNamePatterns
* @see IncludeTags
* @see ExcludeTags
* @see IncludeEngines
* @see ExcludeEngines
* @see UseTechnicalNames
*/
@API(Maintained)
public class JUnitPlatform extends Runner implements Filterable {
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final String EMPTY_STRING = "";
private final Class<?> testClass;
private final Launcher launcher;
private LauncherDiscoveryRequest discoveryRequest;
private JUnitPlatformTestTree testTree;
public JUnitPlatform(Class<?> testClass) throws InitializationError {
this(testClass, LauncherFactory.create());
}
// For testing only
JUnitPlatform(Class<?> testClass, Launcher launcher) throws InitializationError {
this.launcher = launcher;
this.testClass = testClass;
this.discoveryRequest = createDiscoveryRequest();
this.testTree = generateTestTree();
}
@Override
public Description getDescription() {
return this.testTree.getSuiteDescription();
}
@Override
public void run(RunNotifier notifier) {
JUnitPlatformRunnerListener listener = new JUnitPlatformRunnerListener(this.testTree, notifier);
this.launcher.registerTestExecutionListeners(listener);
this.launcher.execute(this.discoveryRequest);
}
private JUnitPlatformTestTree generateTestTree() {
Preconditions.notNull(this.discoveryRequest, "DiscoveryRequest must not be null");
TestPlan plan = this.launcher.discover(this.discoveryRequest);
return new JUnitPlatformTestTree(plan, testClass);
}
private LauncherDiscoveryRequest createDiscoveryRequest() {
List<DiscoverySelector> selectors = getSelectorsFromAnnotations();
// Allows to simply add @RunWith(JUnitPlatform.class) to any test case
boolean isSuite = !selectors.isEmpty();
if (!isSuite) {
selectors.add(selectClass(this.testClass));
}
LauncherDiscoveryRequestBuilder requestBuilder = request().selectors(selectors);
addFiltersFromAnnotations(requestBuilder, isSuite);
return requestBuilder.build();
}
private void addFiltersFromAnnotations(LauncherDiscoveryRequestBuilder requestBuilder, boolean isSuite) {
addIncludeClassNamePatternFilter(requestBuilder, isSuite);
addIncludePackagesFilter(requestBuilder);
addExcludePackagesFilter(requestBuilder);
addIncludedTagsFilter(requestBuilder);
addExcludedTagsFilter(requestBuilder);
addIncludedEnginesFilter(requestBuilder);
addExcludedEnginesFilter(requestBuilder);
}
private List<DiscoverySelector> getSelectorsFromAnnotations() {
List<DiscoverySelector> selectors = new ArrayList<>();
selectors.addAll(transform(getSelectedClasses(), DiscoverySelectors::selectClass));
selectors.addAll(transform(getSelectedPackageNames(), DiscoverySelectors::selectPackage));
return selectors;
}
private <T> List<DiscoverySelector> transform(T[] sourceElements, Function<T, DiscoverySelector> transformer) {
return stream(sourceElements).map(transformer).collect(toList());
}
private void addIncludeClassNamePatternFilter(LauncherDiscoveryRequestBuilder requestBuilder, boolean isSuite) {
String[] patterns = getIncludeClassNamePatterns(isSuite);
if (patterns.length > 0) {
requestBuilder.filters(includeClassNamePatterns(patterns));
}
}
private void addIncludePackagesFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] includedPackages = getIncludedPackages();
if (includedPackages.length > 0) {
requestBuilder.filters(includePackageNames(includedPackages));
}
}
private void addExcludePackagesFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] excludedPackages = getExcludedPackages();
if (excludedPackages.length > 0) {
requestBuilder.filters(excludePackageNames(excludedPackages));
}
}
private void addIncludedTagsFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] includedTags = getIncludedTags();
if (includedTags.length > 0) {
requestBuilder.filters(includeTags(includedTags));
}
}
private void addExcludedTagsFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] excludedTags = getExcludedTags();
if (excludedTags.length > 0) {
requestBuilder.filters(excludeTags(excludedTags));
}
}
private void addIncludedEnginesFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] engineIds = getIncludedEngineIds();
if (engineIds.length > 0) {
requestBuilder.filters(includeEngines(engineIds));
}
}
private void addExcludedEnginesFilter(LauncherDiscoveryRequestBuilder requestBuilder) {
String[] engineIds = getExcludedEngineIds();
if (engineIds.length > 0) {
requestBuilder.filters(excludeEngines(engineIds));
}
}
private Class<?>[] getSelectedClasses() {
return getValueFromAnnotation(SelectClasses.class, SelectClasses::value, EMPTY_CLASS_ARRAY);
}
private String[] getSelectedPackageNames() {
return getValueFromAnnotation(SelectPackages.class, SelectPackages::value, EMPTY_STRING_ARRAY);
}
private String[] getIncludedPackages() {
return getValueFromAnnotation(IncludePackages.class, IncludePackages::value, EMPTY_STRING_ARRAY);
}
private String[] getExcludedPackages() {
return getValueFromAnnotation(ExcludePackages.class, ExcludePackages::value, EMPTY_STRING_ARRAY);
}
private String[] getIncludedTags() {
return getValueFromAnnotation(IncludeTags.class, IncludeTags::value, EMPTY_STRING_ARRAY);
}
private String[] getExcludedTags() {
return getValueFromAnnotation(ExcludeTags.class, ExcludeTags::value, EMPTY_STRING_ARRAY);
}
private String[] getIncludedEngineIds() {
return getValueFromAnnotation(IncludeEngines.class, IncludeEngines::value, EMPTY_STRING_ARRAY);
}
private String[] getExcludedEngineIds() {
return getValueFromAnnotation(ExcludeEngines.class, ExcludeEngines::value, EMPTY_STRING_ARRAY);
}
private String[] getIncludeClassNamePatterns(boolean isSuite) {
String[] patterns = getIncludeClassNamePatterns();
if (patterns.length == 0 && isSuite) {
return new String[] { STANDARD_INCLUDE_PATTERN };
}
Preconditions.containsNoNullElements(patterns, "IncludeClassNamePatterns must not contain null elements");
trim(patterns);
return patterns;
}
private void trim(String[] patterns) {
for (int i = 0; i < patterns.length; i++) {
patterns[i] = patterns[i].trim();
}
}
@SuppressWarnings("deprecation")
private String[] getIncludeClassNamePatterns() {
String[] patterns = getValueFromAnnotation(IncludeClassNamePatterns.class, IncludeClassNamePatterns::value,
new String[0]);
String patternFromDeprecatedAnnotation = getValueFromAnnotation(IncludeClassNamePattern.class,
IncludeClassNamePattern::value, EMPTY_STRING);
Preconditions.condition(patterns.length == 0 || patternFromDeprecatedAnnotation.isEmpty(),
"You must not specify both @IncludeClassNamePattern and @IncludeClassNamePatterns");
if (patterns.length == 0 && !patternFromDeprecatedAnnotation.isEmpty()) {
patterns = new String[] { patternFromDeprecatedAnnotation };
}
return patterns;
}
private <A extends Annotation, V> V getValueFromAnnotation(Class<A> annotationClass, Function<A, V> extractor,
V defaultValue) {
A annotation = this.testClass.getAnnotation(annotationClass);
return (annotation != null ? extractor.apply(annotation) : defaultValue);
}
@Override
public void filter(Filter filter) throws NoTestsRemainException {
Set<TestIdentifier> filteredIdentifiers = testTree.getFilteredLeaves(filter);
if (filteredIdentifiers.isEmpty()) {
throw new NoTestsRemainException();
}
this.discoveryRequest = createDiscoveryRequestForUniqueIds(filteredIdentifiers);
this.testTree = generateTestTree();
}
private LauncherDiscoveryRequest createDiscoveryRequestForUniqueIds(Set<TestIdentifier> testIdentifiers) {
// @formatter:off
List<DiscoverySelector> selectors = testIdentifiers.stream()
.map(TestIdentifier::getUniqueId)
.map(DiscoverySelectors::selectUniqueId)
.collect(toList());
// @formatter:on
return request().selectors(selectors).build();
}
}
|
package me.eddiep.minecraft.ls.system.bank;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class BankInventory {
private static HashMap<Player, BankInventory> INSTANCERS = new HashMap<Player, BankInventory>();
private Inventory inventory;
private int offset = 0;
private List<ItemStack> items;
private BankInventory() { }
public static BankInventory create(Player p, List<ItemStack> items) {
int slotSize = 9;
while (items.size() > slotSize) {
slotSize += 9;
}
slotSize += 9;
slotSize = Math.min(slotSize, 54);
Inventory inventory = Bukkit.createInventory(null, slotSize, "Bank");
for (int i = 0; i < slotSize; i++) {
if (i >= items.size())
break;
if (i == 53 || i == 45)
continue;
ItemStack item = items.get(i);
inventory.setItem(i, item);
}
if (slotSize == 54) {
ItemStack item = new ItemStack(Material.EMERALD_BLOCK, 1);
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(ChatColor.GREEN + "Next Page ->"));
item.setItemMeta(meta);
inventory.setItem(53, item);
}
BankInventory sinventory = new BankInventory();
sinventory.inventory = inventory;
sinventory.items = items;
INSTANCERS.put(p, sinventory);
return sinventory;
}
public static BankInventory from(Player p) {
if (INSTANCERS.containsKey(p))
return INSTANCERS.get(p);
return null;
}
public void nextPage() {
if (offset + 45 >= items.size())
return;
saveItems();
offset += 45;
updateView();
}
public void previousPage() {
if (offset - 45 < 0)
return;
saveItems();
offset -= 45;
updateView();
}
private void saveItems() {
for (int i = offset; i < offset + inventory.getSize(); i++) {
if (i == 45 || i == 53)
continue;
if (i >= items.size()) {
if (inventory.getItem(i % 54) != null) {
this.items.add(inventory.getItem(i % 54));
}
} else {
if (inventory.getItem(i % 54) == null) {
this.items.remove(i);
} else {
this.items.set(i, inventory.getItem(i % 54));
}
}
}
}
public void updateView() {
inventory.clear();
for (int i = offset; i < offset + 45; i++) {
if (i >= items.size())
break;
ItemStack item = items.get(i);
inventory.setItem(i % 54, item);
}
if (offset + 45 < items.size()) {
ItemStack item = new ItemStack(Material.EMERALD_BLOCK, 1);
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(ChatColor.GREEN + "Next Page ->"));
item.setItemMeta(meta);
inventory.setItem(53, item);
}
if (offset != 0) {
ItemStack item = new ItemStack(Material.EMERALD_BLOCK, 1);
ItemMeta meta = item.getItemMeta();
meta.setLore(Collections.singletonList(ChatColor.GREEN + "<- Previous Page"));
item.setItemMeta(meta);
inventory.setItem(45, item);
}
for (HumanEntity p : inventory.getViewers()) {
if (p instanceof Player) {
((Player)p).updateInventory();
}
}
}
public Inventory openFor(Player p) {
p.openInventory(inventory);
return inventory;
}
public boolean isNextPageButton(ItemStack stack) {
if (stack == null)
return false;
if (stack.getItemMeta() == null)
return false;
if (stack.getItemMeta().getLore() != null) {
for (String lore : stack.getItemMeta().getLore()) {
if (lore.equals(ChatColor.GREEN + "Next Page ->"))
return true;
}
}
return false;
}
public boolean isPreviousPageButton(ItemStack stack) {
if (stack == null)
return false;
if (stack.getItemMeta() == null)
return false;
if (stack.getItemMeta().getLore() != null) {
for (String lore : stack.getItemMeta().getLore()) {
if (lore.equals(ChatColor.GREEN + "<- Previous Page"))
return true;
}
}
return false;
}
public void end(Player p) {
saveItems();
INSTANCERS.remove(p);
}
public List<ItemStack> getItems() {
return items;
}
}
|
package liquibase.structure.core;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.logging.LogFactory;
import liquibase.servicelocator.ServiceLocator;
import liquibase.structure.DatabaseObject;
import liquibase.util.StringUtils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DatabaseObjectFactory {
private static DatabaseObjectFactory instance;
private Set<Class<? extends DatabaseObject>> standardTypes;
public static synchronized DatabaseObjectFactory getInstance() {
if (instance == null) {
instance = new DatabaseObjectFactory();
}
return instance;
}
private DatabaseObjectFactory() {
}
public Set<Class<? extends DatabaseObject>> parseTypes(String typesString) {
if (StringUtils.trimToNull(typesString) == null) {
return getStandardTypes();
} else {
Set<Class<? extends DatabaseObject>> returnSet = new HashSet<Class<? extends DatabaseObject>>();
Set<String> typesToInclude = new HashSet<String>(Arrays.asList(typesString.toLowerCase().split("\\s*,\\s*")));
Set<String> typesNotFound = new HashSet<String>(typesToInclude);
Class<? extends DatabaseObject>[] classes = ServiceLocator.getInstance().findClasses(DatabaseObject.class);
for (Class<? extends DatabaseObject> clazz : classes) {
if (typesToInclude.contains(clazz.getSimpleName().toLowerCase())
|| typesToInclude.contains(clazz.getSimpleName().toLowerCase()+"s")
|| typesToInclude.contains(clazz.getSimpleName().toLowerCase()+"es") //like indexes
) {
returnSet.add(clazz);
typesNotFound.remove(clazz.getSimpleName().toLowerCase());
typesNotFound.remove(clazz.getSimpleName().toLowerCase()+"s");
typesNotFound.remove(clazz.getSimpleName().toLowerCase()+"es");
}
}
if (typesNotFound.size() > 0) {
throw new UnexpectedLiquibaseException("Unknown snapshot type(s) "+StringUtils.join(typesNotFound, ", "));
}
return returnSet;
}
}
public Set<Class<? extends DatabaseObject>> getStandardTypes() {
if (standardTypes == null) {
Set<Class<? extends DatabaseObject>> set = new HashSet<Class<? extends DatabaseObject>>();
Class<? extends DatabaseObject>[] classes = ServiceLocator.getInstance().findClasses(DatabaseObject.class);
for (Class<? extends DatabaseObject> clazz : classes) {
try {
if (clazz.newInstance().snapshotByDefault()) {
set.add(clazz);
}
} catch (Exception e) {
LogFactory.getLogger().info("Cannot construct "+clazz.getName()+" to determine if it should be included in the snapshot by default");
}
}
standardTypes = set;
}
return standardTypes;
}
public void reset() {
this.standardTypes = null;
}
}
|
public class Runner {
public interface OutputListener {
void print(String message);
}
private boolean draw = false;
private boolean error = false;
private boolean silent = false;
private String errorLog = "";
private OutputListener listener;
private long start;
public Runner(OutputListener listener) {
this.listener = listener;
}
public void start(boolean silent) {
start = System.currentTimeMillis();
this.silent = silent;
}
public void stop() {
if (silent) return;
if (error) {
listener.print("\n" + errorLog);
listener.print("\nBUILD FAILED\n");
} else {
listener.print("\nBUILD SUCCESFULL\n");
}
long end = (System.currentTimeMillis() - start) / 1000;
if (end > 59) {
end = end / 60;
if (end > 59) listener.print("Total time: " + end / 60 + " hours\n");
else listener.print("Total time: " + end + " minutes\n");
} else {
listener.print("Total time: " + end + " seconds\n");
}
System.exit(error ? -1 : 0);
}
public void warn(String msg) {
listener.print("\n" + msg + "\n");
}
public void error(Exception e) {
error = true;
errorLog += e.getMessage() + "\n";
}
public void finish() {
draw = false;
if (error) stop();
}
}
|
package com.axelor.contact.web;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.contact.db.Address;
import com.axelor.contact.db.Company;
import com.axelor.contact.db.Contact;
import com.axelor.contact.db.Country;
import com.axelor.contact.db.repo.CountryRepository;
import com.axelor.contact.service.HelloService;
import com.axelor.inject.Beans;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.meta.schema.actions.ActionView.ActionViewBuilder;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.common.base.Joiner;
import com.google.inject.persist.Transactional;
public class HelloController {
protected Logger log = LoggerFactory.getLogger(getClass());
@Inject
private HelloService service;
public void say(ActionRequest request, ActionResponse response) {
Contact contact = request.getContext().asType(Contact.class);
String message = service.say(contact);
if (contact.getAddresses() != null) {
int total = contact.getAddresses().size();
int selected = 0;
for (Address it : contact.getAddresses()) {
if(it.isSelected()) { selected++; }
}
message += "<br>" + String.format("You have selected %s record(s) from total %s address records.", selected, total);
}
log.info("send greetings to: ${contact.fullName}");
response.setFlash(message);
}
public void about(ActionRequest request, ActionResponse response) {
Address address = request.getContext().asType(Address.class);
Contact contact = request.getContext().getParent().asType(Contact.class);
String name = contact.getFullName();
if (name == null) { name = contact.getFirstName(); }
String message = "Where are you from ?";
if (address.getCountry() != null)
message = String.format("'%s' is a beautiful country!", address.getCountry().getName());
if (name != null) { message = String.format("Welcome '%s'...</br>", name) + message; }
response.setFlash(message);
}
public void guessEmail(ActionRequest request, ActionResponse response) {
Contact contact = request.getContext().asType(Contact.class);
if (contact.getEmail() == null) {
String email = Joiner.on(".").skipNulls().join(contact.getFirstName(), contact.getLastName()) + "@gmail.com";
List<Address> addresses = createAddresses();
response.setValue("email", email.toLowerCase());
response.setValue("addresses", addresses);
}
}
private List<Address> createAddresses() {
Country frCountry = Beans.get(CountryRepository.class).all().filter("self.code = ?", "FR").fetchOne();
if (frCountry == null) {
frCountry = createDefaultCountry();
}
return Arrays.asList(
new Address("My", "Home", "Paris", frCountry),
new Address("My", "Office", "Paris", frCountry)
);
}
@Transactional
protected Country createDefaultCountry() {
log.debug("creating a Country record: { code: \"FR\", name: \"France\"}");
Country frCountry = new Country("FR", "France");
return Beans.get(CountryRepository.class).save(frCountry);
}
public void showHomePage(ActionRequest request, ActionResponse response) {
response.setView(ActionView.define("Axelor.com")
.add("html" , "http:
.map());
}
public void showCompanyList(ActionRequest request, ActionResponse response) {
Contact contact = request.getContext().asType(Contact.class);
ActionViewBuilder builder = ActionView.define("All Companies").model(Company.class.getName());
if (contact.getCompany() != null) {
builder.domain("self.code = '" + contact.getCompany().getCode() + "' OR self.parent.code = '" + contact.getCompany().getCode() + "'");
}
response.setView(builder.map());
}
}
|
package org.wso2.balana.attr;
import org.wso2.balana.ParsingException;
import org.wso2.balana.UnknownIdentifierException;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.Node;
/**
* This is a basic implementation of <code>AttributeFactory</code>. It implements the insertion and
* retrieval methods, but doesn't actually setup the factory with any datatypes.
* <p>
* Note that while this class is thread-safe on all creation methods, it is not safe to add support
* for a new datatype while creating an instance of a value. This follows from the assumption that
* most people will initialize these factories up-front, and then start processing without ever
* modifying the factories. If you need these mutual operations to be thread-safe, then you should
* write a wrapper class that implements the right synchronization.
*
* @since 1.2
* @author Seth Proctor
*/
public class BaseAttributeFactory extends AttributeFactory {
// the map of proxies
private HashMap attributeMap;
/**
* Default constructor.
*/
public BaseAttributeFactory() {
attributeMap = new HashMap();
}
public BaseAttributeFactory(Map attributes) {
attributeMap = new HashMap();
Iterator it = attributes.keySet().iterator();
while (it.hasNext()) {
try {
String id = (it.next()).toString();
AttributeProxy proxy = (AttributeProxy) (attributes.get(id));
attributeMap.put(id, proxy);
} catch (ClassCastException cce) {
throw new IllegalArgumentException("an element of the map "
+ "was not an instance of " + "AttributeProxy");
}
}
}
/**
* Adds a proxy to the factory, which in turn will allow new attribute types to be created using
* the factory. Typically the proxy is provided as an anonymous class that simply calls the
* getInstance methods (or something similar) of some <code>AttributeValue</code> class.
*
* @param id the name of the attribute type
* @param proxy the proxy used to create new attributes of the given type
*/
public void addDatatype(String id, AttributeProxy proxy) {
// make sure this doesn't already exist
if (attributeMap.containsKey(id))
throw new IllegalArgumentException("datatype already exists");
attributeMap.put(id, proxy);
}
/**
* Returns the datatype identifiers supported by this factory.
*
* @return a <code>Set</code> of <code>String</code>s
*/
public Set getSupportedDatatypes() {
return Collections.unmodifiableSet(attributeMap.keySet());
}
/**
* Creates a value based on the given DOM root node. The type of the attribute is assumed to be
* present in the node as an XACML attribute named <code>DataType</code>, as is the case with
* the AttributeValueType in the policy schema. The value is assumed to be the first child of
* this node.
*
* @param root the DOM root of an attribute value
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type in the node isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root) throws UnknownIdentifierException,
ParsingException {
Node node = root.getAttributes().getNamedItem("DataType");
return createValue(root, node.getNodeValue());
}
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param dataType the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root, URI dataType) throws UnknownIdentifierException,
ParsingException {
return createValue(root, dataType.toString());
}
/**
* Creates a value based on the given DOM root node and data type.
*
* @param root the DOM root of an attribute value
* @param type the type of the attribute
*
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the type isn't known to the factory
* @throws ParsingException if the node is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(Node root, String type) throws UnknownIdentifierException,
ParsingException {
AttributeValue attributeValue;
AttributeProxy proxy = (AttributeProxy) (attributeMap.get(type));
if (proxy != null) {
try {
attributeValue = proxy.getInstance(root);
} catch (Exception e) {
throw new ParsingException("couldn't create " + type
+ " attribute based on DOM node");
}
} else {
throw new UnknownIdentifierException("Attributes of type " + type
+ " aren't supported.");
}
if (attributeValue == null) {
throw new ParsingException("Invalid request. Couldn't create " + type + " attribute based on DOM node");
}
return attributeValue;
}
/**
* Creates a value based on the given data type and text-encoded value. Used primarily by code
* that does an XPath query to get an attribute value, and then needs to turn the resulting
* value into an Attribute class.
*
* @param dataType the type of the attribute
* @param value the text-encoded representation of an attribute's value
* @param params additional parameters that need to creates a value
* @return a new <code>AttributeValue</code>
*
* @throws UnknownIdentifierException if the data type isn't known to the factory
* @throws ParsingException if the text is invalid or can't be parsed by the appropriate proxy
*/
public AttributeValue createValue(URI dataType, String value, String[] params)
throws UnknownIdentifierException, ParsingException {
String type = dataType.toString();
AttributeProxy proxy = (AttributeProxy) (attributeMap.get(type));
if (proxy != null) {
try {
return proxy.getInstance(value, params);
} catch (Exception e) {
throw new ParsingException("couldn't create " + type + " attribute from input: "
+ value);
}
} else {
throw new UnknownIdentifierException("Attributes of type " + type
+ " aren't supported.");
}
}
}
|
package testcase;
import static org.junit.Assert.*;
import org.junit.Test;
import chessGame.ChessMonitoringSystem;
import chessGame.ChessPlayer;
import chessGame.GameMode;
import chessGame.RankScoringMode;
import chessGame.ScoringMode;
public class TestRankScoringMode {
private ChessMonitoringSystem chessMonitoringSystem = ChessMonitoringSystem.getInstance();
private GameMode mode = new RankScoringMode();
@Test
public void testAddLittleScore() {
ChessPlayer p1=new ChessPlayer("a", 0);
int[] scoreRelated={100, 0};
mode.addScore(p1, scoreRelated);
int result = p1.getPlayerScore();
assertEquals(result,80);
}
@Test
public void testAddSameScore() {
ChessPlayer p1=new ChessPlayer("a", 0);
int[] scoreRelated={100, 2};
mode.addScore(p1, scoreRelated);
int result = p1.getPlayerScore();
assertEquals(100, result);
}
@Test
public void testAddHigherScore() {
ChessPlayer p1=new ChessPlayer("a", 0);
int[] scoreRelated={100, 1};
mode.addScore(p1, scoreRelated);
int result = p1.getPlayerScore();
assertEquals(120, result);
}
//test print Result
@Test
public void testPrintResultPlayer1Win() {
ChessPlayer p1=new ChessPlayer("a", 0);
ChessPlayer p2=new ChessPlayer("b", 1);
int[] scoreRelated={100, 0};
mode.addScore(p1, scoreRelated);
String winner = mode.printResult(p1, p2);
assertEquals(winner,"a"+ " is the winner!" + "\n" + "winner's score: 80");
}
@Test
public void testPrintResultPlayer2Win() {
ChessPlayer p1=new ChessPlayer("a", 0);
ChessPlayer p2=new ChessPlayer("b", 1);
int[] scoreRelated={100, 0};
mode.addScore(p2, scoreRelated);
String winner = mode.printResult(p1, p2);
assertEquals(winner,"b"+ " is the winner!" + "\n" + "winner's score: 80");
}
@Test
public void testPrintResultDraw() {
ChessPlayer p1=new ChessPlayer("a", 0);
ChessPlayer p2=new ChessPlayer("b", 1);
String winner = mode.printResult(p1, p2);
assertEquals(winner,"Draw!");
}
}
|
package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.table.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
String[] columnNames = {"String", "Integer", "Boolean"};
Object[][] data = {
{"aaa", 12, true}, {"bbb", 5, false},
{"CCC", 92, true}, {"DDD", 0, false}
};
TableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(new JTable(model)), new JScrollPane(new JTree()));
JRadioButton r0 = new JRadioButton("0.0", true);
r0.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
sp.setResizeWeight(0d);
}
});
JRadioButton r1 = new JRadioButton("0.5");
r1.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
sp.setResizeWeight(.5);
}
});
JRadioButton r2 = new JRadioButton("1.0");
r2.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
sp.setResizeWeight(1d);
}
});
ButtonGroup bg = new ButtonGroup();
JPanel p = new JPanel();
p.add(new JLabel("JSplitPane#setResizeWeight: "));
for (JRadioButton r: Arrays.asList(r0, r1, r2)) {
bg.add(r);
p.add(r);
}
add(p, BorderLayout.NORTH);
add(sp);
setPreferredSize(new Dimension(320, 240));
EventQueue.invokeLater(() -> {
sp.setDividerLocation(.5);
//sp.setResizeWeight(.5);
});
}
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);
}
}
|
/* A Karapostolakis, B Lit, G Smith
* 2017-06-09
* A basic survival RPG */
package com.surviveandthrive;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class SurviveAndThrive implements InputProcessor, Screen {
int[] backgroundLayers = {0};
int[] foregroundLayers = {1};
SpriteBatch batch;
Sprite sprite;
Player testPlayer;
Texture img;
TiledMap map;
OrthographicCamera cam;
TiledMapRenderer mapRenderer;
MapObjects objects;
List<Interactable> treeObjects;
List<Interactable> rockObjects;
List<Interactable> mapObjects;
String itemType, itemName, recipe;
int foodValue;
Item[][] items;
int readInIndex = 0;
TiledMapTileLayer trees;
//player coordinates, tile size, and player location within the tile
int playerX, playerY, tileWidth, tileHeight, tilePosX, tilePosY;
TiledMapTileLayer layer;
//arrays to hold the tiles surrounding the player
Cell[][] cell = new Cell[3][3];
TiledMapTile[][] tile = new TiledMapTile[3][3];
MainGame game;
boolean hasSword;
Inventory screen1;
public SurviveAndThrive(MainGame g) {
game = g;
batch = new SpriteBatch();
testPlayer = new Player();
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
//set up the map and camera
cam = new OrthographicCamera();
cam.setToOrtho(false, w, h);
map = new TmxMapLoader().load("takethree.tmx");
//scale the map
mapRenderer = new OrthogonalTiledMapRenderer(map, 4 / 1f);
Gdx.input.setInputProcessor(this);
//set player size and position
testPlayer.setSize(48, 70);
testPlayer.setPosition(5276, 5256);
cam.translate(5000, 5000);
//get some map properties for later
layer = (TiledMapTileLayer) map.getLayers().get("Tile Layer 1");
tileWidth = (int) layer.getTileWidth();
tileHeight = (int) layer.getTileHeight();
//read item data from file
readInItems();
screen1 = new Inventory(items, game, this);
//load object layer from tilemap
objects = map.getLayers().get("Object Layer 1").getObjects();
//store all trees and rocks in lists
treeObjects = new ArrayList<>();
rockObjects = new ArrayList<>();
mapObjects = new ArrayList<>();
//loop through all mapobjects, add to list
for (int i = 0; i < objects.getCount(); i++) {
Interactable obj = new Interactable((RectangleMapObject) objects.get(i));
obj.setName(obj.getProperties().get("name", String.class));
mapObjects.add(obj);
}
}
/**
* Renders the canvas.
* @param f
*/
@Override
public void render(float f) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//update the camera
cam.update();
mapRenderer.setView(cam);
batch.setProjectionMatrix(cam.combined);
//draw the background
mapRenderer.render(backgroundLayers);
batch.begin();
batch.enableBlending();
//draw the player
testPlayer.draw(batch);
batch.end();
//draw the foreground
mapRenderer.render(foregroundLayers);
//get player location, both on the map, and within the specific tile
playerX = (int) testPlayer.getX() / tileWidth / 4;
playerY = (int) testPlayer.getY() / tileHeight / 4;
tilePosX = (int) testPlayer.getX() % 60 / 4;
tilePosY = (int) testPlayer.getY() % 60 / 4;
//cell the player is on
cell[1][1] = layer.getCell(playerX, playerY);
tile[1][1] = cell[1][1].getTile();
//above
cell[1][0] = layer.getCell(playerX, playerY + 1);
tile[1][0] = cell[1][0].getTile();
//below
cell[1][2] = layer.getCell(playerX, playerY - 1);
tile[1][2] = cell[1][2].getTile();
//left
cell[0][1] = layer.getCell(playerX - 1, playerY);
tile[0][1] = cell[0][1].getTile();
//right
cell[2][1] = layer.getCell(playerX + 1, playerY);
tile[2][1] = cell[2][1].getTile();
//top left
cell[0][0] = layer.getCell(playerX - 1, playerY + 1);
tile[0][0] = cell[0][0].getTile();
//top right
cell[2][0] = layer.getCell(playerX + 1, playerY + 1);
tile[2][0] = cell[2][0].getTile();
//bottom left
cell[0][2] = layer.getCell(playerX - 1, playerY - 1);
tile[0][2] = cell[0][2].getTile();
//bottom right
cell[2][2] = layer.getCell(playerX + 1, playerY - 1);
tile[2][2] = cell[2][2].getTile();
//if statements get key input
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
//make sure the player isnt running into any water tiles
if (!(tile[0][1].getProperties().containsKey("water") && tilePosX <= 1)) {
//move player and camera
cam.translate(-4, 0);
testPlayer.translateX(-4);
}
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
//make sure the player isnt running into any water tiles
if (!(tile[2][1].getProperties().containsKey("water") && (tilePosX + 11) <= 15)) {
//move player and camera
cam.translate(4, 0);
testPlayer.translateX(4);
}
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
//make sure the player isnt running into any water tiles
if (!(tile[1][2].getProperties().containsKey("water") && tilePosY <= 1)) {
//check the tile next to the player as well so that they dont appear to be walking on water
if (!((tilePosX > 4 && tilePosY <= 1) && tile[2][2].getProperties().containsKey("water"))) {
//move player and camera
cam.translate(0, -4);
testPlayer.translateY(-4);
}
}
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
//make sure the player isnt running into any water tiles
if (!(tile[1][0].getProperties().containsKey("water") && tilePosY <= 12)) {
//check the tile next to the player as well so that they dont appear to be walking on water
if (!((tilePosX > 4 && tilePosY <= 12) && tile[2][0].getProperties().containsKey("water"))) {
//move player and camera
cam.translate(0, 4);
testPlayer.translateY(4);
}
}
}
//if the users pressed E
if (Gdx.input.isKeyJustPressed(Input.Keys.E)) {
//switches to the inventory screen
screen1.updateInventory(items);
game.setScreen(new Inventory(items, game, this));
}
//if the user pressed ESC
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
//switches to the pause menu
game.setScreen(new PauseMenu(testPlayer, items, game, this));
}
}
/**
* Causes the player to interact with the nearest object.
*
* @return Whether the interaction succeeded
*/
public boolean interact() {
//check each object in the map
for (int i = 0; i < mapObjects.size(); i++) {
//check whether distance is less than 100 pixels in either direction
if (distance(testPlayer, mapObjects.get(i).getRectangle()) <= 100) {
//check if object has resources left
if (mapObjects.get(i).interact()) {
//trigger object interaction
//check if item is already present in inventory
for (int j = 0; j < items.length; j++) {
for (int k = 0; k < items[j].length; k++) {
//check if current item matches original
if (items[j][k] != null && mapObjects.get(i).getName().equals(items[j][k].getName())) {
System.out.println(mapObjects.get(i).getName() + " found at index [" + j + "][" + k + "]");
//add item to matching inventory slot
items[j][k].addItem(1);
return true;
}
}
}
//item not present in inventory, place in first empty slot
/*for (int j = 0; j < items.length; j++) {
for (int k = 0; k < items[j].length; k++) {
if (items[j][k] == null) {
//place in slot
items[j][k] = new Resource(mapObjects.get(i).getName(), 1);
}
}
}*/
} else {
//display message
JOptionPane.showMessageDialog(null, "This resource has been exhausted.");
}
}
}
return false;
}
/**
* Calculates the distance between a player and a rectangle.
*
* @param player The Player to check distance for
* @param obj The Rectangle to check distance for
* @return The largest orthogonal distance between the Player and the
* Rectangle
*/
public double distance(Player player, Rectangle obj) {
//get centres of objects
double playerX = player.getX() + (player.getWidth() / 2.0);
double playerY = player.getY() + (player.getHeight() / 2.0);
double objX = (obj.getX() + (obj.getWidth() / 2.0)) * 4.0;
double objY = (obj.getY() + (obj.getHeight() / 2.0)) * 4.0;
//get distances in each direction
double xDist = Math.abs(playerX - objX);
double yDist = Math.abs(playerY - objY);
//return larger distance
return Math.max(xDist, yDist);
}
@Override
public void dispose() {
batch.dispose();
}
/**
* Reads in item data from a the file ItemRecipes.txt.
*/
public void readInItems() {
int ResourceIndex = 0;
int FoodIndex = 0;
int ToolIndex = 0;
FileHandle itemsFile = Gdx.files.internal("ItemRecipes.txt");
String test = itemsFile.readString();
String itemData[] = test.split("\n");
//Format for new Items:
//Type of Item
//Name
//Special attributes to the item
//Item 1 to craft
//amount of Item 1
//Item 2 to craft
//amount of Item 2
//etc. will continue until program reads in:
//End
//When the program reads DONE it means that there are no more items to read in
items = new Item[5][10];
for (int i = 0; i < 10; i++) {
itemType = itemData[readInIndex].trim();
readInIndex++;
if (itemType.equals("DONE")) {
break;
}
if (itemType.equals("Resource")) {
itemName = itemData[readInIndex].trim();
readInIndex++;
items[0][ResourceIndex] = new Resource(itemName, 0);
ResourceIndex++;
} else if (itemType.equals("Food")) {
itemName = itemData[readInIndex].trim();
readInIndex++;
foodValue = Integer.parseInt(itemData[readInIndex].trim());
readInIndex++;
recipe = itemData[readInIndex].trim();
readInIndex++;
items[1][FoodIndex] = new Food(itemName, 0, true, foodValue, recipe);
FoodIndex++;
} else if (itemType.equals("Tool")) {
itemName = itemData[readInIndex].trim();
readInIndex++;
recipe = itemData[readInIndex].trim();
readInIndex++;
items[2][ToolIndex] = new Tools(itemName, 0, recipe);
ToolIndex++;
}
}
}
@Override
public boolean keyDown(int keycode) {
boolean added = false;
if (keycode == Input.Keys.SPACE) {
//interact with closest object
interact();
//check if the user has a sword
for(int i = 0; i < 4; i++){
for(int j = 0; j < 7; j++){
if(items[i][j] != null && items[i][j].getName().equals("Sword")){
//if they do, set hasSword to true, if not make sure it is false
hasSword = true;
}else{
hasSword = false;
}
}
}
//check if the player is in a meadow
if(tile[1][1].getProperties().containsKey("meadow") && hasSword){
//if they are look for the rest of the rabbits in their inventory, and add another one
for(int i = 0; i < 4; i++){
for(int j = 0; j < 7; j++){
if(items[i][j] != null && items[i][j].getName().equals("Rabbit")){
items[i][j].addItem(1);
added = true;
System.out.println("got rabbit");
}
}
}
}
return true;
}
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
@Override
public void resize(int i, int i1) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void show() {
}
@Override
public void hide() {
}
}
|
package edu.umich.verdict.dbms;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.spark.sql.DataFrame;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import edu.umich.verdict.VerdictConf;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.datatypes.SampleParam;
import edu.umich.verdict.datatypes.SampleSizeInfo;
import edu.umich.verdict.datatypes.TableUniqueName;
import edu.umich.verdict.exceptions.VerdictException;
import edu.umich.verdict.relation.ExactRelation;
import edu.umich.verdict.relation.Relation;
import edu.umich.verdict.relation.SingleRelation;
import edu.umich.verdict.relation.expr.Expr;
import edu.umich.verdict.util.VerdictLogger;
/**
* This class is responsible for choosing a right DBMS class.
*/
public abstract class Dbms {
protected final String dbName;
protected Optional<String> currentSchema;
protected VerdictContext vc;
public VerdictContext getVc() {
return vc;
}
public void setVc(VerdictContext vc) {
this.vc = vc;
}
public String getDbName() {
return dbName;
}
public void setCurrentSchema(Optional<String> currentSchema) {
this.currentSchema = currentSchema;
}
/**
* Copy constructor for not sharing the underlying statement.
* @param another
*/
public Dbms(Dbms another) {
dbName = another.dbName;
currentSchema = another.currentSchema;
vc = another.vc;
}
protected Dbms(VerdictContext vc, String dbName) {
this.vc = vc;
this.dbName = dbName;
currentSchema = Optional.absent();
}
public static Dbms from(VerdictContext vc, VerdictConf conf) throws VerdictException {
Dbms dbms = Dbms.getInstance(
vc,
conf.getDbms(),
conf.getHost(),
conf.getPort(),
conf.getDbmsSchema(),
(conf.ignoreUserCredentials())? "" : conf.getUser(),
(conf.ignoreUserCredentials())? "" : conf.getPassword(),
conf.getDbmsClassName());
Set<String> jdbcDbmsNames = Sets.newHashSet("mysql", "impala", "hive", "hive2");
if (jdbcDbmsNames.contains(conf.getDbms())) {
VerdictLogger.info(
(conf.getDbmsSchema() != null) ?
String.format("Connected to database: %s//%s:%s/%s",
conf.getDbms(), conf.getHost(), conf.getPort(), conf.getDbmsSchema())
: String.format("Connected to database: %s
conf.getDbms(), conf.getHost(), conf.getPort()));
}
return dbms;
}
protected static Dbms getInstance(VerdictContext vc,
String dbName,
String host,
String port,
String schema,
String user,
String password,
String jdbcClassName) throws VerdictException {
Dbms dbms = null;
if (dbName.equals("mysql")) {
dbms = new DbmsMySQL(vc, dbName, host, port, schema, user, password, jdbcClassName);
} else if (dbName.equals("impala")) {
dbms = new DbmsImpala(vc, dbName, host, port, schema, user, password, jdbcClassName);
} else if (dbName.equals("hive") || dbName.equals("hive2")) {
dbms = new DbmsHive(vc, dbName, host, port, schema, user, password, jdbcClassName);
} else if (dbName.equals("dummy")) {
dbms = new DbmsDummy(vc);
} else {
String msg = String.format("Unsupported DBMS: %s", dbName);
VerdictLogger.error("Dbms", msg);
throw new VerdictException(msg);
}
return dbms;
}
public String getName() {
return dbName;
}
public Optional<String> getCurrentSchema() {
return currentSchema;
}
public ResultSet executeJdbcQuery(String sql) throws VerdictException {
execute(sql);
ResultSet rs = getResultSet();
return rs;
}
public DataFrame executeSparkQuery(String sql) throws VerdictException {
execute(sql);
DataFrame rs = getDataFrame();
return rs;
}
public abstract boolean execute(String sql) throws VerdictException;
public abstract ResultSet getResultSet();
public abstract DataFrame getDataFrame();
public abstract void executeUpdate(String sql) throws VerdictException;
public void changeDatabase(String schemaName) throws VerdictException {
execute(String.format("use %s", schemaName));
currentSchema = Optional.fromNullable(schemaName);
VerdictLogger.info("Database changed to: " + schemaName);
}
public void createDatabase(String database) throws VerdictException {
createCatalog(database);
}
public void createCatalog(String catalog) throws VerdictException {
String sql = String.format("create database if not exists %s", catalog);
executeUpdate(sql);
}
public void dropTable(TableUniqueName tableName) throws VerdictException {
Set<String> databases = vc.getMeta().getDatabases();
// TODO: this is buggy when the database created while a query is executued.
// it can happen during sample creations.
if (!databases.contains(tableName.getSchemaName())) {
VerdictLogger.debug(this, String.format("Database, %s, does not exists. Verdict doesn't bother to run a drop table statement.", tableName.getSchemaName()));
return;
}
List<String> tables = getTables(tableName.getSchemaName());
if (!tables.contains(tableName.getTableName())) {
VerdictLogger.debug(this, String.format("Table, %s, does not exists. Verdict doesn't bother to run a drop table statement.", tableName));
return;
}
String sql = String.format("DROP TABLE IF EXISTS %s", tableName);
VerdictLogger.debug(this, String.format("Drops table: %s", sql));
executeUpdate(sql);
VerdictLogger.debug(this, tableName + " has been dropped.");
}
public void moveTable(TableUniqueName from, TableUniqueName to) throws VerdictException {
VerdictLogger.debug(this, String.format("Moves table %s to table %s", from, to));
String sql = String.format("CREATE TABLE %s AS SELECT * FROM %s", to, from);
dropTable(to);
executeUpdate(sql);
dropTable(from);
VerdictLogger.debug(this, "Moving table done.");
}
public List<Pair<String, String>> getAllTableAndColumns(String schema) throws VerdictException {
Set<String> databases = vc.getMeta().getDatabases();
if (!databases.contains(schema)) {
return Arrays.asList();
}
List<Pair<String, String>> tablesAndColumns = new ArrayList<Pair<String, String>>();
List<String> tables = getTables(schema);
for (String table : tables) {
Map<String, String> col2type = getColumns(TableUniqueName.uname(schema, table));
for (String column : col2type.keySet()) {
tablesAndColumns.add(Pair.of(table, column));
}
}
return tablesAndColumns;
}
public abstract Set<String> getDatabases() throws VerdictException;
public abstract List<String> getTables(String schema) throws VerdictException;
/**
* Retrieves the mapping from column name to its type for a given table.
* @param table
* @return
* @throws VerdictException
*/
public abstract Map<String, String> getColumns(TableUniqueName table) throws VerdictException;
public abstract void deleteEntry(TableUniqueName tableName, List<Pair<String, String>> colAndValues) throws VerdictException;
public abstract void insertEntry(TableUniqueName tableName, List<Object> values) throws VerdictException;
public abstract long getTableSize(TableUniqueName tableName) throws VerdictException;
public void createMetaTablesInDMBS(
TableUniqueName originalTableName,
TableUniqueName sizeTableName,
TableUniqueName nameTableName) throws VerdictException {
VerdictLogger.debug(this, "Creates meta tables if not exist.");
String sql = String.format("CREATE TABLE IF NOT EXISTS %s", sizeTableName)
+ " (schemaname STRING, "
+ " tablename STRING, "
+ " samplesize BIGINT, "
+ " originaltablesize BIGINT)";
executeUpdate(sql);
sql = String.format("CREATE TABLE IF NOT EXISTS %s", nameTableName)
+ " (originalschemaname STRING, "
+ " originaltablename STRING, "
+ " sampleschemaaname STRING, "
+ " sampletablename STRING, "
+ " sampletype STRING, "
+ " samplingratio DOUBLE, "
+ " columnnames STRING)";
executeUpdate(sql);
VerdictLogger.debug(this, "Meta tables created.");
}
public boolean doesMetaTablesExist(String schemaName) throws VerdictException {
String metaSchema = vc.getMeta().metaCatalogForDataCatalog(schemaName);
String metaNameTable = vc.getMeta().getMetaNameTableForOriginalSchema(schemaName).getTableName();
String metaSizeTable = vc.getMeta().getMetaSizeTableForOriginalSchema(schemaName).getTableName();
Set<String> tables = new HashSet<String>(getTables(metaSchema));
if (tables.contains(metaNameTable) && tables.contains(metaSizeTable)) {
return true;
} else {
return false;
}
}
public Pair<Long, Long> createUniformRandomSampleTableOf(SampleParam param) throws VerdictException {
dropTable(param.sampleTableName());
// justCreateUniformRandomSampleTableOf(param);
TableUniqueName temp = createUniformRandomSampledTable(param);
attachUniformProbabilityToTempTable(param, temp);
dropTable(temp);
return Pair.of(getTableSize(param.sampleTableName()), getTableSize(param.originalTable));
}
protected TableUniqueName createUniformRandomSampledTable(SampleParam param) throws VerdictException {
String whereClause = String.format("__rand < %f", param.samplingRatio);
ExactRelation sampled = SingleRelation.from(vc, param.getOriginalTable())
.select(String.format("*, %s as __rand", randomNumberExpression(param)))
.where(whereClause)
.select("*, " + randomPartitionColumn());
TableUniqueName temp = Relation.getTempTableName(vc, param.sampleTableName().getSchemaName());
String sql = String.format("create table %s as %s", temp, sampled.toSql());
VerdictLogger.debug(this, "The query used for creating a temporary table without sampling probabilities:");
VerdictLogger.debugPretty(this, Relation.prettyfySql(sql), " ");
executeUpdate(sql);
return temp;
}
protected void attachUniformProbabilityToTempTable(SampleParam param, TableUniqueName temp) throws VerdictException {
String samplingProbCol = vc.getDbms().samplingProbabilityColumnName();
long total_size = SingleRelation.from(vc, param.getOriginalTable()).countValue();
long sample_size = SingleRelation.from(vc, temp).countValue();
String parquetString="";
if(vc.getConf().areSamplesStoredAsParquet()) {
parquetString = getParquetString();
}
ExactRelation withRand = SingleRelation.from(vc, temp)
.select("*, " + String.format("%d / %d as %s", sample_size, total_size, samplingProbCol));
String sql = String.format("create table %s%s as %s", param.sampleTableName(), parquetString, withRand.toSql());
VerdictLogger.debug(this, "The query used for creating a temporary table without sampling probabilities:");
//VerdictLogger.debugPretty(this, Relation.prettyfySql(sql), " ");
VerdictLogger.debug(this, sql);
executeUpdate(sql);
}
public Pair<Long, Long> createStratifiedSampleTableOf(SampleParam param) throws VerdictException {
SampleSizeInfo info = vc.getMeta().getSampleSizeOf(new SampleParam(vc, param.originalTable, "uniform", null, new ArrayList<String>()));
if (info == null) {
String msg = "A uniform random must first be created before creating a stratified sample.";
VerdictLogger.error(this, msg);
throw new VerdictException(msg);
}
dropTable(param.sampleTableName());
TableUniqueName groupSizeTemp = createGroupSizeTempTable(param);
createStratifiedSampleFromGroupSizeTemp(param, groupSizeTemp);
dropTable(groupSizeTemp);
return Pair.of(getTableSize(param.sampleTableName()), getTableSize(param.originalTable));
}
private TableUniqueName createGroupSizeTempTable(SampleParam param) throws VerdictException {
TableUniqueName groupSizeTemp = Relation.getTempTableName(vc, param.sampleTableName().getSchemaName());
ExactRelation groupSize = SingleRelation.from(vc, param.originalTable)
.groupby(param.columnNames)
.agg("count(*) AS __group_size");
String sql = String.format("create table %s as %s", groupSizeTemp, groupSize.toSql());
VerdictLogger.debug(this, "The query used for the group-size temp table: ");
VerdictLogger.debugPretty(this, Relation.prettyfySql(sql), " ");
executeUpdate(sql);
return groupSizeTemp;
}
final protected long NULL_LONG = Long.MIN_VALUE + 1;
final protected String NULL_STRING = "VERDICT_NULL";
final protected String NULL_TIMESTAMP = "1970-01-02"; // unix timestamp starts on '1970-01-01'. We add one day just to avoid possible conlicts.
protected void createStratifiedSampleFromGroupSizeTemp(SampleParam param, TableUniqueName groupSizeTemp) throws VerdictException {
Map<String, String> col2types = vc.getMeta().getColumn2Types(param.originalTable);
SampleSizeInfo info = vc.getMeta().getSampleSizeOf(new SampleParam(vc, param.originalTable, "uniform", null, new ArrayList<String>()));
long originalTableSize = info.originalTableSize;
long groupCount = SingleRelation.from(vc, groupSizeTemp).countValue();
String samplingProbColName = vc.getDbms().samplingProbabilityColumnName();
// equijoin expression that considers possible null values
List<Pair<Expr, Expr>> joinExprs = new ArrayList<Pair<Expr, Expr>>();
for (String col : param.getColumnNames()) {
boolean isString = false;
boolean isTimeStamp = false;
if (col2types.containsKey(col)) {
if (col2types.get(col).toLowerCase().contains("char") || col2types.get(col).toLowerCase().contains("str")) {
isString = true;
} else if (col2types.get(col).toLowerCase().contains("time")) {
isTimeStamp = true;
}
}
if (isString) {
Expr left = Expr.from(String.format("case when s.%s is null then '%s' else s.%s end", col, NULL_STRING, col));
Expr right = Expr.from(String.format("case when t.%s is null then '%s' else t.%s end", col, NULL_STRING, col));
joinExprs.add(Pair.of(left, right));
} else if (isTimeStamp) {
Expr left = Expr.from(String.format("case when s.%s is null then '%s' else s.%s end", col, NULL_TIMESTAMP, col));
Expr right = Expr.from(String.format("case when t.%s is null then '%s' else t.%s end", col, NULL_TIMESTAMP, col));
joinExprs.add(Pair.of(left, right));
} else {
Expr left = Expr.from(String.format("case when s.%s is null then %d else s.%s end", col, NULL_LONG, col));
Expr right = Expr.from(String.format("case when t.%s is null then %d else t.%s end", col, NULL_LONG, col));
joinExprs.add(Pair.of(left, right));
}
}
// where clause using rand function
String whereClause = String.format("__rand < %d * %f / %d / __group_size",
originalTableSize,
param.getSamplingRatio(),
groupCount);
// aliased select list
List<String> selectElems = new ArrayList<String>();
for (String col : col2types.keySet()) {
selectElems.add(String.format("s.%s", col));
}
// sample table
TableUniqueName sampledNoRand = Relation.getTempTableName(vc, param.sampleTableName().getSchemaName());
ExactRelation sampled = SingleRelation.from(vc, param.getOriginalTable())
.select(String.format("*, %s as __rand", randomNumberExpression(param)))
.withAlias("s")
.join(SingleRelation.from(vc, groupSizeTemp).withAlias("t"), joinExprs)
.where(whereClause)
.select(Joiner.on(", ").join(selectElems) + ", __group_size");
String sql1 = String.format("create table %s as %s", sampledNoRand, sampled.toSql());
VerdictLogger.debug(this, "The query used for creating a stratified sample without sampling probabilities.");
VerdictLogger.debugPretty(this, Relation.prettyfySql(sql1), " ");
executeUpdate(sql1);
// attach sampling probabilities and random partition number
ExactRelation sampledGroupSize = SingleRelation.from(vc, sampledNoRand)
.groupby(param.columnNames)
.agg("count(*) AS __group_size_in_sample");
ExactRelation withRand = SingleRelation.from(vc, sampledNoRand).withAlias("s")
.join(sampledGroupSize.withAlias("t"), joinExprs)
.select(Joiner.on(", ").join(selectElems)
+ String.format(", __group_size_in_sample / __group_size as %s", samplingProbColName)
+ ", " + randomPartitionColumn());
String parquetString="";
if(vc.getConf().areSamplesStoredAsParquet()) {
parquetString = getParquetString();
}
String sql2 = String.format("create table %s%s as %s", param.sampleTableName(), parquetString, withRand.toSql());
VerdictLogger.debug(this, "The query used for creating a stratified sample with sampling probabilities.");
//VerdictLogger.debugPretty(this, Relation.prettyfySql(sql2), " ");
VerdictLogger.debug(this, sql2);
executeUpdate(sql2);
dropTable(sampledNoRand);
}
// protected abstract void justCreateStratifiedSampleTableof(SampleParam param) throws VerdictException;
public Pair<Long, Long> createUniverseSampleTableOf(SampleParam param) throws VerdictException {
dropTable(param.sampleTableName());
TableUniqueName temp = createUniverseSampledTable(param);
createUniverseSampleWithProbFromSample(param, temp);
dropTable(temp);
return Pair.of(getTableSize(param.sampleTableName()), getTableSize(param.originalTable));
}
protected TableUniqueName createUniverseSampledTable(SampleParam param) throws VerdictException {
TableUniqueName temp = Relation.getTempTableName(vc, param.sampleTableName().getSchemaName());
ExactRelation sampled = SingleRelation.from(vc, param.originalTable)
.where(modOfHash(param.columnNames.get(0), 1000000) +
String.format(" < %.2f", param.samplingRatio * 1000000));
String sql = String.format("create table %s AS %s", temp, sampled.toSql());
VerdictLogger.debug(this, "The query used for creating a universe sample without sampling probability:");
VerdictLogger.debugPretty(this, Relation.prettyfySql(sql), " ");
executeUpdate(sql);
return temp;
}
protected void createUniverseSampleWithProbFromSample(SampleParam param, TableUniqueName temp) throws VerdictException {
String samplingProbCol = vc.getDbms().samplingProbabilityColumnName();
ExactRelation sampled = SingleRelation.from(vc, temp);
long total_size = SingleRelation.from(vc, param.originalTable).countValue();
long sample_size = sampled.countValue();
ExactRelation withProb = sampled.select(
String.format("*, %d / %d AS %s", sample_size, total_size, samplingProbCol) + ", " +
randomPartitionColumn());
String parquetString="";
if(vc.getConf().areSamplesStoredAsParquet()) {
parquetString = getParquetString();
}
String sql = String.format("create table %s%s AS %s", param.sampleTableName(), parquetString, withProb.toSql());
VerdictLogger.debug(this, "The query used for creating a universe sample with sampling probability:");
//VerdictLogger.debugPretty(this, Relation.prettyfySql(sql), " ");
VerdictLogger.debug(this, sql);
executeUpdate(sql);
}
public void updateSampleNameEntryIntoDBMS(SampleParam param, TableUniqueName metaNameTableName) throws VerdictException {
TableUniqueName tempTableName = createTempTableExlucdingNameEntry(param, metaNameTableName);
insertSampleNameEntryIntoDBMS(param, tempTableName);
moveTable(tempTableName, metaNameTableName);
}
protected TableUniqueName createTempTableExlucdingNameEntry(SampleParam param, TableUniqueName metaNameTableName) throws VerdictException {
String metaSchema = param.sampleTableName().getSchemaName();
TableUniqueName tempTableName = Relation.getTempTableName(vc, metaSchema);
TableUniqueName originalTableName = param.originalTable;
executeUpdate(String.format("CREATE TABLE %s AS SELECT * FROM %s "
+ "WHERE originalschemaname <> \"%s\" OR originaltablename <> \"%s\" OR sampletype <> \"%s\""
+ "OR samplingratio <> %s OR columnnames <> \"%s\"",
tempTableName, metaNameTableName, originalTableName.getSchemaName(), originalTableName.getTableName(),
param.sampleType, samplingRatioToString(param.samplingRatio), columnNameListToString(param.columnNames)));
return tempTableName;
}
protected void insertSampleNameEntryIntoDBMS(SampleParam param, TableUniqueName metaNameTableName) throws VerdictException {
TableUniqueName originalTableName = param.originalTable;
TableUniqueName sampleTableName = param.sampleTableName();
List<Object> values = new ArrayList<Object>();
values.add(originalTableName.getSchemaName());
values.add(originalTableName.getTableName());
values.add(sampleTableName.getSchemaName());
values.add(sampleTableName.getTableName());
values.add(param.sampleType);
values.add(param.samplingRatio);
values.add(columnNameListToString(param.columnNames));
insertEntry(metaNameTableName, values);
}
public void updateSampleSizeEntryIntoDBMS(SampleParam param, long sampleSize, long originalTableSize, TableUniqueName metaSizeTableName) throws VerdictException {
TableUniqueName tempTableName = createTempTableExlucdingSizeEntry(param, metaSizeTableName);
insertSampleSizeEntryIntoDBMS(param, sampleSize, originalTableSize, tempTableName);
moveTable(tempTableName, metaSizeTableName);
}
protected TableUniqueName createTempTableExlucdingSizeEntry(SampleParam param, TableUniqueName metaSizeTableName) throws VerdictException {
String metaSchema = param.sampleTableName().getSchemaName();
TableUniqueName tempTableName = Relation.getTempTableName(vc, metaSchema);
TableUniqueName sampleTableName = param.sampleTableName();
executeUpdate(String.format("CREATE TABLE %s AS SELECT * FROM %s WHERE schemaname <> \"%s\" OR tablename <> \"%s\" ",
tempTableName, metaSizeTableName, sampleTableName.getSchemaName(), sampleTableName.getTableName()));
return tempTableName;
}
protected void insertSampleSizeEntryIntoDBMS(SampleParam param, long sampleSize, long originalTableSize, TableUniqueName metaSizeTableName) throws VerdictException {
TableUniqueName sampleTableName = param.sampleTableName();
List<Object> values = new ArrayList<Object>();
values.add(sampleTableName.getSchemaName());
values.add(sampleTableName.getTableName());
values.add(sampleSize);
values.add(originalTableSize);
insertEntry(metaSizeTableName, values);
}
public void deleteSampleNameEntryFromDBMS(SampleParam param, TableUniqueName metaNameTableName) throws VerdictException {
TableUniqueName tempTable = createTempTableExlucdingNameEntry(param, metaNameTableName);
moveTable(tempTable, metaNameTableName);
}
public void deleteSampleSizeEntryFromDBMS(SampleParam param, TableUniqueName metaSizeTableName) throws VerdictException {
TableUniqueName tempTable = createTempTableExlucdingSizeEntry(param, metaSizeTableName);
moveTable(tempTable, metaSizeTableName);
}
public void cacheTable(TableUniqueName tableName) {}
/**
* Column expression that generates a number between 0 and 99.
* @return
*/
protected abstract String randomPartitionColumn();
/**
* Column expression that generates a number between 0 and 1.
* @return
*/
protected abstract String randomNumberExpression(SampleParam param);
public abstract String modOfHash(String col, int mod);
protected abstract String modOfRand(int mod);
protected String quote(String expr) {
return String.format("\"%s\"", expr);
}
protected String columnNameListToString(List<String> columnNames) {
return Joiner.on(",").join(columnNames);
}
protected String samplingRatioToString(double samplingRatio) {
return String.format("%.4f", samplingRatio);
}
public String partitionColumnName() {
return vc.getConf().subsamplingPartitionColumn();
}
public int partitionCount() {
return vc.getConf().subsamplingPartitionCount();
}
public String samplingProbabilityColumnName() {
return vc.getConf().subsamplingProbabilityColumn();
}
public boolean isJDBC() {
return false;
}
public boolean isSpark() {
return false;
}
public abstract void close() throws VerdictException;
@Deprecated
public String getQuoteString() {
return "`";
}
@Deprecated
public String varianceFunction() {
return "VAR_SAMP";
}
@Deprecated
public String stddevFunction() {
return "STDDEV";
}
public String getParquetString() {
return " stored as parquet";
}
}
|
package backend;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class MutualAuthentication {
ByteUtils util = new ByteUtils();
ConstantValues CV = new ConstantValues();
Serialization serial = new Serialization();
CardTerminalCommunication CT = new CardTerminalCommunication();
int NONCE_LENGTH = 16;
public MutualAuthentication(){
}
/**
* Terminal Mutual Authentication:
* 1. Read RT Certificate from file (OK)
* 2. Generate Nonce (OK)
* 3. Combine those two and split them into two package; (OK)
* 4. Send those two package to card --
* 5. Received 4 packages from smartcard --
* (ask the card for the every next package; differentiate the package number in INS) --
* 6. Read RT Priv Key from file (OK)
* 7. Decrypt every packages (OK)
* 8. Combine the decrypted packages (OK)
* 9. Split the smartcard's certificate (certS) and Data (N, Ktmp) from the decrypted packages (OK)
* 10.Verify the Certificate (with the CAPublicKey - from file - and check the revocation status) (OK)
* 11. Verify the card Signature (data, cardPubKey, dataSignature) (Max help. OK)
* 12. Send the session key to card --
*/
public byte[] TerminalMutualAuth(byte[] cert, RSAPrivateKey privKey){
byte[] cardCert = null;
byte[] scPack1 = null;
byte[] sessionKey = null;
//byte[] rtCert = readFiles(certFilename); //Read Certificate for Terminal
byte[] nounce = util.GenerateRandomBytes(NONCE_LENGTH); //generate nonces
//Split the certificate into two package
byte[] pack1 = new byte[CV.PUBMODULUS + 1]; //129
System.arraycopy(cert, 0, pack1, 0, pack1.length);
byte[] pack2 = new byte[CV.SIG_LENGTH + NONCE_LENGTH]; //SIGNATURE + NONCE = 144
System.arraycopy(cert, CV.PUBMODULUS+1, pack2, 0, CV.SIG_LENGTH);
System.arraycopy(nounce, 0, pack2, CV.SIG_LENGTH, nounce.length);
byte[] sig = new byte[CV.SIG_LENGTH];
System.arraycopy(pack2, 0, sig, 0, CV.SIG_LENGTH);
/* DEBUG
try {
FileInputStream file = new FileInputStream("CAPublicKey");
byte[] bytes = new byte[file.available()];
file.read(bytes);
X509EncodedKeySpec pubspec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPublicKey capubkey = (RSAPublicKey) factory.generatePublic(pubspec);
System.err.println("checking signature of terminal: " + sigVerif(pack1, util.getBytes(capubkey.getModulus()), sig));
file.close();
CertAuth ca = new CertAuth();
System.err.println("check again: " + sigVerif(pack1, util.getBytes(ca.getVerificationKey().getModulus()), sig));
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
*/
//TODO: send to card // consider while loop. if the card is not responding ?
CT.sendToCard(pack1, CT.INS_AUTH_1);
scPack1 = CT.sendToCard(pack2, CT.INS_AUTH_2);
//TODO: GET PACKAGE FROM CARD -- SIZE 128
byte[] scPack2 = CT.sendToCard(null, CT.INS_AUTH_3); //received 2nd package from sc
byte[] scPack3 = CT.sendToCard(null, CT.INS_AUTH_4); //received 3nd package from sc
byte[] scPack4 = CT.sendToCard(null, CT.INS_AUTH_5); //received 4nd package from sc
//get The private Key
//RSAPrivateKey rtPrivKey = GetPrivateKeyFromFile("RTPrivateKey");
byte[] scDataPack1 = RSADecrypt(scPack1, privKey);
byte[] scDataPack2 = RSADecrypt(scPack2, privKey);
byte[] scDataPack3 = RSADecrypt(scPack3, privKey);
byte[] scDataPack4 = RSADecrypt(scPack4, privKey);
//combine the decrypted package
byte[] scPack = serial.combineThePackage(scDataPack1, scDataPack2, scDataPack3, scDataPack4);
//System.out.println(util.toHexString(scPack));
//split card certificate and the card data {N, Ktmp}Sig
cardCert = new byte[CV.CARDCERT_LENGTH];
System.arraycopy(scPack, 0, cardCert, 0, CV.CARDCERT_LENGTH);
//System.out.println(util.toHexString(cardCert));
byte[] cardData = new byte[32];
System.arraycopy(scPack, CV.CARDCERT_LENGTH, cardData, 0, 32);
//System.out.println(util.toHexString(cardData));
//get card public key (from cardCert)
byte[] certPubKey = new byte[CV.PUBMODULUS];
System.arraycopy(scPack, 1, certPubKey, 0, CV.PUBMODULUS);
//get signature from cardData
byte[] cardDataSig = new byte[CV.SIG_LENGTH];
System.arraycopy(scPack, 32 + CV.CARDCERT_LENGTH, cardDataSig, 0, CV.SIG_LENGTH);
//Verify the certificate
if(certVerify(cardCert)){
//Verify the cardData {N, Ktmp} signature
if(sigVerif(cardData, certPubKey, cardDataSig)){
//TODO send session key to card
CT.sendToCard(nounce, CT.INS_AUTH_6, sessionKey);
}else{
//Emptying the card certificate --> the card cert is not valid
//System.err.println("clearing");
cardCert = null;
}
}else{
//Emptying the card certificate --> the card cert is not valid
cardCert = null;
}
return cardCert;
}
/**
* Init Verify with CApubKey
* Update with card cert data
* sig.verify with card signature
* @param certSC
* @return
*/
public boolean certVerify(byte[] cardCert){
boolean result = false;
byte[] CAPkBytes = readFiles("CAPublicKey");
X509EncodedKeySpec pubspec = new X509EncodedKeySpec(CAPkBytes);
KeyFactory factory;
RSAPublicKey CAPubKey = null;
try {
factory = KeyFactory.getInstance("RSA");
CAPubKey = (RSAPublicKey) factory.generatePublic(pubspec);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//split the certificate data and the signature
byte[] certData = serial.getCardCertDataFromCert(cardCert); //without signature
byte[] certSig = serial.getSigFromCert(cardCert); //card signature
if(sigVerif(certData, CAPubKey, certSig)){
result = true;
}
return result;
}
public boolean sigVerif(byte[] data, RSAPublicKey pubKey, byte[] signature) {
Signature sig;
boolean result = false;
try {
sig = Signature.getInstance("MD5WithRSA");
sig.initVerify(pubKey);
sig.update(data);
result = sig.verify(signature);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public boolean sigVerif(byte[] data, byte[] pubKey, byte[] signature) {
// Convert bytekey (public Modulus into a RSAPublicKey
byte[] padded = new byte[129];
padded[0] = 0;
System.arraycopy(pubKey, 0, padded, 1, 128);
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(padded), CV.PUBEXPONENT_BYTE);
RSAPublicKey pub = null;
try {
KeyFactory factory = KeyFactory.getInstance("RSA");
pub = (RSAPublicKey) factory.generatePublic(spec);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("This is the public key, gotten from the card:");
//System.out.println(pub);
//System.out.println(util.toHexString(padded));
Signature sig;
boolean result = false;
try {
sig = Signature.getInstance("MD5WithRSA");
sig.initVerify(pub);
sig.update(data);
result = sig.verify(signature);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
MutualAuthentication ma = new MutualAuthentication();
ma.TerminalMutualAuth(null, null);
}
public byte[] readFiles(String filename) {
FileInputStream file;
byte[] bytes = null;
try {
file = new FileInputStream(filename);
bytes = new byte[file.available()];
file.read(bytes);
file.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bytes;
}
public byte[] RSADecrypt(byte[] ciphertext, RSAPrivateKey privatekey) {
byte[] plaintext = null;
try {
/* Create cipher for decryption. */
Cipher decrypt_cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decrypt_cipher.init(Cipher.DECRYPT_MODE, privatekey);
/* Reconstruct the plaintext message. */
byte[] temp = decrypt_cipher.doFinal(ciphertext);
plaintext = new byte[temp.length];
plaintext = temp;
} catch (Exception e) {
e.printStackTrace();
}
return plaintext;
}
/*
public byte[] RSAEncrypt(byte[] plaintext, RSAPublicKey publicKey) {
byte[] ciphertext = null;
try {
// Create a cipher for encrypting.
Cipher encrypt_cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encrypt_cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// Encrypt the secret message and store in file.
ciphertext = encrypt_cipher.doFinal(plaintext);
} catch (Exception e) {
e.printStackTrace();
}
return ciphertext;
}*/
}
|
package jenkins.install;
import hudson.BulkChange;
import hudson.FilePath;
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.SecurityRealm;
import hudson.security.csrf.DefaultCrumbIssuer;
import hudson.util.HttpResponses;
import hudson.util.PluginServletFilter;
import jenkins.model.Jenkins;
import jenkins.security.s2m.AdminWhitelistRule;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;
import java.util.logging.Logger;
/**
* A Jenkins instance used during first-run to provide a limited set of services while
* initial installation is in progress
*
* @since 2.0
*/
public class SetupWizard {
/**
* The security token parameter name
*/
public static String initialSetupAdminUserName = "admin";
private final Logger LOGGER = Logger.getLogger(SetupWizard.class.getName());
public SetupWizard(Jenkins j) throws IOException, InterruptedException {
// Create an admin user by default with a
// difficult password
FilePath iapf = getInitialAdminPasswordFile();
if(j.getSecurityRealm() == null || j.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION) { // this seems very fragile
BulkChange bc = new BulkChange(j);
try{
HudsonPrivateSecurityRealm securityRealm = new HudsonPrivateSecurityRealm(false, false, null);
j.setSecurityRealm(securityRealm);
String randomUUID = UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ENGLISH);
// create an admin user
securityRealm.createAccount(SetupWizard.initialSetupAdminUserName, randomUUID);
// JENKINS-33599 - write to a file in the jenkins home directory
// most native packages of Jenkins creates a machine user account 'jenkins' to run Jenkins,
// and use group 'jenkins' for admins. So we allo groups to read this file
iapf.write(randomUUID, "UTF-8");
iapf.chmod(0640);
// Lock Jenkins down:
FullControlOnceLoggedInAuthorizationStrategy authStrategy = new FullControlOnceLoggedInAuthorizationStrategy();
authStrategy.setAllowAnonymousRead(false);
j.setAuthorizationStrategy(authStrategy);
// Shut down all the ports we can by default:
j.setSlaveAgentPort(-1); // -1 to disable
// require a crumb issuer
j.setCrumbIssuer(new DefaultCrumbIssuer(false));
// set master -> slave security:
j.getInjector().getInstance(AdminWhitelistRule.class)
.setMasterKillSwitch(false);
j.save();
bc.commit();
} finally {
bc.abort();
}
}
String setupKey = iapf.readToString().trim();
LOGGER.info("\n\n*************************************************************\n"
+ "*************************************************************\n"
+ "*************************************************************\n"
+ "\n"
+ "Jenkins initial setup is required. An admin user has been created and"
+ "a password generated. \n"
+ "Please use the following password to proceed to installation: \n"
+ "\n"
+ "" + setupKey + "\n"
+ "\n"
+ "This may also be found at: " + iapf.getRemote() + "\n"
+ "\n"
+ "*************************************************************\n"
+ "*************************************************************\n"
+ "*************************************************************\n");
try {
PluginServletFilter.addFilter(FORCE_SETUP_WIZARD_FILTER);
} catch (ServletException e) {
throw new AssertionError(e);
}
}
/**
* Gets the file used to store the initial admin password
*/
@Restricted(NoExternalUse.class) // use by Jelly
public FilePath getInitialAdminPasswordFile() {
return Jenkins.getInstance().getRootPath().child("initialAdminPassword");
}
/**
* Remove the setupWizard filter, ensure all updates are written to disk, etc
*/
public HttpResponse doCompleteInstall() throws IOException, ServletException {
Jenkins j = Jenkins.getInstance();
j.setInstallState(InstallState.INITIAL_SETUP_COMPLETED);
InstallUtil.saveLastExecVersion();
PluginServletFilter.removeFilter(FORCE_SETUP_WIZARD_FILTER);
// Also, clean up the setup wizard if it's completed
j.setSetupWizard(null);
return HttpResponses.okJSON();
}
/**
* This filter will validate that the security token is provided
*/
private final Filter FORCE_SETUP_WIZARD_FILTER = new Filter() {
@Override
public void init(FilterConfig cfg) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// As an extra measure of security, the install wizard generates a security token, and
// requires the user to enter it before proceeding through the installation. Once set
// we'll set a cookie so the subsequent operations succeed
if (request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest)request;
//if (!Pattern.compile(".*[.](css|ttf|gif|woff|eot|png|js)").matcher(req.getRequestURI()).matches()) {
// Allow js & css requests through
if((req.getContextPath() + "/").equals(req.getRequestURI())) {
chain.doFilter(new HttpServletRequestWrapper(req) {
public String getRequestURI() {
return getContextPath() + "/setupWizard/";
}
}, response);
return;
}
// fall through to handling the request normally
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
};
}
|
package io.branch.referral;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
public class Branch {
public static String FEATURE_TAG_SHARE = "share";
public static String FEATURE_TAG_REFERRAL = "referral";
public static String FEATURE_TAG_INVITE = "invite";
public static String FEATURE_TAG_DEAL = "deal";
public static String FEATURE_TAG_GIFT = "gift";
public static String REDEEM_CODE = "$redeem_code";
public static String REEFERRAL_BUCKET_DEFAULT = "default";
public static String REFERRAL_CODE_TYPE = "credit";
public static int REFERRAL_CREATION_SOURCE_SDK = 2;
public static int REFERRAL_CODE_LOCATION_REFERREE = 0;
public static int REFERRAL_CODE_LOCATION_REFERRING_USER = 2;
public static int REFERRAL_CODE_LOCATION_BOTH = 3;
public static int REFERRAL_CODE_AWARD_UNLIMITED = 1;
public static int REFERRAL_CODE_AWARD_UNIQUE = 0;
private static final int SESSION_KEEPALIVE = 5000;
private static final int INTERVAL_RETRY = 3000;
private static final int MAX_RETRIES = 5;
private static Branch branchReferral_;
private boolean isInit_;
private BranchReferralInitListener initSessionFinishedCallback_;
private BranchReferralInitListener initIdentityFinishedCallback_;
private BranchReferralStateChangedListener stateChangedCallback_;
private BranchLinkCreateListener linkCreateCallback_;
private BranchListResponseListener creditHistoryCallback_;
private BranchReferralInitListener getReferralCodeCallback_;
private BranchReferralInitListener validateReferralCodeCallback_;
private BranchRemoteInterface kRemoteInterface_;
private PrefHelper prefHelper_;
private SystemObserver systemObserver_;
private Context context_;
private Timer closeTimer;
private boolean keepAlive_;
private Semaphore serverSema_;
private ServerRequestQueue requestQueue_;
private int networkCount_;
private int retryCount_;
private boolean initFinished_;
private boolean hasNetwork_;
private boolean debug_;
private Branch(Context context) {
prefHelper_ = PrefHelper.getInstance(context);
kRemoteInterface_ = new BranchRemoteInterface(context);
systemObserver_ = new SystemObserver(context);
kRemoteInterface_.setNetworkCallbackListener(new ReferralNetworkCallback());
requestQueue_ = ServerRequestQueue.getInstance(context);
serverSema_ = new Semaphore(1);
closeTimer = new Timer();
keepAlive_ = false;
isInit_ = false;
networkCount_ = 0;
initFinished_ = false;
hasNetwork_ = true;
debug_ = false;
}
public static Branch getInstance(Context context, String key) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
}
branchReferral_.context_ = context;
branchReferral_.prefHelper_.setAppKey(key);
return branchReferral_;
}
public static Branch getInstance(Context context) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
}
branchReferral_.context_ = context;
return branchReferral_;
}
private static Branch initInstance(Context context) {
return new Branch(context.getApplicationContext());
}
public void resetUserSession() {
isInit_ = false;
}
// if you want to flag debug, call this before initUserSession
public void setDebug() {
debug_ = true;
}
@Deprecated
public void initUserSession(BranchReferralInitListener callback) {
initSession(callback);
}
public void initSession(BranchReferralInitListener callback) {
if (systemObserver_.getUpdateState() == 0 && !hasUser()) {
prefHelper_.setIsReferrable();
} else {
prefHelper_.clearIsReferrable();
}
initUserSessionInternal(callback);
}
@Deprecated
public void initUserSession(BranchReferralInitListener callback, Uri data) {
initSession(callback, data);
}
public void initSession(BranchReferralInitListener callback, Uri data) {
if (data != null) {
if (data.getQueryParameter("link_click_id") != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id"));
}
}
initSession(callback);
}
@Deprecated
public void initUserSession() {
initSession();
}
public void initSession() {
initSession(null);
}
@Deprecated
public void initUserSessionWithData(Uri data) {
initSessionWithData(data);
}
public void initSessionWithData(Uri data) {
if (data != null) {
if (data.getQueryParameter("link_click_id") != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id"));
}
}
initSession(null);
}
@Deprecated
public void initUserSession(boolean isReferrable) {
initSession(isReferrable);
}
public void initSession(boolean isReferrable) {
initSession(null, isReferrable);
}
@Deprecated
public void initUserSession(BranchReferralInitListener callback,
boolean isReferrable, Uri data) {
initSession(callback, isReferrable, data);
}
public void initSession(BranchReferralInitListener callback,
boolean isReferrable, Uri data) {
if (data != null) {
if (data.getQueryParameter("link_click_id") != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter("link_click_id"));
}
}
initSession(callback, isReferrable);
}
@Deprecated
public void initUserSession(BranchReferralInitListener callback,
boolean isReferrable) {
initSession(callback, isReferrable);
}
public void initSession(BranchReferralInitListener callback,
boolean isReferrable) {
if (isReferrable) {
this.prefHelper_.setIsReferrable();
} else {
this.prefHelper_.clearIsReferrable();
}
initUserSessionInternal(callback);
}
private void initUserSessionInternal(BranchReferralInitListener callback) {
initSessionFinishedCallback_ = callback;
if (!isInit_) {
new Thread(new Runnable() {
@Override
public void run() {
initializeSession();
}
}).start();
isInit_ = true;
} else {
boolean installOrOpenInQueue = requestQueue_.containsInstallOrOpen();
if (hasUser() && hasSession() && !installOrOpenInQueue) {
if (callback != null) callback.onInitFinished(new JSONObject());
} else {
if (!installOrOpenInQueue) {
new Thread(new Runnable() {
@Override
public void run() {
initializeSession();
}
}).start();
} else {
processNextQueueItem();
}
}
}
}
public void closeSession() {
if (keepAlive_) {
return;
}
// else, real close
isInit_ = false;
if (!hasNetwork_) {
// if there's no network connectivity, purge the old install/open
ServerRequest req = requestQueue_.peek();
if (req != null && (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN))) {
requestQueue_.dequeue();
}
} else {
new Thread(new Runnable() {
@Override
public void run() {
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE, null));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
}
@Deprecated
public void identifyUser(String userId, BranchReferralInitListener callback) {
setIdentity(userId, callback);
}
public void setIdentity(String userId, BranchReferralInitListener callback) {
initIdentityFinishedCallback_ = callback;
setIdentity(userId);
}
@Deprecated
public void identifyUser(final String userId) {
setIdentity(userId);
}
public void setIdentity(final String userId) {
if (userId == null || userId.length() == 0) {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
post.put("identity", userId);
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_IDENTIFY, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
@Deprecated
public void clearUser() {
logout();
}
public void logout() {
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("session_id", prefHelper_.getSessionID());
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_LOGOUT, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void loadActionCounts() {
loadActionCounts(null);
}
public void loadActionCounts(BranchReferralStateChangedListener callback) {
stateChangedCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS, null));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void loadRewards() {
loadRewards(null);
}
public void loadRewards(BranchReferralStateChangedListener callback) {
stateChangedCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARDS, null));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public int getCredits() {
return prefHelper_.getCreditCount();
}
public int getCreditsForBucket(String bucket) {
return prefHelper_.getCreditCount(bucket);
}
public int getTotalCountsForAction(String action) {
return prefHelper_.getActionTotalCount(action);
}
public int getUniqueCountsForAction(String action) {
return prefHelper_.getActionUniqueCount(action);
}
public void redeemRewards(int count) {
redeemRewards("default", count);
}
public void redeemRewards(final String bucket, final int count) {
new Thread(new Runnable() {
@Override
public void run() {
int creditsToRedeem = 0;
int credits = prefHelper_.getCreditCount(bucket);
if (count > credits) {
creditsToRedeem = credits;
Log.i("BranchSDK", "Branch Warning: You're trying to redeem more credits than are available. Have you updated loaded rewards");
} else {
creditsToRedeem = count;
}
if (creditsToRedeem > 0) {
retryCount_ = 0;
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
post.put("bucket", bucket);
post.put("amount", creditsToRedeem);
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}
}).start();
}
public void getCreditHistory(BranchListResponseListener callback) {
getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
public void getCreditHistory(final String bucket, BranchListResponseListener callback) {
getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) {
getCreditHistory(null, afterId, length, order, callback);
}
public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) {
creditHistoryCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
post.put("length", length);
post.put("direction", order.ordinal());
if (bucket != null) {
post.put("bucket", bucket);
}
if (afterId != null) {
post.put("begin_after_id", afterId);
}
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void userCompletedAction(final String action, final JSONObject metadata) {
new Thread(new Runnable() {
@Override
public void run() {
retryCount_ = 0;
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("session_id", prefHelper_.getSessionID());
post.put("event", action);
if (metadata != null) post.put("metadata", metadata);
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void userCompletedAction(final String action) {
userCompletedAction(action, null);
}
@Deprecated
public JSONObject getInstallReferringParams() {
return getFirstReferringParams();
}
public JSONObject getFirstReferringParams() {
String storedParam = prefHelper_.getInstallParams();
return convertParamsStringToDictionary(storedParam);
}
@Deprecated
public JSONObject getReferringParams() {
return getLatestReferringParams();
}
public JSONObject getLatestReferringParams() {
String storedParam = prefHelper_.getSessionParams();
return convertParamsStringToDictionary(storedParam);
}
public void getShortUrl(BranchLinkCreateListener callback) {
generateShortLink(null, null, null, null, stringifyParams(null), callback);
}
public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, null, null, null, stringifyParams(params), callback);
}
public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(params), callback);
}
public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(params), callback);
}
public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, channel, FEATURE_TAG_SHARE, null, stringifyParams(params), callback);
}
public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(params), callback);
}
public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, channel, feature, stage, stringifyParams(params), callback);
}
public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(tags, channel, feature, stage, stringifyParams(params), callback);
}
public void getReferralCode(BranchReferralInitListener callback) {
getReferralCodeCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void getReferralCode(final int amount, BranchReferralInitListener callback) {
this.getReferralCode(null, amount, null, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, null, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) {
this.getReferralCode(null, amount, expiration, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, expiration, REEFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, null, REEFERRAL_BUCKET_DEFAULT, calculationType, location, callback);
}
public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) {
getReferralCodeCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
post.put("calculation_type", calculationType);
post.put("location", location);
post.put("type", REFERRAL_CODE_TYPE);
post.put("creation_source", REFERRAL_CREATION_SOURCE_SDK);
post.put("amount", amount);
post.put("bucket", bucket != null ? bucket : REEFERRAL_BUCKET_DEFAULT);
if (prefix != null && prefix.length() > 0) {
post.put("prefix", prefix);
}
if (expiration != null) {
post.put("expiration", convertDate(expiration));
}
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void validateReferralCode(final String code, BranchReferralInitListener callback) {
validateReferralCodeCallback_ = callback;
new Thread(new Runnable() {
@Override
public void run() {
JSONObject post = new JSONObject();
try {
post.put("app_id", prefHelper_.getAppKey());
post.put("identity_id", prefHelper_.getIdentityID());
post.put("referral_code", code);
} catch (JSONException ex) {
ex.printStackTrace();
return;
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE, post));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
public void applyReferralCode(final String code, final BranchReferralInitListener callback) {
this.validateReferralCode(code, new BranchReferralInitListener() {
@Override
public void onInitFinished(JSONObject referringParams) {
if (referringParams.has("referral_code")) {
userCompletedAction(REDEEM_CODE + "-" + code);
if (callback != null) {
callback.onInitFinished(referringParams);
}
} else {
if (callback != null) {
callback.onInitFinished(new JSONObject());
}
}
}
});
}
// PRIVATE FUNCTIONS
private String convertDate(Date date) {
return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString();
}
private String stringifyParams(JSONObject params) {
if (params == null) {
params = new JSONObject();
}
try {
params.put("source", "android");
} catch (JSONException e) {
e.printStackTrace();
}
return params.toString();
}
private void generateShortLink(final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback) {
linkCreateCallback_ = callback;
if (hasUser()) {
new Thread(new Runnable() {
@Override
public void run() {
JSONObject linkPost = new JSONObject();
try {
linkPost.put("app_id", prefHelper_.getAppKey());
linkPost.put("identity_id", prefHelper_.getIdentityID());
if (tags != null) {
JSONArray tagArray = new JSONArray();
for (String tag : tags)
tagArray.put(tag);
linkPost.put("tags", tagArray);
}
if (channel != null) {
linkPost.put("channel", channel);
}
if (feature != null) {
linkPost.put("feature", feature);
}
if (stage != null) {
linkPost.put("stage", stage);
}
if (params != null)
linkPost.put("data", params);
} catch (JSONException ex) {
ex.printStackTrace();
}
requestQueue_.enqueue(new ServerRequest(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL, linkPost));
if (initFinished_ || !hasNetwork_) {
processNextQueueItem();
}
}
}).start();
}
}
private JSONObject convertParamsStringToDictionary(String paramString) {
if (paramString.equals(PrefHelper.NO_STRING_VALUE)) {
return new JSONObject();
} else {
try {
return new JSONObject(paramString);
} catch (JSONException e) {
byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP);
try {
return new JSONObject(new String(encodedArray));
} catch (JSONException ex) {
ex.printStackTrace();
return new JSONObject();
}
}
}
}
private void processNextQueueItem() {
try {
serverSema_.acquire();
if (networkCount_ == 0 && requestQueue_.getSize() > 0) {
networkCount_ = 1;
serverSema_.release();
ServerRequest req = requestQueue_.peek();
if (!req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) {
keepAlive();
}
if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) {
kRemoteInterface_.registerInstall(PrefHelper.NO_STRING_VALUE, debug_);
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) {
kRemoteInterface_.registerOpen(debug_);
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) && hasUser() && hasSession()) {
kRemoteInterface_.getReferralCounts();
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS) && hasUser() && hasSession()) {
kRemoteInterface_.getRewards();
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REDEEM_REWARDS) && hasUser() && hasSession()) {
kRemoteInterface_.redeemRewards(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY) && hasUser() && hasSession()) {
kRemoteInterface_.getCreditHistory(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_COMPLETE_ACTION) && hasUser() && hasSession()){
kRemoteInterface_.userCompletedAction(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL) && hasUser() && hasSession()) {
kRemoteInterface_.createCustomUrl(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY) && hasUser() && hasSession()) {
kRemoteInterface_.identifyUser(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE) && hasUser() && hasSession()) {
kRemoteInterface_.registerClose();
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_LOGOUT) && hasUser() && hasSession()) {
kRemoteInterface_.logoutUser(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE) && hasUser() && hasSession()) {
kRemoteInterface_.getReferralCode(req.getPost());
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE) && hasUser() && hasSession()) {
kRemoteInterface_.validateReferralCode(req.getPost());
} else if (!hasUser()) {
if (!hasAppKey() && hasSession()) {
Log.i("BranchSDK", "Branch Warning: User session has not been initialized");
} else {
networkCount_ = 0;
initSession();
}
}
} else {
serverSema_.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleFailure() {
final ServerRequest req = requestQueue_.peek();
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN) ) {
if (initSessionFinishedCallback_ != null) {
JSONObject obj = new JSONObject();
try {
obj.put("error_message", "Trouble reaching server. Please try again in a few minutes");
} catch(JSONException ex) {
ex.printStackTrace();
}
initSessionFinishedCallback_.onInitFinished(obj);
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS) || req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) {
if (stateChangedCallback_ != null) {
stateChangedCallback_.onStateChanged(false);
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) {
if (creditHistoryCallback_ != null) {
creditHistoryCallback_.onReceivingResponse(null);
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) {
if (linkCreateCallback_ != null) {
linkCreateCallback_.onLinkCreate("Trouble reaching server. Please try again in a few minutes");
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) {
if (initIdentityFinishedCallback_ != null) {
JSONObject obj = new JSONObject();
try {
obj.put("error_message", "Trouble reaching server. Please try again in a few minutes");
} catch(JSONException ex) {
ex.printStackTrace();
}
initIdentityFinishedCallback_.onInitFinished(obj);
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) {
if (getReferralCodeCallback_ != null) {
getReferralCodeCallback_.onInitFinished(null);
}
} else if (req.getTag().equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) {
if (validateReferralCodeCallback_ != null) {
validateReferralCodeCallback_.onInitFinished(null);
}
}
}
});
}
private void retryLastRequest() {
retryCount_ = retryCount_ + 1;
if (retryCount_ > MAX_RETRIES) {
handleFailure();
requestQueue_.dequeue();
retryCount_ = 0;
} else {
try {
Thread.sleep(INTERVAL_RETRY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void updateAllRequestsInQueue() {
try {
for (int i = 0; i < requestQueue_.getSize(); i++) {
ServerRequest req = requestQueue_.peekAt(i);
if (req.getPost() != null) {
Iterator<?> keys = req.getPost().keys();
while (keys.hasNext()) {
String key = (String)keys.next();
if (key.equals("app_id")) {
req.getPost().put(key, prefHelper_.getAppKey());
} else if (key.equals("session_id")) {
req.getPost().put(key, prefHelper_.getSessionID());
} else if (key.equals("identity_id")) {
req.getPost().put(key, prefHelper_.getIdentityID());
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void clearTimer() {
if (closeTimer == null)
return;
closeTimer.cancel();
closeTimer.purge();
closeTimer = new Timer();
}
private void keepAlive() {
keepAlive_ = true;
clearTimer();
closeTimer.schedule(new TimerTask() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
keepAlive_ = false;
}
}).start();
}
}, SESSION_KEEPALIVE);
}
private boolean hasAppKey() {
return !prefHelper_.getAppKey().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasSession() {
return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasUser() {
return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE);
}
private void insertRequestAtFront(ServerRequest req) {
if (networkCount_ == 0) {
requestQueue_.insert(req, 0);
} else {
requestQueue_.insert(req, 1);
}
}
private void registerInstallOrOpen(String tag) {
if (!requestQueue_.containsInstallOrOpen()) {
insertRequestAtFront(new ServerRequest(tag));
} else {
requestQueue_.moveInstallOrOpenToFront(tag, networkCount_);
}
processNextQueueItem();
}
private void initializeSession() {
if (hasUser()) {
registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN);
} else {
registerInstallOrOpen(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL);
}
}
private void processReferralCounts(ServerResponse resp) {
boolean updateListener = false;
Iterator<?> keys = resp.getObject().keys();
while (keys.hasNext()) {
String key = (String)keys.next();
try {
JSONObject counts = resp.getObject().getJSONObject(key);
int total = counts.getInt("total");
int unique = counts.getInt("unique");
if (total != prefHelper_.getActionTotalCount(key) || unique != prefHelper_.getActionUniqueCount(key)) {
updateListener = true;
}
prefHelper_.setActionTotalCount(key, total);
prefHelper_.setActionUniqueCount(key, unique);
} catch (JSONException e) {
e.printStackTrace();
}
}
final boolean finUpdateListener = updateListener;
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (stateChangedCallback_ != null) {
stateChangedCallback_.onStateChanged(finUpdateListener);
}
}
});
}
private void processRewardCounts(ServerResponse resp) {
boolean updateListener = false;
Iterator<?> keys = resp.getObject().keys();
while (keys.hasNext()) {
String key = (String)keys.next();
try {
int credits = resp.getObject().getInt(key);
if (credits != prefHelper_.getCreditCount(key)) {
updateListener = true;
}
prefHelper_.setCreditCount(key, credits);
} catch (JSONException e) {
e.printStackTrace();
}
}
final boolean finUpdateListener = updateListener;
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (stateChangedCallback_ != null) {
stateChangedCallback_.onStateChanged(finUpdateListener);
}
}
});
}
private void processCreditHistory(final ServerResponse resp) {
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (creditHistoryCallback_ != null) {
creditHistoryCallback_.onReceivingResponse(resp.getArray());
}
}
});
}
private void processReferralCodeGet(final ServerResponse resp) {
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (getReferralCodeCallback_ != null) {
try {
JSONObject data = resp.getObject();
String event = data.getString("event");
String code = event.substring(REDEEM_CODE.length() + 1);
data.put("referral_code", code);
getReferralCodeCallback_.onInitFinished(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
private void processReferralCodeValidation(final ServerResponse resp) {
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (validateReferralCodeCallback_ != null) {
try {
JSONObject data = resp.getObject();
String event = data.getString("event");
String code = event.substring(REDEEM_CODE.length() + 1);
data.put("referral_code", code);
validateReferralCodeCallback_.onInitFinished(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
public class ReferralNetworkCallback implements NetworkCallback {
@Override
public void finished(ServerResponse serverResponse) {
if (serverResponse != null) {
try {
int status = serverResponse.getStatusCode();
String requestTag = serverResponse.getTag();
hasNetwork_ = true;
if (status >= 400 && status < 500) {
if (serverResponse.getObject().has("error") && serverResponse.getObject().getJSONObject("error").has("message")) {
Log.i("BranchSDK", "Branch API Error: " + serverResponse.getObject().getJSONObject("error").getString("message"));
}
requestQueue_.dequeue();
} else if (status != 200) {
if (status == RemoteInterface.NO_CONNECTIVITY_STATUS) {
hasNetwork_ = false;
handleFailure();
if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_CLOSE)) {
requestQueue_.dequeue();
}
Log.i("BranchSDK", "Branch API Error: " + "poor network connectivity. Please try again later.");
} else {
retryLastRequest();
}
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_COUNTS)) {
processReferralCounts(serverResponse);
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARDS)) {
processRewardCounts(serverResponse);
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REWARD_HISTORY)) {
processCreditHistory(serverResponse);
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_INSTALL)) {
prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString("device_fingerprint_id"));
prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id"));
prefHelper_.setUserURL(serverResponse.getObject().getString("link"));
prefHelper_.setSessionID(serverResponse.getObject().getString("session_id"));
prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE);
if (prefHelper_.getIsReferrable() == 1) {
if (serverResponse.getObject().has("data")) {
String params = serverResponse.getObject().getString("data");
prefHelper_.setInstallParams(params);
} else {
prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE);
}
}
if (serverResponse.getObject().has("link_click_id")) {
prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id"));
} else {
prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE);
}
if (serverResponse.getObject().has("data")) {
String params = serverResponse.getObject().getString("data");
prefHelper_.setSessionParams(params);
} else {
prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE);
}
updateAllRequestsInQueue();
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (initSessionFinishedCallback_ != null) {
initSessionFinishedCallback_.onInitFinished(getLatestReferringParams());
}
}
});
requestQueue_.dequeue();
initFinished_ = true;
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_REGISTER_OPEN)) {
prefHelper_.setSessionID(serverResponse.getObject().getString("session_id"));
prefHelper_.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE);
if (serverResponse.getObject().has("identity_id")) {
prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id"));
}
if (serverResponse.getObject().has("link_click_id")) {
prefHelper_.setLinkClickID(serverResponse.getObject().getString("link_click_id"));
} else {
prefHelper_.setLinkClickID(PrefHelper.NO_STRING_VALUE);
}
if (prefHelper_.getIsReferrable() == 1) {
if (serverResponse.getObject().has("data")) {
String params = serverResponse.getObject().getString("data");
prefHelper_.setInstallParams(params);
}
}
if (serverResponse.getObject().has("data")) {
String params = serverResponse.getObject().getString("data");
prefHelper_.setSessionParams(params);
} else {
prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE);
}
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (initSessionFinishedCallback_ != null) {
initSessionFinishedCallback_.onInitFinished(getLatestReferringParams());
}
}
});
requestQueue_.dequeue();
initFinished_ = true;
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_CUSTOM_URL)) {
final String url = serverResponse.getObject().getString("url");
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (linkCreateCallback_ != null) {
linkCreateCallback_.onLinkCreate(url);
}
}
});
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_LOGOUT)) {
prefHelper_.setSessionID(serverResponse.getObject().getString("session_id"));
prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id"));
prefHelper_.setUserURL(serverResponse.getObject().getString("link"));
prefHelper_.setInstallParams(PrefHelper.NO_STRING_VALUE);
prefHelper_.setSessionParams(PrefHelper.NO_STRING_VALUE);
prefHelper_.setIdentity(PrefHelper.NO_STRING_VALUE);
prefHelper_.clearUserValues();
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_IDENTIFY)) {
prefHelper_.setIdentityID(serverResponse.getObject().getString("identity_id"));
prefHelper_.setUserURL(serverResponse.getObject().getString("link"));
if (serverResponse.getObject().has("referring_data")) {
String params = serverResponse.getObject().getString("referring_data");
prefHelper_.setInstallParams(params);
}
if (requestQueue_.getSize() > 0) {
ServerRequest req = requestQueue_.peek();
if (req.getPost() != null && req.getPost().has("identity")) {
prefHelper_.setIdentity(req.getPost().getString("identity"));
}
}
Handler mainHandler = new Handler(context_.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
if (initIdentityFinishedCallback_ != null) {
initIdentityFinishedCallback_.onInitFinished(getFirstReferringParams());
}
}
});
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_GET_REFERRAL_CODE)) {
processReferralCodeGet(serverResponse);
requestQueue_.dequeue();
} else if (requestTag.equals(BranchRemoteInterface.REQ_TAG_VALIDATE_REFERRAL_CODE)) {
processReferralCodeValidation(serverResponse);
requestQueue_.dequeue();
} else {
requestQueue_.dequeue();
}
networkCount_ = 0;
if (hasNetwork_) {
processNextQueueItem();
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
public interface BranchReferralInitListener {
public void onInitFinished(JSONObject referringParams);
}
public interface BranchReferralStateChangedListener {
public void onStateChanged(boolean changed);
}
public interface BranchLinkCreateListener {
public void onLinkCreate(String url);
}
public interface BranchListResponseListener {
public void onReceivingResponse(JSONArray list);
}
public enum CreditHistoryOrder {
kMostRecentFirst,
kLeastRecentFirst
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.game;
import java.util.ArrayList;
import java.util.List;
import playn.core.PlayN;
import playn.core.Game;
import tripleplay.util.Interpolator;
/**
* Manages a stack of screens. The stack supports useful manipulations: pushing a new screen onto
* the stack, replacing the screen at the top of the stack with a new screen, popping a screen from
* the stack.
*
* <p> Care is taken to preserve stack invariants even in the face of errors thrown by screens when
* being added, removed, shown or hidden. Users can override {@link #handleError} and either simply
* log the error, or rethrow it if they would prefer that a screen failure render their entire
* screen stack unusable. </p>
*/
public abstract class ScreenStack
{
/** Direction constants, used by transitions. */
public static enum Dir { UP, DOWN, LEFT, RIGHT; };
/** Implements a particular screen transition. */
public interface Transition {
/** Allows the transition to pre-compute useful values. This will immediately be followed
* by call to {@link #update} with an elapsed time of zero. */
void init (Screen oscreen, Screen nscreen);
/** Called every frame to update the transition
* @param oscreen the outgoing screen.
* @param nscreen the incoming screen.
* @param elapsed the elapsed time since the transition started (in millis if that's what
* your game is sending to {@link ScreenStack#update}).
* @return false if the transition is not yet complete, true when it is complete. The stack
* will automatically destroy/hide the old screen when the transition returns true.
*/
boolean update (Screen oscreen, Screen nscreen, float elapsed);
}
/** Simply puts the new screen in place and removes the old screen. */
public static final Transition NOOP = new Transition() {
public void init (Screen oscreen, Screen nscreen) {} // noopski!
public boolean update (Screen oscreen, Screen nscreen, float elapsed) { return true; }
};
/** Slides the old screen off, and the new screen on right behind. */
public class SlideTransition implements Transition {
public SlideTransition dir (Dir dir) { _dir = dir; return this; }
public SlideTransition up () { return dir(Dir.UP); }
public SlideTransition down () { return dir(Dir.DOWN); }
public SlideTransition left () { return dir(Dir.LEFT); }
public SlideTransition right () { return dir(Dir.RIGHT); }
public SlideTransition interp (Interpolator interp) { _interp = interp; return this; }
public SlideTransition linear () { return interp(Interpolator.LINEAR); }
public SlideTransition easeIn () { return interp(Interpolator.EASE_IN); }
public SlideTransition easeOut () { return interp(Interpolator.EASE_OUT); }
public SlideTransition easeInOut () { return interp(Interpolator.EASE_INOUT); }
public SlideTransition duration (float duration) { _duration = duration; return this; }
@Override public void init (Screen oscreen, Screen nscreen) {
switch (_dir) {
case UP:
_odx = originX; _ody = originY-oscreen.height();
_nsx = originX; _nsy = originY+nscreen.height();
break;
case DOWN:
_odx = originX; _ody = originY+oscreen.height();
_nsx = originX; _nsy = originY-nscreen.height();
break;
case LEFT: default:
_odx = originX-oscreen.width(); _ody = originY;
_nsx = originX+nscreen.width(); _nsy = originY;
break;
case RIGHT:
_odx = originX+oscreen.width(); _ody = originY;
_nsx = originX-nscreen.width(); _nsy = originY;
break;
}
nscreen.layer.setTranslation(_nsx, _nsy);
}
@Override public boolean update (Screen oscreen, Screen nscreen, float elapsed) {
float ox = _interp.apply(originX, _odx-originX, elapsed, _duration);
float oy = _interp.apply(originY, _ody-originY, elapsed, _duration);
oscreen.layer.setTranslation(ox, oy);
float nx = _interp.apply(_nsx, originX-_nsx, elapsed, _duration);
float ny = _interp.apply(_nsy, originY-_nsy, elapsed, _duration);
nscreen.layer.setTranslation(nx, ny);
return elapsed >= _duration;
}
protected Dir _dir = Dir.LEFT;
protected Interpolator _interp = Interpolator.EASE_INOUT;
protected float _duration = 500;
protected float _odx, _ody, _nsx, _nsy;
}
/** The x-coordinate at which screens are located. Defaults to 0. */
public float originX = 0;
/** The y-coordinate at which screens are located. Defaults to 0. */
public float originY = 0;
/** Creates a slide transition. */
public SlideTransition slide () { return new SlideTransition(); }
/**
* {@link #push(Screen,Transition)} with the default transition.
*/
public void push (Screen screen) {
push(screen, defaultPushTransition());
}
public void push (Screen screen, Transition trans) {
if (_screens.isEmpty()) {
addAndShow(screen);
} else {
final Screen otop = top();
transition(new Transitor(otop, screen, trans) {
protected void onComplete() { hide(otop); }
});
}
}
/**
* {@link #push(Iterable,Transition)} with the default transition.
*/
public void push (Iterable<? extends Screen> screens) {
push(screens, defaultPushTransition());
}
/**
* Pushes the supplied set of screens onto the stack, in order. The last screen to be pushed
* will also be shown, using the supplied transition. Note that the transition will be from the
* screen that was on top prior to this call.
*/
public void push (Iterable<? extends Screen> screens, Transition trans) {
if (!screens.iterator().hasNext()) {
throw new IllegalArgumentException("Cannot push empty list of screens.");
}
if (_screens.isEmpty()) {
for (Screen screen : screens) add(screen);
show(top());
} else {
final Screen otop = top();
Screen last = null;
for (Screen screen : screens) {
if (last != null) add(last);
last = screen;
}
transition(new Transitor(otop, last, trans) {
protected void onComplete() { hide(otop); }
});
}
}
/**
* {@link #popTo(Screen,Transition)} with the default transition.
*/
public void popTo (Screen newTopScreen) {
popTo(newTopScreen, defaultPopTransition());
}
/**
* Pops the top screen from the stack until the specified screen has become the
* topmost/visible screen. If newTopScreen is null or is not on the stack, this will remove
* all screens.
*/
public void popTo (Screen newTopScreen, Transition trans) {
// remove all intervening screens
while (_screens.size() > 1 && _screens.get(1) != newTopScreen) {
removeNonTop(_screens.get(1));
}
// now just pop the top screen
remove(top(), trans);
}
/**
* {@link #replace(Screen,Transition)} with the default transition.
*/
public void replace (Screen screen) {
replace(screen, defaultPushTransition());
}
public void replace (Screen screen, Transition trans) {
if (_screens.isEmpty()) {
addAndShow(screen);
} else {
final Screen otop = top();
transition(new Transitor(otop, screen, trans) {
protected void onComplete () {
hide(otop);
remove(otop);
}
});
}
}
/**
* {@link #remove(Screen,Transition)} with the default transition.
*/
public boolean remove (Screen screen) {
return remove(screen, defaultPopTransition());
}
/**
* Removes the specified screen from the stack. If it is the currently visible screen, it will
* first be hidden, and the next screen below in the stack will be made visible.
*/
public boolean remove (Screen screen, Transition trans) {
if (top() == screen && _screens.size() > 1) {
transition(new Untransitor(screen, _screens.get(1), trans) {
protected void onComplete () {
hide(_oscreen);
removeNonTop(_oscreen);
}
});
return true;
} else {
return removeNonTop(screen);
}
}
/**
* Updates the currently visible screen. A screen stack client should call this method from
* {@link Game#update}.
*/
public void update (float delta) {
if (_transitor != null) _transitor.update(delta);
else if (!_screens.isEmpty()) top().update(delta);
}
/**
* Paints the currently visible screen. A screen stack client should call this method from
* {@link Game#paint}.
*/
public void paint (float alpha) {
if (_transitor != null) _transitor.paint(alpha);
else if (!_screens.isEmpty()) top().paint(alpha);
}
protected Transition defaultPushTransition () {
return NOOP;
}
protected Transition defaultPopTransition () {
return NOOP;
}
protected Screen top () {
return _screens.get(0);
}
protected void add (Screen screen) {
if (_screens.contains(screen)) {
throw new IllegalArgumentException("Cannot add screen to stack twice.");
}
_screens.add(0, screen);
try { screen.wasAdded(); }
catch (RuntimeException e) { handleError(e); }
}
protected void addAndShow (Screen screen) {
add(screen);
show(screen);
}
protected void show (Screen screen) {
PlayN.graphics().rootLayer().add(screen.layer);
try { screen.wasShown(); }
catch (RuntimeException e) { handleError(e); }
}
protected void hide (Screen screen) {
PlayN.graphics().rootLayer().remove(screen.layer);
try { screen.wasHidden(); }
catch (RuntimeException e) { handleError(e); }
}
protected boolean removeNonTop (Screen screen) {
boolean removed = _screens.remove(screen);
if (removed) {
try { screen.wasRemoved(); }
catch (RuntimeException e) { handleError(e); }
}
return removed;
}
protected void transition (Transitor transitor) {
if (_transitor != null) _transitor.complete();
_transitor = transitor;
}
protected class Transitor {
public Transitor (Screen oscreen, Screen nscreen, Transition trans) {
_oscreen = oscreen;
_nscreen = nscreen;
_trans = trans;
_trans.init(oscreen, nscreen);
didInit();
}
public void update (float delta) {
_oscreen.update(delta);
_nscreen.update(delta);
_elapsed += delta;
if (_trans.update(_oscreen, _nscreen, _elapsed)) {
complete();
}
}
public void paint (float alpha) {
_oscreen.paint(alpha);
_nscreen.paint(alpha);
}
public void complete () {
_transitor = null;
// make sure the new screen is in the right position
_nscreen.layer.setTranslation(originX, originY);
_nscreen.showTransitionCompleted();
onComplete();
}
protected void didInit () {
_oscreen.hideTransitionStarted();
addAndShow(_nscreen);
}
protected void onComplete () {}
protected final Screen _oscreen, _nscreen;
protected final Transition _trans;
protected float _elapsed;
}
protected class Untransitor extends Transitor {
public Untransitor (Screen oscreen, Screen nscreen, Transition trans) {
super(oscreen, nscreen, trans);
}
@Override protected void didInit () {
_oscreen.hideTransitionStarted();
show(_nscreen);
}
}
/** Called if any exceptions are thrown by the screen callback functions. */
protected abstract void handleError (RuntimeException error);
/** The currently executing transition, or null. */
protected Transitor _transitor;
/** Containts the stacked screens from top-most, to bottom-most. */
protected final List<Screen> _screens = new ArrayList<Screen>();
}
|
package wge3.entity.terrainelements;
public abstract class MapObject extends TerrainElement {
protected int maxHP;
protected int HP;
protected boolean hasDestroyedSprite;
protected int hardness;
public MapObject() {
// Default values:
maxHP = 100;
HP = maxHP;
passable = true;
blocksVision = true;
drainsHP = false;
hardness = 9;
}
public void dealDamage(int amount) {
HP -= Math.max(amount - hardness, 0);
}
public boolean isDestroyed() {
return HP <= 0;
}
public boolean hasDestroyedSprite() {
return hasDestroyedSprite;
}
}
|
package ch.hsr.ifs.pystructure.playground;
import java.util.LinkedList;
import org.python.pydev.parser.jython.SimpleNode;
import org.python.pydev.parser.jython.ast.Expr;
import org.python.pydev.parser.jython.ast.exprType;
import ch.hsr.ifs.pystructure.typeinference.contexts.PythonContext;
import ch.hsr.ifs.pystructure.typeinference.dltk.types.IEvaluatedType;
import ch.hsr.ifs.pystructure.typeinference.goals.types.ExpressionTypeGoal;
import ch.hsr.ifs.pystructure.typeinference.inferencer.PythonTypeInferencer;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition;
import ch.hsr.ifs.pysucture.typeinference.model.definitions.Definition;
import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module;
import ch.hsr.ifs.pystructure.typeinference.visitors.ExpressionAtLineVisitor;
import ch.hsr.ifs.pystructure.typeinference.visitors.Workspace;
public class Swush {
public static void main(String[] args) {
LinkedList<String> sysPath = new LinkedList<String>();
PythonTypeInferencer inferencer = new PythonTypeInferencer();
String path = "/Users/reto/scripts/pydoku";
Workspace workspace = new Workspace(path, sysPath);
String name = "pydoku";
Module module = workspace.getModule(name);
// Expr expression = getExpressionAtLine(module, 7);
PythonContext context = new PythonContext(workspace, module);
for (Definition<?> x : module.getDefinitions()) {
if (x instanceof AssignDefinition) {
AssignDefinition assign = (AssignDefinition) x;
exprType node = assign.getNode().targets[0];
ExpressionTypeGoal goal = new ExpressionTypeGoal(context, node);
IEvaluatedType type = inferencer.evaluateType(goal, -1);
if (type == null) {
System.out.println("Type inferencer returned null for " + x + " / " + x.getNode());
} else {
System.out.println(" type " + type.getTypeName()) ;
}
}
}
}
private static Expr getExpressionAtLine(Module module, int line) {
SimpleNode rootNode = module.getNode();
ExpressionAtLineVisitor visitor = new ExpressionAtLineVisitor(line);
try {
visitor.traverse(rootNode);
} catch (Exception e) {
throw new RuntimeException(e);
}
Expr expression = visitor.getExpression();
if (expression == null) {
throw new RuntimeException("Unable to find node for expresssion '" + expression + "'");
}
return expression;
}
}
|
package com.genymobile.scrcpy;
import android.util.Log;
/**
* Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal
* directly).
*/
public final class Ln {
private static final String TAG = "scrcpy";
private static final String PREFIX = "[server] ";
enum Level {
DEBUG,
INFO,
WARN,
ERROR;
}
private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO;
private Ln() {
// not instantiable
}
public static boolean isEnabled(Level level) {
return level.ordinal() >= THRESHOLD.ordinal();
}
public static void d(String message) {
if (isEnabled(Level.DEBUG)) {
Log.d(TAG, message);
System.out.println(PREFIX + "DEBUG: " + message);
}
}
public static void i(String message) {
if (isEnabled(Level.INFO)) {
Log.i(TAG, message);
System.out.println(PREFIX + "INFO: " + message);
}
}
public static void w(String message) {
if (isEnabled(Level.WARN)) {
Log.w(TAG, message);
System.out.println(PREFIX + "WARN: " + message);
}
}
public static void e(String message, Throwable throwable) {
if (isEnabled(Level.ERROR)) {
Log.e(TAG, message, throwable);
System.out.println(PREFIX + "ERROR: " + message);
if (throwable != null) {
throwable.printStackTrace();
}
}
}
public static void e(String message) {
e(message, null);
}
}
|
package org.catacombae.util;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
public class Util {
public static class Pair<A,B> {
private A a;
private B b;
public Pair() {
a = null;
b = null;
}
public Pair(A iA, B iB) {
a = iA;
b = iB;
}
public final A getA() { return a; }
public final B getB() { return b; }
public final void setA(A iA) { a = iA; }
public final void setB(B iB) { b = iB; }
}
public static String byteArrayToHexString(byte[] array) {
return byteArrayToHexString(array, 0, array.length);
}
public static String byteArrayToHexString(byte[] array, int offset,
int length)
{
String result = "";
for(int i = offset; i < (offset + length); ++i) {
byte b = array[i];
String currentHexString = Integer.toHexString(b & 0xFF);
if(currentHexString.length() == 1)
currentHexString = "0" + currentHexString;
result += currentHexString;
}
return result;
}
public static String toHexStringBE(char[] array) {
return toHexStringBE(array, 0, array.length);
}
public static String toHexStringBE(char[] array, int offset, int length) {
StringBuilder result = new StringBuilder();
for(int i = offset; i < length; ++i)
result.append(toHexStringBE(array[i]));
return result.toString();
}
public static String toHexStringBE(short[] array) {
return toHexStringBE(array, 0, array.length);
}
public static String toHexStringBE(short[] array, int offset, int length) {
StringBuilder result = new StringBuilder();
for(int i = offset; i < length; ++i)
result.append(toHexStringBE(array[i]));
return result.toString();
}
public static String toHexStringBE(int[] array) {
return toHexStringBE(array, 0, array.length);
}
public static String toHexStringBE(int[] array, int offset, int length) {
StringBuilder result = new StringBuilder();
for(int i = offset; i < length; ++i)
result.append(toHexStringBE(array[i]));
return result.toString();
}
public static String toHexStringLE(byte n) {
return byteArrayToHexString(toByteArrayLE(n));
}
public static String toHexStringLE(short n) {
return byteArrayToHexString(toByteArrayLE(n));
}
public static String toHexStringLE(char n) {
return byteArrayToHexString(toByteArrayLE(n));
}
public static String toHexStringLE(int n) {
return byteArrayToHexString(toByteArrayLE(n));
}
public static String toHexStringLE(long n) {
return byteArrayToHexString(toByteArrayLE(n));
}
public static String toHexStringBE(byte n) {
return byteArrayToHexString(toByteArrayBE(n));
}
public static String toHexStringBE(short n) {
return byteArrayToHexString(toByteArrayBE(n));
}
public static String toHexStringBE(char n) {
return byteArrayToHexString(toByteArrayBE(n));
}
public static String toHexStringBE(int n) {
return byteArrayToHexString(toByteArrayBE(n));
}
public static String toHexStringBE(long n) {
return byteArrayToHexString(toByteArrayBE(n));
}
public static byte[] invert(byte[] array) {
byte[] newArray = new byte[array.length];
for(int i = 0; i < array.length; ++i)
newArray[newArray.length - i - 1] = array[i];
return newArray;
}
public static long readLongLE(byte[] data) {
return readLongLE(data, 0);
}
public static long readLongLE(byte[] data, int offset) {
return (((long) data[offset + 7] & 0xFF) << 56 |
((long) data[offset + 6] & 0xFF) << 48 |
((long) data[offset + 5] & 0xFF) << 40 |
((long) data[offset + 4] & 0xFF) << 32 |
((long) data[offset + 3] & 0xFF) << 24 |
((long) data[offset + 2] & 0xFF) << 16 |
((long) data[offset + 1] & 0xFF) << 8 |
((long) data[offset + 0] & 0xFF) << 0);
}
public static int readIntLE(byte[] data) {
return readIntLE(data, 0);
}
public static int readIntLE(byte[] data, int offset) {
return ((data[offset + 3] & 0xFF) << 24 |
(data[offset + 2] & 0xFF) << 16 |
(data[offset + 1] & 0xFF) << 8 |
(data[offset + 0] & 0xFF) << 0);
}
public static short readShortLE(byte[] data) {
return readShortLE(data, 0);
}
public static short readShortLE(byte[] data, int offset) {
return (short) ((data[offset + 1] & 0xFF) << 8 |
(data[offset + 0] & 0xFF) << 0);
}
public static byte readByteLE(byte[] data) {
return readByteLE(data, 0);
}
public static byte readByteLE(byte[] data, int offset) {
return data[offset];
}
public static long readLongBE(byte[] data) {
return readLongBE(data, 0);
}
public static long readLongBE(byte[] data, int offset) {
return (((long) data[offset + 0] & 0xFF) << 56 |
((long) data[offset + 1] & 0xFF) << 48 |
((long) data[offset + 2] & 0xFF) << 40 |
((long) data[offset + 3] & 0xFF) << 32 |
((long) data[offset + 4] & 0xFF) << 24 |
((long) data[offset + 5] & 0xFF) << 16 |
((long) data[offset + 6] & 0xFF) << 8 |
((long) data[offset + 7] & 0xFF) << 0);
}
public static int readIntBE(byte[] data) {
return readIntBE(data, 0);
}
public static int readIntBE(byte[] data, int offset) {
return ((data[offset + 0] & 0xFF) << 24 |
(data[offset + 1] & 0xFF) << 16 |
(data[offset + 2] & 0xFF) << 8 |
(data[offset + 3] & 0xFF) << 0);
}
public static short readShortBE(byte[] data) {
return readShortBE(data, 0);
}
public static short readShortBE(byte[] data, int offset) {
return (short) ((data[offset + 0] & 0xFF) << 8 |
(data[offset + 1] & 0xFF) << 0);
}
public static byte readByteBE(byte[] data) {
return readByteBE(data, 0);
}
public static byte readByteBE(byte[] data, int offset) {
return data[offset];
}
public static byte[] toByteArrayLE(byte b) {
byte[] result = new byte[1];
result[0] = b;
return result;
}
public static byte[] toByteArrayLE(short s) {
byte[] result = new byte[2];
arrayPutLE(result, 0, s);
return result;
}
public static byte[] toByteArrayLE(char c) {
byte[] result = new byte[2];
arrayPutLE(result, 0, c);
return result;
}
public static byte[] toByteArrayLE(int i) {
byte[] result = new byte[4];
arrayPutLE(result, 0, i);
return result;
}
public static byte[] toByteArrayLE(long l) {
byte[] result = new byte[8];
arrayPutLE(result, 0, l);
return result;
}
public static byte[] toByteArrayBE(byte b) {
byte[] result = new byte[1];
result[0] = b;
return result;
}
public static byte[] toByteArrayBE(short s) {
byte[] result = new byte[2];
arrayPutBE(result, 0, s);
return result;
}
public static byte[] toByteArrayBE(char c) {
byte[] result = new byte[2];
arrayPutBE(result, 0, c);
return result;
}
public static byte[] toByteArrayBE(int i) {
byte[] result = new byte[4];
arrayPutBE(result, 0, i);
return result;
}
public static byte[] toByteArrayBE(long l) {
byte[] result = new byte[8];
arrayPutBE(result, 0, l);
return result;
}
public static boolean zeroed(byte[] ba) {
for(byte b : ba)
if(b != 0)
return false;
return true;
}
public static void zero(byte[]... arrays) {
for(byte[] ba : arrays)
set(ba, 0, ba.length, (byte)0);
}
public static void zero(byte[] ba, int offset, int length) {
set(ba, offset, length, (byte)0);
}
public static void zero(short[]... arrays) {
for(short[] array : arrays)
set(array, 0, array.length, (short)0);
}
public static void zero(short[] ba, int offset, int length) {
set(ba, offset, length, (short) 0);
}
public static void zero(int[]... arrays) {
for(int[] array : arrays)
set(array, 0, array.length, (int) 0);
}
public static void zero(int[] ba, int offset, int length) {
set(ba, offset, length, (int) 0);
}
public static void zero(long[]... arrays) {
for(long[] array : arrays)
set(array, 0, array.length, (long) 0);
}
public static void zero(long[] ba, int offset, int length) {
set(ba, offset, length, (long) 0);
}
public static void set(boolean[] array, boolean value) {
set(array, 0, array.length, value);
}
public static void set(byte[] array, byte value) {
set(array, 0, array.length, value);
}
public static void set(short[] array, short value) {
set(array, 0, array.length, value);
}
public static void set(char[] array, char value) {
set(array, 0, array.length, value);
}
public static void set(int[] array, int value) {
set(array, 0, array.length, value);
}
public static void set(long[] array, long value) {
set(array, 0, array.length, value);
}
public static <T> void set(T[] array, T value) {
set(array, 0, array.length, value);
}
public static void set(boolean[] ba, int offset, int length, boolean value)
{
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static void set(byte[] ba, int offset, int length, byte value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static void set(short[] ba, int offset, int length, short value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static void set(char[] ba, int offset, int length, char value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static void set(int[] ba, int offset, int length, int value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static void set(long[] ba, int offset, int length, long value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static <T> void set(T[] ba, int offset, int length, T value) {
for(int i = offset; i < length; ++i)
ba[i] = value;
}
public static byte[] createCopy(byte[] data) {
return createCopy(data, 0, data.length);
}
public static byte[] createCopy(byte[] data, int offset, int length) {
byte[] copy = new byte[length];
System.arraycopy(data, offset, copy, 0, length);
return copy;
}
public static char[] createCopy(char[] data) {
return createCopy(data, 0, data.length);
}
public static char[] createCopy(char[] data, int offset, int length) {
char[] copy = new char[length];
System.arraycopy(data, offset, copy, 0, length);
return copy;
}
public static short[] createCopy(short[] data) {
return createCopy(data, 0, data.length);
}
public static short[] createCopy(short[] data, int offset, int length) {
short[] copy = new short[length];
System.arraycopy(data, offset, copy, 0, length);
return copy;
}
public static int[] createCopy(int[] data) {
return createCopy(data, 0, data.length);
}
public static int[] createCopy(int[] data, int offset, int length) {
int[] copy = new int[length];
System.arraycopy(data, offset, copy, 0, length);
return copy;
}
public static long[] createCopy(long[] data) {
return createCopy(data, 0, data.length);
}
public static long[] createCopy(long[] data, int offset, int length) {
long[] copy = new long[length];
System.arraycopy(data, offset, copy, 0, length);
return copy;
}
/**
* Creates a copy of the input data reversed byte by byte. This is helpful
* for endian swapping.
*
* @param data
* @return a copy of the input data reversed byte by byte.
*/
public static byte[] createReverseCopy(byte[] data) {
return createReverseCopy(data, 0, data.length);
}
/**
* Creates a copy of the input data reversed byte by byte. This is helpful
* for endian swapping.
*
* @param data
* @param offset
* @param length
* @return a copy of the input data reversed byte by byte.
*/
public static byte[] createReverseCopy(byte[] data, int offset, int length)
{
byte[] copy = new byte[length];
for(int i = 0; i < copy.length; ++i) {
copy[i] = data[offset + (length - i - 1)];
}
return copy;
}
public static byte[] arrayCopy(byte[] source, byte[] dest) {
return arrayCopy(source, dest, 0);
}
public static byte[] arrayCopy(byte[] source, byte[] dest, int destPos) {
if(dest.length - destPos < source.length)
throw new RuntimeException("Destination array not large enough.");
System.arraycopy(source, 0, dest, 0, source.length);
return dest;
}
public static <T> T[] arrayCopy(T[] source, T[] dest) {
return arrayCopy(source, dest, 0);
}
public static <T> T[] arrayCopy(T[] source, T[] dest, int destPos) {
return arrayCopy(source, 0, dest, destPos, source.length);
}
public static <T> T[] arrayCopy(T[] source, int sourcePos, T[] dest,
int destPos, int length)
{
if(source.length - sourcePos < length)
throw new RuntimeException("Source array not large enough.");
if(dest.length - destPos < length)
throw new RuntimeException("Destination array not large enough.");
System.arraycopy(source, sourcePos, dest, destPos, length);
return dest;
}
public static boolean arraysEqual(boolean[] a, boolean[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(boolean[] a, int aoff, int alen,
boolean[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(byte[] a, byte[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(byte[] a, int aoff, int alen,
byte[] b, int boff, int blen) {
if(a.length != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(char[] a, char[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(char[] a, int aoff, int alen,
char[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(short[] a, short[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(short[] a, int aoff, int alen,
short[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(int[] a, int[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(int[] a, int aoff, int alen,
int[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(long[] a, long[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(long[] a, int aoff, int alen,
long[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(a[aoff + i] != b[boff + i])
return false;
return true;
}
}
public static boolean arraysEqual(Object[] a, Object[] b) {
return arrayRegionsEqual(a, 0, a.length, b, 0, b.length);
}
public static boolean arrayRegionsEqual(Object[] a, int aoff, int alen,
Object[] b, int boff, int blen) {
if(alen != blen)
return false;
else {
for(int i = 0; i < alen; ++i)
if(!a[aoff + i].equals(b[boff + i]))
return false;
return true;
}
}
public static long pow(long a, long b) {
if(b < 0)
throw new IllegalArgumentException("b can not be negative");
long result = 1;
for(long i = 0; i < b; ++i)
result *= a;
return result;
}
public static int strlen(byte[] data) {
int length = 0;
for(byte b : data) {
if(b == 0)
break;
else
++length;
}
return length;
}
public static boolean getBit(long data, int bitNumber) {
return ((data >>> bitNumber) & 0x1) == 0x1;
}
public static byte setBit(byte data, int bitNumber, boolean value) {
if(bitNumber < 0 || bitNumber > 7)
throw new IllegalArgumentException("bitNumber out of range");
return (byte) setBit(data & 0xFF, bitNumber, value);
}
public static short setBit(short data, int bitNumber, boolean value) {
if(bitNumber < 0 || bitNumber > 15)
throw new IllegalArgumentException("bitNumber out of range");
return (short) setBit(data & 0xFFFF, bitNumber, value);
}
public static char setBit(char data, int bitNumber, boolean value) {
if(bitNumber < 0 || bitNumber > 15)
throw new IllegalArgumentException("bitNumber out of range");
return (char) setBit(data & 0xFFFF, bitNumber, value);
}
public static int setBit(int data, int bitNumber, boolean value) {
if(bitNumber < 0 || bitNumber > 31)
throw new IllegalArgumentException("bitNumber out of range");
if(value)
return data | (0x1 << bitNumber);
else
return data & (data ^ (0x1 << bitNumber));
}
public static long setBit(long data, int bitNumber, boolean value) {
if(bitNumber < 0 || bitNumber > 63)
throw new IllegalArgumentException("bitNumber out of range");
if(value)
return data | (0x1 << bitNumber);
else
return data & (data ^ (0x1 << bitNumber));
}
public static int arrayCompareLex(byte[] a, byte[] b) {
return arrayCompareLex(a, 0, a.length, b, 0, b.length);
}
public static int arrayCompareLex(byte[] a, int aoff, int alen, byte[] b,
int boff, int blen)
{
int compareLen = alen < blen ? alen : blen; // equiv. Math.min
for(int i = 0; i < compareLen; ++i) {
byte curA = a[aoff + i];
byte curB = b[boff + i];
if(curA != curB)
return curA - curB;
}
return alen - blen; // The shortest array gets higher priority
}
public static int unsignedArrayCompareLex(byte[] a, byte[] b) {
return unsignedArrayCompareLex(a, 0, a.length, b, 0, b.length);
}
public static int unsignedArrayCompareLex(byte[] a, int aoff, int alen,
byte[] b, int boff, int blen)
{
int compareLen = alen < blen ? alen : blen; // equiv. Math.min
for(int i = 0; i < compareLen; ++i) {
int curA = a[aoff + i] & 0xFF;
int curB = b[boff + i] & 0xFF;
if(curA != curB)
return curA - curB;
}
return alen - blen; // The shortest array gets higher priority
}
public static int unsignedArrayCompareLex(char[] a, char[] b) {
return unsignedArrayCompareLex(a, 0, a.length, b, 0, b.length);
}
public static int unsignedArrayCompareLex(char[] a, int aoff, int alen,
char[] b, int boff, int blen)
{
int compareLen = alen < blen ? alen : blen; // equiv. Math.min
for(int i = 0; i < compareLen; ++i) {
int curA = a[aoff + i] & 0xFFFF; // Unsigned char values represented as int
int curB = b[boff + i] & 0xFFFF;
if(curA != curB)
return curA - curB;
}
return alen - blen; // The shortest array gets higher priority
}
// All below is from Util2 (got tired of having two Util classes...)
public static String toASCIIString(byte[] data) {
return toASCIIString(data, 0, data.length);
}
public static String toASCIIString(byte[] data, int offset, int length) {
return readString(data, offset, length, "US-ASCII");
}
public static String toASCIIString(short i) {
return toASCIIString(Util.toByteArrayBE(i));
}
public static String toASCIIString(int i) {
return toASCIIString(Util.toByteArrayBE(i));
}
public static String readString(byte[] data, String encoding) {
return readString(data, 0, data.length, encoding);
}
public static String readString(byte[] data, int offset, int length,
String encoding)
{
try {
return new String(data, offset, length, encoding);
} catch(Exception e) {
return null;
}
}
public static String readString(short i, String encoding) {
return readString(Util.toByteArrayBE(i), encoding);
}
public static String readString(int i, String encoding) {
return readString(Util.toByteArrayBE(i), encoding);
}
public static String readNullTerminatedASCIIString(byte[] data) {
return readNullTerminatedASCIIString(data, 0, data.length);
}
public static String readNullTerminatedASCIIString(byte[] data, int offset,
int maxLength)
{
int i;
for(i = offset; i < (offset + maxLength); ++i)
if(data[i] == 0)
break;
return toASCIIString(data, offset, i - offset);
}
public static char readCharLE(byte[] data) {
return readCharLE(data, 0);
}
public static char readCharLE(byte[] data, int offset) {
return (char) ((data[offset + 1] & 0xFF) << 8 |
(data[offset + 0] & 0xFF) << 0);
}
public static char readCharBE(byte[] data) {
return readCharBE(data, 0);
}
public static char readCharBE(byte[] data, int offset) {
return (char) ((data[offset + 0] & 0xFF) << 8 |
(data[offset + 1] & 0xFF) << 0);
}
/** Stupid method which should go away. */
public static byte[] readByteArrayBE(byte[] b) {
return readByteArrayBE(b, 0, b.length);
}
/** Stupid method which should go away. */
public static byte[] readByteArrayBE(byte[] b, int offset, int size) {
return createCopy(b, offset, size);
}
public static char[] readCharArrayBE(byte[] b) {
char[] result = new char[b.length / 2];
for(int i = 0; i < result.length; ++i)
result[i] = Util.readCharBE(b, i * 2);
return result;
}
public static short[] readShortArrayBE(byte[] b) {
short[] result = new short[b.length / 2];
for(int i = 0; i < result.length; ++i)
result[i] = Util.readShortBE(b, i * 2);
return result;
}
public static int[] readIntArrayBE(byte[] b) {
int[] result = new int[b.length / 4];
for(int i = 0; i < result.length; ++i)
result[i] = Util.readIntBE(b, i * 4);
return result;
}
public static long[] readLongArrayBE(byte[] b) {
long[] result = new long[b.length / 8];
for(int i = 0; i < result.length; ++i)
result[i] = Util.readLongBE(b, i * 8);
return result;
}
public static byte[] readByteArrayLE(char[] data) {
return readByteArrayLE(data, 0, data.length);
}
public static byte[] readByteArrayLE(char[] data, int offset, int size) {
byte[] result = new byte[data.length * 2];
for(int i = 0; i < data.length; ++i) {
byte[] cur = toByteArrayLE(data[i]);
result[i * 2] = cur[0];
result[i * 2 + 1] = cur[1];
}
return result;
}
public static byte[] readByteArrayBE(char[] data) {
return readByteArrayBE(data, 0, data.length);
}
public static byte[] readByteArrayBE(char[] data, int offset, int size) {
byte[] result = new byte[data.length * 2];
for(int i = 0; i < data.length; ++i) {
byte[] cur = toByteArrayBE(data[i]);
result[i * 2] = cur[0];
result[i * 2 + 1] = cur[1];
}
return result;
}
public static byte[] fillBuffer(InputStream is, byte[] buffer)
throws IOException
{
DataInputStream dis = new DataInputStream(is);
dis.readFully(buffer);
return buffer;
}
public static short unsign(byte b) {
return (short) (b & 0xFF);
}
public static int unsign(short s) {
return s & 0xFFFF;
}
public static int unsign(char s) {
return s & 0xFFFF;
}
public static long unsign(int i) {
return i & 0xFFFFFFFFL;
}
public static BigInteger unsign(long l) {
return new BigInteger(1, toByteArrayBE(l));
}
public static short[] unsign(byte[] ab) {
short[] res = new short[ab.length];
for(int i = 0; i < ab.length; ++i)
res[i] = unsign(ab[i]);
return res;
}
public static int[] unsign(short[] as) {
int[] res = new int[as.length];
for(int i = 0; i < as.length; ++i)
res[i] = unsign(as[i]);
return res;
}
public static int[] unsign(char[] ac) {
int[] res = new int[ac.length];
for(int i = 0; i < ac.length; ++i)
res[i] = unsign(ac[i]);
return res;
}
public static long[] unsign(int[] ai) {
long[] res = new long[ai.length];
for(int i = 0; i < ai.length; ++i)
res[i] = unsign(ai[i]);
return res;
}
public static BigInteger[] unsign(long[] al) {
BigInteger[] res = new BigInteger[al.length];
for(int i = 0; i < al.length; ++i)
res[i] = unsign(al[i]);
return res;
}
// Added 2007-06-24 for DMGExtractor
public static String readFully(Reader r) throws IOException {
StringBuilder sb = new StringBuilder();
char[] temp = new char[512];
long bytesRead = 0;
int curBytesRead = r.read(temp, 0, temp.length);
while(curBytesRead >= 0) {
sb.append(temp, 0, curBytesRead);
curBytesRead = r.read(temp, 0, temp.length);
}
return sb.toString();
}
// Added 2007-06-26 for DMGExtractor
public static String[] concatenate(String[] a, String... b) {
String[] c = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
public static <T> T[] concatenate(T[] a, T[] b, T[] target) {
System.arraycopy(a, 0, target, 0, a.length);
System.arraycopy(b, 0, target, a.length, b.length);
return target;
}
// From IRCForME
public static byte[] encodeString(String string, String encoding) {
try {
return string.getBytes(encoding);
} catch(Exception e) {
return null;
}
}
/**
* Encodes a String containing only ASCII characters into an ASCII-encoded
* byte array.
*
* @param s source string.
* @return the ASCII-encoded byte string corresponding to <code>s</code>.
*/
public static byte[] encodeASCIIString(String s) {
byte[] result = new byte[s.codePointCount(0, s.length())];
encodeASCIIString(s, 0, result, 0, result.length);
return result;
}
/**
* Encodes a String containing only ASCII characters into ASCII-encoded
* data, stored in <code>b</code>.
*
* @param s source string.
* @param sPos read position in source String.
* @param b target array.
* @param bPos store position in target array.
* @param len the number of codepoints to read from <code>s</code> and
* thus the number of bytes to write to <code>b</code>.
*/
public static void encodeASCIIString(String s, int sPos, byte[] b, int bPos,
final int len)
{
for(int i = 0; i < len; ++i) {
int curCodePoint = s.codePointAt(i+sPos);
if(curCodePoint >= 0 && curCodePoint < 0x80) {
b[i+bPos] = (byte) curCodePoint;
}
else {
throw new IllegalArgumentException("Illegal ASCII character: " +
"\"" + new String(new int[]{curCodePoint}, 0, 1) +
"\" (0x" + Util.toHexStringBE(curCodePoint) + ")");
}
}
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static boolean contains(byte[] array, byte element) {
for(byte b : array) {
if(b == element)
return true;
}
return false;
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static boolean contains(char[] array, char element) {
for(char c : array) {
if(c == element)
return true;
}
return false;
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static boolean contains(short[] array, short element) {
for(short s : array) {
if(s == element)
return true;
}
return false;
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static boolean contains(int[] array, int element) {
for(int i : array) {
if(i == element)
return true;
}
return false;
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static boolean contains(long[] array, long element) {
for(long l : array) {
if(l == element)
return true;
}
return false;
}
/**
* Checks if the given <code>array</code> contains the specified
* <code>element</code> at least once.
*
* @param array the array to search.
* @param element the element to look for.
* @return true if <code>element</code> was present in <code>array</code>,
* and false otherwise.
*/
public static <A> boolean contains(A[] array, A element) {
for(A a : array) {
if(a == element)
return true;
}
return false;
}
/**
* Checks if the given list of arrays contains an array that is equal to
* <code>array</code> by the definition of Arrays.equal(..) (both arrays
* must have the same number of elements, and every pair of elements must be
* equal according to Object.equals).
*
* @param <A> the type of the array.
* @param listOfArrays the list of arrays to search.
* @param array the array to match.
* @return <code>true</code> if an equal to <code>array</code> was found in
* <code>listOfArrays</code>, otherwise <code>false</code>.
*/
public static <A> boolean contains(List<A[]> listOfArrays, A[] array) {
for(A[] curArray : listOfArrays) {
if(Arrays.equals(curArray, array))
return true;
}
return false;
}
/**
* Concatenates the <code>strings</code> into one big string, putting
* <code>glueString</code> between each pair. Example:<br/>
* <code>concatenateStrings(new String[] {"joe", "lisa", "bob"},
* " and ");</code> yields the string "joe and lisa and bob".
*
* @param strings
* @param glueString
* @return the input strings concatenated into one string, adding the
* <code>glueString</code> between each pair.
*/
public static String concatenateStrings(Object[] strings, String glueString)
{
if(strings.length > 0) {
StringBuilder sb = new StringBuilder(strings[0].toString());
for(int i = 1; i < strings.length; ++i)
sb.append(glueString).append(strings[i].toString());
return sb.toString();
}
else
return "";
}
public static String concatenateStrings(List<? extends Object> strings,
String glueString)
{
if(strings.size() > 0) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for(Object s : strings) {
if(!first)
sb.append(glueString);
else
first = false;
sb.append(s.toString());
}
return sb.toString();
}
else
return "";
}
public static String addUnitSpaces(String string, int unitSize) {
int parts = string.length() / unitSize;
StringBuilder sizeStringBuilder = new StringBuilder();
String head = string.substring(0, string.length() - parts * unitSize);
if(head.length() > 0)
sizeStringBuilder.append(head);
for(int i = parts - 1; i >= 0; --i) {
if(i < parts-1 || (i == parts-1 && head.length() > 0))
sizeStringBuilder.append(" ");
sizeStringBuilder.append(string.substring(string.length() -
(i + 1) * unitSize, string.length() - i * unitSize));
}
return sizeStringBuilder.toString();
}
public static void buildStackTrace(Throwable t, int maxStackTraceLines,
StringBuilder sb)
{
int stackTraceLineCount = 0;
Throwable curThrowable = t;
while(curThrowable != null && stackTraceLineCount < maxStackTraceLines)
{
sb.append(curThrowable.toString()).append("\n");
++stackTraceLineCount;
for(StackTraceElement ste : curThrowable.getStackTrace()) {
if(stackTraceLineCount < maxStackTraceLines) {
sb.append(" ").append(ste.toString()).append("\n");
}
++stackTraceLineCount;
}
Throwable cause = curThrowable.getCause();
if(cause != null) {
if(stackTraceLineCount < maxStackTraceLines) {
sb.append("Caused by:\n");
++stackTraceLineCount;
}
}
curThrowable = cause;
}
if(stackTraceLineCount >= maxStackTraceLines)
sb.append("...and ").append(stackTraceLineCount-maxStackTraceLines).
append(" more.");
}
/**
* Reverses the order of the array <code>data</code>.
*
* @param data the array to reverse.
* @return <code>data</code>.
*/
public static byte[] byteSwap(byte[] data) {
return byteSwap(data, 0, data.length);
}
/**
* Reverses the order of the range defined by <code>offset</code> and
* <code>length</code> in the array <code>data</code>.
*
* @param data the array to reverse.
* @param offset the start offset of the region to reverse.
* @param length the length of the region to reverse.
* @return <code>data</code>.
*/
public static byte[] byteSwap(byte[] data, int offset, int length) {
int endOffset = offset + length - 1;
int middleOffset = offset + (length / 2);
byte tmp;
for(int head = offset; head < middleOffset; ++head) {
int tail = endOffset - head;
if(head == tail)
break;
// Swap data[head] and data[tail]
tmp = data[head];
data[head] = data[tail];
data[tail] = tmp;
}
return data;
}
/**
* Reverses the byte order of <code>i</code>. If <code>i</code> is
* Big Endian, the result will be Little Endian, and vice versa.
*
* @param i the value for which we want to reverse the byte order.
* @return the value of <code>i</code> in reversed byte order.
*/
public static short byteSwap(short i) {
return (short) (((i & 0xFF) << 8) | ((i >> 8) & 0xFF));
}
/**
* Reverses the byte order of <code>i</code>. If <code>i</code> is
* Big Endian, the result will be Little Endian, and vice versa.
*
* @param i the value for which we want to reverse the byte order.
* @return the value of <code>i</code> in reversed byte order.
*/
public static char byteSwap(char i) {
return (char) (((i & 0xFF) << 8) | ((i >> 8) & 0xFF));
}
/**
* Reverses the byte order of <code>i</code>. If <code>i</code> is
* Big Endian, the result will be Little Endian, and vice versa.
*
* @param i the value for which we want to reverse the byte order.
* @return the value of <code>i</code> in reversed byte order.
*/
public static int byteSwap(int i) {
return (((i & 0xFF) << 24) |
((i & 0xFF00) << 8) |
((i >> 8) & 0xFF00) |
((i >> 24) & 0xFF));
}
/**
* Reverses the byte order of <code>i</code>. If <code>i</code> is
* Big Endian, the result will be Little Endian, and vice versa.
*
* @param i the value for which we want to reverse the byte order.
* @return the value of <code>i</code> in reversed byte order.
*/
public static long byteSwap(long i) {
return (((i & 0xFFL) << 56) |
((i & 0xFF00L) << 40) |
((i & 0xFF0000L) << 24) |
((i & 0xFF000000L) << 8) |
((i >> 8) & 0xFF000000L) |
((i >> 24) & 0xFF0000L) |
((i >> 40) & 0xFF00L) |
((i >> 56) & 0xFFL));
}
/**
* Writes the specified native type to <code>array</code> using Big Endian
* representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutBE(byte[] array, int pos, byte data) {
array[pos+0] = data;
}
/**
* Writes the specified native type to <code>array</code> using Big Endian
* representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutBE(byte[] array, int pos, short data) {
array[pos+0] = (byte) ((data >> 8) & 0xFF);
array[pos+1] = (byte) ((data >> 0) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Big Endian
* representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutBE(byte[] array, int pos, char data) {
array[pos+0] = (byte) ((data >> 8) & 0xFF);
array[pos+1] = (byte) ((data >> 0) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Big Endian
* representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutBE(byte[] array, int pos, int data) {
array[pos+0] = (byte) ((data >> 24) & 0xFF);
array[pos+1] = (byte) ((data >> 16) & 0xFF);
array[pos+2] = (byte) ((data >> 8) & 0xFF);
array[pos+3] = (byte) ((data >> 0) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Big Endian
* representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutBE(byte[] array, int pos, long data) {
array[pos+0] = (byte) ((data >> 56) & 0xFF);
array[pos+1] = (byte) ((data >> 48) & 0xFF);
array[pos+2] = (byte) ((data >> 40) & 0xFF);
array[pos+3] = (byte) ((data >> 32) & 0xFF);
array[pos+4] = (byte) ((data >> 24) & 0xFF);
array[pos+5] = (byte) ((data >> 16) & 0xFF);
array[pos+6] = (byte) ((data >> 8) & 0xFF);
array[pos+7] = (byte) ((data >> 0) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Little
* Endian representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutLE(byte[] array, int pos, byte data) {
array[pos+0] = data;
}
/**
* Writes the specified native type to <code>array</code> using Little
* Endian representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutLE(byte[] array, int pos, short data) {
array[pos+0] = (byte) ((data >> 0) & 0xFF);
array[pos+1] = (byte) ((data >> 8) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Little
* Endian representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutLE(byte[] array, int pos, char data) {
array[pos+0] = (byte) ((data >> 0) & 0xFF);
array[pos+1] = (byte) ((data >> 8) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Little
* Endian representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutLE(byte[] array, int pos, int data) {
array[pos+0] = (byte) ((data >> 0) & 0xFF);
array[pos+1] = (byte) ((data >> 8) & 0xFF);
array[pos+2] = (byte) ((data >> 16) & 0xFF);
array[pos+3] = (byte) ((data >> 24) & 0xFF);
}
/**
* Writes the specified native type to <code>array</code> using Little
* Endian representation.
*
* @param array the array to which we should write.
* @param pos the position in the array where writing should begin.
* @param data the data to write.
*/
public static void arrayPutLE(byte[] array, int pos, long data) {
array[pos+0] = (byte) ((data >> 0) & 0xFF);
array[pos+1] = (byte) ((data >> 8) & 0xFF);
array[pos+2] = (byte) ((data >> 16) & 0xFF);
array[pos+3] = (byte) ((data >> 24) & 0xFF);
array[pos+4] = (byte) ((data >> 32) & 0xFF);
array[pos+5] = (byte) ((data >> 40) & 0xFF);
array[pos+6] = (byte) ((data >> 48) & 0xFF);
array[pos+7] = (byte) ((data >> 56) & 0xFF);
}
}
|
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* Value type indicating that the value contains an Object.
*/
public static final int VALUE_TYPE_SERIALIZABLE= 7;
/**
* Value type indicating that the value contains binary data:
* BLOB, CLOB, ...
*/
public static final int VALUE_TYPE_BINARY = 8;
/**
* The descriptions of the value types.
*/
private static final String valueTypeCode[]=
{
"-", // $NON-NLS-1$
"Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable", "Binary" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$ $NON-NLS-7$
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
// clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
// clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
// clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param valType The type to convert to.
*/
private void convertTo(int valType)
{
if (value!=null)
{
switch(valType)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
case VALUE_TYPE_BINARY : value = new ValueBinary(value.getBytes()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param valType Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int valType, int length, int precision)
{
this(name, valType);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
// clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
// clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
// clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
// clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
// clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
// clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BINARY, with a name, containing a bytes value
*
* @param name Sets the name of the Value
* @param b The bytes to store in this Value
*/
public Value(String name, byte[] b)
{
clearValue();
setValue(b);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
// setType(v.getType()); // Is this really needed???
value = v.getValueCopy();
setName(v.getName());
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
setNull(true);
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
if (value!=null) retval.value = (ValueInterface) value.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
public void setSerializedValue(Serializable ser) {
if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser);
else value.setSerializable(ser);
setNull(ser==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Sets the Value to a byte array
* @param b The byte array to which the Value has to be set.
*/
public void setValue(byte[] b)
{
if (value==null || value.getType()!=VALUE_TYPE_BINARY) value = new ValueBinary(b);
else value.setBytes(b);
if ( b == null )
setNull(true);
else
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null || isNull()) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null || isNull()) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null || isNull()) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null || isNull()) return null;
return value.getDate();
}
/**
* Get the Serializable of this Value.
* If the Value is not of type Serializable, it returns null.
* @return the Serializable of this Value.
*/
public Serializable getSerializable()
{
if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null;
return value.getSerializable();
}
public boolean getBoolean()
{
if (value==null || isNull()) return false;
return value.getBoolean();
}
public long getInteger()
{
if (value==null || isNull()) return 0L;
return value.getInteger();
}
public byte[] getBytes()
{
if (value==null || isNull()) return null;
return value.getBytes();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is of type Serializable
* @return true if this value has type Serializable
*/
public boolean isSerializableType() {
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_SERIALIZABLE;
}
/**
* Checks whether or not this value is of type Binary
* @return true if this value has type Binary
*/
public boolean isBinary() {
// Serializable is not included here as it used for
// internal purposes only.
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_BINARY;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
case VALUE_TYPE_BINARY : retval=toStringBinary(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toStringMeta()
{
// We (Sven Boden) did explicit performance testing for this
// part. The original version used Strings instead of StringBuffers,
// performance between the 2 does not differ that much. A few milliseconds
// on 100000 iterations in the advantage of StringBuffers. The
// lessened creation of objects may be worth it in the long run.
StringBuffer retval=new StringBuffer(getTypeDesc());
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval.append('(').append(getLength()).append(')');
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval.append('(').append(getLength());
if (getPrecision()>0)
{
retval.append(", ").append(getPrecision());
}
retval.append(')');
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval.append('(').append(getLength()).append(')');
}
break;
default: break;
}
return retval.toString();
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
if (pad)
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
retval=ret.toString();
}
else
{
if (isNull() || value.getString()==null)
{
retval=Const.NULL_STRING;
}
else
{
retval = value.getString();
}
}
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern("
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form.format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
for (i=0;i<value.getLength();i++) fmt.append('0');
fmt.append(".00"); // for the .00
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=Double.toString(value.getNumber());
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US);
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
/*
This code was removed as TYPE_VALUE_DATE does not know "length", so this
could never be called anyway
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
*/
return retval;
}
/**
* Returns a String representing the boolean value.
* It will be either "true" or "false".
*
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
retval=value.getBoolean()?"true":"false";
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat("
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
if (pad)
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign.
int len = getLength();
for (i=0;i<len;i++) fmt.append('0'); // all zeroes.
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
else
{
retval = Long.toString(value.getInteger());
}
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Returns a String representing the binary value.
*
* @return a String representing the binary value.
*/
private String toStringBinary(boolean pad)
{
String retval;
if (value==null) return null;
if (isNull() || value.getBytes() == null)
{
retval=Const.NULL_BINARY;
}
else
{
retval = new String(value.getBytes());
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return valueTypeCode[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.VALUE_TYPE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<valueTypeCode.length;i++)
{
if (valueTypeCode[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[valueTypeCode.length-1];
System.arraycopy(valueTypeCode, 1, retval, 0, valueTypeCode.length-1);
return retval;
}
/**
* Get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[valueTypeCode.length];
System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length);
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt(getType());
// Handle name-length
dos.writeInt(name.length());
// Write name
dos.writeChars(name);
// length & precision
dos.writeInt(getLength());
dos.writeInt(getPrecision());
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes("UTF-8").length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
dos.flush();
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar());
setName(new String(nameBuffer));
// length & precision
setLength(dis.readInt(), dis.readInt());
// Null?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
//int dataLength=dis.readInt();
//if (dataLength>0)
String string = dis.readUTF();
setValue(string);
//else
// setValue("");
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
//if (getString()!=null && getString().getBytes().length>0)
{
// dos.writeInt(getString().getBytes().length);
dos.writeUTF(getString());
}
// else
// dos.writeInt(0);
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
dos.flush();
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
// int dataLength=dis.readInt();
// if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
if (metaData.isBigNumber()) convertString(metaData.getType());
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached while reading value", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null);
boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_STRING:
{
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
int cmp=0;
if (caseInsensitive)
{
cmp = one.compareToIgnoreCase(two);
}
else
{
cmp = one.compareTo(two);
}
return cmp;
}
case VALUE_TYPE_INTEGER:
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_DATE :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BOOLEAN:
{
if (getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if (getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
}
case VALUE_TYPE_NUMBER :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BIGNUMBER:
{
return getBigNumber().compareTo(v.getBigNumber());
}
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
if (isNull() || v.isNull())
{
setNull();
}
else
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if (isNull() || v.isNull())
{
setNull();
return this;
}
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue(getBigNumber().multiply(v.getBigNumber()));
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue(getNumber()*v.getNumber());
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue(getInteger()*v.getInteger());
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull())
{
return this;
}
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new
KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap()
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.initCap(getString()) );
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds off to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Right trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); }
public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol );
if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) );
if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (format!=null && format.length()>0) df.applyPattern(format);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
setValue(new Date(getInteger()));
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if ( !Const.isEmpty(pattern ) ) df.applyPattern( pattern );
if ( !Const.isEmpty(decimal ) ) dfs.setDecimalSeparator( decimal.charAt(0) );
if ( !Const.isEmpty(grouping) ) dfs.setGroupingSeparator( grouping.charAt(0) );
if ( !Const.isEmpty(currency) ) dfs.setCurrencySymbol( currency );
try
{
df.setDecimalFormatSymbols(dfs);
setValue( df.parse(getString()).doubleValue() );
}
catch(Exception e)
{
String message = "Couldn't convert string to number "+e.toString();
if ( !Const.isEmpty(pattern ) ) message+=" pattern="+pattern;
if ( !Const.isEmpty(decimal ) ) message+=" decimal="+decimal;
if ( !Const.isEmpty(grouping) ) message+=" grouping="+grouping.charAt(0);
if ( !Const.isEmpty(currency) ) message+=" currency="+currency;
throw new KettleValueException(message);
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/**
* Add a number of days to a Date value.
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0);
// MILI-SECONDS
case 0: cal.set(Calendar.MILLISECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 0 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "61".
*
* Note that transformations happen in groups of 2 hex characters, so
* the value of a characters is always in the range 0-255.
*
* @return Value itself
* @throws KettleValueException
*/
public Value byteToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hi nibble
hexString.append(hexDigits[s[i] & 0x000F]); // lo nibble
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of odd length a leading zero will be used.
*
* Note that only the low byte of a character will be processed, this
* is for binary transformations.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToByteDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 1) / 2];
boolean evenByte = true;
int nextByte = 0;
// we assume a leading 0 if the length is not even.
if ((len % 2) == 1)
evenByte = false;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (evenByte)
{
nextByte = (nibble << 4);
}
else
{
nextByte += nibble;
chArray[j] = (char)nextByte;
j++;
}
evenByte = ! evenByte;
}
setValue(new String(chArray));
return this;
}
/**
* Change a string into its hexadecimal representation. E.g. if Value
* contains string "a" afterwards it would contain value "0061".
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value charToHexEncode()
{
final char hexDigits[] =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
String hex = getString();
char[] s = hex.toCharArray();
StringBuffer hexString = new StringBuffer(2 * s.length);
for (int i = 0; i < s.length; i++)
{
hexString.append(hexDigits[(s[i] & 0xF000) >> 12]); // hex 1
hexString.append(hexDigits[(s[i] & 0x0F00) >> 8]); // hex 2
hexString.append(hexDigits[(s[i] & 0x00F0) >> 4]); // hex 3
hexString.append(hexDigits[s[i] & 0x000F]); // hex 4
}
setValue( hexString );
return this;
}
/**
* Change a hexadecimal string into normal ASCII representation. E.g. if Value
* contains string "61" afterwards it would contain value "a". If the
* hexadecimal string is of a wrong length leading zeroes will be used.
*
* Note that transformations happen in groups of 4 hex characters, so
* the value of a characters is always in the range 0-65535.
*
* @return Value itself
* @throws KettleValueException
*/
public Value hexToCharDecode() throws KettleValueException
{
setType(VALUE_TYPE_STRING);
if (isNull())
{
return this;
}
setValue( getString() );
String hexString = getString();
int len = hexString.length();
char chArray[] = new char[(len + 3) / 4];
int charNr;
int nextChar = 0;
// we assume a leading 0s if the length is not right.
charNr = (len % 4);
if ( charNr == 0 ) charNr = 4;
int nibble;
int i, j;
for (i = 0, j = 0; i < len; i++)
{
char c = hexString.charAt(i);
if ((c >= '0') && (c <= '9'))
nibble = c - '0';
else if ((c >= 'A') && (c <= 'F'))
nibble = c - 'A' + 0x0A;
else if ((c >= 'a') && (c <= 'f'))
nibble = c - 'a' + 0x0A;
else
throw new KettleValueException("invalid hex digit '" + c + "'.");
if (charNr == 4)
{
nextChar = (nibble << 12);
charNr
}
else if (charNr == 3)
{
nextChar += (nibble << 8);
charNr
}
else if (charNr == 2)
{
nextChar += (nibble << 4);
charNr
}
else // charNr == 1
{
nextChar += nibble;
chArray[j] = (char)nextChar;
charNr = 4;
j++;
}
}
setValue(new String(chArray));
return this;
}
/*
* Some javascript extensions...
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(XMLHandler.addTagValue("name", getName(), false));
retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false));
retval.append(XMLHandler.addTagValue("text", toString(false), false));
retval.append(XMLHandler.addTagValue("length", getLength(), false));
retval.append(XMLHandler.addTagValue("precision", getPrecision(), false));
retval.append(XMLHandler.addTagValue("isnull", isNull(), false));
return retval.toString();
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
public boolean equalValueType(Value v)
{
return equalValueType(v, false);
}
/**
* Returns whether "types" of the values are exactly the same: type,
* name, length, precision.
*
* @param v Value to compare type against.
*
* @return == true when types are the same
* == false when the types differ
*/
public boolean equalValueType(Value v, boolean checkTypeOnly)
{
if (v == null)
return false;
if (getType() != v.getType())
return false;
if (!checkTypeOnly) {
if ((getName() == null && v.getName() != null) ||
(getName() != null && v.getName() == null) ||
!(getName().equals(v.getName())))
return false;
if (getLength() != v.getLength())
return false;
if (getPrecision() != v.getPrecision())
return false;
}
return true;
}
public ValueInterface getValueInterface()
{
return value;
}
public void setValueInterface(ValueInterface valueInterface)
{
this.value = valueInterface;
}
}
|
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* Value type indicating that the value contains an Object.
*/
public static final int VALUE_TYPE_SERIALIZABLE = 7;
/**
* The descriptions of the value types.
*/
private static final String valueTypeCode[]=
{
"-", // $NON-NLS-1$
"Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param valType The type to convert to.
*/
private void convertTo(int valType)
{
if (value!=null)
{
switch(valType)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param valType Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int valType, int length, int precision)
{
this(name, valType);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
setType(v.getType());
value = v.getValueCopy();
setName(v.getName());
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
setNull(true);
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
public void setSerializedValue(Serializable ser) {
if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser);
else value.setSerializable(ser);
setNull(ser==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null || isNull()) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null || isNull()) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null || isNull()) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null || isNull()) return null;
return value.getDate();
}
/**
* Get the Serializable of this Value.
* If the Value is not of type Serializable, it returns null.
* @return the Serializable of this Value.
*/
public Serializable getSerializable()
{
if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null;
return value.getSerializable();
}
public boolean getBoolean()
{
if (value==null || isNull()) return false;
return value.getBoolean();
}
public long getInteger()
{
if (value==null || isNull()) return 0L;
return value.getInteger();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is of type Serializable
* @retur true if this value has type Serializable
*/
public boolean isSerializableType() {
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_SERIALIZABLE;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toStringMeta()
{
// We (Sven Boden) did explicit performance testing for this
// part. The original version used Strings instead of StringBuffers,
// performance between the 2 does not differ that much. A few milliseconds
// on 100000 iterations in the advantage of StringBuffers. The
// lessened creation of objects may be worth it in the long run.
StringBuffer retval=new StringBuffer(getTypeDesc());
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval.append('(').append(getLength()).append(')');
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval.append('(').append(getLength());
if (getPrecision()>0)
{
retval.append(", ").append(getPrecision());
}
retval.append(')');
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval.append('(').append(getLength()).append(')');
}
break;
default: break;
}
return retval.toString();
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
if (pad)
{
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
}
retval=ret.toString();
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern("
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form.format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
for (i=0;i<value.getLength();i++) fmt.append('0');
fmt.append(".00"); // for the .00
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=Double.toString(value.getNumber());
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US);
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
/*
This code was removed as TYPE_VALUE_DATE does not know "length", so this
could never be called anyway
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
*/
return retval;
}
/**
* Returns a String representing the boolean value.
* It will be either "true" or "false".
*
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
retval=value.getBoolean()?"true":"false";
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat("
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign.
int len = getLength();
for (i=0;i<len;i++) fmt.append('0'); // all zeroes.
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return valueTypeCode[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.VALUE_TYPE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<valueTypeCode.length;i++)
{
if (valueTypeCode[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[valueTypeCode.length-1];
System.arraycopy(valueTypeCode, 1, retval, 0, valueTypeCode.length-1);
return retval;
}
/**
* Get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[valueTypeCode.length];
System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length);
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt(getType());
// Handle name-length
dos.writeInt(name.length());
// Write name
dos.writeChars(name);
// length & precision
dos.writeInt(getLength());
dos.writeInt(getPrecision());
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes("UTF-8").length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar());
setName(new String(nameBuffer));
// length & precision
setLength(dis.readInt(), dis.readInt());
// Null?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
}
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
if (metaData.isBigNumber()) convertString(metaData.getType());
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null);
boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_STRING:
{
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
int cmp=0;
if (caseInsensitive)
{
cmp = one.compareToIgnoreCase(two);
}
else
{
cmp = one.compareTo(two);
}
return cmp;
}
case VALUE_TYPE_INTEGER:
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_DATE :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BOOLEAN:
{
if (getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if (getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
}
case VALUE_TYPE_NUMBER :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BIGNUMBER:
{
return getBigNumber().compareTo(v.getBigNumber());
}
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
if (isNull() || v.isNull())
{
setNull();
}
else
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if (isNull() || v.isNull())
{
setNull();
return this;
}
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue(getBigNumber().multiply(v.getBigNumber()));
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue(getNumber()*v.getNumber());
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue(getInteger()*v.getInteger());
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull())
{
return this;
}
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new
KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap() throws KettleValueException
{
if (isNull()) return this;
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
}
else
{
StringBuffer change=new StringBuffer(getString());
boolean new_word;
int i;
char lower, upper, ch;
new_word=true;
for (i=0 ; i<getString().length() ; i++)
{
lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default.
upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words.
ch=upper;
if (new_word)
{
change.setCharAt(i, upper);
}
else
{
change.setCharAt(i, lower);
}
new_word = false;
if ( !(ch>='A' && ch<='Z') &&
!(ch>='0' && ch<='9') &&
ch!='_'
) new_word = true;
}
setValue( change.toString() );
}
}
else
{
throw new KettleValueException("Function INITCAP only works with a string");
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds off to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Right trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); }
public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol );
if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) );
if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (format!=null && format.length()>0) df.applyPattern(format);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
value = new ValueDate();
value.setInteger(getInteger());
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if ( pattern !=null && pattern .length()>0 ) df.applyPattern( pattern );
if ( decimal !=null && decimal .length()>0 ) dfs.setDecimalSeparator( decimal.charAt(0) );
if ( grouping!=null && grouping.length()>0 ) dfs.setGroupingSeparator( grouping.charAt(0) );
if ( currency!=null && currency.length()>0 ) dfs.setCurrencySymbol( currency );
try
{
df.setDecimalFormatSymbols(dfs);
setValue( nf.parse(getString()).doubleValue() );
}
catch(Exception e)
{
String message = "Couldn't convert string to number "+e.toString();
if ( pattern !=null && pattern .length()>0 ) message+=" pattern="+pattern;
if ( decimal !=null && decimal .length()>0 ) message+=" decimal="+decimal;
if ( grouping!=null && grouping.length()>0 ) message+=" grouping="+grouping.charAt(0);
if ( currency!=null && currency.length()>0 ) message+=" currency="+currency;
throw new KettleValueException(message);
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/**
* Add a number of days to a Date value.
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 1 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/* Some javascript extensions...
*
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(XMLHandler.addTagValue("name", getName(), false));
retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false));
retval.append(XMLHandler.addTagValue("text", toString(false), false));
retval.append(XMLHandler.addTagValue("length", getLength(), false));
retval.append(XMLHandler.addTagValue("precision", getPrecision(), false));
retval.append(XMLHandler.addTagValue("isnull", isNull(), false));
return retval.toString();
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
}
|
package net.nemerosa.ontrack.boot.ui;
import net.nemerosa.ontrack.model.structure.*;
import net.nemerosa.ontrack.ui.resource.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.concurrent.Callable;
import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on;
@RestController
@RequestMapping("/decorations")
public class DecorationsController extends AbstractProjectEntityController {
private final DecorationService decorationService;
@Autowired
public DecorationsController(StructureService structureService, DecorationService decorationService) {
super(structureService);
this.decorationService = decorationService;
}
/**
* Decorations for an entity.
*/
@RequestMapping(value = "{entityType}/{id}", method = RequestMethod.GET)
public Callable<Resources<Decoration<?>>> getDecorations(@PathVariable ProjectEntityType entityType, @PathVariable ID id) {
// Gets the current request attributes
RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
return () -> {
RequestContextHolder.setRequestAttributes(attributes);
try {
return Resources.of(
decorationService.getDecorations(getEntity(entityType, id)),
uri(on(getClass()).getDecorations(entityType, id))
).forView(Decoration.class);
} finally {
RequestContextHolder.resetRequestAttributes();
}
};
}
}
|
import com.onyxdevtools.benchmark.base.BenchmarkTest;
import com.onyxdevtools.provider.DatabaseProvider;
import com.onyxdevtools.provider.PersistenceProviderFactory;
import com.onyxdevtools.provider.manager.ProviderPersistenceManager;
import java.io.File;
import java.lang.reflect.Constructor;
public class BenchmarkRunner {
/**
* Main Class
* @param args Main arguments
* @throws Exception Generic Exception
*/
@SuppressWarnings("unchecked")
public static void main(@SuppressWarnings("ParameterCanBeLocal") String args[]) throws Exception {
//Default values to run via the IDE
/*args = new String[2];
args[0] = "1";
args[1] = "RandomTransactionBenchmarkTest";*/
// Delete the existing database so we start with a clean slate
deleteDirectory(new File(DatabaseProvider.DATABASE_LOCATION));
// Default Provider properties
DatabaseProvider databaseProvider;
BenchmarkTest benchmarkBenchmarkTest = null;
// If the arguments exist through command line use them
if (args.length > 1) {
int databaseProviderIndex = Integer.valueOf(args[0]);
String test = args[1];
Class testClass = Class.forName("com.onyxdevtools.benchmark." + test);
Constructor<?> constructor = testClass.getConstructor(ProviderPersistenceManager.class);
databaseProvider = DatabaseProvider.values()[databaseProviderIndex];
benchmarkBenchmarkTest = (BenchmarkTest) constructor.newInstance(PersistenceProviderFactory.getPersistenceManager(databaseProvider));
}
runTest(benchmarkBenchmarkTest);
System.exit(0);
}
/**
* Helper method for deleting the database directory
* @param path Directory path of database
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
static private void deleteDirectory(File path) {
if (path.exists()) {
for (File f : path.listFiles()) {
if (f.isDirectory()) {
deleteDirectory(f);
}
f.delete();
}
path.delete();
}
}
/**
* Execute a test and go through the benchmark test workflow
* @param benchmarkTest instance of benchmark test
*/
private static void runTest(BenchmarkTest benchmarkTest) {
benchmarkTest.before();
benchmarkTest.markBeginingOfTest();
benchmarkTest.execute(benchmarkTest.getNumberOfExecutions());
benchmarkTest.markEndOfTest();
benchmarkTest.after();
benchmarkTest.cleanup();
}
}
|
package org.opennms.web.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
import org.hibernate.criterion.Restrictions;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.SnmpInterfaceDao;
import org.opennms.netmgt.model.OnmsCriteria;
import org.opennms.netmgt.model.OnmsEntity;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.opennms.netmgt.model.OnmsSnmpInterfaceList;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.model.events.EventProxy;
import org.opennms.netmgt.model.events.EventProxyException;
import org.opennms.netmgt.xml.event.Event;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.sun.jersey.spi.resource.PerRequest;
@Component
@PerRequest
@Scope("prototype")
@Transactional
public class OnmsSnmpInterfaceResource extends OnmsRestService {
@Autowired
private NodeDao m_nodeDao;
@Autowired
private SnmpInterfaceDao m_snmpInterfaceDao;
@Autowired
private EventProxy m_eventProxy;
@Context
UriInfo m_uriInfo;
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public OnmsSnmpInterfaceList getSnmpInterfaces(@PathParam("nodeCriteria") String nodeCriteria) {
OnmsNode node = m_nodeDao.get(nodeCriteria);
MultivaluedMap<String,String> params = m_uriInfo.getQueryParameters();
OnmsCriteria criteria = new OnmsCriteria(OnmsSnmpInterface.class);
setLimitOffset(params, criteria, 20);
if(params.containsKey("orderBy") && params.containsKey("order")){
addOrdering(params, criteria);
}
addFiltersToCriteria(params, criteria, OnmsSnmpInterface.class);
criteria.createCriteria("node").add(Restrictions.eq("id", node.getId()));
OnmsSnmpInterfaceList snmpList = new OnmsSnmpInterfaceList(m_snmpInterfaceDao.findMatching(criteria));
OnmsCriteria crit = new OnmsCriteria(OnmsSnmpInterface.class);
crit.createCriteria("node").add(Restrictions.eq("id", node.getId()));
addFiltersToCriteria(params, crit, OnmsSnmpInterface.class);
snmpList.setTotalCount(m_snmpInterfaceDao.countMatching(crit));
return snmpList;
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("{ifIndex}")
public OnmsEntity getSnmpInterface(@PathParam("nodeCriteria") String nodeCriteria, @PathParam("ifIndex") int ifIndex) {
OnmsNode node = m_nodeDao.get(nodeCriteria);
return node.getSnmpInterfaceWithIfIndex(ifIndex);
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public Response addSnmpInterface(@PathParam("nodeCriteria") String nodeCriteria, OnmsSnmpInterface snmpInterface) {
OnmsNode node = m_nodeDao.get(nodeCriteria);
if (node == null) {
throwException(Status.BAD_REQUEST, "addSnmpInterface: can't find node " + nodeCriteria);
}
if (snmpInterface == null) {
throwException(Status.BAD_REQUEST, "addSnmpInterface: snmp interface object cannot be null");
}
log().debug("addSnmpInterface: adding interface " + snmpInterface);
node.addSnmpInterface(snmpInterface);
if (snmpInterface.getIpAddress() != null) {
OnmsIpInterface iface = node.getIpInterfaceByIpAddress(snmpInterface.getIpAddress());
iface.setSnmpInterface(snmpInterface);
// TODO Add important events here
}
m_snmpInterfaceDao.save(snmpInterface);
return Response.ok().build();
}
@DELETE
@Path("{ifIndex}")
public Response deleteSnmpInterface(@PathParam("nodeCriteria") String nodeCriteria, @PathParam("ifIndex") int ifIndex) {
OnmsNode node = m_nodeDao.get(nodeCriteria);
if (node == null) {
throwException(Status.BAD_REQUEST, "deleteSnmpInterface: can't find node " + nodeCriteria);
}
OnmsEntity snmpInterface = node.getSnmpInterfaceWithIfIndex(ifIndex);
if (snmpInterface == null) {
throwException(Status.BAD_REQUEST, "deleteSnmpInterface: can't find snmp interface with ifIndex " + ifIndex + " for node " + nodeCriteria);
}
log().debug("deletSnmpInterface: deleting interface with ifIndex " + ifIndex + " from node " + nodeCriteria);
node.getSnmpInterfaces().remove(snmpInterface);
m_nodeDao.saveOrUpdate(node);
// TODO Add important events here
return Response.ok().build();
}
@PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("{ifIndex}")
public Response updateSnmpInterface(@PathParam("nodeCriteria") String nodeCriteria, @PathParam("ifIndex") int ifIndex, MultivaluedMapImpl params) {
OnmsNode node = m_nodeDao.get(nodeCriteria);
if (node == null) {
throwException(Status.BAD_REQUEST, "deleteSnmpInterface: can't find node " + nodeCriteria);
}
OnmsSnmpInterface snmpInterface = node.getSnmpInterfaceWithIfIndex(ifIndex);
if (snmpInterface == null) {
throwException(Status.BAD_REQUEST, "deleteSnmpInterface: can't find snmp interface with ifIndex " + ifIndex + " for node " + nodeCriteria);
}
log().debug("updateSnmpInterface: updating snmp interface " + snmpInterface);
BeanWrapper wrapper = new BeanWrapperImpl(snmpInterface);
for(String key : params.keySet()) {
if (wrapper.isWritableProperty(key)) {
String stringValue = params.getFirst(key);
Object value = wrapper.convertIfNecessary(stringValue, wrapper.getPropertyType(key));
wrapper.setPropertyValue(key, value);
}
}
Event e = null;
if (params.containsKey("collect")) {
// we've updated the collection flag so we need to send an event to redo collection
EventBuilder bldr = new EventBuilder(EventConstants.REINITIALIZE_PRIMARY_SNMP_INTERFACE_EVENT_UEI, "OpenNMS.Webapp");
bldr.setNode(node);
bldr.setInterface(node.getPrimaryInterface().getIpAddress());
e = bldr.getEvent();
}
log().debug("updateSnmpInterface: snmp interface " + snmpInterface + " updated");
m_snmpInterfaceDao.saveOrUpdate(snmpInterface);
if (e != null) {
try {
m_eventProxy.send(e);
} catch (EventProxyException ex) {
return throwException(Response.Status.INTERNAL_SERVER_ERROR, "Exception occurred sending event: "+ex.getMessage());
}
}
return Response.ok().build();
}
}
|
package org.caleydo.view.subgraph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.caleydo.core.view.opengl.layout2.layout.GLPadding;
import org.caleydo.core.view.opengl.layout2.layout.IGLLayout;
import org.caleydo.core.view.opengl.layout2.layout.IGLLayoutElement;
import org.caleydo.view.subgraph.GLSubGraph.PathwayMultiFormInfo;
/**
* @author Christian
*
*/
public class GLPathwayGridLayout implements IGLLayout {
protected final GLSubGraph view;
protected List<PathwayColumn> columns = new ArrayList<>();
protected GLPadding padding;
protected float gap;
public GLPathwayGridLayout(GLSubGraph view, GLPadding padding, float gap) {
this.view = view;
this.padding = padding;
this.gap = gap;
}
public void addColumn(GLPathwayWindow window) {
PathwayColumn column = new PathwayColumn();
column.windows.add(window);
columns.add(column);
}
@Override
public void doLayout(List<? extends IGLLayoutElement> children, float w, float h) {
Map<GLPathwayWindow, IGLLayoutElement> windowToElement = new HashMap<>();
for (IGLLayoutElement child : children) {
windowToElement.put((GLPathwayWindow) child.asElement(), child);
}
List<LayoutSnapshot> snapshots = new ArrayList<>();
snapshots.add(new LayoutSnapshot(columns));
// float freeSpaceHorizontal =
float freeSpaceVertical = h - padding.vert();
if (!isSufficientSpace(columns, getFreeHorizontalSpace(w))) {
if (!mergeColumns(snapshots, w, freeSpaceVertical)) {
List<PathwayMultiFormInfo> infos = new ArrayList<>(view.pathwayInfos.size());
infos.addAll(view.pathwayInfos);
Collections.sort(infos, new Comparator<PathwayMultiFormInfo>() {
@Override
public int compare(PathwayMultiFormInfo o1, PathwayMultiFormInfo o2) {
int priority1 = o1.getEmbeddingIDFromRendererID(o1.multiFormRenderer.getActiveRendererID())
.renderPriority();
int priority2 = o2.getEmbeddingIDFromRendererID(o2.multiFormRenderer.getActiveRendererID())
.renderPriority();
if (priority1 == priority2) {
return o1.age - o2.age;
}
return priority1 - priority2;
}
});
Collections.reverse(infos);
for (PathwayMultiFormInfo info : infos) {
EEmbeddingID level = info
.getEmbeddingIDFromRendererID(info.multiFormRenderer.getActiveRendererID());
if (info.multiFormRenderer != view.lastUsedRenderer) {
EEmbeddingID levelDown = EEmbeddingID.levelDown(level);
if (levelDown != EEmbeddingID.PATHWAY_LEVEL4) {
int rendererID = info.embeddingIDToRendererIDs.get(levelDown).get(0);
info.multiFormRenderer.setActive(rendererID);
snapshots.add(new LayoutSnapshot(columns));
if (isSufficientSpace(columns, getFreeHorizontalSpace(w))) {
break;
}
if (mergeColumns(snapshots, w, freeSpaceVertical)) {
break;
}
}
}
}
}
}
Collections.reverse(snapshots);
LayoutSnapshot previousSnapshot = null;
for (LayoutSnapshot snapshot : snapshots) {
if (previousSnapshot != null) {
if (previousSnapshot.minTotalWidth < snapshot.minTotalWidth) {
columns = previousSnapshot.cols;
for (PathwayColumn column : columns) {
for (GLPathwayWindow window : column.windows) {
window.info.multiFormRenderer.setActive(previousSnapshot.windowToRendererID.get(window));
}
}
}
break;
}
previousSnapshot = snapshot;
}
Set<PathwayColumn> level1Columns = new HashSet<>();
int minTotalLevel1Size = 0;
int totalFixedSize = 0;
for (PathwayColumn column : columns) {
if (column.getLevelScore() == EEmbeddingID.PATHWAY_LEVEL1.renderPriority()) {
level1Columns.add(column);
minTotalLevel1Size += column.getMinWidth();
} else {
totalFixedSize += column.getMinWidth();
// column.setSize(column.getMinWidth(), freeSpaceVertical);
// column.setSize(column.getMinWidth(), Float.NaN);
}
}
float currentPositionX = padding.left;
for (PathwayColumn column : columns) {
float columnWidth = 0;
if (minTotalLevel1Size == 0) {
columnWidth = ((float) column.getMinWidth() / (float) totalFixedSize) * getFreeHorizontalSpace(w);
} else {
if (level1Columns.contains(column)) {
columnWidth = ((float) column.getMinWidth() / (float) minTotalLevel1Size)
* (getFreeHorizontalSpace(w) - totalFixedSize);
} else {
columnWidth = column.getMinWidth();
}
}
column.layout(windowToElement, currentPositionX, padding.top, columnWidth, freeSpaceVertical);
currentPositionX += columnWidth + gap;
}
}
private boolean isSufficientSpace(List<PathwayColumn> pathwayColumns, float freeSpace) {
int minWidth = 0;
for (PathwayColumn column : pathwayColumns) {
minWidth += column.getMinWidth();
}
return freeSpace >= minWidth;
}
private float getFreeHorizontalSpace(float w) {
return w - padding.hor() - (columns.size() - 1) * gap;
}
/**
*
*
* @param w
* @param pathwayColumns
* @param h
* @return True, if there is enough space after merging columns
*/
private boolean mergeColumns(List<LayoutSnapshot> snapshots, float w, float h) {
boolean columnsMerged = false;
do {
columnsMerged = false;
PathwayColumn columnToRemove = null;
Collections.sort(columns);
for (PathwayColumn sourceColumn : columns) {
for (PathwayColumn destColumn : columns) {
if (sourceColumn != destColumn) {
if (sourceColumn.getMinHeight() + destColumn.getMinHeight() <= h) {
destColumn.merge(sourceColumn);
columnToRemove = sourceColumn;
columnsMerged = true;
break;
}
}
}
if (columnsMerged)
break;
}
if (columnsMerged) {
columns.remove(columnToRemove);
snapshots.add(new LayoutSnapshot(columns));
}
if (isSufficientSpace(columns, getFreeHorizontalSpace(w)))
return true;
} while (columnsMerged);
return false;
}
private class LayoutSnapshot {
protected List<PathwayColumn> cols = new ArrayList<>();
protected Map<GLPathwayWindow, Integer> windowToRendererID = new HashMap<>();
protected float minTotalWidth = 0;
public LayoutSnapshot(List<PathwayColumn> columns) {
for (PathwayColumn column : columns) {
PathwayColumn newColumn = new PathwayColumn();
for (GLPathwayWindow window : column.windows) {
newColumn.windows.add(window);
windowToRendererID.put(window, window.info.multiFormRenderer.getActiveRendererID());
}
cols.add(newColumn);
minTotalWidth += column.getMinWidth();
}
}
}
private class PathwayColumn implements Comparable<PathwayColumn> {
protected List<GLPathwayWindow> windows = new ArrayList<>();
public int getMinHeight() {
int minHeight = 0;
for (GLPathwayWindow window : windows) {
minHeight += window.getMinHeight();
}
return minHeight;
}
public int getMinWidth() {
int maxMinWidth = 0;
for (GLPathwayWindow window : windows) {
int minWidth = window.getMinWidth();
if (minWidth > maxMinWidth)
maxMinWidth = minWidth;
}
return maxMinWidth;
}
protected void layout(Map<GLPathwayWindow, IGLLayoutElement> windowToElement, float x, float y, float w, float h) {
float freeSpaceVertical = h - gap * (windows.size() - 1);
Set<GLPathwayWindow> level1Windows = new HashSet<>();
int minTotalLevel1Size = 0;
int totalFixedSize = 0;
for (GLPathwayWindow window : windows) {
if (window.info.getEmbeddingIDFromRendererID(window.info.multiFormRenderer.getActiveRendererID()) == EEmbeddingID.PATHWAY_LEVEL1) {
level1Windows.add(window);
minTotalLevel1Size += window.getMinHeight();
} else {
totalFixedSize += window.getMinHeight();
}
}
float currentPositionY = y;
for (GLPathwayWindow window : windows) {
float windowHeight = 0;
if (minTotalLevel1Size == 0) {
int minHeight = window.getMinHeight();
float factor = (float) minHeight / (float) totalFixedSize;
windowHeight = factor * freeSpaceVertical;
} else {
if (level1Windows.contains(window)) {
windowHeight = ((float) window.getMinHeight() / (float) minTotalLevel1Size)
* (freeSpaceVertical - totalFixedSize);
} else {
windowHeight = window.getMinHeight();
}
}
windowToElement.get(window).setSize(w, windowHeight);
windowToElement.get(window).setLocation(x, currentPositionY);
currentPositionY += windowHeight + gap;
}
}
protected void merge(PathwayColumn column) {
windows.addAll(column.windows);
}
protected int getLevelScore() {
int score = 0;
for (GLPathwayWindow window : windows) {
int rendererID = window.info.multiFormRenderer.getActiveRendererID();
EEmbeddingID embdeddingID = window.info.getEmbeddingIDFromRendererID(rendererID);
if (embdeddingID.renderPriority() > score)
score = embdeddingID.renderPriority();
}
return score;
}
@Override
public int compareTo(PathwayColumn o) {
return getLevelScore() - o.getLevelScore();
}
}
}
|
package org.eclipse.egit.ui.internal;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.List;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IResource;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.internal.gerrit.GerritUtil;
import org.eclipse.egit.ui.internal.trace.GitTraceLocation;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryState;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
/**
* Resource-based property tester.
* <p>
* Supported properties:
* <ul>
* <li>isShared <code>true</code> if the resource is mapped to EGit. EGit may
* still affect a resource if it belongs to the workspace of some shared
* project.</li>
* <li>isContainer <code>true</code> if the resource is a project or a folder</li>
* <li>is<em>repository state</em>
* <ul>
* <li>isSafe - see {@link RepositoryState#SAFE}</li>
* <li>isReverting - see {@link RepositoryState#REVERTING}</li>
* <li>isRevertingResolved - see {@link RepositoryState#REVERTING_RESOLVED}</li>
* <li>isCherryPicking - see {@link RepositoryState#CHERRY_PICKING}</li>
* <li>isCherryPickingResolved - see
* {@link RepositoryState#CHERRY_PICKING_RESOLVED}</li>
* <li>isMerging - see {@link RepositoryState#MERGING}</li>
* <li>isMergingResolved - see {@link RepositoryState#MERGING_RESOLVED}</li>
* <li>isRebasing - see {@link RepositoryState#REBASING}</li>
* <li>isRebasingRebasing - see {@link RepositoryState#REBASING_REBASING}</li>
* <li>isRebasingMerge - see {@link RepositoryState#REBASING_MERGE}</li>
* <li>isRebasingInteractive - see {@link RepositoryState#REBASING_INTERACTIVE}</li>
* <li>isApply - see {@link RepositoryState#APPLY}</li>
* <li>isBisecting - see {@link RepositoryState#BISECTING}</li>
* </ul>
* <li>Capabilities/properties of the current state:<ul>
* <li>canCheckout - see {@link RepositoryState#canCheckout()}</li>
* <li>canAmend - see {@link RepositoryState#canAmend()}</li>
* <li>canCommit - see {@link RepositoryState#canCommit()}</li>
* <li>canResetHead - see {@link RepositoryState#canResetHead()}</li>
* </ul>
* </ul>
*/
public class ResourcePropertyTester extends PropertyTester {
public boolean test(Object receiver, String property, Object[] args,
Object expectedValue) {
boolean value = internalTest(receiver, property);
boolean trace = GitTraceLocation.PROPERTIESTESTER.isActive();
if (trace)
GitTraceLocation
.getTrace()
.trace(GitTraceLocation.PROPERTIESTESTER.getLocation(),
"prop " + property + " of " + receiver + " = " + value + ", expected = " + expectedValue); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
return value;
}
private boolean internalTest(Object receiver, String property) {
if (!(receiver instanceof IResource))
return false;
IResource res = (IResource) receiver;
if ("isContainer".equals(property)) { //$NON-NLS-1$
int type = res.getType();
return type == IResource.FOLDER || type == IResource.PROJECT;
}
RepositoryMapping mapping = RepositoryMapping.getMapping(res
.getProject());
if (mapping != null) {
Repository repository = mapping.getRepository();
return testRepositoryState(repository, property);
}
return false;
}
/**
* @param repository
* @param property
* @return true if the repository is in an appropriate state. See
* {@link ResourcePropertyTester}
*/
public static boolean testRepositoryState(Repository repository, String property) {
if ("isShared".equals(property)) //$NON-NLS-1$
return repository != null;
if (repository != null) {
if ("hasGerritConfiguration".equals(property)) //$NON-NLS-1$
return hasGerritConfiguration(repository);
RepositoryState state = repository.getRepositoryState();
if ("canAbortRebase".equals(property)) //$NON-NLS-1$
switch (state) {
case REBASING_INTERACTIVE:
return true;
case REBASING_REBASING:
return true;
default:
return false;
}
if ("canContinueRebase".equals(property)) //$NON-NLS-1$
switch (state) {
case REBASING_INTERACTIVE:
return true;
default:
return false;
}
// isSTATE checks repository state where STATE is the CamelCase version
// of the RepositoryState enum values.
if (property.length() > 3 && property.startsWith("is")) { //$NON-NLS-1$
// e.g. isCherryPickingResolved => CHERRY_PICKING_RESOLVED
String lookFor = property.substring(2,3) + property.substring(3).replaceAll("([A-Z])","_$1").toUpperCase(); //$NON-NLS-1$//$NON-NLS-2$
if (state.toString().equals(lookFor))
return true;
}
// invokes test methods of RepositoryState, canCommit etc
try {
Method method = RepositoryState.class.getMethod(property);
if (method.getReturnType() == boolean.class) {
Boolean ret = (Boolean) method.invoke(state);
return ret.booleanValue();
}
} catch (Exception e) {
// ignore
}
}
return false;
}
/**
* @param repository
* @return {@code true} if repository has been configured for Gerrit
*/
public static boolean hasGerritConfiguration(Repository repository) {
Config config = repository.getConfig();
if (GerritUtil.getCreateChangeId(config))
return true;
try {
List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);
for (RemoteConfig remoteConfig : remoteConfigs) {
for (RefSpec pushSpec : remoteConfig.getPushRefSpecs()) {
String destination = pushSpec.getDestination();
if (destination == null)
continue;
return destination.startsWith(GerritUtil.REFS_FOR);
}
}
} catch (URISyntaxException e) {
// Assume it doesn't contain Gerrit configuration
return false;
}
return false;
}
}
|
package org.opentosca.bus.management.utils;
import java.io.StringWriter;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.opentosca.bus.management.servicehandler.ServiceHandler;
import org.opentosca.container.core.model.csar.id.CSARID;
import org.opentosca.container.core.model.instance.NodeInstance;
import org.opentosca.container.core.model.instance.ServiceInstance;
import org.opentosca.container.core.tosca.convention.Interfaces;
import org.opentosca.container.core.tosca.convention.Types;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
public class MBUtils {
final private static Logger LOG = LoggerFactory.getLogger(MBUtils.class);
/**
*
* Returns the OperatingSystem NodeTemplate.
*
* @param csarID
* @param serviceTemplateID
* @param nodeTemplateID
*
* @return name of the OperatingSystem NodeTemplate.
*/
public static String getOperatingSystemNodeTemplateID(final CSARID csarID, final QName serviceTemplateID,
String nodeTemplateID) {
MBUtils.LOG.debug("Searching the OperatingSystemNode of NodeTemplate: {}, ServiceTemplate: {} & CSAR: {} ...",
nodeTemplateID, serviceTemplateID, csarID);
QName nodeType =
ServiceHandler.toscaEngineService.getNodeTypeOfNodeTemplate(csarID, serviceTemplateID, nodeTemplateID);
while (!isOperatingSystemNodeType(csarID, nodeType) && nodeTemplateID != null) {
MBUtils.LOG.debug("{} isn't the OperatingSystemNode.", nodeTemplateID);
MBUtils.LOG.debug("Getting the underneath Node for checking if it is the OperatingSystemNode...");
// try different relationshiptypes with priority on hostedOn
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID, nodeTemplateID,
Types.hostedOnRelationType);
if (nodeTemplateID == null) {
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID,
nodeTemplateID,
Types.deployedOnRelationType);
if (nodeTemplateID == null) {
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID,
nodeTemplateID,
Types.dependsOnRelationType);
}
}
if (nodeTemplateID != null) {
MBUtils.LOG.debug("Checking if the underneath Node: {} is the OperatingSystemNode.", nodeTemplateID);
nodeType = ServiceHandler.toscaEngineService.getNodeTypeOfNodeTemplate(csarID, serviceTemplateID,
nodeTemplateID);
} else {
MBUtils.LOG.debug("No underneath Node found.");
}
}
if (nodeTemplateID != null) {
MBUtils.LOG.debug("OperatingSystemNode found: {}", nodeTemplateID);
}
return nodeTemplateID;
}
/**
*
* Checks if the specified NodeType is the OperatingSystem NodeType.
*
* @param csarID
* @param nodeType
* @return true if the specified NodeType is the OperatingSystem NodeType. Otherwise false.
*/
private static boolean isOperatingSystemNodeType(final CSARID csarID, final QName nodeType) {
if (ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_RUNSCRIPT)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_TRANSFERFILE)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_INSTALLPACKAGE)) {
return true;
} else if (ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER_RUNSCRIPT)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER_TRANSFERFILE)) {
return true;
}
return false;
}
/**
* Returns the OS interface of the given OS Node Type
*
* @param csarID the CSAR Id where the referenced Node Type is declared
* @param nodeType a QName of the Node Type to check
* @return a String containing the name of the OS interface, or if the given Node Type is not an
* OS Node Type null
*/
public static String getInterfaceForOperatingSystemNodeType(final CSARID csarID, final QName nodeType) {
if (ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_RUNSCRIPT)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_TRANSFERFILE)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM_INSTALLPACKAGE)) {
return Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM;
} else if (ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER_RUNSCRIPT)
&& ServiceHandler.toscaEngineService.doesInterfaceOfNodeTypeContainOperation(csarID, nodeType,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER,
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER_TRANSFERFILE)) {
return Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER;
}
return null;
}
/**
*
* Returns the name of the OperatingSystem ImplementationArtifact.
*
* @param csarID
* @param serviceTemplateID
* @param osNodeTemplateID
*
*
* @return name of the OperatingSystem ImplementationArtifact.
*/
public static String getOperatingSystemIA(final CSARID csarID, final QName serviceTemplateID,
final String osNodeTemplateID) {
MBUtils.LOG.debug("Searching the OperatingSystem-IA of NodeTemplate: {}, ServiceTemplate: {} & CSAR: {} ...",
osNodeTemplateID, serviceTemplateID, csarID);
final QName osNodeType =
ServiceHandler.toscaEngineService.getNodeTypeOfNodeTemplate(csarID, serviceTemplateID, osNodeTemplateID);
final List<QName> osNodeTypeImpls =
ServiceHandler.toscaEngineService.getNodeTypeImplementationsOfNodeType(csarID, osNodeType);
for (final QName osNodeTypeImpl : osNodeTypeImpls) {
MBUtils.LOG.debug("NodeTypeImpl: {} ", osNodeTypeImpl);
final List<String> osIANames =
ServiceHandler.toscaEngineService.getImplementationArtifactNamesOfNodeTypeImplementation(csarID,
osNodeTypeImpl);
for (final String osIAName : osIANames) {
MBUtils.LOG.debug("IA: {} ", osIAName);
final String osIAInterface =
ServiceHandler.toscaEngineService.getInterfaceOfAImplementationArtifactOfANodeTypeImplementation(csarID,
osNodeTypeImpl, osIAName);
MBUtils.LOG.debug("Interface: {} ", osIAInterface);
if (osIAInterface == null
|| osIAInterface.equals(Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM)
|| osIAInterface.equals(Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_DOCKERCONTAINER)) {
return osIAName;
}
}
}
return null;
}
/**
*
* Traverses the topology and searches for the specified property. If found, the value from the
* instance data is returned.
*
* @param property
* @param csarID
* @param serviceTemplateID
* @param nodeTemplateID
* @param serviceInstanceID
*
*
* @return instance data value of searched property if found. Otherwise null.
*/
public static String searchProperty(final String property, final CSARID csarID, final QName serviceTemplateID,
String nodeTemplateID, final URI serviceInstanceID) {
MBUtils.LOG.debug("Searching the Property: {} in or under the NodeTemplateID: {} ServiceTemplate: {} & CSAR: {} ...",
property, nodeTemplateID, serviceTemplateID, csarID);
String propertyValue =
getInstanceDataPropertyValue(property, csarID, serviceTemplateID, nodeTemplateID, serviceInstanceID);
while (propertyValue == null && nodeTemplateID != null) {
MBUtils.LOG.debug("{} hasn't the searched property: {}.", nodeTemplateID, property);
MBUtils.LOG.debug("Getting the underneath Node for checking if it has the searched property...");
// try different relationshiptypes with priority on hostedOn
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID, nodeTemplateID,
Types.hostedOnRelationType);
if (nodeTemplateID == null) {
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID,
nodeTemplateID,
Types.deployedOnRelationType);
if (nodeTemplateID == null) {
nodeTemplateID =
ServiceHandler.toscaEngineService.getRelatedNodeTemplateID(csarID, serviceTemplateID,
nodeTemplateID,
Types.dependsOnRelationType);
}
}
if (nodeTemplateID != null) {
MBUtils.LOG.debug("Checking if the Node: {} has the searched property: {}.", nodeTemplateID, property);
propertyValue = getInstanceDataPropertyValue(property, csarID, serviceTemplateID, nodeTemplateID,
serviceInstanceID);
} else {
MBUtils.LOG.debug("No underneath Node found.");
}
}
if (propertyValue != null) {
MBUtils.LOG.debug("Searched property: {} with value: {} found in NodeTemplate: {}.", property,
propertyValue, nodeTemplateID);
} else {
MBUtils.LOG.debug("Searched property: {} not found!", property);
}
return propertyValue;
}
/**
* @param property
* @param csarID
* @param serviceTemplateID
* @param nodeTemplateID
* @param serviceInstanceID
*
* @return instance data value of searched property if found. Otherwise null.
*/
public static String getInstanceDataPropertyValue(final String property, final CSARID csarID,
final QName serviceTemplateID, final String nodeTemplateID,
final URI serviceInstanceID) {
final HashMap<String, String> propertiesMap =
getInstanceDataProperties(csarID, serviceTemplateID, nodeTemplateID, serviceInstanceID);
return propertiesMap.get(property);
}
/**
* @param csarID
* @param serviceTemplateID
* @param nodeTemplateID
* @param serviceInstanceID
* @return the in the InstanceService stored properties for the specified parameters or null if
* it can not be found.
*/
public static HashMap<String, String> getInstanceDataProperties(final CSARID csarID, final QName serviceTemplateID,
final String nodeTemplateID,
final URI serviceInstanceID) {
final String serviceTemplateName =
ServiceHandler.toscaEngineService.getNameOfReference(csarID, serviceTemplateID);
HashMap<String, String> propertiesMap = new HashMap<>();
if (serviceInstanceID != null) {
final List<ServiceInstance> serviceInstanceList =
ServiceHandler.instanceDataService.getServiceInstances(serviceInstanceID, serviceTemplateName,
serviceTemplateID);
final QName nodeTemplateQName = new QName(serviceTemplateID.getNamespaceURI(), nodeTemplateID);
for (final ServiceInstance serviceInstance : serviceInstanceList) {
if (serviceInstance.getCSAR_ID().toString().equals(csarID.toString())) {
/**
* This is a workaround. The first statement should work, but unfortunately does
* not (the list is null / empty). We were not able to identify the root of the
* error, in debug mode it seemed to work but in "production" mode not. Somehow
* the lazy loading mechanism of JPA / EclipseLink seems to not work properly.
*/
// List<NodeInstance> nodeInstanceList =
// serviceInstance.getNodeInstances();
final List<NodeInstance> nodeInstanceList =
ServiceHandler.instanceDataService.getNodeInstances(null, null, null, serviceInstanceID);
for (final NodeInstance nodeInstance : nodeInstanceList) {
if (nodeInstance.getNodeTemplateID().equals(nodeTemplateQName)) {
final Document doc = nodeInstance.getProperties();
if (doc != null) {
propertiesMap = docToMap(doc, false);
}
return propertiesMap;
}
}
}
MBUtils.LOG.debug("No InstanceData found for CsarID: " + csarID + ", ServiceTemplateID: "
+ serviceTemplateID + ", ServiceTemplateName: " + serviceTemplateName + " and ServiceInstanceID: "
+ serviceInstanceID);
}
}
return null;
}
/**
* Transfers the properties document to a map.
*
* @param propertiesDocument to be transfered to a map.
* @return transfered map.
*/
public static HashMap<String, String> docToMap(final Document propertiesDocument, final boolean allowEmptyEntries) {
final HashMap<String, String> reponseMap = new HashMap<>();
final DocumentTraversal traversal = (DocumentTraversal) propertiesDocument;
final NodeIterator iterator =
traversal.createNodeIterator(propertiesDocument.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
for (Node node = iterator.nextNode(); node != null; node = iterator.nextNode()) {
final String name = ((Element) node).getLocalName();
final StringBuilder content = new StringBuilder();
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
content.append(child.getTextContent());
}
}
if (allowEmptyEntries) {
reponseMap.put(name, content.toString());
} else {
if (!content.toString().trim().isEmpty()) {
reponseMap.put(name, content.toString());
}
}
}
return reponseMap;
}
public static String toString(final Document doc) {
try {
final StringWriter sw = new StringWriter();
final TransformerFactory tf = TransformerFactory.newInstance();
final Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
}
catch (final Exception e) {
throw new RuntimeException("Error converting Document to String: " + e.getMessage(), e);
}
}
}
|
package com.intellij.codeInsight.navigation;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.documentation.DocumentationManager;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction;
import com.intellij.codeInsight.navigation.actions.GotoTypeDeclarationAction;
import com.intellij.ide.util.EditSourceUtil;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.searches.DefinitionsScopedSearch;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.ScreenUtil;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.usageView.UsageViewShortNameLocation;
import com.intellij.usageView.UsageViewTypeLocation;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.Consumer;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.concurrency.CancellablePromise;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
public final class CtrlMouseHandler {
private static final Logger LOG = Logger.getInstance(CtrlMouseHandler.class);
private final Project myProject;
private HighlightersSet myHighlighter;
@JdkConstants.InputEventMask private int myStoredModifiers;
private TooltipProvider myTooltipProvider;
@Nullable private Point myPrevMouseLocation;
private LightweightHint myHint;
public enum BrowseMode {None, Declaration, TypeDeclaration, Implementation}
private final KeyListener myEditorKeyListener = new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
handleKey(e);
}
@Override
public void keyReleased(final KeyEvent e) {
handleKey(e);
}
private void handleKey(final KeyEvent e) {
int modifiers = e.getModifiers();
if (modifiers == myStoredModifiers) {
return;
}
BrowseMode browseMode = getBrowseMode(modifiers);
if (browseMode == BrowseMode.None) {
disposeHighlighter();
cancelPreviousTooltip();
}
else {
TooltipProvider tooltipProvider = myTooltipProvider;
if (tooltipProvider != null) {
if (browseMode != tooltipProvider.getBrowseMode()) {
disposeHighlighter();
}
myStoredModifiers = modifiers;
cancelPreviousTooltip();
myTooltipProvider = new TooltipProvider(tooltipProvider);
myTooltipProvider.execute(browseMode);
}
}
}
};
private final VisibleAreaListener myVisibleAreaListener = __ -> {
disposeHighlighter();
cancelPreviousTooltip();
};
private final EditorMouseListener myEditorMouseAdapter = new EditorMouseListener() {
@Override
public void mouseReleased(@NotNull EditorMouseEvent e) {
disposeHighlighter();
cancelPreviousTooltip();
}
};
private final EditorMouseMotionListener myEditorMouseMotionListener = new EditorMouseMotionListener() {
@Override
public void mouseMoved(@NotNull final EditorMouseEvent e) {
if (e.isConsumed() || !myProject.isInitialized() || myProject.isDisposed()) {
return;
}
MouseEvent mouseEvent = e.getMouseEvent();
Point prevLocation = myPrevMouseLocation;
myPrevMouseLocation = mouseEvent.getLocationOnScreen();
if (isMouseOverTooltip(mouseEvent.getLocationOnScreen())
|| ScreenUtil.isMovementTowards(prevLocation, mouseEvent.getLocationOnScreen(), getHintBounds())) {
return;
}
cancelPreviousTooltip();
myStoredModifiers = mouseEvent.getModifiers();
BrowseMode browseMode = getBrowseMode(myStoredModifiers);
if (browseMode == BrowseMode.None || e.getArea() != EditorMouseEventArea.EDITING_AREA) {
disposeHighlighter();
return;
}
Editor editor = e.getEditor();
if (!(editor instanceof EditorEx) || editor.getProject() != null && editor.getProject() != myProject) return;
Point point = new Point(mouseEvent.getPoint());
if (!EditorUtil.isPointOverText(editor, point)) {
disposeHighlighter();
return;
}
myTooltipProvider = new TooltipProvider((EditorEx)editor, editor.xyToLogicalPosition(point));
myTooltipProvider.execute(browseMode);
}
};
public CtrlMouseHandler(@NotNull Project project) {
myProject = project;
StartupManager.getInstance(project).registerPostStartupActivity((DumbAwareRunnable)() -> {
EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
eventMulticaster.addEditorMouseListener(myEditorMouseAdapter, project);
eventMulticaster.addEditorMouseMotionListener(myEditorMouseMotionListener, project);
eventMulticaster.addCaretListener(new CaretListener() {
@Override
public void caretPositionChanged(@NotNull CaretEvent e) {
if (myHint != null) {
DocumentationManager.getInstance(myProject).updateToolwindowContext();
}
}
}, project);
});
project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener(){
@Override
public void selectionChanged(@NotNull FileEditorManagerEvent event) {
disposeHighlighter();
cancelPreviousTooltip();
}
});
}
private void cancelPreviousTooltip() {
if (myTooltipProvider != null) {
myTooltipProvider.dispose();
myTooltipProvider = null;
}
}
private boolean isMouseOverTooltip(@NotNull Point mouseLocationOnScreen) {
Rectangle bounds = getHintBounds();
return bounds != null && bounds.contains(mouseLocationOnScreen);
}
@Nullable
private Rectangle getHintBounds() {
LightweightHint hint = myHint;
if (hint == null) {
return null;
}
JComponent hintComponent = hint.getComponent();
if (!hintComponent.isShowing()) {
return null;
}
return new Rectangle(hintComponent.getLocationOnScreen(), hintComponent.getSize());
}
@NotNull
private static BrowseMode getBrowseMode(@JdkConstants.InputEventMask int modifiers) {
if (modifiers != 0) {
final Keymap activeKeymap = KeymapManager.getInstance().getActiveKeymap();
if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_DECLARATION)) return BrowseMode.Declaration;
if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_TYPE_DECLARATION)) return BrowseMode.TypeDeclaration;
if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_IMPLEMENTATION)) return BrowseMode.Implementation;
}
return BrowseMode.None;
}
@Nullable
@TestOnly
public static String getInfo(PsiElement element, PsiElement atPointer) {
return generateInfo(element, atPointer, true).text;
}
@Nullable
@TestOnly
public static String getInfo(@NotNull Editor editor, BrowseMode browseMode) {
Project project = editor.getProject();
if (project == null) return null;
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (file == null) return null;
Info info = getInfoAt(project, editor, file, editor.getCaretModel().getOffset(), browseMode);
return info == null ? null : info.getInfo().text;
}
@NotNull
private static DocInfo generateInfo(PsiElement element, PsiElement atPointer, boolean fallbackToBasicInfo) {
final DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(element, atPointer);
String result = documentationProvider.getQuickNavigateInfo(element, atPointer);
if (result == null && fallbackToBasicInfo) {
result = doGenerateInfo(element);
}
return result == null ? DocInfo.EMPTY : new DocInfo(result, documentationProvider);
}
@Nullable
private static String doGenerateInfo(@NotNull PsiElement element) {
if (element instanceof PsiFile) {
final VirtualFile virtualFile = ((PsiFile)element).getVirtualFile();
if (virtualFile != null) {
return virtualFile.getPresentableUrl();
}
}
String info = getQuickNavigateInfo(element);
if (info != null) {
return info;
}
if (element instanceof NavigationItem) {
final ItemPresentation presentation = ((NavigationItem)element).getPresentation();
if (presentation != null) {
return presentation.getPresentableText();
}
}
return null;
}
@Nullable
private static String getQuickNavigateInfo(PsiElement element) {
final String name = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE);
if (StringUtil.isEmpty(name)) return null;
final String typeName = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE);
final PsiFile file = element.getContainingFile();
final StringBuilder sb = new StringBuilder();
if (StringUtil.isNotEmpty(typeName)) sb.append(typeName).append(" ");
sb.append("\"").append(name).append("\"");
if (file != null && file.isPhysical()) {
sb.append(" [").append(file.getName()).append("]");
}
return sb.toString();
}
public abstract static class Info {
@NotNull final PsiElement myElementAtPointer;
@NotNull private final List<TextRange> myRanges;
public Info(@NotNull PsiElement elementAtPointer, @NotNull List<TextRange> ranges) {
myElementAtPointer = elementAtPointer;
myRanges = ranges;
}
public Info(@NotNull PsiElement elementAtPointer) {
this(elementAtPointer, getReferenceRanges(elementAtPointer));
}
@NotNull
private static List<TextRange> getReferenceRanges(@NotNull PsiElement elementAtPointer) {
if (!elementAtPointer.isPhysical()) return Collections.emptyList();
int textOffset = elementAtPointer.getTextOffset();
final TextRange range = elementAtPointer.getTextRange();
if (range == null) {
throw new AssertionError("Null range for " + elementAtPointer + " of " + elementAtPointer.getClass());
}
if (textOffset < range.getStartOffset() || textOffset < 0) {
LOG.error("Invalid text offset " + textOffset + " of element " + elementAtPointer + " of " + elementAtPointer.getClass());
textOffset = range.getStartOffset();
}
return Collections.singletonList(new TextRange(textOffset, range.getEndOffset()));
}
boolean isSimilarTo(@NotNull Info that) {
return Comparing.equal(myElementAtPointer, that.myElementAtPointer) && myRanges.equals(that.myRanges);
}
@NotNull
public List<TextRange> getRanges() {
return myRanges;
}
@NotNull
public abstract DocInfo getInfo();
public abstract boolean isValid(@NotNull Document document);
public abstract boolean isNavigatable();
boolean rangesAreCorrect(@NotNull Document document) {
final TextRange docRange = new TextRange(0, document.getTextLength());
for (TextRange range : getRanges()) {
if (!docRange.contains(range)) return false;
}
return true;
}
}
private static void showDumbModeNotification(@NotNull Project project) {
DumbService.getInstance(project).showDumbModeNotification("Element information is not available during index update");
}
private static class InfoSingle extends Info {
@NotNull private final PsiElement myTargetElement;
InfoSingle(@NotNull PsiElement elementAtPointer, @NotNull PsiElement targetElement) {
super(elementAtPointer);
myTargetElement = targetElement;
}
InfoSingle(@NotNull PsiReference ref, @NotNull final PsiElement targetElement) {
super(ref.getElement(), ReferenceRange.getAbsoluteRanges(ref));
myTargetElement = targetElement;
}
@Override
@NotNull
public DocInfo getInfo() {
return areElementsValid() ? generateInfo(myTargetElement, myElementAtPointer, isNavigatable()) : DocInfo.EMPTY;
}
private boolean areElementsValid() {
return myTargetElement.isValid() && myElementAtPointer.isValid();
}
@Override
public boolean isValid(@NotNull Document document) {
return areElementsValid() && rangesAreCorrect(document);
}
@Override
public boolean isNavigatable() {
return myTargetElement != myElementAtPointer && myTargetElement != myElementAtPointer.getParent();
}
}
private static class InfoMultiple extends Info {
InfoMultiple(@NotNull final PsiElement elementAtPointer) {
super(elementAtPointer);
}
InfoMultiple(@NotNull final PsiElement elementAtPointer, @NotNull PsiReference ref) {
super(elementAtPointer, ReferenceRange.getAbsoluteRanges(ref));
}
@Override
@NotNull
public DocInfo getInfo() {
return new DocInfo(CodeInsightBundle.message("multiple.implementations.tooltip"), null);
}
@Override
public boolean isValid(@NotNull Document document) {
return rangesAreCorrect(document);
}
@Override
public boolean isNavigatable() {
return true;
}
}
@Nullable
private Info getInfoAt(@NotNull final Editor editor, @NotNull PsiFile file, int offset, @NotNull BrowseMode browseMode) {
return getInfoAt(myProject, editor, file, offset, browseMode);
}
@Nullable
public static Info getInfoAt(@NotNull Project project, @NotNull final Editor editor, @NotNull PsiFile file, int offset,
@NotNull BrowseMode browseMode) {
PsiElement targetElement = null;
if (browseMode == BrowseMode.TypeDeclaration) {
try {
targetElement = GotoTypeDeclarationAction.findSymbolType(editor, offset);
}
catch (IndexNotReadyException e) {
showDumbModeNotification(project);
}
}
else if (browseMode == BrowseMode.Declaration) {
final PsiReference ref = TargetElementUtil.findReference(editor, offset);
final List<PsiElement> resolvedElements = ref == null ? Collections.emptyList() : resolve(ref);
final PsiElement resolvedElement = resolvedElements.size() == 1 ? resolvedElements.get(0) : null;
final PsiElement[] targetElements = GotoDeclarationAction.findTargetElementsNoVS(project, editor, offset, false);
final PsiElement elementAtPointer = file.findElementAt(TargetElementUtil.adjustOffset(file, editor.getDocument(), offset));
if (targetElements != null) {
if (targetElements.length == 0) {
return null;
}
else if (targetElements.length == 1) {
if (targetElements[0] != resolvedElement && elementAtPointer != null && targetElements[0].isPhysical()) {
return ref != null ? new InfoSingle(ref, targetElements[0]) : new InfoSingle(elementAtPointer, targetElements[0]);
}
}
else {
return elementAtPointer != null ? new InfoMultiple(elementAtPointer) : null;
}
}
if (resolvedElements.size() == 1) {
return new InfoSingle(ref, resolvedElements.get(0));
}
if (resolvedElements.size() > 1) {
return elementAtPointer != null ? new InfoMultiple(elementAtPointer, ref) : null;
}
}
else if (browseMode == BrowseMode.Implementation) {
final PsiElement element = TargetElementUtil.getInstance().findTargetElement(editor, ImplementationSearcher.getFlags(), offset);
PsiElement[] targetElements = new ImplementationSearcher() {
@Override
@NotNull
protected PsiElement[] searchDefinitions(final PsiElement element, Editor editor) {
final List<PsiElement> found = new ArrayList<>(2);
DefinitionsScopedSearch.search(element, getSearchScope(element, editor)).forEach(psiElement -> {
found.add(psiElement);
return found.size() != 2;
});
return PsiUtilCore.toPsiElementArray(found);
}
}.searchImplementations(editor, element, offset);
if (targetElements == null) {
return null;
}
if (targetElements.length > 1) {
PsiElement elementAtPointer = file.findElementAt(offset);
if (elementAtPointer != null) {
return new InfoMultiple(elementAtPointer);
}
return null;
}
if (targetElements.length == 1) {
Navigatable descriptor = EditSourceUtil.getDescriptor(targetElements[0]);
if (descriptor == null || !descriptor.canNavigate()) {
return null;
}
targetElement = targetElements[0];
}
}
if (targetElement != null && targetElement.isPhysical()) {
PsiElement elementAtPointer = file.findElementAt(offset);
if (elementAtPointer != null) {
return new InfoSingle(elementAtPointer, targetElement);
}
}
final PsiElement element = GotoDeclarationAction.findElementToShowUsagesOf(editor, offset);
if (element instanceof PsiNameIdentifierOwner) {
PsiElement identifier = ((PsiNameIdentifierOwner)element).getNameIdentifier();
if (identifier != null && identifier.isValid()) {
return new Info(identifier){
@NotNull
@Override
public DocInfo getInfo() {
String name = UsageViewUtil.getType(element) + " '"+ UsageViewUtil.getShortName(element)+"'";
return new DocInfo("Show usages of "+name, null);
}
@Override
public boolean isValid(@NotNull Document document) {
return element.isValid();
}
@Override
public boolean isNavigatable() {
return true;
}
};
}
}
return null;
}
@NotNull
private static List<PsiElement> resolve(@NotNull PsiReference ref) {
// IDEA-56727 try resolve first as in GotoDeclarationAction
PsiElement resolvedElement = ref.resolve();
if (resolvedElement == null && ref instanceof PsiPolyVariantReference) {
List<PsiElement> result = new ArrayList<>();
final ResolveResult[] psiElements = ((PsiPolyVariantReference)ref).multiResolve(false);
for (ResolveResult resolveResult : psiElements) {
if (resolveResult.getElement() != null) {
result.add(resolveResult.getElement());
}
}
return result;
}
return resolvedElement == null ? Collections.emptyList() : Collections.singletonList(resolvedElement);
}
private void disposeHighlighter() {
HighlightersSet highlighter = myHighlighter;
if (highlighter != null) {
myHighlighter = null;
highlighter.uninstall();
HintManager.getInstance().hideAllHints();
}
}
private void updateText(@NotNull String updatedText,
@NotNull Consumer<? super String> newTextConsumer,
@NotNull LightweightHint hint,
@NotNull Editor editor) {
UIUtil.invokeLaterIfNeeded(() -> {
// There is a possible case that quick doc control width is changed, e.g. it contained text
// like 'public final class String implements java.io.Serializable, java.lang.Comparable<java.lang.String>' and
// new text replaces fully-qualified class names by hyperlinks with short name.
// That's why we might need to update the control size. We assume that the hint component is located at the
// layered pane, so, the algorithm is to find an ancestor layered pane and apply new size for the target component.
JComponent component = hint.getComponent();
Dimension oldSize = component.getPreferredSize();
newTextConsumer.consume(updatedText);
Dimension newSize = component.getPreferredSize();
if (newSize.width == oldSize.width) {
return;
}
component.setPreferredSize(new Dimension(newSize.width, newSize.height));
// We're assuming here that there are two possible hint representation modes: popup and layered pane.
if (hint.isRealPopup()) {
TooltipProvider tooltipProvider = myTooltipProvider;
if (tooltipProvider != null) {
// There is a possible case that 'raw' control was rather wide but the 'rich' one is narrower. That's why we try to
// re-show the hint here. Benefits: there is a possible case that we'll be able to show nice layered pane-based balloon;
// the popup will be re-positioned according to the new width.
hint.hide();
tooltipProvider.showHint(new LightweightHint(component), editor);
}
else {
component.setPreferredSize(new Dimension(newSize.width, oldSize.height));
hint.pack();
}
return;
}
Container topLevelLayeredPaneChild = null;
boolean adjustBounds = false;
for (Container current = component.getParent(); current != null; current = current.getParent()) {
if (current instanceof JLayeredPane) {
adjustBounds = true;
break;
}
else {
topLevelLayeredPaneChild = current;
}
}
if (adjustBounds && topLevelLayeredPaneChild != null) {
Rectangle bounds = topLevelLayeredPaneChild.getBounds();
topLevelLayeredPaneChild.setBounds(bounds.x, bounds.y, bounds.width + newSize.width - oldSize.width, bounds.height);
}
});
}
private final class TooltipProvider {
@NotNull private final EditorEx myHostEditor;
private final int myHostOffset;
private BrowseMode myBrowseMode;
private boolean myDisposed;
private CancellablePromise<?> myExecutionProgress;
TooltipProvider(@NotNull EditorEx hostEditor, @NotNull LogicalPosition hostPos) {
myHostEditor = hostEditor;
myHostOffset = hostEditor.logicalPositionToOffset(hostPos);
}
@SuppressWarnings("CopyConstructorMissesField")
TooltipProvider(@NotNull TooltipProvider source) {
myHostEditor = source.myHostEditor;
myHostOffset = source.myHostOffset;
}
void dispose() {
myDisposed = true;
if (myExecutionProgress != null) {
myExecutionProgress.cancel();
}
}
BrowseMode getBrowseMode() {
return myBrowseMode;
}
void execute(@NotNull BrowseMode browseMode) {
myBrowseMode = browseMode;
if (PsiDocumentManager.getInstance(myProject).getPsiFile(myHostEditor.getDocument()) == null) return;
int selStart = myHostEditor.getSelectionModel().getSelectionStart();
int selEnd = myHostEditor.getSelectionModel().getSelectionEnd();
if (myHostOffset >= selStart && myHostOffset < selEnd) {
disposeHighlighter();
return;
}
myExecutionProgress = ReadAction
.nonBlocking(() -> doExecute())
.withDocumentsCommitted(myProject)
.expireWhen(() -> isTaskOutdated(myHostEditor))
.finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run)
.submit(AppExecutorUtil.getAppExecutorService());
}
private Runnable createDisposalContinuation() {
return CtrlMouseHandler.this::disposeHighlighter;
}
@NotNull
private Runnable doExecute() {
EditorEx editor = getPossiblyInjectedEditor();
int offset = getOffset(editor);
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
if (file == null) return createDisposalContinuation();
final Info info;
final DocInfo docInfo;
try {
info = getInfoAt(editor, file, offset, myBrowseMode);
if (info == null) return createDisposalContinuation();
docInfo = info.getInfo();
}
catch (IndexNotReadyException e) {
showDumbModeNotification(myProject);
return createDisposalContinuation();
}
LOG.debug("Obtained info about element under cursor");
return () -> addHighlighterAndShowHint(info, docInfo, editor);
}
@NotNull
private EditorEx getPossiblyInjectedEditor() {
final Document document = myHostEditor.getDocument();
if (PsiDocumentManager.getInstance(myProject).isCommitted(document)) {
PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
return (EditorEx)InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myHostEditor, psiFile, myHostOffset);
}
return myHostEditor;
}
private boolean isTaskOutdated(@NotNull Editor editor) {
return myDisposed || myProject.isDisposed() || editor.isDisposed() ||
!ApplicationManager.getApplication().isUnitTestMode() && !editor.getComponent().isShowing();
}
private int getOffset(@NotNull Editor editor) {
return editor instanceof EditorWindow ? ((EditorWindow)editor).getDocument().hostToInjected(myHostOffset) : myHostOffset;
}
private void addHighlighterAndShowHint(@NotNull Info info, @NotNull DocInfo docInfo, @NotNull EditorEx editor) {
if (myDisposed || editor.isDisposed()) return;
if (myHighlighter != null) {
if (!info.isSimilarTo(myHighlighter.getStoredInfo())) {
disposeHighlighter();
}
else {
// highlighter already set
if (info.isNavigatable()) {
editor.setCustomCursor(CtrlMouseHandler.class, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
return;
}
}
if (!info.isValid(editor.getDocument()) || !info.isNavigatable() && docInfo.text == null) {
return;
}
boolean highlighterOnly = EditorSettingsExternalizable.getInstance().isShowQuickDocOnMouseOverElement() &&
DocumentationManager.getInstance(myProject).getDocInfoHint() != null;
myHighlighter = installHighlighterSet(info, editor, highlighterOnly);
if (highlighterOnly || docInfo.text == null) return;
HyperlinkListener hyperlinkListener = docInfo.docProvider == null
? null
: new QuickDocHyperlinkListener(docInfo.docProvider, info.myElementAtPointer);
Ref<Consumer<? super String>> newTextConsumerRef = new Ref<>();
JComponent component = HintUtil.createInformationLabel(docInfo.text, hyperlinkListener, null, newTextConsumerRef);
component.setBorder(JBUI.Borders.empty(6, 6, 5, 6));
final LightweightHint hint = new LightweightHint(wrapInScrollPaneIfNeeded(component, editor));
myHint = hint;
hint.addHintListener(__ -> myHint = null);
showHint(hint, editor);
Consumer<? super String> newTextConsumer = newTextConsumerRef.get();
if (newTextConsumer != null) {
updateOnPsiChanges(hint, info, newTextConsumer, docInfo.text, editor);
}
}
@NotNull
private JComponent wrapInScrollPaneIfNeeded(@NotNull JComponent component, @NotNull Editor editor) {
if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
Dimension preferredSize = component.getPreferredSize();
Dimension maxSize = getMaxPopupSize(editor);
if (preferredSize.width > maxSize.width || preferredSize.height > maxSize.height) {
// We expect documentation providers to exercise good judgement in limiting the displayed information,
// but in any case, we don't want the hint to cover the whole screen, so we also implement certain limiting here.
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(component, true);
scrollPane.setPreferredSize(new Dimension(Math.min(preferredSize.width, maxSize.width),
Math.min(preferredSize.height, maxSize.height)));
return scrollPane;
}
}
return component;
}
@NotNull
private Dimension getMaxPopupSize(@NotNull Editor editor) {
Rectangle rectangle = ScreenUtil.getScreenRectangle(editor.getContentComponent());
return new Dimension((int)(0.9 * Math.max(640, rectangle.width)), (int)(0.33 * Math.max(480, rectangle.height)));
}
private void updateOnPsiChanges(@NotNull LightweightHint hint,
@NotNull Info info,
@NotNull Consumer<? super String> textConsumer,
@NotNull String oldText,
@NotNull Editor editor) {
if (!hint.isVisible()) return;
Disposable hintDisposable = Disposer.newDisposable("CtrlMouseHandler.TooltipProvider.updateOnPsiChanges");
hint.addHintListener(__ -> Disposer.dispose(hintDisposable));
myProject.getMessageBus().connect(hintDisposable).subscribe(PsiModificationTracker.TOPIC, () -> ReadAction
.nonBlocking(() -> {
try {
DocInfo newDocInfo = info.getInfo();
return (Runnable)() -> {
if (newDocInfo.text != null && !oldText.equals(newDocInfo.text)) {
updateText(newDocInfo.text, textConsumer, hint, editor);
}
};
}
catch (IndexNotReadyException e) {
showDumbModeNotification(myProject);
return createDisposalContinuation();
}
})
.finishOnUiThread(ModalityState.defaultModalityState(), Runnable::run)
.withDocumentsCommitted(myProject)
.expireWith(hintDisposable)
.expireWhen(() -> !info.isValid(editor.getDocument()))
.coalesceBy(hint)
.submit(AppExecutorUtil.getAppExecutorService()));
}
public void showHint(@NotNull LightweightHint hint, @NotNull Editor editor) {
if (ApplicationManager.getApplication().isUnitTestMode() || editor.isDisposed()) return;
final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
short constraint = HintManager.ABOVE;
LogicalPosition position = editor.offsetToLogicalPosition(getOffset(editor));
Point p = HintManagerImpl.getHintPosition(hint, editor, position, constraint);
if (p.y - hint.getComponent().getPreferredSize().height < 0) {
constraint = HintManager.UNDER;
p = HintManagerImpl.getHintPosition(hint, editor, position, constraint);
}
hintManager.showEditorHint(hint, editor, p,
HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING,
0, false, HintManagerImpl.createHintHint(editor, p, hint, constraint).setContentActive(false));
}
}
@NotNull
private HighlightersSet installHighlighterSet(@NotNull Info info, @NotNull EditorEx editor, boolean highlighterOnly) {
editor.getContentComponent().addKeyListener(myEditorKeyListener);
editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
if (info.isNavigatable()) {
editor.setCustomCursor(CtrlMouseHandler.class, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
List<RangeHighlighter> highlighters = new ArrayList<>();
if (!highlighterOnly || info.isNavigatable()) {
TextAttributes attributes = info.isNavigatable()
? EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR)
: new TextAttributes(null, HintUtil.getInformationColor(), null, null, Font.PLAIN);
for (TextRange range : info.getRanges()) {
TextAttributes attr = NavigationUtil.patchAttributesColor(attributes, range, editor);
final RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(),
HighlighterLayer.HYPERLINK,
attr,
HighlighterTargetArea.EXACT_RANGE);
highlighters.add(highlighter);
}
}
return new HighlightersSet(highlighters, editor, info);
}
@TestOnly
public boolean isCalculationInProgress() {
TooltipProvider provider = myTooltipProvider;
if (provider == null) return false;
Future<?> progress = provider.myExecutionProgress;
if (progress == null) return false;
return !progress.isDone();
}
private final class HighlightersSet {
@NotNull private final List<? extends RangeHighlighter> myHighlighters;
@NotNull private final EditorEx myHighlighterView;
@NotNull private final Info myStoredInfo;
private HighlightersSet(@NotNull List<? extends RangeHighlighter> highlighters,
@NotNull EditorEx highlighterView,
@NotNull Info storedInfo) {
myHighlighters = highlighters;
myHighlighterView = highlighterView;
myStoredInfo = storedInfo;
}
public void uninstall() {
for (RangeHighlighter highlighter : myHighlighters) {
highlighter.dispose();
}
myHighlighterView.setCustomCursor(CtrlMouseHandler.class, null);
myHighlighterView.getContentComponent().removeKeyListener(myEditorKeyListener);
myHighlighterView.getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener);
}
@NotNull
Info getStoredInfo() {
return myStoredInfo;
}
}
public static final class DocInfo {
public static final DocInfo EMPTY = new DocInfo(null, null);
@Nullable public final String text;
@Nullable final DocumentationProvider docProvider;
DocInfo(@Nullable String text, @Nullable DocumentationProvider provider) {
this.text = text;
docProvider = provider;
}
}
private final class QuickDocHyperlinkListener implements HyperlinkListener {
@NotNull private final DocumentationProvider myProvider;
@NotNull private final PsiElement myContext;
QuickDocHyperlinkListener(@NotNull DocumentationProvider provider, @NotNull PsiElement context) {
myProvider = provider;
myContext = context;
}
@Override
public void hyperlinkUpdate(@NotNull HyperlinkEvent e) {
if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) {
return;
}
String description = e.getDescription();
if (StringUtil.isEmpty(description) || !description.startsWith(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL)) {
return;
}
String elementName = e.getDescription().substring(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL.length());
DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> {
PsiElement targetElement = myProvider.getDocumentationElementForLink(PsiManager.getInstance(myProject), elementName, myContext);
if (targetElement != null) {
LightweightHint hint = myHint;
if (hint != null) {
hint.hide(true);
}
DocumentationManager.getInstance(myProject).showJavaDocInfo(targetElement, myContext, null);
}
});
}
}
}
|
package org.zstack.storage.primary.local;
import org.zstack.header.identity.rbac.RBACDescription;
import org.zstack.header.volume.VolumeVO;
public class RBACInfo implements RBACDescription {
@Override
public void permissions() {
permissionBuilder()
.adminOnlyAPIs("org.zstack.storage.primary.local.**")
.normalAPIs(APILocalStorageGetVolumeMigratableHostsMsg.class, APILocalStorageMigrateVolumeMsg.class,
APIQueryLocalStorageResourceRefMsg.class)
.targetResources(VolumeVO.class)
.build();
}
@Override
public void contributeToRoles() {
roleContributorBuilder()
.roleName("other")
.actions(APILocalStorageGetVolumeMigratableHostsMsg.class, APILocalStorageMigrateVolumeMsg.class,
APIQueryLocalStorageResourceRefMsg.class)
.build();
}
@Override
public void roles() {
}
@Override
public void globalReadableResources() {
}
}
|
package clojuredev.outline;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.IElementComparer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import clojure.lang.Keyword;
import clojuredev.ClojuredevPlugin;
import clojuredev.debug.IClojureClientProvider;
public class ClojureNSOutlinePage extends Page implements
IContentOutlinePage, ISelectionChangedListener {
private ListenerList selectionChangedListeners = new ListenerList();
private TreeViewer treeViewer;
private final IClojureClientProvider clojureClientProvider;
private static final Keyword KEYWORD_NAME = Keyword.intern(null, "name");
private static final Keyword KEYWORD_CHILDREN = Keyword.intern(null, "children");
private static final Keyword KEYWORD_TYPE = Keyword.intern(null, "type");
private static final Keyword KEYWORD_PRIVATE = Keyword.intern(null, "private");
private static final Keyword KEYWORD_DOC = Keyword.intern(null, "doc");
private static final Keyword KEYWORD_ARGLISTS = Keyword.intern(null, "arglists");
private Composite control;
private Text filterText;
private String patternString = "";
private Pattern pattern;
private boolean searchInName = true;
private boolean searchInDoc = false;
private ISelection selectionBeforePatternSearchBegan;
private Object[] expandedElementsBeforeSearchBegan;
public ClojureNSOutlinePage(IClojureClientProvider clojureClientProvider) {
this.clojureClientProvider = clojureClientProvider;
}
@Override
public void createControl(Composite theParent) {
control = new Composite(theParent, SWT.NONE);
GridLayout gl = new GridLayout();
gl.numColumns = 4;
control.setLayout(gl);
Label l = new Label(control, SWT.NONE);
l.setText("Find :");
l.setToolTipText("Enter an expression on which the browser will filter, based on name and doc string of symbols");
GridData gd = new GridData();
gd.verticalAlignment = SWT.CENTER;
l.setLayoutData(gd);
filterText = new Text(control, SWT.FILL | SWT.BORDER);
filterText.setTextLimit(10);
filterText.setToolTipText("Enter here a word to search. It can be a regexp. e.g. \"-map$\" (without double quotes) for matching strings ending with -map");
gd = new GridData();
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.CENTER;
filterText.setLayoutData(gd);
filterText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
patternString = ((Text) e.getSource()).getText();
if ("".equals(patternString.trim())) {
if (pattern != null) {
// user stops search, we restore the previous state of the tree
pattern = null;
treeViewer.refresh(false);
treeViewer.setExpandedElements(expandedElementsBeforeSearchBegan);
treeViewer.setSelection(selectionBeforePatternSearchBegan);
selectionBeforePatternSearchBegan = null;
expandedElementsBeforeSearchBegan = null;
}
} else {
pattern = Pattern.compile(patternString.trim());
if (selectionBeforePatternSearchBegan==null) {
// user triggers search, we save the current state of the tree
selectionBeforePatternSearchBegan = treeViewer.getSelection();
expandedElementsBeforeSearchBegan = treeViewer.getExpandedElements();
}
treeViewer.refresh(false);
treeViewer.expandAll();
}
}
});
Button inName = new Button(control, SWT.CHECK);
gd = new GridData();
gd.verticalAlignment = SWT.CENTER;
inName.setLayoutData(gd);
inName.setText("in name");
inName.setToolTipText("Press to enable the search in the name");
inName.setSelection(true);
inName.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
searchInName = ((Button) e.getSource()).getSelection();
treeViewer.refresh(false);
}
});
Button inDoc = new Button(control, SWT.CHECK);
gd = new GridData();
gd.verticalAlignment = SWT.CENTER;
inDoc.setLayoutData(gd);
inDoc.setText("in doc");
inDoc.setToolTipText("Press to enable the search in the documentation string");
inDoc.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
searchInDoc = ((Button) e.getSource()).getSelection();
treeViewer.refresh(false);
}
});
treeViewer = new TreeViewer(control, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
treeViewer.addSelectionChangedListener(this);
gd = new GridData();//SWT.FILL, SWT.FILL, true, true, 2, 1);
gd.horizontalSpan = 4;
gd.horizontalAlignment = SWT.FILL;
gd.grabExcessHorizontalSpace = true;
gd.verticalAlignment = SWT.FILL;
gd.grabExcessVerticalSpace = true;
treeViewer.getControl().setLayoutData(gd);
ColumnViewerToolTipSupport.enableFor(treeViewer);
treeViewer.setContentProvider(new ContentProvider());
treeViewer.setLabelProvider(new LabelProvider());
treeViewer.setSorter(new NSSorter());
treeViewer.setComparer(new IElementComparer() {
public boolean equals(Object a, Object b) {
if (a == b) {
return true;
}
if ( (a==null && b!=null) || (b==null && a!=null) ) {
return false;
}
if (a instanceof Map && b instanceof Map
&& ((Map) a).get(KEYWORD_NAME)!=null && ((Map) b).get(KEYWORD_NAME)!=null) {
return ((Map) a).get(KEYWORD_NAME).equals(((Map) b).get(KEYWORD_NAME));
} else {
return a.equals(b);
}
}
public int hashCode(Object element) {
if (element == null) {
return 0;
}
if ( element instanceof Map && ((Map) element).get(KEYWORD_NAME)!=null) {
return ((Map) element).get(KEYWORD_NAME).hashCode();
} else {
return element.hashCode();
}
}
});
treeViewer.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (patternString==null || patternString.trim().equals("")) {
return true;
}
Map parent = (Map) parentElement;
Map elem = (Map) element;
if ("var".equals(elem.get(KEYWORD_TYPE))) {
String name = (String) elem.get(KEYWORD_NAME);
boolean nameMatches = searchInName && name!=null && pattern.matcher(name).find();
String doc = (String) elem.get(KEYWORD_DOC);
boolean docMatches = searchInDoc && doc!=null && pattern.matcher(doc).find();
return nameMatches || docMatches;
} else {
return true;
}
}});
}
private static class ContentProvider implements ITreeContentProvider {
private Object input;
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.input = newInput;
}
public Object[] getChildren(Object parentElement) {
if (Map.class.isInstance(parentElement)) {
Collection children = (Collection) ((Map) parentElement).get(KEYWORD_CHILDREN);
if (children == null) {
return new Object[0];
} else {
return children.toArray();
}
} else {
return new Object[0];
}
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object parentElement) {
if (Map.class.isInstance(parentElement)) {
return ((Map) parentElement).get(KEYWORD_CHILDREN) != null;
} else {
return false;
}
}
}
private static class LabelProvider extends CellLabelProvider {
public String getToolTipText(Object element) {
StringBuilder result = new StringBuilder();
Object maybeArglist = ((Map) element).get(KEYWORD_ARGLISTS);
if (maybeArglist != null) {
result.append("arglists: ");
result.append(maybeArglist);
}
Object maybeDoc = ((Map) element).get(KEYWORD_DOC);
if (maybeDoc != null) {
if (result.length() > 0) {
result.append("\n\n");
}
result.append(maybeDoc);
}
if (result.length() != 0) {
return result.toString();
} else {
return "no documentation information";
}
}
public Point getToolTipShift(Object object) {
return new Point(5,15);
}
public int getToolTipDisplayDelayTime(Object object) {
return 100;
}
public int getToolTipTimeDisplayed(Object object) {
return 15000;
}
public void update(ViewerCell cell) {
cell.setText(getText(cell.getElement()));
cell.setImage(getImage(cell.getElement()));
}
private String getText(Object element) {
if (Map.class.isInstance(element)) {
return (String) ((Map) element).get(KEYWORD_NAME);
} else {
return element.toString();
}
}
private Image getImage(Object element) {
if (Map.class.isInstance(element)) {
Map node = (Map) element;
if ("ns".equals(node.get(KEYWORD_TYPE))) {
return ClojuredevPlugin.getDefault().getImageRegistry().get(ClojuredevPlugin.NS);
} else {
if ("true".equals(node.get(KEYWORD_PRIVATE))) {
return ClojuredevPlugin.getDefault().getImageRegistry().get(ClojuredevPlugin.PRIVATE_FUNCTION);
} else {
return ClojuredevPlugin.getDefault().getImageRegistry().get(ClojuredevPlugin.PUBLIC_FUNCTION);
}
}
}
return null;
}
}
private static class NSSorter extends ViewerSorter {
}
private Map<String, List<String>> getRemoteNsTree() {
Object result = clojureClientProvider.getClojureClient().invokeStr("(clojuredev.debug.serverrepl/namespaces-info)");
System.out.println("invokeStr called");
return (Map<String, List<String>>) result;
}
public void refresh() {
if (treeViewer == null) {
return;
}
Object oldInput = treeViewer.getInput();
final Object newInput = getRemoteNsTree();
if (oldInput!=null && oldInput.equals(newInput)) {
return;
}
if (Display.getCurrent() == null) {
final Display display = PlatformUI.getWorkbench().getDisplay();
display.asyncExec(new Runnable() {
public void run() {
refreshTreeViewer(newInput);
}
});
} else {
refreshTreeViewer(newInput);
}
}
private void refreshTreeViewer(Object newInput) {
ISelection sel = treeViewer.getSelection();
TreePath[] expandedTreePaths = treeViewer.getExpandedTreePaths();
treeViewer.setInput(newInput);
treeViewer.setExpandedTreePaths(expandedTreePaths);
treeViewer.setSelection(sel);
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* Fires a selection changed event.
*
* @param selection the new selection
*/
protected void fireSelectionChanged(ISelection selection) {
// create an event
final SelectionChangedEvent event = new SelectionChangedEvent(this,
selection);
// fire the event
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i) {
final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
SafeRunner.run(new SafeRunnable() {
public void run() {
l.selectionChanged(event);
}
});
}
}
public Control getControl() {
if (control == null) {
return null;
}
return control;
}
public ISelection getSelection() {
if (treeViewer == null) {
return StructuredSelection.EMPTY;
}
return treeViewer.getSelection();
}
public void init(IPageSite pageSite) {
super.init(pageSite);
pageSite.setSelectionProvider(this);
}
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
public void selectionChanged(SelectionChangedEvent event) {
fireSelectionChanged(event.getSelection());
}
/**
* Sets focus to a part in the page.
*/
public void setFocus() {
treeViewer.getControl().setFocus();
}
public void setSelection(ISelection selection) {
if (treeViewer != null) {
treeViewer.setSelection(selection);
}
}
}
|
package com.kotcrab.vis.editor;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.kotcrab.vis.editor.event.Event;
import com.kotcrab.vis.editor.event.EventListener;
import com.kotcrab.vis.editor.event.ProjectStatusEvent;
import com.kotcrab.vis.editor.event.ProjectStatusEvent.Status;
import com.kotcrab.vis.editor.event.StatusBarEvent;
import com.kotcrab.vis.editor.module.ColorPickerModule;
import com.kotcrab.vis.editor.module.EditorModuleContainer;
import com.kotcrab.vis.editor.module.EditorSettingsIOModule;
import com.kotcrab.vis.editor.module.GeneralSettingsModule;
import com.kotcrab.vis.editor.module.MenuBarModule;
import com.kotcrab.vis.editor.module.ProjectIOModule;
import com.kotcrab.vis.editor.module.StatusBarModule;
import com.kotcrab.vis.editor.module.TabsModule;
import com.kotcrab.vis.editor.module.ToolbarModule;
import com.kotcrab.vis.editor.module.project.AssetsManagerUIModule;
import com.kotcrab.vis.editor.module.project.AssetsWatcherModule;
import com.kotcrab.vis.editor.module.project.ExportModule;
import com.kotcrab.vis.editor.module.project.FileAccessModule;
import com.kotcrab.vis.editor.module.project.Project;
import com.kotcrab.vis.editor.module.project.ProjectInfoTabModule;
import com.kotcrab.vis.editor.module.project.ProjectModuleContainer;
import com.kotcrab.vis.editor.module.project.SceneIOModule;
import com.kotcrab.vis.editor.module.project.SceneTabsModule;
import com.kotcrab.vis.editor.module.project.TextureCacheModule;
import com.kotcrab.vis.editor.module.scene.EditorScene;
import com.kotcrab.vis.editor.module.scene.GridRendererModule.GridSettingsModule;
import com.kotcrab.vis.editor.module.scene.InputModule;
import com.kotcrab.vis.editor.ui.EditorFrame;
import com.kotcrab.vis.editor.ui.SettingsDialog;
import com.kotcrab.vis.editor.ui.tab.Tab;
import com.kotcrab.vis.editor.ui.tab.TabViewMode;
import com.kotcrab.vis.editor.util.EditorException;
import com.kotcrab.vis.editor.util.Log;
import com.kotcrab.vis.ui.OptionDialogAdapter;
import com.kotcrab.vis.ui.VisTable;
import com.kotcrab.vis.ui.VisUI;
import com.kotcrab.vis.ui.util.DialogUtils;
import com.kotcrab.vis.ui.util.DialogUtils.OptionDialogType;
import com.kotcrab.vis.ui.widget.VisLabel;
import com.kotcrab.vis.ui.widget.VisSplitPane;
import com.kotcrab.vis.ui.widget.file.FileChooser;
public class Editor extends ApplicationAdapter implements EventListener {
public static Editor instance;
private EditorFrame frame;
private Stage stage;
private Table root;
// TODO move to module
private Table mainContentTable;
private Table tabContentTable;
private VisTable projectContentTable;
private VisSplitPane splitPane;
private SettingsDialog settingsDialog;
private EditorModuleContainer editorMC;
private ProjectModuleContainer projectMC;
private InputModule inputModule;
private GeneralSettingsModule settings;
private boolean projectLoaded = false;
private Tab tab;
public Editor (EditorFrame frame) {
this.frame = frame;
}
@Override
public void create () {
instance = this;
Assets.load();
VisUI.load();
VisUI.setDefaultTitleAlign(Align.center);
FileChooser.setFavoritesPrefsName("com.kotcrab.vis.editor");
App.eventBus.register(this);
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
root = new Table();
root.setFillParent(true);
stage.addActor(root);
createUI();
createModuleContainers();
createModulesUI();
// debug section
try {
editorMC.get(ProjectIOModule.class).load((Gdx.files.absolute("F:\\Poligon\\Tester")));
} catch (EditorException e) {
Log.exception(e);
}
FileHandle scene = Gdx.files.absolute("F:\\Poligon\\Tester\\vis\\assets\\scene\\test.scene");
if (scene.exists()) {
EditorScene testScene = projectMC.get(SceneIOModule.class).load(scene);
projectMC.get(SceneTabsModule.class).open(testScene);
}
//showSettingsWindow();
//debug end
Log.info("Loading completed");
}
private void createUI () {
mainContentTable = new Table();
tabContentTable = new Table();
projectContentTable = new VisTable(true);
splitPane = new VisSplitPane(null, null, true);
splitPane.setSplitAmount(0.78f);
projectContentTable.add(new VisLabel("Project Content Manager has not been loaded yet"));
settingsDialog = new SettingsDialog();
}
private void createModuleContainers () {
editorMC = new EditorModuleContainer();
projectMC = new ProjectModuleContainer(editorMC);
editorMC.add(new ProjectIOModule());
editorMC.add(inputModule = new InputModule(mainContentTable));
editorMC.add(new MenuBarModule(projectMC));
editorMC.add(new ToolbarModule());
editorMC.add(new TabsModule());
editorMC.add(new StatusBarModule());
editorMC.add(new EditorSettingsIOModule());
editorMC.add(new ColorPickerModule());
editorMC.add(settings = new GeneralSettingsModule());
editorMC.add(new GridSettingsModule());
editorMC.init();
settingsDialog.addAll(editorMC.getModules());
}
private void createModulesUI () {
root.add(editorMC.get(MenuBarModule.class).getTable()).fillX().expandX().row();
root.add(editorMC.get(ToolbarModule.class).getTable()).fillX().expandX().row();
root.add(editorMC.get(TabsModule.class).getTable()).fillX().expandX().row();
root.add(mainContentTable).expand().fill().row();
root.add(editorMC.get(StatusBarModule.class).getTable()).fillX().expandX().row();
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
editorMC.resize();
projectMC.resize();
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
if (tab != null) tab.render(stage.getBatch());
stage.draw();
}
@Override
public void dispose () {
App.eventBus.stop();
editorMC.dispose();
if (projectLoaded) projectMC.dispose();
stage.dispose();
Assets.dispose();
VisUI.dispose();
frame.dispose();
Log.dispose();
}
public void requestExit () {
if (settings.isConfirmExit()) {
DialogUtils.OptionDialog dialog = DialogUtils.showOptionDialog(getStage(), "Confirm Exit", "Are you sure you want to exit VisEditor?", OptionDialogType.YES_CANCEL, new OptionDialogAdapter() {
@Override
public void yes () {
exit();
}
});
dialog.setYesButtonText("Exit");
} else
exit();
}
private void exit () {
Gdx.app.exit();
}
public Stage getStage () {
return stage;
}
@Override
public boolean onEvent (Event e) {
return false;
}
public void requestProjectUnload () {
projectLoaded = false;
projectMC.dispose();
settingsDialog.removeAll(projectMC.getModules());
App.eventBus.post(new StatusBarEvent("Project unloaded"));
App.eventBus.post(new ProjectStatusEvent(Status.Unloaded));
}
public void projectLoaded (Project project) {
// TODO unload previous project dialog
if (projectLoaded) {
DialogUtils.showErrorDialog(getStage(), "Other project is already loaded!");
return;
}
projectLoaded = true;
projectMC.setProject(project);
projectMC.add(new FileAccessModule());
projectMC.add(new AssetsWatcherModule());
projectMC.add(new TextureCacheModule());
projectMC.add(new ExportModule());
projectMC.add(new SceneIOModule());
projectMC.add(new SceneTabsModule());
projectMC.add(new ProjectInfoTabModule());
projectMC.add(new AssetsManagerUIModule());
projectMC.init();
settingsDialog.addAll(projectMC.getModules());
App.eventBus.post(new StatusBarEvent("Project loaded"));
App.eventBus.post(new ProjectStatusEvent(Status.Loaded));
}
public void tabChanged (Tab tab) {
this.tab = tab;
tabContentTable.clear();
mainContentTable.clear();
splitPane.setWidgets(null, null);
if (tab != null) {
tabContentTable.add(tab.getContentTable()).expand().fill();
if (tab.getViewMode() == TabViewMode.TAB_ONLY)
mainContentTable.add(tabContentTable).expand().fill();
else {
splitPane.setWidgets(tabContentTable, projectContentTable);
mainContentTable.add(splitPane).expand().fill();
}
}
inputModule.reattachListeners();
}
public VisTable getProjectContentTable () {
return projectContentTable;
}
public void showSettingsWindow () {
stage.addActor(settingsDialog.fadeIn());
}
}
|
package bd.ac.seu.advancedjavalab;
import java.util.ArrayList;
/**
*
* @author kmhasan
*/
public class Task1 {
?? subset ??
public <T> void print(ArrayList<T> data) {
for (T t: data)
System.out.println(t);
}
public Task1() {
ArrayList<String> cricketers = new ArrayList<>();
cricketers.add("Mashrafi");
cricketers.add("Sabbir");
cricketers.add("Nasir");
cricketers.add("Mushfiq");
cricketers.add("Mustafiz");
cricketers.add("Rubel");
cricketers.add("Tamim");
print(subset(cricketers, ??));
//print(cricketers);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Task1();
}
}
|
package com.digero.common.midi;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Transmitter;
import javax.swing.Timer;
import com.digero.common.util.IDisposable;
import com.sun.media.sound.MidiUtils;
import com.sun.media.sound.MidiUtils.TempoCache;
public class SequencerWrapper implements IMidiConstants, IDisposable {
public static final int UPDATE_FREQUENCY_MILLIS = 25;
public static final long UPDATE_FREQUENCY_MICROS = UPDATE_FREQUENCY_MILLIS * 1000;
protected Sequencer sequencer;
private Receiver receiver;
private Transmitter transmitter;
private List<Transceiver> transceivers = new ArrayList<Transceiver>();
private long dragPosition;
private boolean isDragging;
private TempoCache tempoCache = new TempoCache();
private Timer updateTimer = new Timer(UPDATE_FREQUENCY_MILLIS, new TimerActionListener());
private long lastUpdatePosition = -1;
private boolean lastRunning = false;
private List<SequencerListener> listeners = null;
public SequencerWrapper() throws MidiUnavailableException {
sequencer = MidiSystem.getSequencer(false);
sequencer.open();
transmitter = sequencer.getTransmitter();
receiver = createReceiver();
transmitter.setReceiver(receiver);
}
protected Receiver createReceiver() throws MidiUnavailableException {
return MidiSystem.getReceiver();
}
@Override
public void dispose() {
if (sequencer != null) {
stop();
}
listeners = null;
if (updateTimer != null)
updateTimer.stop();
if (transceivers != null) {
for (Transceiver t : transceivers)
t.close();
transceivers = null;
}
if (transmitter != null)
transmitter.close();
if (receiver != null)
receiver.close();
if (sequencer != null)
sequencer.close();
}
public void addTransceiver(Transceiver transceiver) {
Transmitter lastTransmitter = transmitter;
if (!transceivers.isEmpty())
lastTransmitter = transceivers.get(transceivers.size() - 1);
// Hook up the transceiver in the chain
lastTransmitter.setReceiver(transceiver);
transceiver.setReceiver(receiver);
transceivers.add(transceiver);
}
private class TimerActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (sequencer != null) {
long songPos = sequencer.getMicrosecondPosition();
if (songPos >= getLength()) {
// There's a bug in Sun's RealTimeSequencer, where there is a possible
// deadlock when calling setMicrosecondPosition(0) exactly when the sequencer
// hits the end of the sequence. It looks like it's safe to call
// sequencer.setTickPosition(0).
sequencer.stop();
sequencer.setTickPosition(0);
lastUpdatePosition = songPos;
}
else {
if (lastUpdatePosition != songPos) {
lastUpdatePosition = songPos;
fireChangeEvent(SequencerProperty.POSITION);
}
boolean running = sequencer.isRunning();
if (lastRunning != running) {
lastRunning = running;
if (running)
updateTimer.start();
else
updateTimer.stop();
fireChangeEvent(SequencerProperty.IS_RUNNING);
}
}
}
}
};
public void reset(boolean fullReset) {
stop();
setPosition(0);
if (fullReset) {
Sequence seqSave = sequencer.getSequence();
try {
sequencer.setSequence((Sequence) null);
}
catch (InvalidMidiDataException e) {
// This won't happen
throw new RuntimeException(e);
}
sequencer.close();
transmitter.close();
receiver.close();
try {
sequencer = MidiSystem.getSequencer(false);
sequencer.open();
transmitter = sequencer.getTransmitter();
receiver = createReceiver();
}
catch (MidiUnavailableException e1) {
throw new RuntimeException(e1);
}
try {
sequencer.setSequence(seqSave);
}
catch (InvalidMidiDataException e) {
// This won't happen
throw new RuntimeException(e);
}
// Hook up the transmitter to the receiver through any transceivers that we have
Transmitter prevTransmitter = transmitter;
for (Transceiver transceiver : transceivers) {
prevTransmitter.setReceiver(transceiver);
prevTransmitter = transceiver;
}
prevTransmitter.setReceiver(receiver);
try {
ShortMessage msg = new ShortMessage();
msg.setMessage(ShortMessage.SYSTEM_RESET);
receiver.send(msg, -1);
}
catch (InvalidMidiDataException e) {
e.printStackTrace();
}
}
else { // Not a full reset
boolean isOpen = sequencer.isOpen();
try {
if (!isOpen)
sequencer.open();
ShortMessage msg = new ShortMessage();
for (int i = 0; i < CHANNEL_COUNT; i++) {
msg.setMessage(ShortMessage.PROGRAM_CHANGE, i, 0, 0);
receiver.send(msg, -1);
msg.setMessage(ShortMessage.CONTROL_CHANGE, i, ALL_CONTROLLERS_OFF, 0);
receiver.send(msg, -1);
}
msg.setMessage(ShortMessage.SYSTEM_RESET);
receiver.send(msg, -1);
}
catch (MidiUnavailableException e) {
// Ignore
}
catch (InvalidMidiDataException e) {
// Ignore
e.printStackTrace();
}
if (!isOpen)
sequencer.close();
}
}
public long getTickPosition() {
return sequencer.getTickPosition();
}
public void setTickPosition(long tick) {
if (tick != getTickPosition()) {
sequencer.setTickPosition(tick);
lastUpdatePosition = sequencer.getMicrosecondPosition();
fireChangeEvent(SequencerProperty.POSITION);
}
}
public long getPosition() {
return sequencer.getMicrosecondPosition();
}
public void setPosition(long position) {
if (position == 0) {
// Sun's RealtimeSequencer isn't entirely reliable when calling
// setMicrosecondPosition(0). Instead call setTickPosition(0),
// which has the same effect and isn't so buggy.
setTickPosition(0);
}
else if (position != getPosition()) {
sequencer.setMicrosecondPosition(position);
lastUpdatePosition = sequencer.getMicrosecondPosition();
fireChangeEvent(SequencerProperty.POSITION);
}
}
public long getLength() {
return sequencer.getMicrosecondLength();
}
public float getTempoFactor() {
return sequencer.getTempoFactor();
}
public void setTempoFactor(float tempo) {
if (tempo != getTempoFactor()) {
sequencer.setTempoFactor(tempo);
fireChangeEvent(SequencerProperty.TEMPO);
}
}
public boolean isRunning() {
return sequencer.isRunning();
}
public void setRunning(boolean isRunning) {
if (isRunning != this.isRunning()) {
if (isRunning) {
sequencer.start();
updateTimer.start();
}
else {
sequencer.stop();
updateTimer.stop();
}
lastRunning = isRunning;
fireChangeEvent(SequencerProperty.IS_RUNNING);
}
}
public void start() {
setRunning(true);
}
public void stop() {
setRunning(false);
}
public boolean getTrackMute(int track) {
return sequencer.getTrackMute(track);
}
public void setTrackMute(int track, boolean mute) {
if (mute != this.getTrackMute(track)) {
sequencer.setTrackMute(track, mute);
fireChangeEvent(SequencerProperty.TRACK_ACTIVE);
}
}
public boolean getTrackSolo(int track) {
return sequencer.getTrackSolo(track);
}
public void setTrackSolo(int track, boolean solo) {
if (solo != this.getTrackSolo(track)) {
sequencer.setTrackSolo(track, solo);
fireChangeEvent(SequencerProperty.TRACK_ACTIVE);
}
}
/**
* Takes into account both muting and solo.
*/
public boolean isTrackActive(int track) {
Sequence song = sequencer.getSequence();
if (song == null)
return true;
if (sequencer.getTrackSolo(track))
return true;
for (int i = song.getTracks().length - 1; i >= 0; --i) {
if (i != track && sequencer.getTrackSolo(i))
return false;
}
return !sequencer.getTrackMute(track);
}
/**
* Overriden by NoteFilterSequencerWrapper. On SequencerWrapper for
* convienience.
*/
public boolean isNoteActive(int noteId) {
return true;
}
/**
* If dragging, returns the drag position. Otherwise returns the song
* position.
*/
public long getThumbPosition() {
return isDragging() ? getDragPosition() : getPosition();
}
/** If dragging, returns the drag tick. Otherwise returns the song tick. */
public long getThumbTick() {
return isDragging() ? getDragTick() : getTickPosition();
}
public long getDragPosition() {
return dragPosition;
}
public long getDragTick() {
return MidiUtils.microsecond2tick(getSequence(), getDragPosition(), tempoCache);
}
public void setDragTick(long tick) {
setDragPosition(MidiUtils.tick2microsecond(getSequence(), tick, tempoCache));
}
public void setDragPosition(long dragPosition) {
if (this.dragPosition != dragPosition) {
this.dragPosition = dragPosition;
fireChangeEvent(SequencerProperty.DRAG_POSITION);
}
}
public boolean isDragging() {
return isDragging;
}
public void setDragging(boolean isDragging) {
if (this.isDragging != isDragging) {
this.isDragging = isDragging;
fireChangeEvent(SequencerProperty.IS_DRAGGING);
}
}
public void addChangeListener(SequencerListener l) {
if (listeners == null)
listeners = new ArrayList<SequencerListener>();
listeners.add(l);
}
public void removeChangeListener(SequencerListener l) {
if (listeners != null)
listeners.remove(l);
}
protected void fireChangeEvent(SequencerProperty property) {
if (listeners != null) {
SequencerEvent e = new SequencerEvent(this, property);
for (SequencerListener l : listeners) {
l.propertyChanged(e);
}
}
}
public void setSequence(Sequence sequence) throws InvalidMidiDataException {
if (sequencer.getSequence() != sequence) {
boolean preLoaded = isLoaded();
sequencer.setSequence(sequence);
if (sequence != null)
tempoCache.refresh(sequence);
if (preLoaded != isLoaded())
fireChangeEvent(SequencerProperty.IS_LOADED);
fireChangeEvent(SequencerProperty.LENGTH);
fireChangeEvent(SequencerProperty.SEQUENCE);
}
}
public void clearSequence() {
try {
setSequence(null);
}
catch (InvalidMidiDataException e) {
// This shouldn't happen
throw new RuntimeException(e);
}
}
public boolean isLoaded() {
return sequencer.getSequence() != null;
}
public Sequence getSequence() {
return sequencer.getSequence();
}
public Transmitter getTransmitter() {
return transmitter;
}
public Receiver getReceiver() {
return receiver;
}
public void open() throws MidiUnavailableException {
sequencer.open();
}
public void close() {
sequencer.close();
}
}
|
package org.hawk.emf.metamodel;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.hawk.core.IMetaModelResourceFactory;
import org.hawk.core.model.IHawkMetaModelResource;
import org.hawk.core.model.IHawkPackage;
import org.hawk.emf.EMFPackage;
import org.hawk.emf.model.util.RegisterMeta;
public class EMFMetaModelResourceFactory implements IMetaModelResourceFactory {
/**
* Property that can be set to a comma-separated list of extensions (e.g.
* ".profile.xmi") that should be supported in addition to the default
* ones (".ecore"). Composite extensions are allowed (e.g.
* ".rail.way").
*/
public static final String PROPERTY_EXTRA_EXTENSIONS = "org.hawk.emf.metamodel.extraExtensions";
private final String hrn = "EMF Metamodel Resource Factory";
private final Set<String> metamodelExtensions;
private final ResourceSet resourceSet;
public EMFMetaModelResourceFactory() {
metamodelExtensions = new HashSet<String>();
metamodelExtensions.add(".ecore");
final String sExtraExtensions = System.getProperty(PROPERTY_EXTRA_EXTENSIONS);
if (sExtraExtensions != null) {
String[] extraExtensions = sExtraExtensions.split(",");
for (String extraExtension : extraExtensions) {
metamodelExtensions.add(extraExtension);
}
}
if (EPackage.Registry.INSTANCE.getEPackage(EcorePackage.eNS_URI) == null) {
EPackage.Registry.INSTANCE.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
}
resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore",
new EcoreResourceFactoryImpl());
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
}
@Override
public String getType() {
return getClass().getName();
}
@Override
public String getHumanReadableName() {
return hrn;
}
@Override
public void shutdown() {
}
@Override
public IHawkMetaModelResource parse(File f) throws Exception {
EMFMetaModelResource ret;
Resource r = resourceSet.createResource(URI.createFileURI(f.getAbsolutePath()));
r.load(null);
RegisterMeta.registerPackages(r);
ret = new EMFMetaModelResource(r, this);
return ret;
}
@Override
public Set<String> getMetaModelExtensions() {
return metamodelExtensions;
}
@Override
public String dumpPackageToString(IHawkPackage pkg) throws Exception {
final EMFPackage ePackage = (EMFPackage) pkg;
final EMFMetaModelResource eResource = (EMFMetaModelResource) ePackage.getResource();
final Resource oldResource = eResource.res;
// Separate the EPackage to be saved to its own resource
final Resource newResource = resourceSet
.createResource(URI.createURI("resource_from_epackage_" + ePackage.getNsURI()));
final EObject eob = ePackage.getEObject();
newResource.getContents().add(eob);
/*
* Separate the other EPackages that may reside in the old resource in
* the same way, so they all refer to each other using
* resource_from_epackage_...
*/
final List<EObject> otherContents = new ArrayList<>(oldResource.getContents());
final List<Resource> auxResources = new ArrayList<>();
for (EObject otherContent : otherContents) {
if (otherContent instanceof EPackage) {
final EPackage otherEPackage = (EPackage) otherContent;
final Resource auxResource = resourceSet
.createResource(URI.createURI("resource_from_epackage_" + otherEPackage.getNsURI()));
auxResources.add(auxResource);
auxResource.getContents().add(otherEPackage);
}
}
assert oldResource.getContents().isEmpty() : "The old resource should be empty before the dump";
final ByteArrayOutputStream bOS = new ByteArrayOutputStream();
try {
newResource.save(bOS, null);
final String contents = new String(bOS.toByteArray());
return contents;
} finally {
/*
* Move back all EPackages into the original resource, to avoid
* inconsistencies across restarts.
*/
oldResource.getContents().add(eob);
oldResource.getContents().addAll(otherContents);
/*
* Unload and remove all the auxiliary resources we've created
* during the dumping.
*/
assert newResource.getContents().isEmpty() : "The new resource should be empty after the dump";
newResource.unload();
resourceSet.getResources().remove(newResource);
for (Resource auxResource : auxResources) {
assert auxResource.getContents().isEmpty() : "The aux resource should be empty after the dump";
auxResource.unload();
resourceSet.getResources().remove(auxResource);
}
}
}
@Override
public IHawkMetaModelResource parseFromString(String name, String contents) throws Exception {
if (name != null && contents != null) {
Resource r = resourceSet.createResource(URI.createURI(name));
InputStream input = new ByteArrayInputStream(contents.getBytes("UTF-8"));
r.load(input, null);
RegisterMeta.registerPackages(r);
return new EMFMetaModelResource(r, this);
} else
return null;
}
@Override
public void removeMetamodel(String property) {
boolean found = false;
Resource rem = null;
for (Resource r : resourceSet.getResources())
if (r.getURI().toString().contains(property)) {
rem = r;
found = true;
break;
}
if (found)
try {
rem.delete(null);
// EPackage.Registry.INSTANCE.remove(property);
} catch (Exception e) {
e.printStackTrace();
}
System.err.println(found ? "removed: " + property : property + " not present in this EMF parser");
}
@Override
public boolean canParse(File f) {
String[] split = f.getPath().split("\\.");
String extension = split[split.length - 1];
return getMetaModelExtensions().contains(extension);
}
@Override
public Set<IHawkMetaModelResource> getStaticMetamodels() {
return Collections.emptySet();
}
}
|
package org.batfish.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.batfish.collections.AdvertisementSet;
import org.batfish.collections.EdgeSet;
import org.batfish.collections.FibMap;
import org.batfish.collections.FibRow;
import org.batfish.collections.FibSet;
import org.batfish.collections.InterfaceSet;
import org.batfish.collections.FunctionSet;
import org.batfish.collections.IbgpTopology;
import org.batfish.collections.IpEdge;
import org.batfish.collections.MultiSet;
import org.batfish.collections.NodeInterfacePair;
import org.batfish.collections.NodeRoleMap;
import org.batfish.collections.NodeSet;
import org.batfish.collections.PolicyRouteFibIpMap;
import org.batfish.collections.PolicyRouteFibNodeMap;
import org.batfish.collections.PredicateSemantics;
import org.batfish.collections.PredicateValueTypeMap;
import org.batfish.collections.QualifiedNameMap;
import org.batfish.collections.RoleNodeMap;
import org.batfish.collections.RoleSet;
import org.batfish.collections.RouteSet;
import org.batfish.collections.TreeMultiSet;
import org.batfish.common.BatfishLogger;
import org.batfish.common.BfConsts;
import org.batfish.common.BatfishException;
import org.batfish.common.CleanBatfishException;
import org.batfish.grammar.BatfishCombinedParser;
import org.batfish.grammar.ParseTreePrettyPrinter;
import org.batfish.grammar.juniper.JuniperCombinedParser;
import org.batfish.grammar.juniper.JuniperFlattener;
import org.batfish.grammar.logicblox.LogQLPredicateInfoExtractor;
import org.batfish.grammar.logicblox.LogiQLCombinedParser;
import org.batfish.grammar.logicblox.LogiQLPredicateInfoResolver;
import org.batfish.grammar.question.QuestionCombinedParser;
import org.batfish.grammar.question.QuestionExtractor;
import org.batfish.grammar.topology.BatfishTopologyCombinedParser;
import org.batfish.grammar.topology.BatfishTopologyExtractor;
import org.batfish.grammar.topology.GNS3TopologyCombinedParser;
import org.batfish.grammar.topology.GNS3TopologyExtractor;
import org.batfish.grammar.topology.RoleCombinedParser;
import org.batfish.grammar.topology.RoleExtractor;
import org.batfish.grammar.topology.TopologyExtractor;
import org.batfish.grammar.z3.ConcretizerQueryResultCombinedParser;
import org.batfish.grammar.z3.ConcretizerQueryResultExtractor;
import org.batfish.grammar.z3.DatalogQueryResultCombinedParser;
import org.batfish.grammar.z3.DatalogQueryResultExtractor;
import org.batfish.job.BatfishJobExecutor;
import org.batfish.job.ConvertConfigurationJob;
import org.batfish.job.ConvertConfigurationResult;
import org.batfish.job.FlattenVendorConfigurationJob;
import org.batfish.job.FlattenVendorConfigurationResult;
import org.batfish.job.ParseVendorConfigurationJob;
import org.batfish.job.ParseVendorConfigurationResult;
import org.batfish.logic.LogicResourceLocator;
import org.batfish.logicblox.Block;
import org.batfish.logicblox.ConfigurationFactExtractor;
import org.batfish.logicblox.Facts;
import org.batfish.logicblox.LBValueType;
import org.batfish.logicblox.LogicBloxFrontend;
import org.batfish.logicblox.LogicBloxFrontendManager;
import org.batfish.logicblox.PredicateInfo;
import org.batfish.logicblox.ProjectFile;
import org.batfish.logicblox.QueryException;
import org.batfish.logicblox.TopologyFactExtractor;
import org.batfish.main.Settings.EnvironmentSettings;
import org.batfish.question.DestinationQuestion;
import org.batfish.question.FailureQuestion;
import org.batfish.question.IngressPathQuestion;
import org.batfish.question.LocalPathQuestion;
import org.batfish.question.MultipathQuestion;
import org.batfish.question.Question;
import org.batfish.question.TracerouteQuestion;
import org.batfish.question.VerifyProgram;
import org.batfish.question.VerifyQuestion;
import org.batfish.representation.AsPath;
import org.batfish.representation.AsSet;
import org.batfish.representation.BgpAdvertisement;
import org.batfish.representation.BgpNeighbor;
import org.batfish.representation.BgpProcess;
import org.batfish.representation.Configuration;
import org.batfish.representation.DataPlane;
import org.batfish.representation.Edge;
import org.batfish.representation.Flow;
import org.batfish.representation.FlowHistory;
import org.batfish.representation.FlowTrace;
import org.batfish.representation.Interface;
import org.batfish.representation.Ip;
import org.batfish.representation.IpProtocol;
import org.batfish.representation.LineAction;
import org.batfish.representation.OspfArea;
import org.batfish.representation.OspfProcess;
import org.batfish.representation.PolicyMap;
import org.batfish.representation.PolicyMapAction;
import org.batfish.representation.PolicyMapClause;
import org.batfish.representation.PolicyMapMatchRouteFilterListLine;
import org.batfish.representation.PrecomputedRoute;
import org.batfish.representation.Prefix;
import org.batfish.representation.RouteFilterLine;
import org.batfish.representation.RouteFilterList;
import org.batfish.representation.Topology;
import org.batfish.representation.VendorConfiguration;
import org.batfish.representation.cisco.CiscoVendorConfiguration;
import org.batfish.util.StringFilter;
import org.batfish.util.SubRange;
import org.batfish.util.UrlZipExplorer;
import org.batfish.util.Util;
import org.batfish.z3.BlacklistDstIpQuerySynthesizer;
import org.batfish.z3.CompositeNodJob;
import org.batfish.z3.ConcretizerQuery;
import org.batfish.z3.DropQuerySynthesizer;
import org.batfish.z3.MultipathInconsistencyQuerySynthesizer;
import org.batfish.z3.NodJob;
import org.batfish.z3.NodJobResult;
import org.batfish.z3.QuerySynthesizer;
import org.batfish.z3.ReachEdgeQuerySynthesizer;
import org.batfish.z3.ReachableQuerySynthesizer;
import org.batfish.z3.RoleReachabilityQuerySynthesizer;
import org.batfish.z3.RoleTransitQuerySynthesizer;
import org.batfish.z3.Synthesizer;
import com.logicblox.bloxweb.client.ServiceClientException;
import com.logicblox.connect.Workspace.Relation;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* This class encapsulates the main control logic for Batfish.
*/
public class Batfish implements AutoCloseable {
/**
* Name of the LogiQL executable block containing basic facts that are true
* for any network
*/
private static final String BASIC_FACTS_BLOCKNAME = "BaseFacts";
private static final String BGP_ADVERTISEMENT_ROUTE_PREDICATE_NAME = "BgpAdvertisementRoute";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for policy-routing
*/
private static final String FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME = "FibForwardPolicyRouteNextHopIp";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for destination-based routing
*/
private static final String FIB_PREDICATE_NAME = "FibNetwork";
private static final String FLOW_HISTORY_PREDICATE_NAME = "FlowPathHistory";
/**
* Name of the LogiQL predicate containing flow-sink interface tags
*/
private static final String FLOW_SINK_PREDICATE_NAME = "SetFlowSinkInterface";
private static final String GEN_OSPF_STARTING_IP = "10.0.0.0";
private static final String IBGP_NEIGHBORS_PREDICATE_NAME = "IbgpNeighbors";
private static final String INSTALLED_ROUTE_PREDICATE_NAME = "InstalledRoute";
/**
* A byte-array containing the first 4 bytes comprising the header for a file
* that is the output of java serialization
*/
private static final byte[] JAVA_SERIALIZED_OBJECT_HEADER = { (byte) 0xac,
(byte) 0xed, (byte) 0x00, (byte) 0x05 };
/**
* The name of the LogiQL library for org.batfish
*/
private static final String LB_BATFISH_LIBRARY_NAME = "libbatfish";
private static final String NETWORKS_PREDICATE_NAME = "SetNetwork";
private static final String PRECOMPUTED_BGP_ADVERTISEMENT_AS_PATH_LENGTH_PREDICATE_NAME = "SetBgpAdvertisementPathSize";
private static final String PRECOMPUTED_BGP_ADVERTISEMENT_AS_PATH_PREDICATE_NAME = "SetBgpAdvertisementPath";
private static final String PRECOMPUTED_BGP_ADVERTISEMENT_COMMUNITY_PREDICATE_NAME = "SetBgpAdvertisementCommunity";
private static final String PRECOMPUTED_BGP_ADVERTISEMENTS_PREDICATE_NAME = "SetBgpAdvertisement_flat";
private static final String PRECOMPUTED_IBGP_NEIGHBORS_PREDICATE_NAME = "SetIbgpNeighbors";
private static final String PRECOMPUTED_ROUTES_PREDICATE_NAME = "SetPrecomputedRoute_flat";
/**
* The name of the file in which LogiQL predicate type-information and
* documentation is serialized
*/
private static final String PREDICATE_INFO_FILENAME = "predicateInfo.object";
/**
* A string containing the system-specific path separator character
*/
private static final String SEPARATOR = System.getProperty("file.separator");
/**
* Role name for generated stubs
*/
private static final String STUB_ROLE = "generated_stubs";
/**
* The name of the [optional] topology file within a test-rig
*/
private static final String TOPOLOGY_FILENAME = "topology.net";
private static final String TRACE_PREFIX = "trace:";
public static String flatten(String input, BatfishLogger logger,
Settings settings) {
JuniperCombinedParser jparser = new JuniperCombinedParser(input,
settings.getThrowOnParserError(), settings.getThrowOnLexerError());
ParserRuleContext jtree = parse(jparser, logger, settings);
JuniperFlattener flattener = new JuniperFlattener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(flattener, jtree);
return flattener.getFlattenedConfigurationText();
}
private static void initControlPlaneFactBins(
Map<String, StringBuilder> factBins, boolean addHeaders) {
initFactBins(Facts.CONTROL_PLANE_FACT_COLUMN_HEADERS, factBins,
addHeaders);
}
private static void initFactBins(Map<String, String> columnHeaderMap,
Map<String, StringBuilder> factBins, boolean addHeaders) {
for (String factPredicate : columnHeaderMap.keySet()) {
if (addHeaders) {
String columnHeaders = columnHeaderMap.get(factPredicate);
String initialText = columnHeaders + "\n";
factBins.put(factPredicate, new StringBuilder(initialText));
}
else {
factBins.put(factPredicate, new StringBuilder());
}
}
}
private static void initTrafficFactBins(Map<String, StringBuilder> factBins) {
initFactBins(Facts.TRAFFIC_FACT_COLUMN_HEADERS, factBins, true);
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
BatfishLogger logger, Settings settings) {
ParserRuleContext tree;
try {
tree = parser.parse();
}
catch (BatfishException e) {
throw new ParserBatfishException("Parser error", e);
}
List<String> errors = parser.getErrors();
int numErrors = errors.size();
if (numErrors > 0) {
logger.error(numErrors + " ERROR(S)\n");
for (int i = 0; i < numErrors; i++) {
String prefix = "ERROR " + (i + 1) + ": ";
String msg = errors.get(i);
String prefixedMsg = Util.applyPrefix(prefix, msg);
logger.error(prefixedMsg + "\n");
}
throw new ParserBatfishException("Parser error(s)");
}
else if (!settings.printParseTree()) {
logger.info("OK\n");
}
else {
logger.info("OK, PRINTING PARSE TREE:\n");
logger.info(ParseTreePrettyPrinter.print(tree, parser) + "\n\n");
}
return tree;
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename, BatfishLogger logger, Settings settings) {
logger.info("Parsing: \"" + filename + "\" ...");
return parse(parser, logger, settings);
}
private EnvironmentSettings _baseEnvSettings;
private EnvironmentSettings _diffEnvSettings;
private EnvironmentSettings _envSettings;
private BatfishLogger _logger;
private LogicBloxFrontendManager _manager;
private PredicateInfo _predicateInfo;
private Settings _settings;
private long _timerCount;
private File _tmpLogicDir;
public Batfish(Settings settings) {
_settings = settings;
_envSettings = settings.getActiveEnvironmentSettings();
_baseEnvSettings = settings.getBaseEnvironmentSettings();
_diffEnvSettings = settings.getDiffEnvironmentSettings();
_logger = _settings.getLogger();
_manager = new LogicBloxFrontendManager(settings, _logger, _envSettings);
_tmpLogicDir = null;
}
private void addProject() {
LogicBloxFrontend lbFrontend = _manager.connect();
_logger.info("\n*** ADDING PROJECT ***\n");
resetTimer();
String settingsLogicDir = _settings.getLogicDir();
File logicDir;
if (settingsLogicDir != null) {
logicDir = new ProjectFile(settingsLogicDir);
}
else {
logicDir = retrieveLogicDir().getAbsoluteFile();
}
String result = lbFrontend.addProject(logicDir, "");
cleanupLogicDir();
if (result != null) {
throw new BatfishException(result + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void addStaticFacts(String blockName) {
LogicBloxFrontend lbFrontend = _manager.connect();
_logger.info("\n*** ADDING STATIC FACTS ***\n");
resetTimer();
_logger.info("Adding " + blockName + "....");
String output = lbFrontend.execNamedBlock(LB_BATFISH_LIBRARY_NAME + ":"
+ blockName);
if (output == null) {
_logger.info("OK\n");
}
else {
throw new BatfishException(output + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void anonymizeConfigurations() {
// TODO Auto-generated method stub
}
private void answer(String questionPath) {
boolean dp = false;
boolean diff = false;
Question question = parseQuestion(questionPath);
switch (question.getType()) {
case DESTINATION:
answerDestination((DestinationQuestion) question);
dp = true;
diff = true;
break;
case FAILURE:
answerFailure((FailureQuestion) question);
dp = true;
diff = true;
break;
case INGRESS_PATH:
answerIngressPath((IngressPathQuestion) question);
dp = true;
diff = true;
break;
case LOCAL_PATH:
answerLocalPath((LocalPathQuestion) question);
dp = true;
diff = true;
break;
case MULTIPATH:
answerMultipath((MultipathQuestion) question);
dp = true;
break;
case TRACEROUTE:
answerTraceroute((TracerouteQuestion) question);
dp = true;
break;
case VERIFY:
answerVerify((VerifyQuestion) question);
break;
default:
throw new BatfishException("Unknown question type");
}
if (diff) {
_settings.setPostFlows(false);
_settings.setHistory(false);
}
else {
_settings.setPostDifferentialFlows(false);
_settings.setDifferentialHistory(false);
}
if (!dp) {
_settings.setPostDifferentialFlows(false);
_settings.setDifferentialHistory(false);
_settings.setPostFlows(false);
_settings.setHistory(false);
}
}
private void answerDestination(DestinationQuestion question) {
checkDifferentialDataPlaneQuestionDependencies();
throw new UnsupportedOperationException(
"no implementation for generated method"); // TODO Auto-generated
// method stub
}
private void answerFailure(FailureQuestion question) {
checkDifferentialDataPlaneQuestionDependencies();
String tag = getDifferentialFlowTag();
_baseEnvSettings
.setDumpFactsDir(_baseEnvSettings.getTrafficFactDumpDir());
_diffEnvSettings
.setDumpFactsDir(_diffEnvSettings.getTrafficFactDumpDir());
// load base configurations and generate base data plane
Map<String, Configuration> baseConfigurations = loadConfigurations(_baseEnvSettings);
File baseDataPlanePath = new File(_baseEnvSettings.getDataPlanePath());
Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane(
baseConfigurations, baseDataPlanePath);
// load diff configurations and generate diff data plane
Map<String, Configuration> diffConfigurations = loadConfigurations(_diffEnvSettings);
File diffDataPlanePath = new File(_diffEnvSettings.getDataPlanePath());
Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane(
diffConfigurations, diffDataPlanePath);
Set<String> commonNodes = new TreeSet<String>();
commonNodes.addAll(baseConfigurations.keySet());
commonNodes.retainAll(diffConfigurations.keySet());
NodeSet blacklistNodes = getNodeBlacklist(_diffEnvSettings);
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(_diffEnvSettings);
EdgeSet blacklistEdges = getEdgeBlacklist(_diffEnvSettings);
BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer(
null, blacklistNodes, blacklistInterfaces, blacklistEdges,
baseConfigurations);
// compute composite program and flows
List<Synthesizer> synthesizers = new ArrayList<Synthesizer>();
synthesizers.add(baseDataPlaneSynthesizer);
synthesizers.add(diffDataPlaneSynthesizer);
synthesizers.add(baseDataPlaneSynthesizer);
List<CompositeNodJob> jobs = new ArrayList<CompositeNodJob>();
// generate base reachability and diff blackhole and blacklist queries
for (String node : commonNodes) {
ReachableQuerySynthesizer reachableQuery = new ReachableQuerySynthesizer(
node, null);
ReachableQuerySynthesizer blackHoleQuery = new ReachableQuerySynthesizer(
node, null);
blackHoleQuery.setNegate(true);
NodeSet nodes = new NodeSet();
nodes.add(node);
List<QuerySynthesizer> queries = new ArrayList<QuerySynthesizer>();
queries.add(reachableQuery);
queries.add(blackHoleQuery);
queries.add(blacklistQuery);
CompositeNodJob job = new CompositeNodJob(synthesizers, queries,
nodes, tag);
jobs.add(job);
}
Set<Flow> flows = computeCompositeNodOutput(jobs);
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (Flow flow : flows) {
wSetFlowOriginate.append(flow.toLBLine());
_logger.output(flow.toString() + "\n");
}
dumpFacts(trafficFactBins, _baseEnvSettings);
dumpFacts(trafficFactBins, _diffEnvSettings);
}
private void answerIngressPath(IngressPathQuestion question) {
checkDifferentialDataPlaneQuestionDependencies();
throw new UnsupportedOperationException(
"no implementation for generated method"); // TODO Auto-generated
// method stub
}
private void answerLocalPath(LocalPathQuestion question) {
checkDifferentialDataPlaneQuestionDependencies();
String tag = getDifferentialFlowTag();
_baseEnvSettings
.setDumpFactsDir(_baseEnvSettings.getTrafficFactDumpDir());
_diffEnvSettings
.setDumpFactsDir(_diffEnvSettings.getTrafficFactDumpDir());
// load base configurations and generate base data plane
Map<String, Configuration> baseConfigurations = loadConfigurations(_baseEnvSettings);
File baseDataPlanePath = new File(_baseEnvSettings.getDataPlanePath());
Synthesizer baseDataPlaneSynthesizer = synthesizeDataPlane(
baseConfigurations, baseDataPlanePath);
// load diff configurations and generate diff data plane
Map<String, Configuration> diffConfigurations = loadConfigurations(_diffEnvSettings);
File diffDataPlanePath = new File(_diffEnvSettings.getDataPlanePath());
Synthesizer diffDataPlaneSynthesizer = synthesizeDataPlane(
diffConfigurations, diffDataPlanePath);
Set<String> commonNodes = new TreeSet<String>();
commonNodes.addAll(baseConfigurations.keySet());
commonNodes.retainAll(diffConfigurations.keySet());
NodeSet blacklistNodes = getNodeBlacklist(_diffEnvSettings);
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(_diffEnvSettings);
EdgeSet blacklistEdges = getEdgeBlacklist(_diffEnvSettings);
BlacklistDstIpQuerySynthesizer blacklistQuery = new BlacklistDstIpQuerySynthesizer(
null, blacklistNodes, blacklistInterfaces, blacklistEdges,
baseConfigurations);
// compute composite program and flows
List<Synthesizer> commonEdgeSynthesizers = new ArrayList<Synthesizer>();
commonEdgeSynthesizers.add(baseDataPlaneSynthesizer);
commonEdgeSynthesizers.add(diffDataPlaneSynthesizer);
commonEdgeSynthesizers.add(baseDataPlaneSynthesizer);
List<CompositeNodJob> jobs = new ArrayList<CompositeNodJob>();
// generate local edge reachability and black hole queries
Topology diffTopology = loadTopology(_diffEnvSettings);
EdgeSet diffEdges = diffTopology.getEdges();
for (Edge edge : diffEdges) {
String ingressNode = edge.getNode1();
ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, edge, true);
ReachEdgeQuerySynthesizer noReachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, edge, false);
noReachQuery.setNegate(true);
List<QuerySynthesizer> queries = new ArrayList<QuerySynthesizer>();
queries.add(reachQuery);
queries.add(noReachQuery);
queries.add(blacklistQuery);
NodeSet nodes = new NodeSet();
nodes.add(ingressNode);
CompositeNodJob job = new CompositeNodJob(commonEdgeSynthesizers,
queries, nodes, tag);
jobs.add(job);
}
// we also need queries for nodes next to edges that are now missing, in
// the case that those nodes still exist
List<Synthesizer> missingEdgeSynthesizers = new ArrayList<Synthesizer>();
missingEdgeSynthesizers.add(baseDataPlaneSynthesizer);
missingEdgeSynthesizers.add(baseDataPlaneSynthesizer);
Topology baseTopology = loadTopology(_baseEnvSettings);
EdgeSet baseEdges = baseTopology.getEdges();
EdgeSet missingEdges = new EdgeSet();
missingEdges.addAll(baseEdges);
missingEdges.removeAll(diffEdges);
for (Edge missingEdge : missingEdges) {
String ingressNode = missingEdge.getNode1();
if (diffConfigurations.containsKey(ingressNode)) {
ReachEdgeQuerySynthesizer reachQuery = new ReachEdgeQuerySynthesizer(
ingressNode, missingEdge, true);
List<QuerySynthesizer> queries = new ArrayList<QuerySynthesizer>();
queries.add(reachQuery);
queries.add(blacklistQuery);
NodeSet nodes = new NodeSet();
nodes.add(ingressNode);
CompositeNodJob job = new CompositeNodJob(missingEdgeSynthesizers,
queries, nodes, tag);
jobs.add(job);
}
}
Set<Flow> flows = computeCompositeNodOutput(jobs);
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (Flow flow : flows) {
wSetFlowOriginate.append(flow.toLBLine());
_logger.output(flow.toString() + "\n");
}
dumpFacts(trafficFactBins, _baseEnvSettings);
dumpFacts(trafficFactBins, _diffEnvSettings);
}
private void answerMultipath(MultipathQuestion question) {
checkDataPlaneQuestionDependencies();
String tag = getFlowTag();
_envSettings.setDumpFactsDir(_envSettings.getTrafficFactDumpDir());
Map<String, Configuration> configurations = loadConfigurations();
File dataPlanePath = new File(_envSettings.getDataPlanePath());
Set<Flow> flows = null;
Synthesizer dataPlaneSynthesizer = synthesizeDataPlane(configurations,
dataPlanePath);
List<NodJob> jobs = new ArrayList<NodJob>();
for (String node : configurations.keySet()) {
MultipathInconsistencyQuerySynthesizer query = new MultipathInconsistencyQuerySynthesizer(
node);
NodeSet nodes = new NodeSet();
nodes.add(node);
NodJob job = new NodJob(dataPlaneSynthesizer, query, nodes, tag);
jobs.add(job);
}
flows = computeNodOutput(jobs);
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (Flow flow : flows) {
wSetFlowOriginate.append(flow.toLBLine());
}
dumpFacts(trafficFactBins);
}
private void answerTraceroute(TracerouteQuestion question) {
checkDataPlaneQuestionDependencies();
_envSettings.setDumpFactsDir(_envSettings.getTrafficFactDumpDir());
Set<Flow> flows = question.getFlows();
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (Flow flow : flows) {
wSetFlowOriginate.append(flow.toLBLine());
}
dumpFacts(trafficFactBins);
}
private void answerVerify(VerifyQuestion question) {
checkConfigurations();
Map<String, Configuration> configurations = loadConfigurations();
VerifyProgram program = question.getProgram();
program.execute(configurations, _logger, _settings);
if (program.getAssertions()) {
int totalAssertions = program.getTotalAssertions();
int failedAssertions = program.getFailedAssertions();
int passedAssertions = totalAssertions - failedAssertions;
double percentPassed = 100 * ((double) passedAssertions)
/ totalAssertions;
_logger.outputf("%d/%d (%.1f%%) assertions passed.\n",
passedAssertions, totalAssertions, percentPassed);
if (!program.getUnsafe()) {
_logger.output("No violations detected\n");
}
}
}
/**
* This function extracts predicate type information from the logic files. It
* is meant only to be called during the build process, and should never be
* executed from a jar
*/
private void buildPredicateInfo() {
Path logicBinDirPath = null;
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
if (logicSourceString.startsWith("onejar:")) {
throw new BatfishException(
"buildPredicateInfo() should never be called from within a jar");
}
String logicPackageResourceName = LogicResourceLocator.class.getPackage()
.getName().replace('.', SEPARATOR.charAt(0));
try {
logicBinDirPath = Paths.get(LogicResourceLocator.class
.getClassLoader().getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic output directory",
e);
}
Path logicSrcDirPath = Paths.get(_settings.getLogicSrcDir());
final Set<Path> logicFiles = new TreeSet<Path>();
try {
Files.walkFileTree(logicSrcDirPath,
new java.nio.file.SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
String name = file.getFileName().toString();
if (!name.equals("BaseFacts.logic")
&& !name.equals("pedantic.logic")
&& !name.endsWith("_rules.logic")
&& !name.startsWith("service_")
&& name.endsWith(".logic")) {
logicFiles.add(file);
}
return super.visitFile(file, attrs);
}
});
}
catch (IOException e) {
throw new BatfishException("Could not make list of logic files", e);
}
PredicateValueTypeMap predicateValueTypes = new PredicateValueTypeMap();
QualifiedNameMap qualifiedNameMap = new QualifiedNameMap();
FunctionSet functions = new FunctionSet();
PredicateSemantics predicateSemantics = new PredicateSemantics();
List<ParserRuleContext> trees = new ArrayList<ParserRuleContext>();
for (Path logicFilePath : logicFiles) {
String input = Util.readFile(logicFilePath.toFile());
LogiQLCombinedParser parser = new LogiQLCombinedParser(input,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, logicFilePath.toString());
trees.add(tree);
}
ParseTreeWalker walker = new ParseTreeWalker();
for (ParserRuleContext tree : trees) {
LogQLPredicateInfoExtractor extractor = new LogQLPredicateInfoExtractor(
predicateValueTypes);
walker.walk(extractor, tree);
}
for (ParserRuleContext tree : trees) {
LogiQLPredicateInfoResolver resolver = new LogiQLPredicateInfoResolver(
predicateValueTypes, qualifiedNameMap, functions,
predicateSemantics);
walker.walk(resolver, tree);
}
PredicateInfo predicateInfo = new PredicateInfo(predicateSemantics,
predicateValueTypes, functions, qualifiedNameMap);
File predicateInfoFile = logicBinDirPath.resolve(PREDICATE_INFO_FILENAME)
.toFile();
serializeObject(predicateInfo, predicateInfoFile);
}
private void checkConfigurations() {
String serializedConfigPath = _settings.getSerializeIndependentPath();
File dir = new File(serializedConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new CleanBatfishException(
"Missing compiled vendor-independent configurations for this test-rig\n");
}
else if (serializedConfigs.length == 0) {
throw new CleanBatfishException(
"Nothing to do: Set of vendor-independent configurations for this test-rig is empty\n");
}
}
private void checkDataPlane(EnvironmentSettings envSettings) {
String dpPath = _envSettings.getDataPlanePath();
File dp = new File(dpPath);
if (!dp.exists()) {
throw new CleanBatfishException(
"Missing data plane for this test-rig\n");
}
}
private void checkDataPlaneQuestionDependencies() {
checkDataPlaneQuestionDependencies(_envSettings);
}
private void checkDataPlaneQuestionDependencies(
EnvironmentSettings envSettings) {
checkConfigurations();
checkDataPlane(envSettings);
}
private void checkDifferentialDataPlaneQuestionDependencies() {
checkConfigurations();
checkDataPlane(_baseEnvSettings);
checkDataPlane(_diffEnvSettings);
}
private void cleanupLogicDir() {
if (_tmpLogicDir != null) {
try {
FileUtils.deleteDirectory(_tmpLogicDir);
}
catch (IOException e) {
throw new BatfishException(
"Error cleaning up temporary logic directory", e);
}
_tmpLogicDir = null;
}
}
@Override
public void close() throws Exception {
if (_manager != null) {
_manager.close();
}
}
private Set<Flow> computeCompositeNodOutput(List<CompositeNodJob> jobs) {
_logger.info("\n*** EXECUTING COMPOSITE NOD JOBS ***\n");
resetTimer();
Set<Flow> flows = new TreeSet<Flow>();
BatfishJobExecutor<CompositeNodJob, NodJobResult, Set<Flow>> executor = new BatfishJobExecutor<CompositeNodJob, NodJobResult, Set<Flow>>(
_settings, _logger);
executor.executeJobs(jobs, flows);
printElapsedTime();
return flows;
}
private void computeControlPlaneFacts(Map<String, StringBuilder> cpFactBins) {
if (_settings.getUsePrecomputedRoutes()) {
Set<String> precomputedRoutesPaths = _settings
.getPrecomputedRoutesPaths();
String precomputedRoutesPath = _settings.getPrecomputedRoutesPath();
if (precomputedRoutesPaths == null) {
if (precomputedRoutesPath == null) {
throw new BatfishException(
"Must specify path(s) to precomputed routes");
}
else {
precomputedRoutesPaths = Collections
.singleton(precomputedRoutesPath);
}
}
populatePrecomputedRoutes(precomputedRoutesPaths, cpFactBins);
}
if (_settings.getUsePrecomputedIbgpNeighbors()) {
populatePrecomputedIbgpNeighbors(
_settings.getPrecomputedIbgpNeighborsPath(), cpFactBins);
}
if (_settings.getUsePrecomputedBgpAdvertisements()) {
populatePrecomputedBgpAdvertisements(
_settings.getPrecomputedBgpAdvertisementsPath(), cpFactBins);
}
Map<String, Configuration> configurations = loadConfigurations();
Topology topology = computeTopology(_settings.getTestRigPath(),
configurations, cpFactBins);
String edgeBlacklistPath = _envSettings.getEdgeBlacklistPath();
String serializedTopologyPath = _envSettings.getSerializedTopologyPath();
InterfaceSet flowSinks = null;
boolean differentialContext = _diffEnvSettings.getName() != null;
if (differentialContext) {
flowSinks = getFlowSinkSet(_baseEnvSettings.getDataPlanePath());
}
EdgeSet blacklistEdges = getEdgeBlacklist(_envSettings);
if (edgeBlacklistPath != null) {
File edgeBlacklistPathAsFile = new File(edgeBlacklistPath);
if (edgeBlacklistPathAsFile.exists()) {
EdgeSet edges = topology.getEdges();
edges.removeAll(blacklistEdges);
}
}
NodeSet blacklistNodes = getNodeBlacklist(_envSettings);
if (blacklistNodes != null) {
if (differentialContext) {
flowSinks.removeNodes(blacklistNodes);
}
for (String blacklistNode : blacklistNodes) {
topology.removeNode(blacklistNode);
}
}
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(_envSettings);
if (blacklistInterfaces != null) {
for (NodeInterfacePair blacklistInterface : blacklistInterfaces) {
topology.removeInterface(blacklistInterface);
if (differentialContext) {
flowSinks.remove(blacklistInterface);
}
}
}
if (!differentialContext) {
flowSinks = computeFlowSinks(configurations, topology);
}
writeTopologyFacts(topology, cpFactBins);
writeConfigurationFacts(configurations, cpFactBins);
writeFlowSinkFacts(flowSinks, cpFactBins);
if (!_logger.isActive(BatfishLogger.LEVEL_INFO)) {
_logger.output("LogicBlox facts generated successfully.\n");
}
if (_settings.getDumpControlPlaneFacts()) {
dumpFacts(cpFactBins);
}
if (_settings.getFacts()) {
// serialize topology
File topologyPath = new File(serializedTopologyPath);
_logger.info("Serializing topology...");
serializeObject(topology, topologyPath);
_logger.info("OK\n");
}
}
private void computeDataPlane() {
String dataPlanePath = _envSettings.getDataPlanePath();
if (dataPlanePath == null) {
throw new BatfishException("Missing path to data plane");
}
File dataPlanePathAsFile = new File(dataPlanePath);
computeDataPlane(dataPlanePathAsFile);
}
private void computeDataPlane(File dataPlanePath) {
LogicBloxFrontend lbFrontend = _manager.connect();
_logger.info("\n*** COMPUTING DATA PLANE STRUCTURES ***\n");
resetTimer();
lbFrontend.initEntityTable();
_logger.info("Retrieving flow sink information from LogicBlox...");
InterfaceSet flowSinks = getFlowSinkSet(lbFrontend);
_logger.info("OK\n");
Topology topology = loadTopology();
EdgeSet topologyEdges = topology.getEdges();
String fibQualifiedName = _predicateInfo.getPredicateNames().get(
FIB_PREDICATE_NAME);
_logger
.info("Retrieving destination-routing FIB information from LogicBlox...");
Relation fibNetwork = lbFrontend.queryPredicate(fibQualifiedName);
_logger.info("OK\n");
String fibPolicyRouteNextHopQualifiedName = _predicateInfo
.getPredicateNames().get(FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME);
_logger
.info("Retrieving policy-routing FIB information from LogicBlox...");
Relation fibPolicyRouteNextHops = lbFrontend
.queryPredicate(fibPolicyRouteNextHopQualifiedName);
_logger.info("OK\n");
_logger.info("Caclulating forwarding rules...");
FibMap fibs = getRouteForwardingRules(fibNetwork, lbFrontend);
PolicyRouteFibNodeMap policyRouteFibNodeMap = getPolicyRouteFibNodeMap(
fibPolicyRouteNextHops, lbFrontend);
_logger.info("OK\n");
DataPlane dataPlane = new DataPlane(flowSinks, topologyEdges, fibs,
policyRouteFibNodeMap);
_logger.info("Serializing data plane...");
serializeObject(dataPlane, dataPlanePath);
_logger.info("OK\n");
printElapsedTime();
}
private InterfaceSet computeFlowSinks(
Map<String, Configuration> configurations, Topology topology) {
InterfaceSet flowSinks = new InterfaceSet();
InterfaceSet topologyInterfaces = new InterfaceSet();
for (Edge edge : topology.getEdges()) {
topologyInterfaces.add(edge.getInterface1());
topologyInterfaces.add(edge.getInterface2());
}
for (Configuration node : configurations.values()) {
String hostname = node.getHostname();
for (Interface iface : node.getInterfaces().values()) {
String ifaceName = iface.getName();
NodeInterfacePair p = new NodeInterfacePair(hostname, ifaceName);
if (iface.getActive() && !iface.isLoopback(node.getVendor())
&& !topologyInterfaces.contains(p)) {
flowSinks.add(p);
}
}
}
return flowSinks;
}
private Set<Flow> computeNodOutput(List<NodJob> jobs) {
_logger.info("\n*** EXECUTING NOD JOBS ***\n");
resetTimer();
Set<Flow> flows = new TreeSet<Flow>();
BatfishJobExecutor<NodJob, NodJobResult, Set<Flow>> executor = new BatfishJobExecutor<NodJob, NodJobResult, Set<Flow>>(
_settings, _logger);
executor.executeJobs(jobs, flows);
printElapsedTime();
return flows;
}
public Topology computeTopology(String testRigPath,
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
Path topologyFilePath = Paths.get(testRigPath, TOPOLOGY_FILENAME);
Topology topology;
// Get generated facts from topology file
if (Files.exists(topologyFilePath)) {
topology = processTopologyFile(topologyFilePath.toFile(), factBins);
}
else {
// guess adjacencies based on interface subnetworks
_logger
.info("*** (GUESSING TOPOLOGY IN ABSENCE OF EXPLICIT FILE) ***\n");
EdgeSet edges = synthesizeTopology(configurations);
topology = new Topology(edges);
}
return topology;
}
private void concretize() {
_logger.info("\n*** GENERATING Z3 CONCRETIZER QUERIES ***\n");
resetTimer();
String[] concInPaths = _settings.getConcretizerInputFilePaths();
String[] negConcInPaths = _settings.getNegatedConcretizerInputFilePaths();
List<ConcretizerQuery> concretizerQueries = new ArrayList<ConcretizerQuery>();
String blacklistDstIpPath = _settings.getBlacklistDstIpPath();
if (blacklistDstIpPath != null) {
String blacklistDstIpFileText = Util.readFile(new File(
blacklistDstIpPath));
String[] blacklistDstpIpStrs = blacklistDstIpFileText.split("\n");
Set<Ip> blacklistDstIps = new TreeSet<Ip>();
for (String blacklistDstIpStr : blacklistDstpIpStrs) {
Ip blacklistDstIp = new Ip(blacklistDstIpStr);
blacklistDstIps.add(blacklistDstIp);
}
if (blacklistDstIps.size() == 0) {
_logger.warn("Warning: empty set of blacklisted destination ips\n");
}
ConcretizerQuery blacklistIpQuery = ConcretizerQuery
.blacklistDstIpQuery(blacklistDstIps);
concretizerQueries.add(blacklistIpQuery);
}
for (String concInPath : concInPaths) {
_logger.info("Reading z3 datalog query output file: \"" + concInPath
+ "\" ...");
File queryOutputFile = new File(concInPath);
String queryOutputStr = Util.readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, concInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), false);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
if (negConcInPaths != null) {
for (String negConcInPath : negConcInPaths) {
_logger
.info("Reading z3 datalog query output file (to be negated): \""
+ negConcInPath + "\" ...");
File queryOutputFile = new File(negConcInPath);
String queryOutputStr = Util.readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, negConcInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), true);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
}
for (int i = 0; i < concretizerQueries.size(); i++) {
ConcretizerQuery cq = concretizerQueries.get(i);
String concQueryPath = _settings.getConcretizerOutputFilePath() + "-"
+ i + ".smt2";
_logger.info("Writing concretizer query file: \"" + concQueryPath
+ "\" ...");
writeFile(concQueryPath, cq.getText());
_logger.info("OK\n");
}
printElapsedTime();
}
private Map<String, Configuration> convertConfigurations(
Map<String, VendorConfiguration> vendorConfigurations) {
_logger
.info("\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n");
resetTimer();
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
List<ConvertConfigurationJob> jobs = new ArrayList<ConvertConfigurationJob>();
for (String hostname : vendorConfigurations.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
VendorConfiguration vc = vendorConfigurations.get(hostname);
ConvertConfigurationJob job = new ConvertConfigurationJob(_settings,
vc, hostname, warnings);
jobs.add(job);
}
BatfishJobExecutor<ConvertConfigurationJob, ConvertConfigurationResult, Map<String, Configuration>> executor = new BatfishJobExecutor<ConvertConfigurationJob, ConvertConfigurationResult, Map<String, Configuration>>(
_settings, _logger);
executor.executeJobs(jobs, configurations);
printElapsedTime();
return configurations;
}
private void createWorkspace() {
addProject();
String lbHostnamePath = _envSettings.getJobLogicBloxHostnamePath();
String lbHostname = _settings.getServiceLogicBloxHostname();
if (lbHostname == null) {
lbHostname = "localhost";
}
if (lbHostnamePath != null) {
writeFile(lbHostnamePath, lbHostname);
}
}
private void deleteWorkspace() {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.deleteWorkspace();
}
public Map<String, Configuration> deserializeConfigurations(
String serializedConfigPath) {
_logger
.info("\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
File dir = new File(serializedConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException(
"Error reading vendor-independent configs directory: \""
+ dir.toString() + "\"");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.debug("Reading config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
Configuration c = (Configuration) object;
configurations.put(name, c);
_logger.debug(" ...OK\n");
}
disableBlacklistedInterface(configurations);
disableBlacklistedNode(configurations);
printElapsedTime();
return configurations;
}
private Object deserializeObject(File inputFile) {
FileInputStream fis;
Object o = null;
ObjectInputStream ois;
try {
fis = new FileInputStream(inputFile);
if (!isJavaSerializationData(inputFile)) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
ois = xstream.createObjectInputStream(fis);
}
else {
ois = new ObjectInputStream(fis);
}
o = ois.readObject();
ois.close();
}
catch (IOException | ClassNotFoundException e) {
throw new BatfishException("Failed to deserialize object from file: "
+ inputFile.toString(), e);
}
return o;
}
public Map<String, VendorConfiguration> deserializeVendorConfigurations(
String serializedVendorConfigPath) {
_logger.info("\n*** DESERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
File dir = new File(serializedVendorConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException("Error reading vendor configs directory");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.info("Reading vendor config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
VendorConfiguration vc = (VendorConfiguration) object;
vendorConfigurations.put(name, vc);
_logger.info("...OK\n");
}
printElapsedTime();
return vendorConfigurations;
}
private void disableBlacklistedInterface(
Map<String, Configuration> configurations) {
String blacklistInterfaceString = _settings.getBlacklistInterfaceString();
if (blacklistInterfaceString != null) {
String[] blacklistInterfaceStringParts = blacklistInterfaceString
.split(",");
String blacklistInterfaceNode = blacklistInterfaceStringParts[0];
String blacklistInterfaceName = blacklistInterfaceStringParts[1];
Configuration c = configurations.get(blacklistInterfaceNode);
Interface i = c.getInterfaces().get(blacklistInterfaceName);
i.setActive(false);
}
}
private void disableBlacklistedNode(Map<String, Configuration> configurations) {
String blacklistNode = _settings.getBlacklistNode();
if (blacklistNode != null) {
if (!configurations.containsKey(blacklistNode)) {
throw new BatfishException("Cannot blacklist non-existent node: "
+ blacklistNode);
}
Configuration configuration = configurations.get(blacklistNode);
for (Interface iface : configuration.getInterfaces().values()) {
iface.setActive(false);
}
}
}
private void dumpFacts(Map<String, StringBuilder> factBins) {
dumpFacts(factBins, _envSettings);
}
private void dumpFacts(Map<String, StringBuilder> factBins,
EnvironmentSettings envSettings) {
_logger.info("\n*** DUMPING FACTS ***\n");
resetTimer();
Path factsDir = Paths.get(envSettings.getDumpFactsDir());
try {
Files.createDirectories(factsDir);
for (String factsFilename : factBins.keySet()) {
String facts = factBins.get(factsFilename).toString();
Path factsFilePath = factsDir.resolve(factsFilename);
_logger.info("Writing: \""
+ factsFilePath.toAbsolutePath().toString() + "\"\n");
FileUtils.write(factsFilePath.toFile(), facts);
}
}
catch (IOException e) {
throw new BatfishException("Failed to write fact dump file", e);
}
printElapsedTime();
}
private void dumpInterfaceDescriptions(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> configs = parseVendorConfigurations(configurationData);
Map<String, VendorConfiguration> sortedConfigs = new TreeMap<String, VendorConfiguration>();
sortedConfigs.putAll(configs);
StringBuilder sb = new StringBuilder();
for (VendorConfiguration vconfig : sortedConfigs.values()) {
String node = vconfig.getHostname();
CiscoVendorConfiguration config = null;
try {
config = (CiscoVendorConfiguration) vconfig;
}
catch (ClassCastException e) {
continue;
}
Map<String, org.batfish.representation.cisco.Interface> sortedInterfaces = new TreeMap<String, org.batfish.representation.cisco.Interface>();
sortedInterfaces.putAll(config.getInterfaces());
for (org.batfish.representation.cisco.Interface iface : sortedInterfaces
.values()) {
String iname = iface.getName();
String description = iface.getDescription();
sb.append(node + " " + iname);
if (description != null) {
sb.append(" \"" + description + "\"");
}
sb.append("\n");
}
}
String output = sb.toString();
writeFile(outputPath, output);
}
private void flatten(String inputPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(inputPath);
Map<File, String> outputConfigurationData = new TreeMap<File, String>();
File inputFolder = new File(inputPath);
File[] configs = inputFolder.listFiles();
if (configs == null) {
throw new BatfishException("Error reading configs from input test rig");
}
try {
Files.createDirectories(Paths.get(outputPath));
}
catch (IOException e) {
throw new BatfishException(
"Could not create output testrig directory", e);
}
_logger.info("\n*** FLATTENING TEST RIG ***\n");
resetTimer();
List<FlattenVendorConfigurationJob> jobs = new ArrayList<FlattenVendorConfigurationJob>();
for (File inputFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(inputFile);
String name = inputFile.getName();
File outputFile = Paths.get(outputPath,
BfConsts.RELPATH_CONFIGURATIONS_DIR, name).toFile();
FlattenVendorConfigurationJob job = new FlattenVendorConfigurationJob(
_settings, fileText, inputFile, outputFile, warnings);
jobs.add(job);
}
BatfishJobExecutor<FlattenVendorConfigurationJob, FlattenVendorConfigurationResult, Map<File, String>> executor = new BatfishJobExecutor<FlattenVendorConfigurationJob, FlattenVendorConfigurationResult, Map<File, String>>(
_settings, _logger);
executor.executeJobs(jobs, outputConfigurationData);
printElapsedTime();
for (Entry<File, String> e : outputConfigurationData.entrySet()) {
File outputFile = e.getKey();
String flatConfigText = e.getValue();
String outputFileAsString = outputFile.toString();
_logger.debug("Writing config to \"" + outputFileAsString + "\"...");
writeFile(outputFileAsString, flatConfigText);
_logger.debug("OK\n");
}
Path inputTopologyPath = Paths.get(inputPath, TOPOLOGY_FILENAME);
Path outputTopologyPath = Paths.get(outputPath, TOPOLOGY_FILENAME);
if (Files.isRegularFile(inputTopologyPath)) {
String topologyFileText = Util.readFile(inputTopologyPath.toFile());
writeFile(outputTopologyPath.toString(), topologyFileText);
}
}
private void genBlackHoleQueries() {
_logger.info("\n*** GENERATING BLACK-HOLE QUERIES ***\n");
resetTimer();
String fiQueryBasePath = _settings.getBlackHoleQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new DropQuerySynthesizer(hostname);
String queryText = synth.getQueryText();
String fiQueryPath;
fiQueryPath = fiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + fiQueryPath + "\"...");
writeFile(fiQueryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void generateOspfConfigs(String topologyPath, String outputPath) {
File topologyFilePath = new File(topologyPath);
Topology topology = parseTopology(topologyFilePath);
Map<String, Configuration> configs = new TreeMap<String, Configuration>();
NodeSet allNodes = new NodeSet();
Map<NodeInterfacePair, Set<NodeInterfacePair>> interfaceMap = new HashMap<NodeInterfacePair, Set<NodeInterfacePair>>();
// first we collect set of all mentioned nodes, and build mapping from
// each interface to the set of interfaces that connect to each other
for (Edge edge : topology.getEdges()) {
allNodes.add(edge.getNode1());
allNodes.add(edge.getNode2());
NodeInterfacePair interface1 = new NodeInterfacePair(edge.getNode1(),
edge.getInt1());
NodeInterfacePair interface2 = new NodeInterfacePair(edge.getNode2(),
edge.getInt2());
Set<NodeInterfacePair> interfaceSet = interfaceMap.get(interface1);
if (interfaceSet == null) {
interfaceSet = new HashSet<NodeInterfacePair>();
}
interfaceMap.put(interface1, interfaceSet);
interfaceMap.put(interface2, interfaceSet);
interfaceSet.add(interface1);
interfaceSet.add(interface2);
}
// then we create configs for every mentioned node
for (String hostname : allNodes) {
Configuration config = new Configuration(hostname);
configs.put(hostname, config);
}
// Now we create interfaces for each edge and record the number of
// neighbors so we know how large to make the subnet
long currentStartingIpAsLong = new Ip(GEN_OSPF_STARTING_IP).asLong();
Set<Set<NodeInterfacePair>> interfaceSets = new HashSet<Set<NodeInterfacePair>>();
interfaceSets.addAll(interfaceMap.values());
for (Set<NodeInterfacePair> interfaceSet : interfaceSets) {
int numInterfaces = interfaceSet.size();
if (numInterfaces < 2) {
throw new BatfishException(
"The following interface set contains less than two interfaces: "
+ interfaceSet.toString());
}
int numHostBits = 0;
for (int shiftedValue = numInterfaces - 1; shiftedValue != 0; shiftedValue >>= 1, numHostBits++) {
}
int subnetBits = 32 - numHostBits;
int offset = 0;
for (NodeInterfacePair currentPair : interfaceSet) {
Ip ip = new Ip(currentStartingIpAsLong + offset);
Prefix prefix = new Prefix(ip, subnetBits);
String ifaceName = currentPair.getInterface();
Interface iface = new Interface(ifaceName);
iface.setPrefix(prefix);
// dirty hack for setting bandwidth for now
double ciscoBandwidth = org.batfish.representation.cisco.Interface
.getDefaultBandwidth(ifaceName);
double juniperBandwidth = org.batfish.representation.juniper.Interface
.getDefaultBandwidthByName(ifaceName);
double bandwidth = Math.min(ciscoBandwidth, juniperBandwidth);
iface.setBandwidth(bandwidth);
String hostname = currentPair.getHostname();
Configuration config = configs.get(hostname);
config.getInterfaces().put(ifaceName, iface);
offset++;
}
currentStartingIpAsLong += (1 << numHostBits);
}
for (Configuration config : configs.values()) {
// use cisco arbitrarily
config.setVendor(ConfigurationFormat.CISCO);
OspfProcess proc = new OspfProcess();
config.setOspfProcess(proc);
proc.setReferenceBandwidth(org.batfish.representation.cisco.OspfProcess.DEFAULT_REFERENCE_BANDWIDTH);
long backboneArea = 0;
OspfArea area = new OspfArea(backboneArea);
proc.getAreas().put(backboneArea, area);
area.getInterfaces().addAll(config.getInterfaces().values());
}
serializeIndependentConfigs(configs, outputPath);
}
private void generateStubs(String inputRole, int stubAs,
String interfaceDescriptionRegex) {
Map<String, Configuration> configs = loadConfigurations();
Pattern pattern = Pattern.compile(interfaceDescriptionRegex);
Map<String, Configuration> stubConfigurations = new TreeMap<String, Configuration>();
_logger.info("\n*** GENERATING STUBS ***\n");
resetTimer();
// load old node-roles to be updated at end
RoleSet stubRoles = new RoleSet();
stubRoles.add(STUB_ROLE);
File nodeRolesPath = new File(_settings.getNodeRolesPath());
_logger.info("Deserializing old node-roles mappings: \"" + nodeRolesPath
+ "\" ...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(nodeRolesPath);
_logger.info("OK\n");
// create origination policy common to all stubs
String stubOriginationPolicyName = "~STUB_ORIGINATION_POLICY~";
PolicyMap stubOriginationPolicy = new PolicyMap(stubOriginationPolicyName);
PolicyMapClause clause = new PolicyMapClause();
stubOriginationPolicy.getClauses().add(clause);
String stubOriginationRouteFilterListName = "~STUB_ORIGINATION_ROUTE_FILTER~";
RouteFilterList rf = new RouteFilterList(
stubOriginationRouteFilterListName);
RouteFilterLine rfl = new RouteFilterLine(LineAction.ACCEPT, Prefix.ZERO,
new SubRange(0, 0));
rf.addLine(rfl);
PolicyMapMatchRouteFilterListLine matchLine = new PolicyMapMatchRouteFilterListLine(
Collections.singleton(rf));
clause.getMatchLines().add(matchLine);
clause.setAction(PolicyMapAction.PERMIT);
// create flow sink interface common to all stubs
String flowSinkName = "TenGibabitEthernet100/100";
Interface flowSink = new Interface(flowSinkName);
flowSink.setPrefix(Prefix.ZERO);
flowSink.setActive(true);
flowSink.setBandwidth(10E9d);
Set<String> skipWarningNodes = new HashSet<String>();
for (Configuration config : configs.values()) {
if (!config.getRoles().contains(inputRole)) {
continue;
}
for (BgpNeighbor neighbor : config.getBgpProcess().getNeighbors()
.values()) {
if (!neighbor.getRemoteAs().equals(stubAs)) {
continue;
}
Prefix neighborPrefix = neighbor.getPrefix();
if (neighborPrefix.getPrefixLength() != 32) {
throw new BatfishException(
"do not currently handle generating stubs based on dynamic bgp sessions");
}
Ip neighborAddress = neighborPrefix.getAddress();
int edgeAs = neighbor.getLocalAs();
/*
* Now that we have the ip address of the stub, we want to find the
* interface that connects to it. We will extract the hostname for
* the stub from the description of this interface using the
* supplied regex.
*/
boolean found = false;
for (Interface iface : config.getInterfaces().values()) {
Prefix prefix = iface.getPrefix();
if (prefix == null || !prefix.contains(neighborAddress)) {
continue;
}
// the neighbor address falls within the network assigned to this
// interface, so now we check the description
String description = iface.getDescription();
Matcher matcher = pattern.matcher(description);
if (matcher.find()) {
String hostname = matcher.group(1);
if (configs.containsKey(hostname)) {
Configuration duplicateConfig = configs.get(hostname);
if (!duplicateConfig.getRoles().contains(STUB_ROLE)
|| duplicateConfig.getRoles().size() != 1) {
throw new BatfishException(
"A non-generated node with hostname: \""
+ hostname
+ "\" already exists in network under analysis");
}
else {
if (!skipWarningNodes.contains(hostname)) {
_logger
.warn("WARNING: Overwriting previously generated node: \""
+ hostname + "\"\n");
skipWarningNodes.add(hostname);
}
}
}
found = true;
Configuration stub = stubConfigurations.get(hostname);
// create stub if it doesn't exist yet
if (stub == null) {
stub = new Configuration(hostname);
stubConfigurations.put(hostname, stub);
stub.getInterfaces().put(flowSinkName, flowSink);
stub.setBgpProcess(new BgpProcess());
stub.getPolicyMaps().put(stubOriginationPolicyName,
stubOriginationPolicy);
stub.getRouteFilterLists().put(
stubOriginationRouteFilterListName, rf);
stub.setVendor(ConfigurationFormat.CISCO);
stub.setRoles(stubRoles);
nodeRoles.put(hostname, stubRoles);
}
// create interface that will on which peering will occur
Map<String, Interface> stubInterfaces = stub.getInterfaces();
String stubInterfaceName = "TenGigabitEthernet0/"
+ (stubInterfaces.size() - 1);
Interface stubInterface = new Interface(stubInterfaceName);
stubInterfaces.put(stubInterfaceName, stubInterface);
stubInterface.setPrefix(new Prefix(neighborAddress, prefix
.getPrefixLength()));
stubInterface.setActive(true);
stubInterface.setBandwidth(10E9d);
// create neighbor within bgp process
BgpNeighbor edgeNeighbor = new BgpNeighbor(prefix);
edgeNeighbor.getOriginationPolicies().add(
stubOriginationPolicy);
edgeNeighbor.setRemoteAs(edgeAs);
edgeNeighbor.setLocalAs(stubAs);
edgeNeighbor.setSendCommunity(true);
edgeNeighbor.setDefaultMetric(0);
stub.getBgpProcess().getNeighbors()
.put(edgeNeighbor.getPrefix(), edgeNeighbor);
break;
}
else {
throw new BatfishException(
"Unable to derive stub hostname from interface description: \""
+ description + "\" using regex: \""
+ interfaceDescriptionRegex + "\"");
}
}
if (!found) {
throw new BatfishException(
"Could not determine stub hostname corresponding to ip: \""
+ neighborAddress.toString()
+ "\" listed as neighbor on router: \""
+ config.getHostname() + "\"");
}
}
}
// write updated node-roles mappings to disk
_logger.info("Serializing updated node-roles mappings: \""
+ nodeRolesPath + "\" ...");
serializeObject(nodeRoles, nodeRolesPath);
_logger.info("OK\n");
printElapsedTime();
// write stubs to disk
serializeIndependentConfigs(stubConfigurations,
_settings.getSerializeIndependentPath());
}
private void genMultipathQueries() {
_logger.info("\n*** GENERATING MULTIPATH-INCONSISTENCY QUERIES ***\n");
resetTimer();
String mpiQueryBasePath = _settings.getMultipathInconsistencyQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new MultipathInconsistencyQuerySynthesizer(
hostname);
String queryText = synth.getQueryText();
String mpiQueryPath = mpiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + mpiQueryPath + "\"...");
writeFile(mpiQueryPath, queryText);
_logger.info("OK\n");
}
_logger.info("Writing node lines for next stage...");
StringBuilder sb = new StringBuilder();
for (String node : nodes) {
sb.append(node + "\n");
}
writeFile(nodeSetTextPath, sb.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genReachableQueries() {
_logger.info("\n*** GENERATING REACHABLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getReachableQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String acceptNode = _settings.getAcceptNode();
String blacklistedNode = _settings.getBlacklistNode();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
if (hostname.equals(acceptNode) || hostname.equals(blacklistedNode)) {
continue;
}
QuerySynthesizer synth = new ReachableQuerySynthesizer(hostname,
acceptNode);
String queryText = synth.getQueryText();
String queryPath;
queryPath = queryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void genRoleReachabilityQueries() {
_logger.info("\n*** GENERATING NODE-TO-ROLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleReachabilityQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String iterationsPath = nodeRolesPath + ".iterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (String hostname : nodes) {
for (String role : roleNodes.keySet()) {
QuerySynthesizer synth = new RoleReachabilityQuerySynthesizer(
hostname, role);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + hostname + "-" + role
+ ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
_logger
.info("Writing role-node-role iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transmittingRole = roleNodeEntry.getKey();
NodeSet transmittingNodes = roleNodeEntry.getValue();
if (transmittingNodes.size() < 2) {
continue;
}
String[] tNodeArray = transmittingNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String receivingRole : roleNodes.keySet()) {
String iterationLine = transmittingRole + ":" + masterNode + ":"
+ slaveNode + ":" + receivingRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genRoleTransitQueries() {
_logger.info("\n*** GENERATING ROLE-TO-NODE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleTransitQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String roleNodesPath = _settings.getRoleNodesPath();
String iterationsPath = nodeRolesPath + ".rtiterations";
String constraintsIterationsPath = nodeRolesPath
+ ".rtconstraintsiterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (Entry<String, NodeSet> sourceEntry : roleNodes.entrySet()) {
String sourceRole = sourceEntry.getKey();
for (Entry<String, NodeSet> transitEntry : roleNodes.entrySet()) {
String transitRole = transitEntry.getKey();
if (transitRole.equals(sourceRole)) {
continue;
}
NodeSet transitNodes = transitEntry.getValue();
for (String transitNode : transitNodes) {
QuerySynthesizer synth = new RoleTransitQuerySynthesizer(
sourceRole, transitNode);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + transitNode + "-"
+ sourceRole + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
// not actually sure if this is necessary
StringBuilder sbRoleNodes = new StringBuilder();
_logger.info("Writing role-node mappings for concretizer stage...");
sbRoleNodes = new StringBuilder();
for (Entry<String, NodeSet> e : roleNodes.entrySet()) {
String role = e.getKey();
NodeSet currentNodes = e.getValue();
sbRoleNodes.append(role + ":");
for (String node : currentNodes) {
sbRoleNodes.append(node + ",");
}
sbRoleNodes.append(role + "\n");
}
writeFile(roleNodesPath, sbRoleNodes.toString());
_logger
.info("Writing transitrole-transitnode-sourcerole iteration ordering lines for constraints stage...");
StringBuilder sbConstraintsIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
for (String transitNode : transitNodes) {
String iterationLine = transitRole + ":" + transitNode + ":"
+ sourceRole + "\n";
sbConstraintsIterations.append(iterationLine);
}
}
}
writeFile(constraintsIterationsPath, sbConstraintsIterations.toString());
_logger.info("OK\n");
_logger
.info("Writing transitrole-master-slave-sourcerole iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
String[] tNodeArray = transitNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
String iterationLine = transitRole + ":" + masterNode + ":"
+ slaveNode + ":" + sourceRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genZ3(Map<String, Configuration> configurations,
File dataPlanePath) {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
String outputPath = _settings.getZ3File();
if (outputPath == null) {
throw new BatfishException("Need to specify output path for z3 logic");
}
String nodeSetPath = _settings.getNodeSetPath();
if (nodeSetPath == null) {
throw new BatfishException(
"Need to specify output path for serialized set of nodes in environment");
}
_logger.info("Deserializing data plane: \"" + dataPlanePath.toString()
+ "\"...");
DataPlane dataPlane = (DataPlane) deserializeObject(dataPlanePath);
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, dataPlane,
_settings.getSimplify());
String result = s.synthesize();
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
_logger.info("Writing Z3 logic: \"" + outputPath + "\"...");
File z3Out = new File(outputPath);
z3Out.delete();
writeFile(outputPath, result);
_logger.info("OK\n");
_logger.info("Serializing node set: \"" + nodeSetPath + "\"...");
NodeSet nodeSet = s.getNodeSet();
serializeObject(nodeSet, new File(nodeSetPath));
_logger.info("OK\n");
printElapsedTime();
}
private AdvertisementSet getAdvertisements(LogicBloxFrontend lbFrontend) {
AdvertisementSet adverts = new AdvertisementSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
BGP_ADVERTISEMENT_ROUTE_PREDICATE_NAME);
Relation bgpAdvertisementRouteRelation = lbFrontend
.queryPredicate(qualifiedName);
lbFrontend.fillBgpAdvertisementColumn(adverts,
bgpAdvertisementRouteRelation.getColumns().get(0));
return adverts;
}
public Map<String, Configuration> getConfigurations(
String serializedVendorConfigPath) {
Map<String, VendorConfiguration> vendorConfigurations = deserializeVendorConfigurations(serializedVendorConfigPath);
Map<String, Configuration> configurations = convertConfigurations(vendorConfigurations);
return configurations;
}
private Map<String, Configuration> getDeltaConfigurations(
EnvironmentSettings envSettings) {
String deltaConfigurationsDir = envSettings.getDeltaConfigurationsDir();
if (deltaConfigurationsDir != null) {
File deltaConfigurationsDirAsFile = new File(deltaConfigurationsDir);
if (deltaConfigurationsDirAsFile.exists()) {
File configParentDir = deltaConfigurationsDirAsFile.getParentFile();
Map<File, String> deltaConfigsText = readConfigurationFiles(configParentDir
.toString());
Map<String, VendorConfiguration> vendorDeltaConfigs = parseVendorConfigurations(deltaConfigsText);
Map<String, Configuration> deltaConfigs = convertConfigurations(vendorDeltaConfigs);
return deltaConfigs;
}
}
return Collections.<String, Configuration> emptyMap();
}
private String getDifferentialFlowTag() {
return _settings.getQuestionName() + ":" + _baseEnvSettings.getName()
+ ":" + _diffEnvSettings.getName();
}
private void getDifferentialHistory() {
LogicBloxFrontend baseLbFrontend = _manager.connect(_baseEnvSettings);
LogicBloxFrontend diffLbFrontend = _manager.connect(_diffEnvSettings);
baseLbFrontend.initEntityTable();
diffLbFrontend.initEntityTable();
String tag = getDifferentialFlowTag();
FlowHistory flowHistory = new FlowHistory();
populateFlowHistory(flowHistory, baseLbFrontend,
_baseEnvSettings.getName(), tag);
populateFlowHistory(flowHistory, diffLbFrontend,
_diffEnvSettings.getName(), tag);
_logger.output(flowHistory.toString());
}
private EdgeSet getEdgeBlacklist(EnvironmentSettings envSettings) {
EdgeSet blacklistEdges = null;
String edgeBlacklistPath = envSettings.getEdgeBlacklistPath();
if (edgeBlacklistPath != null) {
File edgeBlacklistPathAsFile = new File(edgeBlacklistPath);
if (edgeBlacklistPathAsFile.exists()) {
Topology blacklistTopology = parseTopology(edgeBlacklistPathAsFile);
blacklistEdges = blacklistTopology.getEdges();
}
}
return blacklistEdges;
}
// private Set<Path> getMultipathQueryPaths(Path directory) {
// Set<Path> queryPaths = new TreeSet<Path>();
// try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(
// directory, new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path path) throws IOException {
// String filename = path.getFileName().toString();
// return filename
// .startsWith(BfConsts.RELPATH_MULTIPATH_QUERY_PREFIX)
// && filename.endsWith(".smt2");
// for (Path path : directoryStream) {
// queryPaths.add(path);
// catch (IOException ex) {
// throw new BatfishException(
// "Could not list files in queries directory", ex);
// return queryPaths;
private double getElapsedTime(long beforeTime) {
long difference = System.currentTimeMillis() - beforeTime;
double seconds = difference / 1000d;
return seconds;
}
private InterfaceSet getFlowSinkSet(LogicBloxFrontend lbFrontend) {
InterfaceSet flowSinks = new InterfaceSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
FLOW_SINK_PREDICATE_NAME);
Relation flowSinkRelation = lbFrontend.queryPredicate(qualifiedName);
List<String> nodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodes,
flowSinkRelation.getColumns().get(0));
List<String> interfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaces,
flowSinkRelation.getColumns().get(1));
for (int i = 0; i < nodes.size(); i++) {
String node = nodes.get(i);
String iface = interfaces.get(i);
NodeInterfacePair f = new NodeInterfacePair(node, iface);
flowSinks.add(f);
}
return flowSinks;
}
private InterfaceSet getFlowSinkSet(String dataPlanePath) {
_logger.info("Deserializing data plane: \"" + dataPlanePath + "\"...");
File dataPlanePathAsFile = new File(dataPlanePath);
DataPlane dataPlane = (DataPlane) deserializeObject(dataPlanePathAsFile);
_logger.info("OK\n");
return dataPlane.getFlowSinks();
}
private String getFlowTag() {
return _settings.getQuestionName() + ":" + _envSettings.getName();
}
private List<String> getHelpPredicates(Map<String, String> predicateSemantics) {
Set<String> helpPredicateSet = new LinkedHashSet<String>();
_settings.getHelpPredicates();
if (_settings.getHelpPredicates() == null) {
helpPredicateSet.addAll(predicateSemantics.keySet());
}
else {
helpPredicateSet.addAll(_settings.getHelpPredicates());
}
List<String> helpPredicates = new ArrayList<String>();
helpPredicates.addAll(helpPredicateSet);
Collections.sort(helpPredicates);
return helpPredicates;
}
private void getHistory() {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
String tag = getFlowTag();
FlowHistory flowHistory = new FlowHistory();
populateFlowHistory(flowHistory, lbFrontend, _envSettings.getName(), tag);
_logger.output(flowHistory.toString());
}
private Set<NodeInterfacePair> getInterfaceBlacklist(
EnvironmentSettings envSettings) {
Set<NodeInterfacePair> blacklistInterfaces = null;
String interfaceBlacklistPath = envSettings.getInterfaceBlacklistPath();
if (interfaceBlacklistPath != null) {
File interfaceBlacklistPathAsFile = new File(interfaceBlacklistPath);
if (interfaceBlacklistPathAsFile.exists()) {
blacklistInterfaces = parseInterfaceBlacklist(interfaceBlacklistPathAsFile);
}
}
return blacklistInterfaces;
}
private NodeSet getNodeBlacklist(EnvironmentSettings envSettings) {
NodeSet blacklistNodes = null;
String nodeBlacklistPath = envSettings.getNodeBlacklistPath();
if (nodeBlacklistPath != null) {
File nodeBlacklistPathAsFile = new File(nodeBlacklistPath);
if (nodeBlacklistPathAsFile.exists()) {
blacklistNodes = parseNodeBlacklist(nodeBlacklistPathAsFile);
}
}
return blacklistNodes;
}
private PolicyRouteFibNodeMap getPolicyRouteFibNodeMap(
Relation fibPolicyRouteNextHops, LogicBloxFrontend lbFrontend) {
PolicyRouteFibNodeMap nodeMap = new PolicyRouteFibNodeMap();
List<String> nodeList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodeList,
fibPolicyRouteNextHops.getColumns().get(0));
List<String> ipList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_IP, ipList,
fibPolicyRouteNextHops.getColumns().get(1));
List<String> outInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, outInterfaces,
fibPolicyRouteNextHops.getColumns().get(2));
List<String> inNodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inNodes,
fibPolicyRouteNextHops.getColumns().get(3));
List<String> inInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inInterfaces,
fibPolicyRouteNextHops.getColumns().get(4));
int size = nodeList.size();
for (int i = 0; i < size; i++) {
String nodeOut = nodeList.get(i);
String nodeIn = inNodes.get(i);
Ip ip = new Ip(ipList.get(i));
String ifaceOut = outInterfaces.get(i);
String ifaceIn = inInterfaces.get(i);
PolicyRouteFibIpMap ipMap = nodeMap.get(nodeOut);
if (ipMap == null) {
ipMap = new PolicyRouteFibIpMap();
nodeMap.put(nodeOut, ipMap);
}
EdgeSet edges = ipMap.get(ip);
if (edges == null) {
edges = new EdgeSet();
ipMap.put(ip, edges);
}
Edge newEdge = new Edge(nodeOut, ifaceOut, nodeIn, ifaceIn);
edges.add(newEdge);
}
return nodeMap;
}
public PredicateInfo getPredicateInfo(Map<String, String> logicFiles) {
// Get predicate semantics from rules file
_logger.info("\n*** PARSING PREDICATE INFO ***\n");
resetTimer();
String predicateInfoPath = getPredicateInfoPath();
PredicateInfo predicateInfo = (PredicateInfo) deserializeObject(new File(
predicateInfoPath));
printElapsedTime();
return predicateInfo;
}
private String getPredicateInfoPath() {
File logicDir = retrieveLogicDir();
return Paths.get(logicDir.toString(), PREDICATE_INFO_FILENAME).toString();
}
private FibMap getRouteForwardingRules(Relation fibNetworkForward,
LogicBloxFrontend lbFrontend) {
FibMap fibs = new FibMap();
List<String> nameList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nameList,
fibNetworkForward.getColumns().get(0));
List<String> networkList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_INDEX_NETWORK, networkList,
fibNetworkForward.getColumns().get(1));
List<String> interfaceList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaceList,
fibNetworkForward.getColumns().get(2));
List<String> nextHopList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopList,
fibNetworkForward.getColumns().get(3));
List<String> nextHopIntList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopIntList,
fibNetworkForward.getColumns().get(4));
String currentHostname = "";
Map<String, Integer> startIndices = new HashMap<String, Integer>();
Map<String, Integer> endIndices = new HashMap<String, Integer>();
for (int i = 0; i < nameList.size(); i++) {
String currentRowHostname = nameList.get(i);
if (!currentHostname.equals(currentRowHostname)) {
if (i > 0) {
endIndices.put(currentHostname, i - 1);
}
currentHostname = currentRowHostname;
startIndices.put(currentHostname, i);
}
}
endIndices.put(currentHostname, nameList.size() - 1);
for (String hostname : startIndices.keySet()) {
FibSet fibRows = new FibSet();
fibs.put(hostname, fibRows);
int startIndex = startIndices.get(hostname);
int endIndex = endIndices.get(hostname);
for (int i = startIndex; i <= endIndex; i++) {
String networkStr = networkList.get(i);
Prefix prefix = new Prefix(networkStr);
String iface = interfaceList.get(i);
String nextHop = nextHopList.get(i);
String nextHopInt = nextHopIntList.get(i);
fibRows.add(new FibRow(prefix, iface, nextHop, nextHopInt));
}
}
return fibs;
}
private RouteSet getRoutes(LogicBloxFrontend lbFrontend) {
RouteSet routes = new RouteSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
INSTALLED_ROUTE_PREDICATE_NAME);
Relation installedRoutesRelation = lbFrontend
.queryPredicate(qualifiedName);
lbFrontend.fillRouteColumn(routes, installedRoutesRelation.getColumns()
.get(0));
return routes;
}
private Map<String, String> getSemanticsFiles() {
final Map<String, String> semanticsFiles = new HashMap<String, String>();
File logicDirFile = retrieveLogicDir();
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String pathString = file.toString();
if (pathString.endsWith(".semantics")) {
String contents = Util.readFile(file.toFile());
semanticsFiles.put(pathString, contents);
}
return super.visitFile(file, attrs);
}
};
try {
Files.walkFileTree(Paths.get(logicDirFile.getAbsolutePath()), visitor);
}
catch (IOException e) {
e.printStackTrace();
}
cleanupLogicDir();
return semanticsFiles;
}
private Set<Edge> getSymmetricEdgePairs(EdgeSet edges) {
LinkedHashSet<Edge> consumedEdges = new LinkedHashSet<Edge>();
for (Edge edge : edges) {
if (consumedEdges.contains(edge)) {
continue;
}
Edge reverseEdge = new Edge(edge.getInterface2(), edge.getInterface1());
consumedEdges.add(edge);
consumedEdges.add(reverseEdge);
}
return consumedEdges;
}
private void histogram(String testRigPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
_logger.info("Building feature histogram...");
MultiSet<String> histogram = new TreeMultiSet<String>();
for (VendorConfiguration vc : vendorConfigurations.values()) {
Set<String> unimplementedFeatures = vc.getUnimplementedFeatures();
histogram.add(unimplementedFeatures);
}
_logger.info("OK\n");
for (String feature : histogram.elements()) {
int count = histogram.count(feature);
_logger.output(feature + ": " + count + "\n");
}
}
private boolean isJavaSerializationData(File inputFile) {
try (FileInputStream i = new FileInputStream(inputFile)) {
int headerLength = JAVA_SERIALIZED_OBJECT_HEADER.length;
byte[] headerBytes = new byte[headerLength];
int result = i.read(headerBytes, 0, headerLength);
if (result != headerLength) {
throw new BatfishException("Read wrong number of bytes");
}
return Arrays.equals(headerBytes, JAVA_SERIALIZED_OBJECT_HEADER);
}
catch (IOException e) {
throw new BatfishException("Could not read header from file: "
+ inputFile.toString(), e);
}
}
private void keepBlocks(List<String> blockNames) {
LogicBloxFrontend lbFrontend = _manager.connect();
Set<String> allBlockNames = new LinkedHashSet<String>();
allBlockNames.addAll(Block.BLOCKS.keySet());
for (String blockName : blockNames) {
Block block = Block.BLOCKS.get(blockName);
if (block == null) {
throw new BatfishException("Invalid block name: \"" + blockName
+ "\"");
}
Set<Block> dependencies = block.getDependencies();
for (Block dependency : dependencies) {
allBlockNames.remove(dependency.getName());
}
allBlockNames.remove(blockName);
}
List<String> qualifiedBlockNames = new ArrayList<String>();
for (String blockName : allBlockNames) {
String qualifiedBlockName = LB_BATFISH_LIBRARY_NAME + ":" + blockName
+ "_rules";
qualifiedBlockNames.add(qualifiedBlockName);
}
lbFrontend.removeBlocks(qualifiedBlockNames);
}
public Map<String, Configuration> loadConfigurations() {
return loadConfigurations(_envSettings);
}
public Map<String, Configuration> loadConfigurations(
EnvironmentSettings envSettings) {
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
processNodeBlacklist(configurations, envSettings);
processInterfaceBlacklist(configurations, envSettings);
processDeltaConfigurations(configurations, envSettings);
return configurations;
}
private Topology loadTopology() {
return loadTopology(_envSettings);
}
private Topology loadTopology(EnvironmentSettings envSettings) {
String topologyPath = envSettings.getSerializedTopologyPath();
File topologyPathFile = new File(topologyPath);
_logger.info("Deserializing topology...");
Topology topology = (Topology) deserializeObject(topologyPathFile);
_logger.info("OK\n");
return topology;
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser) {
return parse(parser, _logger, _settings);
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename) {
_logger.info("Parsing: \"" + filename + "\"...");
return parse(parser);
}
private void parseFlowsFromConstraints(StringBuilder sb,
RoleNodeMap roleNodes) {
Path flowConstraintsDir = Paths.get(_settings.getFlowPath());
File[] constraintsFiles = flowConstraintsDir.toFile().listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.matches(".*-concrete-.*.smt2.out");
}
});
if (constraintsFiles == null) {
throw new BatfishException("Error reading flow constraints directory");
}
for (File constraintsFile : constraintsFiles) {
String flowConstraintsText = Util.readFile(constraintsFile);
ConcretizerQueryResultCombinedParser parser = new ConcretizerQueryResultCombinedParser(
flowConstraintsText, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, constraintsFile.toString());
ParseTreeWalker walker = new ParseTreeWalker();
ConcretizerQueryResultExtractor extractor = new ConcretizerQueryResultExtractor();
walker.walk(extractor, tree);
String id = extractor.getId();
if (id == null) {
continue;
}
Map<String, Long> constraints = extractor.getConstraints();
long src_ip = 0;
long dst_ip = 0;
long src_port = 0;
long dst_port = 0;
long protocol = IpProtocol.IP.number();
for (String varName : constraints.keySet()) {
Long value = constraints.get(varName);
switch (varName) {
case Synthesizer.SRC_IP_VAR:
src_ip = value;
break;
case Synthesizer.DST_IP_VAR:
dst_ip = value;
break;
case Synthesizer.SRC_PORT_VAR:
src_port = value;
break;
case Synthesizer.DST_PORT_VAR:
dst_port = value;
break;
case Synthesizer.IP_PROTOCOL_VAR:
protocol = value;
break;
default:
throw new Error("invalid variable name");
}
}
// TODO: cleanup dirty hack
if (roleNodes != null) {
// id is role
NodeSet nodes = roleNodes.get(id);
for (String node : nodes) {
String line = node + "|" + src_ip + "|" + dst_ip + "|"
+ src_port + "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
else {
String node = id;
String line = node + "|" + src_ip + "|" + dst_ip + "|" + src_port
+ "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
}
private Set<NodeInterfacePair> parseInterfaceBlacklist(
File interfaceBlacklistPath) {
Set<NodeInterfacePair> ifaces = new TreeSet<NodeInterfacePair>();
String interfaceBlacklistText = Util.readFile(interfaceBlacklistPath);
String[] interfaceBlacklistLines = interfaceBlacklistText.split("\n");
for (String interfaceBlacklistLine : interfaceBlacklistLines) {
String trimmedLine = interfaceBlacklistLine.trim();
if (trimmedLine.length() > 0) {
String[] parts = trimmedLine.split(":");
if (parts.length != 2) {
throw new BatfishException(
"Invalid node-interface pair format: " + trimmedLine);
}
String hostname = parts[0];
String iface = parts[1];
NodeInterfacePair p = new NodeInterfacePair(hostname, iface);
ifaces.add(p);
}
}
return ifaces;
}
private NodeSet parseNodeBlacklist(File nodeBlacklistPath) {
NodeSet nodeSet = new NodeSet();
String nodeBlacklistText = Util.readFile(nodeBlacklistPath);
String[] nodeBlacklistLines = nodeBlacklistText.split("\n");
for (String nodeBlacklistLine : nodeBlacklistLines) {
String hostname = nodeBlacklistLine.trim();
if (hostname.length() > 0) {
nodeSet.add(hostname);
}
}
return nodeSet;
}
private NodeRoleMap parseNodeRoles(String testRigPath) {
Path rolePath = Paths.get(testRigPath, "node_roles");
String roleFileText = Util.readFile(rolePath.toFile());
_logger.info("Parsing: \"" + rolePath.toAbsolutePath().toString() + "\"");
BatfishCombinedParser<?, ?> parser = new RoleCombinedParser(roleFileText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
RoleExtractor extractor = new RoleExtractor();
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
NodeRoleMap nodeRoles = extractor.getRoleMap();
return nodeRoles;
}
private Question parseQuestion(String questionPath) {
File questionFile = new File(questionPath);
_logger.info("Reading question file: \"" + questionPath + "\"...");
String questionText = Util.readFile(questionFile);
_logger.info("OK\n");
QuestionCombinedParser parser = new QuestionCombinedParser(questionText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
QuestionExtractor extractor = new QuestionExtractor(getFlowTag());
try {
ParserRuleContext tree = parse(parser, questionPath);
_logger.info("\tPost-processing...");
extractor.processParseTree(tree);
_logger.info("OK\n");
}
catch (ParserBatfishException e) {
String error = "Error parsing question: \"" + questionPath + "\"";
throw new BatfishException(error, e);
}
catch (Exception e) {
String error = "Error post-processing parse tree of question file: \""
+ questionPath + "\"";
throw new BatfishException(error, e);
}
return extractor.getQuestion();
}
private Topology parseTopology(File topologyFilePath) {
_logger.info("*** PARSING TOPOLOGY ***\n");
resetTimer();
String topologyFileText = Util.readFile(topologyFilePath);
BatfishCombinedParser<?, ?> parser = null;
TopologyExtractor extractor = null;
_logger.info("Parsing: \""
+ topologyFilePath.getAbsolutePath().toString() + "\" ...");
if (topologyFileText.startsWith("autostart")) {
parser = new GNS3TopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new GNS3TopologyExtractor();
}
else if (topologyFileText
.startsWith(BatfishTopologyCombinedParser.HEADER)) {
parser = new BatfishTopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new BatfishTopologyExtractor();
}
else if (topologyFileText.equals("")) {
throw new BatfishException("ERROR: empty topology\n");
}
else {
_logger.fatal("...ERROR\n");
throw new BatfishException("Topology format error");
}
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
Topology topology = extractor.getTopology();
printElapsedTime();
return topology;
}
private Map<String, VendorConfiguration> parseVendorConfigurations(
Map<File, String> configurationData) {
_logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n");
resetTimer();
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
List<ParseVendorConfigurationJob> jobs = new ArrayList<ParseVendorConfigurationJob>();
for (File currentFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(currentFile);
ParseVendorConfigurationJob job = new ParseVendorConfigurationJob(
_settings, fileText, currentFile, warnings);
jobs.add(job);
}
BatfishJobExecutor<ParseVendorConfigurationJob, ParseVendorConfigurationResult, Map<String, VendorConfiguration>> executor = new BatfishJobExecutor<ParseVendorConfigurationJob, ParseVendorConfigurationResult, Map<String, VendorConfiguration>>(
_settings, _logger);
executor.executeJobs(jobs, vendorConfigurations);
printElapsedTime();
return vendorConfigurations;
}
private void populateConfigurationFactBins(
Collection<Configuration> configurations,
Map<String, StringBuilder> factBins) {
_logger
.info("\n*** EXTRACTING LOGICBLOX FACTS FROM CONFIGURATIONS ***\n");
resetTimer();
Set<Long> communities = new LinkedHashSet<Long>();
for (Configuration c : configurations) {
communities.addAll(c.getCommunities());
}
boolean pedanticAsError = _settings.getPedanticAsError();
boolean pedanticRecord = _settings.getPedanticRecord();
boolean redFlagAsError = _settings.getRedFlagAsError();
boolean redFlagRecord = _settings.getRedFlagRecord();
boolean unimplementedAsError = _settings.getUnimplementedAsError();
boolean unimplementedRecord = _settings.getUnimplementedRecord();
boolean processingError = false;
for (Configuration c : configurations) {
String hostname = c.getHostname();
_logger.debug("Extracting facts from: \"" + hostname + "\"");
Warnings warnings = new Warnings(pedanticAsError, pedanticRecord,
redFlagAsError, redFlagRecord, unimplementedAsError,
unimplementedRecord, false);
try {
ConfigurationFactExtractor cfe = new ConfigurationFactExtractor(c,
communities, factBins, warnings);
cfe.writeFacts();
_logger.debug("...OK\n");
}
catch (BatfishException e) {
_logger.fatal("...EXTRACTION ERROR\n");
_logger.fatal(ExceptionUtils.getStackTrace(e));
processingError = true;
if (_settings.getExitOnFirstError()) {
break;
}
else {
continue;
}
}
finally {
for (String warning : warnings.getRedFlagWarnings()) {
_logger.redflag(warning);
}
for (String warning : warnings.getUnimplementedWarnings()) {
_logger.unimplemented(warning);
}
for (String warning : warnings.getPedanticWarnings()) {
_logger.pedantic(warning);
}
}
}
if (processingError) {
throw new BatfishException(
"Failed to extract facts from vendor-indpendent configuration structures");
}
printElapsedTime();
}
private void populateFlowHistory(FlowHistory flowHistory,
LogicBloxFrontend lbFrontend, String environmentName, String tag) {
String qualifiedName = _predicateInfo.getPredicateNames().get(
FLOW_HISTORY_PREDICATE_NAME);
Relation relation = lbFrontend.queryPredicate(qualifiedName);
List<Flow> flows = new ArrayList<Flow>();
List<String> historyLines = new ArrayList<String>();
lbFrontend.fillFlowColumn(flows, relation.getColumns().get(0));
lbFrontend.fillColumn(LBValueType.STRING, historyLines, relation
.getColumns().get(1));
int numEntries = flows.size();
for (int i = 0; i < numEntries; i++) {
Flow flow = flows.get(i);
if (flow.getTag().equals(tag)) {
String historyLine = historyLines.get(i);
FlowTrace flowTrace = new FlowTrace(historyLine);
flowHistory.addFlowTrace(flow, environmentName, flowTrace);
}
}
}
private void populatePrecomputedBgpAdvertisements(
String precomputedBgpAdvertisementsPath,
Map<String, StringBuilder> cpFactBins) {
File inputFile = new File(precomputedBgpAdvertisementsPath);
StringBuilder adverts = cpFactBins
.get(PRECOMPUTED_BGP_ADVERTISEMENTS_PREDICATE_NAME);
StringBuilder advertCommunities = cpFactBins
.get(PRECOMPUTED_BGP_ADVERTISEMENT_COMMUNITY_PREDICATE_NAME);
StringBuilder advertPaths = cpFactBins
.get(PRECOMPUTED_BGP_ADVERTISEMENT_AS_PATH_PREDICATE_NAME);
StringBuilder advertPathLengths = cpFactBins
.get(PRECOMPUTED_BGP_ADVERTISEMENT_AS_PATH_LENGTH_PREDICATE_NAME);
AdvertisementSet advertSet = (AdvertisementSet) deserializeObject(inputFile);
StringBuilder wNetworks = cpFactBins.get(NETWORKS_PREDICATE_NAME);
Set<Prefix> networks = new HashSet<Prefix>();
int pcIndex = 0;
for (BgpAdvertisement advert : advertSet) {
String type = advert.getType();
switch (type) {
case "ibgp_ti":
case "bgp_ti":
break;
default:
continue;
}
Prefix network = advert.getNetwork();
networks.add(network);
long networkStart = network.getAddress().asLong();
long networkEnd = network.getEndAddress().asLong();
int prefixLength = network.getPrefixLength();
long nextHopIp = advert.getNextHopIp().asLong();
String srcNode = advert.getSrcNode();
long srcIp = advert.getSrcIp().asLong();
String dstNode = advert.getDstNode();
long dstIp = advert.getDstIp().asLong();
String srcProtocol = advert.getSrcProtocol().protocolName();
String originType = advert.getOriginType().toString();
int localPref = advert.getLocalPreference();
int med = advert.getMed();
long originatorIp = advert.getOriginatorIp().asLong();
adverts.append(pcIndex + "|" + type + "|" + networkStart + "|"
+ networkEnd + "|" + prefixLength + "|" + nextHopIp + "|"
+ srcNode + "|" + srcIp + "|" + dstNode + "|" + dstIp + "|"
+ srcProtocol + "|" + originType + "|" + localPref + "|" + med
+ "|" + originatorIp + "\n");
for (Long community : advert.getCommunities()) {
advertCommunities.append(pcIndex + "|" + community + "\n");
}
AsPath asPath = advert.getAsPath();
int asPathLength = asPath.size();
for (int i = 0; i < asPathLength; i++) {
AsSet asSet = asPath.get(i);
for (Integer as : asSet) {
advertPaths.append(pcIndex + "|" + i + "|" + as + "\n");
}
}
advertPathLengths.append(pcIndex + "|" + asPathLength + "\n");
pcIndex++;
}
for (Prefix network : networks) {
long networkStart = network.getNetworkAddress().asLong();
long networkEnd = network.getEndAddress().asLong();
int prefixLength = network.getPrefixLength();
wNetworks.append(networkStart + "|" + networkStart + "|" + networkEnd
+ "|" + prefixLength + "\n");
}
}
private void populatePrecomputedFacts(String precomputedFactsPath,
Map<String, StringBuilder> cpFactBins) {
File precomputedFactsDir = new File(precomputedFactsPath);
String[] filenames = precomputedFactsDir.list();
for (String filename : filenames) {
File file = Paths.get(precomputedFactsPath, filename).toFile();
StringBuilder sb = cpFactBins.get(filename);
if (sb == null) {
throw new BatfishException("File: \"" + filename
+ "\" does not correspond to a fact");
}
String contents = Util.readFile(file);
sb.append(contents);
}
Set<Map.Entry<String, StringBuilder>> cpEntries = cpFactBins.entrySet();
Set<Map.Entry<String, StringBuilder>> cpEntriesToRemove = new HashSet<Map.Entry<String, StringBuilder>>();
for (Entry<String, StringBuilder> e : cpEntries) {
StringBuilder sb = e.getValue();
if (sb.toString().length() == 0) {
cpEntriesToRemove.add(e);
}
}
for (Entry<String, StringBuilder> e : cpEntriesToRemove) {
cpEntries.remove(e);
}
}
private void populatePrecomputedIbgpNeighbors(
String precomputedIbgpNeighborsPath,
Map<String, StringBuilder> cpFactBins) {
File inputFile = new File(precomputedIbgpNeighborsPath);
StringBuilder sb = cpFactBins
.get(PRECOMPUTED_IBGP_NEIGHBORS_PREDICATE_NAME);
IbgpTopology topology = (IbgpTopology) deserializeObject(inputFile);
for (IpEdge edge : topology) {
String node1 = edge.getNode1();
long ip1 = edge.getIp1().asLong();
String node2 = edge.getNode2();
long ip2 = edge.getIp2().asLong();
sb.append(node1 + "|" + ip1 + "|" + node2 + "|" + ip2 + "\n");
}
}
private void populatePrecomputedRoutes(Set<String> precomputedRoutesPaths,
Map<String, StringBuilder> cpFactBins) {
StringBuilder sb = cpFactBins.get(PRECOMPUTED_ROUTES_PREDICATE_NAME);
StringBuilder wNetworks = cpFactBins.get(NETWORKS_PREDICATE_NAME);
Set<Prefix> networks = new HashSet<Prefix>();
for (String precomputedRoutesPath : precomputedRoutesPaths) {
File inputFile = new File(precomputedRoutesPath);
RouteSet routes = (RouteSet) deserializeObject(inputFile);
for (PrecomputedRoute route : routes) {
String node = route.getNode();
Prefix prefix = route.getPrefix();
networks.add(prefix);
long networkStart = prefix.getNetworkAddress().asLong();
long networkEnd = prefix.getEndAddress().asLong();
int prefixLength = prefix.getPrefixLength();
long nextHopIp = route.getNextHopIp().asLong();
int admin = route.getAdministrativeCost();
int cost = route.getCost();
String protocol = route.getProtocol().protocolName();
int tag = route.getTag();
sb.append(node + "|" + networkStart + "|" + networkEnd + "|"
+ prefixLength + "|" + nextHopIp + "|" + admin + "|" + cost
+ "|" + protocol + "|" + tag + "\n");
}
for (Prefix network : networks) {
long networkStart = network.getNetworkAddress().asLong();
long networkEnd = network.getEndAddress().asLong();
int prefixLength = network.getPrefixLength();
wNetworks.append(networkStart + "|" + networkStart + "|"
+ networkEnd + "|" + prefixLength + "\n");
}
}
}
private void postDifferentialFlows() {
LogicBloxFrontend baseLbFrontend = _manager.connect(_baseEnvSettings);
LogicBloxFrontend diffLbFrontend = _manager.connect(_diffEnvSettings);
Map<String, StringBuilder> baseTrafficFactBins = new LinkedHashMap<String, StringBuilder>();
Map<String, StringBuilder> diffTrafficFactBins = new LinkedHashMap<String, StringBuilder>();
Path baseDumpDir = Paths.get(_baseEnvSettings.getTrafficFactDumpDir());
Path diffDumpDir = Paths.get(_diffEnvSettings.getTrafficFactDumpDir());
for (String predicate : Facts.TRAFFIC_FACT_COLUMN_HEADERS.keySet()) {
File factFile = baseDumpDir.resolve(predicate).toFile();
String contents = Util.readFile(factFile);
StringBuilder sb = new StringBuilder();
baseTrafficFactBins.put(predicate, sb);
sb.append(contents);
}
for (String predicate : Facts.TRAFFIC_FACT_COLUMN_HEADERS.keySet()) {
File factFile = diffDumpDir.resolve(predicate).toFile();
String contents = Util.readFile(factFile);
StringBuilder sb = new StringBuilder();
diffTrafficFactBins.put(predicate, sb);
sb.append(contents);
}
postFacts(baseLbFrontend, baseTrafficFactBins);
postFacts(diffLbFrontend, baseTrafficFactBins);
}
private void postFacts(LogicBloxFrontend lbFrontend,
Map<String, StringBuilder> factBins) {
Map<String, StringBuilder> enabledFacts = new HashMap<String, StringBuilder>();
enabledFacts.putAll(factBins);
enabledFacts.keySet().removeAll(_settings.getDisabledFacts());
_logger.info("\n*** POSTING FACTS TO BLOXWEB SERVICES ***\n");
resetTimer();
_logger.info("Starting bloxweb services...");
lbFrontend.startLbWebServices();
_logger.info("OK\n");
_logger.info("Posting facts...");
try {
lbFrontend.postFacts(enabledFacts);
}
catch (ServiceClientException e) {
throw new BatfishException("Failed to post facts to bloxweb services",
e);
}
_logger.info("OK\n");
_logger.info("Stopping bloxweb services...");
lbFrontend.stopLbWebServices();
_logger.info("OK\n");
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void postFacts(Map<String, StringBuilder> factBins) {
LogicBloxFrontend lbFrontend = _manager.connect();
postFacts(lbFrontend, factBins);
}
private void postFlows() {
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
Path dumpDir = Paths.get(_envSettings.getTrafficFactDumpDir());
for (String predicate : Facts.TRAFFIC_FACT_COLUMN_HEADERS.keySet()) {
File factFile = dumpDir.resolve(predicate).toFile();
String contents = Util.readFile(factFile);
StringBuilder sb = new StringBuilder();
trafficFactBins.put(predicate, sb);
sb.append(contents);
}
postFacts(trafficFactBins);
}
private void printAllPredicateSemantics(
Map<String, String> predicateSemantics) {
// Get predicate semantics from rules file
_logger.info("\n*** PRINTING PREDICATE SEMANTICS ***\n");
List<String> helpPredicates = getHelpPredicates(predicateSemantics);
for (String predicate : helpPredicates) {
printPredicateSemantics(predicate);
_logger.info("\n");
}
}
private void printElapsedTime() {
double seconds = getElapsedTime(_timerCount);
_logger.info("Time taken for this task: " + seconds + " seconds\n");
}
private void printPredicate(LogicBloxFrontend lbFrontend,
String predicateName) {
List<String> output;
printPredicateSemantics(predicateName);
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
_logger.output(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
}
private void printPredicateCount(LogicBloxFrontend lbFrontend,
String predicateName) {
int numRows = lbFrontend.queryPredicate(predicateName).getColumns()
.get(0).size();
String output = "|" + predicateName + "| = " + numRows + "\n";
_logger.info(output);
}
public void printPredicateCounts(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
for (String predicateName : predicateNames) {
printPredicateCount(lbFrontend, predicateName);
// _logger.info("\n");
}
printElapsedTime();
}
public void printPredicates(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
String queryDumpDirStr = _settings.getQueryDumpDir();
if (queryDumpDirStr == null) {
for (String predicateName : predicateNames) {
printPredicate(lbFrontend, predicateName);
}
}
else {
Path queryDumpDir = Paths.get(queryDumpDirStr);
queryDumpDir.toFile().mkdirs();
for (String predicateName : predicateNames) {
String outputPath = queryDumpDir.resolve(predicateName).toString();
printPredicateToFile(lbFrontend, predicateName, outputPath);
}
}
printElapsedTime();
}
private void printPredicateSemantics(String predicateName) {
String semantics = _predicateInfo.getPredicateSemantics(predicateName);
if (semantics == null) {
semantics = "<missing>";
}
_logger.info("\n");
_logger.info("Predicate: " + predicateName + "\n");
_logger.info("Semantics: " + semantics + "\n");
}
private void printPredicateToFile(LogicBloxFrontend lbFrontend,
String predicateName, String outputPath) {
List<String> output;
printPredicateSemantics(predicateName);
StringBuilder sb = new StringBuilder();
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
sb.append(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
String outputString = sb.toString();
writeFile(outputPath, outputString);
}
private void printSymmetricEdgePairs() {
Map<String, Configuration> configs = loadConfigurations();
EdgeSet edges = synthesizeTopology(configs);
Set<Edge> symmetricEdgePairs = getSymmetricEdgePairs(edges);
List<Edge> edgeList = new ArrayList<Edge>();
edgeList.addAll(symmetricEdgePairs);
for (int i = 0; i < edgeList.size() / 2; i++) {
Edge edge1 = edgeList.get(2 * i);
Edge edge2 = edgeList.get(2 * i + 1);
_logger.output(edge1.getNode1() + ":" + edge1.getInt1() + ","
+ edge1.getNode2() + ":" + edge1.getInt2() + " "
+ edge2.getNode1() + ":" + edge2.getInt1() + ","
+ edge2.getNode2() + ":" + edge2.getInt2() + "\n");
}
printElapsedTime();
}
private void printTracePredicate(LogicBloxFrontend lbFrontend,
String predicateName) {
List<String> output;
printPredicateSemantics(predicateName);
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(TRACE_PREFIX
+ qualifiedName);
try {
output = lbFrontend.getTracePredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
_logger.output(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
}
public void printTracePredicates(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
for (String predicateName : predicateNames) {
printTracePredicate(lbFrontend, predicateName);
}
printElapsedTime();
}
private void processDeltaConfigurations(
Map<String, Configuration> configurations,
EnvironmentSettings envSettings) {
Map<String, Configuration> deltaConfigurations = getDeltaConfigurations(envSettings);
configurations.putAll(deltaConfigurations);
// TODO: deal with topological changes
}
private void processInterfaceBlacklist(
Map<String, Configuration> configurations,
EnvironmentSettings envSettings) {
Set<NodeInterfacePair> blacklistInterfaces = getInterfaceBlacklist(envSettings);
if (blacklistInterfaces != null) {
for (NodeInterfacePair p : blacklistInterfaces) {
String hostname = p.getHostname();
String iface = p.getInterface();
Configuration node = configurations.get(hostname);
node.getInterfaces().get(iface).setActive(false);
}
}
}
private void processNodeBlacklist(Map<String, Configuration> configurations,
EnvironmentSettings envSettings) {
NodeSet blacklistNodes = getNodeBlacklist(envSettings);
if (blacklistNodes != null) {
for (String hostname : blacklistNodes) {
configurations.remove(hostname);
}
}
}
private Topology processTopologyFile(File topologyFilePath,
Map<String, StringBuilder> factBins) {
Topology topology = parseTopology(topologyFilePath);
return topology;
}
private void query() {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
Map<String, String> allPredicateNames = _predicateInfo
.getPredicateNames();
Set<String> predicateNames = new TreeSet<String>();
if (_settings.getQueryAll()) {
predicateNames.addAll(allPredicateNames.keySet());
}
else {
predicateNames.addAll(_settings.getPredicates());
}
if (_settings.getCountsOnly()) {
printPredicateCounts(lbFrontend, predicateNames);
}
else {
printPredicates(lbFrontend, predicateNames);
}
}
private Map<File, String> readConfigurationFiles(String testRigPath) {
_logger.info("\n*** READING CONFIGURATION FILES ***\n");
resetTimer();
Map<File, String> configurationData = new TreeMap<File, String>();
File configsPath = Paths.get(testRigPath,
BfConsts.RELPATH_CONFIGURATIONS_DIR).toFile();
File[] configFilePaths = configsPath.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
});
if (configFilePaths == null) {
throw new BatfishException(
"Error reading test rig configs directory: \""
+ configsPath.toString() + "\"");
}
for (File file : configFilePaths) {
_logger.debug("Reading: \"" + file.toString() + "\"\n");
String fileText = Util.readFile(file.getAbsoluteFile()) + "\n";
configurationData.put(file, fileText);
}
printElapsedTime();
return configurationData;
}
private void removeBlocks(List<String> blockNames) {
LogicBloxFrontend lbFrontend = _manager.connect();
Set<String> allBlockNames = new LinkedHashSet<String>();
for (String blockName : blockNames) {
Block block = Block.BLOCKS.get(blockName);
if (block == null) {
throw new BatfishException("Invalid block name: \"" + blockName
+ "\"");
}
Set<Block> dependents = block.getDependents();
for (Block dependent : dependents) {
allBlockNames.add(dependent.getName());
}
allBlockNames.add(blockName);
}
List<String> qualifiedBlockNames = new ArrayList<String>();
for (String blockName : allBlockNames) {
String qualifiedBlockName = LB_BATFISH_LIBRARY_NAME + ":" + blockName
+ "_rules";
qualifiedBlockNames.add(qualifiedBlockName);
}
lbFrontend.removeBlocks(qualifiedBlockNames);
}
private void resetTimer() {
_timerCount = System.currentTimeMillis();
}
private File retrieveLogicDir() {
File logicDirFile = null;
final String locatorFilename = LogicResourceLocator.class.getSimpleName()
+ ".class";
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
UrlZipExplorer zip = null;
StringFilter lbFilter = new StringFilter() {
@Override
public boolean accept(String filename) {
return filename.endsWith(".lbb") || filename.endsWith(".lbp")
|| filename.endsWith(".semantics")
|| filename.endsWith(locatorFilename)
|| filename.endsWith(PREDICATE_INFO_FILENAME);
}
};
if (logicSourceString.startsWith("onejar:")) {
FileVisitor<Path> visitor = null;
try {
zip = new UrlZipExplorer(logicSourceURL);
Path destinationDir = Files.createTempDirectory("lbtmpproject");
File destinationDirAsFile = destinationDir.toFile();
zip.extractFiles(lbFilter, destinationDirAsFile);
visitor = new SimpleFileVisitor<Path>() {
private String _projectDirectory;
@Override
public String toString() {
return _projectDirectory;
}
@Override
public FileVisitResult visitFile(Path aFile,
BasicFileAttributes aAttrs) throws IOException {
if (aFile.endsWith(locatorFilename)) {
_projectDirectory = aFile.getParent().toString();
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(destinationDir, visitor);
_tmpLogicDir = destinationDirAsFile;
}
catch (IOException e) {
throw new BatfishException(
"Failed to retrieve logic dir from onejar archive", e);
}
String fileString = visitor.toString();
return new File(fileString);
}
else {
String logicPackageResourceName = LogicResourceLocator.class
.getPackage().getName().replace('.', SEPARATOR.charAt(0));
try {
logicDirFile = new File(LogicResourceLocator.class.getClassLoader()
.getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic directory", e);
}
return logicDirFile;
}
}
private void revert() {
_logger.info("\n*** REVERTING WORKSPACE ***\n");
LogicBloxFrontend lbFrontend = _manager.connect();
String workspaceName = new File(_settings.getTestRigPath()).getName();
String branchName = _settings.getBranchName();
_logger.debug("Reverting workspace: \"" + workspaceName
+ "\" to branch: \"" + branchName + "\n");
String errorResult = lbFrontend.revertDatabase(branchName);
if (errorResult != null) {
throw new BatfishException("Failed to revert database: " + errorResult);
}
}
public void run() {
boolean action = false;
if (_settings.getQuery() || _settings.getPrintSemantics()
|| _settings.getDataPlane() || _settings.getWriteRoutes()
|| _settings.getWriteBgpAdvertisements()
|| _settings.getWriteIbgpNeighbors()
|| _settings.getDifferentialHistory() || _settings.getHistory()
|| _settings.getTraceQuery()) {
Map<String, String> logicFiles = getSemanticsFiles();
_predicateInfo = getPredicateInfo(logicFiles);
// Print predicate semantics and quit if requested
if (_settings.getPrintSemantics()) {
printAllPredicateSemantics(_predicateInfo.getPredicateSemantics());
return;
}
}
if (_settings.getPrintSymmetricEdgePairs()) {
printSymmetricEdgePairs();
return;
}
if (_settings.getSynthesizeTopology()) {
writeSynthesizedTopology();
return;
}
if (_settings.getAnswer()) {
String questionPath = _settings.getQuestionPath();
answer(questionPath);
action = true;
}
if (_settings.getBuildPredicateInfo()) {
buildPredicateInfo();
return;
}
if (_settings.getHistogram()) {
histogram(_settings.getTestRigPath());
return;
}
if (_settings.getGenerateOspfTopologyPath() != null) {
generateOspfConfigs(_settings.getGenerateOspfTopologyPath(),
_settings.getSerializeIndependentPath());
return;
}
if (_settings.getFlatten()) {
String flattenSource = _settings.getTestRigPath();
String flattenDestination = _settings.getFlattenDestination();
flatten(flattenSource, flattenDestination);
return;
}
if (_settings.getGenerateStubs()) {
String inputRole = _settings.getGenerateStubsInputRole();
String interfaceDescriptionRegex = _settings
.getGenerateStubsInterfaceDescriptionRegex();
int stubAs = _settings.getGenerateStubsRemoteAs();
generateStubs(inputRole, stubAs, interfaceDescriptionRegex);
return;
}
if (_settings.getZ3()) {
Map<String, Configuration> configurations = loadConfigurations();
String dataPlanePath = _envSettings.getDataPlanePath();
if (dataPlanePath == null) {
throw new BatfishException("Missing path to data plane");
}
File dataPlanePathAsFile = new File(dataPlanePath);
genZ3(configurations, dataPlanePathAsFile);
return;
}
if (_settings.getAnonymize()) {
anonymizeConfigurations();
return;
}
if (_settings.getInterfaceFailureInconsistencyReachableQuery()) {
genReachableQueries();
return;
}
if (_settings.getRoleReachabilityQuery()) {
genRoleReachabilityQueries();
return;
}
if (_settings.getRoleTransitQuery()) {
genRoleTransitQueries();
return;
}
if (_settings.getInterfaceFailureInconsistencyBlackHoleQuery()) {
genBlackHoleQueries();
return;
}
if (_settings.getGenerateMultipathInconsistencyQuery()) {
genMultipathQueries();
return;
}
if (_settings.getSerializeVendor()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getSerializeVendorPath();
serializeVendorConfigs(testRigPath, outputPath);
return;
}
if (_settings.dumpInterfaceDescriptions()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getDumpInterfaceDescriptionsPath();
dumpInterfaceDescriptions(testRigPath, outputPath);
return;
}
if (_settings.getSerializeIndependent()) {
String inputPath = _settings.getSerializeVendorPath();
String outputPath = _settings.getSerializeIndependentPath();
serializeIndependentConfigs(inputPath, outputPath);
return;
}
if (_settings.getConcretize()) {
concretize();
return;
}
Map<String, StringBuilder> cpFactBins = null;
if (_settings.getFacts() || _settings.getDumpControlPlaneFacts()) {
boolean usePrecomputedFacts = _settings.getUsePrecomputedFacts();
cpFactBins = new LinkedHashMap<String, StringBuilder>();
initControlPlaneFactBins(cpFactBins, !usePrecomputedFacts);
if (!usePrecomputedFacts) {
computeControlPlaneFacts(cpFactBins);
}
action = true;
}
if (_settings.getUsePrecomputedFacts()) {
populatePrecomputedFacts(_settings.getPrecomputedFactsPath(),
cpFactBins);
}
if (_settings.getWriteRoutes()) {
writeRoutes(_settings.getPrecomputedRoutesPath());
action = true;
}
if (_settings.getWriteBgpAdvertisements()) {
writeBgpAdvertisements(_settings.getPrecomputedBgpAdvertisementsPath());
action = true;
}
if (_settings.getWriteIbgpNeighbors()) {
writeIbgpNeighbors(_settings.getPrecomputedIbgpNeighborsPath());
action = true;
}
if (_settings.revert()) {
revert();
return;
}
if (_settings.getDeleteWorkspace()) {
deleteWorkspace();
return;
}
// Create new workspace (will overwrite existing) if requested
if (_settings.createWorkspace()) {
createWorkspace();
action = true;
}
// Remove blocks if requested
if (_settings.getRemoveBlocks() || _settings.getKeepBlocks()) {
List<String> blockNames = _settings.getBlockNames();
if (_settings.getRemoveBlocks()) {
removeBlocks(blockNames);
}
if (_settings.getKeepBlocks()) {
keepBlocks(blockNames);
}
action = true;
}
// Post facts if requested
if (_settings.getFacts()) {
addStaticFacts(BASIC_FACTS_BLOCKNAME);
postFacts(cpFactBins);
return;
}
if (_settings.getQuery()) {
query();
return;
}
if (_settings.getTraceQuery()) {
traceQuery();
return;
}
if (_settings.getDataPlane()) {
computeDataPlane();
return;
}
if (_settings.getPostFlows()) {
postFlows();
action = true;
}
if (_settings.getPostDifferentialFlows()) {
postDifferentialFlows();
action = true;
}
if (_settings.getHistory()) {
getHistory();
action = true;
}
if (_settings.getDifferentialHistory()) {
getDifferentialHistory();
action = true;
}
if (_settings.getDumpTrafficFacts()) {
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
writeTrafficFacts(trafficFactBins);
dumpFacts(trafficFactBins);
return;
}
if (!action) {
throw new BatfishException(
"No task performed! Run with -help flag to see usage");
}
}
private void serializeIndependentConfigs(
Map<String, Configuration> configurations, String outputPath) {
if (configurations == null) {
throw new BatfishException("Exiting due to conversion error(s)");
}
if (!_settings.getNoOutput()) {
_logger
.info("\n*** SERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : configurations.keySet()) {
Configuration c = configurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.info("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"");
serializeObject(c, currentOutputPath.toFile());
_logger.info(" ...OK\n");
}
printElapsedTime();
}
}
private void serializeIndependentConfigs(String vendorConfigPath,
String outputPath) {
Map<String, Configuration> configurations = getConfigurations(vendorConfigPath);
serializeIndependentConfigs(configurations, outputPath);
}
private void serializeObject(Object object, File outputFile) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = new FileOutputStream(outputFile);
if (_settings.getSerializeToText()) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
oos = xstream.createObjectOutputStream(fos);
}
else {
oos = new ObjectOutputStream(fos);
}
oos.writeObject(object);
oos.close();
}
catch (IOException e) {
throw new BatfishException(
"Failed to serialize object to output file: "
+ outputFile.toString(), e);
}
}
private void serializeVendorConfigs(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
if (vendorConfigurations == null) {
throw new BatfishException("Exiting due to parser errors");
}
String nodeRolesPath = _settings.getNodeRolesPath();
if (nodeRolesPath != null) {
NodeRoleMap nodeRoles = parseNodeRoles(testRigPath);
for (Entry<String, RoleSet> nodeRolesEntry : nodeRoles.entrySet()) {
String hostname = nodeRolesEntry.getKey();
VendorConfiguration config = vendorConfigurations.get(hostname);
if (config == null) {
throw new BatfishException(
"role set assigned to non-existent node: \"" + hostname
+ "\"");
}
RoleSet roles = nodeRolesEntry.getValue();
config.setRoles(roles);
}
if (!_settings.getNoOutput()) {
_logger.info("Serializing node-roles mappings: \"" + nodeRolesPath
+ "\"...");
serializeObject(nodeRoles, new File(nodeRolesPath));
_logger.info("OK\n");
}
}
if (!_settings.getNoOutput()) {
_logger
.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : vendorConfigurations.keySet()) {
VendorConfiguration vc = vendorConfigurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.debug("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"...");
serializeObject(vc, currentOutputPath.toFile());
_logger.debug("OK\n");
}
printElapsedTime();
}
}
private Synthesizer synthesizeDataPlane(
Map<String, Configuration> configurations, File dataPlanePath) {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
_logger.info("Deserializing data plane: \"" + dataPlanePath.toString()
+ "\"...");
DataPlane dataPlane = (DataPlane) deserializeObject(dataPlanePath);
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, dataPlane,
_settings.getSimplify());
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
printElapsedTime();
return s;
}
private EdgeSet synthesizeTopology(Map<String, Configuration> configurations) {
_logger
.info("\n*** SYNTHESIZING TOPOLOGY FROM INTERFACE SUBNET INFORMATION ***\n");
resetTimer();
EdgeSet edges = new EdgeSet();
Map<Prefix, Set<NodeInterfacePair>> prefixInterfaces = new HashMap<Prefix, Set<NodeInterfacePair>>();
for (Entry<String, Configuration> e1 : configurations.entrySet()) {
String nodeName = e1.getKey();
Configuration node = e1.getValue();
for (Entry<String, Interface> e2 : node.getInterfaces().entrySet()) {
Interface iface = e2.getValue();
String ifaceName = e2.getKey();
Prefix prefix = e2.getValue().getPrefix();
if (!iface.isLoopback(node.getVendor()) && iface.getActive()
&& prefix != null && prefix.getPrefixLength() < 32) {
Prefix network = new Prefix(prefix.getNetworkAddress(),
prefix.getPrefixLength());
NodeInterfacePair pair = new NodeInterfacePair(nodeName,
ifaceName);
Set<NodeInterfacePair> interfaceBucket = prefixInterfaces
.get(network);
if (interfaceBucket == null) {
interfaceBucket = new HashSet<NodeInterfacePair>();
prefixInterfaces.put(network, interfaceBucket);
}
interfaceBucket.add(pair);
}
}
}
for (Set<NodeInterfacePair> bucket : prefixInterfaces.values()) {
for (NodeInterfacePair p1 : bucket) {
for (NodeInterfacePair p2 : bucket) {
if (!p1.equals(p2)) {
Edge edge = new Edge(p1, p2);
edges.add(edge);
}
}
}
}
return edges;
}
private void traceQuery() {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
lbFrontend.initTraceEntityTable();
Map<String, String> allPredicateNames = _predicateInfo
.getPredicateNames();
Set<String> predicateNames = new TreeSet<String>();
if (_settings.getQueryAll()) {
predicateNames.addAll(allPredicateNames.keySet());
}
else {
predicateNames.addAll(_settings.getPredicates());
}
printTracePredicates(lbFrontend, predicateNames);
// Map<Integer, Map<Long, PrecomputedRoute>> routes = lbFrontend
// .getTraceRoutes();
// Map<Integer, Map<Long, BgpAdvertisement>> adverts = lbFrontend
// .getTraceAdvertisements();
// for (int traceNumber : routes.keySet()) {
// Map<Long, PrecomputedRoute> currentRoutes = routes
// .get(traceNumber);
// for (long index : currentRoutes.keySet()) {
// PrecomputedRoute route = currentRoutes.get(index);
// _logger.output("Trace: " + traceNumber + ", " + route.toString()
// for (int traceNumber : adverts.keySet()) {
// Map<Long, BgpAdvertisement> currentAdverts = adverts
// .get(traceNumber);
// for (long index : currentAdverts.keySet()) {
// BgpAdvertisement advert = currentAdverts.get(index);
// _logger.output("Trace: " + traceNumber + ", "
// + advert.toString() + "\n");
}
private void writeBgpAdvertisements(String writeAdvertsPath) {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
File advertsFile = new File(writeAdvertsPath);
File parentDir = advertsFile.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
AdvertisementSet adverts = getAdvertisements(lbFrontend);
_logger.info("Serializing: BGP advertisements => \"" + writeAdvertsPath
+ "\"...");
serializeObject(adverts, advertsFile);
_logger.info("OK\n");
}
public void writeConfigurationFacts(
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
populateConfigurationFactBins(configurations.values(), factBins);
}
private void writeFile(String outputPath, String output) {
File outputFile = new File(outputPath);
try {
FileUtils.write(outputFile, output);
}
catch (IOException e) {
throw new BatfishException("Failed to write file: " + outputPath, e);
}
}
private void writeFlowSinkFacts(InterfaceSet flowSinks,
Map<String, StringBuilder> cpFactBins) {
StringBuilder sb = cpFactBins.get("SetFlowSinkInterface");
for (NodeInterfacePair f : flowSinks) {
String node = f.getHostname();
String iface = f.getInterface();
sb.append(node + "|" + iface + "\n");
}
}
private void writeIbgpNeighbors(String ibgpTopologyPath) {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
File ibgpTopologyFile = new File(ibgpTopologyPath);
File parentDir = ibgpTopologyFile.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
String qualifiedName = _predicateInfo.getPredicateNames().get(
IBGP_NEIGHBORS_PREDICATE_NAME);
IbgpTopology topology = lbFrontend.getIbgpNeighbors(qualifiedName);
_logger.info("Serializing: IBGP neighbors => \"" + ibgpTopologyPath
+ "\"...");
serializeObject(topology, ibgpTopologyFile);
_logger.info("OK\n");
}
private void writeRoutes(String writeRoutesPath) {
LogicBloxFrontend lbFrontend = _manager.connect();
lbFrontend.initEntityTable();
File routesFile = new File(writeRoutesPath);
File parentDir = routesFile.getParentFile();
if (parentDir != null) {
parentDir.mkdirs();
}
RouteSet routes = getRoutes(lbFrontend);
_logger.info("Serializing: routes => \"" + writeRoutesPath + "\"...");
serializeObject(routes, routesFile);
_logger.info("OK\n");
}
private void writeSynthesizedTopology() {
Map<String, Configuration> configs = loadConfigurations();
EdgeSet edges = synthesizeTopology(configs);
_logger.output(BatfishTopologyCombinedParser.HEADER + "\n");
for (Edge edge : edges) {
_logger.output(edge.getNode1() + ":" + edge.getInt1() + ","
+ edge.getNode2() + ":" + edge.getInt2() + "\n");
}
printElapsedTime();
}
private void writeTopologyFacts(Topology topology,
Map<String, StringBuilder> factBins) {
TopologyFactExtractor tfe = new TopologyFactExtractor(topology);
tfe.writeFacts(factBins);
}
private void writeTrafficFacts(Map<String, StringBuilder> factBins) {
StringBuilder wSetFlowOriginate = factBins.get("SetFlowOriginate");
RoleNodeMap roleNodes = null;
if (_settings.getRoleHeaders()) {
String nodeRolesPath = _settings.getNodeRolesPath();
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
roleNodes = nodeRoles.toRoleNodeMap();
}
parseFlowsFromConstraints(wSetFlowOriginate, roleNodes);
if (_settings.duplicateRoleFlows()) {
StringBuilder wDuplicateRoleFlows = factBins.get("DuplicateRoleFlows");
wDuplicateRoleFlows.append("1\n");
}
}
}
|
package com.github.andlyticsproject.model;
import java.text.DecimalFormat;
import java.util.Date;
public class Admob {
private String siteId;
private Integer requests = 0;
private Integer houseadRequests = 0;
private Integer interstitialRequests = 0;
private Integer impressions = 0;
private Float fillRate = .0f;
private Float houseadFillRate = .0f;
private Float overallFillRate = .0f;
private Integer clicks = 0;
private Integer houseAdClicks = 0;
private Float ctr = .0f;
private Float ecpm = .0f;
private Float revenue = .0f;
private Float cpcRevenue = .0f;
private Float cpmRevenue = .0f;
private Integer exchangeDownloads = 0;
private Date date;
private static final int XK_cent = 0x00a2; /* U+00A2 CENT SIGN */
private static final DecimalFormat centsFormatter = new DecimalFormat("0.00" + ((char) XK_cent));
public String getSiteId() {
return siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public Integer getRequests() {
return requests;
}
public void setRequests(Integer requests) {
this.requests = requests;
}
public Integer getHouseadRequests() {
return houseadRequests;
}
public void setHouseadRequests(Integer houseadRequests) {
this.houseadRequests = houseadRequests;
}
public Integer getInterstitialRequests() {
return interstitialRequests;
}
public void setInterstitialRequests(Integer interstitialRequests) {
this.interstitialRequests = interstitialRequests;
}
public Integer getImpressions() {
return impressions;
}
public void setImpressions(Integer impressions) {
this.impressions = impressions;
}
public Float getFillRate() {
return fillRate;
}
public void setFillRate(Float fillRate) {
this.fillRate = fillRate;
}
public Float getHouseadFillRate() {
return houseadFillRate;
}
public void setHouseadFillRate(Float houseadFillRate) {
this.houseadFillRate = houseadFillRate;
}
public Float getOverallFillRate() {
return overallFillRate;
}
public void setOverallFillRate(Float overallFillRate) {
this.overallFillRate = overallFillRate;
}
public Integer getClicks() {
return clicks;
}
public void setClicks(Integer clicks) {
this.clicks = clicks;
}
public Integer getHouseAdClicks() {
return houseAdClicks;
}
public void setHouseAdClicks(Integer houseAdClicks) {
this.houseAdClicks = houseAdClicks;
}
public Float getCtr() {
return ctr;
}
public void setCtr(Float ctr) {
this.ctr = ctr;
}
public Float getEcpm() {
return ecpm;
}
public String getEpcCents() {
return centsFormatter.format(getEpc());
}
public Float getEpc() {
return clicks > 0 ? (revenue * 100.f / clicks) : 0;
}
public void setEcpm(Float ecpm) {
this.ecpm = ecpm;
}
public Float getRevenue() {
return revenue;
}
public void setRevenue(Float revenue) {
this.revenue = revenue;
}
public Float getCpcRevenue() {
return cpcRevenue;
}
public void setCpcRevenue(Float cpcRevenue) {
this.cpcRevenue = cpcRevenue;
}
public Float getCpmRevenue() {
return cpmRevenue;
}
public void setCpmRevenue(Float cpmRevenue) {
this.cpmRevenue = cpmRevenue;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void setExchangeDownloads(Integer exchangeDownloads) {
this.exchangeDownloads = exchangeDownloads;
}
public Integer getExchangeDownloads() {
return exchangeDownloads;
}
}
|
package org.jetbrains.yaml.meta.impl;
import com.intellij.lang.documentation.AbstractDocumentationProvider;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLLanguage;
import org.jetbrains.yaml.meta.model.Field;
import org.jetbrains.yaml.meta.model.TypeFieldPair;
import org.jetbrains.yaml.meta.model.YamlMetaType;
import org.jetbrains.yaml.meta.model.YamlMetaType.ForcedCompletionPath;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLMapping;
import org.jetbrains.yaml.psi.YAMLPsiElement;
import org.jetbrains.yaml.psi.YAMLValue;
import java.util.Objects;
@ApiStatus.Experimental
public abstract class YamlDocumentationProviderBase extends AbstractDocumentationProvider {
@Override
@Nullable
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
return null;
}
@Override
public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
if (!(element instanceof DocumentationElement)) {
return null;
}
return ((DocumentationElement)element).getDocumentation();
}
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor,
@NotNull PsiFile file,
@Nullable PsiElement contextElement) {
if (contextElement == null || !isRelevant(contextElement)) {
return null;
}
return createFromPsiElement(contextElement);
}
@Override
public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement contextElement) {
if (object instanceof ForcedCompletionPath) { // deep completion
return createFromCompletionPath((ForcedCompletionPath)object, contextElement);
}
else if (object instanceof TypeFieldPair) { // basic completion with Field object
return createFromField((TypeFieldPair)object, contextElement);
}
else if (object instanceof String) { // basic completion with plain string
return createFromString((String)object, contextElement);
}
else {
return null;
}
}
protected abstract boolean isRelevant(@NotNull PsiElement element);
/**
* Provides documentation for the specified type and field.
* If the field isn't given, only the documentation for the type should be returned.
*/
@Nullable
protected abstract String getDocumentation(@NotNull Project project, @NotNull YamlMetaType type, @Nullable Field field);
@Nullable
protected abstract YamlMetaTypeProvider getMetaTypeProvider(@NotNull PsiElement element);
@Nullable
private static <T extends PsiElement> T getTypedAncestorOrSelf(@NotNull PsiElement psi, @NotNull Class<? extends T> clazz) {
return clazz.isInstance(psi) ? clazz.cast(psi) : PsiTreeUtil.getParentOfType(psi, clazz);
}
@Nullable
private DocumentationElement createFromPsiElement(@Nullable PsiElement contextElement) {
if (contextElement == null) {
return null;
}
final YamlMetaTypeProvider modelProvider = getMetaTypeProvider(contextElement);
if (modelProvider == null) {
return null;
}
YAMLPsiElement yamlElement = getTypedAncestorOrSelf(contextElement, YAMLPsiElement.class);
if (yamlElement == null) {
return null;
}
final YamlMetaTypeProvider.MetaTypeProxy objectMetatype; // describes the object type
YamlMetaTypeProvider.MetaTypeProxy fieldMetatype; // describes the field
if (yamlElement instanceof YAMLValue) {
fieldMetatype = modelProvider.getMetaTypeProxy(yamlElement);
final YAMLMapping mapping = getTypedAncestorOrSelf(yamlElement, YAMLMapping.class);
objectMetatype = mapping != null ? modelProvider.getMetaTypeProxy(mapping) : null;
// if the element is the value of the key "kind" and there is a "apiVersion" key in the same mapping,
// then we show documentation for the resource type, not the field
if (mapping != null &&
fieldMetatype != null &&
fieldMetatype.getField().getName().equals("kind") &&
mapping.getKeyValues().stream().anyMatch(kv -> "apiVersion".equals(kv.getKeyText().trim()))) {
fieldMetatype = null;
}
}
else if (yamlElement instanceof YAMLKeyValue) {
objectMetatype = modelProvider.getMetaTypeProxy(yamlElement);
fieldMetatype = modelProvider.getKeyValueMetaType((YAMLKeyValue)yamlElement);
}
else {
objectMetatype = modelProvider.getMetaTypeProxy(yamlElement);
fieldMetatype = null;
}
if (objectMetatype == null) {
return null;
}
return new DocumentationElement(contextElement.getManager(),
objectMetatype.getMetaType(),
fieldMetatype != null ? fieldMetatype.getField() : null);
}
@Nullable
private DocumentationElement createFromCompletionPath(@NotNull ForcedCompletionPath path, @NotNull PsiElement contextElement) {
final YamlMetaTypeProvider typeProvider = getMetaTypeProvider(contextElement);
if (typeProvider == null) {
return null;
}
final Field field = path.getFinalizingField();
if (field == null) {
return null;
}
YamlMetaType type = path.getFinalizingType();
if (type == null) {
final YamlMetaTypeProvider.MetaTypeProxy proxy = typeProvider.getMetaTypeProxy(contextElement);
if (proxy == null) {
return null;
}
type = proxy.getMetaType();
}
return new DocumentationElement(contextElement.getManager(), type, field);
}
@Nullable
private DocumentationElement createFromString(@NotNull String fieldName, @NotNull PsiElement contextElement) {
final YamlMetaTypeProvider typeProvider = getMetaTypeProvider(contextElement);
if (typeProvider == null) {
return null;
}
final YamlMetaTypeProvider.MetaTypeProxy proxy = typeProvider.getMetaTypeProxy(contextElement);
if (proxy == null) {
return null;
}
final Field field = proxy.getMetaType().findFeatureByName(fieldName);
if (field == null) {
return null;
}
return new DocumentationElement(contextElement.getManager(), proxy.getMetaType(), field);
}
@NotNull
private DocumentationElement createFromField(@NotNull TypeFieldPair field, @NotNull PsiElement contextElement) {
return new DocumentationElement(contextElement.getManager(), field.getMetaType(), field.getField());
}
private class DocumentationElement extends LightElement {
@NotNull private final Project myProject;
@NotNull private final YamlMetaType myType;
@Nullable private final Field myField;
public DocumentationElement(@NotNull PsiManager manager,
@NotNull YamlMetaType type,
@Nullable Field field) {
super(manager, YAMLLanguage.INSTANCE);
myProject = manager.getProject();
myType = type;
myField = field;
}
@Override
public String toString() {
return "DocumentationElement: " + myType + "#" + myField;
}
@Override
public String getText() {
return myField != null
? myField.getName() + " : " + myField.getDefaultType().getDisplayName()
: myType.getDisplayName(); // todo replace with rich presentation
}
@Nullable
public String getDocumentation() {
return YamlDocumentationProviderBase.this.getDocumentation(myProject, myType, myField);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DocumentationElement element = (DocumentationElement)o;
return Objects.equals(myProject, element.myProject) &&
Objects.equals(myType, element.myType) &&
Objects.equals(myField, element.myField);
}
@Override
public int hashCode() {
return Objects.hash(myProject, myType, myField);
}
}
}
|
package com.maddyhome.idea.vim.ex;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.common.Register;
import com.maddyhome.idea.vim.ex.handler.CmdFilterHandler;
import com.maddyhome.idea.vim.ex.handler.CopyTextHandler;
import com.maddyhome.idea.vim.ex.handler.DeleteLinesHandler;
import com.maddyhome.idea.vim.ex.handler.DumpLineHandler;
import com.maddyhome.idea.vim.ex.handler.EditFileHandler;
import com.maddyhome.idea.vim.ex.handler.ExitHandler;
import com.maddyhome.idea.vim.ex.handler.FindClassHandler;
import com.maddyhome.idea.vim.ex.handler.FindFileHandler;
import com.maddyhome.idea.vim.ex.handler.GotoCharacterHandler;
import com.maddyhome.idea.vim.ex.handler.GotoLineHandler;
import com.maddyhome.idea.vim.ex.handler.HelpHandler;
import com.maddyhome.idea.vim.ex.handler.JoinLinesHandler;
import com.maddyhome.idea.vim.ex.handler.MarkHandler;
import com.maddyhome.idea.vim.ex.handler.MarksHandler;
import com.maddyhome.idea.vim.ex.handler.MoveTextHandler;
import com.maddyhome.idea.vim.ex.handler.NextFileHandler;
import com.maddyhome.idea.vim.ex.handler.OnlyHandler;
import com.maddyhome.idea.vim.ex.handler.PreviousFileHandler;
import com.maddyhome.idea.vim.ex.handler.PromptFindHandler;
import com.maddyhome.idea.vim.ex.handler.PromptReplaceHandler;
import com.maddyhome.idea.vim.ex.handler.PutLinesHandler;
import com.maddyhome.idea.vim.ex.handler.QuitHandler;
import com.maddyhome.idea.vim.ex.handler.RedoHandler;
import com.maddyhome.idea.vim.ex.handler.RegistersHandler;
import com.maddyhome.idea.vim.ex.handler.RepeatHandler;
import com.maddyhome.idea.vim.ex.handler.SelectFileHandler;
import com.maddyhome.idea.vim.ex.handler.SelectFirstFileHandler;
import com.maddyhome.idea.vim.ex.handler.SelectLastFileHandler;
import com.maddyhome.idea.vim.ex.handler.SetHandler;
import com.maddyhome.idea.vim.ex.handler.ShiftLeftHandler;
import com.maddyhome.idea.vim.ex.handler.ShiftRightHandler;
import com.maddyhome.idea.vim.ex.handler.SubstituteHandler;
import com.maddyhome.idea.vim.ex.handler.UndoHandler;
import com.maddyhome.idea.vim.ex.handler.WriteAllHandler;
import com.maddyhome.idea.vim.ex.handler.WriteHandler;
import com.maddyhome.idea.vim.ex.handler.WriteNextFileHandler;
import com.maddyhome.idea.vim.ex.handler.WritePreviousFileHandler;
import com.maddyhome.idea.vim.ex.handler.WriteQuitHandler;
import com.maddyhome.idea.vim.ex.handler.YankLinesHandler;
import com.maddyhome.idea.vim.ex.handler.FindSymbolHandler;
import com.maddyhome.idea.vim.ex.range.AbstractRange;
import com.maddyhome.idea.vim.group.CommandGroups;
import com.maddyhome.idea.vim.helper.MessageHelper;
import com.maddyhome.idea.vim.helper.Msg;
/**
* Maintains a tree of Ex commands based on the required and optional parts of the command names. Parses and
* executes Ex commands entered by the user.
*/
public class CommandParser
{
/**
* There is only one parser.
* @return The singleton instance
*/
public synchronized static CommandParser getInstance()
{
if (ourInstance == null)
{
ourInstance = new CommandParser();
}
return ourInstance;
}
/**
* Don't let anyone create one of these.
*/
private CommandParser()
{
}
/**
* Registers all the supported Ex commands
*/
public void registerHandlers()
{
new CmdFilterHandler();
new CopyTextHandler();
new DeleteLinesHandler();
new DumpLineHandler();
new EditFileHandler();
new ExitHandler();
new FindClassHandler();
new FindFileHandler();
new FindSymbolHandler();
new GotoCharacterHandler();
//new GotoLineHandler(); - not needed here
new HelpHandler();
new JoinLinesHandler();
new MarkHandler();
new MarksHandler();
new MoveTextHandler();
new NextFileHandler();
new OnlyHandler();
new PreviousFileHandler();
new PromptFindHandler();
new PromptReplaceHandler();
new PutLinesHandler();
new QuitHandler();
new RedoHandler();
new RegistersHandler();
new RepeatHandler();
new SelectFileHandler();
new SelectFirstFileHandler();
new SelectLastFileHandler();
new SetHandler();
new ShiftLeftHandler();
new ShiftRightHandler();
new SubstituteHandler();
new UndoHandler();
new WriteAllHandler();
new WriteHandler();
new WriteNextFileHandler();
new WritePreviousFileHandler();
new WriteQuitHandler();
new YankLinesHandler();
}
/**
* Used to rerun the last Ex command, if any
* @param editor The editor to run the command in
* @param context The data context
* @param count The number of times to run the command
* @return True if the command succeeded, false if it failed or there was no previous command
* @throws ExException if any part of the command was invalid
*/
public boolean processLastCommand(Editor editor, DataContext context, int count) throws ExException
{
Register reg = CommandGroups.getInstance().getRegister().getRegister(':');
if (reg == null)
{
return false;
}
processCommand(editor, context, reg.getText(), count);
return true;
}
/**
* Parse and execute an Ex command entered by the user
* @param editor The editor to run the command in
* @param context The data context
* @param cmd The text entered by the user
* @param count The count entered before the colon
* @throws ExException if any part of the command is invalid or unknown
*/
public void processCommand(Editor editor, DataContext context, String cmd, int count) throws ExException
{
// Nothing entered
if (cmd.length() == 0)
{
return;
}
// Parse the command
ParseResult res = parse(cmd);
String command = res.getCommand();
// If there is no command, just a range, use the 'goto line' handler
CommandHandler handler = null;
if (command.length() == 0)
{
handler = new GotoLineHandler();
}
else
{
// See if the user entered a supported command by checking each character entered
CommandNode node = root;
for (int i = 0; i < command.length(); i++)
{
node = node.getChild(command.charAt(i));
if (node == null)
{
MessageHelper.EMSG(Msg.NOT_EX_CMD, command);
// No such command
throw new InvalidCommandException(cmd);
}
}
// We found a valid command
handler = node.getCommandHandler();
}
if (handler == null)
{
MessageHelper.EMSG(Msg.NOT_EX_CMD, command);
throw new InvalidCommandException(cmd);
}
if ((handler.getArgFlags() & CommandHandler.WRITABLE) > 0 && !editor.getDocument().isWritable())
{
VimPlugin.indicateError();
return;
}
// Run the command
handler.process(editor, context, new ExCommand(res.getRanges(), command, res.getArgument()), count);
if ((handler.getArgFlags() & CommandHandler.DONT_SAVE_LAST) == 0)
{
CommandGroups.getInstance().getRegister().storeTextInternal(editor, context, -1, -1, cmd,
Command.FLAG_MOT_CHARACTERWISE, ':', false, false);
}
}
/**
* Parse the text entered by the user. This does not include the leading colon.
* @param cmd The user entered text
* @return The parse result
* @throws ExException if the text is syntactically incorrect
*/
public ParseResult parse(String cmd) throws ExException
{
// This is a complicated state machine that should probably be rewritten
logger.debug("processing `" + cmd + "'");
int state = STATE_START;
Ranges ranges = new Ranges(); // The list of ranges
StringBuffer command = new StringBuffer(); // The command
StringBuffer argument = new StringBuffer(); // The command's argument(s)
StringBuffer location = null; // The current range text
int offsetSign = 1; // Sign of current range offset
int offsetNumber = 0; // The value of the current range offset
int offsetTotal = 0; // The sum of all the current range offsets
boolean move = false; // , vs. ; separated ranges (true=; false=,)
char patternType = 0;
int backCount = 0; // Number of backslashes in a row in a pattern
boolean inBrackets = false; // If inside [ ] range in a pattern
String error = "";
// Loop through each character. Treat the end of the string as a newline character
for (int i = 0; i <= cmd.length(); i++)
{
boolean reprocess = true; // Should the current character be reprocessed after a state change?
char ch = (i == cmd.length() ? '\n' : cmd.charAt(i));
while (reprocess)
{
switch (state)
{
case STATE_START: // Very start of the entered text
if (Character.isLetter(ch) || "~<>@=#*&!".indexOf(ch) >= 0)
{
state = STATE_COMMAND;
}
else
{
state = STATE_RANGE;
}
break;
case STATE_COMMAND: // Reading the actual command name
// For commands that start with a non-letter, treat other non-letter characters as part of
// the argument except for < or >
if (Character.isLetter(ch) ||
(command.length() == 0 && "~<>@=#*&!".indexOf(ch) >= 0) ||
(command.length() > 0 && ch == command.charAt(command.length() - 1) &&
"<>".indexOf(ch) >= 0))
{
command.append(ch);
reprocess = false;
if (!Character.isLetter(ch))
{
state = STATE_CMD_ARG;
}
}
else
{
state = STATE_CMD_ARG;
}
break;
case STATE_CMD_ARG: // Reading the command's argument
argument.append(ch);
reprocess = false;
break;
case STATE_RANGE: // Starting a new range
location = new StringBuffer();
offsetTotal = 0;
offsetNumber = 0;
move = false;
if (ch >= '0' && ch <= '9')
{
state = STATE_RANGE_LINE;
}
else if (ch == '.')
{
state = STATE_RANGE_CURRENT;
}
else if (ch == '$')
{
state = STATE_RANGE_LAST;
}
else if (ch == '%')
{
state = STATE_RANGE_ALL;
}
else if (ch == '\'')
{
state = STATE_RANGE_MARK;
}
else if (ch == '+' || ch == '-')
{
location.append('0');
state = STATE_RANGE_OFFSET;
}
else if (ch == '\\')
{
location.append(ch);
state = STATE_RANGE_SHORT_PATTERN;
reprocess = false;
}
else if (ch == '/' || ch == '?')
{
location.append(ch);
patternType = ch;
backCount = 0;
inBrackets = false;
state = STATE_RANGE_PATTERN;
reprocess = false;
}
else
{
error = MessageHelper.getMsg(Msg.e_badrange, Character.toString(ch));
state = STATE_ERROR;
reprocess = false;
}
break;
case STATE_RANGE_SHORT_PATTERN: // Handle \/, \?, and \& patterns
if (ch == '/' || ch == '?' || ch == '&')
{
location.append(ch);
state = STATE_RANGE_PATTERN_MAYBE_DONE;
reprocess = false;
}
else
{
error = MessageHelper.getMsg(Msg.e_backslash);
state = STATE_ERROR;
reprocess = false;
}
break;
case STATE_RANGE_PATTERN: // Reading a pattern range
// No trailing / or ? required if there is no command so look for newline to tell us we are done
if (ch == '\n')
{
location.append(patternType);
state = STATE_RANGE_MAYBE_DONE;
}
else
{
// We need to skip over [ ] ranges. The ] is valid right after the [ or [^
location.append(ch);
if (ch == '[' && !inBrackets)
{
inBrackets = true;
}
else if (ch == ']' && inBrackets && !(location.charAt(location.length() - 2) == '[' ||
(location.length() >= 3 && location.substring(location.length() - 3).equals("[^]"))))
{
inBrackets = false;
}
// Keep count of the backslashes
else if (ch == '\\')
{
backCount++;
}
// Does this mark the end of the current pattern? True if we found the matching / or ?
// and it is not preceded by an even number of backslashes
else if (ch == patternType && !inBrackets &&
(location.charAt(location.length() - 2) != '\\' || backCount % 2 == 0))
{
state = STATE_RANGE_PATTERN_MAYBE_DONE;
}
// No more backslashes
if (ch != '\\')
{
backCount = 0;
}
reprocess = false;
}
break;
case STATE_RANGE_PATTERN_MAYBE_DONE: // Check to see if there is another immediate pattern
if (ch == '/' || ch == '?')
{
// Use a special character to separate pattern for later, easier, parsing
location.append('\u0000');
location.append(ch);
patternType = ch;
backCount = 0;
inBrackets = false;
state = STATE_RANGE_PATTERN;
reprocess = false;
}
else
{
state = STATE_RANGE_MAYBE_DONE;
}
break;
case STATE_RANGE_LINE: // Explicit line number
if (ch >= '0' && ch <= '9')
{
location.append(ch);
state = STATE_RANGE_MAYBE_DONE;
reprocess = false;
}
else
{
state = STATE_RANGE_MAYBE_DONE;
}
break;
case STATE_RANGE_CURRENT: // Current line - .
location.append(ch);
state = STATE_RANGE_MAYBE_DONE;
reprocess = false;
break;
case STATE_RANGE_LAST: // Last line - $
location.append(ch);
state = STATE_RANGE_MAYBE_DONE;
reprocess = false;
break;
case STATE_RANGE_ALL: // All lines - %
location.append(ch);
state = STATE_RANGE_MAYBE_DONE;
reprocess = false;
break;
case STATE_RANGE_MARK: // Mark line - 'x
location.append(ch);
state = STATE_RANGE_MARK_CHAR;
reprocess = false;
break;
case STATE_RANGE_MARK_CHAR: // Actual mark
location.append(ch);
state = STATE_RANGE_MAYBE_DONE;
reprocess = false;
break;
case STATE_RANGE_DONE: // We have hit the end of a range - process it
Range[] range = AbstractRange.createRange(location.toString(), offsetTotal, move);
ranges.addRange(range);
// Could there be more ranges - nope - at end, start command
if (ch == ':' || ch == '\n')
{
state = STATE_COMMAND;
reprocess = false;
}
// Start of command
else if (Character.isLetter(ch) || "~<>@=#*&!".indexOf(ch) >= 0)
{
state = STATE_COMMAND;
}
// We have another range
else
{
state = STATE_RANGE;
}
break;
case STATE_RANGE_MAYBE_DONE: // Are we done with the current range?
// The range has an offset after it
if (ch == '+' || ch == '-')
{
state = STATE_RANGE_OFFSET;
}
// End of the range - we found a separator
else if (ch == ',' || ch == ';')
{
state = STATE_RANGE_SEPARATOR;
}
// Part of a line number
else if (ch >= '0' && ch <= '9')
{
state = STATE_RANGE_LINE;
}
// No more range
else
{
state = STATE_RANGE_DONE;
}
break;
case STATE_RANGE_OFFSET: // Offset after a range
// Figure out the sign of the offset and reset the offset value
offsetNumber = 0;
if (ch == '+')
{
offsetSign = 1;
}
else if (ch == '-')
{
offsetSign = -1;
}
state = STATE_RANGE_OFFSET_MAYBE_DONE;
reprocess = false;
break;
case STATE_RANGE_OFFSET_MAYBE_DONE: // Are we done with the offset?
// We found an offset value
if (ch >= '0' && ch <= '9')
{
state = STATE_RANGE_OFFSET_NUM;
}
// Yes, offset done
else
{
state = STATE_RANGE_OFFSET_DONE;
}
break;
case STATE_RANGE_OFFSET_DONE: // At the end of a range offset
// No number implies a one
if (offsetNumber == 0)
{
offsetNumber = 1;
}
// Update offset total for this range
offsetTotal += offsetNumber * offsetSign;
// Another offset
if (ch == '+' || ch == '-')
{
state = STATE_RANGE_OFFSET;
}
// No more offsets for this range
else
{
state = STATE_RANGE_MAYBE_DONE;
}
break;
case STATE_RANGE_OFFSET_NUM: // An offset number
// Update the value of the current offset
if (ch >= '0' && ch <= '9')
{
offsetNumber = offsetNumber * 10 + (ch - '0');
state = STATE_RANGE_OFFSET_MAYBE_DONE;
reprocess = false;
}
// Found the start of a new offset
else if (ch == '+' || ch == '-')
{
state = STATE_RANGE_OFFSET_DONE;
}
else
{
state = STATE_RANGE_OFFSET_MAYBE_DONE;
}
break;
case STATE_RANGE_SEPARATOR: // Found a range separator
if (ch == ',')
{
move = false;
}
else if (ch == ';')
{
move = true;
}
state = STATE_RANGE_DONE;
reprocess = false;
break;
}
}
// Oops - bad command string
if (state == STATE_ERROR)
{
VimPlugin.showMessage(error);
throw new InvalidCommandException(cmd);
}
}
logger.debug("ranges = " + ranges);
logger.debug("command = " + command);
logger.debug("argument = " + argument);
return new ParseResult(ranges, command.toString(), argument.toString().trim());
}
/**
* Adds a command handler to the parser
* @param handler The new handler to add
*/
public void addHandler(CommandHandler handler)
{
// Iterator through each command name alias
CommandName[] names = handler.getNames();
for (int c = 0; c < names.length; c++)
{
CommandNode node = root;
String text = names[c].getRequired();
// Build a tree for each character in the required portion of the command name
for (int i = 0; i < text.length() - 1; i++)
{
CommandNode cn = node.getChild(text.charAt(i));
if (cn == null)
{
cn = node.addChild(text.charAt(i), null);
}
node = cn;
}
// For the last character we need to add the actual handler
CommandNode cn = node.getChild(text.charAt(text.length() - 1));
if (cn == null)
{
cn = node.addChild(text.charAt(text.length() - 1), handler);
}
else
{
cn.setCommandHandler(handler);
}
node = cn;
// Now add the handler for each character in the optional portion of the command name
text = names[c].getOptional();
for (int i = 0; i < text.length(); i++)
{
cn = node.getChild(text.charAt(i));
if (cn == null)
{
cn = node.addChild(text.charAt(i), handler);
}
node = cn;
}
}
}
private CommandNode root = new CommandNode();
private static CommandParser ourInstance;
private static final int STATE_START = 1;
private static final int STATE_COMMAND = 10;
private static final int STATE_CMD_ARG = 11;
private static final int STATE_RANGE = 20;
private static final int STATE_RANGE_LINE = 21;
private static final int STATE_RANGE_CURRENT = 22;
private static final int STATE_RANGE_LAST = 23;
private static final int STATE_RANGE_MARK = 24;
private static final int STATE_RANGE_MARK_CHAR = 25;
private static final int STATE_RANGE_ALL = 26;
private static final int STATE_RANGE_PATTERN = 27;
private static final int STATE_RANGE_SHORT_PATTERN = 28;
private static final int STATE_RANGE_PATTERN_MAYBE_DONE = 29;
private static final int STATE_RANGE_OFFSET = 30;
private static final int STATE_RANGE_OFFSET_NUM = 31;
private static final int STATE_RANGE_OFFSET_DONE = 32;
private static final int STATE_RANGE_OFFSET_MAYBE_DONE = 33;
private static final int STATE_RANGE_SEPARATOR = 40;
private static final int STATE_RANGE_MAYBE_DONE = 50;
private static final int STATE_RANGE_DONE = 51;
private static final int STATE_ERROR = 99;
private static Logger logger = Logger.getInstance(CommandParser.class.getName());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.