gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.zeppelin.jdbc;
import static java.lang.String.format;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.DEFAULT_DRIVER;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.DEFAULT_PASSWORD;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.DEFAULT_USER;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.DEFAULT_URL;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.DEFAULT_PRECODE;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.PRECODE_KEY_TEMPLATE;
import static org.apache.zeppelin.jdbc.JDBCInterpreter.COMMON_MAX_LINE;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.zeppelin.completer.CompletionType;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.apache.zeppelin.scheduler.FIFOScheduler;
import org.apache.zeppelin.scheduler.ParallelScheduler;
import org.apache.zeppelin.scheduler.Scheduler;
import org.apache.zeppelin.user.AuthenticationInfo;
import org.apache.zeppelin.user.UserCredentials;
import org.apache.zeppelin.user.UsernamePassword;
import org.junit.Before;
import org.junit.Test;
import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter;
/**
* JDBC interpreter unit tests
*/
public class JDBCInterpreterTest extends BasicJDBCTestCaseAdapter {
static String jdbcConnection;
InterpreterContext interpreterContext;
private static String getJdbcConnection() throws IOException {
if(null == jdbcConnection) {
Path tmpDir = Files.createTempDirectory("h2-test-");
tmpDir.toFile().deleteOnExit();
jdbcConnection = format("jdbc:h2:%s", tmpDir);
}
return jdbcConnection;
}
public static Properties getJDBCTestProperties() {
Properties p = new Properties();
p.setProperty("default.driver", "org.postgresql.Driver");
p.setProperty("default.url", "jdbc:postgresql://localhost:5432/");
p.setProperty("default.user", "gpadmin");
p.setProperty("default.password", "");
p.setProperty("common.max_count", "1000");
return p;
}
@Before
public void setUp() throws Exception {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(getJdbcConnection());
Statement statement = connection.createStatement();
statement.execute(
"DROP TABLE IF EXISTS test_table; " +
"CREATE TABLE test_table(id varchar(255), name varchar(255));");
PreparedStatement insertStatement = connection.prepareStatement("insert into test_table(id, name) values ('a', 'a_name'),('b', 'b_name'),('c', ?);");
insertStatement.setString(1, null);
insertStatement.execute();
interpreterContext = new InterpreterContext("", "1", null, "", "", new AuthenticationInfo(), null, null, null, null,
null, null);
}
@Test
public void testForParsePropertyKey() throws IOException {
JDBCInterpreter t = new JDBCInterpreter(new Properties());
assertEquals(t.getPropertyKey("(fake) select max(cant) from test_table where id >= 2452640"),
"fake");
assertEquals(t.getPropertyKey("() select max(cant) from test_table where id >= 2452640"),
"");
assertEquals(t.getPropertyKey(")fake( select max(cant) from test_table where id >= 2452640"),
"default");
// when you use a %jdbc(prefix1), prefix1 is the propertyKey as form part of the cmd string
assertEquals(t.getPropertyKey("(prefix1)\n select max(cant) from test_table where id >= 2452640"),
"prefix1");
assertEquals(t.getPropertyKey("(prefix2) select max(cant) from test_table where id >= 2452640"),
"prefix2");
// when you use a %jdbc, prefix is the default
assertEquals(t.getPropertyKey("select max(cant) from test_table where id >= 2452640"),
"default");
}
@Test
public void testForMapPrefix() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "(fake) select * from test_table";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
// if prefix not found return ERROR and Prefix not found.
assertEquals(InterpreterResult.Code.ERROR, interpreterResult.code());
assertEquals("Prefix not found.", interpreterResult.message().get(0).getData());
}
@Test
public void testDefaultProperties() throws SQLException {
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(getJDBCTestProperties());
assertEquals("org.postgresql.Driver", jdbcInterpreter.getProperty(DEFAULT_DRIVER));
assertEquals("jdbc:postgresql://localhost:5432/", jdbcInterpreter.getProperty(DEFAULT_URL));
assertEquals("gpadmin", jdbcInterpreter.getProperty(DEFAULT_USER));
assertEquals("", jdbcInterpreter.getProperty(DEFAULT_PASSWORD));
assertEquals("1000", jdbcInterpreter.getProperty(COMMON_MAX_LINE));
}
@Test
public void testSelectQuery() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "select * from test_table WHERE ID in ('a', 'b')";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("ID\tNAME\na\ta_name\nb\tb_name\n", interpreterResult.message().get(0).getData());
}
@Test
public void testSplitSqlQuery() throws SQLException, IOException {
String sqlQuery = "insert into test_table(id, name) values ('a', ';\"');" +
"select * from test_table;" +
"select * from test_table WHERE ID = \";'\";" +
"select * from test_table WHERE ID = ';'";
Properties properties = new Properties();
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
ArrayList<String> multipleSqlArray = t.splitSqlQueries(sqlQuery);
assertEquals(4, multipleSqlArray.size());
assertEquals("insert into test_table(id, name) values ('a', ';\"')", multipleSqlArray.get(0));
assertEquals("select * from test_table", multipleSqlArray.get(1));
assertEquals("select * from test_table WHERE ID = \";'\"", multipleSqlArray.get(2));
assertEquals("select * from test_table WHERE ID = ';'", multipleSqlArray.get(3));
}
@Test
public void testSelectMultipleQuries() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "select * from test_table;" +
"select * from test_table WHERE ID = ';';";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(2, interpreterResult.message().size());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("ID\tNAME\na\ta_name\nb\tb_name\nc\tnull\n", interpreterResult.message().get(0).getData());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(1).getType());
assertEquals("ID\tNAME\n", interpreterResult.message().get(1).getData());
}
@Test
public void testSelectQueryWithNull() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "select * from test_table WHERE ID = 'c'";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("ID\tNAME\nc\tnull\n", interpreterResult.message().get(0).getData());
}
@Test
public void testSelectQueryMaxResult() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "select * from test_table";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("ID\tNAME\na\ta_name\n", interpreterResult.message().get(0).getData());
assertEquals(InterpreterResult.Type.HTML, interpreterResult.message().get(1).getType());
assertTrue(interpreterResult.message().get(1).getData().contains("alert-warning"));
}
@Test
public void concurrentSettingTest() {
Properties properties = new Properties();
properties.setProperty("zeppelin.jdbc.concurrent.use", "true");
properties.setProperty("zeppelin.jdbc.concurrent.max_connection", "10");
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties);
assertTrue(jdbcInterpreter.isConcurrentExecution());
assertEquals(10, jdbcInterpreter.getMaxConcurrentConnection());
Scheduler scheduler = jdbcInterpreter.getScheduler();
assertTrue(scheduler instanceof ParallelScheduler);
properties.clear();
properties.setProperty("zeppelin.jdbc.concurrent.use", "false");
jdbcInterpreter = new JDBCInterpreter(properties);
assertFalse(jdbcInterpreter.isConcurrentExecution());
scheduler = jdbcInterpreter.getScheduler();
assertTrue(scheduler instanceof FIFOScheduler);
}
@Test
public void testAutoCompletion() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties);
jdbcInterpreter.open();
jdbcInterpreter.interpret("", interpreterContext);
List<InterpreterCompletion> completionList = jdbcInterpreter.completion("sel", 3, null);
InterpreterCompletion correctCompletionKeyword = new InterpreterCompletion("select ", "select ", CompletionType.keyword.name());
assertEquals(1, completionList.size());
assertEquals(true, completionList.contains(correctCompletionKeyword));
}
private Properties getDBProperty(String dbUser, String dbPassowrd) throws IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
if (dbUser != null) {
properties.setProperty("default.user", dbUser);
}
if (dbPassowrd != null) {
properties.setProperty("default.password", dbPassowrd);
}
return properties;
}
private AuthenticationInfo getUserAuth(String user, String entityName, String dbUser, String dbPassword){
UserCredentials userCredentials = new UserCredentials();
if (entityName != null && dbUser != null && dbPassword != null) {
UsernamePassword up = new UsernamePassword(dbUser, dbPassword);
userCredentials.putUsernamePassword(entityName, up);
}
AuthenticationInfo authInfo = new AuthenticationInfo();
authInfo.setUserCredentials(userCredentials);
authInfo.setUser(user);
return authInfo;
}
@Test
public void testMultiTenant() throws SQLException, IOException {
/**
* assume that the database user is 'dbuser' and password is 'dbpassword'
* 'jdbc1' interpreter has user('dbuser')/password('dbpassword') property
* 'jdbc2' interpreter doesn't have user/password property
* 'user1' doesn't have Credential information.
* 'user2' has 'jdbc2' Credential information that is same with database account.
*/
JDBCInterpreter jdbc1 = new JDBCInterpreter(getDBProperty("dbuser", "dbpassword"));
JDBCInterpreter jdbc2 = new JDBCInterpreter(getDBProperty(null, null));
AuthenticationInfo user1Credential = getUserAuth("user1", null, null, null);
AuthenticationInfo user2Credential = getUserAuth("user2", "jdbc.jdbc2", "dbuser", "dbpassword");
// user1 runs jdbc1
jdbc1.open();
InterpreterContext ctx1 = new InterpreterContext("", "1", "jdbc.jdbc1", "", "", user1Credential,
null, null, null, null, null, null);
jdbc1.interpret("", ctx1);
JDBCUserConfigurations user1JDBC1Conf = jdbc1.getJDBCConfiguration("user1");
assertEquals("dbuser", user1JDBC1Conf.getPropertyMap("default").get("user"));
assertEquals("dbpassword", user1JDBC1Conf.getPropertyMap("default").get("password"));
jdbc1.close();
// user1 runs jdbc2
jdbc2.open();
InterpreterContext ctx2 = new InterpreterContext("", "1", "jdbc.jdbc2", "", "", user1Credential,
null, null, null, null, null, null);
jdbc2.interpret("", ctx2);
JDBCUserConfigurations user1JDBC2Conf = jdbc2.getJDBCConfiguration("user1");
assertNull(user1JDBC2Conf.getPropertyMap("default").get("user"));
assertNull(user1JDBC2Conf.getPropertyMap("default").get("password"));
jdbc2.close();
// user2 runs jdbc1
jdbc1.open();
InterpreterContext ctx3 = new InterpreterContext("", "1", "jdbc.jdbc1", "", "", user2Credential,
null, null, null, null, null, null);
jdbc1.interpret("", ctx3);
JDBCUserConfigurations user2JDBC1Conf = jdbc1.getJDBCConfiguration("user2");
assertEquals("dbuser", user2JDBC1Conf.getPropertyMap("default").get("user"));
assertEquals("dbpassword", user2JDBC1Conf.getPropertyMap("default").get("password"));
jdbc1.close();
// user2 runs jdbc2
jdbc2.open();
InterpreterContext ctx4 = new InterpreterContext("", "1", "jdbc.jdbc2", "", "", user2Credential,
null, null, null, null, null, null);
jdbc2.interpret("", ctx4);
JDBCUserConfigurations user2JDBC2Conf = jdbc2.getJDBCConfiguration("user2");
assertNull(user2JDBC2Conf.getPropertyMap("default").get("user"));
assertNull(user2JDBC2Conf.getPropertyMap("default").get("password"));
jdbc2.close();
}
@Test
public void testPrecode() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
properties.setProperty(DEFAULT_PRECODE, "SET @testVariable=1");
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties);
jdbcInterpreter.open();
String sqlQuery = "select @testVariable";
InterpreterResult interpreterResult = jdbcInterpreter.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("@TESTVARIABLE\n1\n", interpreterResult.message().get(0).getData());
}
@Test
public void testIncorrectPrecode() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
properties.setProperty(DEFAULT_PRECODE, "incorrect command");
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties);
jdbcInterpreter.open();
String sqlQuery = "select 1";
InterpreterResult interpreterResult = jdbcInterpreter.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.ERROR, interpreterResult.code());
assertEquals(InterpreterResult.Type.TEXT, interpreterResult.message().get(0).getType());
}
@Test
public void testPrecodeWithAnotherPrefix() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("anotherPrefix.driver", "org.h2.Driver");
properties.setProperty("anotherPrefix.url", getJdbcConnection());
properties.setProperty("anotherPrefix.user", "");
properties.setProperty("anotherPrefix.password", "");
properties.setProperty(String.format(PRECODE_KEY_TEMPLATE, "anotherPrefix"), "SET @testVariable=2");
JDBCInterpreter jdbcInterpreter = new JDBCInterpreter(properties);
jdbcInterpreter.open();
String sqlQuery = "(anotherPrefix) select @testVariable";
InterpreterResult interpreterResult = jdbcInterpreter.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(InterpreterResult.Type.TABLE, interpreterResult.message().get(0).getType());
assertEquals("@TESTVARIABLE\n2\n", interpreterResult.message().get(0).getData());
}
@Test
public void testExcludingComments() throws SQLException, IOException {
Properties properties = new Properties();
properties.setProperty("common.max_count", "1000");
properties.setProperty("common.max_retry", "3");
properties.setProperty("default.driver", "org.h2.Driver");
properties.setProperty("default.url", getJdbcConnection());
properties.setProperty("default.user", "");
properties.setProperty("default.password", "");
JDBCInterpreter t = new JDBCInterpreter(properties);
t.open();
String sqlQuery = "/* ; */\n" +
"-- /* comment\n" +
"--select * from test_table\n" +
"select * from test_table; /* some comment ; */\n" +
"/*\n" +
"select * from test_table;\n" +
"*/\n" +
"-- a ; b\n" +
"select * from test_table WHERE ID = ';--';\n" +
"select * from test_table WHERE ID = '/*' -- test";
InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext);
assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code());
assertEquals(3, interpreterResult.message().size());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.cache.processor.EntryProcessor;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.managers.deployment.GridDeployment;
import org.apache.ignite.internal.managers.deployment.GridDeploymentInfo;
import org.apache.ignite.internal.managers.deployment.GridDeploymentInfoBean;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.jetbrains.annotations.Nullable;
/**
* Parent of all cache messages.
*/
public abstract class GridCacheMessage implements Message {
/** */
private static final long serialVersionUID = 0L;
/** Maximum number of cache lookup indexes. */
public static final int MAX_CACHE_MSG_LOOKUP_INDEX = 7;
/** Cache message index field name. */
public static final String CACHE_MSG_INDEX_FIELD_NAME = "CACHE_MSG_IDX";
/** Message index id. */
private static final AtomicInteger msgIdx = new AtomicInteger();
/** Null message ID. */
private static final long NULL_MSG_ID = -1;
/** ID of this message. */
private long msgId = NULL_MSG_ID;
/** */
@GridToStringInclude
private GridDeploymentInfoBean depInfo;
/** */
@GridDirectTransient
protected boolean addDepInfo;
/** Force addition of deployment info regardless of {@code addDepInfo} flag value.*/
@GridDirectTransient
protected boolean forceAddDepInfo;
/** */
@GridDirectTransient
private IgniteCheckedException err;
/** */
@GridDirectTransient
private boolean skipPrepare;
/**
* @return ID to distinguish message handlers for the same messages but for different caches/cache groups.
*/
public abstract int handlerId();
/**
* @return {@code True} if cache group message.
*/
public abstract boolean cacheGroupMessage();
/**
* @return Error, if any.
*/
@Nullable public Throwable error() {
return null;
}
/**
* Gets next ID for indexed message ID.
*
* @return Message ID.
*/
public static int nextIndexId() {
return msgIdx.getAndIncrement();
}
/**
* @return {@code True} if this message is partition exchange message.
*/
public boolean partitionExchangeMessage() {
return false;
}
/**
* @return {@code True} if class loading errors should be ignored, false otherwise.
*/
public boolean ignoreClassErrors() {
return false;
}
/**
* Gets message lookup index. All messages that does not return -1 in this method must return a unique
* number in range from 0 to {@link #MAX_CACHE_MSG_LOOKUP_INDEX}.
*
* @return Message lookup index.
*/
public int lookupIndex() {
return -1;
}
/**
* @return Partition ID this message is targeted to or {@code -1} if it cannot be determined.
*/
public int partition() {
return -1;
}
/**
* If class loading error occurred during unmarshalling and {@link #ignoreClassErrors()} is
* set to {@code true}, then the error will be passed into this method.
*
* @param err Error.
*/
public void onClassError(IgniteCheckedException err) {
this.err = err;
}
/**
* @return Error set via {@link #onClassError(IgniteCheckedException)} method.
*/
public IgniteCheckedException classError() {
return err;
}
/**
* @return Message ID.
*/
public long messageId() {
return msgId;
}
/**
* Sets message ID. This method is package protected and is only called
* by {@link GridCacheIoManager}.
*
* @param msgId New message ID.
*/
void messageId(long msgId) {
this.msgId = msgId;
}
/**
* Gets topology version or -1 in case of topology version is not required for this message.
*
* @return Topology version.
*/
public AffinityTopologyVersion topologyVersion() {
return AffinityTopologyVersion.NONE;
}
/**
* Deployment enabled flag indicates whether deployment info has to be added to this message.
*
* @return {@code true} or if deployment info must be added to the the message, {@code false} otherwise.
*/
public abstract boolean addDeploymentInfo();
/**
* @param o Object to prepare for marshalling.
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
protected final void prepareObject(@Nullable Object o, GridCacheContext ctx) throws IgniteCheckedException {
prepareObject(o, ctx.shared());
}
/**
* @param o Object to prepare for marshalling.
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
protected final void prepareObject(@Nullable Object o, GridCacheSharedContext ctx) throws IgniteCheckedException {
assert addDepInfo || forceAddDepInfo;
if (!skipPrepare && o != null) {
GridDeploymentInfo d = ctx.deploy().globalDeploymentInfo();
if (d != null) {
prepare(d);
// Global deployment has been injected.
skipPrepare = true;
}
else {
Class<?> cls = U.detectClass(o);
ctx.deploy().registerClass(cls);
ClassLoader ldr = U.detectClassLoader(cls);
if (ldr instanceof GridDeploymentInfo)
prepare((GridDeploymentInfo)ldr);
}
}
}
/**
* @param depInfo Deployment to set.
* @see GridCacheDeployable#prepare(GridDeploymentInfo)
*/
public final void prepare(GridDeploymentInfo depInfo) {
if (depInfo != this.depInfo) {
if (this.depInfo != null && depInfo instanceof GridDeployment)
// Make sure not to replace remote deployment with local.
if (((GridDeployment)depInfo).local())
return;
this.depInfo = depInfo instanceof GridDeploymentInfoBean ?
(GridDeploymentInfoBean)depInfo : new GridDeploymentInfoBean(depInfo);
}
}
/**
* @return Preset deployment info.
* @see GridCacheDeployable#deployInfo()
*/
public GridDeploymentInfo deployInfo() {
return depInfo;
}
/**
* This method is called before the whole message is serialized
* and is responsible for pre-marshalling state.
*
* @param ctx Cache context.
* @throws IgniteCheckedException If failed.
*/
public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
// No-op.
}
/**
* This method is called after the message is deserialized and is responsible for
* unmarshalling state marshalled in {@link #prepareMarshal(GridCacheSharedContext)} method.
*
* @param ctx Context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
// No-op.
}
/**
* @param info Entry to marshal.
* @param ctx Context.
* @param cacheObjCtx Cache object context.
* @throws IgniteCheckedException If failed.
*/
protected final void marshalInfo(GridCacheEntryInfo info,
GridCacheSharedContext ctx,
CacheObjectContext cacheObjCtx
) throws IgniteCheckedException {
assert ctx != null;
if (info != null) {
info.marshal(cacheObjCtx);
if (addDepInfo) {
if (info.key() != null)
prepareObject(info.key().value(cacheObjCtx, false), ctx);
CacheObject val = info.value();
if (val != null) {
val.finishUnmarshal(cacheObjCtx, ctx.deploy().globalLoader());
prepareObject(val.value(cacheObjCtx, false), ctx);
}
}
}
}
/**
* @param info Entry to unmarshal.
* @param ctx Context.
* @param ldr Loader.
* @throws IgniteCheckedException If failed.
*/
protected final void unmarshalInfo(GridCacheEntryInfo info, GridCacheContext ctx,
ClassLoader ldr) throws IgniteCheckedException {
assert ldr != null;
assert ctx != null;
if (info != null)
info.unmarshal(ctx.cacheObjectContext(), ldr);
}
/**
* @param infos Entries to marshal.
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
protected final void marshalInfos(
Iterable<? extends GridCacheEntryInfo> infos,
GridCacheSharedContext ctx,
CacheObjectContext cacheObjCtx
) throws IgniteCheckedException {
assert ctx != null;
if (infos != null)
for (GridCacheEntryInfo e : infos)
marshalInfo(e, ctx, cacheObjCtx);
}
/**
* @param infos Entries to unmarshal.
* @param ctx Context.
* @param ldr Loader.
* @throws IgniteCheckedException If failed.
*/
protected final void unmarshalInfos(Iterable<? extends GridCacheEntryInfo> infos,
GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException {
assert ldr != null;
assert ctx != null;
if (infos != null)
for (GridCacheEntryInfo e : infos)
unmarshalInfo(e, ctx, ldr);
}
/**
* @param txEntries Entries to marshal.
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
protected final void marshalTx(Iterable<IgniteTxEntry> txEntries, GridCacheSharedContext ctx)
throws IgniteCheckedException {
assert ctx != null;
if (txEntries != null) {
boolean transferExpiry = transferExpiryPolicy();
boolean p2pEnabled = ctx.deploymentEnabled();
for (IgniteTxEntry e : txEntries) {
e.marshal(ctx, transferExpiry);
GridCacheContext cctx = e.context();
if (addDepInfo) {
if (e.key() != null)
prepareObject(e.key().value(cctx.cacheObjectContext(), false), ctx);
if (e.value() != null)
prepareObject(e.value().value(cctx.cacheObjectContext(), false), ctx);
if (e.entryProcessors() != null) {
for (T2<EntryProcessor<Object, Object, Object>, Object[]> entProc : e.entryProcessors())
prepareObject(entProc.get1(), ctx);
}
}
else if (p2pEnabled && e.entryProcessors() != null) {
if (!forceAddDepInfo)
forceAddDepInfo = true;
for (T2<EntryProcessor<Object, Object, Object>, Object[]> entProc : e.entryProcessors())
prepareObject(entProc.get1(), ctx);
}
}
}
}
/**
* @return {@code True} if entries expire policy should be marshalled.
*/
protected boolean transferExpiryPolicy() {
return false;
}
/**
* @param txEntries Entries to unmarshal.
* @param ctx Context.
* @param ldr Loader.
* @throws IgniteCheckedException If failed.
*/
protected final void unmarshalTx(Iterable<IgniteTxEntry> txEntries,
boolean near,
GridCacheSharedContext ctx,
ClassLoader ldr) throws IgniteCheckedException {
assert ldr != null;
assert ctx != null;
if (txEntries != null) {
for (IgniteTxEntry e : txEntries)
e.unmarshal(ctx, near, ldr);
}
}
/**
* @param args Arguments to marshal.
* @param ctx Context.
* @return Marshalled collection.
* @throws IgniteCheckedException If failed.
*/
@Nullable protected final byte[][] marshalInvokeArguments(@Nullable Object[] args, GridCacheContext ctx)
throws IgniteCheckedException {
assert ctx != null;
if (args == null || args.length == 0)
return null;
byte[][] argsBytes = new byte[args.length][];
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
if (addDepInfo)
prepareObject(arg, ctx.shared());
argsBytes[i] = arg == null ? null : CU.marshal(ctx, arg);
}
return argsBytes;
}
/**
* @param byteCol Collection to unmarshal.
* @param ctx Context.
* @param ldr Loader.
* @return Unmarshalled collection.
* @throws IgniteCheckedException If failed.
*/
@Nullable protected final Object[] unmarshalInvokeArguments(@Nullable byte[][] byteCol,
GridCacheSharedContext ctx,
ClassLoader ldr) throws IgniteCheckedException {
assert ldr != null;
assert ctx != null;
if (byteCol == null)
return null;
Object[] args = new Object[byteCol.length];
Marshaller marsh = ctx.marshaller();
for (int i = 0; i < byteCol.length; i++)
args[i] = byteCol[i] == null ? null : U.unmarshal(marsh, byteCol[i], U.resolveClassLoader(ldr, ctx.gridConfig()));
return args;
}
/**
* @param col Collection to marshal.
* @param ctx Context.
* @return Marshalled collection.
* @throws IgniteCheckedException If failed.
*/
@Nullable protected List<byte[]> marshalCollection(@Nullable Collection<?> col,
GridCacheContext ctx) throws IgniteCheckedException {
assert ctx != null;
if (col == null)
return null;
List<byte[]> byteCol = new ArrayList<>(col.size());
for (Object o : col) {
if (addDepInfo)
prepareObject(o, ctx.shared());
byteCol.add(o == null ? null : CU.marshal(ctx, o));
}
return byteCol;
}
/**
* @param col Collection.
* @param ctx Cache context.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
public final void prepareMarshalCacheObjects(@Nullable List<? extends CacheObject> col,
GridCacheContext ctx) throws IgniteCheckedException {
if (col == null)
return;
int size = col.size();
for (int i = 0 ; i < size; i++)
prepareMarshalCacheObject(col.get(i), ctx);
}
/**
* @param obj Object.
* @param ctx Context.
* @throws IgniteCheckedException If failed.
*/
protected final void prepareMarshalCacheObject(CacheObject obj, GridCacheContext ctx) throws IgniteCheckedException {
if (obj != null) {
obj.prepareMarshal(ctx.cacheObjectContext());
if (addDepInfo)
prepareObject(obj.value(ctx.cacheObjectContext(), false), ctx.shared());
}
}
/**
* @param col Collection.
* @param ctx Cache context.
* @throws IgniteCheckedException If failed.
*/
protected final void prepareMarshalCacheObjects(@Nullable Collection<? extends CacheObject> col,
GridCacheContext ctx) throws IgniteCheckedException {
if (col == null)
return;
for (CacheObject obj : col) {
if (obj != null) {
obj.prepareMarshal(ctx.cacheObjectContext());
if (addDepInfo)
prepareObject(obj.value(ctx.cacheObjectContext(), false), ctx.shared());
}
}
}
/**
* @param col Collection.
* @param ctx Context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
public final void finishUnmarshalCacheObjects(@Nullable List<? extends CacheObject> col,
GridCacheContext ctx,
ClassLoader ldr)
throws IgniteCheckedException
{
if (col == null)
return;
int size = col.size();
for (int i = 0 ; i < size; i++) {
CacheObject obj = col.get(i);
if (obj != null)
obj.finishUnmarshal(ctx.cacheObjectContext(), ldr);
}
}
/**
* @param col Collection.
* @param ctx Context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
protected final void finishUnmarshalCacheObjects(@Nullable Collection<? extends CacheObject> col,
GridCacheContext ctx,
ClassLoader ldr)
throws IgniteCheckedException
{
if (col == null)
return;
for (CacheObject obj : col) {
if (obj != null)
obj.finishUnmarshal(ctx.cacheObjectContext(), ldr);
}
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/**
* @param byteCol Collection to unmarshal.
* @param ctx Context.
* @param ldr Loader.
* @return Unmarshalled collection.
* @throws IgniteCheckedException If failed.
*/
@Nullable protected <T> List<T> unmarshalCollection(@Nullable Collection<byte[]> byteCol,
GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
assert ldr != null;
assert ctx != null;
if (byteCol == null)
return null;
List<T> col = new ArrayList<>(byteCol.size());
Marshaller marsh = ctx.marshaller();
for (byte[] bytes : byteCol)
col.add(bytes == null ? null : U.<T>unmarshal(marsh, bytes, U.resolveClassLoader(ldr, ctx.gridConfig())));
return col;
}
/**
* @param ctx Context.
* @return Logger.
*/
public IgniteLogger messageLogger(GridCacheSharedContext ctx) {
return ctx.messageLogger();
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 2;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeMessage("depInfo", depInfo))
return false;
writer.incrementState();
case 1:
if (!writer.writeLong("msgId", msgId))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
depInfo = reader.readMessage("depInfo");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
msgId = reader.readLong("msgId");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridCacheMessage.class);
}
/**
* @param str Bulder.
* @param name Flag name.
*/
protected final void appendFlag(StringBuilder str, String name) {
if (str.length() > 0)
str.append('|');
str.append(name);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheMessage.class, this);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.client.internal;
import java.net.SocketTimeoutException;
import java.util.Iterator;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.geode.InternalGemFireError;
import org.apache.geode.cache.client.ServerOperationException;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.cache.EventID;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage;
import org.apache.geode.internal.cache.tier.sockets.Message;
import org.apache.geode.internal.cache.tier.sockets.Part;
import org.apache.geode.internal.cache.wan.BatchException70;
import org.apache.geode.internal.cache.wan.GatewaySenderEventImpl;
import org.apache.geode.internal.cache.wan.GatewaySenderEventRemoteDispatcher.GatewayAck;
import org.apache.geode.internal.logging.LogService;
@SuppressWarnings("unchecked")
public class GatewaySenderBatchOp {
private static final Logger logger = LogService.getLogger();
/**
* Send a list of gateway events to a server to execute using connections from the given pool to
* communicate with the server.
*
* @param con the connection to send the message on.
* @param pool the pool to use to communicate with the server.
* @param events list of gateway events
* @param batchId the ID of this batch
* @param removeFromQueueOnException true if the events should be processed even after some
* exception
*/
public static void executeOn(Connection con, ExecutablePool pool, List events, int batchId,
boolean removeFromQueueOnException, boolean isRetry) {
AbstractOp op = null;
// System.out.println("Version: "+con.getWanSiteVersion());
// Is this check even needed anymore? It looks like we just create the same exact op impl with
// the same parameters...
if (Version.GFE_651.compareTo(con.getWanSiteVersion()) >= 0) {
op = new GatewaySenderGFEBatchOpImpl(events, batchId, removeFromQueueOnException,
con.getDistributedSystemId(), isRetry);
} else {
// Default should create a batch of server version (ACCEPTOR.VERSION)
op = new GatewaySenderGFEBatchOpImpl(events, batchId, removeFromQueueOnException,
con.getDistributedSystemId(), isRetry);
}
pool.executeOn(con, op, true/* timeoutFatal */);
}
public static Object executeOn(Connection con, ExecutablePool pool) {
AbstractOp op = new GatewaySenderGFEBatchOpImpl();
return pool.executeOn(con, op, true/* timeoutFatal */);
}
private GatewaySenderBatchOp() {
// no instances allowed
}
static class GatewaySenderGFEBatchOpImpl extends AbstractOp {
/**
* @throws org.apache.geode.SerializationException if serialization fails
*/
public GatewaySenderGFEBatchOpImpl(List events, int batchId, boolean removeFromQueueOnException,
int dsId, boolean isRetry) {
super(MessageType.GATEWAY_RECEIVER_COMMAND, calcPartCount(events));
if (isRetry) {
getMessage().setIsRetry();
}
getMessage().addIntPart(events.size());
getMessage().addIntPart(batchId);
getMessage().addIntPart(dsId);
getMessage().addBytesPart(new byte[] {removeFromQueueOnException ? (byte) 1 : (byte) 0});
// Add each event
for (Iterator i = events.iterator(); i.hasNext();) {
GatewaySenderEventImpl event = (GatewaySenderEventImpl) i.next();
// Add action
int action = event.getAction();
getMessage().addIntPart(action);
{ // Add posDup flag
byte posDupByte = (byte) (event.getPossibleDuplicate() ? 0x01 : 0x00);
getMessage().addBytesPart(new byte[] {posDupByte});
}
if (action >= 0 && action <= 3) {
// 0 = create
// 1 = update
// 2 = destroy
String regionName = event.getRegionPath();
EventID eventId = event.getEventId();
Object key = event.getKey();
Object callbackArg = event.getSenderCallbackArgument();
// Add region name
getMessage().addStringPart(regionName, true);
// Add event id
getMessage().addObjPart(eventId);
// Add key
getMessage().addStringOrObjPart(key);
if (action < 2 /* it is 0 or 1 */) {
byte[] value = event.getSerializedValue();
byte valueIsObject = event.getValueIsObject();;
// Add value (which is already a serialized byte[])
getMessage().addRawPart(value, (valueIsObject == 0x01));
}
// Add callback arg if necessary
if (callbackArg == null) {
getMessage().addBytesPart(new byte[] {0x00});
} else {
getMessage().addBytesPart(new byte[] {0x01});
getMessage().addObjPart(callbackArg);
}
getMessage().addLongPart(event.getVersionTimeStamp());
}
}
}
public GatewaySenderGFEBatchOpImpl() {
super(MessageType.GATEWAY_RECEIVER_COMMAND, 0);
}
@Override
public Object attempt(Connection cnx) throws Exception {
if (getMessage().getNumberOfParts() == 0) {
return attemptRead(cnx);
}
this.failed = true;
this.timedOut = false;
long start = startAttempt(cnx.getStats());
try {
try {
attemptSend(cnx);
this.failed = false;
} finally {
endSendAttempt(cnx.getStats(), start);
}
} finally {
endAttempt(cnx.getStats(), start);
}
return this.failed;
}
private Object attemptRead(Connection cnx) throws Exception {
this.failed = true;
try {
Object result = attemptReadResponse(cnx);
this.failed = false;
return result;
} catch (SocketTimeoutException ste) {
this.failed = false;
this.timedOut = true;
throw ste;
}
}
/**
* Attempts to read a response to this operation by reading it from the given connection, and
* returning it.
*
* @param cnx the connection to read the response from
* @return the result of the operation or <code>null</code> if the operation has no result.
* @throws Exception if the execute failed
*/
@Override
protected Object attemptReadResponse(Connection cnx) throws Exception {
Message msg = createResponseMessage();
if (msg != null) {
msg.setComms(cnx.getSocket(), cnx.getInputStream(), cnx.getOutputStream(),
((ConnectionImpl) cnx).getCommBufferForAsyncRead(), cnx.getStats());
if (msg instanceof ChunkedMessage) {
try {
return processResponse(msg, cnx);
} finally {
msg.unsetComms();
// TODO (ashetkar) Handle the case when we fail to read the
// connection id.
processSecureBytes(cnx, msg);
}
}
try {
msg.receive();
} finally {
msg.unsetComms();
processSecureBytes(cnx, msg);
}
return processResponse(msg, cnx);
}
return null;
}
private static int calcPartCount(List events) {
int numberOfParts = 4; // for the number of events and the batchId
for (Iterator i = events.iterator(); i.hasNext();) {
GatewaySenderEventImpl event = (GatewaySenderEventImpl) i.next();
numberOfParts += event.getNumberOfParts();
}
return numberOfParts;
}
@Override
protected boolean needsUserId() {
return false;
}
@Override
protected void sendMessage(Connection cnx) throws Exception {
getMessage().clearMessageHasSecurePartFlag();
getMessage().send(false);
}
@Override
protected Object processResponse(Message msg) throws Exception {
GatewayAck ack = null;
try {
// Read the header which describes the type of message following
switch (msg.getMessageType()) {
case MessageType.REPLY:
// Read the chunk
Part part0 = msg.getPart(0);
if (part0.isBytes() && part0.getLength() == 1 && part0.getSerializedForm()[0] == 0) {
// REPLY_OKAY from a CloseConnection
break;
}
int batchId = part0.getInt();
int numEvents = msg.getPart(1).getInt();
ack = new GatewayAck(batchId, numEvents);
break;
case MessageType.EXCEPTION:
part0 = msg.getPart(0);
Object obj = part0.getObject();
if (obj instanceof List) {
List<BatchException70> l = (List<BatchException70>) part0.getObject();
if (logger.isDebugEnabled()) {
logger.debug(
"We got an exception from the GatewayReceiver. MessageType : {} obj :{}",
msg.getMessageType(), obj);
}
// don't throw Exception but set it in the Ack
BatchException70 be = new BatchException70(l);
ack = new GatewayAck(be, l.get(0).getBatchId());
} else if (obj instanceof Throwable) {
String s = ": While reading Ack from receiver " + ((Throwable) obj).getMessage();
throw new ServerOperationException(s, (Throwable) obj);
}
break;
default:
throw new InternalGemFireError(String.format("Unknown message type %s",
Integer.valueOf(msg.getMessageType())));
}
} finally {
msg.clear();
}
return ack;
}
@Override
protected boolean isErrorResponse(int msgType) {
return false;
}
@Override
protected long startAttempt(ConnectionStats stats) {
return stats.startGatewayBatch();
}
@Override
protected void endSendAttempt(ConnectionStats stats, long start) {
stats.endGatewayBatchSend(start, hasFailed());
}
@Override
protected void endAttempt(ConnectionStats stats, long start) {
stats.endGatewayBatch(start, hasTimedOut(), hasFailed());
}
@Override
public boolean isGatewaySenderOp() {
return true;
}
}
}
| |
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.swing.plaf.nimbus;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.Painter;
final class ScrollBarTrackPainter extends AbstractRegionPainter {
//package private integers representing the available states that
//this painter will paint. These are used when creating a new instance
//of ScrollBarTrackPainter to determine which region/state is being painted
//by that instance.
static final int BACKGROUND_DISABLED = 1;
static final int BACKGROUND_ENABLED = 2;
private int state; //refers to one of the static final ints above
private PaintContext ctx;
//the following 4 variables are reused during the painting code of the layers
private Path2D path = new Path2D.Float();
private Rectangle2D rect = new Rectangle2D.Float(0, 0, 0, 0);
private RoundRectangle2D roundRect = new RoundRectangle2D.Float(0, 0, 0, 0, 0, 0);
private Ellipse2D ellipse = new Ellipse2D.Float(0, 0, 0, 0);
//All Colors used for painting are stored here. Ideally, only those colors being used
//by a particular instance of ScrollBarTrackPainter would be created. For the moment at least,
//however, all are created for each instance.
private Color color1 = decodeColor("nimbusBlueGrey", -0.027777791f, -0.10016362f, 0.011764705f, 0);
private Color color2 = decodeColor("nimbusBlueGrey", -0.027777791f, -0.100476064f, 0.035294116f, 0);
private Color color3 = decodeColor("nimbusBlueGrey", 0.055555582f, -0.10606203f, 0.13333333f, 0);
private Color color4 = decodeColor("nimbusBlueGrey", -0.6111111f, -0.110526316f, 0.24705881f, 0);
private Color color5 = decodeColor("nimbusBlueGrey", 0.02222228f, -0.06465475f, -0.31764707f, 0);
private Color color6 = decodeColor("nimbusBlueGrey", 0.0f, -0.06766917f, -0.19607842f, 0);
private Color color7 = decodeColor("nimbusBlueGrey", -0.006944418f, -0.0655825f, -0.04705882f, 0);
private Color color8 = decodeColor("nimbusBlueGrey", 0.0138888955f, -0.071117446f, 0.05098039f, 0);
private Color color9 = decodeColor("nimbusBlueGrey", 0.0f, -0.07016757f, 0.12941176f, 0);
private Color color10 = decodeColor("nimbusBlueGrey", 0.0f, -0.05967886f, -0.5137255f, 0);
private Color color11 = decodeColor("nimbusBlueGrey", 0.0f, -0.05967886f, -0.5137255f, -255);
private Color color12 = decodeColor("nimbusBlueGrey", -0.027777791f, -0.07826825f, -0.5019608f, -255);
private Color color13 = decodeColor("nimbusBlueGrey", -0.015872955f, -0.06731644f, -0.109803915f, 0);
private Color color14 = decodeColor("nimbusBlueGrey", 0.0f, -0.06924191f, 0.109803915f, 0);
private Color color15 = decodeColor("nimbusBlueGrey", -0.015872955f, -0.06861015f, -0.09019607f, 0);
private Color color16 = decodeColor("nimbusBlueGrey", 0.0f, -0.06766917f, 0.07843137f, 0);
//Array of current component colors, updated in each paint call
private Object[] componentColors;
public ScrollBarTrackPainter(PaintContext ctx, int state) {
super();
this.state = state;
this.ctx = ctx;
}
@Override
protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
//populate componentColors array with colors calculated in getExtendedCacheKeys call
componentColors = extendedCacheKeys;
//generate this entire method. Each state/bg/fg/border combo that has
//been painted gets its own KEY and paint method.
switch(state) {
case BACKGROUND_DISABLED: paintBackgroundDisabled(g); break;
case BACKGROUND_ENABLED: paintBackgroundEnabled(g); break;
}
}
@Override
protected final PaintContext getPaintContext() {
return ctx;
}
private void paintBackgroundDisabled(Graphics2D g) {
rect = decodeRect1();
g.setPaint(decodeGradient1(rect));
g.fill(rect);
}
private void paintBackgroundEnabled(Graphics2D g) {
rect = decodeRect1();
g.setPaint(decodeGradient2(rect));
g.fill(rect);
path = decodePath1();
g.setPaint(decodeGradient3(path));
g.fill(path);
path = decodePath2();
g.setPaint(decodeGradient4(path));
g.fill(path);
path = decodePath3();
g.setPaint(decodeGradient5(path));
g.fill(path);
path = decodePath4();
g.setPaint(decodeGradient6(path));
g.fill(path);
}
private Rectangle2D decodeRect1() {
rect.setRect(decodeX(0.0f), //x
decodeY(0.0f), //y
decodeX(3.0f) - decodeX(0.0f), //width
decodeY(3.0f) - decodeY(0.0f)); //height
return rect;
}
private Path2D decodePath1() {
path.reset();
path.moveTo(decodeX(0.7f), decodeY(0.0f));
path.lineTo(decodeX(0.0f), decodeY(0.0f));
path.lineTo(decodeX(0.0f), decodeY(1.2f));
path.curveTo(decodeAnchorX(0.0f, 0.0f), decodeAnchorY(1.2000000476837158f, 0.0f), decodeAnchorX(0.30000001192092896f, -1.0f), decodeAnchorY(2.200000047683716f, -1.0f), decodeX(0.3f), decodeY(2.2f));
path.curveTo(decodeAnchorX(0.30000001192092896f, 1.0f), decodeAnchorY(2.200000047683716f, 1.0f), decodeAnchorX(0.6785714030265808f, 0.0f), decodeAnchorY(2.799999952316284f, 0.0f), decodeX(0.6785714f), decodeY(2.8f));
path.lineTo(decodeX(0.7f), decodeY(0.0f));
path.closePath();
return path;
}
private Path2D decodePath2() {
path.reset();
path.moveTo(decodeX(3.0f), decodeY(0.0f));
path.lineTo(decodeX(2.2222223f), decodeY(0.0f));
path.lineTo(decodeX(2.2222223f), decodeY(2.8f));
path.curveTo(decodeAnchorX(2.222222328186035f, 0.0f), decodeAnchorY(2.799999952316284f, 0.0f), decodeAnchorX(2.674603223800659f, -1.0f), decodeAnchorY(2.1857142448425293f, 1.0f), decodeX(2.6746032f), decodeY(2.1857142f));
path.curveTo(decodeAnchorX(2.674603223800659f, 1.0000000000000036f), decodeAnchorY(2.1857142448425293f, -1.0f), decodeAnchorX(3.0f, 0.0f), decodeAnchorY(1.2000000476837158f, 0.0f), decodeX(3.0f), decodeY(1.2f));
path.lineTo(decodeX(3.0f), decodeY(0.0f));
path.closePath();
return path;
}
private Path2D decodePath3() {
path.reset();
path.moveTo(decodeX(0.11428572f), decodeY(1.3714286f));
path.curveTo(decodeAnchorX(0.11428572237491608f, 0.7857142857142856f), decodeAnchorY(1.3714286088943481f, -0.571428571428573f), decodeAnchorX(0.4642857015132904f, -1.3571428571428572f), decodeAnchorY(2.0714285373687744f, -1.5714285714285694f), decodeX(0.4642857f), decodeY(2.0714285f));
path.curveTo(decodeAnchorX(0.4642857015132904f, 1.3571428571428577f), decodeAnchorY(2.0714285373687744f, 1.5714285714285694f), decodeAnchorX(0.8714286088943481f, 0.21428571428571352f), decodeAnchorY(2.7285714149475098f, -1.0f), decodeX(0.8714286f), decodeY(2.7285714f));
path.curveTo(decodeAnchorX(0.8714286088943481f, -0.21428571428571352f), decodeAnchorY(2.7285714149475098f, 1.0f), decodeAnchorX(0.3571428656578064f, 1.5000000000000004f), decodeAnchorY(2.3142857551574707f, 1.642857142857146f), decodeX(0.35714287f), decodeY(2.3142858f));
path.curveTo(decodeAnchorX(0.3571428656578064f, -1.5000000000000004f), decodeAnchorY(2.3142857551574707f, -1.642857142857146f), decodeAnchorX(0.11428572237491608f, -0.7857142857142856f), decodeAnchorY(1.3714286088943481f, 0.571428571428573f), decodeX(0.11428572f), decodeY(1.3714286f));
path.closePath();
return path;
}
private Path2D decodePath4() {
path.reset();
path.moveTo(decodeX(2.1111112f), decodeY(2.7f));
path.curveTo(decodeAnchorX(2.1111111640930176f, 0.4285714285714306f), decodeAnchorY(2.700000047683716f, 0.6428571428571388f), decodeAnchorX(2.626984119415283f, -1.571428571428573f), decodeAnchorY(2.200000047683716f, 1.6428571428571388f), decodeX(2.6269841f), decodeY(2.2f));
path.curveTo(decodeAnchorX(2.626984119415283f, 1.571428571428573f), decodeAnchorY(2.200000047683716f, -1.6428571428571388f), decodeAnchorX(2.8412699699401855f, 0.7142857142857224f), decodeAnchorY(1.3857142925262451f, 0.6428571428571459f), decodeX(2.84127f), decodeY(1.3857143f));
path.curveTo(decodeAnchorX(2.8412699699401855f, -0.7142857142857224f), decodeAnchorY(1.3857142925262451f, -0.6428571428571459f), decodeAnchorX(2.5238094329833984f, 0.7142857142857117f), decodeAnchorY(2.057142734527588f, -0.8571428571428541f), decodeX(2.5238094f), decodeY(2.0571427f));
path.curveTo(decodeAnchorX(2.5238094329833984f, -0.7142857142857117f), decodeAnchorY(2.057142734527588f, 0.8571428571428541f), decodeAnchorX(2.1111111640930176f, -0.4285714285714306f), decodeAnchorY(2.700000047683716f, -0.6428571428571388f), decodeX(2.1111112f), decodeY(2.7f));
path.closePath();
return path;
}
private Paint decodeGradient1(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y,
new float[] { 0.016129032f,0.038709678f,0.061290324f,0.16091082f,0.26451612f,0.4378071f,0.88387096f },
new Color[] { color1,
decodeColor(color1,color2,0.5f),
color2,
decodeColor(color2,color3,0.5f),
color3,
decodeColor(color3,color4,0.5f),
color4});
}
private Paint decodeGradient2(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((0.5f * w) + x, (0.0f * h) + y, (0.5f * w) + x, (1.0f * h) + y,
new float[] { 0.0f,0.030645162f,0.061290324f,0.09677419f,0.13225806f,0.22096774f,0.30967742f,0.47434634f,0.82258064f },
new Color[] { color5,
decodeColor(color5,color6,0.5f),
color6,
decodeColor(color6,color7,0.5f),
color7,
decodeColor(color7,color8,0.5f),
color8,
decodeColor(color8,color9,0.5f),
color9});
}
private Paint decodeGradient3(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((0.0f * w) + x, (0.0f * h) + y, (0.9285714f * w) + x, (0.12244898f * h) + y,
new float[] { 0.0f,0.1f,1.0f },
new Color[] { color10,
decodeColor(color10,color11,0.5f),
color11});
}
private Paint decodeGradient4(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((-0.045918368f * w) + x, (0.18336426f * h) + y, (0.872449f * w) + x, (0.04050711f * h) + y,
new float[] { 0.0f,0.87096775f,1.0f },
new Color[] { color12,
decodeColor(color12,color10,0.5f),
color10});
}
private Paint decodeGradient5(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((0.12719299f * w) + x, (0.13157894f * h) + y, (0.90789473f * w) + x, (0.877193f * h) + y,
new float[] { 0.0f,0.5f,1.0f },
new Color[] { color13,
decodeColor(color13,color14,0.5f),
color14});
}
private Paint decodeGradient6(Shape s) {
Rectangle2D bounds = s.getBounds2D();
float x = (float)bounds.getX();
float y = (float)bounds.getY();
float w = (float)bounds.getWidth();
float h = (float)bounds.getHeight();
return decodeGradient((0.86458343f * w) + x, (0.20952381f * h) + y, (0.020833189f * w) + x, (0.95238096f * h) + y,
new float[] { 0.0f,0.5f,1.0f },
new Color[] { color15,
decodeColor(color15,color16,0.5f),
color16});
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.util;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiMethodMember;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.featureStatistics.ProductivityFeatureNames;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
import com.intellij.ide.util.MemberChooser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTypesUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrTraitMethod;
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil;
import java.io.IOException;
import java.util.*;
public final class GroovyOverrideImplementUtil {
private static final Logger LOG = Logger.getInstance(GroovyOverrideImplementUtil.class);
private GroovyOverrideImplementUtil() {
}
public static GrMethod generateMethodPrototype(GrTypeDefinition aClass,
PsiMethod method,
PsiSubstitutor substitutor) {
final Project project = aClass.getProject();
final boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
String templName = isAbstract ? JavaTemplateUtil.TEMPLATE_IMPLEMENTED_METHOD_BODY : JavaTemplateUtil.TEMPLATE_OVERRIDDEN_METHOD_BODY;
final FileTemplate template = FileTemplateManager.getInstance(method.getProject()).getCodeTemplate(templName);
final GrMethod result = (GrMethod)GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass);
setupModifierList(result);
setupOverridingMethodBody(project, method, result, template, substitutor);
setupReturnType(result, method);
setupAnnotations(aClass, method, result);
GroovyChangeContextUtil.encodeContextInfo(result);
return result;
}
public static GrMethod generateTraitMethodPrototype(GrTypeDefinition aClass, GrTraitMethod method, PsiSubstitutor substitutor) {
final Project project = aClass.getProject();
final GrMethod result = (GrMethod)GenerateMembersUtil.substituteGenericMethod(method, substitutor, aClass);
setupModifierList(result);
setupTraitMethodBody(project, result, method);
setupReturnType(result, method);
setupAnnotations(aClass, method, result);
GroovyChangeContextUtil.encodeContextInfo(result);
return result;
}
private static void setupReturnType(GrMethod result, PsiMethod method) {
if (method instanceof GrMethod && ((GrMethod)method).getReturnTypeElementGroovy() == null) {
result.setReturnType(null);
GrModifierList modifierList = result.getModifierList();
if (!modifierList.hasExplicitVisibilityModifiers()) {
modifierList.setModifierProperty(GrModifier.DEF, true);
}
}
}
private static void setupAnnotations(@NotNull GrTypeDefinition aClass, @NotNull PsiMethod method, @NotNull GrMethod result) {
if (OverrideImplementUtil.isInsertOverride(method, aClass)) {
result.getModifierList().addAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE);
}
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(method.getProject());
final PsiParameter[] originalParams = method.getParameterList().getParameters();
GrParameter[] parameters = result.getParameters();
for (int i = 0; i < parameters.length; i++) {
GrParameter parameter = parameters[i];
PsiParameter original = originalParams[i];
for (PsiAnnotation annotation : original.getModifierList().getAnnotations()) {
final GrModifierList modifierList = parameter.getModifierList();
String qname = annotation.getQualifiedName();
if (qname != null && !modifierList.hasAnnotation(qname)) {
if (annotation instanceof GrAnnotation) {
modifierList.add(annotation);
}
else {
modifierList.add(factory.createAnnotationFromText(annotation.getText()));
}
}
}
}
}
private static void setupModifierList(GrMethod result) {
PsiModifierList modifierList = result.getModifierList();
modifierList.setModifierProperty(PsiModifier.ABSTRACT, false);
modifierList.setModifierProperty(PsiModifier.NATIVE, false);
}
@Nullable
private static PsiType getSuperReturnType(@NotNull PsiMethod superMethod) {
if (superMethod instanceof GrMethod) {
final GrTypeElement element = ((GrMethod)superMethod).getReturnTypeElementGroovy();
return element != null ? element.getType() : null;
}
return superMethod.getReturnType();
}
private static void setupOverridingMethodBody(Project project,
PsiMethod method,
GrMethod resultMethod,
FileTemplate template,
PsiSubstitutor substitutor) {
final PsiType returnType = substitutor.substitute(getSuperReturnType(method));
String returnTypeText = "";
if (returnType != null) {
returnTypeText = returnType.getPresentableText();
}
Properties properties = FileTemplateManager.getInstance(project).getDefaultProperties();
properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, returnTypeText);
properties.setProperty(FileTemplate.ATTRIBUTE_DEFAULT_RETURN_VALUE, PsiTypesUtil.getDefaultValueOfType(returnType));
properties.setProperty(FileTemplate.ATTRIBUTE_CALL_SUPER, callSuper(method, resultMethod));
JavaTemplateUtil.setClassAndMethodNameProperties(properties, method.getContainingClass(), resultMethod);
try {
String bodyText = StringUtil.replace(template.getText(properties), ";", "");
GroovyFile file = GroovyPsiElementFactory.getInstance(project).createGroovyFile("\n " + bodyText + "\n", false, null);
GrOpenBlock block = resultMethod.getBlock();
block.getNode().addChildren(file.getFirstChild().getNode(), null, block.getRBrace().getNode());
}
catch (IOException e) {
LOG.error(e);
}
}
private static void setupTraitMethodBody(Project project, GrMethod resultMethod, GrTraitMethod traitMethod) {
PsiClass traitClass = traitMethod.getPrototype().getContainingClass();
@NlsSafe StringBuilder builder = new StringBuilder();
builder.append("\nreturn ");
builder.append(traitClass.getQualifiedName());
builder.append(".super.");
builder.append(traitMethod.getName());
builder.append("(");
GrParameter[] parameters = resultMethod.getParameters();
for (GrParameter parameter : parameters) {
builder.append(parameter.getName()).append(",");
}
if (parameters.length > 0) {
builder.replace(builder.length() - 1, builder.length(), ")\n");
}
else {
builder.append(")\n");
}
GroovyFile file = GroovyPsiElementFactory.getInstance(project).createGroovyFile(builder, false, null);
GrOpenBlock block = resultMethod.getBlock();
block.getNode().addChildren(file.getFirstChild().getNode(), null, block.getRBrace().getNode());
}
public static void chooseAndOverrideMethods(@NotNull Project project,
@NotNull Editor editor,
@NotNull GrTypeDefinition aClass){
FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT);
chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
}
public static void chooseAndImplementMethods(@NotNull Project project,
@NotNull Editor editor,
@NotNull GrTypeDefinition aClass){
FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.CODEASSISTS_OVERRIDE_IMPLEMENT);
chooseAndOverrideOrImplementMethods(project, editor, aClass, true);
}
public static void chooseAndOverrideOrImplementMethods(@NotNull Project project,
@NotNull final Editor editor,
@NotNull final GrTypeDefinition aClass,
boolean toImplement) {
LOG.assertTrue(aClass.isValid());
ApplicationManager.getApplication().assertReadAccessAllowed();
Collection<CandidateInfo> candidates = GroovyOverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, toImplement);
Collection<CandidateInfo> secondary = toImplement || aClass.isInterface() ? new ArrayList<>()
: GroovyOverrideImplementExploreUtil
.getMethodsToOverrideImplement(aClass, true);
if (toImplement) {
for (Iterator<CandidateInfo> iterator = candidates.iterator(); iterator.hasNext(); ) {
CandidateInfo candidate = iterator.next();
PsiElement element = candidate.getElement();
if (element instanceof GrMethod) {
GrMethod method = (GrMethod)element;
if (GrTraitUtil.isTrait(method.getContainingClass()) && !GrTraitUtil.isMethodAbstract(method)) {
iterator.remove();
secondary.add(candidate);
}
}
}
}
final MemberChooser<PsiMethodMember> chooser =
OverrideImplementUtil.showOverrideImplementChooser(editor, aClass, toImplement, candidates, secondary);
if (chooser == null) return;
final List<PsiMethodMember> selectedElements = chooser.getSelectedElements();
if (selectedElements == null || selectedElements.isEmpty()) return;
LOG.assertTrue(aClass.isValid());
WriteCommandAction.writeCommandAction(project, aClass.getContainingFile()).run(() -> OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(editor, aClass, selectedElements, chooser.isCopyJavadoc(),
chooser.isInsertOverrideAnnotation()));
}
@NotNull
private static String callSuper(PsiMethod superMethod, PsiMethod overriding) {
@NonNls StringBuilder buffer = new StringBuilder();
if (!superMethod.isConstructor() && !PsiType.VOID.equals(superMethod.getReturnType())) {
buffer.append("return ");
}
buffer.append("super");
PsiParameter[] parms = overriding.getParameterList().getParameters();
if (!superMethod.isConstructor()) {
buffer.append(".");
buffer.append(superMethod.getName());
}
buffer.append("(");
for (int i = 0; i < parms.length; i++) {
String name = parms[i].getName();
if (i > 0) buffer.append(",");
buffer.append(name);
}
buffer.append(")");
return buffer.toString();
}
}
| |
package redis.clients.redisson;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
import org.junit.Assert;
import org.junit.Test;
import redis.clients.redisson.api.RPriorityQueue;
public class RedissonPriorityQueueTest extends BaseTest {
@Test
public void testReadAll() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("simple");
set.add(2);
set.add(0);
set.add(1);
set.add(5);
assertThat(set.readAll()).containsExactly(0, 1, 2, 5);
}
@Test
public void testIteratorNextNext() {
RPriorityQueue<String> list = redisson.getPriorityQueue("simple");
list.add("1");
list.add("4");
Iterator<String> iter = list.iterator();
Assert.assertEquals("1", iter.next());
Assert.assertEquals("4", iter.next());
Assert.assertFalse(iter.hasNext());
}
@Test
public void testIteratorRemove() {
RPriorityQueue<String> list = redisson.getPriorityQueue("list");
list.add("1");
list.add("4");
list.add("2");
list.add("5");
list.add("3");
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String value = iterator.next();
if (value.equals("2")) {
iterator.remove();
}
}
assertThat(list).contains("1", "4", "5", "3");
int iteration = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
iteration++;
}
Assert.assertEquals(4, iteration);
Assert.assertEquals(0, list.size());
Assert.assertTrue(list.isEmpty());
}
@Test
public void testIteratorSequence() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
for (int i = 0; i < 1000; i++) {
set.add(Integer.valueOf(i));
}
Queue<Integer> setCopy = new PriorityQueue<Integer>();
for (int i = 0; i < 1000; i++) {
setCopy.add(Integer.valueOf(i));
}
checkIterator(set, setCopy);
}
private void checkIterator(Queue<Integer> set, Queue<Integer> setCopy) {
for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) {
Integer value = iterator.next();
if (!setCopy.remove(value)) {
Assert.fail();
}
}
Assert.assertEquals(0, setCopy.size());
}
@Test
public void testTrySetComparator() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
boolean setRes = set.trySetComparator(Collections.reverseOrder());
Assert.assertTrue(setRes);
Assert.assertTrue(set.add(1));
Assert.assertTrue(set.add(2));
Assert.assertTrue(set.add(3));
Assert.assertTrue(set.add(4));
Assert.assertTrue(set.add(5));
assertThat(set).containsExactly(5, 4, 3, 2, 1);
boolean setRes2 = set.trySetComparator(Collections.reverseOrder(Collections.reverseOrder()));
Assert.assertFalse(setRes2);
assertThat(set).containsExactly(5, 4, 3, 2, 1);
set.clear();
boolean setRes3 = set.trySetComparator(Collections.reverseOrder(Collections.reverseOrder()));
Assert.assertTrue(setRes3);
set.add(3);
set.add(1);
set.add(2);
assertThat(set).containsExactly(1, 2, 3);
}
@Test
public void testSort() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
Assert.assertTrue(set.add(2));
Assert.assertTrue(set.add(3));
Assert.assertTrue(set.add(1));
Assert.assertTrue(set.add(4));
Assert.assertTrue(set.add(10));
Assert.assertTrue(set.add(-1));
Assert.assertTrue(set.add(0));
assertThat(set).containsExactly(-1, 0, 1, 2, 3, 4, 10);
Assert.assertEquals(-1, (int)set.peek());
}
@Test
public void testRemove() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
set.add(5);
set.add(3);
set.add(1);
set.add(2);
set.add(4);
set.add(1);
Assert.assertFalse(set.remove(0));
Assert.assertTrue(set.remove(3));
Assert.assertTrue(set.remove(1));
assertThat(set).containsExactly(1, 2, 4, 5);
}
@Test
public void testRetainAll() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
for (int i = 0; i < 200; i++) {
set.add(i);
}
Assert.assertTrue(set.retainAll(Arrays.asList(1, 2)));
Assert.assertEquals(2, set.size());
}
@Test
public void testContainsAll() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
for (int i = 0; i < 200; i++) {
set.add(i);
}
Assert.assertTrue(set.containsAll(Arrays.asList(30, 11)));
Assert.assertFalse(set.containsAll(Arrays.asList(30, 711, 11)));
}
@Test
public void testToArray() {
RPriorityQueue<String> set = redisson.getPriorityQueue("set");
set.add("1");
set.add("4");
set.add("2");
set.add("5");
set.add("3");
assertThat(set.toArray()).contains("1", "4", "2", "5", "3");
String[] strs = set.toArray(new String[0]);
assertThat(strs).contains("1", "4", "2", "5", "3");
}
@Test
public void testContains() {
RPriorityQueue<TestObject> set = redisson.getPriorityQueue("set");
set.add(new TestObject("1", "2"));
set.add(new TestObject("1", "2"));
set.add(new TestObject("2", "3"));
set.add(new TestObject("3", "4"));
set.add(new TestObject("5", "6"));
Assert.assertTrue(set.contains(new TestObject("2", "3")));
Assert.assertTrue(set.contains(new TestObject("1", "2")));
Assert.assertFalse(set.contains(new TestObject("1", "9")));
}
@Test
public void testDuplicates() {
RPriorityQueue<TestObject> set = redisson.getPriorityQueue("set");
set.add(new TestObject("1", "2"));
set.add(new TestObject("2", "3"));
set.add(new TestObject("5", "6"));
set.add(new TestObject("1", "2"));
set.add(new TestObject("3", "4"));
Assert.assertEquals(5, set.size());
assertThat(set).containsExactly(new TestObject("1", "2"), new TestObject("1", "2"),
new TestObject("2", "3"), new TestObject("3", "4"), new TestObject("5", "6"));
}
@Test
public void testSize() {
RPriorityQueue<Integer> set = redisson.getPriorityQueue("set");
set.add(1);
set.add(2);
set.add(3);
set.add(3);
set.add(4);
set.add(5);
set.add(5);
Assert.assertEquals(7, set.size());
}
}
| |
/*
* Copyright 2014 Magnus Woxblom
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.woxthebox.draglistview;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.woxthebox.draglistview.swipe.ListSwipeHelper;
public class DragListView extends FrameLayout {
public interface DragListListener {
void onItemDragStarted(int position);
void onItemDragging(int itemPosition, float x, float y);
void onItemDragEnded(int fromPosition, int toPosition);
}
public static abstract class DragListListenerAdapter implements DragListListener {
public abstract void onItemClick(int position);
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragging(int itemPosition, float x, float y) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
}
}
public interface DragListCallback {
boolean canDragItemAtPosition(int dragPosition);
boolean canDropItemAtPosition(int dropPosition);
}
public static abstract class DragListCallbackAdapter implements DragListCallback {
@Override
public boolean canDragItemAtPosition(int dragPosition) {
return true;
}
@Override
public boolean canDropItemAtPosition(int dropPosition) {
return true;
}
}
private DragItemRecyclerView mRecyclerView;
private DragListListener mDragListListener;
private DragListCallback mDragListCallback;
private DragItem mDragItem;
private ListSwipeHelper mSwipeHelper;
private float mTouchX;
private float mTouchY;
public DragListView(Context context) {
super(context);
}
public DragListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DragListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mDragItem = new DragItem(getContext());
mRecyclerView = createRecyclerView();
mRecyclerView.setDragItem(mDragItem);
addView(mRecyclerView);
addView(mDragItem.getDragItemView());
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean retValue = handleTouchEvent(event);
return retValue || super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean retValue = handleTouchEvent(event);
return retValue || super.onTouchEvent(event);
}
private boolean handleTouchEvent(MotionEvent event) {
mTouchX = event.getX();
mTouchY = event.getY();
if (isDragging()) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
mRecyclerView.onDragging(event.getX(), event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mRecyclerView.onDragEnded();
break;
}
return true;
}
return false;
}
private DragItemRecyclerView createRecyclerView() {
final DragItemRecyclerView recyclerView = (DragItemRecyclerView) LayoutInflater.from(getContext()).inflate(R.layout.drag_item_recycler_view, this, false);
recyclerView.setMotionEventSplittingEnabled(false);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setVerticalScrollBarEnabled(false);
recyclerView.setHorizontalScrollBarEnabled(false);
recyclerView.setDragItemListener(new DragItemRecyclerView.DragItemListener() {
private int mDragStartPosition;
@Override
public void onDragStarted(int itemPosition, float x, float y) {
getParent().requestDisallowInterceptTouchEvent(true);
mDragStartPosition = itemPosition;
if (mDragListListener != null) {
mDragListListener.onItemDragStarted(itemPosition);
}
}
@Override
public void onDragging(int itemPosition, float x, float y) {
if (mDragListListener != null) {
mDragListListener.onItemDragging(itemPosition, x, y);
}
}
@Override
public void onDragEnded(int newItemPosition) {
if (mDragListListener != null) {
mDragListListener.onItemDragEnded(mDragStartPosition, newItemPosition);
}
}
});
recyclerView.setDragItemCallback(new DragItemRecyclerView.DragItemCallback() {
@Override
public boolean canDragItemAtPosition(int dragPosition) {
return mDragListCallback == null || mDragListCallback.canDragItemAtPosition(dragPosition);
}
@Override
public boolean canDropItemAtPosition(int dropPosition) {
return mDragListCallback == null || mDragListCallback.canDropItemAtPosition(dropPosition);
}
});
return recyclerView;
}
public void setSwipeListener(ListSwipeHelper.OnSwipeListener swipeListener) {
if (mSwipeHelper == null) {
mSwipeHelper = new ListSwipeHelper(getContext().getApplicationContext(), swipeListener);
} else {
mSwipeHelper.setSwipeListener(swipeListener);
}
// Always detach first so we don't get double listeners
mSwipeHelper.detachFromRecyclerView();
if (swipeListener != null) {
mSwipeHelper.attachToRecyclerView(mRecyclerView);
}
}
/**
* Resets the swipe state of all list item views except the one that is passed as an exception view.
*
* @param exceptionView This view will not be reset.
*/
public void resetSwipedViews(View exceptionView) {
if (mSwipeHelper != null) {
mSwipeHelper.resetSwipedViews(exceptionView);
}
}
public RecyclerView getRecyclerView() {
return mRecyclerView;
}
public DragItemAdapter getAdapter() {
if (mRecyclerView != null) {
return (DragItemAdapter) mRecyclerView.getAdapter();
}
return null;
}
public void setAdapter(DragItemAdapter adapter, boolean hasFixedItemSize) {
mRecyclerView.setHasFixedSize(hasFixedItemSize);
mRecyclerView.setAdapter(adapter);
adapter.setDragStartedListener(new DragItemAdapter.DragStartCallback() {
@Override
public boolean startDrag(View itemView, long itemId) {
return mRecyclerView.startDrag(itemView, itemId, mTouchX, mTouchY);
}
@Override
public boolean isDragging() {
return mRecyclerView.isDragging();
}
});
}
public void setLayoutManager(RecyclerView.LayoutManager layout) {
mRecyclerView.setLayoutManager(layout);
}
public void setDragListListener(DragListListener listener) {
mDragListListener = listener;
}
public void setDragListCallback(DragListCallback callback) {
mDragListCallback = callback;
}
public boolean isDragEnabled() {
return mRecyclerView.isDragEnabled();
}
public void setDragEnabled(boolean enabled) {
mRecyclerView.setDragEnabled(enabled);
}
public void setCustomDragItem(DragItem dragItem) {
removeViewAt(1);
DragItem newDragItem;
if (dragItem != null) {
newDragItem = dragItem;
} else {
newDragItem = new DragItem(getContext());
}
newDragItem.setCanDragHorizontally(mDragItem.canDragHorizontally());
newDragItem.setSnapToTouch(mDragItem.isSnapToTouch());
mDragItem = newDragItem;
mRecyclerView.setDragItem(mDragItem);
addView(mDragItem.getDragItemView());
}
public boolean isDragging() {
return mRecyclerView.isDragging();
}
public void setCanDragHorizontally(boolean canDragHorizontally) {
mDragItem.setCanDragHorizontally(canDragHorizontally);
}
public void setSnapDragItemToTouch(boolean snapToTouch) {
mDragItem.setSnapToTouch(snapToTouch);
}
public void setCanNotDragAboveTopItem(boolean canNotDragAboveTop) {
mRecyclerView.setCanNotDragAboveTopItem(canNotDragAboveTop);
}
public void setCanNotDragBelowBottomItem(boolean canNotDragBelowBottom) {
mRecyclerView.setCanNotDragBelowBottomItem(canNotDragBelowBottom);
}
public void setScrollingEnabled(boolean scrollingEnabled) {
mRecyclerView.setScrollingEnabled(scrollingEnabled);
}
/**
* Set if items should not reorder automatically when dragging. If reorder is disabled, drop target
* drawables can be set with {@link #setDropTargetDrawables} which will highlight the current item that
* will be swapped when dropping. By default items will reorder automatically when dragging.
*
* @param disableReorder True if reorder of items should be disabled, false otherwise.
*/
public void setDisableReorderWhenDragging(boolean disableReorder) {
mRecyclerView.setDisableReorderWhenDragging(disableReorder);
}
/**
* If {@link #setDisableReorderWhenDragging} has been set to True then a background and/or foreground drawable
* can be provided to highlight the current item which will be swapped when dropping. These drawables
* will be drawn as decorations in the RecyclerView and will not interfere with the items own background
* and foreground drawables.
*
* @param backgroundDrawable The background drawable for the item that will be swapped.
* @param foregroundDrawable The foreground drawable for the item that will be swapped.
*/
public void setDropTargetDrawables(Drawable backgroundDrawable, Drawable foregroundDrawable) {
mRecyclerView.setDropTargetDrawables(backgroundDrawable, foregroundDrawable);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.api.ldap.model.name;
import java.util.List;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.model.entry.StringValue;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.util.Position;
import org.apache.directory.api.util.Strings;
/**
* A fast LDAP Dn parser that handles only simple DNs. If the Dn contains
* any special character an {@link TooComplexException} is thrown.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
/* No protection*/enum FastDnParser
{
INSTANCE;
/**
* Parses a Dn from a String
*
* @param name The Dn to parse
* @return A valid Dn
* @throws org.apache.directory.api.ldap.model.exception.LdapException If the Dn was invalid
*/
/* No protection*/static Dn parse( String name ) throws LdapException
{
Dn dn = new Dn();
parseDn( name, dn );
return dn;
}
/**
* Parses the given name string and fills the given Dn object.
*
* @param name the name to parse
* @param dn the Dn to fill
*
* @throws LdapInvalidDnException the invalid name exception
*/
/* No protection*/static void parseDn( String name, Dn dn ) throws LdapInvalidDnException
{
parseDn( name, dn.rdns );
dn.setUpName( name );
dn.apply( null );
}
/* No protection*/static void parseDn( String name, List<Rdn> rdns ) throws LdapInvalidDnException
{
if ( ( name == null ) || ( name.trim().length() == 0 ) )
{
// We have an empty Dn, just get out of the function.
return;
}
Position pos = new Position();
pos.start = 0;
pos.length = name.length();
while ( true )
{
Rdn rdn = new Rdn();
parseRdnInternal( name, pos, rdn );
rdns.add( rdn );
if ( !hasMoreChars( pos ) )
{
// end of line reached
break;
}
char c = nextChar( name, pos, true );
switch ( c )
{
case ',':
case ';':
// another Rdn to parse
break;
default:
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04192, c,
pos.start ) );
}
}
}
/**
* Parses the given name string and fills the given Rdn object.
*
* @param name the name to parse
* @param rdn the Rdn to fill
*
* @throws LdapInvalidDnException the invalid name exception
*/
/* No protection*/static void parseRdn( String name, Rdn rdn ) throws LdapInvalidDnException
{
if ( name == null || name.length() == 0 )
{
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04193 ) );
}
if ( rdn == null )
{
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04194 ) );
}
Position pos = new Position();
pos.start = 0;
pos.length = name.length();
parseRdnInternal( name, pos, rdn );
}
private static void parseRdnInternal( String name, Position pos, Rdn rdn ) throws LdapInvalidDnException
{
int rdnStart = pos.start;
// SPACE*
matchSpaces( name, pos );
// attributeType: ALPHA (ALPHA|DIGIT|HYPEN) | NUMERICOID
String type = matchAttributeType( name, pos );
// SPACE*
matchSpaces( name, pos );
// EQUALS
matchEquals( name, pos );
// SPACE*
matchSpaces( name, pos );
// here we only match "simple" values
// stops at \ + # " -> Too Complex Exception
String upValue = matchValue( name, pos );
String value = Strings.trimRight( upValue );
// TODO: trim, normalize, etc
// SPACE*
matchSpaces( name, pos );
String upName = name.substring( rdnStart, pos.start );
Ava ava = new Ava( type, type, new StringValue( upValue ),
new StringValue( value ), upName );
rdn.addAVA( null, ava );
rdn.setUpName( upName );
rdn.normalize();
}
/**
* Matches and forgets optional spaces.
*
* @param name the name
* @param pos the pos
* @throws LdapInvalidDnException
*/
private static void matchSpaces( String name, Position pos ) throws LdapInvalidDnException
{
while ( hasMoreChars( pos ) )
{
char c = nextChar( name, pos, true );
if ( c != ' ' )
{
pos.start--;
break;
}
}
}
/**
* Matches attribute type.
*
* @param name the name
* @param pos the pos
*
* @return the matched attribute type
*
* @throws LdapInvalidDnException the invalid name exception
*/
private static String matchAttributeType( String name, Position pos ) throws LdapInvalidDnException
{
char c = nextChar( name, pos, false );
switch ( c )
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
// descr
return matchAttributeTypeDescr( name, pos );
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// numericoid
return matchAttributeTypeNumericOid( name, pos );
default:
// error
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04195, c,
pos.start ) );
}
}
/**
* Matches attribute type descr.
*
* @param name the name
* @param pos the pos
*
* @return the attribute type descr
*
* @throws LdapInvalidDnException the invalid name exception
*/
private static String matchAttributeTypeDescr( String name, Position pos ) throws LdapInvalidDnException
{
StringBuilder descr = new StringBuilder();
while ( hasMoreChars( pos ) )
{
char c = nextChar( name, pos, true );
switch ( c )
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '_': // Violation of the RFC, just because those idiots at Microsoft decided to support it...
descr.append( c );
break;
case ' ':
case '=':
pos.start--;
return descr.toString();
case '.':
// occurs for RDNs of form "oid.1.2.3=test"
throw TooComplexDnException.INSTANCE;
default:
// error
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04196, c,
pos.start ) );
}
}
return descr.toString();
}
/**
* Matches attribute type numeric OID.
*
* @param name the name
* @param pos the pos
*
* @return the attribute type OID
*
* @throws org.apache.directory.api.ldap.model.exception.LdapInvalidDnException the invalid name exception
*/
private static String matchAttributeTypeNumericOid( String name, Position pos ) throws LdapInvalidDnException
{
StringBuilder numericOid = new StringBuilder();
int dotCount = 0;
while ( true )
{
char c = nextChar( name, pos, true );
switch ( c )
{
case '0':
// leading '0', no other digit may follow!
numericOid.append( c );
c = nextChar( name, pos, true );
switch ( c )
{
case '.':
numericOid.append( c );
dotCount++;
break;
case ' ':
case '=':
pos.start--;
break;
default:
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err(
I18n.ERR_04197, c, pos.start ) );
}
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
numericOid.append( c );
boolean inInnerLoop = true;
while ( inInnerLoop )
{
c = nextChar( name, pos, true );
switch ( c )
{
case ' ':
case '=':
inInnerLoop = false;
pos.start--;
break;
case '.':
inInnerLoop = false;
dotCount++;
// no break!
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
numericOid.append( c );
break;
default:
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err(
I18n.ERR_04197, c, pos.start ) );
}
}
break;
case ' ':
case '=':
pos.start--;
if ( dotCount > 0 )
{
return numericOid.toString();
}
else
{
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04198 ) );
}
default:
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04199, c,
pos.start ) );
}
}
}
/**
* Matches the equals character.
*
* @param name the name
* @param pos the pos
*
* @throws LdapInvalidDnException the invalid name exception
*/
private static void matchEquals( String name, Position pos ) throws LdapInvalidDnException
{
char c = nextChar( name, pos, true );
if ( c != '=' )
{
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04200, c, pos.start ) );
}
}
/**
* Matches the assertion value. This method only handles simple values.
* If we find any special character (BACKSLASH, PLUS, SHARP or DQUOTE),
* a TooComplexException will be thrown.
*
* @param name the name
* @param pos the pos
*
* @return the string
*
* @throws LdapInvalidDnException the invalid name exception
*/
private static String matchValue( String name, Position pos ) throws LdapInvalidDnException
{
StringBuilder value = new StringBuilder();
int numTrailingSpaces = 0;
while ( true )
{
if ( !hasMoreChars( pos ) )
{
pos.start -= numTrailingSpaces;
return value.substring( 0, value.length() - numTrailingSpaces );
}
char c = nextChar( name, pos, true );
switch ( c )
{
case '\\':
case '+':
case '#':
case '"':
throw TooComplexDnException.INSTANCE;
case ',':
case ';':
pos.start--;
pos.start -= numTrailingSpaces;
return value.substring( 0, value.length() - numTrailingSpaces );
case ' ':
numTrailingSpaces++;
value.append( c );
break;
default:
numTrailingSpaces = 0;
value.append( c );
}
}
}
/**
* Gets the next character.
*
* @param name the name
* @param pos the pos
* @param increment true to increment the position
*
* @return the character
* @throws LdapInvalidDnException If no more characters are available
*/
private static char nextChar( String name, Position pos, boolean increment ) throws LdapInvalidDnException
{
if ( !hasMoreChars( pos ) )
{
throw new LdapInvalidDnException( ResultCodeEnum.INVALID_DN_SYNTAX, I18n.err( I18n.ERR_04201, pos.start ) );
}
char c = name.charAt( pos.start );
if ( increment )
{
pos.start++;
}
return c;
}
/**
* Checks if there are more characters.
*
* @param pos the pos
*
* @return true, if more characters are available
*/
private static boolean hasMoreChars( Position pos )
{
return pos.start < pos.length;
}
}
| |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.media;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.os.Build;
import org.chromium.base.Log;
import org.chromium.base.annotations.JNINamespace;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
/**
* Video Capture Device extension of VideoCapture to provide common functionality
* for capture using android.hardware.Camera API (deprecated in API 21). Normal
* Android and Tango devices are extensions of this class.
**/
@JNINamespace("media")
@SuppressWarnings("deprecation")
//TODO: is this class only used on ICS MR1 (or some later version) and above?
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public abstract class VideoCaptureCamera extends VideoCapture
implements android.hardware.Camera.PreviewCallback {
protected android.hardware.Camera mCamera;
// Lock to mutually exclude execution of OnPreviewFrame() and {start/stop}Capture().
protected ReentrantLock mPreviewBufferLock = new ReentrantLock();
// True when native code has started capture.
protected boolean mIsRunning = false;
protected int[] mGlTextures = null;
protected SurfaceTexture mSurfaceTexture = null;
protected static final int GL_TEXTURE_EXTERNAL_OES = 0x8D65;
private static final String TAG = "cr.media";
protected static android.hardware.Camera.CameraInfo getCameraInfo(int id) {
android.hardware.Camera.CameraInfo cameraInfo =
new android.hardware.Camera.CameraInfo();
try {
android.hardware.Camera.getCameraInfo(id, cameraInfo);
} catch (RuntimeException ex) {
Log.e(TAG, "getCameraInfo: Camera.getCameraInfo: " + ex);
return null;
}
return cameraInfo;
}
protected static android.hardware.Camera.Parameters getCameraParameters(
android.hardware.Camera camera) {
android.hardware.Camera.Parameters parameters;
try {
parameters = camera.getParameters();
} catch (RuntimeException ex) {
Log.e(TAG, "getCameraParameters: android.hardware.Camera.getParameters: " + ex);
camera.release();
return null;
}
return parameters;
}
VideoCaptureCamera(Context context,
int id,
long nativeVideoCaptureDeviceAndroid) {
super(context, id, nativeVideoCaptureDeviceAndroid);
}
@Override
public boolean allocate(int width, int height, int frameRate) {
Log.d(TAG, "allocate: requested (%d x %d) @%dfps", width, height, frameRate);
try {
mCamera = android.hardware.Camera.open(mId);
} catch (RuntimeException ex) {
Log.e(TAG, "allocate: Camera.open: " + ex);
return false;
}
android.hardware.Camera.CameraInfo cameraInfo = VideoCaptureCamera.getCameraInfo(mId);
if (cameraInfo == null) {
mCamera.release();
mCamera = null;
return false;
}
mCameraNativeOrientation = cameraInfo.orientation;
// For Camera API, the readings of back-facing camera need to be inverted.
mInvertDeviceOrientationReadings =
(cameraInfo.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
Log.d(TAG, "allocate: Rotation dev=%d, cam=%d, facing back? %s", getDeviceRotation(),
mCameraNativeOrientation, mInvertDeviceOrientationReadings);
android.hardware.Camera.Parameters parameters = getCameraParameters(mCamera);
if (parameters == null) {
mCamera = null;
return false;
}
// getSupportedPreviewFpsRange() returns a List with at least one
// element, but when camera is in bad state, it can return null pointer.
List<int[]> listFpsRange = parameters.getSupportedPreviewFpsRange();
if (listFpsRange == null || listFpsRange.size() == 0) {
Log.e(TAG, "allocate: no fps range found");
return false;
}
// API fps ranges are scaled up x1000 to avoid floating point.
int frameRateScaled = frameRate * 1000;
// Use the first range as the default chosen range.
int[] chosenFpsRange = listFpsRange.get(0);
int frameRateNearest = Math.abs(frameRateScaled - chosenFpsRange[0])
< Math.abs(frameRateScaled - chosenFpsRange[1])
? chosenFpsRange[0] : chosenFpsRange[1];
int chosenFrameRate = (frameRateNearest + 999) / 1000;
int fpsRangeSize = Integer.MAX_VALUE;
for (int[] fpsRange : listFpsRange) {
if (fpsRange[0] <= frameRateScaled && frameRateScaled <= fpsRange[1]
&& (fpsRange[1] - fpsRange[0]) <= fpsRangeSize) {
chosenFpsRange = fpsRange;
chosenFrameRate = frameRate;
fpsRangeSize = fpsRange[1] - fpsRange[0];
}
}
Log.d(TAG, "allocate: fps set to %d, [%d-%d]", chosenFrameRate,
chosenFpsRange[0], chosenFpsRange[1]);
// Calculate size.
List<android.hardware.Camera.Size> listCameraSize =
parameters.getSupportedPreviewSizes();
int minDiff = Integer.MAX_VALUE;
int matchedWidth = width;
int matchedHeight = height;
for (android.hardware.Camera.Size size : listCameraSize) {
int diff = Math.abs(size.width - width)
+ Math.abs(size.height - height);
Log.d(TAG, "allocate: supported (%d, %d), diff=%d", size.width, size.height, diff);
// TODO(wjia): Remove this hack (forcing width to be multiple
// of 32) by supporting stride in video frame buffer.
// Right now, VideoCaptureController requires compact YV12
// (i.e., with no padding).
if (diff < minDiff && (size.width % 32 == 0)) {
minDiff = diff;
matchedWidth = size.width;
matchedHeight = size.height;
}
}
if (minDiff == Integer.MAX_VALUE) {
Log.e(TAG, "allocate: can not find a multiple-of-32 resolution");
return false;
}
Log.d(TAG, "allocate: matched (%d x %d)", matchedWidth, matchedHeight);
if (parameters.isVideoStabilizationSupported()) {
Log.d(TAG, "Image stabilization supported, currently: "
+ parameters.getVideoStabilization() + ", setting it.");
parameters.setVideoStabilization(true);
} else {
Log.d(TAG, "Image stabilization not supported.");
}
if (parameters.getSupportedFocusModes().contains(
android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
parameters.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
} else {
Log.d(TAG, "Continuous focus mode not supported.");
}
setCaptureParameters(matchedWidth, matchedHeight, chosenFrameRate, parameters);
parameters.setPictureSize(matchedWidth, matchedHeight);
parameters.setPreviewSize(matchedWidth, matchedHeight);
parameters.setPreviewFpsRange(chosenFpsRange[0], chosenFpsRange[1]);
parameters.setPreviewFormat(mCaptureFormat.mPixelFormat);
try {
mCamera.setParameters(parameters);
} catch (RuntimeException ex) {
Log.e(TAG, "setParameters: " + ex);
return false;
}
// Set SurfaceTexture. Android Capture needs a SurfaceTexture even if
// it is not going to be used.
mGlTextures = new int[1];
// Generate one texture pointer and bind it as an external texture.
GLES20.glGenTextures(1, mGlTextures, 0);
GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, mGlTextures[0]);
// No mip-mapping with camera source.
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// Clamp to edge is only option.
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
mSurfaceTexture = new SurfaceTexture(mGlTextures[0]);
mSurfaceTexture.setOnFrameAvailableListener(null);
try {
mCamera.setPreviewTexture(mSurfaceTexture);
} catch (IOException ex) {
Log.e(TAG, "allocate: " + ex);
return false;
}
allocateBuffers();
return true;
}
@Override
public boolean startCapture() {
if (mCamera == null) {
Log.e(TAG, "startCapture: camera is null");
return false;
}
mPreviewBufferLock.lock();
try {
if (mIsRunning) {
return true;
}
mIsRunning = true;
} finally {
mPreviewBufferLock.unlock();
}
setPreviewCallback(this);
try {
mCamera.startPreview();
} catch (RuntimeException ex) {
Log.e(TAG, "startCapture: Camera.startPreview: " + ex);
return false;
}
return true;
}
@Override
public boolean stopCapture() {
if (mCamera == null) {
Log.e(TAG, "stopCapture: camera is null");
return true;
}
mPreviewBufferLock.lock();
try {
if (!mIsRunning) {
return true;
}
mIsRunning = false;
} finally {
mPreviewBufferLock.unlock();
}
mCamera.stopPreview();
setPreviewCallback(null);
return true;
}
@Override
public void deallocate() {
if (mCamera == null) return;
stopCapture();
try {
mCamera.setPreviewTexture(null);
if (mGlTextures != null) GLES20.glDeleteTextures(1, mGlTextures, 0);
mCaptureFormat = null;
mCamera.release();
mCamera = null;
} catch (IOException ex) {
Log.e(TAG, "deallocate: failed to deallocate camera, " + ex);
return;
}
}
// Local hook to allow derived classes to configure and plug capture
// buffers if needed.
abstract void allocateBuffers();
// Local hook to allow derived classes to fill capture format and modify
// camera parameters as they see fit.
abstract void setCaptureParameters(
int width,
int height,
int frameRate,
android.hardware.Camera.Parameters cameraParameters);
// Local method to be overriden with the particular setPreviewCallback to be
// used in the implementations.
abstract void setPreviewCallback(android.hardware.Camera.PreviewCallback cb);
}
| |
/*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibatis.sqlmap;
import com.testdomain.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NestedIterateTest extends BaseSqlMapTest {
protected void setUp() throws Exception {
initSqlMap("com/ibatis/sqlmap/maps/SqlMapConfig.xml", null);
initScript("com/scripts/person-init.sql");
initScript("com/scripts/jpetstore-hsqldb-schema.sql");
initScript("com/scripts/jpetstore-hsqldb-dataload.sql");
}
/*
* This test should return 9 rows: ids 1-9
* <p/>
* This method works as expected
*/
public void testShouldReturn9Rows() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results =
sqlMap.queryForList("NestedIterateTest1", po);
assertEquals(9, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
assertEquals(5, ((Person) results.get(4)).getId().intValue());
assertEquals(6, ((Person) results.get(5)).getId().intValue());
assertEquals(7, ((Person) results.get(6)).getId().intValue());
assertEquals(8, ((Person) results.get(7)).getId().intValue());
assertEquals(9, ((Person) results.get(8)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test shoud return 1 row: id 4
*/
public void test02() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest2", po);
assertEquals(1, results.size());
assertEquals(4, ((Person) results.get(0)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 8 rows: ids 1-3, 5-9
*/
public void test03() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(4)); // put first to make the test fail
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest3", po);
assertEquals(8, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(5, ((Person) results.get(3)).getId().intValue());
assertEquals(6, ((Person) results.get(4)).getId().intValue());
assertEquals(7, ((Person) results.get(5)).getId().intValue());
assertEquals(8, ((Person) results.get(6)).getId().intValue());
assertEquals(9, ((Person) results.get(7)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 5 rows: ids 5-9
*/
public void test04() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest4", po);
assertEquals(5, results.size());
assertEquals(5, ((Person) results.get(0)).getId().intValue());
assertEquals(6, ((Person) results.get(1)).getId().intValue());
assertEquals(7, ((Person) results.get(2)).getId().intValue());
assertEquals(8, ((Person) results.get(3)).getId().intValue());
assertEquals(9, ((Person) results.get(4)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 6 rows: ids 4-9
*/
public void test05() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest5", po);
assertEquals(6, results.size());
assertEquals(4, ((Person) results.get(0)).getId().intValue());
assertEquals(5, ((Person) results.get(1)).getId().intValue());
assertEquals(6, ((Person) results.get(2)).getId().intValue());
assertEquals(7, ((Person) results.get(3)).getId().intValue());
assertEquals(8, ((Person) results.get(4)).getId().intValue());
assertEquals(9, ((Person) results.get(5)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 3 rows: ids 1-3
*/
public void test06() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
// go backwards to make the test fail
po.addId(new Integer(9));
po.addId(new Integer(8));
po.addId(new Integer(7));
po.addId(new Integer(6));
po.addId(new Integer(5));
po.addId(new Integer(4));
po.addId(new Integer(3));
po.addId(new Integer(2));
po.addId(new Integer(1));
try {
List results = sqlMap.queryForList("NestedIterateTest6", po);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 4 rows: ids 1-4
*/
public void test07() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
// go backwards to make the test fail
po.addId(new Integer(9));
po.addId(new Integer(8));
po.addId(new Integer(7));
po.addId(new Integer(6));
po.addId(new Integer(5));
po.addId(new Integer(4));
po.addId(new Integer(3));
po.addId(new Integer(2));
po.addId(new Integer(1));
try {
List results = sqlMap.queryForList("NestedIterateTest7", po);
assertEquals(4, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return four rows: ids 1, 2, 7, 8
*/
public void test08() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addFirstName("Jeff");
po.addFirstName("Matt");
po.addLastName("Jones");
po.addLastName("Smith");
try {
List results = sqlMap.queryForList("NestedIterateTest8", po);
assertEquals(4, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(7, ((Person) results.get(2)).getId().intValue());
assertEquals(8, ((Person) results.get(3)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return two rows: ids 1, 2
* <p/>
* This method works when Christian's IBATIS-281 patches are applied
*/
public void test09() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest9", po);
assertEquals(2, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
public void test09a() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest9a", po);
assertEquals(2, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test shoud return 1 row: id 4
*/
public void test10() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest10", po);
assertEquals(1, results.size());
assertEquals(4, ((Person) results.get(0)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 8 rows: ids 1-3, 5-9
*/
public void test11() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(4)); // put first to make the test fail
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest11", po);
assertEquals(8, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(5, ((Person) results.get(3)).getId().intValue());
assertEquals(6, ((Person) results.get(4)).getId().intValue());
assertEquals(7, ((Person) results.get(5)).getId().intValue());
assertEquals(8, ((Person) results.get(6)).getId().intValue());
assertEquals(9, ((Person) results.get(7)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 5 rows: ids 5-9
*/
public void test12() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest12", po);
assertEquals(5, results.size());
assertEquals(5, ((Person) results.get(0)).getId().intValue());
assertEquals(6, ((Person) results.get(1)).getId().intValue());
assertEquals(7, ((Person) results.get(2)).getId().intValue());
assertEquals(8, ((Person) results.get(3)).getId().intValue());
assertEquals(9, ((Person) results.get(4)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 6 rows: ids 4-9
*/
public void test13() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest13", po);
assertEquals(6, results.size());
assertEquals(4, ((Person) results.get(0)).getId().intValue());
assertEquals(5, ((Person) results.get(1)).getId().intValue());
assertEquals(6, ((Person) results.get(2)).getId().intValue());
assertEquals(7, ((Person) results.get(3)).getId().intValue());
assertEquals(8, ((Person) results.get(4)).getId().intValue());
assertEquals(9, ((Person) results.get(5)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 3 rows: ids 1-3
*/
public void test14() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
// go backwards to make the test fail
po.addId(new Integer(9));
po.addId(new Integer(8));
po.addId(new Integer(7));
po.addId(new Integer(6));
po.addId(new Integer(5));
po.addId(new Integer(4));
po.addId(new Integer(3));
po.addId(new Integer(2));
po.addId(new Integer(1));
try {
List results = sqlMap.queryForList("NestedIterateTest14", po);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This test should return 4 rows: ids 1-4
*/
public void test15() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
// go backwards to make the test fail
po.addId(new Integer(9));
po.addId(new Integer(8));
po.addId(new Integer(7));
po.addId(new Integer(6));
po.addId(new Integer(5));
po.addId(new Integer(4));
po.addId(new Integer(3));
po.addId(new Integer(2));
po.addId(new Integer(1));
try {
List results = sqlMap.queryForList("NestedIterateTest15", po);
assertEquals(4, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return six rows: ids 1-6
* <p/>
* This method works when Christian's IBATIS-281 patches are applied
*/
public void test16() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(false));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest16", po);
assertEquals(6, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
assertEquals(5, ((Person) results.get(4)).getId().intValue());
assertEquals(6, ((Person) results.get(5)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return six rows: ids 1-6
* <p/>
* This method works when Christian's IBATIS-281 patches are applied
*/
public void test17() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(false));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest17", po);
assertEquals(6, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
assertEquals(5, ((Person) results.get(4)).getId().intValue());
assertEquals(6, ((Person) results.get(5)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return two rows: ids 1, 2
* <p/>
* This method tests <isNotPropertyAvailable> inside in <iterate>
*/
public void test18() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(false));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest18", po);
assertEquals(2, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return two rows: ids 1, 2
* <p/>
* This method tests <isNotNull> inside an <iterate>
*/
public void test19() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(false));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest19", po);
assertEquals(2, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return two rows: ids 1, 2
* <p/>
* This method tests <isNotEmpty> inside an <iterate>
*/
public void test20() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
NestedIterateParameterObject.AndCondition andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Jeff", new Boolean(false));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
andCondition = new NestedIterateParameterObject.AndCondition();
andCondition.addCondition("first_name =", "Matt", new Boolean(true));
andCondition.addCondition("last_name =", "Jones", new Boolean(true));
po.addOrCondition(andCondition);
try {
List results = sqlMap.queryForList("NestedIterateTest20", po);
assertEquals(2, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return nine rows: ids 1-9
* <p/>
* This method tests the open, close, and prepend attributes
* when no sub elements satisfy - so no where clause should be
* generated
*/
public void test21() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest21", po);
assertEquals(9, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
assertEquals(4, ((Person) results.get(3)).getId().intValue());
assertEquals(5, ((Person) results.get(4)).getId().intValue());
assertEquals(6, ((Person) results.get(5)).getId().intValue());
assertEquals(7, ((Person) results.get(6)).getId().intValue());
assertEquals(8, ((Person) results.get(7)).getId().intValue());
assertEquals(9, ((Person) results.get(8)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return one rows: id 4
* <p/>
* This method tests the open, close, and prepend attributes
* when the first element doesn't satisfy
*/
public void test22() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest22", po);
assertEquals(1, results.size());
assertEquals(4, ((Person) results.get(0)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return one rows: id 1
*/
public void test23() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest23", po);
assertEquals(1, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return one rows: id 9
*/
public void test24() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest24", po);
assertEquals(1, results.size());
assertEquals(9, ((Person) results.get(0)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This method should return three rows: id 1-3
*/
public void test25() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
try {
List results = sqlMap.queryForList("NestedIterateTest25", po);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This tests nesting when objects are maps and not a list nested in a list
*/
public void test26() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
Map params = new HashMap();
params.put("po", po);
try {
List results = sqlMap.queryForList("NestedIterateTest26", params);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This tests nesting when objects are maps and not a list nested in a list
* same as test26 except deeper
*/
public void test27() {
Map firstMap = new HashMap();
List firstList = new ArrayList();
Map params = new HashMap();
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
params.put("po", po);
firstList.add(params);
firstMap.put("firstList", firstList);
try {
List results = sqlMap.queryForList("NestedIterateTest27", firstMap);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This tests nesting when objects are maps and not a list nested in a list
*/
public void test28() {
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
SimpleNestedParameterObject simpleNestedParameterObject =
new SimpleNestedParameterObject();
simpleNestedParameterObject.setNestedIterateParameterObject(po);
try {
List results = sqlMap.queryForList("NestedIterateTest28", simpleNestedParameterObject);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This tests nesting when objects are maps and not a list nested in a list
* same as test26 except deeper
*/
public void test29() {
SimpleNestedParameterObject firstParameterObject =
new SimpleNestedParameterObject();
SimpleNestedParameterObject secondParameterObject =
new SimpleNestedParameterObject();
List parameterObjectList = new ArrayList();
NestedIterateParameterObject po = new NestedIterateParameterObject();
po.addId(new Integer(1));
po.addId(new Integer(2));
po.addId(new Integer(3));
po.addId(new Integer(4));
po.addId(new Integer(5));
po.addId(new Integer(6));
po.addId(new Integer(7));
po.addId(new Integer(8));
po.addId(new Integer(9));
secondParameterObject.setNestedIterateParameterObject(po);
parameterObjectList.add(secondParameterObject);
firstParameterObject.setNestedList(parameterObjectList);
try {
List results = sqlMap.queryForList("NestedIterateTest29", firstParameterObject);
assertEquals(3, results.size());
assertEquals(1, ((Person) results.get(0)).getId().intValue());
assertEquals(2, ((Person) results.get(1)).getId().intValue());
assertEquals(3, ((Person) results.get(2)).getId().intValue());
} catch (Exception e) {
fail(e.getMessage());
}
}
/*
* This tests nesting when a list is initially nested in a bean. so it tests
* [bean]->[list]->[property_of_object_on_exposed_index]
*/
public void test30() {
try {
// prepare item list
Item item1 = new Item();
item1.setItemId("EST-1");
item1.setProductId("FI-SW-01");
List itemList = new ArrayList();
itemList.add(item1);
// prepare product list
Product product1 = new Product();
product1.setProductId("FI-SW-01");
product1.setCategoryId("DOGS");
product1.setItemList(itemList);
List productList = new ArrayList();
productList.add(product1);
//prepare parent category
Category parentCategory = new Category();
parentCategory.setCategoryId("DOGS");
parentCategory.setProductList(productList);
// setup Category
Category category = new Category();
category.setCategoryId("FISH");
category.setParentCategory(parentCategory);
List results = sqlMap.queryForList("NestedIterateTest30", category);
assertEquals(1, results.size());
} catch (Exception e) {
fail(e.getMessage());
}
}
}
| |
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb.client;
import com.google.gwtorm.client.Column;
/** Preferences about a single user. */
public final class AccountGeneralPreferences {
/** Default number of items to display per page. */
public static final short DEFAULT_PAGESIZE = 25;
/** Valid choices for the page size. */
public static final short[] PAGESIZE_CHOICES = {10, 25, 50, 100};
/** Preferred scheme type to download a change. */
public static enum DownloadScheme {
ANON_GIT, ANON_HTTP, ANON_SSH, HTTP, SSH, REPO_DOWNLOAD, DEFAULT_DOWNLOADS;
}
/** Preferred method to download a change. */
public static enum DownloadCommand {
REPO_DOWNLOAD, PULL, CHECKOUT, CHERRY_PICK, FORMAT_PATCH, DEFAULT_DOWNLOADS;
}
public static enum DateFormat {
/** US style dates: Apr 27, Feb 14, 2010 */
STD("MMM d", "MMM d, yyyy"),
/** US style dates: 04/27, 02/14/10 */
US("MM/dd", "MM/dd/yy"),
/** ISO style dates: 2010-02-14 */
ISO("MM-dd", "yyyy-MM-dd"),
/** European style dates: 27. Apr, 27.04.2010 */
EURO("d. MMM", "dd.MM.yyyy");
private final String shortFormat;
private final String longFormat;
DateFormat(String shortFormat, String longFormat) {
this.shortFormat = shortFormat;
this.longFormat = longFormat;
}
public String getShortFormat() {
return shortFormat;
}
public String getLongFormat() {
return longFormat;
}
}
public static enum CommentVisibilityStrategy {
COLLAPSE_ALL,
EXPAND_MOST_RECENT,
EXPAND_RECENT,
EXPAND_ALL;
}
public static enum TimeFormat {
/** 12-hour clock: 1:15 am, 2:13 pm */
HHMM_12("h:mm a"),
/** 24-hour clock: 01:15, 14:13 */
HHMM_24("HH:mm");
private final String format;
TimeFormat(String format) {
this.format = format;
}
public String getFormat() {
return format;
}
}
/** Number of changes to show in a screen. */
@Column(id = 2)
protected short maximumPageSize;
/** Should the site header be displayed when logged in ? */
@Column(id = 3)
protected boolean showSiteHeader;
/** Should the Flash helper movie be used to copy text to the clipboard? */
@Column(id = 4)
protected boolean useFlashClipboard;
/** Type of download URL the user prefers to use. */
@Column(id = 5, length = 20, notNull = false)
protected String downloadUrl;
/** Type of download command the user prefers to use. */
@Column(id = 6, length = 20, notNull = false)
protected String downloadCommand;
/** If true we CC the user on their own changes. */
@Column(id = 7)
protected boolean copySelfOnEmail;
@Column(id = 8, length = 10, notNull = false)
protected String dateFormat;
@Column(id = 9, length = 10, notNull = false)
protected String timeFormat;
/**
* If true display the patch sets in the ChangeScreen in reverse order
* (show latest patch set on top).
*/
@Column(id = 10)
protected boolean reversePatchSetOrder;
@Column(id = 11)
protected boolean showUsernameInReviewCategory;
@Column(id = 12)
protected boolean relativeDateInChangeTable;
@Column(id = 13, length = 20, notNull = false)
protected String commentVisibilityStrategy;
public AccountGeneralPreferences() {
}
public short getMaximumPageSize() {
return maximumPageSize;
}
public void setMaximumPageSize(final short s) {
maximumPageSize = s;
}
public boolean isShowSiteHeader() {
return showSiteHeader;
}
public void setShowSiteHeader(final boolean b) {
showSiteHeader = b;
}
public boolean isUseFlashClipboard() {
return useFlashClipboard;
}
public void setUseFlashClipboard(final boolean b) {
useFlashClipboard = b;
}
public DownloadScheme getDownloadUrl() {
if (downloadUrl == null) {
return null;
}
return DownloadScheme.valueOf(downloadUrl);
}
public void setDownloadUrl(DownloadScheme url) {
if (url != null) {
downloadUrl = url.name();
} else {
downloadUrl = null;
}
}
public DownloadCommand getDownloadCommand() {
if (downloadCommand == null) {
return null;
}
return DownloadCommand.valueOf(downloadCommand);
}
public void setDownloadCommand(DownloadCommand cmd) {
if (cmd != null) {
downloadCommand = cmd.name();
} else {
downloadCommand = null;
}
}
public boolean isCopySelfOnEmails() {
return copySelfOnEmail;
}
public void setCopySelfOnEmails(boolean includeSelfOnEmail) {
copySelfOnEmail = includeSelfOnEmail;
}
public boolean isReversePatchSetOrder() {
return reversePatchSetOrder;
}
public void setReversePatchSetOrder(final boolean reversePatchSetOrder) {
this.reversePatchSetOrder = reversePatchSetOrder;
}
public boolean isShowUsernameInReviewCategory() {
return showUsernameInReviewCategory;
}
public void setShowUsernameInReviewCategory(final boolean showUsernameInReviewCategory) {
this.showUsernameInReviewCategory = showUsernameInReviewCategory;
}
public DateFormat getDateFormat() {
if (dateFormat == null) {
return DateFormat.STD;
}
return DateFormat.valueOf(dateFormat);
}
public void setDateFormat(DateFormat fmt) {
dateFormat = fmt.name();
}
public TimeFormat getTimeFormat() {
if (timeFormat == null) {
return TimeFormat.HHMM_12;
}
return TimeFormat.valueOf(timeFormat);
}
public void setTimeFormat(TimeFormat fmt) {
timeFormat = fmt.name();
}
public boolean isRelativeDateInChangeTable() {
return relativeDateInChangeTable;
}
public void setRelativeDateInChangeTable(final boolean relativeDateInChangeTable) {
this.relativeDateInChangeTable = relativeDateInChangeTable;
}
public CommentVisibilityStrategy getCommentVisibilityStrategy() {
if (commentVisibilityStrategy == null) {
return CommentVisibilityStrategy.EXPAND_RECENT;
}
return CommentVisibilityStrategy.valueOf(commentVisibilityStrategy);
}
public void setCommentVisibilityStrategy(
CommentVisibilityStrategy strategy) {
commentVisibilityStrategy = strategy.name();
}
public void resetToDefaults() {
maximumPageSize = DEFAULT_PAGESIZE;
showSiteHeader = true;
useFlashClipboard = true;
copySelfOnEmail = false;
reversePatchSetOrder = false;
showUsernameInReviewCategory = false;
downloadUrl = null;
downloadCommand = null;
dateFormat = null;
timeFormat = null;
relativeDateInChangeTable = false;
}
}
| |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kogitune.launcher3;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import java.util.ArrayList;
/**
* Class for initiating a drag within a view or across multiple views.
*/
public class DragController {
private static final String TAG = "Launcher.DragController";
/** Indicates the drag is a move. */
public static int DRAG_ACTION_MOVE = 0;
/** Indicates the drag is a copy. */
public static int DRAG_ACTION_COPY = 1;
private static final int SCROLL_DELAY = 500;
private static final int RESCROLL_DELAY = PagedView.PAGE_SNAP_ANIMATION_DURATION + 150;
private static final boolean PROFILE_DRAWING_DURING_DRAG = false;
private static final int SCROLL_OUTSIDE_ZONE = 0;
private static final int SCROLL_WAITING_IN_ZONE = 1;
static final int SCROLL_NONE = -1;
static final int SCROLL_LEFT = 0;
static final int SCROLL_RIGHT = 1;
private static final float MAX_FLING_DEGREES = 35f;
private Launcher mLauncher;
private Handler mHandler;
// temporaries to avoid gc thrash
private Rect mRectTemp = new Rect();
private final int[] mCoordinatesTemp = new int[2];
/** Whether or not we're dragging. */
private boolean mDragging;
/** X coordinate of the down event. */
private int mMotionDownX;
/** Y coordinate of the down event. */
private int mMotionDownY;
/** the area at the edge of the screen that makes the workspace go left
* or right while you're dragging.
*/
private int mScrollZone;
private DropTarget.DragObject mDragObject;
/** Who can receive drop events */
private ArrayList<DropTarget> mDropTargets = new ArrayList<DropTarget>();
private ArrayList<DragListener> mListeners = new ArrayList<DragListener>();
private DropTarget mFlingToDeleteDropTarget;
/** The window token used as the parent for the DragView. */
private IBinder mWindowToken;
/** The view that will be scrolled when dragging to the left and right edges of the screen. */
private View mScrollView;
private View mMoveTarget;
private DragScroller mDragScroller;
private int mScrollState = SCROLL_OUTSIDE_ZONE;
private ScrollRunnable mScrollRunnable = new ScrollRunnable();
private DropTarget mLastDropTarget;
private InputMethodManager mInputMethodManager;
private int mLastTouch[] = new int[2];
private long mLastTouchUpTime = -1;
private int mDistanceSinceScroll = 0;
private int mTmpPoint[] = new int[2];
private Rect mDragLayerRect = new Rect();
protected int mFlingToDeleteThresholdVelocity;
private VelocityTracker mVelocityTracker;
/**
* Interface to receive notifications when a drag starts or stops
*/
interface DragListener {
/**
* A drag has begun
*
* @param source An object representing where the drag originated
* @param info The data associated with the object that is being dragged
* @param dragAction The drag action: either {@link DragController#DRAG_ACTION_MOVE}
* or {@link DragController#DRAG_ACTION_COPY}
*/
void onDragStart(DragSource source, Object info, int dragAction);
/**
* The drag has ended
*/
void onDragEnd();
}
/**
* Used to create a new DragLayer from XML.
*
* @param context The application's context.
*/
public DragController(Launcher launcher) {
Resources r = launcher.getResources();
mLauncher = launcher;
mHandler = new Handler();
mScrollZone = r.getDimensionPixelSize(R.dimen.scroll_zone);
mVelocityTracker = VelocityTracker.obtain();
float density = r.getDisplayMetrics().density;
mFlingToDeleteThresholdVelocity =
(int) (r.getInteger(R.integer.config_flingToDeleteMinVelocity) * density);
}
public boolean dragging() {
return mDragging;
}
/**
* Starts a drag.
*
* @param v The view that is being dragged
* @param bmp The bitmap that represents the view being dragged
* @param source An object representing where the drag originated
* @param dragInfo The data associated with the object that is being dragged
* @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
* {@link #DRAG_ACTION_COPY}
* @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
* Makes dragging feel more precise, e.g. you can clip out a transparent border
*/
public void startDrag(View v, Bitmap bmp, DragSource source, Object dragInfo, int dragAction,
Point extraPadding, float initialDragViewScale) {
int[] loc = mCoordinatesTemp;
mLauncher.getDragLayer().getLocationInDragLayer(v, loc);
int viewExtraPaddingLeft = extraPadding != null ? extraPadding.x : 0;
int viewExtraPaddingTop = extraPadding != null ? extraPadding.y : 0;
int dragLayerX = loc[0] + v.getPaddingLeft() + viewExtraPaddingLeft +
(int) ((initialDragViewScale * bmp.getWidth() - bmp.getWidth()) / 2);
int dragLayerY = loc[1] + v.getPaddingTop() + viewExtraPaddingTop +
(int) ((initialDragViewScale * bmp.getHeight() - bmp.getHeight()) / 2);
startDrag(bmp, dragLayerX, dragLayerY, source, dragInfo, dragAction, null,
null, initialDragViewScale);
if (dragAction == DRAG_ACTION_MOVE) {
v.setVisibility(View.GONE);
}
}
/**
* Starts a drag.
*
* @param b The bitmap to display as the drag image. It will be re-scaled to the
* enlarged size.
* @param dragLayerX The x position in the DragLayer of the left-top of the bitmap.
* @param dragLayerY The y position in the DragLayer of the left-top of the bitmap.
* @param source An object representing where the drag originated
* @param dragInfo The data associated with the object that is being dragged
* @param dragAction The drag action: either {@link #DRAG_ACTION_MOVE} or
* {@link #DRAG_ACTION_COPY}
* @param dragRegion Coordinates within the bitmap b for the position of item being dragged.
* Makes dragging feel more precise, e.g. you can clip out a transparent border
*/
public void startDrag(Bitmap b, int dragLayerX, int dragLayerY,
DragSource source, Object dragInfo, int dragAction, Point dragOffset, Rect dragRegion,
float initialDragViewScale) {
if (PROFILE_DRAWING_DURING_DRAG) {
android.os.Debug.startMethodTracing("Launcher");
}
// Hide soft keyboard, if visible
if (mInputMethodManager == null) {
mInputMethodManager = (InputMethodManager)
mLauncher.getSystemService(Context.INPUT_METHOD_SERVICE);
}
mInputMethodManager.hideSoftInputFromWindow(mWindowToken, 0);
for (DragListener listener : mListeners) {
listener.onDragStart(source, dragInfo, dragAction);
}
final int registrationX = mMotionDownX - dragLayerX;
final int registrationY = mMotionDownY - dragLayerY;
final int dragRegionLeft = dragRegion == null ? 0 : dragRegion.left;
final int dragRegionTop = dragRegion == null ? 0 : dragRegion.top;
mDragging = true;
mDragObject = new DropTarget.DragObject();
mDragObject.dragComplete = false;
mDragObject.xOffset = mMotionDownX - (dragLayerX + dragRegionLeft);
mDragObject.yOffset = mMotionDownY - (dragLayerY + dragRegionTop);
mDragObject.dragSource = source;
mDragObject.dragInfo = dragInfo;
final DragView dragView = mDragObject.dragView = new DragView(mLauncher, b, registrationX,
registrationY, 0, 0, b.getWidth(), b.getHeight(), initialDragViewScale);
if (dragOffset != null) {
dragView.setDragVisualizeOffset(new Point(dragOffset));
}
if (dragRegion != null) {
dragView.setDragRegion(new Rect(dragRegion));
}
mLauncher.getDragLayer().performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
dragView.show(mMotionDownX, mMotionDownY);
handleMoveEvent(mMotionDownX, mMotionDownY);
}
/**
* Draw the view into a bitmap.
*/
Bitmap getViewBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
float alpha = v.getAlpha();
v.setAlpha(1.0f);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setAlpha(alpha);
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
/**
* Call this from a drag source view like this:
*
* <pre>
* @Override
* public boolean dispatchKeyEvent(KeyEvent event) {
* return mDragController.dispatchKeyEvent(this, event)
* || super.dispatchKeyEvent(event);
* </pre>
*/
public boolean dispatchKeyEvent(KeyEvent event) {
return mDragging;
}
public boolean isDragging() {
return mDragging;
}
/**
* Stop dragging without dropping.
*/
public void cancelDrag() {
if (mDragging) {
if (mLastDropTarget != null) {
mLastDropTarget.onDragExit(mDragObject);
}
mDragObject.deferDragViewCleanupPostAnimation = false;
mDragObject.cancelled = true;
mDragObject.dragComplete = true;
mDragObject.dragSource.onDropCompleted(null, mDragObject, false, false);
}
endDrag();
}
public void onAppsRemoved(ArrayList<AppInfo> appInfos, Context context) {
// Cancel the current drag if we are removing an app that we are dragging
if (mDragObject != null) {
Object rawDragInfo = mDragObject.dragInfo;
if (rawDragInfo instanceof ShortcutInfo) {
ShortcutInfo dragInfo = (ShortcutInfo) rawDragInfo;
for (AppInfo info : appInfos) {
// Added null checks to prevent NPE we've seen in the wild
if (dragInfo != null &&
dragInfo.intent != null) {
boolean isSameComponent =
dragInfo.intent.getComponent().equals(info.componentName);
if (isSameComponent) {
cancelDrag();
return;
}
}
}
}
}
}
private void endDrag() {
if (mDragging) {
mDragging = false;
clearScrollRunnable();
boolean isDeferred = false;
if (mDragObject.dragView != null) {
isDeferred = mDragObject.deferDragViewCleanupPostAnimation;
if (!isDeferred) {
mDragObject.dragView.remove();
}
mDragObject.dragView = null;
}
// Only end the drag if we are not deferred
if (!isDeferred) {
for (DragListener listener : mListeners) {
listener.onDragEnd();
}
}
}
releaseVelocityTracker();
}
/**
* This only gets called as a result of drag view cleanup being deferred in endDrag();
*/
void onDeferredEndDrag(DragView dragView) {
dragView.remove();
if (mDragObject.deferDragViewCleanupPostAnimation) {
// If we skipped calling onDragEnd() before, do it now
for (DragListener listener : mListeners) {
listener.onDragEnd();
}
}
}
void onDeferredEndFling(DropTarget.DragObject d) {
d.dragSource.onFlingToDeleteCompleted();
}
/**
* Clamps the position to the drag layer bounds.
*/
private int[] getClampedDragLayerPos(float x, float y) {
mLauncher.getDragLayer().getLocalVisibleRect(mDragLayerRect);
mTmpPoint[0] = (int) Math.max(mDragLayerRect.left, Math.min(x, mDragLayerRect.right - 1));
mTmpPoint[1] = (int) Math.max(mDragLayerRect.top, Math.min(y, mDragLayerRect.bottom - 1));
return mTmpPoint;
}
long getLastGestureUpTime() {
if (mDragging) {
return System.currentTimeMillis();
} else {
return mLastTouchUpTime;
}
}
void resetLastGestureUpTime() {
mLastTouchUpTime = -1;
}
/**
* Call this from a drag source view.
*/
public boolean onInterceptTouchEvent(MotionEvent ev) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(Launcher.TAG, "DragController.onInterceptTouchEvent " + ev + " mDragging="
+ mDragging);
}
// Update the velocity tracker
acquireVelocityTrackerAndAddMovement(ev);
final int action = ev.getAction();
final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
final int dragLayerX = dragLayerPos[0];
final int dragLayerY = dragLayerPos[1];
switch (action) {
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
mMotionDownX = dragLayerX;
mMotionDownY = dragLayerY;
mLastDropTarget = null;
break;
case MotionEvent.ACTION_UP:
mLastTouchUpTime = System.currentTimeMillis();
if (mDragging) {
PointF vec = isFlingingToDelete(mDragObject.dragSource);
if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
vec = null;
}
if (vec != null) {
dropOnFlingToDeleteTarget(dragLayerX, dragLayerY, vec);
} else {
drop(dragLayerX, dragLayerY);
}
}
endDrag();
break;
case MotionEvent.ACTION_CANCEL:
cancelDrag();
break;
}
return mDragging;
}
/**
* Sets the view that should handle move events.
*/
void setMoveTarget(View view) {
mMoveTarget = view;
}
public boolean dispatchUnhandledMove(View focused, int direction) {
return mMoveTarget != null && mMoveTarget.dispatchUnhandledMove(focused, direction);
}
private void clearScrollRunnable() {
mHandler.removeCallbacks(mScrollRunnable);
if (mScrollState == SCROLL_WAITING_IN_ZONE) {
mScrollState = SCROLL_OUTSIDE_ZONE;
mScrollRunnable.setDirection(SCROLL_RIGHT);
mDragScroller.onExitScrollArea();
mLauncher.getDragLayer().onExitScrollArea();
}
}
private void handleMoveEvent(int x, int y) {
mDragObject.dragView.move(x, y);
// Drop on someone?
final int[] coordinates = mCoordinatesTemp;
DropTarget dropTarget = findDropTarget(x, y, coordinates);
mDragObject.x = coordinates[0];
mDragObject.y = coordinates[1];
checkTouchMove(dropTarget);
// Check if we are hovering over the scroll areas
mDistanceSinceScroll +=
Math.sqrt(Math.pow(mLastTouch[0] - x, 2) + Math.pow(mLastTouch[1] - y, 2));
mLastTouch[0] = x;
mLastTouch[1] = y;
checkScrollState(x, y);
}
public void forceTouchMove() {
int[] dummyCoordinates = mCoordinatesTemp;
DropTarget dropTarget = findDropTarget(mLastTouch[0], mLastTouch[1], dummyCoordinates);
mDragObject.x = dummyCoordinates[0];
mDragObject.y = dummyCoordinates[1];
checkTouchMove(dropTarget);
}
private void checkTouchMove(DropTarget dropTarget) {
if (dropTarget != null) {
if (mLastDropTarget != dropTarget) {
if (mLastDropTarget != null) {
mLastDropTarget.onDragExit(mDragObject);
}
dropTarget.onDragEnter(mDragObject);
}
dropTarget.onDragOver(mDragObject);
} else {
if (mLastDropTarget != null) {
mLastDropTarget.onDragExit(mDragObject);
}
}
mLastDropTarget = dropTarget;
}
private void checkScrollState(int x, int y) {
final int slop = ViewConfiguration.get(mLauncher).getScaledWindowTouchSlop();
final int delay = mDistanceSinceScroll < slop ? RESCROLL_DELAY : SCROLL_DELAY;
final DragLayer dragLayer = mLauncher.getDragLayer();
final boolean isRtl = (dragLayer.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
final int forwardDirection = isRtl ? SCROLL_RIGHT : SCROLL_LEFT;
final int backwardsDirection = isRtl ? SCROLL_LEFT : SCROLL_RIGHT;
if (x < mScrollZone) {
if (mScrollState == SCROLL_OUTSIDE_ZONE) {
mScrollState = SCROLL_WAITING_IN_ZONE;
if (mDragScroller.onEnterScrollArea(x, y, forwardDirection)) {
dragLayer.onEnterScrollArea(forwardDirection);
mScrollRunnable.setDirection(forwardDirection);
mHandler.postDelayed(mScrollRunnable, delay);
}
}
} else if (x > mScrollView.getWidth() - mScrollZone) {
if (mScrollState == SCROLL_OUTSIDE_ZONE) {
mScrollState = SCROLL_WAITING_IN_ZONE;
if (mDragScroller.onEnterScrollArea(x, y, backwardsDirection)) {
dragLayer.onEnterScrollArea(backwardsDirection);
mScrollRunnable.setDirection(backwardsDirection);
mHandler.postDelayed(mScrollRunnable, delay);
}
}
} else {
clearScrollRunnable();
}
}
/**
* Call this from a drag source view.
*/
public boolean onTouchEvent(MotionEvent ev) {
if (!mDragging) {
return false;
}
// Update the velocity tracker
acquireVelocityTrackerAndAddMovement(ev);
final int action = ev.getAction();
final int[] dragLayerPos = getClampedDragLayerPos(ev.getX(), ev.getY());
final int dragLayerX = dragLayerPos[0];
final int dragLayerY = dragLayerPos[1];
switch (action) {
case MotionEvent.ACTION_DOWN:
// Remember where the motion event started
mMotionDownX = dragLayerX;
mMotionDownY = dragLayerY;
if ((dragLayerX < mScrollZone) || (dragLayerX > mScrollView.getWidth() - mScrollZone)) {
mScrollState = SCROLL_WAITING_IN_ZONE;
mHandler.postDelayed(mScrollRunnable, SCROLL_DELAY);
} else {
mScrollState = SCROLL_OUTSIDE_ZONE;
}
handleMoveEvent(dragLayerX, dragLayerY);
break;
case MotionEvent.ACTION_MOVE:
handleMoveEvent(dragLayerX, dragLayerY);
break;
case MotionEvent.ACTION_UP:
// Ensure that we've processed a move event at the current pointer location.
handleMoveEvent(dragLayerX, dragLayerY);
mHandler.removeCallbacks(mScrollRunnable);
if (mDragging) {
PointF vec = isFlingingToDelete(mDragObject.dragSource);
if (!DeleteDropTarget.willAcceptDrop(mDragObject.dragInfo)) {
vec = null;
}
if (vec != null) {
dropOnFlingToDeleteTarget(dragLayerX, dragLayerY, vec);
} else {
drop(dragLayerX, dragLayerY);
}
}
endDrag();
break;
case MotionEvent.ACTION_CANCEL:
mHandler.removeCallbacks(mScrollRunnable);
cancelDrag();
break;
}
return true;
}
/**
* Determines whether the user flung the current item to delete it.
*
* @return the vector at which the item was flung, or null if no fling was detected.
*/
private PointF isFlingingToDelete(DragSource source) {
if (mFlingToDeleteDropTarget == null) return null;
if (!source.supportsFlingToDelete()) return null;
ViewConfiguration config = ViewConfiguration.get(mLauncher);
mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
// Do a quick dot product test to ensure that we are flinging upwards
PointF vel = new PointF(mVelocityTracker.getXVelocity(),
mVelocityTracker.getYVelocity());
PointF upVec = new PointF(0f, -1f);
float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
(vel.length() * upVec.length()));
if (theta <= Math.toRadians(MAX_FLING_DEGREES)) {
return vel;
}
}
return null;
}
private void dropOnFlingToDeleteTarget(float x, float y, PointF vel) {
final int[] coordinates = mCoordinatesTemp;
mDragObject.x = coordinates[0];
mDragObject.y = coordinates[1];
// Clean up dragging on the target if it's not the current fling delete target otherwise,
// start dragging to it.
if (mLastDropTarget != null && mFlingToDeleteDropTarget != mLastDropTarget) {
mLastDropTarget.onDragExit(mDragObject);
}
// Drop onto the fling-to-delete target
boolean accepted = false;
mFlingToDeleteDropTarget.onDragEnter(mDragObject);
// We must set dragComplete to true _only_ after we "enter" the fling-to-delete target for
// "drop"
mDragObject.dragComplete = true;
mFlingToDeleteDropTarget.onDragExit(mDragObject);
if (mFlingToDeleteDropTarget.acceptDrop(mDragObject)) {
mFlingToDeleteDropTarget.onFlingToDelete(mDragObject, mDragObject.x, mDragObject.y,
vel);
accepted = true;
}
mDragObject.dragSource.onDropCompleted((View) mFlingToDeleteDropTarget, mDragObject, true,
accepted);
}
private void drop(float x, float y) {
final int[] coordinates = mCoordinatesTemp;
final DropTarget dropTarget = findDropTarget((int) x, (int) y, coordinates);
mDragObject.x = coordinates[0];
mDragObject.y = coordinates[1];
boolean accepted = false;
if (dropTarget != null) {
mDragObject.dragComplete = true;
dropTarget.onDragExit(mDragObject);
if (dropTarget.acceptDrop(mDragObject)) {
dropTarget.onDrop(mDragObject);
accepted = true;
}
}
mDragObject.dragSource.onDropCompleted((View) dropTarget, mDragObject, false, accepted);
}
private DropTarget findDropTarget(int x, int y, int[] dropCoordinates) {
final Rect r = mRectTemp;
final ArrayList<DropTarget> dropTargets = mDropTargets;
final int count = dropTargets.size();
for (int i=count-1; i>=0; i--) {
DropTarget target = dropTargets.get(i);
if (!target.isDropEnabled())
continue;
target.getHitRectRelativeToDragLayer(r);
mDragObject.x = x;
mDragObject.y = y;
if (r.contains(x, y)) {
dropCoordinates[0] = x;
dropCoordinates[1] = y;
mLauncher.getDragLayer().mapCoordInSelfToDescendent((View) target, dropCoordinates);
return target;
}
}
return null;
}
public void setDragScoller(DragScroller scroller) {
mDragScroller = scroller;
}
public void setWindowToken(IBinder token) {
mWindowToken = token;
}
/**
* Sets the drag listner which will be notified when a drag starts or ends.
*/
public void addDragListener(DragListener l) {
mListeners.add(l);
}
/**
* Remove a previously installed drag listener.
*/
public void removeDragListener(DragListener l) {
mListeners.remove(l);
}
/**
* Add a DropTarget to the list of potential places to receive drop events.
*/
public void addDropTarget(DropTarget target) {
mDropTargets.add(target);
}
/**
* Don't send drop events to <em>target</em> any more.
*/
public void removeDropTarget(DropTarget target) {
mDropTargets.remove(target);
}
/**
* Sets the current fling-to-delete drop target.
*/
public void setFlingToDeleteDropTarget(DropTarget target) {
mFlingToDeleteDropTarget = target;
}
private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
private void releaseVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
/**
* Set which view scrolls for touch events near the edge of the screen.
*/
public void setScrollView(View v) {
mScrollView = v;
}
DragView getDragView() {
return mDragObject.dragView;
}
private class ScrollRunnable implements Runnable {
private int mDirection;
ScrollRunnable() {
}
public void run() {
if (mDragScroller != null) {
if (mDirection == SCROLL_LEFT) {
mDragScroller.scrollLeft();
} else {
mDragScroller.scrollRight();
}
mScrollState = SCROLL_OUTSIDE_ZONE;
mDistanceSinceScroll = 0;
mDragScroller.onExitScrollArea();
mLauncher.getDragLayer().onExitScrollArea();
if (isDragging()) {
// Check the scroll again so that we can requeue the scroller if necessary
checkScrollState(mLastTouch[0], mLastTouch[1]);
}
}
}
void setDirection(int direction) {
mDirection = direction;
}
}
}
| |
/*
* Copyright 2017 Marcus Portmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package guru.mmp.application.messaging.messages;
//~--- non-JDK imports --------------------------------------------------------
import guru.mmp.application.messaging.Message;
import guru.mmp.application.messaging.MessagingException;
import guru.mmp.application.messaging.WbxmlMessageData;
import guru.mmp.common.util.ISO8601;
import guru.mmp.common.wbxml.Document;
import guru.mmp.common.wbxml.Element;
import guru.mmp.common.wbxml.Encoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
//~--- JDK imports ------------------------------------------------------------
/**
* The <code>GetCodeCategoryWithParametersRequestData</code> class manages the data for a
* "Get Code Category With Parameters Request" message.
* <p/>
* This is a synchronous message.
*
* @author Marcus Portmann
*/
public class GetCodeCategoryWithParametersRequestData extends WbxmlMessageData
{
/**
* The UUID for the "Get Code Category With Parameters Request" message.
*/
public static final UUID MESSAGE_TYPE_ID = UUID.fromString(
"3500a28a-6a2c-482b-b81f-a849c9c3ef79");
/**
* The Universally Unique Identifier (UUID) used to uniquely identify the code category to
* retrieve.
*/
private UUID id;
/**
* The date and time the code category was last retrieved.
*/
private LocalDateTime lastRetrieved;
/**
* The parameters.
*/
private Map<String, String> parameters;
/**
* Should the codes for the code category be returned if the code category is current?
*/
private boolean returnCodesIfCurrent;
/**
* Constructs a new <code>GetCodeCategoryWithParametersRequestData</code>.
*/
public GetCodeCategoryWithParametersRequestData()
{
super(MESSAGE_TYPE_ID, Message.Priority.HIGH);
parameters = new HashMap<>();
}
/**
* Constructs a new <code>GetCodeCategoryWithParametersRequestData</code>.
*
* @param id the Universally Unique Identifier (UUID) used to uniquely identify
* the code category to retrieve
* @param lastRetrieved the date and time the code category was last retrieved
* @param parameters the parameters
* @param returnCodesIfCurrent should the codes for the code category be returned if the code
* category is current
*/
public GetCodeCategoryWithParametersRequestData(UUID id, LocalDateTime lastRetrieved, Map<String,
String> parameters, boolean returnCodesIfCurrent)
{
super(MESSAGE_TYPE_ID, Message.Priority.HIGH);
this.id = id;
this.lastRetrieved = lastRetrieved;
this.parameters = parameters;
this.returnCodesIfCurrent = returnCodesIfCurrent;
}
/**
* Extract the message data from the WBXML data for a message.
*
* @param messageData the WBXML data for the message
*
* @return <code>true</code> if the message data was extracted successfully from the WBXML data or
* <code>false</code> otherwise
*/
public boolean fromMessageData(byte[] messageData)
throws MessagingException
{
Element rootElement = parseWBXML(messageData).getRootElement();
if (!rootElement.getName().equals("GetCodeCategoryWithParametersRequest"))
{
return false;
}
if ((!rootElement.hasChild("Id"))
|| (!rootElement.hasChild("LastRetrieved"))
|| (!rootElement.hasChild("ReturnCodesIfCurrent")))
{
return false;
}
this.id = UUID.fromString(rootElement.getChildText("Id"));
String lastRetrievedValue = rootElement.getChildText("LastRetrieved");
if (lastRetrievedValue.contains("T"))
{
try
{
this.lastRetrieved = ISO8601.toLocalDateTime(lastRetrievedValue);
}
catch (Throwable e)
{
throw new RuntimeException("Failed to parse the LastRetrieved ISO8601 timestamp ("
+ lastRetrievedValue + ") for" + " the \"Get Code Category Request\" message", e);
}
}
else
{
this.lastRetrieved = LocalDateTime.ofInstant(Instant.ofEpochSecond(Long.parseLong(
lastRetrievedValue)), ZoneId.systemDefault());
}
this.returnCodesIfCurrent = Boolean.parseBoolean(rootElement.getChildText(
"ReturnCodesIfCurrent"));
this.parameters = new HashMap<>();
List<Element> parameterElements = rootElement.getChildren("Parameter");
for (Element parameterElement : parameterElements)
{
String parameterName = parameterElement.getAttributeValue("name");
String parameterValue = parameterElement.getAttributeValue("value");
this.parameters.put(parameterName, parameterValue);
}
return true;
}
/**
* Returns the Universally Unique Identifier (UUID) uniquely identifying the code category
* to retrieve.
*
* @return the Universally Unique Identifier (UUID) uniquely identify the code category to
* retrieve
*/
public UUID getId()
{
return id;
}
/**
* Returns the date and time the code category was last retrieved.
*
* @return the date and time the code category was last retrieved
*/
public LocalDateTime getLastRetrieved()
{
return lastRetrieved;
}
/**
* Returns the parameters.
*
* @return the parameters
*/
public Map<String, String> getParameters()
{
return parameters;
}
/**
* Returns <code>true</code> if the codes for the code category be returned if the code category
* is current or <code>false</code> otherwise.
*
* @return <code>true</code> if the codes for the code category be returned if the code category
* is current or <code>false</code> otherwise
*/
public boolean getReturnCodesIfCurrent()
{
return returnCodesIfCurrent;
}
/**
* Returns the WBXML data representation of the message data that will be sent as part of a
* message.
*
* @return the WBXML data representation of the message data that will be sent as part of a
* message
*/
public byte[] toMessageData()
throws MessagingException
{
Element rootElement = new Element("GetCodeCategoryWithParametersRequest");
rootElement.addContent(new Element("Id", id.toString()));
rootElement.addContent(new Element("LastRetrieved",
(lastRetrieved == null)
? ISO8601.now()
: ISO8601.fromLocalDateTime(lastRetrieved)));
rootElement.addContent(new Element("ReturnCodesIfCurrent", String.valueOf(
returnCodesIfCurrent)));
for (String parameterName : parameters.keySet())
{
String parameterValue = parameters.get(parameterName);
Element parameterElement = new Element("Parameter");
parameterElement.setAttribute("name", parameterName);
parameterElement.setAttribute("value", parameterValue);
rootElement.addContent(parameterElement);
}
Encoder encoder = new Encoder(new Document(rootElement));
return encoder.getData();
}
}
| |
/*
* Copyright (c) 2016 Nova Ordis LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.novaordis.utilities.zip;
import io.novaordis.utilities.Files;
import io.novaordis.utilities.Util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Ovidiu Feodorov <ovidiu@novaordis.com>
* @since 11/28/16
*/
public class ZipUtilTest {
// Constants -------------------------------------------------------------------------------------------------------
private static final Logger log = LoggerFactory.getLogger(ZipUtilTest.class);
// Static ----------------------------------------------------------------------------------------------------------
// Attributes ------------------------------------------------------------------------------------------------------
// Constructors ----------------------------------------------------------------------------------------------------
// Public ----------------------------------------------------------------------------------------------------------
private File scratchDirectory;
@Before
public void before() throws Exception {
String projectBaseDirName = System.getProperty("basedir");
scratchDirectory = new File(projectBaseDirName, "target/test-scratch");
assertTrue(scratchDirectory.isDirectory());
}
@After
public void after() throws Exception {
//
// scratch directory cleanup
//
assertTrue(io.novaordis.utilities.Files.rmdir(scratchDirectory, false));
}
// Test ------------------------------------------------------------------------------------------------------------
// list ------------------------------------------------------------------------------------------------------------
@Test
public void list_Null() throws Exception {
try {
ZipUtil.list(null);
fail("should throw exception");
}
catch(IllegalArgumentException e) {
log.info(e.getMessage());
}
}
@Test
public void list_NotAFile() throws Exception {
try {
ZipUtil.list(new File("/I/am/sure/no/such/file/exists"));
fail("should throw exception");
}
catch(IllegalArgumentException e) {
log.info(e.getMessage());
}
}
@Test
public void list_NotAZipFile() throws Exception {
File fakeZip = new File(scratchDirectory, "fake.zip");
assertTrue(Files.write(fakeZip, "NOT A ZIP FILE"));
try {
ZipUtil.list(fakeZip);
fail("should throw exception");
}
catch(IllegalArgumentException e) {
String msg = e.getMessage();
log.info(msg);
assertEquals(msg, "invalid or corrupted zip file " + fakeZip.getAbsolutePath());
}
}
@Test
public void list() throws Exception {
File zipFile = Util.cp("zip/zip-example.zip", scratchDirectory);
String list = ZipUtil.list(zipFile);
log.info(list);
String expected =
"top-level-dir/\n" +
"top-level-dir/a/\n" +
"top-level-dir/a/a-file.txt\n" +
"top-level-dir/a/x/\n" +
"top-level-dir/a/x/x-file.txt\n" +
"top-level-dir/a/y/\n" +
"top-level-dir/a/z/\n" +
"top-level-dir/b/\n" +
"top-level-dir/c/\n" +
"top-level-dir/top-level-file.txt\n";
assertEquals(expected, list);
}
// getTopLevelDirectoryName ----------------------------------------------------------------------------------------
@Test
public void getTopLevelDirectoryName_Null() throws Exception {
try {
ZipUtil.getTopLevelDirectoryName(null);
fail("should throw exception");
}
catch(IllegalArgumentException e) {
log.info(e.getMessage());
}
}
@Test
public void getTopLevelDirectoryName_NotAFile() throws Exception {
try {
ZipUtil.getTopLevelDirectoryName(new File("/I/am/sure/no/such/file/exists"));
fail("should throw exception");
}
catch(IllegalArgumentException e) {
log.info(e.getMessage());
}
}
@Test
public void getTopLevelDirectoryName_NotAZipFile() throws Exception {
File fakeZip = new File(scratchDirectory, "fake.zip");
assertTrue(Files.write(fakeZip, "NOT A ZIP FILE"));
try {
ZipUtil.getTopLevelDirectoryName(fakeZip);
fail("should throw exception");
}
catch(IllegalArgumentException e) {
String msg = e.getMessage();
log.info(msg);
assertEquals(msg, "invalid or corrupted zip file " + fakeZip.getAbsolutePath());
}
}
@Test
public void getTopLevelDirectoryName_RelativeDirectories_MultipleTopLevelDirectories() throws Exception {
File zipFile = Util.cp("zip/two-top-level-directories.zip", scratchDirectory);
String name = ZipUtil.getTopLevelDirectoryName(zipFile);
assertNull(name);
}
@Test
public void getTopLevelDirectoryName_NoTopLevelDirectories() throws Exception {
File zipFile = Util.cp("zip/no-top-level-directory.zip", scratchDirectory);
String name = ZipUtil.getTopLevelDirectoryName(zipFile);
assertNull(name);
}
@Test
public void getTopLevelDirectoryName_RelativeDirectories() throws Exception {
File zipFile = Util.cp("zip/zip-example.zip", scratchDirectory);
String name = ZipUtil.getTopLevelDirectoryName(zipFile);
assertEquals("top-level-dir", name);
}
// Package protected -----------------------------------------------------------------------------------------------
// Protected -------------------------------------------------------------------------------------------------------
// Private ---------------------------------------------------------------------------------------------------------
// Inner classes ---------------------------------------------------------------------------------------------------
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.rdf.model.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.jena.rdf.model.* ;
import org.apache.jena.rdf.model.test.helpers.ModelHelper ;
import org.apache.jena.rdf.model.test.helpers.TestingModelFactory ;
import org.apache.jena.test.JenaTestBase ;
import org.junit.Assert;
/**
* This class tests various properties of RDFNodes.
*/
public class TestRDFNodes extends AbstractModelTestBase
{
public TestRDFNodes( final TestingModelFactory modelFactory,
final String name )
{
super(modelFactory, name);
}
public void testInModel()
{
final Model m1 = ModelHelper.modelWithStatements(this, "");
final Model m2 = ModelHelper.modelWithStatements(this, "");
final Resource r1 = ModelHelper.resource(m1, "r1");
final Resource r2 = ModelHelper.resource(m1, "_r2");
/* */
Assert.assertEquals(r1.getModel(), m1);
Assert.assertEquals(r2.getModel(), m1);
Assert.assertFalse(r1.isAnon());
Assert.assertTrue(r2.isAnon());
/* */
Assert.assertEquals(r1.inModel(m2).getModel(), m2);
Assert.assertEquals(r2.inModel(m2).getModel(), m2);
/* */
Assert.assertEquals(r1, r1.inModel(m2));
Assert.assertEquals(r2, r2.inModel(m2));
}
public void testIsAnon()
{
final Model m = ModelHelper.modelWithStatements(this, "");
Assert.assertEquals(false, m.createResource("eh:/foo").isAnon());
Assert.assertEquals(true, m.createResource().isAnon());
Assert.assertEquals(false, m.createTypedLiteral(17).isAnon());
Assert.assertEquals(false, m.createTypedLiteral("hello").isAnon());
}
public void testIsLiteral()
{
final Model m = ModelHelper.modelWithStatements(this, "");
Assert.assertEquals(false, m.createResource("eh:/foo").isLiteral());
Assert.assertEquals(false, m.createResource().isLiteral());
Assert.assertEquals(true, m.createTypedLiteral(17).isLiteral());
Assert.assertEquals(true, m.createTypedLiteral("hello").isLiteral());
}
public void testIsResource()
{
final Model m = ModelHelper.modelWithStatements(this, "");
Assert.assertEquals(true, m.createResource("eh:/foo").isResource());
Assert.assertEquals(true, m.createResource().isResource());
Assert.assertEquals(false, m.createTypedLiteral(17).isResource());
Assert.assertEquals(false, m.createTypedLiteral("hello").isResource());
}
public void testIsURIResource()
{
final Model m = ModelHelper.modelWithStatements(this, "");
Assert.assertEquals(true, m.createResource("eh:/foo").isURIResource());
Assert.assertEquals(false, m.createResource().isURIResource());
Assert.assertEquals(false, m.createTypedLiteral(17).isURIResource());
Assert.assertEquals(false, m.createTypedLiteral("hello")
.isURIResource());
}
public void testLiteralAsResourceThrows()
{
final Model m = ModelHelper.modelWithStatements(this, "");
final Resource r = m.createResource("eh:/spoo");
try
{
r.asLiteral();
Assert.fail("should not be able to do Resource.asLiteral()");
}
catch (final LiteralRequiredException e)
{
}
}
public void testRDFNodeAsLiteral()
{
final Model m = ModelHelper.modelWithStatements(this, "");
final Literal l = m.createLiteral("hello, world");
Assert.assertSame(l, ((RDFNode) l).asLiteral());
}
public void testRDFNodeAsResource()
{
final Model m = ModelHelper.modelWithStatements(this, "");
final Resource r = m.createResource("eh:/spoo");
Assert.assertSame(r, ((RDFNode) r).asResource());
}
public void testRDFVisitor()
{
final List<String> history = new ArrayList<>();
final Model m = ModelFactory.createDefaultModel();
final RDFNode S = m.createResource();
final RDFNode P = m.createProperty("eh:PP");
final RDFNode O = m.createLiteral("LL");
/* */
final RDFVisitor rv = new RDFVisitor() {
@Override
public Object visitBlank( final Resource R, final AnonId id )
{
history.add("blank");
Assert.assertTrue("must visit correct node", R == S);
Assert.assertEquals("must have correct field", R.getId(), id);
return "blank result";
}
@Override
public Object visitLiteral( final Literal L )
{
history.add("literal");
Assert.assertTrue("must visit correct node", L == O);
return "literal result";
}
@Override
public Object visitURI( final Resource R, final String uri )
{
history.add("uri");
Assert.assertTrue("must visit correct node", R == P);
Assert.assertEquals("must have correct field", R.getURI(), uri);
return "uri result";
}
@Override
public Object visitStmt(Resource r, Statement statement) {
history.add("statementTerm");
return "statement term result";
}
};
/* */
Assert.assertEquals("blank result", S.visitWith(rv));
Assert.assertEquals("uri result", P.visitWith(rv));
Assert.assertEquals("literal result", O.visitWith(rv));
Assert.assertEquals(JenaTestBase.listOfStrings("blank uri literal"),
history);
}
public void testRemoveAllBoring()
{
final Model m1 = ModelHelper.modelWithStatements(this, "x P a; y Q b");
final Model m2 = ModelHelper.modelWithStatements(this, "x P a; y Q b");
ModelHelper.resource(m2, "x").removeAll(ModelHelper.property(m2, "Z"));
ModelHelper.assertIsoModels("m2 should be unchanged", m1, m2);
}
public void testRemoveAllRemoves()
{
final String ps = "x P a; x P b", rest = "x Q c; y P a; y Q b";
final Model m = ModelHelper.modelWithStatements(this, ps + "; " + rest);
final Resource r = ModelHelper.resource(m, "x");
final Resource r2 = r.removeAll(ModelHelper.property(m, "P"));
Assert.assertSame("removeAll should deliver its receiver", r, r2);
ModelHelper.assertIsoModels("x's P-values should go",
ModelHelper.modelWithStatements(this, rest), m);
}
public void testResourceAsLiteralThrows()
{
final Model m = ModelHelper.modelWithStatements(this, "");
final Literal l = m.createLiteral("hello, world");
try
{
l.asResource();
Assert.fail("should not be able to do Literal.asResource()");
}
catch (final ResourceRequiredException e)
{
}
}
}
| |
package net.qiujuer.genius.material;
import android.animation.AnimatorSet;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Property;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import net.qiujuer.genius.Attributes;
import net.qiujuer.genius.MaterialUI;
import net.qiujuer.genius.R;
import static android.graphics.Paint.ANTI_ALIAS_FLAG;
public class MaterialButton extends Button implements Attributes.AttributeChangeListener {
private static final Interpolator ANIMATION_INTERPOLATOR = new DecelerateInterpolator();
private Paint backgroundPaint;
private static ArgbEvaluator argbEvaluator = new ArgbEvaluator();
private float paintX, paintY, radius;
private int bottom;
private Attributes attributes;
public MaterialButton(Context context) {
super(context);
init(null, 0);
}
public MaterialButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public MaterialButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
@SuppressWarnings("deprecation")
private void init(AttributeSet attrs, int defStyle) {
// default values of specific attributes
// saving padding values for using them after setting background drawable
final int paddingTop = getPaddingTop();
final int paddingRight = getPaddingRight();
final int paddingLeft = getPaddingLeft();
final int paddingBottom = getPaddingBottom();
if (attributes == null)
attributes = new Attributes(this, getResources());
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MaterialButton, defStyle, 0);
// getting common attributes
int customTheme = a.getResourceId(R.styleable.MaterialButton_gm_theme, Attributes.DEFAULT_THEME);
attributes.setThemeSilent(customTheme, getResources());
attributes.setFontFamily(a.getString(R.styleable.MaterialButton_gm_fontFamily));
attributes.setFontWeight(a.getString(R.styleable.MaterialButton_gm_fontWeight));
attributes.setFontExtension(a.getString(R.styleable.MaterialButton_gm_fontExtension));
attributes.setTextAppearance(a.getInt(R.styleable.MaterialButton_gm_textAppearance, Attributes.DEFAULT_TEXT_APPEARANCE));
attributes.setRadius(a.getDimensionPixelSize(R.styleable.MaterialButton_gm_cornerRadius, Attributes.DEFAULT_RADIUS_PX));
attributes.setMaterial(a.getBoolean(R.styleable.MaterialButton_gm_isMaterial, true));
// getting view specific attributes
bottom = a.getDimensionPixelSize(R.styleable.MaterialButton_gm_blockButtonEffectHeight, bottom);
a.recycle();
}
// creating normal state drawable
ShapeDrawable normalFront = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
normalFront.getPaint().setColor(attributes.getColor(2));
ShapeDrawable normalBack = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
normalBack.getPaint().setColor(attributes.getColor(1));
normalBack.setPadding(0, 0, 0, bottom);
Drawable[] d = {normalBack, normalFront};
LayerDrawable normal = new LayerDrawable(d);
// creating disabled state drawable
ShapeDrawable disabledFront = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
disabledFront.getPaint().setColor(attributes.getColor(3));
ShapeDrawable disabledBack = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
disabledBack.getPaint().setColor(attributes.getColor(2));
Drawable[] d3 = {disabledBack, disabledFront};
LayerDrawable disabled = new LayerDrawable(d3);
// set StateListDrawable
StateListDrawable states = new StateListDrawable();
if (!attributes.isMaterial()) {
// creating pressed state drawable
ShapeDrawable pressedFront = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
pressedFront.getPaint().setColor(attributes.getColor(1));
ShapeDrawable pressedBack = new ShapeDrawable(new RoundRectShape(attributes.getOuterRadius(), null, null));
pressedBack.getPaint().setColor(attributes.getColor(0));
if (bottom != 0) pressedBack.setPadding(0, 0, 0, bottom / 2);
Drawable[] d2 = {pressedBack, pressedFront};
LayerDrawable pressed = new LayerDrawable(d2);
states.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
states.addState(new int[]{android.R.attr.state_focused, android.R.attr.state_enabled}, pressed);
}
states.addState(new int[]{android.R.attr.state_enabled}, normal);
states.addState(new int[]{-android.R.attr.state_enabled}, disabled);
// set Background
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
setBackgroundDrawable(states);
else
setBackground(states);
setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
if (attributes.getTextAppearance() == 1) setTextColor(attributes.getColor(0));
else if (attributes.getTextAppearance() == 2) setTextColor(attributes.getColor(3));
else setTextColor(Color.WHITE);
backgroundPaint = new Paint(ANTI_ALIAS_FLAG);
backgroundPaint.setStyle(Paint.Style.FILL);
backgroundPaint.setColor(attributes.getColor(1));
// check for IDE preview render
if (!this.isInEditMode()) {
Typeface typeface = MaterialUI.getFont(getContext(), attributes);
if (typeface != null) setTypeface(typeface);
}
}
@Override
public void onThemeChange() {
init(null, 0);
}
@SuppressWarnings("NullableProblems")
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.drawCircle(paintX, paintY, radius, backgroundPaint);
canvas.restore();
super.onDraw(canvas);
}
@SuppressWarnings("NullableProblems")
@Override
public boolean onTouchEvent(MotionEvent event) {
if (attributes.isMaterial() && event.getAction() == MotionEvent.ACTION_DOWN) {
paintX = event.getX();
paintY = event.getY();
startAnimator();
}
return super.onTouchEvent(event);
}
/**
* start Animator
*/
private void startAnimator() {
int start, end;
if (getHeight() < getWidth()) {
start = getHeight();
end = getWidth();
} else {
start = getWidth();
end = getHeight();
}
float startRadius = (start / 2 > paintY ? start - paintY : paintY) * 1.15f;
float endRadius = (end / 2 > paintX ? end - paintX : paintX) * 0.85f;
AnimatorSet set = new AnimatorSet();
set.playTogether(
ObjectAnimator.ofFloat(this, mRadiusProperty, startRadius, endRadius),
ObjectAnimator.ofObject(this, mBackgroundColorProperty, argbEvaluator, attributes.getColor(1), attributes.getColor(2))
);
// set Time
set.setDuration((long) (1200 / end * endRadius));
set.setInterpolator(ANIMATION_INTERPOLATOR);
set.start();
}
private Property<MaterialButton, Float> mRadiusProperty = new Property<MaterialButton, Float>(Float.class, "radius") {
@Override
public Float get(MaterialButton object) {
return object.radius;
}
@Override
public void set(MaterialButton object, Float value) {
object.radius = value;
invalidate();
}
};
private Property<MaterialButton, Integer> mBackgroundColorProperty = new Property<MaterialButton, Integer>(Integer.class, "bg_color") {
@Override
public Integer get(MaterialButton object) {
return object.backgroundPaint.getColor();
}
@Override
public void set(MaterialButton object, Integer value) {
object.backgroundPaint.setColor(value);
}
};
}
| |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.appengine.tools.mapreduce.inputs;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.io.CountingInputStream;
import com.google.common.primitives.Bytes;
import junit.framework.TestCase;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Unit test for {@code InputStreamIterator}.
*
*/
public class InputStreamIteratorTest extends TestCase {
// ------------------------------ FIELDS ------------------------------
InputStream input;
private final List<String> content =
ImmutableList.of("I", "am", "RecordReader", "Hello", "", "world", "!");
private final List<Long> byteContentOffsets = Lists.newArrayListWithCapacity(content.size());
// ------------------------ OVERRIDING METHODS ------------------------
@Override
protected void setUp() throws Exception {
super.setUp();
byte[] terminator = new byte[] { -1 };
byte[] byteContent = new byte[0];
for (String str : content) {
byteContentOffsets.add((long) byteContent.length);
byteContent = Bytes.concat(byteContent, str.getBytes(), terminator);
}
input = new BufferedInputStream(new NonResetableByteArrayInputStream(byteContent));
}
// -------------------------- TEST METHODS --------------------------
/** Tests leading split the size of the record. Should return this and the next record. */
public void testLeadingGreaterThanRecord() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start, byteContentOffsets.get(startIndex + 1),
false, startIndex, startIndex + 2);
}
/** Tests leading split smaller than a record. Should return one record. */
public void testLeadingSmallerThanRecord() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start, start + 2, false, startIndex, startIndex + 1);
}
/** Tests iterating over all items. */
public void testAllItems() throws Exception {
test(0, Long.MAX_VALUE, false, 0, content.size());
}
/** Tests leading split of length 0 with an empty record. Should return this record. */
public void testLeadingWithEmptyRecord() throws Exception {
int startIndex = 4;
long start = byteContentOffsets.get(startIndex);
test(start, start, false, startIndex, startIndex + 1);
}
/** Tests non-leading split the size of the record. Should return next record. */
public void testNonLeadingGreaterThanRecord() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start, byteContentOffsets.get(startIndex + 1),
true, startIndex + 1, startIndex + 2);
}
/** Tests non-leading split smaller than a record. Should return no records. */
public void testNonLeadingSmallerThanRecord() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start, start + 2, true, startIndex, startIndex);
}
/**
* Tests non-leading split starting at the previous record. Should return this and the next
* records.
*/
public void testNonLeadingStartingAtRecord() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start - 2, byteContentOffsets.get(startIndex + 1),
true, startIndex, startIndex + 2);
}
/**
* Tests non-leading split starting at the terminator of the previous record. Should return
* this and the next records.
*/
public void testNonLeadingStartingAtRecordTerminator() throws Exception {
int startIndex = 3;
long start = byteContentOffsets.get(startIndex);
test(start - 1, byteContentOffsets.get(startIndex + 1),
true, startIndex, startIndex + 2);
}
/**
* Makes sure that the basic method of offset record pair behave correctly,
*/
public void testOffsetRecordPair() throws Exception {
byte[] testArray1 = new byte[]{0x20, 0x40};
// Logically equal to array 1, but not referentially equal
byte[] testArray1copy = new byte[]{0x20, 0x40};
byte[] testArray2 = new byte[]{0x30};
byte[] testArray3 = new byte[0];
long offset1 = 10;
long offset2 = 4;
InputStreamIterator.OffsetRecordPair pair11 = new InputStreamIterator.OffsetRecordPair(
offset1, testArray1);
InputStreamIterator.OffsetRecordPair pair21 = new InputStreamIterator.OffsetRecordPair(
offset2, testArray1);
InputStreamIterator.OffsetRecordPair pair11copy = new InputStreamIterator.OffsetRecordPair(
offset1, testArray1copy);
InputStreamIterator.OffsetRecordPair pair12 = new InputStreamIterator.OffsetRecordPair(
offset1, testArray2);
InputStreamIterator.OffsetRecordPair pair13 = new InputStreamIterator.OffsetRecordPair(
offset1, testArray3);
assertEquals(pair11, pair11copy);
assertFalse(pair11.equals(pair21));
assertFalse(pair11.equals(pair12));
assertFalse(pair11.equals(pair13));
assertFalse(pair11.equals("foo"));
assertFalse(pair11.equals(null));
assertEquals(pair11.hashCode(), pair11copy.hashCode());
}
public void testExceptionHandling() throws Exception {
// Create an input stream than has 2 records in the first 9 bytes and exception while the 3rd
// record is read
byte[] content = new byte[] {1, 2, 3, 4, 0, 6, 7, 8, 0, 10, 11, 12};
InputStreamIterator iterator =
new InputStreamIterator(new CountingInputStream(new ExceptionThrowingInputStream(
new BufferedInputStream(new NonResetableByteArrayInputStream(content)), 11)),
content.length, false, (byte) 0);
assertTrue(iterator.hasNext());
iterator.next();
assertTrue(iterator.hasNext());
iterator.next();
try {
assertTrue(iterator.hasNext());
fail("Exception was not passed through");
} catch (RuntimeException expected) {
}
}
// -------------------------- INSTANCE METHODS --------------------------
private List<InputStreamIterator.OffsetRecordPair> readPairs(
long start, long end, boolean skipFirstTerminator)
throws IOException {
input.skip(start);
InputStreamIterator iterator = new InputStreamIterator(new CountingInputStream(input),
end - start, skipFirstTerminator, (byte) -1);
return ImmutableList.copyOf(iterator);
}
private void test(long start, long end, boolean skipFirstTerminator, int expectedIndexStart,
int expectedIndexEnd) throws IOException {
List<InputStreamIterator.OffsetRecordPair> pairs = readPairs(start, end, skipFirstTerminator);
assertEquals("pairs between " + start + " and " + end, expectedIndexEnd - expectedIndexStart,
pairs.size());
for (int i = 0; i < pairs.size(); i++) {
assertEquals(content.get(i + expectedIndexStart), new String(pairs.get(i).getRecord()));
assertEquals(byteContentOffsets.get(i + expectedIndexStart).longValue(),
pairs.get(i).getOffset() + start);
}
}
// -------------------------- INNER CLASSES --------------------------
/**
* Wrapper class for {@code ByteArrayInputStream} to double check that an InputStreamIterator
* applied to a BufferedInputStream doesn't call mark() and reset() on the underlying InputStream.
* Should be obvious, but doesn't hurt to test.
*/
public class NonResetableByteArrayInputStream extends ByteArrayInputStream {
public NonResetableByteArrayInputStream(byte[] array) {
super(array);
}
@Override
public void mark(int readAheadLimit) {
fail("Tried to call mark() on the underlying InputStream");
}
@Override
public synchronized void reset() {
fail("Tried to call reset() on the underlying InputStream");
}
}
/**
* Wrapper class for InputStream that throws an IOException after the specified number of reads
*/
private static class ExceptionThrowingInputStream extends InputStream {
private InputStream inputStream;
private int readsBetweenExceptions;
private int reads;
public ExceptionThrowingInputStream(InputStream inputStream, int readBetweenExceptions) {
this.inputStream = inputStream;
this.readsBetweenExceptions = readBetweenExceptions;
this.reads = 0;
}
@Override
public int read() throws IOException {
reads++;
if (reads % readsBetweenExceptions == 0) {
throw new IOException();
} else {
return inputStream.read();
}
}
}
}
| |
// $Id: Validation.java 17620 2009-10-04 19:19:28Z hardy.ferentschik $
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.validation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.validation.bootstrap.GenericBootstrap;
import javax.validation.bootstrap.ProviderSpecificBootstrap;
import javax.validation.spi.BootstrapState;
import javax.validation.spi.ValidationProvider;
/**
* This class is the entry point for Bean Validation. There are three ways
* to bootstrap it:
* <ul>
* <li>
* The easiest approach is to build the default <code>ValidatorFactory</code>.
* <pre>{@code ValidatorFactory factory = Validation.buildDefaultValidatorFactory();}</pre>
* In this case, the default validation provider resolver
* will be used to locate available providers.
* The chosen provider is defined as followed:
* <ul>
* <li>if the XML configuration defines a provider, this provider is used</li>
* <li>if the XML configuration does not define a provider or if no XML configuration
* is present the first provider returned by the
* <code>ValidationProviderResolver</code> instance is used.</li>
* </ul>
* </li>
* <li>
* The second bootstrap approach allows to choose a custom
* <code>ValidationProviderResolver</code>. The chosen
* <code>ValidationProvider</code> is then determined in the same way
* as in the default bootstrapping case (see above).
* <pre>{@code
* Configuration<?> configuration = Validation
* .byDefaultProvider()
* .providerResolver( new MyResolverStrategy() )
* .configure();
* ValidatorFactory factory = configuration.buildValidatorFactory();}
* </pre>
* </li>
* <li>
* The third approach allows you to specify explicitly and in
* a type safe fashion the expected provider.
* <p/>
* Optionally you can choose a custom <code>ValidationProviderResolver</code>.
* <pre>{@code
* ACMEConfiguration configuration = Validation
* .byProvider(ACMEProvider.class)
* .providerResolver( new MyResolverStrategy() ) // optionally set the provider resolver
* .configure();
* ValidatorFactory factory = configuration.buildValidatorFactory();}
* </pre>
* </li>
* </ul>
* Note:<br/>
* <ul>
* <li>
* The <code>ValidatorFactory</code> object built by the bootstrap process should be cached
* and shared amongst <code>Validator</code> consumers.
* </li>
* <li>
* This class is thread-safe.
* </li>
* </ul>
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public class Validation {
/**
* Build and return a <code>ValidatorFactory</code> instance based on the
* default Bean Validation provider and following the XML configuration.
* <p/>
* The provider list is resolved using the default validation provider resolver
* logic.
* <p/> The code is semantically equivalent to
* <code>Validation.byDefaultProvider().configure().buildValidatorFactory()</code>
*
* @return <code>ValidatorFactory</code> instance.
*
* @throws ValidationException if the ValidatorFactory cannot be built
*/
public static ValidatorFactory buildDefaultValidatorFactory() {
return byDefaultProvider().configure().buildValidatorFactory();
}
/**
* Build a <code>Configuration</code>. The provider list is resolved
* using the strategy provided to the bootstrap state.
* <pre>
* Configuration<?> configuration = Validation
* .byDefaultProvider()
* .providerResolver( new MyResolverStrategy() )
* .configure();
* ValidatorFactory factory = configuration.buildValidatorFactory();
* </pre>
* The provider can be specified in the XML configuration. If the XML
* configuration does not exsist or if no provider is specified,
* the first available provider will be returned.
*
* @return instance building a generic <code>Configuration</code>
* compliant with the bootstrap state provided.
*/
public static GenericBootstrap byDefaultProvider() {
return new GenericBootstrapImpl();
}
/**
* Build a <code>Configuration</code> for a particular provider implementation.
* Optionally overrides the provider resolution strategy used to determine the provider.
* <p/>
* Used by applications targeting a specific provider programmatically.
* <p/>
* <pre>
* ACMEConfiguration configuration =
* Validation.byProvider(ACMEProvider.class)
* .providerResolver( new MyResolverStrategy() )
* .configure();
* </pre>,
* where <code>ACMEConfiguration</code> is the
* <code>Configuration</code> sub interface uniquely identifying the
* ACME Bean Validation provider. and <code>ACMEProvider</code> is the
* <code>ValidationProvider</code> implementation of the ACME provider.
*
* @param providerType the <code>ValidationProvider</code> implementation type
*
* @return instance building a provider specific <code>Configuration</code>
* sub interface implementation.
*/
public static <T extends Configuration<T>, U extends ValidationProvider<T>>
ProviderSpecificBootstrap<T> byProvider(Class<U> providerType) {
return new ProviderSpecificBootstrapImpl<T, U>( providerType );
}
//private class, not exposed
private static class ProviderSpecificBootstrapImpl<T extends Configuration<T>, U extends ValidationProvider<T>>
implements ProviderSpecificBootstrap<T> {
private final Class<U> validationProviderClass;
private ValidationProviderResolver resolver;
public ProviderSpecificBootstrapImpl(Class<U> validationProviderClass) {
this.validationProviderClass = validationProviderClass;
}
/**
* Optionally define the provider resolver implementation used.
* If not defined, use the default ValidationProviderResolver
*
* @param resolver ValidationProviderResolver implementation used
*
* @return self
*/
public ProviderSpecificBootstrap<T> providerResolver(ValidationProviderResolver resolver) {
this.resolver = resolver;
return this;
}
/**
* Determine the provider implementation suitable for byProvider(Class)
* and delegate the creation of this specific Configuration subclass to the provider.
*
* @return a Configuration sub interface implementation
*/
public T configure() {
if ( validationProviderClass == null ) {
throw new ValidationException(
"builder is mandatory. Use Validation.byDefaultProvider() to use the generic provider discovery mechanism"
);
}
//used mostly as a BootstrapState
GenericBootstrapImpl state = new GenericBootstrapImpl();
if ( resolver == null ) {
resolver = state.getDefaultValidationProviderResolver();
}
else {
//stay null if no resolver is defined
state.providerResolver( resolver );
}
List<ValidationProvider<?>> resolvers;
try {
resolvers = resolver.getValidationProviders();
}
catch ( RuntimeException re ) {
throw new ValidationException( "Unable to get available provider resolvers.", re );
}
for ( ValidationProvider provider : resolvers ) {
if ( validationProviderClass.isAssignableFrom( provider.getClass() ) ) {
ValidationProvider<T> specificProvider = validationProviderClass.cast( provider );
return specificProvider.createSpecializedConfiguration( state );
}
}
throw new ValidationException( "Unable to find provider: " + validationProviderClass );
}
}
//private class, not exposed
private static class GenericBootstrapImpl implements GenericBootstrap, BootstrapState {
private ValidationProviderResolver resolver;
private ValidationProviderResolver defaultResolver;
public GenericBootstrap providerResolver(ValidationProviderResolver resolver) {
this.resolver = resolver;
return this;
}
public ValidationProviderResolver getValidationProviderResolver() {
return resolver;
}
public ValidationProviderResolver getDefaultValidationProviderResolver() {
if ( defaultResolver == null ) {
defaultResolver = new DefaultValidationProviderResolver();
}
return defaultResolver;
}
public Configuration<?> configure() {
ValidationProviderResolver resolver = this.resolver == null ?
getDefaultValidationProviderResolver() :
this.resolver;
List<ValidationProvider<?>> resolvers;
try {
resolvers = resolver.getValidationProviders();
}
catch ( RuntimeException re ) {
throw new ValidationException( "Unable to get available provider resolvers.", re );
}
if ( resolvers.size() == 0 ) {
//FIXME looks like an assertion error almost
throw new ValidationException( "Unable to find a default provider" );
}
Configuration<?> config;
try {
config = resolver.getValidationProviders().get( 0 ).createGenericConfiguration( this );
}
catch ( RuntimeException re ) {
throw new ValidationException( "Unable to instantiate Configuration.", re );
}
return config;
}
}
/**
* Find <code>ValidationProvider</code> according to the default <code>ValidationProviderResolver</code> defined in the
* Bean Validation specification. This implementation uses the current classloader or the classloader which has loaded
* the current class if the current class loader is unavailable. The classloader is used to retrieve the Service Provider files.
* <p>
* This class implements the Service Provider pattern described <a href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service%20Provider">here</a>.
* Since we cannot rely on Java 6 we have to reimplement the <code>Service</code> functionality.
* </p>
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
private static class DefaultValidationProviderResolver implements ValidationProviderResolver {
//cache per classloader for an appropriate discovery
//keep them in a weak hashmap to avoid memory leaks and allow proper hot redeployment
//TODO use a WeakConcurrentHashMap
//FIXME The List<VP> does keep a strong reference to the key ClassLoader, use the same model as JPA CachingPersistenceProviderResolver
private static final Map<ClassLoader, List<ValidationProvider<?>>> providersPerClassloader =
new WeakHashMap<ClassLoader, List<ValidationProvider<?>>>();
private static final String SERVICES_FILE = "META-INF/services/" + ValidationProvider.class.getName();
public List<ValidationProvider<?>> getValidationProviders() {
ClassLoader classloader = GetClassLoader.fromContext();
if ( classloader == null ) {
classloader = GetClassLoader.fromClass( DefaultValidationProviderResolver.class );
}
List<ValidationProvider<?>> providers;
synchronized ( providersPerClassloader ) {
providers = providersPerClassloader.get( classloader );
}
if ( providers == null ) {
providers = new ArrayList<ValidationProvider<?>>();
try {
// If we are deployed into an OSGi environment, leverage it
Class<? extends ValidationProvider> providerClass = org.apache.servicemix.specs.locator.OsgiLocator.locate(ValidationProvider.class);
if (providerClass != null) {
providers.add(providerClass.newInstance());
}
} catch (Throwable e) {
// Do nothing here
}
String name = null;
try {
Enumeration<URL> providerDefinitions = classloader.getResources( SERVICES_FILE );
while ( providerDefinitions.hasMoreElements() ) {
URL url = providerDefinitions.nextElement();
InputStream stream = url.openStream();
try {
BufferedReader reader = new BufferedReader( new InputStreamReader( stream ), 100 );
name = reader.readLine();
while ( name != null ) {
name = name.trim();
if ( !name.startsWith( "#" ) ) {
final Class<?> providerClass = loadClass(
name,
DefaultValidationProviderResolver.class
);
providers.add(
( ValidationProvider ) providerClass.newInstance()
);
}
name = reader.readLine();
}
}
finally {
stream.close();
}
}
}
catch ( IOException e ) {
throw new ValidationException( "Unable to read " + SERVICES_FILE, e );
}
catch ( ClassNotFoundException e ) {
//TODO is it better to not fail the whole loading because of a black sheep?
throw new ValidationException( "Unable to load Bean Validation provider " + name, e );
}
catch ( IllegalAccessException e ) {
throw new ValidationException( "Unable to instanciate Bean Validation provider" + name, e );
}
catch ( InstantiationException e ) {
throw new ValidationException( "Unable to instanciate Bean Validation provider" + name, e );
}
synchronized ( providersPerClassloader ) {
providersPerClassloader.put( classloader, providers );
}
}
return providers;
}
private static Class<?> loadClass(String name, Class<?> caller) throws ClassNotFoundException {
try {
//try context classloader, if fails try caller classloader
ClassLoader loader = GetClassLoader.fromContext();
if ( loader != null ) {
return loader.loadClass( name );
}
}
catch ( ClassNotFoundException e ) {
//trying caller classloader
if ( caller == null ) {
throw e;
}
}
return Class.forName( name, true, GetClassLoader.fromClass( caller ) );
}
}
private static class GetClassLoader implements PrivilegedAction<ClassLoader> {
private final Class<?> clazz;
public static ClassLoader fromContext() {
final GetClassLoader action = new GetClassLoader( null );
if ( System.getSecurityManager() != null ) {
return AccessController.doPrivileged( action );
}
else {
return action.run();
}
}
public static ClassLoader fromClass(Class<?> clazz) {
if ( clazz == null ) {
throw new IllegalArgumentException( "Class is null" );
}
final GetClassLoader action = new GetClassLoader( clazz );
if ( System.getSecurityManager() != null ) {
return AccessController.doPrivileged( action );
}
else {
return action.run();
}
}
private GetClassLoader(Class<?> clazz) {
this.clazz = clazz;
}
public ClassLoader run() {
if ( clazz != null ) {
return clazz.getClassLoader();
}
else {
return Thread.currentThread().getContextClassLoader();
}
}
}
}
| |
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.collection.primitive;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.neo4j.function.LongPredicate;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PrimitiveLongCollectionsTest
{
@Test
public void arrayOfItemsAsIterator() throws Exception
{
// GIVEN
long[] items = new long[] { 2, 5, 234 };
// WHEN
PrimitiveLongIterator iterator = PrimitiveLongCollections.iterator( items );
// THEN
assertItems( iterator, items );
}
@Test
public void arrayOfReversedItemsAsIterator() throws Exception
{
// GIVEN
long[] items = new long[] { 2, 5, 234 };
// WHEN
PrimitiveLongIterator iterator = PrimitiveLongCollections.reversed( items );
// THEN
assertItems( iterator, reverse( items ) );
}
@Test
public void concatenateTwoIterators() throws Exception
{
// GIVEN
PrimitiveLongIterator firstItems = PrimitiveLongCollections.iterator( 10, 3, 203, 32 );
PrimitiveLongIterator otherItems = PrimitiveLongCollections.iterator( 1, 2, 5 );
// WHEN
PrimitiveLongIterator iterator = PrimitiveLongCollections.concat( asList( firstItems, otherItems ).iterator() );
// THEN
assertItems( iterator, 10, 3, 203, 32, 1, 2, 5 );
}
@Test
public void prependItem() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 10, 23 );
long prepended = 5;
// WHEN
PrimitiveLongIterator iterator = PrimitiveLongCollections.prepend( prepended, items );
// THEN
assertItems( iterator, prepended, 10, 23 );
}
@Test
public void appendItem() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2 );
long appended = 3;
// WHEN
PrimitiveLongIterator iterator = PrimitiveLongCollections.append( items, appended );
// THEN
assertItems( iterator, 1, 2, appended );
}
@Test
public void filter() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
PrimitiveLongIterator filtered = PrimitiveLongCollections.filter( items, new LongPredicate()
{
@Override
public boolean test( long item )
{
return item != 2;
}
} );
// THEN
assertItems( filtered, 1, 3 );
}
@Test
public void dedup() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 1, 2, 3, 2 );
// WHEN
PrimitiveLongIterator deduped = PrimitiveLongCollections.dedup( items );
// THEN
assertItems( deduped, 1, 2, 3 );
}
@Test
public void limit() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
PrimitiveLongIterator limited = PrimitiveLongCollections.limit( items, 2 );
// THEN
assertItems( limited, 1, 2 );
}
@Test
public void skip() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3, 4 );
// WHEN
PrimitiveLongIterator skipped = PrimitiveLongCollections.skip( items, 2 );
// THEN
assertItems( skipped, 3, 4 );
}
// TODO paging iterator
@Test
public void range() throws Exception
{
// WHEN
PrimitiveLongIterator range = PrimitiveLongCollections.range( 5, 15, 3 );
// THEN
assertItems( range, 5, 8, 11, 14 );
}
@Test
public void singleton() throws Exception
{
// GIVEN
long item = 15;
// WHEN
PrimitiveLongIterator singleton = PrimitiveLongCollections.singleton( item );
// THEN
assertItems( singleton, item );
}
@Test
public void reversed() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
PrimitiveLongIterator reversed = PrimitiveLongCollections.reversed( items );
// THEN
assertItems( reversed, 3, 2, 1 );
}
@Test
public void first() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2 );
// WHEN
try
{
PrimitiveLongCollections.first( PrimitiveLongCollections.emptyIterator() );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{ // Good
}
long first = PrimitiveLongCollections.first( items );
// THEN
assertEquals( 1, first );
}
@Test
public void firstWithDefault() throws Exception
{
// GIVEN
long defaultValue = 5;
// WHEN
long firstOnEmpty = PrimitiveLongCollections.first( PrimitiveLongCollections.emptyIterator(), defaultValue );
long first = PrimitiveLongCollections.first( PrimitiveLongCollections.iterator( 1, 2 ), defaultValue );
// THEN
assertEquals( defaultValue, firstOnEmpty );
assertEquals( 1, first );
}
@Test
public void last() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2 );
// WHEN
try
{
PrimitiveLongCollections.last( PrimitiveLongCollections.emptyIterator() );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{ // Good
}
long last = PrimitiveLongCollections.last( items );
// THEN
assertEquals( 2, last );
}
@Test
public void lastWithDefault() throws Exception
{
// GIVEN
long defaultValue = 5;
// WHEN
long lastOnEmpty = PrimitiveLongCollections.last( PrimitiveLongCollections.emptyIterator(), defaultValue );
long last = PrimitiveLongCollections.last( PrimitiveLongCollections.iterator( 1, 2 ), defaultValue );
// THEN
assertEquals( defaultValue, lastOnEmpty );
assertEquals( 2, last );
}
@Test
public void single() throws Exception
{
try
{
PrimitiveLongCollections.single( PrimitiveLongCollections.emptyIterator() );
}
catch ( NoSuchElementException e )
{
assertThat( e.getMessage(), containsString( "No" ) );
}
assertEquals( 3, PrimitiveLongCollections.single( PrimitiveLongCollections.iterator( 3 ) ) );
try
{
PrimitiveLongCollections.single( PrimitiveLongCollections.iterator( 1, 2 ) );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{
assertThat( e.getMessage(), containsString( "More than one" ) );
}
}
@Test
public void singleWithDefault() throws Exception
{
assertEquals( 5, PrimitiveLongCollections.single( PrimitiveLongCollections.emptyIterator(), 5 ) );
assertEquals( 3, PrimitiveLongCollections.single( PrimitiveLongCollections.iterator( 3 ) ) );
try
{
PrimitiveLongCollections.single( PrimitiveLongCollections.iterator( 1, 2 ) );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{ // Good
assertThat( e.getMessage(), containsString( "More than one" ) );
}
}
private static final class CountingPrimitiveLongIteratorResource implements PrimitiveLongIterator, AutoCloseable
{
private final PrimitiveLongIterator delegate;
private final AtomicInteger closeCounter;
private CountingPrimitiveLongIteratorResource( PrimitiveLongIterator delegate, AtomicInteger closeCounter )
{
this.delegate = delegate;
this.closeCounter = closeCounter;
}
@Override
public void close() throws Exception
{
closeCounter.incrementAndGet();
}
@Override
public boolean hasNext()
{
return delegate.hasNext();
}
@Override
public long next()
{
return delegate.next();
}
}
@Test
public void singleMustAutoCloseIterator()
{
AtomicInteger counter = new AtomicInteger();
CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource(
PrimitiveLongCollections.iterator( 13 ), counter );
assertEquals( PrimitiveLongCollections.single( itr ), 13 );
assertEquals( 1, counter.get() );
}
@Test
public void singleWithDefaultMustAutoCloseIterator()
{
AtomicInteger counter = new AtomicInteger();
CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource(
PrimitiveLongCollections.iterator( 13 ), counter );
assertEquals( PrimitiveLongCollections.single( itr, 2 ), 13 );
assertEquals( 1, counter.get() );
}
@Test
public void singleMustAutoCloseEmptyIterator()
{
AtomicInteger counter = new AtomicInteger();
CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource(
PrimitiveLongCollections.emptyIterator(), counter );
try
{
PrimitiveLongCollections.single( itr );
fail( "single() on empty iterator should have thrown" );
}
catch ( NoSuchElementException ignore )
{
}
assertEquals( 1, counter.get() );
}
@Test
public void singleWithDefaultMustAutoCloseEmptyIterator()
{
AtomicInteger counter = new AtomicInteger();
CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource(
PrimitiveLongCollections.emptyIterator(), counter );
assertEquals( PrimitiveLongCollections.single( itr, 2 ), 2 );
assertEquals( 1, counter.get() );
}
@Test
public void itemAt() throws Exception
{
// GIVEN
PrimitiveLongIterable items = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 10, 20, 30 );
}
};
// THEN
try
{
PrimitiveLongCollections.itemAt( items.iterator(), 3 );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{
assertThat( e.getMessage(), containsString( "No element" ) );
}
try
{
PrimitiveLongCollections.itemAt( items.iterator(), -4 );
fail( "Should throw exception" );
}
catch ( NoSuchElementException e )
{
assertThat( e.getMessage(), containsString( "not found" ) );
}
assertEquals( 10, PrimitiveLongCollections.itemAt( items.iterator(), 0 ) );
assertEquals( 20, PrimitiveLongCollections.itemAt( items.iterator(), 1 ) );
assertEquals( 30, PrimitiveLongCollections.itemAt( items.iterator(), 2 ) );
assertEquals( 30, PrimitiveLongCollections.itemAt( items.iterator(), -1 ) );
assertEquals( 20, PrimitiveLongCollections.itemAt( items.iterator(), -2 ) );
assertEquals( 10, PrimitiveLongCollections.itemAt( items.iterator(), -3 ) );
}
@Test
public void itemAtWithDefault() throws Exception
{
// GIVEN
PrimitiveLongIterable items = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 10, 20, 30 );
}
};
long defaultValue = 55;
// THEN
assertEquals( defaultValue, PrimitiveLongCollections.itemAt( items.iterator(), 3, defaultValue ) );
assertEquals( defaultValue, PrimitiveLongCollections.itemAt( items.iterator(), -4, defaultValue ) );
assertEquals( 10, PrimitiveLongCollections.itemAt( items.iterator(), 0 ) );
assertEquals( 20, PrimitiveLongCollections.itemAt( items.iterator(), 1 ) );
assertEquals( 30, PrimitiveLongCollections.itemAt( items.iterator(), 2 ) );
assertEquals( 30, PrimitiveLongCollections.itemAt( items.iterator(), -1 ) );
assertEquals( 20, PrimitiveLongCollections.itemAt( items.iterator(), -2 ) );
assertEquals( 10, PrimitiveLongCollections.itemAt( items.iterator(), -3 ) );
}
@Test
public void indexOf() throws Exception
{
// GIVEN
PrimitiveLongIterable items = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 10, 20, 30 );
}
};
// THEN
assertEquals( -1, PrimitiveLongCollections.indexOf( items.iterator(), 55 ) );
assertEquals( 0, PrimitiveLongCollections.indexOf( items.iterator(), 10 ) );
assertEquals( 1, PrimitiveLongCollections.indexOf( items.iterator(), 20 ) );
assertEquals( 2, PrimitiveLongCollections.indexOf( items.iterator(), 30 ) );
}
@Test
public void iteratorsEqual() throws Exception
{
// GIVEN
PrimitiveLongIterable items1 = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 1, 2, 3 );
}
};
PrimitiveLongIterable items2 = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 1, 20, 3 );
}
};
PrimitiveLongIterable items3 = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 1, 2, 3, 4 );
}
};
PrimitiveLongIterable items4 = new PrimitiveLongIterable()
{
@Override
public PrimitiveLongIterator iterator()
{
return PrimitiveLongCollections.iterator( 1, 2, 3 );
}
};
// THEN
assertFalse( PrimitiveLongCollections.equals( items1.iterator(), items2.iterator() ) );
assertFalse( PrimitiveLongCollections.equals( items1.iterator(), items3.iterator() ) );
assertTrue( PrimitiveLongCollections.equals( items1.iterator(), items4.iterator() ) );
}
@Test
public void iteratorAsSet() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
PrimitiveLongSet set = PrimitiveLongCollections.asSet( items );
// THEN
assertTrue( set.contains( 1 ) );
assertTrue( set.contains( 2 ) );
assertTrue( set.contains( 3 ) );
assertFalse( set.contains( 4 ) );
try
{
PrimitiveLongCollections.asSet( PrimitiveLongCollections.iterator( 1, 2, 1 ) );
fail( "Should fail on duplicates" );
}
catch ( IllegalStateException e )
{ // good
}
}
@Test
public void iteratorAsSetAllowDuplicates() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 1 );
// WHEN
PrimitiveLongSet set = PrimitiveLongCollections.asSetAllowDuplicates( items );
// THEN
assertTrue( set.contains( 1 ) );
assertTrue( set.contains( 2 ) );
assertFalse( set.contains( 3 ) );
}
@Test
public void count() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
int count = PrimitiveLongCollections.count( items );
// THEN
assertEquals( 3, count );
}
@Test
public void asArray() throws Exception
{
// GIVEN
PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 );
// WHEN
long[] array = PrimitiveLongCollections.asArray( items );
// THEN
assertTrue( Arrays.equals( new long[] { 1, 2, 3 }, array ) );
}
private void assertNoMoreItems( PrimitiveLongIterator iterator )
{
assertFalse( iterator + " should have no more items", iterator.hasNext() );
try
{
iterator.next();
fail( "Invoking next() on " + iterator +
" which has no items left should have thrown NoSuchElementException" );
}
catch ( NoSuchElementException e )
{ // Good
}
}
private void assertNextEquals( long expected, PrimitiveLongIterator iterator )
{
assertTrue( iterator + " should have had more items", iterator.hasNext() );
assertEquals( expected, iterator.next() );
}
private void assertItems( PrimitiveLongIterator iterator, long... expectedItems )
{
for ( long expectedItem : expectedItems )
{
assertNextEquals( expectedItem, iterator );
}
assertNoMoreItems( iterator );
}
private long[] reverse( long[] items )
{
long[] result = new long[items.length];
for ( int i = 0; i < items.length; i++ )
{
result[i] = items[items.length-i-1];
}
return result;
}
}
| |
package com.aptima.netstorm.algorithms.aptima.bp.hive;
import com.aptima.netstorm.algorithms.aptima.bp.mismatch.AttributeConstraintVocab;
import com.aptima.netstorm.algorithms.aptima.bp.network.AttributedModelNode;
import com.aptima.netstorm.algorithms.aptima.bp.network.AttributedModelRelation;
import com.aptima.netstorm.algorithms.aptima.bp.network.ModelAttributeConstraints;
public abstract class BitcoinMR extends MRBase {
//public static boolean constrainFlow = false;
public BitcoinMR(String[] args) {
// TODO: implement this or replace with something that reads from a file.
// mixing();
//thiefVictimFinder();
lenderToDonor();
}
public static void lenderToDonor() {
modelNodes = new AttributedModelNode[2];
modelRelations = new AttributedModelRelation[1];
AttributedModelNode lender = new AttributedModelNode();
AttributedModelNode donor = new AttributedModelNode();
AttributedModelRelation lenderDonor = new AttributedModelRelation();
lenderDonor.setFromNode(lender.getId());
lenderDonor.setToNode(donor.getId());
ModelAttributeConstraints donorIndegree = new ModelAttributeConstraints();
donorIndegree.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "25000");
donor.setConstraintSet(donorIndegree);
ModelAttributeConstraints lenderOutAmount = new ModelAttributeConstraints();
lenderOutAmount.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "100");
lender.setConstraintSet(lenderOutAmount);
modelNodes[0] = lender;
modelNodes[1] = donor;
modelRelations[0] = lenderDonor;
}
public static void thiefVictimFinder() {
modelNodes = new AttributedModelNode[3];
modelRelations = new AttributedModelRelation[2];
// create nodes before all relations
// out degree
AttributedModelNode thief = new AttributedModelNode();
AttributedModelNode victim = new AttributedModelNode();
AttributedModelNode finder = new AttributedModelNode();
ModelAttributeConstraints victimThiefConstraints = new ModelAttributeConstraints();
victimThiefConstraints.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "20000");
ModelAttributeConstraints thiefFinderConstraints = new ModelAttributeConstraints();
thiefFinderConstraints.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.LESS_THAN_OR_EQUAL_TO + "1.0");
AttributedModelRelation victimThief = new AttributedModelRelation();
victimThief.setFromNode(victim.getId());
victimThief.setToNode(thief.getId());
victimThief.setConstraintSet(victimThiefConstraints);
AttributedModelRelation thiefFinder = new AttributedModelRelation();
thiefFinder.setFromNode(thief.getId());
thiefFinder.setToNode(finder.getId());
thiefFinder.setConstraintSet(thiefFinderConstraints);
// from flush
ModelAttributeConstraints victimInDegree = new ModelAttributeConstraints();
victimInDegree.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "50");
victim.setConstraintSet(victimInDegree);
modelNodes[0] = victim;
modelNodes[1] = thief;
modelNodes[2] = finder;
modelRelations[0] = victimThief;
modelRelations[1] = thiefFinder;
}
public static void mixing() {
constrainFlow = true;
// 1 3 1 pattern
modelNodes = new AttributedModelNode[5];
modelRelations = new AttributedModelRelation[6];
// create nodes before all relations
// out degree
AttributedModelNode n1 = new AttributedModelNode();
// middle nodes
AttributedModelNode n2 = new AttributedModelNode();
AttributedModelNode n3 = new AttributedModelNode();
AttributedModelNode n4 = new AttributedModelNode();
// in degree
AttributedModelNode n5 = new AttributedModelNode();
ModelAttributeConstraints limitR1 = new ModelAttributeConstraints();
limitR1.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
ModelAttributeConstraints limitR2 = new ModelAttributeConstraints();
limitR2.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
ModelAttributeConstraints limitR3 = new ModelAttributeConstraints();
limitR3.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
ModelAttributeConstraints limitR4 = new ModelAttributeConstraints();
limitR4.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
ModelAttributeConstraints limitR5 = new ModelAttributeConstraints();
limitR5.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
ModelAttributeConstraints limitR6 = new ModelAttributeConstraints();
limitR6.addAttribute(BitcoinMapper.COL_BITCOIN_AMT, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "0.5");
// outflow
AttributedModelRelation r1 = new AttributedModelRelation();
r1.setFromNode(n1.getId());
r1.setToNode(n2.getId());
r1.setConstraintSet(limitR1);
AttributedModelRelation r2 = new AttributedModelRelation();
r2.setFromNode(n1.getId());
r2.setToNode(n3.getId());
r2.setConstraintSet(limitR2);
AttributedModelRelation r3 = new AttributedModelRelation();
r3.setFromNode(n1.getId());
r3.setToNode(n4.getId());
r3.setConstraintSet(limitR3);
// inflow
AttributedModelRelation r4 = new AttributedModelRelation();
r4.setFromNode(n2.getId());
r4.setToNode(n5.getId());
r4.setConstraintSet(limitR4);
AttributedModelRelation r5 = new AttributedModelRelation();
r5.setFromNode(n3.getId());
r5.setToNode(n5.getId());
r5.setConstraintSet(limitR5);
AttributedModelRelation r6 = new AttributedModelRelation();
r6.setFromNode(n4.getId());
r6.setToNode(n5.getId());
r6.setConstraintSet(limitR6);
// out degree Rel
n1.addSuccessorRelation(r1.getId());
n1.addSuccessorRelation(r2.getId());
n1.addSuccessorRelation(r3.getId());
// middle nodes Rel
n2.addPredecessorRelation(r1.getId());
n2.addSuccessorRelation(r4.getId());
n3.addPredecessorRelation(r2.getId());
n3.addSuccessorRelation(r5.getId());
n4.addPredecessorRelation(r3.getId());
n4.addSuccessorRelation(r6.getId());
// in degree Rel
n5.addPredecessorRelation(r4.getId());
n5.addPredecessorRelation(r5.getId());
n5.addPredecessorRelation(r6.getId());
// constraints
ModelAttributeConstraints outDegreeAndFlow = new ModelAttributeConstraints();
outDegreeAndFlow.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_DEGREE, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO
+ "3");
// outDegreeAndFlow.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_AMT, AttributeConstraintVocab.EQUAL_TO + "50");
// inDegreeAndFlow.addAttribute(OUTFLOW, AttributeConstraintVocab.EQUAL_TO + "5000");
ModelAttributeConstraints inDegreeAndFlow = new ModelAttributeConstraints();
inDegreeAndFlow
.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.GREATER_THAN_OR_EQUAL_TO + "3");
// inDegreeAndFlow.addAttribute(BitcoinMapper.COL_BITCOIN_IN_AMT, AttributeConstraintVocab.EQUAL_TO + "50");
// outDegreeAndFlow.addAttribute(INFLOW, AttributeConstraintVocab.EQUAL_TO + "5000");
n1.setConstraintSet(outDegreeAndFlow);
n5.setConstraintSet(inDegreeAndFlow);
/*
* ModelAttributeConstraints n2Flow = new ModelAttributeConstraints();
* n2Flow.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
* n2Flow.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
*
* ModelAttributeConstraints n3Flow = new ModelAttributeConstraints();
* n3Flow.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
* n3Flow.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
*
* ModelAttributeConstraints n4Flow = new ModelAttributeConstraints();
* n4Flow.addAttribute(BitcoinMapper.COL_BITCOIN_IN_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
* n4Flow.addAttribute(BitcoinMapper.COL_BITCOIN_OUT_DEGREE, AttributeConstraintVocab.EQUAL_TO + "1");
*/
// n2.setConstraintSet(n2Flow);
// n3.setConstraintSet(n3Flow);
// n4.setConstraintSet(n4Flow);
modelNodes[0] = n1;
modelNodes[1] = n2;
modelNodes[2] = n3;
modelNodes[3] = n4;
;
modelNodes[4] = n5;
modelRelations[0] = r1;
modelRelations[1] = r2;
modelRelations[2] = r3;
modelRelations[3] = r4;
modelRelations[4] = r5;
modelRelations[5] = r6;
}
}
| |
/*
* Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document;
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.services.dynamodbv2.document.internal.PageBasedCollection;
import com.amazonaws.services.dynamodbv2.document.internal.PageIterable;
import com.amazonaws.services.dynamodbv2.model.Capacity;
import com.amazonaws.services.dynamodbv2.model.ConsumedCapacity;
/**
* A collection of <code>Item</code>'s.
*
* An <code>ItemCollection</code> object maintains a cursor pointing to its
* current pages of data. Initially the cursor is positioned before the first page.
* The next method moves the cursor to the next row, and because it returns
* false when there are no more rows in the <code>ItemCollection</code> object,
* it can be used in a while loop to iterate through the collection.
*
* Network calls can be triggered when the collection is iterated across page
* boundaries.
*
* @param <R> low level result type
*/
public abstract class ItemCollection<R> extends PageBasedCollection<Item, R> {
private int totalCount;
private int totalScannedCount;
private ConsumedCapacity totalConsumedCapacity;
protected final void accumulateStats(ConsumedCapacity consumedCapacity,
Integer count, Integer scannedCount) {
if (consumedCapacity != null) {
if (totalConsumedCapacity == null) {
// Create a new consumed capacity by cloning the one passed in
this.totalConsumedCapacity = new ConsumedCapacity();
totalConsumedCapacity.setCapacityUnits(consumedCapacity.getCapacityUnits());
totalConsumedCapacity.setGlobalSecondaryIndexes(
clone(consumedCapacity.getGlobalSecondaryIndexes()));
totalConsumedCapacity.setLocalSecondaryIndexes(
clone(consumedCapacity.getLocalSecondaryIndexes()));
totalConsumedCapacity.setTable(clone(consumedCapacity.getTable()));
totalConsumedCapacity.setTableName(consumedCapacity.getTableName());
} else {
// Accumulate the capacity units
final Double capunit = totalConsumedCapacity.getCapacityUnits();
final Double delta = consumedCapacity.getCapacityUnits();
if (capunit == null) {
totalConsumedCapacity.setCapacityUnits(delta);
} else {
totalConsumedCapacity.setCapacityUnits(capunit.doubleValue()
+ (delta == null ? 0 : delta.doubleValue()));
}
// Accumulate the GSI capacities
final Map<String, Capacity> gsi = totalConsumedCapacity.getGlobalSecondaryIndexes();
if (gsi == null) {
totalConsumedCapacity.setGlobalSecondaryIndexes(
clone(consumedCapacity.getGlobalSecondaryIndexes()));
} else {
totalConsumedCapacity.setGlobalSecondaryIndexes(add(
consumedCapacity.getGlobalSecondaryIndexes(),
totalConsumedCapacity.getGlobalSecondaryIndexes()));
}
// Accumulate the LSI capacities
final Map<String, Capacity> lsi = totalConsumedCapacity.getLocalSecondaryIndexes();
if (lsi == null) {
totalConsumedCapacity.setLocalSecondaryIndexes(
clone(consumedCapacity.getLocalSecondaryIndexes()));
} else {
totalConsumedCapacity.setLocalSecondaryIndexes(add(
consumedCapacity.getLocalSecondaryIndexes(),
totalConsumedCapacity.getLocalSecondaryIndexes()));
}
}
}
if (count != null) {
this.totalCount += count.intValue();
}
if (scannedCount != null) {
this.totalScannedCount += scannedCount.intValue();
}
}
private Map<String, Capacity> add(Map<String, Capacity> from, Map<String, Capacity> to) {
if (to == null)
return clone(from);
if (from != null) {
for (Map.Entry<String, Capacity> entryFrom : from.entrySet()) {
final String key = entryFrom.getKey();
final Capacity tocap = to.get(key);
final Capacity fromcap = entryFrom.getValue();
if (tocap == null) {
to.put(key, clone(fromcap));
} else {
to.put(key, new Capacity().withCapacityUnits(
doubleOf(tocap) + doubleOf(fromcap)));
}
}
}
return to;
}
private Map<String, Capacity> clone(Map<String, Capacity> capacityMap) {
if (capacityMap == null)
return null;
Map<String,Capacity> clone =
new HashMap<String,Capacity>(capacityMap.size());
for (Map.Entry<String, Capacity> e : capacityMap.entrySet())
clone.put(e.getKey(), clone(e.getValue()));
return clone;
}
private Capacity clone(Capacity capacity) {
return capacity == null
? null
: new Capacity().withCapacityUnits(capacity.getCapacityUnits());
}
private double doubleOf(Capacity cap) {
if (cap == null)
return 0.0;
Double val = cap.getCapacityUnits();
return val == null ? 0.0 : val.doubleValue();
}
/**
* Returns the total count accumulated so far.
*/
public int getTotalCount() {
return totalCount;
}
/**
* Returns the total scanned count accumulated so far.
*/
public int getTotalScannedCount() {
return totalScannedCount;
}
/**
* Returns the total consumed capacity accumulated so far.
*/
public ConsumedCapacity getTotalConsumedCapacity() {
return totalConsumedCapacity;
}
// Overriding these just so javadocs will show up.
/**
* Returns an {@code Iterable<Page<Item, R>>} that iterates over pages of
* items from this collection. Each call to {@code Iterator.next} on an
* {@code Iterator} returned from this {@code Iterable} results in exactly
* one call to DynamoDB to retrieve a single page of results.
* <p>
* <code>
* ItemCollection<QueryResult> collection = ...;
* for (Page<Item> page : collection.pages()) {
* processItems(page);
*
* ConsumedCapacity consumedCapacity =
* page.getLowLevelResult().getConsumedCapacity();
*
* Thread.sleep(getBackoff(consumedCapacity.getCapacityUnits()));
* }
* </code>
* <p>
* The use of the internal/undocumented {@code PageIterable} class instead
* of {@code Iterable} in the public interface here is retained for
* backwards compatibility. It doesn't expose any methods beyond those
* of the {@code Iterable} interface. This method will be changed to return
* an {@code Iterable<Page<Item, R>>} directly in a future release of the
* SDK.
*
* @see Page
*/
@Override
public PageIterable<Item, R> pages() {
return super.pages();
}
/**
* Returns the maximum number of resources to be retrieved in this
* collection; or null if there is no limit.
*/
@Override
public abstract Integer getMaxResultSize();
/**
* Returns the low-level result last retrieved (for the current page) from
* the server side; or null if there has yet no calls to the server.
*/
@Override
public R getLastLowLevelResult() {
return super.getLastLowLevelResult();
}
/**
* Used to register a listener for the event of receiving a low-level result
* from the server side.
*
* @param listener
* listener to be registered. If null, a "none" listener will be
* set.
* @return the previously registered listener. The return value is never
* null.
*/
@Override
public LowLevelResultListener<R> registerLowLevelResultListener(
LowLevelResultListener<R> listener) {
return super.registerLowLevelResultListener(listener);
}
}
| |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.Nullable;
/**
* Static convenience methods that help a method or constructor check whether it was invoked
* correctly (whether its <i>preconditions</i> have been met). These methods generally accept a
* {@code boolean} expression which is expected to be {@code true} (or in the case of {@code
* checkNotNull}, an object reference which is expected to be non-null). When {@code false} (or
* {@code null}) is passed instead, the {@code Preconditions} method throws an unchecked exception,
* which helps the calling method communicate to <i>its</i> caller that <i>that</i> caller has made
* a mistake. Example: <pre> {@code
*
* /**
* * Returns the positive square root of the given value.
* *
* * @throws IllegalArgumentException if the value is negative
* *}{@code /
* public static double sqrt(double value) {
* Preconditions.checkArgument(value >= 0.0, "negative value: %s", value);
* // calculate the square root
* }
*
* void exampleBadCaller() {
* double d = sqrt(-1.0);
* }}</pre>
*
* In this example, {@code checkArgument} throws an {@code IllegalArgumentException} to indicate
* that {@code exampleBadCaller} made an error in <i>its</i> call to {@code sqrt}.
*
* <h3>Warning about performance</h3>
*
* <p>The goal of this class is to improve readability of code, but in some circumstances this may
* come at a significant performance cost. Remember that parameter values for message construction
* must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even
* when the precondition check then succeeds (as it should almost always do in production). In some
* circumstances these wasted CPU cycles and allocations can add up to a real problem.
* Performance-sensitive precondition checks can always be converted to the customary form:
* <pre> {@code
*
* if (value < 0.0) {
* throw new IllegalArgumentException("negative value: " + value);
* }}</pre>
*
* <h3>Other types of preconditions</h3>
*
* <p>Not every type of precondition failure is supported by these methods. Continue to throw
* standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link
* UnsupportedOperationException} in the situations they are intended for.
*
* <h3>Non-preconditions</h3>
*
* <p>It is of course possible to use the methods of this class to check for invalid conditions
* which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is
* misleading to future readers of the code and of stack traces. See
* <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">Conditional
* failures explained</a> in the Guava User Guide for more advice.
*
* <h3>{@code java.util.Objects.requireNonNull()}</h3>
*
* <p>Projects which use {@code com.google.common} should generally avoid the use of {@link
* java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link
* #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation.
* (The same goes for the message-accepting overloads.)
*
* <h3>Only {@code %s} is supported</h3>
*
* <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is
* supported, not the full range of {@link java.util.Formatter} specifiers.
*
* <h3>More information</h3>
*
* <p>See the Guava User Guide on
* <a href="http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">using {@code
* Preconditions}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkArgument(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkState(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...));
* }
*
* The alternative natural refactorings into void or Exception-returning methods are much slower.
* This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This
* is a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
* RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this class want to throw different exceptions, depending on the args, so it
* appears that this pattern is not directly applicable. But we can use the ridiculous, devious
* trick of throwing an exception in the middle of the construction of another exception. Hotspot
* is fine with that.
*/
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
* {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
private static String badElementIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
* size {@code size}. A position index may range from zero to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
* size {@code size}. A position index may range from zero to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
private static String badPositionIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index > size
return format("%s (%s) must not be greater than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list
* or string of size {@code size}, and are in order. A position index may range from zero to
* {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an array, list or string
* @param end a user-supplied index identifying a ending position in an array, list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size},
* or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badPositionIndexes(int start, int end, int size) {
if (start < 0 || start > size) {
return badPositionIndex(start, size, "start index");
}
if (end < 0 || end > size) {
return badPositionIndex(end, size, "end index");
}
// end < start
return format("end index (%s) must not be less than start index (%s)", end, start);
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These are matched by
* position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
* placeholders, the unmatched arguments will be appended to the end of the formatted message in
* square braces.
*
* @param template a non-null string containing 0 or more {@code %s} placeholders.
* @param args the arguments to be substituted into the message template. Arguments are converted
* to strings using {@link String#valueOf(Object)}. Arguments can be null.
*/
// Note that this is somewhat-improperly used from Verify.java as well.
static String format(String template, @Nullable Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}
| |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.cmmn.entity.runtime;
import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_ACTIVITY_DESCRIPTION;
import static org.camunda.bpm.engine.impl.cmmn.handler.ItemHandler.PROPERTY_ACTIVITY_TYPE;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.cmmn.entity.repository.CaseDefinitionEntity;
import org.camunda.bpm.engine.impl.cmmn.execution.CmmnExecution;
import org.camunda.bpm.engine.impl.cmmn.execution.CmmnSentryPart;
import org.camunda.bpm.engine.impl.cmmn.model.CmmnActivity;
import org.camunda.bpm.engine.impl.cmmn.model.CmmnCaseDefinition;
import org.camunda.bpm.engine.impl.cmmn.operation.CmmnAtomicOperation;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.core.instance.CoreExecution;
import org.camunda.bpm.engine.impl.core.operation.CoreAtomicOperation;
import org.camunda.bpm.engine.impl.core.variable.scope.CoreVariableStore;
import org.camunda.bpm.engine.impl.db.DbEntity;
import org.camunda.bpm.engine.impl.db.HasDbReferences;
import org.camunda.bpm.engine.impl.db.HasDbRevision;
import org.camunda.bpm.engine.impl.history.HistoryLevel;
import org.camunda.bpm.engine.impl.history.event.HistoryEvent;
import org.camunda.bpm.engine.impl.history.event.HistoryEventTypes;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import org.camunda.bpm.engine.impl.history.producer.CmmnHistoryEventProducer;
import org.camunda.bpm.engine.impl.history.producer.HistoryEventProducer;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity;
import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity;
import org.camunda.bpm.engine.impl.pvm.PvmProcessDefinition;
import org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl;
import org.camunda.bpm.engine.impl.task.TaskDecorator;
import org.camunda.bpm.engine.runtime.CaseExecution;
import org.camunda.bpm.engine.runtime.CaseInstance;
import org.camunda.bpm.model.cmmn.CmmnModelInstance;
import org.camunda.bpm.model.cmmn.instance.CmmnElement;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.type.ModelElementType;
/**
* @author Roman Smirnov
*
*/
public class CaseExecutionEntity extends CmmnExecution implements CaseExecution, CaseInstance, DbEntity, HasDbRevision, HasDbReferences {
private static final long serialVersionUID = 1L;
// current position /////////////////////////////////////////////////////////
/** the case instance. this is the root of the execution tree.
* the caseInstance of a case instance is a self reference. */
protected transient CaseExecutionEntity caseInstance;
/** the parent execution */
protected transient CaseExecutionEntity parent;
/** nested executions */
protected List<CaseExecutionEntity> caseExecutions;
/** nested case sentry parts */
protected List<CaseSentryPartEntity> caseSentryParts;
protected Map<String, List<CmmnSentryPart>> sentries;
/** reference to a sub process instance, not-null if currently subprocess is started from this execution */
protected transient ExecutionEntity subProcessInstance;
protected transient ExecutionEntity superExecution;
protected transient CaseExecutionEntity subCaseInstance;
protected transient CaseExecutionEntity superCaseExecution;
// associated entities /////////////////////////////////////////////////////
protected CaseExecutionEntityVariableStore variableStore = new CaseExecutionEntityVariableStore(this);
// Persistence //////////////////////////////////////////////////////////////
protected int revision = 1;
protected String caseDefinitionId;
protected String activityId;
protected String caseInstanceId;
protected String parentId;
protected String superCaseExecutionId;
protected String superExecutionId;
// activity properites //////////////////////////////////////////////////////
protected String activityName;
protected String activityType;
protected String activityDescription;
// case definition ///////////////////////////////////////////////////////////
public String getCaseDefinitionId() {
return caseDefinitionId;
}
/** ensures initialization and returns the case definition. */
public CmmnCaseDefinition getCaseDefinition() {
ensureCaseDefinitionInitialized();
return caseDefinition;
}
public void setCaseDefinition(CmmnCaseDefinition caseDefinition) {
super.setCaseDefinition(caseDefinition);
caseDefinitionId = null;
if (caseDefinition != null) {
caseDefinitionId = caseDefinition.getId();
}
}
protected void ensureCaseDefinitionInitialized() {
if ((caseDefinition == null) && (caseDefinitionId != null)) {
CaseDefinitionEntity deployedCaseDefinition = Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.getCaseDefinitionById(caseDefinitionId);
setCaseDefinition(deployedCaseDefinition);
}
}
// parent ////////////////////////////////////////////////////////////////////
public CaseExecutionEntity getParent() {
ensureParentInitialized();
return parent;
}
public void setParent(CmmnExecution parent) {
this.parent = (CaseExecutionEntity) parent;
if (parent != null) {
this.parentId = parent.getId();
} else {
this.parentId = null;
}
}
protected void ensureParentInitialized() {
if (parent == null && parentId != null) {
if(isExecutionTreePrefetchEnabled()) {
ensureCaseExecutionTreeInitialized();
} else {
parent = Context
.getCommandContext()
.getCaseExecutionManager()
.findCaseExecutionById(parentId);
}
}
}
/**
* @see ExecutionEntity#ensureExecutionTreeInitialized
*/
protected void ensureCaseExecutionTreeInitialized() {
List<CaseExecutionEntity> executions = Context.getCommandContext()
.getCaseExecutionManager()
.findChildCaseExecutionsByCaseInstanceId(caseInstanceId);
CaseExecutionEntity caseInstance = null;
Map<String, CaseExecutionEntity> executionMap = new HashMap<String, CaseExecutionEntity>();
for (CaseExecutionEntity execution : executions) {
execution.caseExecutions = new ArrayList<CaseExecutionEntity>();
executionMap.put(execution.getId(), execution);
if(execution.isCaseInstanceExecution()) {
caseInstance = execution;
}
}
for (CaseExecutionEntity execution : executions) {
String parentId = execution.getParentId();
CaseExecutionEntity parent = executionMap.get(parentId);
if(!execution.isCaseInstanceExecution()) {
execution.caseInstance = caseInstance;
execution.parent = parent;
parent.caseExecutions.add(execution);
} else {
execution.caseInstance = execution;
}
}
}
/**
* @return true if execution tree prefetching is enabled
*/
protected boolean isExecutionTreePrefetchEnabled() {
return Context.getProcessEngineConfiguration()
.isExecutionTreePrefetchEnabled();
}
public String getParentId() {
return parentId;
}
// activity //////////////////////////////////////////////////////////////////
public CmmnActivity getActivity() {
ensureActivityInitialized();
return super.getActivity();
}
public void setActivity(CmmnActivity activity) {
super.setActivity(activity);
if (activity != null) {
this.activityId = activity.getId();
this.activityName = activity.getName();
this.activityType = getActivityProperty(activity, PROPERTY_ACTIVITY_TYPE);
this.activityDescription = getActivityProperty(activity, PROPERTY_ACTIVITY_DESCRIPTION);
} else {
this.activityId = null;
this.activityName = null;
this.activityType = null;
this.activityDescription = null;
}
}
protected void ensureActivityInitialized() {
if ((activity == null) && (activityId != null)) {
setActivity(getCaseDefinition().findActivity(activityId));
}
}
protected String getActivityProperty(CmmnActivity activity, String property) {
String result = null;
if (activity != null) {
Object value = activity.getProperty(property);
if (value != null && value instanceof String) {
result = (String) value;
}
}
return result;
}
// activity properties //////////////////////////////////////////////////////
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
public String getActivityType() {
return activityType;
}
public String getActivityDescription() {
return activityDescription;
}
// case executions ////////////////////////////////////////////////////////////////
public List<CaseExecutionEntity> getCaseExecutions() {
return new ArrayList<CaseExecutionEntity>(getCaseExecutionsInternal());
}
protected List<CaseExecutionEntity> getCaseExecutionsInternal() {
ensureCaseExecutionsInitialized();
return caseExecutions;
}
protected void ensureCaseExecutionsInitialized() {
if (caseExecutions == null) {
this.caseExecutions = Context
.getCommandContext()
.getCaseExecutionManager()
.findChildCaseExecutionsByParentCaseExecutionId(id);
}
}
// task ///////////////////////////////////////////////////////////////////
public TaskEntity getTask() {
ensureTaskInitialized();
return task;
}
protected void ensureTaskInitialized() {
if (task == null) {
task = Context
.getCommandContext()
.getTaskManager()
.findTaskByCaseExecutionId(id);
}
}
public TaskEntity createTask(TaskDecorator taskDecorator) {
TaskEntity task = super.createTask(taskDecorator);
fireHistoricCaseActivityInstanceUpdate();
return task;
}
// case instance /////////////////////////////////////////////////////////
public String getCaseInstanceId() {
return caseInstanceId;
}
public CaseExecutionEntity getCaseInstance() {
ensureCaseInstanceInitialized();
return caseInstance;
}
public void setCaseInstance(CmmnExecution caseInstance) {
this.caseInstance = (CaseExecutionEntity) caseInstance;
if (caseInstance != null) {
this.caseInstanceId = this.caseInstance.getId();
}
}
protected void ensureCaseInstanceInitialized() {
if ((caseInstance == null) && (caseInstanceId != null)) {
caseInstance = Context
.getCommandContext()
.getCaseExecutionManager()
.findCaseExecutionById(caseInstanceId);
}
}
@Override
public boolean isCaseInstanceExecution() {
return parentId == null;
}
protected CaseExecutionEntity createCaseExecution(CmmnActivity activity) {
CaseExecutionEntity child = newCaseExecution();
// set activity to execute
child.setActivity(activity);
// handle child/parent-relation
child.setParent(this);
getCaseExecutionsInternal().add(child);
// set case instance
child.setCaseInstance(getCaseInstance());
// set case definition
child.setCaseDefinition(getCaseDefinition());
return child;
}
protected CaseExecutionEntity newCaseExecution() {
CaseExecutionEntity newCaseExecution = new CaseExecutionEntity();
Context
.getCommandContext()
.getCaseExecutionManager()
.insertCaseExecution(newCaseExecution);
return newCaseExecution;
}
// super execution //////////////////////////////////////////////////////
public String getSuperExecutionId() {
return superExecutionId;
}
public void setSuperExecutionId(String superProcessExecutionId) {
this.superExecutionId = superProcessExecutionId;
}
public ExecutionEntity getSuperExecution() {
ensureSuperExecutionInstanceInitialized();
return superExecution;
}
public void setSuperExecution(PvmExecutionImpl superExecution) {
this.superExecution = (ExecutionEntity) superExecution;
if (superExecution != null) {
this.superExecutionId = superExecution.getId();
} else {
this.superExecutionId = null;
}
}
protected void ensureSuperExecutionInstanceInitialized() {
if (superExecution == null && superExecutionId != null) {
superExecution = Context
.getCommandContext()
.getExecutionManager()
.findExecutionById(superExecutionId);
}
}
// sub process instance ///////////////////////////////////////////////////
public ExecutionEntity getSubProcessInstance() {
ensureSubProcessInstanceInitialized();
return subProcessInstance;
}
public void setSubProcessInstance(PvmExecutionImpl subProcessInstance) {
this.subProcessInstance = (ExecutionEntity) subProcessInstance;
}
public ExecutionEntity createSubProcessInstance(PvmProcessDefinition processDefinition) {
return createSubProcessInstance(processDefinition, null);
}
public ExecutionEntity createSubProcessInstance(PvmProcessDefinition processDefinition, String businessKey) {
return createSubProcessInstance(processDefinition, businessKey, getCaseInstanceId());
}
public ExecutionEntity createSubProcessInstance(PvmProcessDefinition processDefinition, String businessKey, String caseInstanceId) {
ExecutionEntity subProcessInstance = (ExecutionEntity) processDefinition.createProcessInstance(businessKey, caseInstanceId);
// manage bidirectional super-subprocess relation
subProcessInstance.setSuperCaseExecution(this);
setSubProcessInstance(subProcessInstance);
fireHistoricCaseActivityInstanceUpdate();
return subProcessInstance;
}
protected void ensureSubProcessInstanceInitialized() {
if (subProcessInstance == null) {
subProcessInstance = Context
.getCommandContext()
.getExecutionManager()
.findSubProcessInstanceBySuperCaseExecutionId(id);
}
}
// sub-/super- case instance ////////////////////////////////////////////////////
public CaseExecutionEntity getSubCaseInstance() {
ensureSubCaseInstanceInitialized();
return subCaseInstance;
}
public void setSubCaseInstance(CmmnExecution subCaseInstance) {
this.subCaseInstance = (CaseExecutionEntity) subCaseInstance;
}
public CaseExecutionEntity createSubCaseInstance(CmmnCaseDefinition caseDefinition) {
return createSubCaseInstance(caseDefinition, null);
}
public CaseExecutionEntity createSubCaseInstance(CmmnCaseDefinition caseDefinition, String businessKey) {
CaseExecutionEntity subCaseInstance = (CaseExecutionEntity) caseDefinition.createCaseInstance(businessKey);
// manage bidirectional super-sub-case-instances relation
subCaseInstance.setSuperCaseExecution(this);
setSubCaseInstance(subCaseInstance);
fireHistoricCaseActivityInstanceUpdate();
return subCaseInstance;
}
public void fireHistoricCaseActivityInstanceUpdate() {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.CASE_ACTIVITY_INSTANCE_UPDATE, this)) {
CmmnHistoryEventProducer eventProducer = configuration.getCmmnHistoryEventProducer();
HistoryEventHandler eventHandler = configuration.getHistoryEventHandler();
HistoryEvent event = eventProducer.createCaseActivityInstanceUpdateEvt(this);
eventHandler.handleEvent(event);
}
}
protected void ensureSubCaseInstanceInitialized() {
if (subCaseInstance == null) {
subCaseInstance = Context
.getCommandContext()
.getCaseExecutionManager()
.findSubCaseInstanceBySuperCaseExecutionId(id);
}
}
public String getSuperCaseExecutionId() {
return superCaseExecutionId;
}
public void setSuperCaseExecutionId(String superCaseExecutionId) {
this.superCaseExecutionId = superCaseExecutionId;
}
public CmmnExecution getSuperCaseExecution() {
ensureSuperCaseExecutionInitialized();
return superCaseExecution;
}
public void setSuperCaseExecution(CmmnExecution superCaseExecution) {
this.superCaseExecution = (CaseExecutionEntity) superCaseExecution;
if (superCaseExecution != null) {
this.superCaseExecutionId = superCaseExecution.getId();
} else {
this.superCaseExecutionId = null;
}
}
protected void ensureSuperCaseExecutionInitialized() {
if (superCaseExecution == null && superCaseExecutionId != null) {
superCaseExecution = Context
.getCommandContext()
.getCaseExecutionManager()
.findCaseExecutionById(superCaseExecutionId);
}
}
// sentry /////////////////////////////////////////////////////////////////////////
public List<CaseSentryPartEntity> getCaseSentryParts() {
ensureCaseSentryPartsInitialized();
return caseSentryParts;
}
protected void ensureCaseSentryPartsInitialized() {
if (caseSentryParts == null) {
caseSentryParts = Context
.getCommandContext()
.getCaseSentryPartManager()
.findCaseSentryPartsByCaseExecutionId(id);
// create a map sentries: sentryId -> caseSentryParts
// for simple select to get all parts for one sentry
sentries = new HashMap<String, List<CmmnSentryPart>>();
for (CaseSentryPartEntity sentryPart : caseSentryParts) {
String sentryId = sentryPart.getSentryId();
List<CmmnSentryPart> parts = sentries.get(sentryId);
if (parts == null) {
parts = new ArrayList<CmmnSentryPart>();
sentries.put(sentryId, parts);
}
parts.add(sentryPart);
}
}
}
protected void addSentryPart(CmmnSentryPart sentryPart) {
CaseSentryPartEntity entity = (CaseSentryPartEntity) sentryPart;
getCaseSentryParts().add(entity);
String sentryId = sentryPart.getSentryId();
List<CmmnSentryPart> parts = sentries.get(sentryId);
if (parts == null) {
parts = new ArrayList<CmmnSentryPart>();
sentries.put(sentryId, parts);
}
parts.add(entity);
}
protected Map<String, List<CmmnSentryPart>> getSentries() {
ensureCaseSentryPartsInitialized();
return sentries;
}
protected List<CmmnSentryPart> findSentry(String sentryId) {
ensureCaseSentryPartsInitialized();
return sentries.get(sentryId);
}
protected CaseSentryPartEntity newSentryPart() {
CaseSentryPartEntity caseSentryPart = new CaseSentryPartEntity();
Context
.getCommandContext()
.getCaseSentryPartManager()
.insertCaseSentryPart(caseSentryPart);
return caseSentryPart;
}
// variables //////////////////////////////////////////////////////////////
protected CoreVariableStore getVariableStore() {
return variableStore;
}
protected void initializeVariableInstanceBackPointer(VariableInstanceEntity variableInstance) {
variableInstance.setCaseInstanceId(caseInstanceId);
variableInstance.setCaseExecutionId(id);
}
protected List<VariableInstanceEntity> loadVariableInstances() {
return Context
.getCommandContext()
.getVariableInstanceManager()
.findVariableInstancesByCaseExecutionId(id);
}
// toString /////////////////////////////////////////////////////////////
public String toString() {
if (isCaseInstanceExecution()) {
return "CaseInstance["+getToStringIdentity()+"]";
} else {
return "CaseExecution["+getToStringIdentity()+"]";
}
}
protected String getToStringIdentity() {
return id;
}
// delete/remove ///////////////////////////////////////////////////////
public void remove() {
super.remove();
variableStore.removeVariablesWithoutFiringEvents();
CommandContext commandContext = Context.getCommandContext();
for (CaseSentryPartEntity sentryPart : getCaseSentryParts()) {
commandContext
.getCaseSentryPartManager()
.deleteSentryPart(sentryPart);
}
// finally delete this execution
commandContext
.getCaseExecutionManager()
.deleteCaseExecution(this);
}
// persistence /////////////////////////////////////////////////////////
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public int getRevisionNext() {
return revision + 1;
}
public void forceUpdate() {
Context.getCommandContext()
.getDbEntityManager()
.forceUpdate(this);
}
public boolean hasReferenceTo(DbEntity entity) {
if (entity instanceof CaseExecutionEntity) {
CaseExecutionEntity otherEntity = (CaseExecutionEntity) entity;
String otherId = otherEntity.getId();
// parentId
if(parentId != null && parentId.equals(otherId)) {
return true;
}
// superExecutionId
if(superCaseExecutionId != null && superCaseExecutionId.equals(otherId)) {
return true;
}
}
return false;
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("caseDefinitionId", caseDefinitionId);
persistentState.put("businessKey", businessKey);
persistentState.put("activityId", activityId);
persistentState.put("parentId", parentId);
persistentState.put("currentState", currentState);
persistentState.put("previousState", previousState);
return persistentState;
}
public CmmnModelInstance getCmmnModelInstance() {
if(caseDefinitionId != null) {
return Context.getProcessEngineConfiguration()
.getDeploymentCache()
.findCmmnModelInstanceForCaseDefinition(caseDefinitionId);
} else {
return null;
}
}
public CmmnElement getCmmnModelElementInstance() {
CmmnModelInstance cmmnModelInstance = getCmmnModelInstance();
if(cmmnModelInstance != null) {
ModelElementInstance modelElementInstance = cmmnModelInstance.getModelElementById(activityId);
try {
return (CmmnElement) modelElementInstance;
} catch(ClassCastException e) {
ModelElementType elementType = modelElementInstance.getElementType();
throw new ProcessEngineException("Cannot cast "+modelElementInstance+" to CmmnElement. "
+ "Is of type "+elementType.getTypeName() + " Namespace "
+ elementType.getTypeNamespace(), e);
}
} else {
return null;
}
}
public ProcessEngineServices getProcessEngineServices() {
return Context
.getProcessEngineConfiguration()
.getProcessEngine();
}
public <T extends CoreExecution> void performOperation(CoreAtomicOperation<T> operation) {
Context.getCommandContext()
.performOperation((CmmnAtomicOperation) operation, this);
}
public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) {
Context.getCommandContext()
.performOperation((CmmnAtomicOperation) operation, this);
}
}
| |
/*
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.support.pagefactory;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.How;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
public class Annotations {
private Field field;
public Annotations(Field field) {
this.field = field;
}
public boolean isLookupCached() {
return (field.getAnnotation(CacheLookup.class) != null);
}
public By buildBy() {
assertValidAnnotations();
By ans = null;
FindBys findBys = field.getAnnotation(FindBys.class);
if (ans == null && findBys != null) {
ans = buildByFromFindBys(findBys);
}
FindBy findBy = field.getAnnotation(FindBy.class);
if (ans == null && findBy != null) {
ans = buildByFromFindBy(findBy);
}
if (ans == null) {
ans = buildByFromDefault();
}
if (ans == null) {
throw new IllegalArgumentException("Cannot determine how to locate element " + field);
}
return ans;
}
protected By buildByFromDefault() {
return new ByIdOrName(field.getName());
}
protected By buildByFromFindBys(FindBys findBys) {
assertValidFindBys(findBys);
FindBy[] findByArray = findBys.value();
By[] byArray = new By[findByArray.length];
for (int i = 0; i < findByArray.length; i++) {
byArray[i] = buildByFromFindBy(findByArray[i]);
}
return new ByChained(byArray);
}
protected By buildByFromFindBy(FindBy findBy) {
assertValidFindBy(findBy);
By ans = buildByFromShortFindBy(findBy);
if (ans == null) {
ans = buildByFromLongFindBy(findBy);
}
return ans;
}
protected By buildByFromLongFindBy(FindBy findBy) {
How how = findBy.how();
String using = findBy.using();
switch (how) {
case CLASS_NAME:
return By.className(using);
case CSS:
return By.cssSelector(using);
case ID:
return By.id(using);
case ID_OR_NAME:
return new ByIdOrName(using);
case LINK_TEXT:
return By.linkText(using);
case NAME:
return By.name(using);
case PARTIAL_LINK_TEXT:
return By.partialLinkText(using);
case TAG_NAME:
return By.tagName(using);
case XPATH:
return By.xpath(using);
default:
// Note that this shouldn't happen (eg, the above matches all
// possible values for the How enum)
throw new IllegalArgumentException("Cannot determine how to locate element " + field);
}
}
protected By buildByFromShortFindBy(FindBy findBy) {
if (!"".equals(findBy.className()))
return By.className(findBy.className());
if (!"".equals(findBy.css()))
return By.cssSelector(findBy.css());
if (!"".equals(findBy.id()))
return By.id(findBy.id());
if (!"".equals(findBy.linkText()))
return By.linkText(findBy.linkText());
if (!"".equals(findBy.name()))
return By.name(findBy.name());
if (!"".equals(findBy.partialLinkText()))
return By.partialLinkText(findBy.partialLinkText());
if (!"".equals(findBy.tagName()))
return By.tagName(findBy.tagName());
if (!"".equals(findBy.xpath()))
return By.xpath(findBy.xpath());
// Fall through
return null;
}
private void assertValidAnnotations() {
FindBys findBys = field.getAnnotation(FindBys.class);
FindBy findBy = field.getAnnotation(FindBy.class);
if (findBys != null && findBy != null) {
throw new IllegalArgumentException("If you use a '@FindBys' annotation, "
+ "you must not also use a '@FindBy' annotation");
}
}
private void assertValidFindBys(FindBys findBys) {
for (FindBy findBy : findBys.value()) {
assertValidFindBy(findBy);
}
}
private void assertValidFindBy(FindBy findBy) {
if (findBy.how() != null) {
if (findBy.using() == null) {
throw new IllegalArgumentException(
"If you set the 'how' property, you must also set 'using'");
}
}
Set<String> finders = new HashSet<String>();
if (!"".equals(findBy.using())) finders.add("how: " + findBy.using());
if (!"".equals(findBy.className())) finders.add("class name:" + findBy.className());
if (!"".equals(findBy.css())) finders.add("css:" + findBy.css());
if (!"".equals(findBy.id())) finders.add("id: " + findBy.id());
if (!"".equals(findBy.linkText())) finders.add("link text: " + findBy.linkText());
if (!"".equals(findBy.name())) finders.add("name: " + findBy.name());
if (!"".equals(findBy.partialLinkText()))
finders.add("partial link text: " + findBy.partialLinkText());
if (!"".equals(findBy.tagName())) finders.add("tag name: " + findBy.tagName());
if (!"".equals(findBy.xpath())) finders.add("xpath: " + findBy.xpath());
// A zero count is okay: it means to look by name or id.
if (finders.size() > 1) {
throw new IllegalArgumentException(
String.format("You must specify at most one location strategy. Number found: %d (%s)",
finders.size(), finders.toString()));
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.framework;
import com.intellij.ide.BootstrapClassLoaderUtil;
import com.intellij.ide.IdeEventQueue;
import com.intellij.ide.WindowsCommandLineProcessor;
import com.intellij.ide.startup.StartupActionScriptManager;
import com.intellij.idea.Main;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.lang.UrlClassLoader;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Pattern;
import static com.intellij.openapi.application.PathManager.PROPERTY_CONFIG_PATH;
import static com.intellij.openapi.application.PathManager.PROPERTY_SYSTEM_PATH;
import static com.intellij.openapi.util.io.FileUtil.*;
import static com.intellij.openapi.util.text.StringUtil.isNotEmpty;
import static com.intellij.testGuiFramework.framework.GuiTestUtil.getProjectCreationDirPath;
import static com.intellij.testGuiFramework.framework.GuiTestUtil.getSystemPropertyOrEnvironmentVariable;
import static com.intellij.util.ArrayUtil.EMPTY_STRING_ARRAY;
import static com.intellij.util.ui.UIUtil.initDefaultLAF;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.reflect.core.Reflection.method;
import static org.junit.Assert.assertNotNull;
public class IdeTestApplication {
private static final Logger LOG = Logger.getInstance(IdeTestApplication.class);
private static final String PROPERTY_IGNORE_CLASSPATH = "ignore.classpath";
private static final String PROPERTY_ALLOW_BOOTSTRAP_RESOURCES = "idea.allow.bootstrap.resources";
private static final String PROPERTY_ADDITIONAL_CLASSPATH = "idea.additional.classpath";
private static final String CUSTOM_CONFIG_PATH= "CUSTOM_CONFIG_PATH";
private static final String CUSTOM_SYSTEM_PATH= "CUSTOM_SYSTEM_PATH";
private static IdeTestApplication ourInstance;
protected ClassLoader myIdeClassLoader;
@NotNull
public ClassLoader getIdeClassLoader() {
return myIdeClassLoader;
}
@NotNull
public static File getFailedTestScreenshotDirPath() throws IOException {
File dirPath = new File(getGuiTestRootDirPath(), "failures");
ensureExists(dirPath);
return dirPath;
}
@NotNull
public static File getTestScreenshotDirPath() throws IOException {
File dirPath = new File(getGuiTestRootDirPath(), "screenshots");
ensureExists(dirPath);
return dirPath;
}
@NotNull
protected static File getGuiTestRootDirPath() throws IOException {
String guiTestRootDirPathProperty = System.getProperty("gui.tests.root.dir.path");
if (isNotEmpty(guiTestRootDirPathProperty)) {
File rootDirPath = new File(guiTestRootDirPathProperty);
if (rootDirPath.isDirectory()) {
return rootDirPath;
}
}
String homeDirPath = toSystemDependentName(PathManager.getHomePath());
assertThat(homeDirPath).isNotEmpty();
File rootDirPath = new File(homeDirPath, "gui-tests");
ensureExists(rootDirPath);
return rootDirPath;
}
@NotNull
public static synchronized IdeTestApplication getInstance() throws Exception {
String customConfigPath = getSystemPropertyOrEnvironmentVariable(CUSTOM_CONFIG_PATH);
String customSystemPath = getSystemPropertyOrEnvironmentVariable(CUSTOM_SYSTEM_PATH);
File configDirPath = null;
boolean isDefaultConfig = true;
if (StringUtil.isEmpty(customConfigPath)) {
configDirPath = getConfigDirPath();
System.setProperty(PROPERTY_CONFIG_PATH, configDirPath.getPath());
} else {
isDefaultConfig = false;
File customConfigFile = new File(customConfigPath);
System.setProperty(PROPERTY_CONFIG_PATH, customConfigFile.getPath());
}
if (! StringUtil.isEmpty(customSystemPath)) System.setProperty(PROPERTY_SYSTEM_PATH, Paths.get(customSystemPath).toFile().getPath());
//Force Swing FileChooser on Mac (instead of native one) to be able to use FEST to drive it.
System.setProperty("native.mac.file.chooser.enabled", "false");
//We are using this property to skip testProjectLeak in _LastSuiteTests
System.setProperty("idea.test.guimode", "true");
if (!isLoaded()) {
ourInstance = new IdeTestApplication();
if (isDefaultConfig) recreateDirectory(configDirPath);
File newProjectsRootDirPath = getProjectCreationDirPath();
recreateDirectory(newProjectsRootDirPath);
ClassLoader ideClassLoader = ourInstance.getIdeClassLoader();
Class<?> clazz = ideClassLoader.loadClass(GuiTestUtil.class.getCanonicalName());
method("waitForIdeToStart").in(clazz).invoke();
}
return ourInstance;
}
@NotNull
private static File getConfigDirPath() throws IOException {
File dirPath = new File(getGuiTestRootDirPath(), "config");
ensureExists(dirPath);
return dirPath;
}
private static void recreateDirectory(@NotNull File path) throws IOException {
delete(path);
ensureExists(path);
}
private IdeTestApplication() throws Exception {
String[] args = EMPTY_STRING_ARRAY;
LOG.assertTrue(ourInstance == null, "Only one instance allowed.");
ourInstance = this;
pluginManagerStart(args);
myIdeClassLoader = createClassLoader();
WindowsCommandLineProcessor.ourMirrorClass = Class.forName(WindowsCommandLineProcessor.class.getName(), true, myIdeClassLoader);
Class<?> classUtilCoreClass = Class.forName("com.intellij.ide.ClassUtilCore", true, myIdeClassLoader);
method("clearJarURLCache").in(classUtilCoreClass).invoke();
Class<?> pluginManagerClass = Class.forName("com.intellij.ide.plugins.PluginManager", true, myIdeClassLoader);
method("start").withParameterTypes(String.class, String.class, String[].class)
.in(pluginManagerClass)
.invoke("com.intellij.idea.MainImpl", "start", args);
}
// This method replaces BootstrapClassLoaderUtil.initClassLoader. The reason behind it is that when running UI tests the ClassLoader
// containing the URLs for the plugin jars is loaded by a different ClassLoader and it gets ignored. The result is test failing because
// classes like AndroidPlugin cannot be found.
@NotNull
private static ClassLoader createClassLoader() throws MalformedURLException, URISyntaxException {
Collection<URL> classpath = new LinkedHashSet<>();
addIdeaLibraries(classpath);
addAdditionalClassPath(classpath);
UrlClassLoader.Builder builder = UrlClassLoader.build()
.urls(filterClassPath(new ArrayList<>(classpath)))
//.parent(IdeTestApplication.class.getClassLoader())
.allowLock(false)
.usePersistentClasspathIndexForLocalClassDirectories();
if (SystemProperties.getBooleanProperty(PROPERTY_ALLOW_BOOTSTRAP_RESOURCES, true)) {
builder.allowBootstrapResources();
}
UrlClassLoader newClassLoader = builder.get();
// prepare plugins
try {
StartupActionScriptManager.executeActionScript();
}
catch (IOException e) {
Main.showMessage("Plugin Installation Error", e);
}
Thread.currentThread().setContextClassLoader(newClassLoader);
return newClassLoader;
}
private static void addIdeaLibraries(@NotNull Collection<URL> classpath) throws MalformedURLException {
Class<BootstrapClassLoaderUtil> aClass = BootstrapClassLoaderUtil.class;
String selfRoot = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
assertNotNull(selfRoot);
URL selfRootUrl = new File(selfRoot).getAbsoluteFile().toURI().toURL();
classpath.add(selfRootUrl);
File libFolder = new File(PathManager.getLibPath());
addLibraries(classpath, libFolder, selfRootUrl);
addLibraries(classpath, new File(libFolder, "ext"), selfRootUrl);
addLibraries(classpath, new File(libFolder, "ant/lib"), selfRootUrl);
}
private static void addLibraries(@NotNull Collection<URL> classPath, @NotNull File fromDir, @NotNull URL selfRootUrl)
throws MalformedURLException {
for (File file : notNullize(fromDir.listFiles())) {
if (isJarOrZip(file)) {
URL url = file.toURI().toURL();
if (!selfRootUrl.equals(url)) {
classPath.add(url);
}
}
}
}
private static void addAdditionalClassPath(@NotNull Collection<URL> classpath) throws MalformedURLException {
StringTokenizer tokenizer = new StringTokenizer(System.getProperty(PROPERTY_ADDITIONAL_CLASSPATH, ""), File.pathSeparator, false);
while (tokenizer.hasMoreTokens()) {
String pathItem = tokenizer.nextToken();
classpath.add(new File(pathItem).toURI().toURL());
}
}
private static List<URL> filterClassPath(@NotNull List<URL> classpath) {
String ignoreProperty = System.getProperty(PROPERTY_IGNORE_CLASSPATH);
if (ignoreProperty != null) {
Pattern pattern = Pattern.compile(ignoreProperty);
for (Iterator<URL> i = classpath.iterator(); i.hasNext(); ) {
String url = i.next().toExternalForm();
if (pattern.matcher(url).matches()) {
i.remove();
}
}
}
return classpath;
}
private static void pluginManagerStart(@NotNull String[] args) {
// Duplicates what PluginManager#start does.
Main.setFlags(args);
initDefaultLAF();
}
public void dispose() {
disposeInstance();
}
public static synchronized void disposeInstance() {
if (!isLoaded()) {
return;
}
IdeEventQueue.getInstance().flushQueue();
final Application application = ApplicationManager.getApplication();
((ApplicationImpl)application).exit(true, true, false);
ourInstance = null;
}
public static synchronized boolean isLoaded() {
return ourInstance != null;
}
}
| |
package com.semperos.screwdriver;
import org.apache.commons.io.filefilter.IOFileFilter;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Default values for configurable aspects of Screwdriver.
*/
public class DefaultConfig {
public static boolean isDebugMode() {
return false;
}
public static String getAssetDirectory() {
return System.getProperty("user.dir");
}
public static String getOutputDirectory() {
return System.getProperty("user.dir") + File.separator + "target" + File.separator + "client";
}
public static String getJsSubDirectoryName() {
return "javascripts";
}
public static String getCssSubDirectoryName() {
return "stylesheets";
}
public static String getImageSubDirectoryName() {
return "images";
}
public static String getTemplateSubDirectoryName() {
return "javascripts";
}
public static String getServerTemplateSubDirectoryName() {
return "server_templates";
}
public static String getStaticAssetDirectoryName() {
return "data";
}
public static boolean isJsSourceMapsEnabled() {
return false;
}
public static ArrayList<String> getJsExtensions() {
ArrayList<String> exts = new ArrayList<>();
exts.add("js");
exts.add("coffee");
return exts;
}
public static ArrayList<String> getCssExtensions() {
ArrayList<String> exts = new ArrayList<>();
exts.add("css");
exts.add("less");
return exts;
}
public static ArrayList<String> getImageExtensions() {
ArrayList<String> exts = new ArrayList<>();
exts.add("bmp");
exts.add("gif");
exts.add("jpg");
exts.add("jpeg");
exts.add("png");
exts.add("svg");
return exts;
}
public static ArrayList<String> getTemplateExtensions() {
ArrayList<String> exts = new ArrayList<>();
exts.add("dust");
return exts;
}
public static ArrayList<String> getServerTemplateExtensions() {
ArrayList<String> exts = new ArrayList<>();
exts.add("html");
exts.add("jade");
return exts;
}
public static ArrayList<String> getStaticAssetExtensions() {
return new ArrayList<String>();
}
public static ArrayList<String> getJsIncludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getJsExcludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getCssIncludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getCssExcludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getImageIncludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getImageExcludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getTemplateIncludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getTemplateExcludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getServerTemplateIncludes() {
return new ArrayList<String>();
}
public static ArrayList<String> getServerTemplateExcludes() {
return new ArrayList<String>();
}
public static boolean isOptimizeJs() {
return false;
}
public static boolean isOptimizeCss() {
return false;
}
public static boolean isOptimizeImage() {
return false;
}
public static ArrayList<String> getRjsModules() {
return new ArrayList<String>();
}
public static IOFileFilter getJsFileFilter() {
return null;
}
public static IOFileFilter getCssFileFilter() {
return null;
}
public static IOFileFilter getImageFileFilter() {
return null;
}
public static IOFileFilter getJsDirFilter() {
return null;
}
public static IOFileFilter getCssDirFilter() {
return null;
}
public static IOFileFilter getImageDirFilter() {
return null;
}
public static IOFileFilter getTemplateFileFilter() {
return null;
}
public static IOFileFilter getTemplateDirFilter() {
return null;
}
public static IOFileFilter getServerTemplateFileFilter() {
return null;
}
public static IOFileFilter getServerTemplateDirFilter() {
return null;
}
public static Map<String,Object> getServerTemplateLocals() {
return new HashMap<String,Object>();
}
public static List<String> getStaticAssetIncludes() {
return new ArrayList<String>();
}
public static List<String> getStaticAssetExcludes() {
return new ArrayList<String>();
}
public static IOFileFilter getStaticAssetFileFilter() {
return null;
}
public static IOFileFilter getStaticAssetDirFilter() {
return null;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.crawl;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.Closeable;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.TreeMap;
// Commons Logging imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapFileOutputFormat;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapred.lib.HashPartitioner;
import org.apache.hadoop.mapred.lib.IdentityMapper;
import org.apache.hadoop.mapred.lib.IdentityReducer;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.NutchTool;
import org.apache.nutch.util.StringUtil;
/**
* Read utility for the CrawlDB.
*
* @author Andrzej Bialecki
*
*/
public class CrawlDbReader extends Configured implements Closeable, Tool {
public static final Logger LOG = LoggerFactory.getLogger(CrawlDbReader.class);
private MapFile.Reader[] readers = null;
private void openReaders(String crawlDb, JobConf config)
throws IOException {
if (readers != null)
return;
FileSystem fs = FileSystem.get(config);
readers = MapFileOutputFormat.getReaders(fs, new Path(crawlDb,
CrawlDb.CURRENT_NAME), config);
}
private void closeReaders() {
if (readers == null)
return;
for (int i = 0; i < readers.length; i++) {
try {
readers[i].close();
} catch (Exception e) {
}
}
}
public static class CrawlDatumCsvOutputFormat extends
FileOutputFormat<Text, CrawlDatum> {
protected static class LineRecordWriter implements
RecordWriter<Text, CrawlDatum> {
private DataOutputStream out;
public LineRecordWriter(DataOutputStream out) {
this.out = out;
try {
out.writeBytes("Url,Status code,Status name,Fetch Time,Modified Time,Retries since fetch,Retry interval seconds,Retry interval days,Score,Signature,Metadata\n");
} catch (IOException e) {
}
}
public synchronized void write(Text key, CrawlDatum value)
throws IOException {
out.writeByte('"');
out.writeBytes(key.toString());
out.writeByte('"');
out.writeByte(',');
out.writeBytes(Integer.toString(value.getStatus()));
out.writeByte(',');
out.writeByte('"');
out.writeBytes(CrawlDatum.getStatusName(value.getStatus()));
out.writeByte('"');
out.writeByte(',');
out.writeBytes(new Date(value.getFetchTime()).toString());
out.writeByte(',');
out.writeBytes(new Date(value.getModifiedTime()).toString());
out.writeByte(',');
out.writeBytes(Integer.toString(value.getRetriesSinceFetch()));
out.writeByte(',');
out.writeBytes(Float.toString(value.getFetchInterval()));
out.writeByte(',');
out.writeBytes(Float.toString((value.getFetchInterval() / FetchSchedule.SECONDS_PER_DAY)));
out.writeByte(',');
out.writeBytes(Float.toString(value.getScore()));
out.writeByte(',');
out.writeByte('"');
out.writeBytes(value.getSignature() != null ? StringUtil
.toHexString(value.getSignature()) : "null");
out.writeByte('"');
out.writeByte(',');
out.writeByte('"');
if (value.getMetaData() != null) {
for (Entry<Writable, Writable> e : value.getMetaData().entrySet()) {
out.writeBytes(e.getKey().toString());
out.writeByte(':');
out.writeBytes(e.getValue().toString());
out.writeBytes("|||");
}
}
out.writeByte('"');
out.writeByte('\n');
}
public synchronized void close(Reporter reporter) throws IOException {
out.close();
}
}
public RecordWriter<Text, CrawlDatum> getRecordWriter(FileSystem fs,
JobConf job, String name, Progressable progress) throws IOException {
Path dir = FileOutputFormat.getOutputPath(job);
DataOutputStream fileOut = fs.create(new Path(dir, name), progress);
return new LineRecordWriter(fileOut);
}
}
public static class CrawlDbStatMapper implements
Mapper<Text, CrawlDatum, Text, LongWritable> {
LongWritable COUNT_1 = new LongWritable(1);
private boolean sort = false;
public void configure(JobConf job) {
sort = job.getBoolean("db.reader.stats.sort", false);
}
public void close() {
}
public void map(Text key, CrawlDatum value,
OutputCollector<Text, LongWritable> output, Reporter reporter)
throws IOException {
output.collect(new Text("T"), COUNT_1);
output.collect(new Text("status " + value.getStatus()), COUNT_1);
output
.collect(new Text("retry " + value.getRetriesSinceFetch()), COUNT_1);
output.collect(new Text("s"), new LongWritable(
(long) (value.getScore() * 1000.0)));
if (sort) {
URL u = new URL(key.toString());
String host = u.getHost();
output.collect(new Text("status " + value.getStatus() + " " + host),
COUNT_1);
}
}
}
public static class CrawlDbStatCombiner implements
Reducer<Text, LongWritable, Text, LongWritable> {
LongWritable val = new LongWritable();
public CrawlDbStatCombiner() {
}
public void configure(JobConf job) {
}
public void close() {
}
public void reduce(Text key, Iterator<LongWritable> values,
OutputCollector<Text, LongWritable> output, Reporter reporter)
throws IOException {
val.set(0L);
String k = key.toString();
if (!k.equals("s")) {
while (values.hasNext()) {
LongWritable cnt = values.next();
val.set(val.get() + cnt.get());
}
output.collect(key, val);
} else {
long total = 0;
long min = Long.MAX_VALUE;
long max = Long.MIN_VALUE;
while (values.hasNext()) {
LongWritable cnt = values.next();
if (cnt.get() < min)
min = cnt.get();
if (cnt.get() > max)
max = cnt.get();
total += cnt.get();
}
output.collect(new Text("scn"), new LongWritable(min));
output.collect(new Text("scx"), new LongWritable(max));
output.collect(new Text("sct"), new LongWritable(total));
}
}
}
public static class CrawlDbStatReducer implements
Reducer<Text, LongWritable, Text, LongWritable> {
public void configure(JobConf job) {
}
public void close() {
}
public void reduce(Text key, Iterator<LongWritable> values,
OutputCollector<Text, LongWritable> output, Reporter reporter)
throws IOException {
String k = key.toString();
if (k.equals("T")) {
// sum all values for this key
long sum = 0;
while (values.hasNext()) {
sum += values.next().get();
}
// output sum
output.collect(key, new LongWritable(sum));
} else if (k.startsWith("status") || k.startsWith("retry")) {
LongWritable cnt = new LongWritable();
while (values.hasNext()) {
LongWritable val = values.next();
cnt.set(cnt.get() + val.get());
}
output.collect(key, cnt);
} else if (k.equals("scx")) {
LongWritable cnt = new LongWritable(Long.MIN_VALUE);
while (values.hasNext()) {
LongWritable val = values.next();
if (cnt.get() < val.get())
cnt.set(val.get());
}
output.collect(key, cnt);
} else if (k.equals("scn")) {
LongWritable cnt = new LongWritable(Long.MAX_VALUE);
while (values.hasNext()) {
LongWritable val = values.next();
if (cnt.get() > val.get())
cnt.set(val.get());
}
output.collect(key, cnt);
} else if (k.equals("sct")) {
LongWritable cnt = new LongWritable();
while (values.hasNext()) {
LongWritable val = values.next();
cnt.set(cnt.get() + val.get());
}
output.collect(key, cnt);
}
}
}
public static class CrawlDbTopNMapper implements
Mapper<Text, CrawlDatum, FloatWritable, Text> {
private static final FloatWritable fw = new FloatWritable();
private float min = 0.0f;
public void configure(JobConf job) {
min = job.getFloat("db.reader.topn.min", 0.0f);
}
public void close() {
}
public void map(Text key, CrawlDatum value,
OutputCollector<FloatWritable, Text> output, Reporter reporter)
throws IOException {
if (value.getScore() < min)
return; // don't collect low-scoring records
fw.set(-value.getScore()); // reverse sorting order
output.collect(fw, key); // invert mapping: score -> url
}
}
public static class CrawlDbTopNReducer implements
Reducer<FloatWritable, Text, FloatWritable, Text> {
private long topN;
private long count = 0L;
public void reduce(FloatWritable key, Iterator<Text> values,
OutputCollector<FloatWritable, Text> output, Reporter reporter)
throws IOException {
while (values.hasNext() && count < topN) {
key.set(-key.get());
output.collect(key, values.next());
count++;
}
}
public void configure(JobConf job) {
topN = job.getLong("db.reader.topn", 100) / job.getNumReduceTasks();
}
public void close() {
}
}
public void close() {
closeReaders();
}
private TreeMap<String, LongWritable> processStatJobHelper(String crawlDb, Configuration config, boolean sort) throws IOException{
Path tmpFolder = new Path(crawlDb, "stat_tmp" + System.currentTimeMillis());
JobConf job = new NutchJob(config);
job.setJobName("stats " + crawlDb);
job.setBoolean("db.reader.stats.sort", sort);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbStatMapper.class);
job.setCombinerClass(CrawlDbStatCombiner.class);
job.setReducerClass(CrawlDbStatReducer.class);
FileOutputFormat.setOutputPath(job, tmpFolder);
job.setOutputFormat(SequenceFileOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
// https://issues.apache.org/jira/browse/NUTCH-1029
job.setBoolean("mapreduce.fileoutputcommitter.marksuccessfuljobs", false);
JobClient.runJob(job);
// reading the result
FileSystem fileSystem = FileSystem.get(config);
SequenceFile.Reader[] readers = SequenceFileOutputFormat.getReaders(config,
tmpFolder);
Text key = new Text();
LongWritable value = new LongWritable();
TreeMap<String, LongWritable> stats = new TreeMap<String, LongWritable>();
for (int i = 0; i < readers.length; i++) {
SequenceFile.Reader reader = readers[i];
while (reader.next(key, value)) {
String k = key.toString();
LongWritable val = stats.get(k);
if (val == null) {
val = new LongWritable();
if (k.equals("scx"))
val.set(Long.MIN_VALUE);
if (k.equals("scn"))
val.set(Long.MAX_VALUE);
stats.put(k, val);
}
if (k.equals("scx")) {
if (val.get() < value.get())
val.set(value.get());
} else if (k.equals("scn")) {
if (val.get() > value.get())
val.set(value.get());
} else {
val.set(val.get() + value.get());
}
}
reader.close();
}
// removing the tmp folder
fileSystem.delete(tmpFolder, true);
return stats;
}
public void processStatJob(String crawlDb, Configuration config, boolean sort)
throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb statistics start: " + crawlDb);
}
TreeMap<String, LongWritable> stats = processStatJobHelper(crawlDb, config, sort);
if (LOG.isInfoEnabled()) {
LOG.info("Statistics for CrawlDb: " + crawlDb);
LongWritable totalCnt = stats.get("T");
stats.remove("T");
LOG.info("TOTAL urls:\t" + totalCnt.get());
for (Map.Entry<String, LongWritable> entry : stats.entrySet()) {
String k = entry.getKey();
LongWritable val = entry.getValue();
if (k.equals("scn")) {
LOG.info("min score:\t" + (val.get() / 1000.0f));
} else if (k.equals("scx")) {
LOG.info("max score:\t" + (val.get() / 1000.0f));
} else if (k.equals("sct")) {
LOG.info("avg score:\t"
+ (float) ((((double) val.get()) / totalCnt.get()) / 1000.0));
} else if (k.startsWith("status")) {
String[] st = k.split(" ");
int code = Integer.parseInt(st[1]);
if (st.length > 2)
LOG.info(" " + st[2] + " :\t" + val);
else
LOG.info(st[0] + " " + code + " ("
+ CrawlDatum.getStatusName((byte) code) + "):\t" + val);
} else
LOG.info(k + ":\t" + val);
}
}
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb statistics: done");
}
}
public CrawlDatum get(String crawlDb, String url, JobConf config)
throws IOException {
Text key = new Text(url);
CrawlDatum val = new CrawlDatum();
openReaders(crawlDb, config);
CrawlDatum res = (CrawlDatum) MapFileOutputFormat.getEntry(readers,
new HashPartitioner<Text, CrawlDatum>(), key, val);
return res;
}
public void readUrl(String crawlDb, String url, JobConf config)
throws IOException {
CrawlDatum res = get(crawlDb, url, config);
System.out.println("URL: " + url);
if (res != null) {
System.out.println(res);
} else {
System.out.println("not found");
}
}
public void processDumpJob(String crawlDb, String output,
JobConf config, String format, String regex, String status,
Integer retry) throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb dump: starting");
LOG.info("CrawlDb db: " + crawlDb);
}
Path outFolder = new Path(output);
JobConf job = new NutchJob(config);
job.setJobName("dump " + crawlDb);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
job.setInputFormat(SequenceFileInputFormat.class);
FileOutputFormat.setOutputPath(job, outFolder);
if (format.equals("csv")) {
job.setOutputFormat(CrawlDatumCsvOutputFormat.class);
} else if (format.equals("crawldb")) {
job.setOutputFormat(MapFileOutputFormat.class);
} else {
job.setOutputFormat(TextOutputFormat.class);
}
if (status != null)
job.set("status", status);
if (regex != null)
job.set("regex", regex);
if (retry != null)
job.setInt("retry", retry);
job.setMapperClass(CrawlDbDumpMapper.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
JobClient.runJob(job);
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb dump: done");
}
}
public static class CrawlDbDumpMapper implements
Mapper<Text, CrawlDatum, Text, CrawlDatum> {
Pattern pattern = null;
Matcher matcher = null;
String status = null;
Integer retry = null;
public void configure(JobConf job) {
if (job.get("regex", null) != null) {
pattern = Pattern.compile(job.get("regex"));
}
status = job.get("status", null);
retry = job.getInt("retry", -1);
}
public void close() {
}
public void map(Text key, CrawlDatum value,
OutputCollector<Text, CrawlDatum> output, Reporter reporter)
throws IOException {
// check retry
if (retry != -1) {
if (value.getRetriesSinceFetch() < retry) {
return;
}
}
// check status
if (status != null
&& !status.equalsIgnoreCase(CrawlDatum.getStatusName(value
.getStatus())))
return;
// check regex
if (pattern != null) {
matcher = pattern.matcher(key.toString());
if (!matcher.matches()) {
return;
}
}
output.collect(key, value);
}
}
public void processTopNJob(String crawlDb, long topN, float min,
String output, JobConf config) throws IOException {
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: starting (topN=" + topN + ", min=" + min + ")");
LOG.info("CrawlDb db: " + crawlDb);
}
Path outFolder = new Path(output);
Path tempDir = new Path(config.get("mapred.temp.dir", ".")
+ "/readdb-topN-temp-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
JobConf job = new NutchJob(config);
job.setJobName("topN prepare " + crawlDb);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(CrawlDbTopNMapper.class);
job.setReducerClass(IdentityReducer.class);
FileOutputFormat.setOutputPath(job, tempDir);
job.setOutputFormat(SequenceFileOutputFormat.class);
job.setOutputKeyClass(FloatWritable.class);
job.setOutputValueClass(Text.class);
job.setFloat("db.reader.topn.min", min);
JobClient.runJob(job);
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: collecting topN scores.");
}
job = new NutchJob(config);
job.setJobName("topN collect " + crawlDb);
job.setLong("db.reader.topn", topN);
FileInputFormat.addInputPath(job, tempDir);
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(IdentityMapper.class);
job.setReducerClass(CrawlDbTopNReducer.class);
FileOutputFormat.setOutputPath(job, outFolder);
job.setOutputFormat(TextOutputFormat.class);
job.setOutputKeyClass(FloatWritable.class);
job.setOutputValueClass(Text.class);
job.setNumReduceTasks(1); // create a single file.
JobClient.runJob(job);
FileSystem fs = FileSystem.get(config);
fs.delete(tempDir, true);
if (LOG.isInfoEnabled()) {
LOG.info("CrawlDb topN: done");
}
}
public int run(String[] args) throws IOException {
@SuppressWarnings("resource")
CrawlDbReader dbr = new CrawlDbReader();
if (args.length < 2) {
System.err
.println("Usage: CrawlDbReader <crawldb> (-stats | -dump <out_dir> | -topN <nnnn> <out_dir> [<min>] | -url <url>)");
System.err
.println("\t<crawldb>\tdirectory name where crawldb is located");
System.err
.println("\t-stats [-sort] \tprint overall statistics to System.out");
System.err.println("\t\t[-sort]\tlist status sorted by host");
System.err
.println("\t-dump <out_dir> [-format normal|csv|crawldb]\tdump the whole db to a text file in <out_dir>");
System.err.println("\t\t[-format csv]\tdump in Csv format");
System.err
.println("\t\t[-format normal]\tdump in standard format (default option)");
System.err.println("\t\t[-format crawldb]\tdump as CrawlDB");
System.err.println("\t\t[-regex <expr>]\tfilter records with expression");
System.err.println("\t\t[-retry <num>]\tminimum retry count");
System.err
.println("\t\t[-status <status>]\tfilter records by CrawlDatum status");
System.err
.println("\t-url <url>\tprint information on <url> to System.out");
System.err
.println("\t-topN <nnnn> <out_dir> [<min>]\tdump top <nnnn> urls sorted by score to <out_dir>");
System.err
.println("\t\t[<min>]\tskip records with scores below this value.");
System.err.println("\t\t\tThis can significantly improve performance.");
return -1;
}
String param = null;
String crawlDb = args[0];
JobConf job = new NutchJob(getConf());
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-stats")) {
boolean toSort = false;
if (i < args.length - 1 && "-sort".equals(args[i + 1])) {
toSort = true;
i++;
}
dbr.processStatJob(crawlDb, job, toSort);
} else if (args[i].equals("-dump")) {
param = args[++i];
String format = "normal";
String regex = null;
Integer retry = null;
String status = null;
for (int j = i + 1; j < args.length; j++) {
if (args[j].equals("-format")) {
format = args[++j];
i = i + 2;
}
if (args[j].equals("-regex")) {
regex = args[++j];
i = i + 2;
}
if (args[j].equals("-retry")) {
retry = Integer.parseInt(args[++j]);
i = i + 2;
}
if (args[j].equals("-status")) {
status = args[++j];
i = i + 2;
}
}
dbr.processDumpJob(crawlDb, param, job, format, regex, status, retry);
} else if (args[i].equals("-url")) {
param = args[++i];
dbr.readUrl(crawlDb, param, job);
} else if (args[i].equals("-topN")) {
param = args[++i];
long topN = Long.parseLong(param);
param = args[++i];
float min = 0.0f;
if (i < args.length - 1) {
min = Float.parseFloat(args[++i]);
}
dbr.processTopNJob(crawlDb, topN, min, param, job);
} else {
System.err.println("\nError: wrong argument " + args[i]);
return -1;
}
}
return 0;
}
public static void main(String[] args) throws Exception {
int result = ToolRunner.run(NutchConfiguration.create(),
new CrawlDbReader(), args);
System.exit(result);
}
public Object query(Map<String, String> args, Configuration conf, String type, String crawlId) throws Exception {
Map<String, Object> results = new HashMap<String, Object>();
String crawlDb = crawlId + "/crawldb";
if(type.equalsIgnoreCase("stats")){
boolean sort = false;
if(args.containsKey("sort")){
if(args.get("sort").equalsIgnoreCase("true"))
sort = true;
}
TreeMap<String , LongWritable> stats = processStatJobHelper(crawlDb, NutchConfiguration.create(), sort);
LongWritable totalCnt = stats.get("T");
stats.remove("T");
results.put("totalUrls", String.valueOf(totalCnt.get()));
Map<String, Object> statusMap = new HashMap<String, Object>();
for (Map.Entry<String, LongWritable> entry : stats.entrySet()) {
String k = entry.getKey();
LongWritable val = entry.getValue();
if (k.equals("scn")) {
results.put("minScore", String.valueOf((val.get() / 1000.0f)));
} else if (k.equals("scx")) {
results.put("maxScore", String.valueOf((val.get() / 1000.0f)));
} else if (k.equals("sct")) {
results.put("avgScore", String.valueOf((float) ((((double) val.get()) / totalCnt.get()) / 1000.0)));
} else if (k.startsWith("status")) {
String[] st = k.split(" ");
int code = Integer.parseInt(st[1]);
if (st.length > 2){
Map<String, Object> individualStatusInfo = (Map<String, Object>) statusMap.get(String.valueOf(code));
Map<String, String> hostValues;
if(individualStatusInfo.containsKey("hostValues")){
hostValues= (Map<String, String>) individualStatusInfo.get("hostValues");
}
else{
hostValues = new HashMap<String, String>();
individualStatusInfo.put("hostValues", hostValues);
}
hostValues.put(st[2], String.valueOf(val));
}
else{
Map<String, Object> individualStatusInfo = new HashMap<String, Object>();
individualStatusInfo.put("statusValue", CrawlDatum.getStatusName((byte) code));
individualStatusInfo.put("count", String.valueOf(val));
statusMap.put(String.valueOf(code), individualStatusInfo);
}
} else
results.put(k, String.valueOf(val));
}
results.put("status", statusMap);
return results;
}
if(type.equalsIgnoreCase("dump")){
String output = args.get("out_dir");
String format = "normal";
String regex = null;
Integer retry = null;
String status = null;
if (args.containsKey("format")) {
format = args.get("format");
}
if (args.containsKey("regex")) {
regex = args.get("regex");
}
if (args.containsKey("retry")) {
retry = Integer.parseInt(args.get("retry"));
}
if (args.containsKey("status")) {
status = args.get("status");
}
processDumpJob(crawlDb, output, new NutchJob(conf), format, regex, status, retry);
File dumpFile = new File(output+"/part-00000");
return dumpFile;
}
if (type.equalsIgnoreCase("topN")) {
String output = args.get("out_dir");
long topN = Long.parseLong(args.get("nnn"));
float min = 0.0f;
if(args.containsKey("min")){
min = Float.parseFloat(args.get("min"));
}
processTopNJob(crawlDb, topN, min, output, new NutchJob(conf));
File dumpFile = new File(output+"/part-00000");
return dumpFile;
}
if(type.equalsIgnoreCase("url")){
String url = args.get("url");
CrawlDatum res = get(crawlDb, url, new NutchJob(conf));
results.put("status", res.getStatus());
results.put("fetchTime", new Date(res.getFetchTime()));
results.put("modifiedTime", new Date(res.getModifiedTime()));
results.put("retriesSinceFetch", res.getRetriesSinceFetch());
results.put("retryInterval", res.getFetchInterval());
results.put("score", res.getScore());
results.put("signature", StringUtil.toHexString(res.getSignature()));
Map<String, String> metadata = new HashMap<String, String>();
if(res.getMetaData()!=null){
for (Entry<Writable, Writable> e : res.getMetaData().entrySet()) {
metadata.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
}
}
results.put("metadata", metadata);
return results;
}
return results;
}
}
| |
/*
* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Olessia Salmina
* @version $Revision: 1.7 $
*/
package org.apache.harmony.test.reliability.api.nio.charset;
import org.apache.harmony.test.reliability.share.Test;
import org.apache.harmony.test.reliability.api.nio.charset.auxiliary.*;
import java.util.SortedMap;
import java.nio.charset.Charset;
//import java.util.Random;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
/**
* Goal: find resource leaks or intermittent failures or Encoder/Decoder cache
* problems, connected with use of abstract methods
* java.nio.charset.Charset.newEncoder() and
* java.nio.charset.Charset.newDecoder().
*
* The test does:
* 1. Reads parameters, which are:
* param[0] - number of threads to be run in parallel
* param[1] - number of iterations with encoding and decoding in each thread.
*
* 2. Receives all charsets through availableCharsets().
*
* 3. Creates 3 strings of length 0xFFFF:
* string[0] = all chars are those for which isJavaIdentifierPart(ch) returns true,
* from 0 to 0xFFFF.
* string[1] = all chars in range 0..0xFFFF, including malformed.
* string[2] = all chars are those for which isJavaIdentifierPart(ch)
* returns true, randomly chosen.
*
* 4. For each charset and each string:
* - creates CharsetDecoder and CharsetEncoder objects via newEncoder(), newDecoder()
* - specifies CodingErrorAction.IGNORE for both CharsetEncoder and CharsetDecoder
* - encodes and decodes each string param[1] times and compare results after
* first iteration and after the last one, expecting they are the same
* - runs System.gc()
*/
public class EncDecTest extends Test {
public static int callSystemGC = 1;
public static int NUMBER_OF_ITERATIONS = 100;
public static int numThreads = 10;
public static int[] statuses;
public static final SortedMap allCharsets = Charset.availableCharsets();
public static void main(String[] args) {
System.exit(new EncDecTest().test(args));
}
public int test(String[] params) {
parseParams(params);
// Start 'numThreads' threads each encoding/decoding
Thread[] t = new Thread[numThreads];
statuses = new int[t.length];
for (int i = 0; i < t.length; i++) {
t[i] = new Thread(new Encoder_DecoderRunner(i, this));
t[i].start();
//log.add("Thread " + i + " started");
}
// Correctly wait for all threads to finish
for (int i = 0; i < t.length; i++) {
try {
t[i].join();
//log.add("Thread " + i + ": joined() ");
} catch (InterruptedException ie) {
return fail("InterruptedException while join() of thread #" + i);
}
}
// For each thread check whether operations/checks PASSed in the thread
for (int i = 0; i < statuses.length; ++i) {
if (statuses[i] != Status.PASS) {
return fail("thread #" + i + " returned not PASS status");
}
//log.add("Status of thread " + i + ": is PASS");
}
return pass("OK");
}
public void parseParams(String[] params) {
if (params.length >= 1) {
numThreads = Integer.parseInt(params[0]);
}
if (params.length >= 2) {
NUMBER_OF_ITERATIONS = Integer.parseInt(params[1]);
}
}
}
class Encoder_DecoderRunner implements Runnable {
public int id;
public EncDecTest base;
public Encoder_DecoderRunner(int id, EncDecTest base) {
this.id = id;
this.base = base;
}
public void run() {
Object[] names = base.allCharsets.keySet().toArray();
String[] strs_to_encode = new String[3];
strs_to_encode[0] = StringCreator.getValidString((char)0,(char)0xFFFF, StringCreator.START_TO_END);
strs_to_encode[1] = StringCreator.getInvalidString();
strs_to_encode[2] = StringCreator.getValidString((char)0,(char)0xFFFF, StringCreator.RANDOM);
base.statuses[id] = Status.PASS;
for (int i = 0; i < names.length; i++) {
Charset chset = (Charset) base.allCharsets.get(names[i]);
if(!chset.canEncode()) {
continue;
}
// base.log.add("Charset " + names[i]);
Thread.yield();
for (int j = 0; j < strs_to_encode.length; j++) {
CharsetEncoder ce = chset.newEncoder().reset();
CharsetDecoder de = chset.newDecoder().reset();
CharBuffer chars_to_encode = CharBuffer.wrap(strs_to_encode[j]
.subSequence(0, strs_to_encode[j].length()));
ByteBuffer encoded_bytes = null;
CharBuffer decoded_chars = null;
Thread.yield();
try {
//base.log.add("String was:"+chars_to_encode.toString());
ce.onMalformedInput(CodingErrorAction.IGNORE);
ce.onUnmappableCharacter(CodingErrorAction.IGNORE);
de.onMalformedInput(CodingErrorAction.IGNORE);
de.onUnmappableCharacter(CodingErrorAction.IGNORE);
encoded_bytes = ce.encode(chars_to_encode);
decoded_chars = de.decode(encoded_bytes);
} catch (Throwable t) {
// base.log.add(t);
}
// base.log.add("After encoding-decoding, 0 iteration: " +
// decoded_chars.toString());
String s = "";
if (decoded_chars == null) {
continue;
} else {
s = decoded_chars.toString();
}
// base.log.add("Thread " + id + ", Charset: " + names[i] +
// ", string length initial = " + s.length());
Thread.yield();
for (int k = 0; k < base.NUMBER_OF_ITERATIONS; ++k) {
try {
ce.reset();
de.reset();
ce.onMalformedInput(CodingErrorAction.IGNORE);
ce.onUnmappableCharacter(CodingErrorAction.IGNORE);
de.onMalformedInput(CodingErrorAction.IGNORE);
de.onUnmappableCharacter(CodingErrorAction.IGNORE);
encoded_bytes = ce.encode(decoded_chars);
decoded_chars = de.decode(encoded_bytes);
// base.log.add("After encoding-decoding, "+ k +"
// iteration: "+ decoded_chars.toString());
Thread.yield();
} catch (Throwable t) {
// base.log.add(t);
}
if (base.callSystemGC != 0) {
System.gc();
}
}
// base.log.add("Thread " + id + ", Charset: " + names[i] +
// ", string length last = " +
// decoded_chars.toString().length());
// for these Charsets it is known at the moment of test creation
// that they return different results after the first and
// further encoding/decodings
if ( !(names[i].equals("ISO-2022-JP")
|| names[i].equals("x-ISCII91")
|| names[i].equals("x-IBM1383")
|| names[i].equals("x-IBM948")
|| names[i].equals("x-IBM950")
|| names[i].equals("x-ISO-2022-CN-CNS")
|| ((String) names[i]).startsWith("x-iscii-"))) {
if (!s.equals(decoded_chars.toString())) {
base.statuses[id] = Status.FAIL;
base.log.add("Thread " + id
+ ", Charset: " + names[i]
+ " chars after first "
+ " encoding/decoding are not equal to chars after "
+ base.NUMBER_OF_ITERATIONS + " encoding/decoding");
/*next statement closed to find all bad charsets
return;
*/
}
}
} // for strings
} // for Charset names
}
}
| |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.usb;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.XmlResourceParser;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.Environment;
import android.os.Process;
import android.os.UserHandle;
import android.util.AtomicFile;
import android.util.Log;
import android.util.Slog;
import android.util.SparseBooleanArray;
import android.util.Xml;
import com.android.internal.content.PackageMonitor;
import com.android.internal.util.FastXmlSerializer;
import com.android.internal.util.XmlUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import libcore.io.IoUtils;
class UsbSettingsManager {
private static final String TAG = "UsbSettingsManager";
private static final boolean DEBUG = false;
/** Legacy settings file, before multi-user */
private static final File sSingleUserSettingsFile = new File(
"/data/system/usb_device_manager.xml");
private final UserHandle mUser;
private final AtomicFile mSettingsFile;
private final Context mContext;
private final Context mUserContext;
private final PackageManager mPackageManager;
// Temporary mapping USB device name to list of UIDs with permissions for the device
private final HashMap<String, SparseBooleanArray> mDevicePermissionMap =
new HashMap<String, SparseBooleanArray>();
// Temporary mapping UsbAccessory to list of UIDs with permissions for the accessory
private final HashMap<UsbAccessory, SparseBooleanArray> mAccessoryPermissionMap =
new HashMap<UsbAccessory, SparseBooleanArray>();
// Maps DeviceFilter to user preferred application package
private final HashMap<DeviceFilter, String> mDevicePreferenceMap =
new HashMap<DeviceFilter, String>();
// Maps AccessoryFilter to user preferred application package
private final HashMap<AccessoryFilter, String> mAccessoryPreferenceMap =
new HashMap<AccessoryFilter, String>();
private final Object mLock = new Object();
// This class is used to describe a USB device.
// When used in HashMaps all values must be specified,
// but wildcards can be used for any of the fields in
// the package meta-data.
private static class DeviceFilter {
// USB Vendor ID (or -1 for unspecified)
public final int mVendorId;
// USB Product ID (or -1 for unspecified)
public final int mProductId;
// USB device or interface class (or -1 for unspecified)
public final int mClass;
// USB device subclass (or -1 for unspecified)
public final int mSubclass;
// USB device protocol (or -1 for unspecified)
public final int mProtocol;
public DeviceFilter(int vid, int pid, int clasz, int subclass, int protocol) {
mVendorId = vid;
mProductId = pid;
mClass = clasz;
mSubclass = subclass;
mProtocol = protocol;
}
public DeviceFilter(UsbDevice device) {
mVendorId = device.getVendorId();
mProductId = device.getProductId();
mClass = device.getDeviceClass();
mSubclass = device.getDeviceSubclass();
mProtocol = device.getDeviceProtocol();
}
public static DeviceFilter read(XmlPullParser parser)
throws XmlPullParserException, IOException {
int vendorId = -1;
int productId = -1;
int deviceClass = -1;
int deviceSubclass = -1;
int deviceProtocol = -1;
int count = parser.getAttributeCount();
for (int i = 0; i < count; i++) {
String name = parser.getAttributeName(i);
// All attribute values are ints
int value = Integer.parseInt(parser.getAttributeValue(i));
if ("vendor-id".equals(name)) {
vendorId = value;
} else if ("product-id".equals(name)) {
productId = value;
} else if ("class".equals(name)) {
deviceClass = value;
} else if ("subclass".equals(name)) {
deviceSubclass = value;
} else if ("protocol".equals(name)) {
deviceProtocol = value;
}
}
return new DeviceFilter(vendorId, productId,
deviceClass, deviceSubclass, deviceProtocol);
}
public void write(XmlSerializer serializer) throws IOException {
serializer.startTag(null, "usb-device");
if (mVendorId != -1) {
serializer.attribute(null, "vendor-id", Integer.toString(mVendorId));
}
if (mProductId != -1) {
serializer.attribute(null, "product-id", Integer.toString(mProductId));
}
if (mClass != -1) {
serializer.attribute(null, "class", Integer.toString(mClass));
}
if (mSubclass != -1) {
serializer.attribute(null, "subclass", Integer.toString(mSubclass));
}
if (mProtocol != -1) {
serializer.attribute(null, "protocol", Integer.toString(mProtocol));
}
serializer.endTag(null, "usb-device");
}
private boolean matches(int clasz, int subclass, int protocol) {
return ((mClass == -1 || clasz == mClass) &&
(mSubclass == -1 || subclass == mSubclass) &&
(mProtocol == -1 || protocol == mProtocol));
}
public boolean matches(UsbDevice device) {
if (mVendorId != -1 && device.getVendorId() != mVendorId) return false;
if (mProductId != -1 && device.getProductId() != mProductId) return false;
// check device class/subclass/protocol
if (matches(device.getDeviceClass(), device.getDeviceSubclass(),
device.getDeviceProtocol())) return true;
// if device doesn't match, check the interfaces
int count = device.getInterfaceCount();
for (int i = 0; i < count; i++) {
UsbInterface intf = device.getInterface(i);
if (matches(intf.getInterfaceClass(), intf.getInterfaceSubclass(),
intf.getInterfaceProtocol())) return true;
}
return false;
}
public boolean matches(DeviceFilter f) {
if (mVendorId != -1 && f.mVendorId != mVendorId) return false;
if (mProductId != -1 && f.mProductId != mProductId) return false;
// check device class/subclass/protocol
return matches(f.mClass, f.mSubclass, f.mProtocol);
}
@Override
public boolean equals(Object obj) {
// can't compare if we have wildcard strings
if (mVendorId == -1 || mProductId == -1 ||
mClass == -1 || mSubclass == -1 || mProtocol == -1) {
return false;
}
if (obj instanceof DeviceFilter) {
DeviceFilter filter = (DeviceFilter)obj;
return (filter.mVendorId == mVendorId &&
filter.mProductId == mProductId &&
filter.mClass == mClass &&
filter.mSubclass == mSubclass &&
filter.mProtocol == mProtocol);
}
if (obj instanceof UsbDevice) {
UsbDevice device = (UsbDevice)obj;
return (device.getVendorId() == mVendorId &&
device.getProductId() == mProductId &&
device.getDeviceClass() == mClass &&
device.getDeviceSubclass() == mSubclass &&
device.getDeviceProtocol() == mProtocol);
}
return false;
}
@Override
public int hashCode() {
return (((mVendorId << 16) | mProductId) ^
((mClass << 16) | (mSubclass << 8) | mProtocol));
}
@Override
public String toString() {
return "DeviceFilter[mVendorId=" + mVendorId + ",mProductId=" + mProductId +
",mClass=" + mClass + ",mSubclass=" + mSubclass +
",mProtocol=" + mProtocol + "]";
}
}
// This class is used to describe a USB accessory.
// When used in HashMaps all values must be specified,
// but wildcards can be used for any of the fields in
// the package meta-data.
private static class AccessoryFilter {
// USB accessory manufacturer (or null for unspecified)
public final String mManufacturer;
// USB accessory model (or null for unspecified)
public final String mModel;
// USB accessory version (or null for unspecified)
public final String mVersion;
public AccessoryFilter(String manufacturer, String model, String version) {
mManufacturer = manufacturer;
mModel = model;
mVersion = version;
}
public AccessoryFilter(UsbAccessory accessory) {
mManufacturer = accessory.getManufacturer();
mModel = accessory.getModel();
mVersion = accessory.getVersion();
}
public static AccessoryFilter read(XmlPullParser parser)
throws XmlPullParserException, IOException {
String manufacturer = null;
String model = null;
String version = null;
int count = parser.getAttributeCount();
for (int i = 0; i < count; i++) {
String name = parser.getAttributeName(i);
String value = parser.getAttributeValue(i);
if ("manufacturer".equals(name)) {
manufacturer = value;
} else if ("model".equals(name)) {
model = value;
} else if ("version".equals(name)) {
version = value;
}
}
return new AccessoryFilter(manufacturer, model, version);
}
public void write(XmlSerializer serializer)throws IOException {
serializer.startTag(null, "usb-accessory");
if (mManufacturer != null) {
serializer.attribute(null, "manufacturer", mManufacturer);
}
if (mModel != null) {
serializer.attribute(null, "model", mModel);
}
if (mVersion != null) {
serializer.attribute(null, "version", mVersion);
}
serializer.endTag(null, "usb-accessory");
}
public boolean matches(UsbAccessory acc) {
if (mManufacturer != null && !acc.getManufacturer().equals(mManufacturer)) return false;
if (mModel != null && !acc.getModel().equals(mModel)) return false;
if (mVersion != null && !acc.getVersion().equals(mVersion)) return false;
return true;
}
public boolean matches(AccessoryFilter f) {
if (mManufacturer != null && !f.mManufacturer.equals(mManufacturer)) return false;
if (mModel != null && !f.mModel.equals(mModel)) return false;
if (mVersion != null && !f.mVersion.equals(mVersion)) return false;
return true;
}
@Override
public boolean equals(Object obj) {
// can't compare if we have wildcard strings
if (mManufacturer == null || mModel == null || mVersion == null) {
return false;
}
if (obj instanceof AccessoryFilter) {
AccessoryFilter filter = (AccessoryFilter)obj;
return (mManufacturer.equals(filter.mManufacturer) &&
mModel.equals(filter.mModel) &&
mVersion.equals(filter.mVersion));
}
if (obj instanceof UsbAccessory) {
UsbAccessory accessory = (UsbAccessory)obj;
return (mManufacturer.equals(accessory.getManufacturer()) &&
mModel.equals(accessory.getModel()) &&
mVersion.equals(accessory.getVersion()));
}
return false;
}
@Override
public int hashCode() {
return ((mManufacturer == null ? 0 : mManufacturer.hashCode()) ^
(mModel == null ? 0 : mModel.hashCode()) ^
(mVersion == null ? 0 : mVersion.hashCode()));
}
@Override
public String toString() {
return "AccessoryFilter[mManufacturer=\"" + mManufacturer +
"\", mModel=\"" + mModel +
"\", mVersion=\"" + mVersion + "\"]";
}
}
private class MyPackageMonitor extends PackageMonitor {
@Override
public void onPackageAdded(String packageName, int uid) {
handlePackageUpdate(packageName);
}
@Override
public boolean onPackageChanged(String packageName, int uid, String[] components) {
handlePackageUpdate(packageName);
return false;
}
@Override
public void onPackageRemoved(String packageName, int uid) {
clearDefaults(packageName);
}
}
MyPackageMonitor mPackageMonitor = new MyPackageMonitor();
public UsbSettingsManager(Context context, UserHandle user) {
if (DEBUG) Slog.v(TAG, "Creating settings for " + user);
try {
mUserContext = context.createPackageContextAsUser("android", 0, user);
} catch (NameNotFoundException e) {
throw new RuntimeException("Missing android package");
}
mContext = context;
mPackageManager = mUserContext.getPackageManager();
mUser = user;
mSettingsFile = new AtomicFile(new File(
Environment.getUserSystemDirectory(user.getIdentifier()),
"usb_device_manager.xml"));
synchronized (mLock) {
if (UserHandle.OWNER.equals(user)) {
upgradeSingleUserLocked();
}
readSettingsLocked();
}
mPackageMonitor.register(mUserContext, null, true);
}
private void readPreference(XmlPullParser parser)
throws XmlPullParserException, IOException {
String packageName = null;
int count = parser.getAttributeCount();
for (int i = 0; i < count; i++) {
if ("package".equals(parser.getAttributeName(i))) {
packageName = parser.getAttributeValue(i);
break;
}
}
XmlUtils.nextElement(parser);
if ("usb-device".equals(parser.getName())) {
DeviceFilter filter = DeviceFilter.read(parser);
mDevicePreferenceMap.put(filter, packageName);
} else if ("usb-accessory".equals(parser.getName())) {
AccessoryFilter filter = AccessoryFilter.read(parser);
mAccessoryPreferenceMap.put(filter, packageName);
}
XmlUtils.nextElement(parser);
}
/**
* Upgrade any single-user settings from {@link #sSingleUserSettingsFile}.
* Should only by called by owner.
*/
private void upgradeSingleUserLocked() {
if (sSingleUserSettingsFile.exists()) {
mDevicePreferenceMap.clear();
mAccessoryPreferenceMap.clear();
FileInputStream fis = null;
try {
fis = new FileInputStream(sSingleUserSettingsFile);
XmlPullParser parser = Xml.newPullParser();
parser.setInput(fis, null);
XmlUtils.nextElement(parser);
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
final String tagName = parser.getName();
if ("preference".equals(tagName)) {
readPreference(parser);
} else {
XmlUtils.nextElement(parser);
}
}
} catch (IOException e) {
Log.wtf(TAG, "Failed to read single-user settings", e);
} catch (XmlPullParserException e) {
Log.wtf(TAG, "Failed to read single-user settings", e);
} finally {
IoUtils.closeQuietly(fis);
}
writeSettingsLocked();
// Success or failure, we delete single-user file
sSingleUserSettingsFile.delete();
}
}
private void readSettingsLocked() {
if (DEBUG) Slog.v(TAG, "readSettingsLocked()");
mDevicePreferenceMap.clear();
mAccessoryPreferenceMap.clear();
FileInputStream stream = null;
try {
stream = mSettingsFile.openRead();
XmlPullParser parser = Xml.newPullParser();
parser.setInput(stream, null);
XmlUtils.nextElement(parser);
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
if ("preference".equals(tagName)) {
readPreference(parser);
} else {
XmlUtils.nextElement(parser);
}
}
} catch (FileNotFoundException e) {
if (DEBUG) Slog.d(TAG, "settings file not found");
} catch (Exception e) {
Slog.e(TAG, "error reading settings file, deleting to start fresh", e);
mSettingsFile.delete();
} finally {
IoUtils.closeQuietly(stream);
}
}
private void writeSettingsLocked() {
if (DEBUG) Slog.v(TAG, "writeSettingsLocked()");
FileOutputStream fos = null;
try {
fos = mSettingsFile.startWrite();
FastXmlSerializer serializer = new FastXmlSerializer();
serializer.setOutput(fos, "utf-8");
serializer.startDocument(null, true);
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "settings");
for (DeviceFilter filter : mDevicePreferenceMap.keySet()) {
serializer.startTag(null, "preference");
serializer.attribute(null, "package", mDevicePreferenceMap.get(filter));
filter.write(serializer);
serializer.endTag(null, "preference");
}
for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
serializer.startTag(null, "preference");
serializer.attribute(null, "package", mAccessoryPreferenceMap.get(filter));
filter.write(serializer);
serializer.endTag(null, "preference");
}
serializer.endTag(null, "settings");
serializer.endDocument();
mSettingsFile.finishWrite(fos);
} catch (IOException e) {
Slog.e(TAG, "Failed to write settings", e);
if (fos != null) {
mSettingsFile.failWrite(fos);
}
}
}
// Checks to see if a package matches a device or accessory.
// Only one of device and accessory should be non-null.
private boolean packageMatchesLocked(ResolveInfo info, String metaDataName,
UsbDevice device, UsbAccessory accessory) {
ActivityInfo ai = info.activityInfo;
XmlResourceParser parser = null;
try {
parser = ai.loadXmlMetaData(mPackageManager, metaDataName);
if (parser == null) {
Slog.w(TAG, "no meta-data for " + info);
return false;
}
XmlUtils.nextElement(parser);
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
if (device != null && "usb-device".equals(tagName)) {
DeviceFilter filter = DeviceFilter.read(parser);
if (filter.matches(device)) {
return true;
}
}
else if (accessory != null && "usb-accessory".equals(tagName)) {
AccessoryFilter filter = AccessoryFilter.read(parser);
if (filter.matches(accessory)) {
return true;
}
}
XmlUtils.nextElement(parser);
}
} catch (Exception e) {
Slog.w(TAG, "Unable to load component info " + info.toString(), e);
} finally {
if (parser != null) parser.close();
}
return false;
}
private final ArrayList<ResolveInfo> getDeviceMatchesLocked(UsbDevice device, Intent intent) {
ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(intent,
PackageManager.GET_META_DATA);
int count = resolveInfos.size();
for (int i = 0; i < count; i++) {
ResolveInfo resolveInfo = resolveInfos.get(i);
if (packageMatchesLocked(resolveInfo, intent.getAction(), device, null)) {
matches.add(resolveInfo);
}
}
return matches;
}
private final ArrayList<ResolveInfo> getAccessoryMatchesLocked(
UsbAccessory accessory, Intent intent) {
ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
List<ResolveInfo> resolveInfos = mPackageManager.queryIntentActivities(intent,
PackageManager.GET_META_DATA);
int count = resolveInfos.size();
for (int i = 0; i < count; i++) {
ResolveInfo resolveInfo = resolveInfos.get(i);
if (packageMatchesLocked(resolveInfo, intent.getAction(), null, accessory)) {
matches.add(resolveInfo);
}
}
return matches;
}
public void deviceAttached(UsbDevice device) {
Intent intent = new Intent(UsbManager.ACTION_USB_DEVICE_ATTACHED);
intent.putExtra(UsbManager.EXTRA_DEVICE, device);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ArrayList<ResolveInfo> matches;
String defaultPackage;
synchronized (mLock) {
matches = getDeviceMatchesLocked(device, intent);
// Launch our default activity directly, if we have one.
// Otherwise we will start the UsbResolverActivity to allow the user to choose.
defaultPackage = mDevicePreferenceMap.get(new DeviceFilter(device));
}
// Send broadcast to running activity with registered intent
mUserContext.sendBroadcast(intent);
// Start activity with registered intent
resolveActivity(intent, matches, defaultPackage, device, null);
}
public void deviceDetached(UsbDevice device) {
// clear temporary permissions for the device
mDevicePermissionMap.remove(device.getDeviceName());
Intent intent = new Intent(UsbManager.ACTION_USB_DEVICE_DETACHED);
intent.putExtra(UsbManager.EXTRA_DEVICE, device);
if (DEBUG) Slog.d(TAG, "usbDeviceRemoved, sending " + intent);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
}
public void accessoryAttached(UsbAccessory accessory) {
Intent intent = new Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ArrayList<ResolveInfo> matches;
String defaultPackage;
synchronized (mLock) {
matches = getAccessoryMatchesLocked(accessory, intent);
// Launch our default activity directly, if we have one.
// Otherwise we will start the UsbResolverActivity to allow the user to choose.
defaultPackage = mAccessoryPreferenceMap.get(new AccessoryFilter(accessory));
}
resolveActivity(intent, matches, defaultPackage, null, accessory);
}
public void accessoryDetached(UsbAccessory accessory) {
// clear temporary permissions for the accessory
mAccessoryPermissionMap.remove(accessory);
Intent intent = new Intent(
UsbManager.ACTION_USB_ACCESSORY_DETACHED);
intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
}
private void resolveActivity(Intent intent, ArrayList<ResolveInfo> matches,
String defaultPackage, UsbDevice device, UsbAccessory accessory) {
int count = matches.size();
// don't show the resolver activity if there are no choices available
if (count == 0) {
if (accessory != null) {
String uri = accessory.getUri();
if (uri != null && uri.length() > 0) {
// display URI to user
// start UsbResolverActivity so user can choose an activity
Intent dialogIntent = new Intent();
dialogIntent.setClassName("com.android.systemui",
"com.android.systemui.usb.UsbAccessoryUriActivity");
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
dialogIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
dialogIntent.putExtra("uri", uri);
try {
mUserContext.startActivityAsUser(dialogIntent, mUser);
} catch (ActivityNotFoundException e) {
Slog.e(TAG, "unable to start UsbAccessoryUriActivity");
}
}
}
// do nothing
return;
}
ResolveInfo defaultRI = null;
if (count == 1 && defaultPackage == null) {
// Check to see if our single choice is on the system partition.
// If so, treat it as our default without calling UsbResolverActivity
ResolveInfo rInfo = matches.get(0);
if (rInfo.activityInfo != null &&
rInfo.activityInfo.applicationInfo != null &&
(rInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
defaultRI = rInfo;
}
}
if (defaultRI == null && defaultPackage != null) {
// look for default activity
for (int i = 0; i < count; i++) {
ResolveInfo rInfo = matches.get(i);
if (rInfo.activityInfo != null &&
defaultPackage.equals(rInfo.activityInfo.packageName)) {
defaultRI = rInfo;
break;
}
}
}
if (defaultRI != null) {
// grant permission for default activity
if (device != null) {
grantDevicePermission(device, defaultRI.activityInfo.applicationInfo.uid);
} else if (accessory != null) {
grantAccessoryPermission(accessory, defaultRI.activityInfo.applicationInfo.uid);
}
// start default activity directly
try {
intent.setComponent(
new ComponentName(defaultRI.activityInfo.packageName,
defaultRI.activityInfo.name));
mUserContext.startActivityAsUser(intent, mUser);
} catch (ActivityNotFoundException e) {
Slog.e(TAG, "startActivity failed", e);
}
} else {
Intent resolverIntent = new Intent();
resolverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (count == 1) {
// start UsbConfirmActivity if there is only one choice
resolverIntent.setClassName("com.android.systemui",
"com.android.systemui.usb.UsbConfirmActivity");
resolverIntent.putExtra("rinfo", matches.get(0));
if (device != null) {
resolverIntent.putExtra(UsbManager.EXTRA_DEVICE, device);
} else {
resolverIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
}
} else {
// start UsbResolverActivity so user can choose an activity
resolverIntent.setClassName("com.android.systemui",
"com.android.systemui.usb.UsbResolverActivity");
resolverIntent.putParcelableArrayListExtra("rlist", matches);
resolverIntent.putExtra(Intent.EXTRA_INTENT, intent);
}
try {
mUserContext.startActivityAsUser(resolverIntent, mUser);
} catch (ActivityNotFoundException e) {
Slog.e(TAG, "unable to start activity " + resolverIntent);
}
}
}
private boolean clearCompatibleMatchesLocked(String packageName, DeviceFilter filter) {
boolean changed = false;
for (DeviceFilter test : mDevicePreferenceMap.keySet()) {
if (filter.matches(test)) {
mDevicePreferenceMap.remove(test);
changed = true;
}
}
return changed;
}
private boolean clearCompatibleMatchesLocked(String packageName, AccessoryFilter filter) {
boolean changed = false;
for (AccessoryFilter test : mAccessoryPreferenceMap.keySet()) {
if (filter.matches(test)) {
mAccessoryPreferenceMap.remove(test);
changed = true;
}
}
return changed;
}
private boolean handlePackageUpdateLocked(String packageName, ActivityInfo aInfo,
String metaDataName) {
XmlResourceParser parser = null;
boolean changed = false;
try {
parser = aInfo.loadXmlMetaData(mPackageManager, metaDataName);
if (parser == null) return false;
XmlUtils.nextElement(parser);
while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
String tagName = parser.getName();
if ("usb-device".equals(tagName)) {
DeviceFilter filter = DeviceFilter.read(parser);
if (clearCompatibleMatchesLocked(packageName, filter)) {
changed = true;
}
}
else if ("usb-accessory".equals(tagName)) {
AccessoryFilter filter = AccessoryFilter.read(parser);
if (clearCompatibleMatchesLocked(packageName, filter)) {
changed = true;
}
}
XmlUtils.nextElement(parser);
}
} catch (Exception e) {
Slog.w(TAG, "Unable to load component info " + aInfo.toString(), e);
} finally {
if (parser != null) parser.close();
}
return changed;
}
// Check to see if the package supports any USB devices or accessories.
// If so, clear any non-matching preferences for matching devices/accessories.
private void handlePackageUpdate(String packageName) {
synchronized (mLock) {
PackageInfo info;
boolean changed = false;
try {
info = mPackageManager.getPackageInfo(packageName,
PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
Slog.e(TAG, "handlePackageUpdate could not find package " + packageName, e);
return;
}
ActivityInfo[] activities = info.activities;
if (activities == null) return;
for (int i = 0; i < activities.length; i++) {
// check for meta-data, both for devices and accessories
if (handlePackageUpdateLocked(packageName, activities[i],
UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
changed = true;
}
if (handlePackageUpdateLocked(packageName, activities[i],
UsbManager.ACTION_USB_ACCESSORY_ATTACHED)) {
changed = true;
}
}
if (changed) {
writeSettingsLocked();
}
}
}
public boolean hasPermission(UsbDevice device) {
synchronized (mLock) {
int uid = Binder.getCallingUid();
if (uid == Process.SYSTEM_UID) {
return true;
}
SparseBooleanArray uidList = mDevicePermissionMap.get(device.getDeviceName());
if (uidList == null) {
return false;
}
return uidList.get(uid);
}
}
public boolean hasPermission(UsbAccessory accessory) {
synchronized (mLock) {
int uid = Binder.getCallingUid();
if (uid == Process.SYSTEM_UID) {
return true;
}
SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
if (uidList == null) {
return false;
}
return uidList.get(uid);
}
}
public void checkPermission(UsbDevice device) {
if (!hasPermission(device)) {
throw new SecurityException("User has not given permission to device " + device);
}
}
public void checkPermission(UsbAccessory accessory) {
if (!hasPermission(accessory)) {
throw new SecurityException("User has not given permission to accessory " + accessory);
}
}
private void requestPermissionDialog(Intent intent, String packageName, PendingIntent pi) {
final int uid = Binder.getCallingUid();
// compare uid with packageName to foil apps pretending to be someone else
try {
ApplicationInfo aInfo = mPackageManager.getApplicationInfo(packageName, 0);
if (aInfo.uid != uid) {
throw new IllegalArgumentException("package " + packageName +
" does not match caller's uid " + uid);
}
} catch (PackageManager.NameNotFoundException e) {
throw new IllegalArgumentException("package " + packageName + " not found");
}
long identity = Binder.clearCallingIdentity();
intent.setClassName("com.android.systemui",
"com.android.systemui.usb.UsbPermissionActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_INTENT, pi);
intent.putExtra("package", packageName);
intent.putExtra(Intent.EXTRA_UID, uid);
try {
mUserContext.startActivityAsUser(intent, mUser);
} catch (ActivityNotFoundException e) {
Slog.e(TAG, "unable to start UsbPermissionActivity");
} finally {
Binder.restoreCallingIdentity(identity);
}
}
public void requestPermission(UsbDevice device, String packageName, PendingIntent pi) {
Intent intent = new Intent();
// respond immediately if permission has already been granted
if (hasPermission(device)) {
intent.putExtra(UsbManager.EXTRA_DEVICE, device);
intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
try {
pi.send(mUserContext, 0, intent);
} catch (PendingIntent.CanceledException e) {
if (DEBUG) Slog.d(TAG, "requestPermission PendingIntent was cancelled");
}
return;
}
// start UsbPermissionActivity so user can choose an activity
intent.putExtra(UsbManager.EXTRA_DEVICE, device);
requestPermissionDialog(intent, packageName, pi);
}
public void requestPermission(UsbAccessory accessory, String packageName, PendingIntent pi) {
Intent intent = new Intent();
// respond immediately if permission has already been granted
if (hasPermission(accessory)) {
intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
intent.putExtra(UsbManager.EXTRA_PERMISSION_GRANTED, true);
try {
pi.send(mUserContext, 0, intent);
} catch (PendingIntent.CanceledException e) {
if (DEBUG) Slog.d(TAG, "requestPermission PendingIntent was cancelled");
}
return;
}
intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
requestPermissionDialog(intent, packageName, pi);
}
public void setDevicePackage(UsbDevice device, String packageName) {
DeviceFilter filter = new DeviceFilter(device);
boolean changed = false;
synchronized (mLock) {
if (packageName == null) {
changed = (mDevicePreferenceMap.remove(filter) != null);
} else {
changed = !packageName.equals(mDevicePreferenceMap.get(filter));
if (changed) {
mDevicePreferenceMap.put(filter, packageName);
}
}
if (changed) {
writeSettingsLocked();
}
}
}
public void setAccessoryPackage(UsbAccessory accessory, String packageName) {
AccessoryFilter filter = new AccessoryFilter(accessory);
boolean changed = false;
synchronized (mLock) {
if (packageName == null) {
changed = (mAccessoryPreferenceMap.remove(filter) != null);
} else {
changed = !packageName.equals(mAccessoryPreferenceMap.get(filter));
if (changed) {
mAccessoryPreferenceMap.put(filter, packageName);
}
}
if (changed) {
writeSettingsLocked();
}
}
}
public void grantDevicePermission(UsbDevice device, int uid) {
synchronized (mLock) {
String deviceName = device.getDeviceName();
SparseBooleanArray uidList = mDevicePermissionMap.get(deviceName);
if (uidList == null) {
uidList = new SparseBooleanArray(1);
mDevicePermissionMap.put(deviceName, uidList);
}
uidList.put(uid, true);
}
}
public void grantAccessoryPermission(UsbAccessory accessory, int uid) {
synchronized (mLock) {
SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
if (uidList == null) {
uidList = new SparseBooleanArray(1);
mAccessoryPermissionMap.put(accessory, uidList);
}
uidList.put(uid, true);
}
}
public boolean hasDefaults(String packageName) {
synchronized (mLock) {
if (mDevicePreferenceMap.values().contains(packageName)) return true;
if (mAccessoryPreferenceMap.values().contains(packageName)) return true;
return false;
}
}
public void clearDefaults(String packageName) {
synchronized (mLock) {
if (clearPackageDefaultsLocked(packageName)) {
writeSettingsLocked();
}
}
}
private boolean clearPackageDefaultsLocked(String packageName) {
boolean cleared = false;
synchronized (mLock) {
if (mDevicePreferenceMap.containsValue(packageName)) {
// make a copy of the key set to avoid ConcurrentModificationException
Object[] keys = mDevicePreferenceMap.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
Object key = keys[i];
if (packageName.equals(mDevicePreferenceMap.get(key))) {
mDevicePreferenceMap.remove(key);
cleared = true;
}
}
}
if (mAccessoryPreferenceMap.containsValue(packageName)) {
// make a copy of the key set to avoid ConcurrentModificationException
Object[] keys = mAccessoryPreferenceMap.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
Object key = keys[i];
if (packageName.equals(mAccessoryPreferenceMap.get(key))) {
mAccessoryPreferenceMap.remove(key);
cleared = true;
}
}
}
return cleared;
}
}
public void dump(FileDescriptor fd, PrintWriter pw) {
synchronized (mLock) {
pw.println(" Device permissions:");
for (String deviceName : mDevicePermissionMap.keySet()) {
pw.print(" " + deviceName + ": ");
SparseBooleanArray uidList = mDevicePermissionMap.get(deviceName);
int count = uidList.size();
for (int i = 0; i < count; i++) {
pw.print(Integer.toString(uidList.keyAt(i)) + " ");
}
pw.println("");
}
pw.println(" Accessory permissions:");
for (UsbAccessory accessory : mAccessoryPermissionMap.keySet()) {
pw.print(" " + accessory + ": ");
SparseBooleanArray uidList = mAccessoryPermissionMap.get(accessory);
int count = uidList.size();
for (int i = 0; i < count; i++) {
pw.print(Integer.toString(uidList.keyAt(i)) + " ");
}
pw.println("");
}
pw.println(" Device preferences:");
for (DeviceFilter filter : mDevicePreferenceMap.keySet()) {
pw.println(" " + filter + ": " + mDevicePreferenceMap.get(filter));
}
pw.println(" Accessory preferences:");
for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
pw.println(" " + filter + ": " + mAccessoryPreferenceMap.get(filter));
}
}
}
}
| |
/**
*
*/
package org.ngbw.sdk.conversion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ngbw.sdk.common.util.Resource;
import org.ngbw.sdk.common.util.ResourceNotFoundException;
import org.ngbw.sdk.common.util.StringUtils;
import org.ngbw.sdk.common.util.XMLHelper;
import org.ngbw.sdk.core.shared.IndexedDataRecord;
import org.ngbw.sdk.core.types.DataFormat;
import org.ngbw.sdk.core.types.RecordFieldType;
import org.ngbw.sdk.core.types.RecordType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* FlatfileParser parses individual records of a flat file dataset into a
* DataRecord. It can be used a generic parser for DataFormatReaders for flat
* file based DataFormats. The class is configured via an xml file. a default
* config file is located in the resources/conversion package. <br />
*
* @author hannes
*
*/
public class FlatfileParser {
private static Log log = LogFactory.getLog(FlatfileParser.class);
private static final String DEFAULT_SEPARATOR = "*";
private static final String DEFAULT_SEPARATOR_REGEX = "\\*";
private static Map<DataFormat, Set<RecordType>> recordTypeLookup = new HashMap<DataFormat, Set<RecordType>>();
private static Map<DataFormat, Map<RecordFieldType, Pattern>> patternLookup = new HashMap<DataFormat, Map<RecordFieldType, Pattern>>();
private static Map<DataFormat, Map<RecordFieldType, Boolean>> collectionLookup = new HashMap<DataFormat, Map<RecordFieldType, Boolean>>();
private static Map<DataFormat, Map<RecordFieldType, String>> dateFormatLookup = new HashMap<DataFormat, Map<RecordFieldType, String>>();
private static Map<DataFormat, Map<RecordFieldType, String>> separatorLookup = new HashMap<DataFormat, Map<RecordFieldType, String>>();
private Set<RecordFieldType> fields;
static {
try {
init(Resource.getResource("conversion/flatfile-parser.cfg.xml"));
} catch (ResourceNotFoundException e) {
throw new RuntimeException(e.toString(), e);
}
}
public FlatfileParser(Set<RecordFieldType> fields) {
if (fields == null)
throw new NullPointerException("fields is null!");
this.fields = fields;
if (log.isDebugEnabled()) {
for (RecordFieldType field : fields)
log.debug(field + " : " + field.dataType());
}
}
public static Map<DataFormat, Set<RecordType>> canParse() {
return recordTypeLookup;
}
public static Map<RecordFieldType, String> parseFields(DataFormat dataFormat, Set<RecordFieldType> fields, String record) {
if (fields == null)
throw new NullPointerException("fields is null!");
if (record == null)
throw new NullPointerException("record is null!");
FlatfileParser parser = new FlatfileParser(fields);
Map<RecordFieldType, StringBuffer> values = new HashMap<RecordFieldType, StringBuffer>();
BufferedReader reader = new BufferedReader(new StringReader(record));
try {
String line;
while ((line = reader.readLine()) != null) {
parser.processLine(dataFormat, fields, line, values);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Map<RecordFieldType, String> result = new HashMap<RecordFieldType, String>(values.size());
for (RecordFieldType field : fields) {
StringBuffer value = values.get(field);
if (value == null)
throw new NullPointerException("Value for RecordField." + field + " is null!");
result.put(field, value.toString());
}
return result;
}
public IndexedDataRecord parse(int index, RecordType recordType, DataFormat dataFormat, String data) throws ParseException {
if (dataFormat == null)
throw new NullPointerException("DataFormat is null!");
if (data == null || data.trim().length() == 0)
throw new NullPointerException("input data is null or empty!");
Map<RecordFieldType, StringBuffer> values = new HashMap<RecordFieldType, StringBuffer>();
BufferedReader reader = new BufferedReader(new StringReader(data));
try {
String line;
while ((line = reader.readLine()) != null) {
processLine(dataFormat, fields, line, values);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
IndexedDataRecord dataRecord = createDataRecord(index, dataFormat, recordType, values);
return dataRecord;
}
private IndexedDataRecord createDataRecord(int index, DataFormat dataFormat,
RecordType recordType, Map<RecordFieldType, StringBuffer> values) throws ParseException {
IndexedDataRecord dataRecord = new IndexedDataRecord(recordType, fields, index);
for (RecordFieldType recordField : values.keySet()) {
String value = values.get(recordField).toString();
if (isCollection(dataFormat, recordField)) {
String separator = getSeparator(dataFormat, recordField);
if (separator == null)
separator = DEFAULT_SEPARATOR_REGEX;
String[] elements = value.split(separator);
ArrayList<String> list = new ArrayList<String>();
for (String element : elements) {
element = element.trim();
if (list.contains(element) == false)
list.add(element);
}
value = StringUtils.join(list, ", ");
} else {
value = value.trim();
}
dataRecord.getField(recordField).setValue(value);
}
return dataRecord;
}
private void processLine(DataFormat dataFormat,
Set<RecordFieldType> recordFields, String line,
Map<RecordFieldType, StringBuffer> values) {
if (dataFormat == null)
throw new NullPointerException("dataFormat is null!");
if (recordFields == null)
throw new NullPointerException("recordFields is null!");
if (line == null)
throw new NullPointerException("line is null!");
if (values == null)
throw new NullPointerException("values is null!");
for (RecordFieldType recordField : recordFields) {
Pattern pattern = getPattern(dataFormat, recordField);
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
StringBuffer value = values.get(recordField);
if (value == null)
value = new StringBuffer();
String currentMatch = matcher.group(1);
if (currentMatch == null)
continue;
if (isCollection(dataFormat, recordField)) {
String separator = getSeparator(dataFormat, recordField);
if (separator == null && value.length() > 0)
value.append(DEFAULT_SEPARATOR + currentMatch);
else
value.append(currentMatch);
} else {
if (value.length() == 0 || value.toString().endsWith(" ")
|| value.toString().endsWith(",")
|| value.toString().endsWith("-"))
value.append(currentMatch);
else
value.append(" " + currentMatch);
}
values.put(recordField, value);
}
}
}
private boolean isCollection(DataFormat dataFormat, RecordFieldType recordField) {
if (dataFormat == null)
throw new NullPointerException("DataFormat is null!");
if (recordField == null)
throw new NullPointerException("RecordField is null!");
if (collectionLookup.containsKey(dataFormat) == false)
throw new NullPointerException(
"No collection lookup map registered for " + dataFormat);
if (collectionLookup.get(dataFormat).containsKey(recordField) == false)
throw new NullPointerException(
"No collection lookup registered for " + recordField);
return collectionLookup.get(dataFormat).get(recordField);
}
private Pattern getPattern(DataFormat dataFormat, RecordFieldType recordField) {
if (dataFormat == null)
throw new NullPointerException("DataFormat is null!");
if (recordField == null)
throw new NullPointerException("RecordField is null!");
if (patternLookup.containsKey(dataFormat) == false)
throw new NullPointerException(
"No pattern lookup map registered for " + dataFormat);
if (patternLookup.get(dataFormat).containsKey(recordField) == false)
throw new NullPointerException("No pattern registered for "
+ recordField);
return patternLookup.get(dataFormat).get(recordField);
}
/*
private String getDateFormat(DataFormat dataFormat, RecordFieldType recordField) {
if (dataFormat == null)
throw new NullPointerException("DataFormat is null!");
if (recordField == null)
throw new NullPointerException("RecordField is null!");
if (dateFormatLookup.containsKey(dataFormat) == false)
throw new NullPointerException(
"No dateFormat lookup map registered for " + dataFormat);
if (dateFormatLookup.get(dataFormat).containsKey(recordField) == false)
throw new NullPointerException("No dateFormat registered for "
+ recordField);
return dateFormatLookup.get(dataFormat).get(recordField);
}
*/
private String getSeparator(DataFormat dataFormat, RecordFieldType recordField) {
if (dataFormat == null)
throw new NullPointerException("DataFormat is null!");
if (recordField == null)
throw new NullPointerException("RecordField is null!");
if (separatorLookup.containsKey(dataFormat) == false)
return null;
if (separatorLookup.get(dataFormat).containsKey(recordField) == false)
return null;
return separatorLookup.get(dataFormat).get(recordField);
}
private static void addRecordFieldMapping(DataFormat dataFormat,
RecordFieldType recordField, String regex, boolean isCollection,
String separator, String dateFormat) {
if (patternLookup.containsKey(dataFormat) == false)
patternLookup.put(dataFormat, new HashMap<RecordFieldType, Pattern>());
patternLookup.get(dataFormat).put(recordField, Pattern.compile(regex));
if (collectionLookup.containsKey(dataFormat) == false)
collectionLookup.put(dataFormat,
new HashMap<RecordFieldType, Boolean>());
collectionLookup.get(dataFormat).put(recordField, isCollection);
if (separator != null) {
if (separatorLookup.containsKey(separator) == false)
separatorLookup.put(dataFormat,
new HashMap<RecordFieldType, String>());
separatorLookup.get(dataFormat).put(recordField, separator);
}
if (dateFormat != null) {
if (dateFormatLookup.containsKey(dataFormat) == false)
dateFormatLookup.put(dataFormat,
new HashMap<RecordFieldType, String>());
dateFormatLookup.get(dataFormat).put(recordField, dateFormat);
}
if (log.isDebugEnabled())
log.debug("Adding RecordField: " + recordField + " DataFormat." + dataFormat
+ " regex: " + regex + " isCollection: " + isCollection + " separator: " + separator
+ " dateFormat: " + dateFormat);
}
private static void mapDataFormat(RecordType recordType, DataFormat dataFormat) {
if (recordTypeLookup.containsKey(dataFormat) == false)
recordTypeLookup.put(dataFormat, new HashSet<RecordType>());
recordTypeLookup.get(dataFormat).add(recordType);
if (log.isDebugEnabled())
log.debug("Map RecordType." + recordType + " to DataFormat." + dataFormat);
}
private static void init(Resource resource) {
Document document = XMLHelper.parseXML(resource.getInputStream());
Element flatfileParserConfigNode = XMLHelper.findNode(document,
"FlatfileParserConfig");
if (flatfileParserConfigNode == null)
throw new NullPointerException(
"Config file does not appear to be a valid FlatfileParser Configuration.");
NodeList recordTypeNodes = XMLHelper.findNodes(
flatfileParserConfigNode, "RecordType");
for (int i = 0; i < recordTypeNodes.getLength(); i++) {
Element recordTypeNode = (Element) recordTypeNodes.item(i);
RecordType recordType = RecordType.valueOf(recordTypeNode
.getAttribute("id"));
NodeList dataFormatNodes = XMLHelper.findNodes(
recordTypeNode, "DataFormat");
for (int j = 0; j < dataFormatNodes.getLength(); j++) {
Element dataFormatNode = (Element) dataFormatNodes.item(j);
DataFormat dataFormat = DataFormat.valueOf(dataFormatNode
.getAttribute("id"));
mapDataFormat(recordType, dataFormat);
NodeList recordFieldNodes = XMLHelper.findNodes(
dataFormatNode, "RecordField");
for (int k = 0; k < recordFieldNodes.getLength(); k++) {
Element recordFieldNode = (Element) recordFieldNodes
.item(k);
RecordFieldType recordField = RecordFieldType
.valueOf(recordFieldNode.getAttribute("id"));
String regex = recordFieldNode.getAttribute("regex");
String dateFormat = null;
if (recordFieldNode.hasAttribute("dateFormat"))
dateFormat = recordFieldNode.getAttribute("dateFormat");
String separator = null;
if (recordFieldNode.hasAttribute("separator"))
separator = recordFieldNode.getAttribute("separator");
Boolean isCollection = Boolean.valueOf(recordFieldNode
.getAttribute("collection"));
if (regex == null || regex.trim().length() == 0)
throw new NullPointerException(
"Missing regex attribute for recordField "
+ recordField);
if (isCollection == null)
throw new NullPointerException(
"Missing collection attribute for recordField "
+ recordField);
addRecordFieldMapping(dataFormat, recordField, regex,
isCollection, separator, dateFormat);
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.service.client.impl;
import com.sun.jersey.api.client.WebResource;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
import org.apache.commons.lang3.StringUtils;
import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity;
import org.apache.eagle.log.entity.GenericServiceAPIResponseEntity;
import org.apache.eagle.service.client.EagleServiceClientException;
import org.apache.eagle.service.client.EagleServiceConnector;
import org.apache.eagle.service.client.EagleServiceSingleEntityQueryRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class EagleServiceClientImpl extends EagleServiceBaseClient {
private static final Logger LOG = LoggerFactory.getLogger(EagleServiceClientImpl.class);
private static final String SERVICE_HOST_KEY = "service.host";
private static final String SERVICE_PORT_KEY = "service.port";
private static final String SERVICE_USERNAME_KEY = "service.username";
private static final String SERVICE_PASSWORD_KEY = "service.password";
public EagleServiceClientImpl(String host, int port) {
super(host, port);
}
@Deprecated
public EagleServiceClientImpl(EagleServiceConnector connector) {
this(connector.getEagleServiceHost(), connector.getEagleServicePort(), connector.getUsername(), connector.getPassword());
}
public EagleServiceClientImpl(Config config) {
super(
config.hasPath(SERVICE_HOST_KEY) ? config.getString(SERVICE_HOST_KEY) : "localhost",
tryGetPortFromConfig(config),
config.hasPath(SERVICE_USERNAME_KEY) ? config.getString(SERVICE_USERNAME_KEY) : null,
config.hasPath(SERVICE_PASSWORD_KEY) ? config.getString(SERVICE_PASSWORD_KEY) : null
);
}
/**
* Try to get eagle service port from config by key: service.port no matter STRING or INT.
*/
private static int tryGetPortFromConfig(Config config) {
if (config.hasPath(SERVICE_PORT_KEY)) {
try {
return config.getInt(SERVICE_PORT_KEY);
} catch (ConfigException.WrongType wrongType) {
String portStr = config.getString(SERVICE_PORT_KEY);
if (StringUtils.isNotBlank(portStr)) {
return Integer.valueOf(portStr);
}
}
}
return 9090;
}
public EagleServiceClientImpl(String host, int port, String username, String password) {
super(host, port, username, password);
}
public EagleServiceClientImpl(String host, int port, String basePath, String username, String password) {
super(host, port, basePath, username, password);
}
private String getWholePath(String urlString) {
return getBaseEndpoint() + urlString;
}
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> create(List<E> entities, String serviceName) throws IOException, EagleServiceClientException {
checkNotNull(serviceName, "serviceName");
checkNotNull(entities, "entities");
final GenericServiceAPIResponseEntity<String> response;
response = postEntitiesWithService(GENERIC_ENTITY_PATH, entities, serviceName);
if (!response.isSuccess()) {
LOG.error("Failed to create entities for service: " + serviceName);
}
return response;
}
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> create(List<E> entities) throws IOException, EagleServiceClientException {
checkNotNull(entities, "entities");
Map<String, List<E>> serviceEntityMap = groupEntitiesByService(entities);
if (LOG.isDebugEnabled()) {
LOG.debug("Creating entities for " + serviceEntityMap.keySet().size() + " services");
}
List<String> createdKeys = new LinkedList<String>();
for (Map.Entry<String, List<E>> entry : serviceEntityMap.entrySet()) {
GenericServiceAPIResponseEntity<String> response = create(entry.getValue(), entry.getKey());
if (!response.isSuccess()) {
throw new IOException("Service side exception: " + response.getException());
} else if (response.getObj() != null) {
createdKeys.addAll(response.getObj());
}
}
GenericServiceAPIResponseEntity<String> entity = new GenericServiceAPIResponseEntity<String>();
entity.setObj(createdKeys);
entity.setSuccess(true);
return entity;
}
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> delete(List<E> entities) throws IOException, EagleServiceClientException {
checkNotNull(entities, "entities");
Map<String, List<E>> serviceEntityMap = groupEntitiesByService(entities);
if (LOG.isDebugEnabled()) {
LOG.debug("Creating entities for " + serviceEntityMap.keySet().size() + " services");
}
List<String> deletedKeys = new LinkedList<String>();
for (Map.Entry<String, List<E>> entry : serviceEntityMap.entrySet()) {
GenericServiceAPIResponseEntity<String> response = delete(entry.getValue(), entry.getKey());
if (!response.isSuccess()) {
LOG.error("Got service exception: " + response.getException());
throw new IOException(response.getException());
} else if (response.getObj() != null) {
deletedKeys.addAll(response.getObj());
}
}
GenericServiceAPIResponseEntity<String> entity = new GenericServiceAPIResponseEntity<String>();
entity.setObj(deletedKeys);
entity.setSuccess(true);
return entity;
}
@SuppressWarnings("unchecked")
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> delete(List<E> entities, String serviceName) throws IOException, EagleServiceClientException {
checkNotNull(entities, "entities");
checkNotNull(serviceName, "serviceName");
return postEntitiesWithService(GENERIC_ENTITY_DELETE_PATH, entities, serviceName);
}
@SuppressWarnings("unchecked")
@Override
public GenericServiceAPIResponseEntity<String> delete(EagleServiceSingleEntityQueryRequest request) throws IOException, EagleServiceClientException {
String queryString = request.getQueryParameterString();
StringBuilder sb = new StringBuilder();
sb.append(GENERIC_ENTITY_PATH);
sb.append("?");
sb.append(queryString);
final String urlString = sb.toString();
if (!this.silence) {
LOG.info("Going to delete by querying service: " + getWholePath(urlString));
}
WebResource r = getWebResource(urlString);
return putAuthHeaderIfNeeded(r.accept(DEFAULT_MEDIA_TYPE)
.header(CONTENT_TYPE, DEFAULT_HTTP_HEADER_CONTENT_TYPE))
.delete(GenericServiceAPIResponseEntity.class);
}
@SuppressWarnings("unchecked")
@Override
public GenericServiceAPIResponseEntity<String> deleteById(List<String> ids, String serviceName) throws EagleServiceClientException, IOException {
checkNotNull(serviceName, "serviceName");
checkNotNull(ids, "ids");
final String json = marshall(ids);
final WebResource r = getWebResource(GENERIC_ENTITY_DELETE_PATH);
return putAuthHeaderIfNeeded(r.queryParam(SERVICE_NAME, serviceName)
.queryParam(DELETE_BY_ID, "true")
.accept(DEFAULT_MEDIA_TYPE))
.header(CONTENT_TYPE, DEFAULT_HTTP_HEADER_CONTENT_TYPE)
.post(GenericServiceAPIResponseEntity.class, json);
}
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> update(List<E> entities) throws IOException, EagleServiceClientException {
checkNotNull(entities, "entities");
Map<String, List<E>> serviceEntityMap = groupEntitiesByService(entities);
if (LOG.isDebugEnabled()) {
LOG.debug("Updating entities for " + serviceEntityMap.keySet().size() + " services");
}
List<String> createdKeys = new LinkedList<String>();
for (Map.Entry<String, List<E>> entry : serviceEntityMap.entrySet()) {
GenericServiceAPIResponseEntity<String> response = update(entry.getValue(), entry.getKey());
if (!response.isSuccess()) {
throw new IOException("Got service exception when updating service " + entry.getKey() + " : " + response.getException());
} else {
if (response.getObj() != null) {
createdKeys.addAll(response.getObj());
}
}
}
GenericServiceAPIResponseEntity<String> entity = new GenericServiceAPIResponseEntity<String>();
entity.setObj(createdKeys);
entity.setSuccess(true);
return entity;
}
@Override
public <E extends TaggedLogAPIEntity> GenericServiceAPIResponseEntity<String> update(List<E> entities, String serviceName) throws IOException, EagleServiceClientException {
checkNotNull(entities, "entities");
checkNotNull(serviceName, "serviceName");
return putEntitiesWithService(GENERIC_ENTITY_PATH, entities, serviceName);
}
@Override
@SuppressWarnings("unchecked")
public <T extends Object> GenericServiceAPIResponseEntity<T> search(EagleServiceSingleEntityQueryRequest request) throws EagleServiceClientException {
String queryString = request.getQueryParameterString();
StringBuilder sb = new StringBuilder();
sb.append(GENERIC_ENTITY_PATH);
sb.append("?");
sb.append(queryString);
final String urlString = sb.toString();
if (!this.silence) {
LOG.info("Going to query service: " + getWholePath(urlString));
}
WebResource r = getWebResource(urlString);
return putAuthHeaderIfNeeded(r.accept(DEFAULT_MEDIA_TYPE))
.header(CONTENT_TYPE, DEFAULT_HTTP_HEADER_CONTENT_TYPE)
.get(GenericServiceAPIResponseEntity.class);
}
}
| |
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ximplementation.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.ximplementation.Implement;
import org.ximplementation.Implementor;
import org.ximplementation.Priority;
import org.ximplementation.Validity;
import org.ximplementation.support.CachedImplementeeMethodInvocationFactory.StaticInvocationInputInfo;
import org.ximplementation.support.CachedImplementeeMethodInvocationFactory.StaticInvocationProcessInfo;
/**
* {@linkplain CachedImplementeeMethodInvocationFactory} unit tests.
*
* @author earthangry@gmail.com
* @date 2016-12-6
*
*/
public class CachedImplementeeMethodInvocationFactoryTest
extends AbstractTestSupport
{
private CachedImplementeeMethodInvocationFactory cachedImplementeeMethodInvocationFactory;
private ImplementationResolver implementationResolver;
@Before
public void setUp() throws Exception
{
this.cachedImplementeeMethodInvocationFactory = new CachedImplementeeMethodInvocationFactory();
this.implementationResolver = new ImplementationResolver();
}
@After
public void tearDown() throws Exception
{
this.cachedImplementeeMethodInvocationFactory = null;
this.implementationResolver = null;
}
@Test
public void getTest() throws Throwable
{
// implementInfo == null || !implementInfo.hasImplementMethodInfo()
{
Class<?> implementee = GetTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver.resolve(implementee);
Method implementeeMethod = getMethodByName(implementee, "plus");
assertNull(this.cachedImplementeeMethodInvocationFactory.get(
implementation,
implementeeMethod, new Object[] { "a", "b" },
new SimpleImplementorBeanFactory()));
}
// invocationCacheValue == null
{
Class<?> implementee = GetTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee, GetTest.Implementor0.class,
GetTest.Implementor1.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
StaticInvocationInputInfo key = new StaticInvocationInputInfo(
implementation, implementInfo,
new Class<?>[] { java.util.Date.class,
java.util.Date.class });
assertNull(this.cachedImplementeeMethodInvocationFactory
.getCachedStaticValidAndDescPrioritizeds(key));
assertNull(this.cachedImplementeeMethodInvocationFactory.get(
implementation,
implementeeMethod,
new Object[] { new java.util.Date(), new java.util.Date() },
new SimpleImplementorBeanFactory()));
assertNotNull(this.cachedImplementeeMethodInvocationFactory
.getCachedStaticValidAndDescPrioritizeds(key));
}
// staticValidAndDescPrioritizeds == null ||
// staticValidAndDescPrioritizeds.length == 0
{
Class<?> implementee = GetTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee, GetTest.Implementor0.class,
GetTest.Implementor1.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
assertNull(this.cachedImplementeeMethodInvocationFactory.get(
implementation, implementeeMethod,
new Object[] { "a", "b" },
new SimpleImplementorBeanFactory()));
}
// !invocationCacheValue.isValidityMethodPresents() &&
// !invocationCacheValue.isPriorityMethodPresents()
{
Class<?> implementee = GetTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee, GetTest.Implementor0.class,
GetTest.Implementor1.class,
GetTest.Implementor2.class,
GetTest.Implementor3.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
CountImplementorBeanFactory implementorBeanFactory = CountImplementorBeanFactory.valueOf(
new GetTest.Implementor0(),
new GetTest.Implementor1(),
new GetTest.Implementor2(),
new GetTest.Implementor3());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.get(
implementation,
implementeeMethod,
new Object[] { 1, 2 },
implementorBeanFactory);
assertEquals(GetTest.Implementor3.class,
invocation.getImplementMethodInfo().getImplementor());
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.getCachedStaticValidAndDescPrioritizeds(new StaticInvocationInputInfo(
implementation, implementInfo,
new Class<?>[] { Integer.class,
Integer.class }));
assertEquals(3,
processInfo.getStaticValidAndDescPrioritizeds().length);
assertEquals(GetTest.Implementor3.class,
processInfo.getStaticValidAndDescPrioritizeds()[0]
.getImplementor());
// createBySelectingFromValidAndDescPrioritizeds(...) only get
// implementor beans with the max priority
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor0.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor1.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor2.class));
assertEquals(1, implementorBeanFactory
.getCount(GetTest.Implementor3.class));
this.cachedImplementeeMethodInvocationFactory.get(implementation,
implementeeMethod, new Object[] { 1, 2 },
implementorBeanFactory);
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor0.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor1.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor2.class));
assertEquals(2, implementorBeanFactory
.getCount(GetTest.Implementor3.class));
}
// else
{
Class<?> implementee = GetTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee, GetTest.Implementor0.class,
GetTest.Implementor1.class,
GetTest.Implementor2.class,
GetTest.Implementor3.class,
GetTest.Implementor4.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
CountImplementorBeanFactory implementorBeanFactory = CountImplementorBeanFactory
.valueOf(new GetTest.Implementor0(),
new GetTest.Implementor1(),
new GetTest.Implementor2(),
new GetTest.Implementor3(),
new GetTest.Implementor4());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.get(implementation, implementeeMethod,
new Object[] { 1, 2 }, implementorBeanFactory);
assertEquals(GetTest.Implementor3.class,
invocation.getImplementMethodInfo().getImplementor());
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.getCachedStaticValidAndDescPrioritizeds(
new StaticInvocationInputInfo(implementation,
implementInfo, new Class<?>[] {
Integer.class, Integer.class }));
assertEquals(4,
processInfo.getStaticValidAndDescPrioritizeds().length);
assertEquals(GetTest.Implementor3.class,
processInfo.getStaticValidAndDescPrioritizeds()[0]
.getImplementor());
// createByEvalingFromValidAndDescPrioritizeds(...) get
// all implementor beans to evaluate the max priority
assertEquals(1, implementorBeanFactory
.getCount(GetTest.Implementor0.class));
assertEquals(1, implementorBeanFactory
.getCount(GetTest.Implementor1.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor2.class));
assertEquals(1, implementorBeanFactory
.getCount(GetTest.Implementor3.class));
assertEquals(1, implementorBeanFactory
.getCount(GetTest.Implementor4.class));
this.cachedImplementeeMethodInvocationFactory.get(implementation,
implementeeMethod, new Object[] { 1, 2 },
implementorBeanFactory);
assertEquals(2, implementorBeanFactory
.getCount(GetTest.Implementor0.class));
assertEquals(2, implementorBeanFactory
.getCount(GetTest.Implementor1.class));
assertEquals(0, implementorBeanFactory
.getCount(GetTest.Implementor2.class));
assertEquals(2, implementorBeanFactory
.getCount(GetTest.Implementor3.class));
assertEquals(2, implementorBeanFactory
.getCount(GetTest.Implementor4.class));
}
}
public static class GetTest
{
public static interface Implementee
{
Number plus(Number a, Number b);
Number minus(Number a, Number b);
}
@Implementor(Implementee.class)
public static class Implementor0
{
@Implement
public Number plus(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor1
{
@Implement
public int plus(Integer a, Integer b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor2
{
@Implement
public float plus(Float a, Float b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor3
{
@Implement
@Priority(priority = Integer.MAX_VALUE)
public Number plus(Number a, Number b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor4
{
@Implement
@Validity("isValid")
public float plus(Integer a, Integer b)
{
return 0;
}
public boolean isValid(Integer a)
{
return a > 0;
}
}
}
@Test
public void evalStaticInvocationProcessInfoTest() throws Throwable
{
// !implementInfo.hasImplementMethodInfo()
{
Class<?> implementee = EvalInvocationCacheValueTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
new Class<?>[] { Integer.class, Integer.class });
assertEquals(0,
processInfo.getStaticValidAndDescPrioritizeds().length);
}
// !isImplementMethodParamTypeValid(...)
{
Class<?> implementee = EvalInvocationCacheValueTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
EvalInvocationCacheValueTest.Implementor0.class,
EvalInvocationCacheValueTest.Implementor1.class,
EvalInvocationCacheValueTest.Implementor2.class,
EvalInvocationCacheValueTest.Implementor3.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
new Class<?>[] { Integer.class, Integer.class });
assertFalse(processInfo.isValidityMethodPresents());
assertFalse(processInfo.isPriorityMethodPresents());
assertEquals(3,
processInfo.getStaticValidAndDescPrioritizeds().length);
assertEquals(EvalInvocationCacheValueTest.Implementor3.class,
processInfo.getStaticValidAndDescPrioritizeds()[0]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor1.class,
processInfo.getStaticValidAndDescPrioritizeds()[1]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor0.class,
processInfo.getStaticValidAndDescPrioritizeds()[2]
.getImplementor());
}
// !validityMethodPresents && implementMethodInfo.hasValidityMethod()
{
Class<?> implementee = EvalInvocationCacheValueTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
EvalInvocationCacheValueTest.Implementor0.class,
EvalInvocationCacheValueTest.Implementor1.class,
EvalInvocationCacheValueTest.Implementor2.class,
EvalInvocationCacheValueTest.Implementor4.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
new Class<?>[] { Integer.class, Integer.class });
assertTrue(processInfo.isValidityMethodPresents());
assertFalse(processInfo.isPriorityMethodPresents());
assertEquals(3,
processInfo.getStaticValidAndDescPrioritizeds().length);
assertEquals(EvalInvocationCacheValueTest.Implementor4.class,
processInfo.getStaticValidAndDescPrioritizeds()[0]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor1.class,
processInfo.getStaticValidAndDescPrioritizeds()[1]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor0.class,
processInfo.getStaticValidAndDescPrioritizeds()[2]
.getImplementor());
}
// !priorityMethodPresents && implementMethodInfo.hasPriorityMethod()
{
Class<?> implementee = EvalInvocationCacheValueTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
EvalInvocationCacheValueTest.Implementor0.class,
EvalInvocationCacheValueTest.Implementor1.class,
EvalInvocationCacheValueTest.Implementor2.class,
EvalInvocationCacheValueTest.Implementor5.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
new Class<?>[] { Integer.class, Integer.class });
assertTrue(processInfo.isValidityMethodPresents());
assertTrue(processInfo.isPriorityMethodPresents());
assertEquals(3,
processInfo.getStaticValidAndDescPrioritizeds().length);
assertEquals(EvalInvocationCacheValueTest.Implementor5.class,
processInfo.getStaticValidAndDescPrioritizeds()[0]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor1.class,
processInfo.getStaticValidAndDescPrioritizeds()[1]
.getImplementor());
assertEquals(EvalInvocationCacheValueTest.Implementor0.class,
processInfo.getStaticValidAndDescPrioritizeds()[2]
.getImplementor());
}
}
protected static class EvalInvocationCacheValueTest
{
public static interface Implementee
{
Number plus(Number a, Number b);
Number minus(Number a, Number b);
}
@Implementor(Implementee.class)
public static class Implementor0
{
@Implement
public Number plus(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor1
{
@Implement
public int plus(Integer a, Integer b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor2
{
@Implement
public float plus(Float a, Float b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor3
{
@Implement
@Priority(priority = Integer.MAX_VALUE)
public Number plus(Number a, Number b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor4
{
@Implement
@Validity("isValid")
public float plus(Integer a, Integer b)
{
return 0;
}
public boolean isValid(Integer a)
{
return a > 0;
}
}
@Implementor(Implementee.class)
public static class Implementor5
{
@Implement
@Validity("isValid")
@Priority("getPriority")
public float plus(Integer a, Integer b)
{
return 0;
}
public boolean isValid(Integer a)
{
return a > 0;
}
public int getPriority()
{
return 1;
}
}
}
@Test
public void createBySelectingFromValidAndDescPrioritizedsTest()
{
// isStaticImplementMethod(myMethodInfo)
{
Class<?> implementee = CreateBySelectingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver.resolve(implementee,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor3.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class, Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo, invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createBySelectingFromValidAndDescPrioritizeds(implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds, implementorBeanFactory);
assertEquals(CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor3.class,
invocation.getImplementMethodInfo().getImplementor());
assertNull(invocation.getImplementorBean());
}
// myBeans != null && !myBeans.isEmpty()
{
Class<?> implementee = CreateBySelectingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
Object expectedImplementorBean = new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(
new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0(),
expectedImplementorBean,
new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createBySelectingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
invocation.getImplementMethodInfo().getImplementor());
assertTrue(
expectedImplementorBean == invocation.getImplementorBean());
}
// myBeans == null
{
Class<?> implementee = CreateBySelectingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
Object expectedImplementorBean = new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(
expectedImplementorBean,
new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createBySelectingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
invocation.getImplementMethodInfo().getImplementor());
assertTrue(
expectedImplementorBean == invocation.getImplementorBean());
}
// finalMethodInfo == null
{
Class<?> implementee = CreateBySelectingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf();
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createBySelectingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertNull(invocation);
}
{
Class<?> implementee = CreateBySelectingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
Object expectedImplementorBean = new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(
new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor0(),
expectedImplementorBean,
new CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor2());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createBySelectingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateBySelectingFromValidAndDescPrioritizedsTest.Implementor1.class,
invocation.getImplementMethodInfo().getImplementor());
assertTrue(
expectedImplementorBean == invocation.getImplementorBean());
}
}
public static class CreateBySelectingFromValidAndDescPrioritizedsTest
{
public static interface Implementee
{
Number plus(Number a, Number b);
Number minus(Number a, Number b);
}
@Implementor(Implementee.class)
public static class Implementor0
{
@Implement
public Number plus(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor1
{
@Implement
public int plus(Integer a, Integer b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor2
{
@Implement
public float plus(Float a, Float b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor3
{
@Implement
public static int plus(Integer a, Integer b)
{
return 0;
}
}
}
@Test
public void createByEvaluatingFromValidAndDescPrioritizedsTest()
throws Throwable
{
// isStaticImplementMethod(myImplementMethodInfo)
{
Class<?> implementee = CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver.resolve(implementee,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor6.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation.getImplementInfo(implementeeMethod);
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class, Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo, invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory.valueOf(
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2());
Object[] invocationParams = new Integer[] { 1, 2 };
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds, implementorBeanFactory);
assertEquals(CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor6.class,
invocation.getImplementMethodInfo().getImplementor());
assertNull(invocation.getImplementorBean());
}
// implementorBeans = getImplementorBeansWithCache
{
Class<?> implementee = CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor3.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation,
implementInfo, invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
CountImplementorBeanFactory implementorBeanFactory = CountImplementorBeanFactory
.valueOf(
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor3(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4());
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertNotNull(invocation);
assertEquals(1, implementorBeanFactory
.getCount(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class));
assertEquals(1, implementorBeanFactory.getCount(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class));
assertEquals(0, implementorBeanFactory
.getCount(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class));
assertEquals(1, implementorBeanFactory
.getCount(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor3.class));
assertEquals(1, implementorBeanFactory
.getCount(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4.class));
}
// implementorBeans == null || implementorBeans.isEmpty()
{
Class<?> implementee = CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor3.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Object[] invocationParams = new Integer[] { 1, 2 };
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf();
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertNull(invocation);
}
// invokeValidityMethod(...)
{
Class<?> implementee = CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest
.Implementor1(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest
.Implementor2(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest
.Implementor4());
// !isValid
{
Object[] invocationParams = new Integer[] { -1, 0 };
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
invocation.getImplementorBean().getClass());
}
// isValid
{
Object[] invocationParams = new Integer[] { 1, 2 };
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor4.class,
invocation.getImplementorBean().getClass());
}
}
// invokePriorityMethod(...)
{
Class<?> implementee = CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2.class,
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor5.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
StaticInvocationProcessInfo processInfo = this.cachedImplementeeMethodInvocationFactory
.evalStaticInvocationProcessInfo(implementation, implementInfo,
invocationParamTypes);
ImplementMethodInfo[] validAndDescPrioritizeds = processInfo
.getStaticValidAndDescPrioritizeds();
ImplementorBeanFactory implementorBeanFactory = SimpleImplementorBeanFactory
.valueOf(
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor0(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor2(),
new CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor5());
// myPriority < 0
{
Object[] invocationParams = new Integer[] { -1, 0 };
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor1.class,
invocation.getImplementorBean().getClass());
}
// myPriority > 0
{
Object[] invocationParams = new Integer[] { 1, 2 };
DefaultImplementeeMethodInvocation invocation = (DefaultImplementeeMethodInvocation) this.cachedImplementeeMethodInvocationFactory
.createByEvaluatingFromValidAndDescPrioritizeds(
implementation, implementInfo, invocationParams,
invocationParamTypes, validAndDescPrioritizeds,
implementorBeanFactory);
assertEquals(
CreateByEvaluatingFromValidAndDescPrioritizedsTest.Implementor5.class,
invocation.getImplementorBean().getClass());
}
}
}
public static class CreateByEvaluatingFromValidAndDescPrioritizedsTest
{
public static interface Implementee
{
Number plus(Number a, Number b);
Number minus(Number a, Number b);
}
@Implementor(Implementee.class)
public static class Implementor0
{
@Implement
public Number plus(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor1
{
@Implement
public int plus(Integer a, Integer b)
{
return 0;
}
@Implement("plus")
public Number plus1(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor2
{
@Implement
public float plus(Float a, Float b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor3
{
@Implement
@Priority(priority = Integer.MAX_VALUE)
public Number plus(Number a, Number b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor4
{
@Implement
@Validity("isValid")
public float plus(Integer a, Integer b)
{
return 0;
}
public boolean isValid(Integer a)
{
return a > 0;
}
}
@Implementor(Implementee.class)
public static class Implementor5
{
@Implement
@Priority("getPriority")
public float plus(Integer a, Integer b)
{
return 0;
}
public int getPriority(Integer a)
{
return a;
}
}
@Implementor(Implementee.class)
public static class Implementor6
{
@Implement
@Priority("getPriority")
public static float plus(Integer a, Integer b)
{
return 0;
}
public static int getPriority(Integer a)
{
return Integer.MAX_VALUE;
}
}
}
@Test
public void sortByStaticPriorityTest()
{
// a.getPriorityValue() - b.getPriorityValue() != 0
{
Class<?> implementee = SortByStaticPriorityTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
SortByStaticPriorityTest.Implementor0.class,
SortByStaticPriorityTest.Implementor1.class,
SortByStaticPriorityTest.Implementor2.class,
SortByStaticPriorityTest.Implementor3.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
ImplementMethodInfo[] implementMethodInfos = implementInfo
.getImplementMethodInfos();
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
this.cachedImplementeeMethodInvocationFactory.sortByStaticPriority(
implementation, implementInfo, invocationParamTypes,
implementMethodInfos);
assertEquals(4, implementMethodInfos.length);
assertEquals(SortByStaticPriorityTest.Implementor2.class,
implementMethodInfos[0].getImplementor());
assertEquals(SortByStaticPriorityTest.Implementor3.class,
implementMethodInfos[1].getImplementor());
assertEquals(SortByStaticPriorityTest.Implementor1.class,
implementMethodInfos[2].getImplementor());
assertEquals(SortByStaticPriorityTest.Implementor0.class,
implementMethodInfos[3].getImplementor());
}
// a.getPriorityValue() - b.getPriorityValue() == 0
{
Class<?> implementee = SortByStaticPriorityTest.Implementee.class;
Implementation<?> implementation = this.implementationResolver
.resolve(implementee,
SortByStaticPriorityTest.Implementor0.class,
SortByStaticPriorityTest.Implementor1.class);
Method implementeeMethod = getMethodByName(implementee, "plus");
ImplementInfo implementInfo = implementation
.getImplementInfo(implementeeMethod);
ImplementMethodInfo[] implementMethodInfos = implementInfo
.getImplementMethodInfos();
Class<?>[] invocationParamTypes = new Class<?>[] { Integer.class,
Integer.class };
this.cachedImplementeeMethodInvocationFactory.sortByStaticPriority(
implementation, implementInfo, invocationParamTypes,
implementMethodInfos);
assertEquals(2, implementMethodInfos.length);
assertEquals(SortByStaticPriorityTest.Implementor1.class,
implementMethodInfos[0].getImplementor());
assertEquals(SortByStaticPriorityTest.Implementor0.class,
implementMethodInfos[1].getImplementor());
}
}
public static class SortByStaticPriorityTest
{
public static interface Implementee
{
Number plus(Number a, Number b);
Number minus(Number a, Number b);
}
@Implementor(Implementee.class)
public static class Implementor0
{
@Implement
public Number plus(Number a, Number b)
{
return null;
}
}
@Implementor(Implementee.class)
public static class Implementor1
{
@Implement
public int plus(Integer a, Integer b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor2
{
@Implement
@Priority(priority = Integer.MAX_VALUE)
public Number plus(Number a, Number b)
{
return 0;
}
}
@Implementor(Implementee.class)
public static class Implementor3
{
@Implement
@Priority(priority = 1)
public float plus(Integer a, Integer b)
{
return 0;
}
}
}
@Test
public void getRandomElementTest()
{
// objs == null
{
assertNull(this.cachedImplementeeMethodInvocationFactory
.getRandomElement(null));
}
// objs.isEmpty()
{
assertNull(this.cachedImplementeeMethodInvocationFactory
.getRandomElement(new HashSet<Object>()));
}
// objs instanceof List<?>
{
Integer i0 = new Integer(0);
Integer i1 = new Integer(0);
List<Object> list = new ArrayList<Object>();
list.add(i0);
list.add(i1);
assertTrue(i0 == this.cachedImplementeeMethodInvocationFactory
.getRandomElement(list));
}
// for (Object obj : objs)
{
Integer i0 = new Integer(0);
Integer i1 = new Integer(0);
Set<Object> set = new HashSet<Object>();
set.add(i0);
set.add(i1);
Object re = this.cachedImplementeeMethodInvocationFactory
.getRandomElement(set);
assertNotNull(re);
}
}
protected static class CountImplementorBeanFactory
extends SimpleImplementorBeanFactory
{
private Map<Class<?>, Integer> counts = new HashMap<Class<?>, Integer>();
public CountImplementorBeanFactory()
{
super();
}
public CountImplementorBeanFactory(
Map<Class<?>, ? extends Collection<?>> implementorBeansMap)
{
super(implementorBeansMap);
}
@Override
public <T> Collection<T> getImplementorBeans(Class<T> implementor)
{
Integer count = getCount(implementor) + 1;
counts.put(implementor, count);
return super.getImplementorBeans(implementor);
}
public int getCount(Class<?> implementor)
{
Integer count = this.counts.get(implementor);
return (count == null ? 0 : count.intValue());
}
public static CountImplementorBeanFactory valueOf(
Object... implementorBeans)
{
Map<Class<?>, List<Object>> implementorBeansMap = new HashMap<Class<?>, List<Object>>();
for (Object implementorBean : implementorBeans)
{
Class<?> myClass = implementorBean.getClass();
List<Object> myBeanList = implementorBeansMap.get(myClass);
if (myBeanList == null)
{
myBeanList = new ArrayList<Object>(1);
implementorBeansMap.put(myClass, myBeanList);
}
myBeanList.add(implementorBean);
}
return new CountImplementorBeanFactory(implementorBeansMap);
}
}
}
| |
// ========================================================================
// $Id: WebApplicationContext.java,v 1.136 2005/10/26 08:11:04 gregwilkins Exp $
// Copyright 2000-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.openqa.jetty.jetty.servlet;
import java.io.Externalizable;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.security.PermissionCollection;
import java.util.Collections;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.openqa.jetty.log.LogFactory;
import org.openqa.jetty.http.HttpException;
import org.openqa.jetty.http.HttpHandler;
import org.openqa.jetty.http.HttpRequest;
import org.openqa.jetty.http.HttpResponse;
import org.openqa.jetty.http.UserRealm;
import org.openqa.jetty.jetty.Server;
import org.openqa.jetty.util.JarResource;
import org.openqa.jetty.util.LazyList;
import org.openqa.jetty.util.Loader;
import org.openqa.jetty.util.MultiException;
import org.openqa.jetty.util.Resource;
/* ------------------------------------------------------------ */
/** Standard web.xml configured HttpContext.
*
* This specialization of HttpContext uses the standardized web.xml
* to describe a web application and configure the handlers for the
* HttpContext.
*
* If a file named web-jetty.xml or jetty-web.xml is found in the
* WEB-INF directory it is applied to the context using the
* XmlConfiguration format.
*
* A single WebApplicationHandler instance is used to provide
* security, filter, sevlet and resource handling.
*
* @see org.openqa.jetty.jetty.servlet.WebApplicationHandler
* @version $Id: WebApplicationContext.java,v 1.136 2005/10/26 08:11:04 gregwilkins Exp $
* @author Greg Wilkins (gregw)
*/
public class WebApplicationContext extends ServletHttpContext implements Externalizable
{
private static Log log= LogFactory.getLog(WebApplicationContext.class);
/* ------------------------------------------------------------ */
private String _defaultsDescriptor= "org/openqa/jetty/jetty/servlet/webdefault.xml";
private String _war;
private boolean _extract;
private boolean _ignorewebjetty;
private boolean _distributable;
private Configuration[] _configurations;
private String[] _configurationClassNames;
private transient Map _resourceAliases;
private transient Resource _webApp;
private transient Resource _webInf;
private transient WebApplicationHandler _webAppHandler;
private transient Object _contextListeners;
private transient Map _errorPages;
/* ------------------------------------------------------------ */
/** Constructor.
*/
public WebApplicationContext()
{
}
/* ------------------------------------------------------------ */
/** Constructor.
* @param webApp The Web application directory or WAR file.
*/
public WebApplicationContext(String webApp)
{
_war= webApp;
}
/* ------------------------------------------------------------ */
public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException
{
out.writeObject(getContextPath());
out.writeObject(getVirtualHosts());
HttpHandler[] handlers= getHandlers();
for (int i= 0; i < handlers.length; i++)
{
if (handlers[i] instanceof WebApplicationHandler)
break;
out.writeObject(handlers[i]);
}
out.writeObject(getAttributes());
out.writeBoolean(isRedirectNullPath());
out.writeInt(getMaxCachedFileSize());
out.writeInt(getMaxCacheSize());
out.writeBoolean(getStatsOn());
out.writeObject(getPermissions());
out.writeBoolean(isClassLoaderJava2Compliant());
out.writeObject(_defaultsDescriptor);
out.writeObject(_war);
out.writeBoolean(_extract);
out.writeBoolean(_ignorewebjetty);
out.writeBoolean(_distributable);
out.writeObject(_configurationClassNames);
}
/* ------------------------------------------------------------ */
public void readExternal(java.io.ObjectInput in) throws java.io.IOException, ClassNotFoundException
{
setContextPath((String)in.readObject());
setVirtualHosts((String[])in.readObject());
Object o= in.readObject();
while (o instanceof HttpHandler)
{
addHandler((HttpHandler)o);
o= in.readObject();
}
setAttributes((Map)o);
setRedirectNullPath(in.readBoolean());
setMaxCachedFileSize(in.readInt());
setMaxCacheSize(in.readInt());
setStatsOn(in.readBoolean());
setPermissions((PermissionCollection)in.readObject());
setClassLoaderJava2Compliant(in.readBoolean());
_defaultsDescriptor= (String)in.readObject();
_war= (String)in.readObject();
_extract= in.readBoolean();
_ignorewebjetty= in.readBoolean();
_distributable= in.readBoolean();
_configurationClassNames=(String[])in.readObject();
}
/* ------------------------------------------------------------ */
public void setConfigurationClassNames (String[] configurationClassNames)
{
if (null != configurationClassNames)
{
_configurationClassNames = new String[configurationClassNames.length];
System.arraycopy (configurationClassNames, 0, _configurationClassNames, 0, configurationClassNames.length);
}
}
/* ------------------------------------------------------------ */
public String[] getConfigurationClassNames ()
{
return _configurationClassNames;
}
/* ------------------------------------------------------------ */
/**
* @param war Filename or URL of the web application directory or WAR file.
*/
public void setWAR(String war)
{
_war= war;
}
/* ------------------------------------------------------------ */
public String getWAR()
{
return _war;
}
/* ------------------------------------------------------------ */
public WebApplicationHandler getWebApplicationHandler()
{
if (_webAppHandler == null)
getServletHandler();
return _webAppHandler;
}
/* ------------------------------------------------------------ */
private void resolveWebApp() throws IOException
{
if (_webApp == null && _war != null && _war.length() > 0)
{
// Set dir or WAR
_webApp= Resource.newResource(_war);
// Accept aliases for WAR files
if (_webApp.getAlias() != null)
{
log.info(_webApp + " anti-aliased to " + _webApp.getAlias());
_webApp= Resource.newResource(_webApp.getAlias());
}
if (log.isDebugEnabled())
log.debug(
"Try webapp=" + _webApp + ", exists=" + _webApp.exists() + ", directory=" + _webApp.isDirectory());
// Is the WAR usable directly?
if (_webApp.exists() && !_webApp.isDirectory() && !_webApp.toString().startsWith("jar:"))
{
// No - then lets see if it can be turned into a jar URL.
Resource jarWebApp= Resource.newResource("jar:" + _webApp + "!/");
if (jarWebApp.exists() && jarWebApp.isDirectory())
{
_webApp= jarWebApp;
_war= _webApp.toString();
if (log.isDebugEnabled())
log.debug(
"Try webapp="
+ _webApp
+ ", exists="
+ _webApp.exists()
+ ", directory="
+ _webApp.isDirectory());
}
}
// If we should extract or the URL is still not usable
if (_webApp.exists()
&& (!_webApp.isDirectory()
|| (_extract && _webApp.getFile() == null)
|| (_extract && _webApp.getFile() != null && !_webApp.getFile().isDirectory())))
{
// Then extract it.
File tempDir= new File(getTempDirectory(), "webapp");
if (tempDir.exists())
tempDir.delete();
tempDir.mkdir();
tempDir.deleteOnExit();
log.info("Extract " + _war + " to " + tempDir);
JarResource.extract(_webApp, tempDir, true);
_webApp= Resource.newResource(tempDir.getCanonicalPath());
if (log.isDebugEnabled())
log.debug(
"Try webapp="
+ _webApp
+ ", exists="
+ _webApp.exists()
+ ", directory="
+ _webApp.isDirectory());
}
// Now do we have something usable?
if (!_webApp.exists() || !_webApp.isDirectory())
{
log.warn("Web application not found " + _war);
throw new java.io.FileNotFoundException(_war);
}
if (log.isDebugEnabled())
log.debug("webapp=" + _webApp);
// Iw there a WEB-INF directory?
_webInf= _webApp.addPath("WEB-INF/");
if (!_webInf.exists() || !_webInf.isDirectory())
_webInf= null;
else
{
// Is there a WEB-INF work directory
Resource work= _webInf.addPath("work");
if (work.exists()
&& work.isDirectory()
&& work.getFile() != null
&& work.getFile().canWrite()
&& getAttribute("javax.servlet.context.tempdir") == null)
setAttribute("javax.servlet.context.tempdir", work.getFile());
}
// ResourcePath
super.setBaseResource(_webApp);
}
}
/* ------------------------------------------------------------ */
public Resource getWebInf() throws IOException
{
if (_webInf==null)
resolveWebApp();
return _webInf;
}
/* ------------------------------------------------------------ */
/** Get the context ServletHandler.
* Conveniance method. If no ServletHandler exists, a new one is added to
* the context. This derivation of the method creates a
* WebApplicationHandler extension of ServletHandler.
* @return WebApplicationHandler
*/
public synchronized ServletHandler getServletHandler()
{
if (_webAppHandler == null)
{
_webAppHandler= (WebApplicationHandler)getHandler(WebApplicationHandler.class);
if (_webAppHandler == null)
{
if (getHandler(ServletHandler.class) != null)
throw new IllegalStateException("Cannot have ServletHandler in WebApplicationContext");
_webAppHandler= new WebApplicationHandler();
addHandler(_webAppHandler);
}
}
return _webAppHandler;
}
/* ------------------------------------------------------------ */
public void setPermissions(PermissionCollection permissions)
{
if (!_ignorewebjetty)
log.warn("Permissions set with web-jetty.xml enabled");
super.setPermissions(permissions);
}
/* ------------------------------------------------------------ */
public boolean isIgnoreWebJetty()
{
return _ignorewebjetty;
}
/* ------------------------------------------------------------ */
/**
* @param b If TRUE, web-jetty.xml and jetty-web.xml configuration
* files are ignored.
*/
public void setIgnoreWebJetty(boolean b)
{
_ignorewebjetty= b;
if (b && getPermissions() != null)
log.warn("Permissions set with web-jetty.xml enabled");
}
/* ------------------------------------------------------------ */
public boolean isDistributable()
{
return _distributable;
}
/* ------------------------------------------------------------ */
public void setDistributable(boolean distributable)
{
_distributable=distributable;
}
/* ------------------------------------------------------------ */
public Configuration[] getConfigurations ()
{
return _configurations;
}
/* ------------------------------------------------------------ */
protected Configuration[] loadConfigurations() throws Exception
{
String[] names = _configurationClassNames;
//if this webapp does not have its own set of configurators, use the defaults
if (null==names)
names = ((Server)getHttpServer()).getWebApplicationConfigurationClassNames();
if (null!=names)
{
//instantiate instances for each
Object[] nullArgs = new Object[0];
Configuration[] configurations = new Configuration[names.length];
for (int i=0; i< names.length; i++)
{
configurations[i] =
(Configuration)Loader.loadClass(WebApplicationContext.class, names[i]).getConstructors()[0].newInstance(nullArgs);
if (log.isDebugEnabled()){log.debug("Loaded instance of "+names[i]);};
}
return configurations;
}
else
return new Configuration[0];
}
/* ------------------------------------------------------------ */
protected void configureClassPath() throws Exception
{
//call each of the instances
// first, configure the classpaths
for (int i=0; i<_configurations.length;i++)
{
_configurations[i].setWebApplicationContext(this);
_configurations[i].configureClassPath();
}
}
/* ------------------------------------------------------------ */
protected void configureDefaults() throws Exception
{
//next, configure default settings
for (int i=0;i<_configurations.length;i++)
{
_configurations[i].setWebApplicationContext(this);
_configurations[i].configureDefaults();
}
}
/* ------------------------------------------------------------ */
protected void configureWebApp () throws Exception
{
//finally, finish configuring the webapp
for (int i=0;i<_configurations.length;i++)
{
_configurations[i].setWebApplicationContext(this);
_configurations[i].configureWebApp();
}
}
/* ------------------------------------------------------------ */
/** Start the Web Application.
* @exception IOException
*/
protected void doStart() throws Exception
{
if (isStarted())
return;
// save context classloader
Thread thread= Thread.currentThread();
ClassLoader lastContextLoader= thread.getContextClassLoader();
MultiException mex= null;
try
{
// Find the webapp
resolveWebApp();
// Get the handler
getServletHandler();
_configurations=loadConfigurations();
// initialize the classloader
configureClassPath();
initClassLoader(true);
thread.setContextClassLoader(getClassLoader());
initialize();
// Do the default configuration
configureDefaults();
// Set classpath for Jasper.
Map.Entry entry= _webAppHandler.getHolderEntry("test.jsp");
if (entry != null)
{
ServletHolder jspHolder= (ServletHolder)entry.getValue();
if (jspHolder != null && jspHolder.getInitParameter("classpath") == null)
{
String fileClassPath= getFileClassPath();
jspHolder.setInitParameter("classpath", fileClassPath);
if (log.isDebugEnabled())
log.debug("Set classpath=" + fileClassPath + " for " + jspHolder);
}
}
// configure webapp
configureWebApp();
// If we have servlets, don't init them yet
_webAppHandler.setAutoInitializeServlets(false);
// Start handlers
super.doStart();
mex= new MultiException();
// Context listeners
if (_contextListeners != null && _webAppHandler != null)
{
ServletContextEvent event= new ServletContextEvent(getServletContext());
for (int i= 0; i < LazyList.size(_contextListeners); i++)
{
try
{
((ServletContextListener)LazyList.get(_contextListeners, i)).contextInitialized(event);
}
catch (Exception ex)
{
mex.add(ex);
}
}
}
// OK to Initialize servlets now
if (_webAppHandler != null && _webAppHandler.isStarted())
{
try
{
_webAppHandler.initializeServlets();
}
catch (Exception ex)
{
mex.add(ex);
}
}
}
catch (Exception e)
{
log.warn("Configuration error on " + _war, e);
throw e;
}
finally
{
thread.setContextClassLoader(lastContextLoader);
}
if (mex != null)
mex.ifExceptionThrow();
}
/* ------------------------------------------------------------ */
/** Stop the web application.
* Handlers for resource, servlet, filter and security are removed
* as they are recreated and configured by any subsequent call to start().
* @exception InterruptedException
*/
protected void doStop() throws Exception
{
MultiException mex=new MultiException();
Thread thread= Thread.currentThread();
ClassLoader lastContextLoader= thread.getContextClassLoader();
try
{
// Context listeners
if (_contextListeners != null)
{
if (_webAppHandler != null)
{
ServletContextEvent event= new ServletContextEvent(getServletContext());
for (int i= LazyList.size(_contextListeners); i-- > 0;)
{
try
{
((ServletContextListener)LazyList.get(_contextListeners, i)).contextDestroyed(event);
}
catch (Exception e)
{
mex.add(e);
}
}
}
}
_contextListeners= null;
// Stop the context
try
{
super.doStop();
}
catch (Exception e)
{
mex.add(e);
}
// clean up
clearSecurityConstraints();
if (_webAppHandler != null)
removeHandler(_webAppHandler);
_webAppHandler= null;
if (_errorPages != null)
_errorPages.clear();
_errorPages= null;
_webApp=null;
_webInf=null;
_configurations=null;
}
finally
{
thread.setContextClassLoader(lastContextLoader);
}
if (mex!=null)
mex.ifExceptionThrow();
}
/* ------------------------------------------------------------ */
public void destroy()
{
super.destroy();
if (isStarted())
throw new IllegalStateException();
_defaultsDescriptor=null;
_war=null;
_configurationClassNames=null;
if (_resourceAliases!=null)
_resourceAliases.clear();
_resourceAliases=null;
_contextListeners=null;
if (_errorPages!=null)
_errorPages.clear();
_errorPages=null;
}
/* ------------------------------------------------------------ */
public void handle(String pathInContext, String pathParams, HttpRequest httpRequest, HttpResponse httpResponse)
throws HttpException, IOException
{
if (!isStarted())
return;
try
{
super.handle(pathInContext, pathParams, httpRequest, httpResponse);
}
finally
{
if (!httpRequest.isHandled())
httpResponse.sendError(HttpResponse.__404_Not_Found);
httpRequest.setHandled(true);
if (!httpResponse.isCommitted())
{
httpResponse.completing();
httpResponse.commit();
}
}
}
/* ------------------------------------------------------------ */
public synchronized void addEventListener(EventListener listener) throws IllegalArgumentException
{
if (listener instanceof ServletContextListener)
{
_contextListeners= LazyList.add(_contextListeners, listener);
}
super.addEventListener(listener);
}
/* ------------------------------------------------------------ */
public synchronized void removeEventListener(EventListener listener)
{
_contextListeners= LazyList.remove(_contextListeners, listener);
super.removeEventListener(listener);
}
/* ------------------------------------------------------------ */
public String getDisplayName()
{
return getHttpContextName();
}
/* ------------------------------------------------------------ */
public void setDisplayName(String name)
{
setHttpContextName(name);
}
/* ------------------------------------------------------------ */
/** Set the defaults web.xml file.
* The default web.xml is used to configure all webapplications
* before the WEB-INF/web.xml file is applied. By default the
* org/mortbay/jetty/servlet/webdefault.xml resource from the
* org.openqa.jetty.jetty.jar is used.
* @param defaults File, Resource, URL or null.
*/
public void setDefaultsDescriptor(String defaults)
{
_defaultsDescriptor= defaults;
}
/* ------------------------------------------------------------ */
public String getDefaultsDescriptor()
{
return _defaultsDescriptor;
}
/* ------------------------------------------------------------ */
/**
* @param extract If true, a WAR is extracted to a temporary
* directory before being deployed.
*/
public void setExtractWAR(boolean extract)
{
_extract= extract;
}
/* ------------------------------------------------------------ */
public boolean getExtractWAR()
{
return _extract;
}
/* ------------------------------------------------------------ */
/**
* Initialize is called by the start method after the contexts classloader
* has been initialied, but before the defaults descriptor has been applied.
* The default implementation does nothing.
*
* @exception Exception if an error occurs
*/
protected void initialize() throws Exception
{
}
/* ------------------------------------------------------------ */
protected UserRealm getUserRealm(String name)
{
return getHttpServer().getRealm(name);
}
/* ------------------------------------------------------------ */
public String toString()
{
String name = getDisplayName();
return "WebApplicationContext[" + getContextPath() + "," + (name == null ? _war : name) + "]";
}
/* ------------------------------------------------------------ */
/** Set Resource Alias.
* Resource aliases map resource uri's within a context.
* They may optionally be used by a handler when looking for
* a resource.
* @param alias
* @param uri
*/
public void setResourceAlias(String alias, String uri)
{
if (_resourceAliases == null)
_resourceAliases= new HashMap(5);
_resourceAliases.put(alias, uri);
}
/* ------------------------------------------------------------ */
public Map getResourceAliases()
{
if (_resourceAliases == null)
return null;
return Collections.unmodifiableMap(_resourceAliases);
}
/* ------------------------------------------------------------ */
public String getResourceAlias(String alias)
{
if (_resourceAliases == null)
return null;
return (String)_resourceAliases.get(alias);
}
/* ------------------------------------------------------------ */
public String removeResourceAlias(String alias)
{
if (_resourceAliases == null)
return null;
return (String)_resourceAliases.remove(alias);
}
/* ------------------------------------------------------------ */
public Resource getResource(String uriInContext) throws IOException
{
IOException ioe= null;
Resource resource= null;
try
{
resource= super.getResource(uriInContext);
if (resource != null && resource.exists())
return resource;
}
catch (IOException e)
{
ioe= e;
}
String aliasedUri= getResourceAlias(uriInContext);
if (aliasedUri != null)
return super.getResource(aliasedUri);
if (ioe != null)
throw ioe;
return resource;
}
/* ------------------------------------------------------------ */
/** set error page URI.
* @param error A string representing an error code or a
* exception classname
* @param uriInContext
*/
public void setErrorPage(String error, String uriInContext)
{
if (_errorPages == null)
_errorPages= new HashMap();
_errorPages.put(error, uriInContext);
}
/* ------------------------------------------------------------ */
/** get error page URI.
* @param error A string representing an error code or a
* exception classname
* @return URI within context
*/
public String getErrorPage(String error)
{
if (_errorPages == null)
return null;
return (String)_errorPages.get(error);
}
/* ------------------------------------------------------------ */
public String removeErrorPage(String error)
{
if (_errorPages == null)
return null;
return (String)_errorPages.remove(error);
}
/* ------------------------------------------------------------------------------- */
/** Base Class for WebApplicationContext Configuration.
* This class can be extended to customize or extend the configuration
* of the WebApplicationContext. If WebApplicationContext.setConfiguration is not
* called, then an XMLConfiguration instance is created.
*
* @version $Revision: 1.136 $
* @author gregw
*/
public static interface Configuration extends Serializable
{
/* ------------------------------------------------------------------------------- */
/** Set up a context on which to perform the configuration.
* @param context
*/
public void setWebApplicationContext (WebApplicationContext context);
/* ------------------------------------------------------------------------------- */
/** Get the context on which the configuration is performed.
* @return
*/
public WebApplicationContext getWebApplicationContext ();
/* ------------------------------------------------------------------------------- */
/** Configure ClassPath.
* This method is called before the context ClassLoader is created.
* Paths and libraries should be added to the context using the setClassPath,
* addClassPath and addClassPaths methods. The default implementation looks
* for WEB-INF/classes, WEB-INF/lib/*.zip and WEB-INF/lib/*.jar
* @throws Exception
*/
public void configureClassPath()
throws Exception;
/* ------------------------------------------------------------------------------- */
/** Configure Defaults.
* This method is called to intialize the context to the containers default configuration.
* Typically this would mean application of the webdefault.xml file. The default
* implementation does nothing.
* @throws Exception
*/
public void configureDefaults()
throws Exception;
/* ------------------------------------------------------------------------------- */
/** Configure WebApp.
* This method is called to apply the standard and vendor deployment descriptors.
* Typically this is web.xml and jetty-web.xml. The default implementation does nothing.
* @throws Exception
*/
public void configureWebApp()
throws Exception;
}
}
| |
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client;
import static com.google.gerrit.common.data.GlobalCapability.CREATE_GROUP;
import static com.google.gerrit.common.data.GlobalCapability.CREATE_PROJECT;
import static com.google.gerrit.common.data.GlobalCapability.VIEW_PLUGINS;
import com.google.gerrit.client.account.AccountApi;
import com.google.gerrit.client.account.AccountCapabilities;
import com.google.gerrit.client.account.AccountInfo;
import com.google.gerrit.client.account.Preferences;
import com.google.gerrit.client.admin.ProjectScreen;
import com.google.gerrit.client.api.ApiGlue;
import com.google.gerrit.client.api.PluginLoader;
import com.google.gerrit.client.changes.ChangeConstants;
import com.google.gerrit.client.changes.ChangeListScreen;
import com.google.gerrit.client.config.ConfigServerApi;
import com.google.gerrit.client.extensions.TopMenu;
import com.google.gerrit.client.extensions.TopMenuItem;
import com.google.gerrit.client.extensions.TopMenuList;
import com.google.gerrit.client.patches.PatchScreen;
import com.google.gerrit.client.rpc.CallbackGroup;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.rpc.Natives;
import com.google.gerrit.client.ui.LinkMenuBar;
import com.google.gerrit.client.ui.LinkMenuItem;
import com.google.gerrit.client.ui.MorphingTabPanel;
import com.google.gerrit.client.ui.PatchLink;
import com.google.gerrit.client.ui.ProjectLinkMenuItem;
import com.google.gerrit.client.ui.Screen;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.common.data.GerritConfig;
import com.google.gerrit.common.data.GitwebConfig;
import com.google.gerrit.common.data.HostPageData;
import com.google.gerrit.common.data.SystemInfoService;
import com.google.gerrit.extensions.webui.GerritTopMenu;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountDiffPreference;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences;
import com.google.gerrit.reviewdb.client.AuthType;
import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.http.client.URL;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwtexpui.clippy.client.CopyableLabel;
import com.google.gwtexpui.user.client.UserAgent;
import com.google.gwtexpui.user.client.ViewSite;
import com.google.gwtjsonrpc.client.JsonDefTarget;
import com.google.gwtjsonrpc.client.JsonUtil;
import com.google.gwtjsonrpc.client.XsrfManager;
import com.google.gwtorm.client.KeyUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Gerrit implements EntryPoint {
public static final GerritConstants C = GWT.create(GerritConstants.class);
public static final ChangeConstants CC = GWT.create(ChangeConstants.class);
public static final GerritMessages M = GWT.create(GerritMessages.class);
public static final GerritResources RESOURCES =
GWT.create(GerritResources.class);
public static final SystemInfoService SYSTEM_SVC;
public static final EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);
public static Themer THEMER = GWT.create(Themer.class);
private static String myHost;
private static GerritConfig myConfig;
private static HostPageData.Theme myTheme;
private static Account myAccount;
private static String defaultScreenToken;
private static AccountDiffPreference myAccountDiffPref;
private static String xGerritAuth;
private static Map<String, LinkMenuBar> menuBars;
private static MorphingTabPanel menuLeft;
private static LinkMenuBar menuRight;
private static RootPanel topMenu;
private static RootPanel siteHeader;
private static RootPanel siteFooter;
private static RootPanel bottomMenu;
private static SearchPanel searchPanel;
private static final Dispatcher dispatcher = new Dispatcher();
private static ViewSite<Screen> body;
private static PatchScreen patchScreen;
private static String lastChangeListToken;
private static String lastViewToken;
static {
SYSTEM_SVC = GWT.create(SystemInfoService.class);
JsonUtil.bind(SYSTEM_SVC, "rpc/SystemInfoService");
}
static void upgradeUI(String token) {
History.newItem(Dispatcher.RELOAD_UI + token, false);
Window.Location.reload();
}
public static PatchScreen.TopView getPatchScreenTopView() {
if (patchScreen == null) {
return null;
}
return patchScreen.getTopView();
}
public static void displayLastChangeList() {
if (lastChangeListToken != null) {
display(lastChangeListToken);
} else if (isSignedIn()) {
display(PageLinks.MINE);
} else {
display(PageLinks.toChangeQuery("status:open"));
}
}
public static String getPriorView() {
return lastViewToken;
}
/**
* Load the screen at the given location, displaying when ready.
* <p>
* If the URL is not already pointing at this location, a new item will be
* added to the browser's history when the screen is fully loaded and
* displayed on the UI.
*
* @param token location to parse, load, and render.
*/
public static void display(final String token) {
if (body.getView() == null || !body.getView().displayToken(token)) {
dispatcher.display(token);
}
}
/**
* Load the screen passed, assuming token can be used to locate it.
* <p>
* The screen is loaded in the background. When it is ready to be visible a
* new item will be added to the browser's history, the screen will be made
* visible, and the window title may be updated.
* <p>
* If {@link Screen#isRequiresSignIn()} is true and the user is not signed in
* yet the screen instance will be discarded, sign-in will take place, and
* will redirect to this location upon success.
*
* @param token location that refers to {@code view}.
* @param view the view to load.
*/
public static void display(final String token, final Screen view) {
if (view.isRequiresSignIn() && !isSignedIn()) {
doSignIn(token);
} else {
view.setToken(token);
body.setView(view);
}
}
/**
* Update any top level menus which can vary based on the view which was
* loaded.
* @param view the loaded view.
*/
public static void updateMenus(Screen view) {
LinkMenuBar diffBar = menuBars.get(GerritTopMenu.DIFFERENCES.menuName);
if (view instanceof PatchScreen) {
patchScreen = (PatchScreen) view;
menuLeft.setVisible(diffBar, true);
menuLeft.selectTab(menuLeft.getWidgetIndex(diffBar));
} else {
if (patchScreen != null && menuLeft.getSelectedWidget() == diffBar) {
menuLeft.selectTab(isSignedIn() ? 1 : 0);
}
patchScreen = null;
menuLeft.setVisible(diffBar, false);
}
}
public static void selectMenu(LinkMenuBar bar) {
menuLeft.selectTab(menuLeft.getWidgetIndex(bar));
}
/**
* Update the current history token after a screen change.
* <p>
* The caller has already updated the UI, but wants to publish a different
* history token for the current browser state. This really only makes sense
* if the caller is a {@code TabPanel} and is firing an event when the tab
* changed to a different part.
*
* @param token new location that is already visible.
*/
public static void updateImpl(final String token) {
History.newItem(token, false);
dispatchHistoryHooks(token);
}
public static void setQueryString(String query) {
searchPanel.setText(query);
}
public static void setWindowTitle(final Screen screen, final String text) {
if (screen == body.getView()) {
if (text == null || text.length() == 0) {
Window.setTitle(M.windowTitle1(myHost));
} else {
Window.setTitle(M.windowTitle2(text, myHost));
}
}
}
public static int getHeaderFooterHeight() {
int h = bottomMenu.getOffsetHeight();
if (topMenu.isVisible()) {
h += topMenu.getOffsetHeight();
}
if (siteHeader.isVisible()) {
h += siteHeader.getOffsetHeight();
}
if (siteFooter.isVisible()) {
h += siteFooter.getOffsetHeight();
}
return h;
}
public static void setHeaderVisible(boolean visible) {
topMenu.setVisible(visible);
siteHeader.setVisible(visible && (myAccount != null
? myAccount.getGeneralPreferences().isShowSiteHeader()
: true));
}
public static boolean isHeaderVisible() {
return topMenu.isVisible();
}
public static String getDefaultScreenToken() {
return defaultScreenToken;
}
public static RootPanel getBottomMenu() {
return bottomMenu;
}
/** Get the public configuration data used by this Gerrit instance. */
public static GerritConfig getConfig() {
return myConfig;
}
public static GitwebLink getGitwebLink() {
GitwebConfig gw = getConfig().getGitwebLink();
return gw != null && gw.type != null ? new GitwebLink(gw) : null;
}
/** Site theme information (site specific colors)/ */
public static HostPageData.Theme getTheme() {
return myTheme;
}
/** @return the currently signed in user's account data; null if no account */
public static Account getUserAccount() {
return myAccount;
}
/** @return the currently signed in user's account data; empty account data if no account */
public static AccountInfo getUserAccountInfo() {
return FormatUtil.asInfo(myAccount);
}
/** @return access token to prove user identity during REST API calls. */
public static String getXGerritAuth() {
return xGerritAuth;
}
/** @return the currently signed in users's diff preferences; null if no diff preferences defined for the account */
public static AccountDiffPreference getAccountDiffPreference() {
return myAccountDiffPref;
}
public static void setAccountDiffPreference(AccountDiffPreference accountDiffPref) {
myAccountDiffPref = accountDiffPref;
}
/** @return true if the user is currently authenticated */
public static boolean isSignedIn() {
return getUserAccount() != null;
}
/** Sign the user into the application. */
public static void doSignIn(String token) {
Location.assign(loginRedirect(token));
}
public static String loginRedirect(String token) {
if (token == null) {
token = "";
} else if (token.startsWith("/")) {
token = token.substring(1);
}
return selfRedirect("login/") + URL.encodePathSegment("#/" + token);
}
public static String selfRedirect(String suffix) {
// Clean up the path. Users seem to like putting extra slashes into the URL
// which can break redirections by misinterpreting at either client or server.
String path = Location.getPath();
if (path == null || path.isEmpty()) {
path = "/";
} else {
while (path.startsWith("//")) {
path = path.substring(1);
}
while (path.endsWith("//")) {
path = path.substring(0, path.length() - 1);
}
if (!path.endsWith("/")) {
path = path + "/";
}
}
if (suffix != null) {
while (suffix.startsWith("/")) {
suffix = suffix.substring(1);
}
path += suffix;
}
UrlBuilder builder = new UrlBuilder();
builder.setProtocol(Location.getProtocol());
builder.setHost(Location.getHost());
String port = Location.getPort();
if (port != null && !port.isEmpty()) {
builder.setPort(Integer.parseInt(port));
}
builder.setPath(path);
return builder.buildString();
}
static void deleteSessionCookie() {
myAccount = null;
myAccountDiffPref = null;
xGerritAuth = null;
refreshMenuBar();
// If the cookie was HttpOnly, this request to delete it will
// most likely not be successful. We can try anyway though.
//
Cookies.removeCookie("GerritAccount");
}
@Override
public void onModuleLoad() {
UserAgent.assertNotInIFrame();
KeyUtil.setEncoderImpl(new KeyUtil.Encoder() {
@Override
public String encode(String e) {
e = URL.encodeQueryString(e);
e = fixPathImpl(e);
e = fixColonImpl(e);
e = fixDoubleQuote(e);
return e;
}
@Override
public String decode(final String e) {
return URL.decodeQueryString(e);
}
private native String fixPathImpl(String path)
/*-{ return path.replace(/%2F/g, "/"); }-*/;
private native String fixColonImpl(String path)
/*-{ return path.replace(/%3A/g, ":"); }-*/;
private native String fixDoubleQuote(String path)
/*-{ return path.replace(/%22/g, '"'); }-*/;
});
initHostname();
Window.setTitle(M.windowTitle1(myHost));
final HostPageDataService hpd = GWT.create(HostPageDataService.class);
hpd.load(new GerritCallback<HostPageData>() {
@Override
public void onSuccess(final HostPageData result) {
Document.get().getElementById("gerrit_hostpagedata").removeFromParent();
myConfig = result.config;
myTheme = result.theme;
if (result.account != null) {
myAccount = result.account;
xGerritAuth = result.xGerritAuth;
}
if (result.accountDiffPref != null) {
myAccountDiffPref = result.accountDiffPref;
applyUserPreferences();
}
onModuleLoad2(result);
}
});
}
private static void initHostname() {
myHost = Location.getHostName();
final int d1 = myHost.indexOf('.');
if (d1 < 0) {
return;
}
final int d2 = myHost.indexOf('.', d1 + 1);
if (d2 >= 0) {
myHost = myHost.substring(0, d2);
}
}
private static void dispatchHistoryHooks(String token) {
ApiGlue.fireEvent("history", token);
}
private static void populateBottomMenu(RootPanel btmmenu, HostPageData hpd) {
String vs = hpd.version;
if (vs == null || vs.isEmpty()) {
vs = "dev";
}
btmmenu.add(new InlineHTML(M.poweredBy(vs)));
final String reportBugText = getConfig().getReportBugText();
Anchor a = new Anchor(
reportBugText == null ? C.reportBug() : reportBugText,
getConfig().getReportBugUrl());
a.setTarget("_blank");
a.setStyleName("");
btmmenu.add(new InlineLabel(" | "));
btmmenu.add(a);
btmmenu.add(new InlineLabel(" | "));
btmmenu.add(new InlineLabel(C.keyHelp()));
}
private void onModuleLoad2(HostPageData hpd) {
RESOURCES.gwt_override().ensureInjected();
RESOURCES.css().ensureInjected();
topMenu = RootPanel.get("gerrit_topmenu");
final RootPanel gStarting = RootPanel.get("gerrit_startinggerrit");
final RootPanel gBody = RootPanel.get("gerrit_body");
bottomMenu = RootPanel.get("gerrit_btmmenu");
topMenu.setStyleName(RESOURCES.css().gerritTopMenu());
gBody.setStyleName(RESOURCES.css().gerritBody());
final Grid menuLine = new Grid(1, 3);
menuLeft = new MorphingTabPanel();
menuRight = new LinkMenuBar();
searchPanel = new SearchPanel();
menuLeft.setStyleName(RESOURCES.css().topmenuMenuLeft());
menuLine.setStyleName(RESOURCES.css().topmenu());
topMenu.add(menuLine);
final FlowPanel menuRightPanel = new FlowPanel();
menuRightPanel.setStyleName(RESOURCES.css().topmenuMenuRight());
menuRightPanel.add(searchPanel);
menuRightPanel.add(menuRight);
menuLine.setWidget(0, 0, menuLeft);
menuLine.setWidget(0, 1, new FlowPanel());
menuLine.setWidget(0, 2, menuRightPanel);
final CellFormatter fmt = menuLine.getCellFormatter();
fmt.setStyleName(0, 0, RESOURCES.css().topmenuTDmenu());
fmt.setStyleName(0, 1, RESOURCES.css().topmenuTDglue());
fmt.setStyleName(0, 2, RESOURCES.css().topmenuTDmenu());
siteHeader = RootPanel.get("gerrit_header");
siteFooter = RootPanel.get("gerrit_footer");
body = new ViewSite<Screen>() {
@Override
protected void onShowView(Screen view) {
String token = view.getToken();
History.newItem(token, false);
dispatchHistoryHooks(token);
if (view instanceof ChangeListScreen) {
lastChangeListToken = token;
}
super.onShowView(view);
view.onShowView();
lastViewToken = token;
}
};
gBody.add(body);
RpcStatus.INSTANCE = new RpcStatus();
JsonUtil.addRpcStartHandler(RpcStatus.INSTANCE);
JsonUtil.addRpcCompleteHandler(RpcStatus.INSTANCE);
JsonUtil.setDefaultXsrfManager(new XsrfManager() {
@Override
public String getToken(JsonDefTarget proxy) {
return xGerritAuth;
}
@Override
public void setToken(JsonDefTarget proxy, String token) {
// Ignore the request, we always rely upon the cookie.
}
});
gStarting.getElement().getParentElement().removeChild(
gStarting.getElement());
RootPanel.detachNow(gStarting);
ApiGlue.init();
applyUserPreferences();
populateBottomMenu(bottomMenu, hpd);
refreshMenuBar(false);
History.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
display(event.getValue());
}
});
JumpKeys.register(body);
saveDefaultTheme();
if (hpd.messages != null) {
new MessageOfTheDayBar(hpd.messages).show();
}
CallbackGroup cbg = new CallbackGroup();
if (isSignedIn()) {
AccountApi.self().view("preferences").get(cbg.add(createMyMenuBarCallback()));
}
PluginLoader.load(hpd.plugins,
cbg.addFinal(new GerritCallback<VoidResult>() {
@Override
public void onSuccess(VoidResult result) {
String token = History.getToken();
if (token.isEmpty()) {
token = isSignedIn()
? PageLinks.MINE
: PageLinks.toChangeQuery("status:open");
}
display(token);
}
}));
}
private void saveDefaultTheme() {
THEMER.init(Document.get().getElementById("gerrit_sitecss"),
Document.get().getElementById("gerrit_header"),
Document.get().getElementById("gerrit_footer"));
}
public static void refreshMenuBar() {
refreshMenuBar(true);
}
private static void refreshMenuBar(boolean populateMyMenu) {
menuLeft.clear();
menuRight.clear();
menuBars = new HashMap<>();
final boolean signedIn = isSignedIn();
final GerritConfig cfg = getConfig();
LinkMenuBar m;
m = new LinkMenuBar();
menuBars.put(GerritTopMenu.ALL.menuName, m);
addLink(m, C.menuAllOpen(), PageLinks.toChangeQuery("status:open"));
addLink(m, C.menuAllMerged(), PageLinks.toChangeQuery("status:merged"));
addLink(m, C.menuAllAbandoned(), PageLinks.toChangeQuery("status:abandoned"));
menuLeft.add(m, C.menuAll());
if (signedIn) {
LinkMenuBar myBar = new LinkMenuBar();
menuBars.put(GerritTopMenu.MY.menuName, myBar);
if (populateMyMenu) {
AccountApi.self().view("preferences").get(createMyMenuBarCallback());
}
menuLeft.add(myBar, C.menuMine());
menuLeft.selectTab(1);
} else {
menuLeft.selectTab(0);
}
patchScreen = null;
LinkMenuBar diffBar = new LinkMenuBar();
menuBars.put(GerritTopMenu.DIFFERENCES.menuName, diffBar);
menuLeft.addInvisible(diffBar, C.menuDiff());
addDiffLink(diffBar, CC.patchTableDiffSideBySide(), PatchScreen.Type.SIDE_BY_SIDE);
addDiffLink(diffBar, CC.patchTableDiffUnified(), PatchScreen.Type.UNIFIED);
addDiffLink(diffBar, C.menuDiffCommit(), PatchScreen.TopView.COMMIT);
addDiffLink(diffBar, C.menuDiffPreferences(), PatchScreen.TopView.PREFERENCES);
addDiffLink(diffBar, C.menuDiffPatchSets(), PatchScreen.TopView.PATCH_SETS);
addDiffLink(diffBar, C.menuDiffFiles(), PatchScreen.TopView.FILES);
final LinkMenuBar projectsBar = new LinkMenuBar();
menuBars.put(GerritTopMenu.PROJECTS.menuName, projectsBar);
addLink(projectsBar, C.menuProjectsList(), PageLinks.ADMIN_PROJECTS);
projectsBar.addItem(new ProjectLinkMenuItem(C.menuProjectsInfo(), ProjectScreen.INFO));
projectsBar.addItem(new ProjectLinkMenuItem(C.menuProjectsBranches(), ProjectScreen.BRANCH));
projectsBar.addItem(new ProjectLinkMenuItem(C.menuProjectsAccess(), ProjectScreen.ACCESS));
final LinkMenuItem dashboardsMenuItem =
new ProjectLinkMenuItem(C.menuProjectsDashboards(),
ProjectScreen.DASHBOARDS) {
protected boolean match(String token) {
return super.match(token) ||
(!getTargetHistoryToken().isEmpty() && ("/admin" + token).startsWith(getTargetHistoryToken()));
}
};
projectsBar.addItem(dashboardsMenuItem);
menuLeft.add(projectsBar, C.menuProjects());
if (signedIn) {
final LinkMenuBar peopleBar = new LinkMenuBar();
menuBars.put(GerritTopMenu.PEOPLE.menuName, peopleBar);
final LinkMenuItem groupsListMenuItem =
addLink(peopleBar, C.menuPeopleGroupsList(), PageLinks.ADMIN_GROUPS);
menuLeft.add(peopleBar, C.menuPeople());
final LinkMenuBar pluginsBar = new LinkMenuBar();
menuBars.put(GerritTopMenu.PLUGINS.menuName, pluginsBar);
AccountCapabilities.all(new GerritCallback<AccountCapabilities>() {
@Override
public void onSuccess(AccountCapabilities result) {
if (result.canPerform(CREATE_PROJECT)) {
insertLink(projectsBar, C.menuProjectsCreate(),
PageLinks.ADMIN_CREATE_PROJECT,
projectsBar.getWidgetIndex(dashboardsMenuItem) + 1);
}
if (result.canPerform(CREATE_GROUP)) {
insertLink(peopleBar, C.menuPeopleGroupsCreate(),
PageLinks.ADMIN_CREATE_GROUP,
peopleBar.getWidgetIndex(groupsListMenuItem) + 1);
}
if (result.canPerform(VIEW_PLUGINS)) {
insertLink(pluginsBar, C.menuPluginsInstalled(),
PageLinks.ADMIN_PLUGINS, 0);
menuLeft.insert(pluginsBar, C.menuPlugins(),
menuLeft.getWidgetIndex(peopleBar) + 1);
}
}
}, CREATE_PROJECT, CREATE_GROUP, VIEW_PLUGINS);
}
if (getConfig().isDocumentationAvailable()) {
m = new LinkMenuBar();
menuBars.put(GerritTopMenu.DOCUMENTATION.menuName, m);
addDocLink(m, C.menuDocumentationTOC(), "index.html");
addDocLink(m, C.menuDocumentationSearch(), "user-search.html");
addDocLink(m, C.menuDocumentationUpload(), "user-upload.html");
addDocLink(m, C.menuDocumentationAccess(), "access-control.html");
addDocLink(m, C.menuDocumentationAPI(), "rest-api.html");
addDocLink(m, C.menuDocumentationProjectOwnerGuide(), "intro-project-owner.html");
menuLeft.add(m, C.menuDocumentation());
}
if (signedIn) {
whoAmI(cfg.getAuthType() != AuthType.CLIENT_SSL_CERT_LDAP);
} else {
switch (cfg.getAuthType()) {
case CLIENT_SSL_CERT_LDAP:
break;
case OPENID:
menuRight.addItem(C.menuRegister(), new Command() {
public void execute() {
String t = History.getToken();
if (t == null) {
t = "";
}
doSignIn(PageLinks.REGISTER + t);
}
});
menuRight.addItem(C.menuSignIn(), new Command() {
public void execute() {
doSignIn(History.getToken());
}
});
break;
case OAUTH:
menuRight.addItem(C.menuSignIn(), new Command() {
@Override
public void execute() {
doSignIn(History.getToken());
}
});
break;
case OPENID_SSO:
menuRight.addItem(C.menuSignIn(), new Command() {
public void execute() {
doSignIn(History.getToken());
}
});
break;
case HTTP:
case HTTP_LDAP:
if (cfg.getLoginUrl() != null) {
final String signinText = cfg.getLoginText() == null ? C.menuSignIn() : cfg.getLoginText();
menuRight.add(anchor(signinText, cfg.getLoginUrl()));
}
break;
case LDAP:
case LDAP_BIND:
case CUSTOM_EXTENSION:
if (cfg.getRegisterUrl() != null) {
final String registerText = cfg.getRegisterText() == null ? C.menuRegister() : cfg.getRegisterText();
menuRight.add(anchor(registerText, cfg.getRegisterUrl()));
}
menuRight.addItem(C.menuSignIn(), new Command() {
public void execute() {
doSignIn(History.getToken());
}
});
break;
case DEVELOPMENT_BECOME_ANY_ACCOUNT:
menuRight.add(anchor("Become", loginRedirect("")));
break;
}
}
ConfigServerApi.topMenus(new GerritCallback<TopMenuList>() {
public void onSuccess(TopMenuList result) {
List<TopMenu> topMenuExtensions = Natives.asList(result);
for (TopMenu menu : topMenuExtensions) {
LinkMenuBar existingBar = menuBars.get(menu.getName());
LinkMenuBar bar = existingBar != null ? existingBar : new LinkMenuBar();
for (TopMenuItem item : Natives.asList(menu.getItems())) {
addExtensionLink(bar, item);
}
if (existingBar == null) {
menuBars.put(menu.getName(), bar);
menuLeft.add(bar, menu.getName());
}
}
}
});
}
private static AsyncCallback<Preferences> createMyMenuBarCallback() {
return new GerritCallback<Preferences>() {
@Override
public void onSuccess(Preferences prefs) {
LinkMenuBar myBar = menuBars.get(GerritTopMenu.MY.menuName);
myBar.clear();
List<TopMenuItem> myMenuItems = Natives.asList(prefs.my());
String url = null;
if (!myMenuItems.isEmpty()) {
if (myMenuItems.get(0).getUrl().startsWith("#")) {
url = myMenuItems.get(0).getUrl().substring(1);
}
for (TopMenuItem item : myMenuItems) {
addExtensionLink(myBar, item);
}
}
defaultScreenToken = url;
}
};
}
public static void applyUserPreferences() {
if (myAccount != null) {
final AccountGeneralPreferences p = myAccount.getGeneralPreferences();
CopyableLabel.setFlashEnabled(p.isUseFlashClipboard());
if (siteHeader != null) {
siteHeader.setVisible(p.isShowSiteHeader());
}
if (siteFooter != null) {
siteFooter.setVisible(p.isShowSiteHeader());
}
FormatUtil.setPreferences(myAccount.getGeneralPreferences());
}
}
private static void whoAmI(boolean canLogOut) {
AccountInfo account = getUserAccountInfo();
final UserPopupPanel userPopup =
new UserPopupPanel(account, canLogOut, true);
final FlowPanel userSummaryPanel = new FlowPanel();
class PopupHandler implements KeyDownHandler, ClickHandler {
private void showHidePopup() {
if (userPopup.isShowing() && userPopup.isVisible()) {
userPopup.hide();
} else {
userPopup.showRelativeTo(userSummaryPanel);
}
}
@Override
public void onClick(ClickEvent event) {
showHidePopup();
}
@Override
public void onKeyDown(KeyDownEvent event) {
if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
showHidePopup();
event.preventDefault();
}
}
}
final PopupHandler popupHandler = new PopupHandler();
final InlineLabel l = new InlineLabel(FormatUtil.name(account));
l.setStyleName(RESOURCES.css().menuBarUserName());
final AvatarImage avatar = new AvatarImage(account, 26, false);
avatar.setStyleName(RESOURCES.css().menuBarUserNameAvatar());
userSummaryPanel.setStyleName(RESOURCES.css().menuBarUserNamePanel());
userSummaryPanel.add(l);
userSummaryPanel.add(avatar);
// "BLACK DOWN-POINTING SMALL TRIANGLE"
userSummaryPanel.add(new InlineLabel(" \u25be"));
userPopup.addAutoHidePartner(userSummaryPanel.getElement());
FocusPanel fp = new FocusPanel(userSummaryPanel);
fp.setStyleName(RESOURCES.css().menuBarUserNameFocusPanel());
fp.addKeyDownHandler(popupHandler);
fp.addClickHandler(popupHandler);
menuRight.add(fp);
}
private static Anchor anchor(final String text, final String to) {
final Anchor a = new Anchor(text, to);
a.setStyleName(RESOURCES.css().menuItem());
Roles.getMenuitemRole().set(a.getElement());
return a;
}
private static LinkMenuItem addLink(final LinkMenuBar m, final String text,
final String historyToken) {
LinkMenuItem i = new LinkMenuItem(text, historyToken);
m.addItem(i);
return i;
}
private static void insertLink(final LinkMenuBar m, final String text,
final String historyToken, final int beforeIndex) {
m.insertItem(new LinkMenuItem(text, historyToken), beforeIndex);
}
private static void addDiffLink(final LinkMenuBar m, final String text,
final PatchScreen.TopView tv) {
m.addItem(new LinkMenuItem(text, "") {
@Override
public void go() {
if (patchScreen != null) {
patchScreen.setTopView(tv);
}
AnchorElement.as(getElement()).blur();
}
});
}
private static void addDiffLink(final LinkMenuBar m, final String text,
final PatchScreen.Type type) {
m.addItem(new LinkMenuItem(text, "") {
@Override
public void go() {
if (patchScreen != null) {
patchScreen.setTopView(PatchScreen.TopView.MAIN);
if (type == patchScreen.getPatchScreenType()) {
AnchorElement.as(getElement()).blur();
} else {
new PatchLink("", type, patchScreen).go();
}
}
}
});
}
private static void addDocLink(final LinkMenuBar m, final String text,
final String href) {
final Anchor atag = anchor(text, selfRedirect("/Documentation/" + href));
atag.setTarget("_blank");
m.add(atag);
}
private static void addExtensionLink(LinkMenuBar m, TopMenuItem item) {
if (item.getUrl().startsWith("#")
&& (item.getTarget() == null || item.getTarget().isEmpty())) {
LinkMenuItem a =
new LinkMenuItem(item.getName(), item.getUrl().substring(1));
if (item.getId() != null) {
a.getElement().setAttribute("id", item.getId());
}
m.addItem(a);
} else {
Anchor atag = anchor(item.getName(), isAbsolute(item.getUrl())
? item.getUrl()
: selfRedirect(item.getUrl()));
if (item.getTarget() != null && !item.getTarget().isEmpty()) {
atag.setTarget(item.getTarget());
}
if (item.getId() != null) {
atag.getElement().setAttribute("id", item.getId());
}
m.add(atag);
}
}
private static boolean isAbsolute(String url) {
return url.matches("^https?://.*");
}
}
| |
package org.basex.index.path;
import static org.basex.data.DataText.*;
import java.io.*;
import java.util.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.index.stats.*;
import org.basex.io.in.DataInput;
import org.basex.io.out.DataOutput;
import org.basex.util.*;
/**
* This class represents a node of the path index.
*
* @author BaseX Team 2005-20, BSD License
* @author Christian Gruen
*/
public final class PathNode {
/** Element/attribute name. */
public final short name;
/** Node kind, defined in the {@link Data} class. */
public final byte kind;
/** Parent. */
public final PathNode parent;
/** Children. */
public PathNode[] children;
/** Node kind. */
public final Stats stats;
/** Empty element flag,assigned during index construction.
* 0: no empty elements;
* 1: test flag;
* 2: element can be empty. */
private byte empty;
/**
* Empty constructor.
*/
PathNode() {
this(0, Data.DOC, null);
}
/**
* Default constructor.
* @param name id of node name
* @param kind node kind
* @param parent parent node
*/
private PathNode(final int name, final byte kind, final PathNode parent) {
children = new PathNode[0];
this.name = (short) name;
this.kind = kind;
this.parent = parent;
stats = new Stats();
}
/**
* Constructor, specifying an input stream.
* @param in input stream
* @param node parent node
* @throws IOException I/O exception
*/
PathNode(final DataInput in, final PathNode node) throws IOException {
name = (short) in.readNum();
kind = (byte) in.read();
in.readNum();
final int cl = in.readNum();
in.readDouble();
children = new PathNode[cl];
stats = new Stats(in);
parent = node;
for(int c = 0; c < cl; ++c) children[c] = new PathNode(in, this);
}
/**
* Indexes the specified name and its kind.
* @param id name id
* @param knd node kind
* @param value value (can be {@code null})
* @param meta meta data
* @return node reference
*/
PathNode index(final int id, final byte knd, final byte[] value, final MetaData meta) {
for(final PathNode child : children) {
if(child.kind == knd && child.name == id) {
child.index(value, meta);
return child;
}
}
final PathNode child = new PathNode(id, knd, this);
child.index(value, meta);
final int cl = children.length;
final PathNode[] nodes = new PathNode[cl + 1];
Array.copy(children, cl, nodes);
nodes[cl] = child;
children = nodes;
return child;
}
/**
* Indexes a value.
* @param value value (can be {@code null})
* @param meta meta data
*/
private void index(final byte[] value, final MetaData meta) {
if(value == null) {
// opening element
if(kind == Data.ELEM) {
// check if this is an empty element: set test flag
if(empty == 0) empty = 1;
// confirm that this element can be empty
else if(empty == 1) empty = 2;
}
} else {
stats.add(value, meta);
// text node: invalidate test flag of parent node
if(kind == Data.TEXT && parent.empty == 1) parent.empty = 0;
}
stats.count++;
}
/**
* Finalizes the index and writes the node to the specified output stream.
* @param out output stream
* @param meta meta data
* @throws IOException I/O exception
*/
void write(final DataOutput out, final MetaData meta) throws IOException {
out.writeNum(name);
out.write1(kind);
// legacy (required before version 7.1)
out.writeNum(0);
out.writeNum(children.length);
// legacy (required before version 7.1)
out.writeDouble(1);
// update leaf flag
boolean leaf = stats.isLeaf();
for(final PathNode child : children) {
if(child.kind == Data.TEXT) {
if(empty != 0) child.stats.add(Token.EMPTY, meta);
} else if(child.kind != Data.ATTR) {
leaf = false;
}
}
stats.setLeaf(leaf);
stats.write(out);
for(final PathNode child : children) child.write(out, meta);
}
/**
* Recursively adds the node and its descendants to the specified list.
* @param nodes node list
*/
void addDesc(final ArrayList<PathNode> nodes) {
nodes.add(this);
for(final PathNode child : children) child.addDesc(nodes);
}
/**
* Recursively adds the node and its descendants to the specified list with the specified name.
* @param nodes node list
* @param nm name id
*/
void addDesc(final ArrayList<PathNode> nodes, final int nm) {
if(kind == Data.ELEM && nm == name) nodes.add(this);
for(final PathNode child : children) child.addDesc(nodes, nm);
}
/**
* Returns a readable representation of this node.
* @param data data reference
* @return completions
*/
public byte[] token(final Data data) {
switch(kind) {
case Data.ELEM: return data.elemNames.key(name);
case Data.ATTR: return Token.concat(ATT, data.attrNames.key(name));
case Data.TEXT: return TEXT;
case Data.COMM: return COMMENT;
case Data.PI: return PI;
default: return Token.EMPTY;
}
}
/**
* Returns the level of the path node.
* @return level
*/
public int level() {
PathNode pn = parent;
int c = 0;
while(pn != null) {
pn = pn.parent;
++c;
}
return c;
}
/**
* Returns a string representation of a path index node.
* @param data data reference
* @param level level
* @return string representation
*/
byte[] info(final Data data, final int level) {
final TokenBuilder tb = new TokenBuilder();
if(level != 0) tb.add(Text.NL);
for(int i = 0; i < level << 1; ++i) tb.add(' ');
switch(kind) {
case Data.DOC: tb.add(DOC); break;
case Data.ELEM: tb.add(data.elemNames.key(name)); break;
case Data.TEXT: tb.add(TEXT); break;
case Data.ATTR: tb.add(ATT); tb.add(data.attrNames.key(name)); break;
case Data.COMM: tb.add(COMMENT); break;
case Data.PI: tb.add(PI); break;
}
tb.add(": " + stats);
for(final PathNode p : children) tb.add(p.info(data, level + 1));
return tb.finish();
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.budgets.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Request of CreateBudget
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateBudgetRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The <code>accountId</code> that is associated with the budget.
* </p>
*/
private String accountId;
/**
* <p>
* The budget object that you want to create.
* </p>
*/
private Budget budget;
/**
* <p>
* A notification that you want to associate with a budget. A budget can have up to five notifications, and each
* notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications and
* subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and subscribers
* for you.
* </p>
*/
private java.util.List<NotificationWithSubscribers> notificationsWithSubscribers;
/**
* <p>
* The <code>accountId</code> that is associated with the budget.
* </p>
*
* @param accountId
* The <code>accountId</code> that is associated with the budget.
*/
public void setAccountId(String accountId) {
this.accountId = accountId;
}
/**
* <p>
* The <code>accountId</code> that is associated with the budget.
* </p>
*
* @return The <code>accountId</code> that is associated with the budget.
*/
public String getAccountId() {
return this.accountId;
}
/**
* <p>
* The <code>accountId</code> that is associated with the budget.
* </p>
*
* @param accountId
* The <code>accountId</code> that is associated with the budget.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateBudgetRequest withAccountId(String accountId) {
setAccountId(accountId);
return this;
}
/**
* <p>
* The budget object that you want to create.
* </p>
*
* @param budget
* The budget object that you want to create.
*/
public void setBudget(Budget budget) {
this.budget = budget;
}
/**
* <p>
* The budget object that you want to create.
* </p>
*
* @return The budget object that you want to create.
*/
public Budget getBudget() {
return this.budget;
}
/**
* <p>
* The budget object that you want to create.
* </p>
*
* @param budget
* The budget object that you want to create.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateBudgetRequest withBudget(Budget budget) {
setBudget(budget);
return this;
}
/**
* <p>
* A notification that you want to associate with a budget. A budget can have up to five notifications, and each
* notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications and
* subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and subscribers
* for you.
* </p>
*
* @return A notification that you want to associate with a budget. A budget can have up to five notifications, and
* each notification can have one SNS subscriber and up to 10 email subscribers. If you include
* notifications and subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the
* notifications and subscribers for you.
*/
public java.util.List<NotificationWithSubscribers> getNotificationsWithSubscribers() {
return notificationsWithSubscribers;
}
/**
* <p>
* A notification that you want to associate with a budget. A budget can have up to five notifications, and each
* notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications and
* subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and subscribers
* for you.
* </p>
*
* @param notificationsWithSubscribers
* A notification that you want to associate with a budget. A budget can have up to five notifications, and
* each notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications
* and subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and
* subscribers for you.
*/
public void setNotificationsWithSubscribers(java.util.Collection<NotificationWithSubscribers> notificationsWithSubscribers) {
if (notificationsWithSubscribers == null) {
this.notificationsWithSubscribers = null;
return;
}
this.notificationsWithSubscribers = new java.util.ArrayList<NotificationWithSubscribers>(notificationsWithSubscribers);
}
/**
* <p>
* A notification that you want to associate with a budget. A budget can have up to five notifications, and each
* notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications and
* subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and subscribers
* for you.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setNotificationsWithSubscribers(java.util.Collection)} or
* {@link #withNotificationsWithSubscribers(java.util.Collection)} if you want to override the existing values.
* </p>
*
* @param notificationsWithSubscribers
* A notification that you want to associate with a budget. A budget can have up to five notifications, and
* each notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications
* and subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and
* subscribers for you.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateBudgetRequest withNotificationsWithSubscribers(NotificationWithSubscribers... notificationsWithSubscribers) {
if (this.notificationsWithSubscribers == null) {
setNotificationsWithSubscribers(new java.util.ArrayList<NotificationWithSubscribers>(notificationsWithSubscribers.length));
}
for (NotificationWithSubscribers ele : notificationsWithSubscribers) {
this.notificationsWithSubscribers.add(ele);
}
return this;
}
/**
* <p>
* A notification that you want to associate with a budget. A budget can have up to five notifications, and each
* notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications and
* subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and subscribers
* for you.
* </p>
*
* @param notificationsWithSubscribers
* A notification that you want to associate with a budget. A budget can have up to five notifications, and
* each notification can have one SNS subscriber and up to 10 email subscribers. If you include notifications
* and subscribers in your <code>CreateBudget</code> call, Amazon Web Services creates the notifications and
* subscribers for you.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateBudgetRequest withNotificationsWithSubscribers(java.util.Collection<NotificationWithSubscribers> notificationsWithSubscribers) {
setNotificationsWithSubscribers(notificationsWithSubscribers);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAccountId() != null)
sb.append("AccountId: ").append(getAccountId()).append(",");
if (getBudget() != null)
sb.append("Budget: ").append(getBudget()).append(",");
if (getNotificationsWithSubscribers() != null)
sb.append("NotificationsWithSubscribers: ").append(getNotificationsWithSubscribers());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateBudgetRequest == false)
return false;
CreateBudgetRequest other = (CreateBudgetRequest) obj;
if (other.getAccountId() == null ^ this.getAccountId() == null)
return false;
if (other.getAccountId() != null && other.getAccountId().equals(this.getAccountId()) == false)
return false;
if (other.getBudget() == null ^ this.getBudget() == null)
return false;
if (other.getBudget() != null && other.getBudget().equals(this.getBudget()) == false)
return false;
if (other.getNotificationsWithSubscribers() == null ^ this.getNotificationsWithSubscribers() == null)
return false;
if (other.getNotificationsWithSubscribers() != null && other.getNotificationsWithSubscribers().equals(this.getNotificationsWithSubscribers()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAccountId() == null) ? 0 : getAccountId().hashCode());
hashCode = prime * hashCode + ((getBudget() == null) ? 0 : getBudget().hashCode());
hashCode = prime * hashCode + ((getNotificationsWithSubscribers() == null) ? 0 : getNotificationsWithSubscribers().hashCode());
return hashCode;
}
@Override
public CreateBudgetRequest clone() {
return (CreateBudgetRequest) super.clone();
}
}
| |
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class StdBanker extends StdShopKeeper implements Banker
{
@Override
public String ID()
{
return "StdBanker";
}
protected double coinInterest=-0.000;
protected double itemInterest=-0.0001;
protected double loanInterest=0.01;
protected static Hashtable<String,Long> bankTimes=new Hashtable<String,Long>();
public StdBanker()
{
super();
username="a banker";
setDescription("He\\`s pleased to be of assistance.");
setDisplayText("A banker is waiting to serve you.");
CMLib.factions().setAlignment(this,Faction.Align.GOOD);
setMoney(0);
whatIsSoldMask=ShopKeeper.DEAL_BANKER;
basePhyStats.setWeight(150);
setWimpHitPoint(0);
baseCharStats().setStat(CharStats.STAT_INTELLIGENCE,16);
baseCharStats().setStat(CharStats.STAT_CHARISMA,25);
basePhyStats().setArmor(0);
baseState.setHitPoints(1000);
recoverMaxState();
resetToMaxState();
recoverPhyStats();
recoverCharStats();
}
@Override
public void addSoldType(int mask)
{
setWhatIsSoldMask(CMath.abs(mask));
}
@Override
public void setWhatIsSoldMask(long newSellCode)
{
super.setWhatIsSoldMask(newSellCode);
if(!isSold(ShopKeeper.DEAL_CLANBANKER))
whatIsSoldMask=ShopKeeper.DEAL_BANKER;
else
whatIsSoldMask=ShopKeeper.DEAL_CLANBANKER;
}
@Override
public String bankChain()
{
return text();
}
@Override
public void setBankChain(String name)
{
setMiscText(name);
}
@Override
public void addDepositInventory(String depositorName, Item item, Item container)
{
final String classID;
if((item instanceof Coins)&&(container == null))
classID="COINS";
else
classID=item.ID();
CMLib.catalog().updateCatalogIntegrity(item);
final String key=""+item+item.hashCode();
if(container != null)
{
final String containerKey=""+container+container.hashCode();
CMLib.database().DBCreateData(depositorName,bankChain(),key,classID+";CONTAINER="+containerKey+";"+CMLib.coffeeMaker().getPropertiesStr(item,true));
}
else
CMLib.database().DBCreateData(depositorName,bankChain(),key,classID+";"+CMLib.coffeeMaker().getPropertiesStr(item,true));
}
protected Pair<Item,String> makeItemContainer(String data)
{
int x=data.indexOf(';');
if(x<0)
return null;
Item I=null;
if(data.substring(0,x).equals("COINS"))
I=CMClass.getItem("StdCoins");
else
I=CMClass.getItem(data.substring(0,x));
if(I!=null)
{
String container="";
String xml = data.substring(x+1);
if(xml.startsWith("CONTAINER="))
{
x=xml.indexOf(';');
if(x>0)
{
container=xml.substring(10,x);
xml=xml.substring(x+1);
}
}
CMLib.coffeeMaker().setPropertiesStr(I,xml,true);
if((I instanceof Coins)
&&(((Coins)I).getDenomination()==0.0)
&&(((Coins)I).getNumberOfCoins()>0))
((Coins)I).setDenomination(1.0);
I.recoverPhyStats();
I.text();
return new Pair<Item,String>(I,container);
}
return null;
}
protected List<Item> findDeleteRecursiveDepositInventoryByContainerKey(Container C, List<PlayerData> rawInventoryV, String key)
{
final List<Item> inventory=new LinkedList<Item>();
for(int v=rawInventoryV.size()-1;v>=0;v--)
{
final DatabaseEngine.PlayerData PD=rawInventoryV.get(v);
final int IDx=PD.xml().indexOf(';');
if(IDx>0)
{
if(PD.xml().substring(IDx+1).startsWith("CONTAINER="+key+";"))
{
Item I=makeItemContainer(PD.xml()).first;
I.setContainer(C);
inventory.add(I);
rawInventoryV.remove(v);
if(I instanceof Container)
inventory.addAll(findDeleteRecursiveDepositInventoryByContainerKey((Container)I,rawInventoryV,PD.key()));
CMLib.database().DBDeleteData(PD.who(),PD.section(),PD.key());
}
}
}
return inventory;
}
@Override
public List<Item> delDepositInventory(String depositorName, Item likeItem)
{
final List<PlayerData> rawInventoryV=getRawPDDepositInventory(depositorName);
final List<Item> items = new ArrayList<Item>();
if(likeItem.container()==null)
{
if(likeItem instanceof Coins)
{
for(int v=rawInventoryV.size()-1;v>=0;v--)
{
final DatabaseEngine.PlayerData PD=rawInventoryV.get(v);
if(PD.xml().startsWith("COINS;"))
{
CMLib.database().DBDeleteData(PD.who(),PD.section(),PD.key());
items.add(makeItemContainer(PD.xml()).first);
}
}
}
else
{
for(int v=rawInventoryV.size()-1;v>=0;v--)
{
final DatabaseEngine.PlayerData PD=rawInventoryV.get(v);
if(PD.xml().startsWith(likeItem.ID()+";") && (!PD.xml().startsWith(likeItem.ID()+";CONTAINER=")))
{
final Pair<Item,String> pI=makeItemContainer(PD.xml());
if((pI!=null) && likeItem.sameAs(pI.first))
{
pI.first.setContainer(null);
if(pI.first instanceof Container)
{
items.add(pI.first);
final Hashtable<String,List<DatabaseEngine.PlayerData>> pairings=new Hashtable<String,List<DatabaseEngine.PlayerData>>();
for(final PlayerData PDp : rawInventoryV)
{
final int IDx=PDp.xml().indexOf(';');
if(IDx>0)
{
final String subXML=PDp.xml().substring(IDx+1);
if(subXML.startsWith("CONTAINER="))
{
int x=subXML.indexOf(';');
if(x>0)
{
final String contKey=subXML.substring(10,x);
if(!pairings.containsKey(contKey))
pairings.put(contKey, new LinkedList<DatabaseEngine.PlayerData>());
pairings.get(contKey).add(PDp);
}
}
}
}
CMLib.database().DBDeleteData(PD.who(),PD.section(),PD.key());
final Map<String,Container> containerMap=new Hashtable<String,Container>();
containerMap.put(PD.key(), (Container)pI.first);
while(containerMap.size()>0)
{
final String contKey=containerMap.keySet().iterator().next();
final Container container=containerMap.remove(contKey);
List<DatabaseEngine.PlayerData> contents=pairings.get(contKey);
if(contents != null)
{
for(DatabaseEngine.PlayerData PDi : contents)
{
Pair<Item,String> pairI=makeItemContainer(PDi.xml());
CMLib.database().DBDeleteData(PDi.who(),PDi.section(),PDi.key());
pairI.first.setContainer(container);
items.add(pairI.first);
if(pairI.first instanceof Container)
containerMap.put(PDi.key(), (Container)pairI.first);
}
}
}
}
else
{
items.add(pI.first);
CMLib.database().DBDeleteData(PD.who(),PD.section(),PD.key());
}
break;
}
}
}
}
}
return items;
}
@Override
public void delAllDeposits(String depositorName)
{
CMLib.database().DBDeleteData(depositorName,bankChain());
}
@Override
public int numberDeposited(String depositorName)
{
return getRawPDDepositInventory(depositorName).size();
}
@Override
public List<Item> getDepositedItems(String depositorName)
{
if((depositorName==null)||(depositorName.length()==0))
return new ArrayList<Item>();
final List<Item> items=new Vector<Item>();
final Hashtable<String,Pair<Item,String>> pairings=new Hashtable<String,Pair<Item,String>>();
for(final PlayerData PD : getRawPDDepositInventory(depositorName))
{
final Pair<Item,String> pair=makeItemContainer(PD.xml());
if(pair!=null)
pairings.put(PD.key(), pair);
}
for(final Pair<Item,String> pair : pairings.values())
{
if(pair.second.length()>0)
{
Pair<Item,String> otherPair = pairings.get(pair.second);
if((otherPair != null)&&(otherPair.first instanceof Container))
pair.first.setContainer((Container)otherPair.first);
}
items.add(pair.first);
}
return items;
}
protected List<PlayerData> getRawPDDepositInventory(String depositorName)
{
return CMLib.database().DBReadData(depositorName,bankChain());
}
@Override
public List<String> getAccountNames()
{
final List<PlayerData> V=CMLib.database().DBReadData(bankChain());
final HashSet<String> h=new HashSet<String>();
final Vector<String> mine=new Vector<String>();
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData V2=V.get(v);
if(!h.contains(V2.who()))
{
h.add(V2.who());
mine.addElement(V2.who());
}
}
return mine;
}
protected void bankLedger(String depositorName, String msg)
{
final String date=CMLib.utensils().getFormattedDate(this);
CMLib.beanCounter().bankLedger(bankChain(),depositorName,date+": "+msg);
}
@Override
public Item findDepositInventory(String depositorName, String itemName)
{
final List<PlayerData> V=getRawPDDepositInventory(depositorName);
if(CMath.s_int(itemName)>0)
{
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData PD=V.get(v);
if(PD.xml().startsWith("COINS;"))
return makeItemContainer(PD.xml()).first;
}
}
else
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData PD=V.get(v);
if(PD.xml().lastIndexOf(";CONTAINER=",81)<0)
{
final Pair<Item,String> pair=makeItemContainer(PD.xml());
if(pair!=null)
{
if(CMLib.english().containsString(pair.first.Name(),itemName))
return pair.first;
pair.first.destroy();
}
}
}
return null;
}
public long timeInterval()
{
return (location().getArea().getTimeObj().getHoursInDay())
*CMProps.getMillisPerMudHour()
*location().getArea().getTimeObj().getDaysInMonth();
}
@Override
public void setCoinInterest(double interest)
{
coinInterest = interest;
}
@Override
public void setItemInterest(double interest)
{
itemInterest = interest;
}
@Override
public double getCoinInterest()
{
return coinInterest;
}
@Override
public double getItemInterest()
{
return itemInterest;
}
@Override
public void setLoanInterest(double interest)
{
loanInterest = interest;
}
@Override
public double getLoanInterest()
{
return loanInterest;
}
@Override
public MoneyLibrary.DebtItem getDebtInfo(String depositorName)
{
final Vector<MoneyLibrary.DebtItem> debt=CMLib.beanCounter().getDebtOwed(bankChain());
if(depositorName.length()==0)
return null;
for(int d=0;d<debt.size();d++)
{
if(debt.elementAt(d).debtor().equalsIgnoreCase(depositorName))
return debt.elementAt(d);
}
return null;
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
return true;
try
{
if(tickID==Tickable.TICKID_MOB)
{
boolean proceed=false;
// handle interest by watching the days go by...
// put stuff up for sale if the account runs out
synchronized(bankChain().intern())
{
Long L=bankTimes.get(bankChain());
long timeInterval=1;
if(((L==null)||(L.longValue()<System.currentTimeMillis()))
&&(location!=null)
&&(location.getArea()!=null)
&&(location.getArea().getTimeObj()!=null)
&&(CMLib.flags().isInTheGame(this,true)))
{
timeInterval=timeInterval();
L=Long.valueOf(System.currentTimeMillis()+timeInterval);
proceed=true;
bankTimes.remove(bankChain());
bankTimes.put(bankChain(),L);
}
if(proceed)
{
final List<PlayerData> bankDataV=CMLib.database().DBReadData(bankChain());
final Vector<String> userNames=new Vector<String>();
for(int v=0;v<bankDataV.size();v++)
{
final DatabaseEngine.PlayerData dat=bankDataV.get(v);
final String name=dat.who();
if(!userNames.contains(name))
{
if(!CMLib.players().playerExists(name))
{
if((CMLib.clans().getClan(name))==null)
delAllDeposits(name);
else
userNames.addElement(name);
}
else
userNames.addElement(name);
}
}
final Vector<MoneyLibrary.DebtItem> debts=CMLib.beanCounter().getDebtOwed(bankChain());
for(int u=0;u<userNames.size();u++)
{
final String name=userNames.elementAt(u);
Coins coinItem=null;
int totalValue=0;
final List<Item> items=getDepositedItems(name);
for(int v=0;v<items.size();v++)
{
final Item I=items.get(v);
if(I instanceof Coins)
coinItem=(Coins)I;
else
if(itemInterest!=0.0)
totalValue+=I.value();
}
double newBalance=0.0;
if(coinItem!=null)
newBalance=coinItem.getTotalValue();
newBalance+=CMath.mul(newBalance,coinInterest);
if(totalValue>0)
newBalance+=CMath.mul(totalValue,itemInterest);
for(int d=debts.size()-1;d>=0;d--)
{
final MoneyLibrary.DebtItem debtItem=debts.elementAt(d);
final String debtor=debtItem.debtor();
if(debtor.equalsIgnoreCase(name))
{
final long debtDueAt=debtItem.due();
final double intRate=debtItem.interest();
final double dueAmount=debtItem.amt();
final String reason=debtItem.reason();
final double intDue=CMath.mul(intRate,dueAmount);
final long timeRemaining=debtDueAt-System.currentTimeMillis();
if((timeRemaining<0)&&(newBalance<((dueAmount)+intDue)))
newBalance=-1.0;
else
{
final double amtDueNow=(timeRemaining<0)?(dueAmount+intDue):CMath.div((dueAmount+intDue),(timeRemaining/timeInterval));
if(newBalance>=amtDueNow)
{
CMLib.beanCounter().bankLedger(bankChain(),name,CMLib.utensils().getFormattedDate(this)+": Withdrawal of "+CMLib.beanCounter().nameCurrencyShort(this,amtDueNow)+": Loan payment made.");
CMLib.beanCounter().adjustDebt(debtor,bankChain(),intDue-amtDueNow,reason,intRate,debtDueAt);
newBalance-=amtDueNow;
}
else
CMLib.beanCounter().adjustDebt(debtor,bankChain(),intDue,reason,intRate,debtDueAt);
}
debts.removeElementAt(d);
}
}
if(newBalance<0)
{
for(int v=0;v<items.size();v++)
{
final Item I=items.get(v);
if((I instanceof LandTitle)&&(((LandTitle)I).getOwnerName().length()>0))
{
((LandTitle)I).setOwnerName("");
((LandTitle)I).updateTitle();
((LandTitle)I).updateLot(null);
}
if(!(I instanceof Coins))
getShop().addStoreInventory(I);
}
delAllDeposits(name);
CMLib.beanCounter().delAllDebt(name,bankChain());
}
else
if((coinItem==null)||(newBalance!=coinItem.getTotalValue()))
{
if(coinItem!=null)
{
if(newBalance>coinItem.getTotalValue())
CMLib.beanCounter().bankLedger(bankChain(),name,CMLib.utensils().getFormattedDate(this)+": Deposit of "+CMLib.beanCounter().nameCurrencyShort(this,newBalance-coinItem.getTotalValue())+": Interest paid.");
else
CMLib.beanCounter().bankLedger(bankChain(),name,CMLib.utensils().getFormattedDate(this)+": Withdrawl of "+CMLib.beanCounter().nameCurrencyShort(this,coinItem.getTotalValue()-newBalance)+": Interest charged.");
delDepositInventory(name,coinItem);
}
final String currency=CMLib.beanCounter().getCurrency(this);
coinItem=CMLib.beanCounter().makeBestCurrency(currency,newBalance);
if(coinItem!=null)
addDepositInventory(name,coinItem,null);
}
for(int v=0;v<items.size();v++)
{
final Item I=items.get(v);
if(I!=null)
I.destroy();
}
}
for(int d=debts.size()-1;d>=0;d--)
CMLib.beanCounter().delAllDebt(debts.elementAt(d).debtor(),bankChain());
}
}
}
}catch(final Exception e){Log.errOut("StdBanker",e);}
return true;
}
@Override
public double getBalance(String depositorName)
{
final Item old=findDepositInventory(depositorName,""+Integer.MAX_VALUE);
if((old!=null)&&(old instanceof Coins))
return ((Coins)old).getTotalValue();
return 0;
}
@Override
public double totalItemsWorth(String depositorName)
{
final List<Item> V=getDepositedItems(depositorName);
double min=0;
for(int v=0;v<V.size();v++)
{
final Item I=V.get(v);
if(!(I instanceof Coins))
min+=I.value();
I.destroy();
}
return min;
}
@Override
public String getBankClientName(MOB mob, Clan.Function func, boolean checked)
{
if(isSold(ShopKeeper.DEAL_CLANBANKER))
{
final Pair<Clan,Integer> clanPair=CMLib.clans().findPrivilegedClan(mob, func);
if(clanPair!=null)
return clanPair.first.clanID();
else
if(checked)
{
if(mob.clans().iterator().hasNext())
{
CMLib.commands().postSay(this,mob,L("I'm sorry, you aren't authorized by your clan to do that."),true,false);
return null;
}
else
{
CMLib.commands().postSay(this,mob,L("I'm sorry, I only deal with clans."),true,false);
return null;
}
}
}
return mob.Name();
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
final MOB mob=msg.source();
if(msg.amITarget(this))
{
switch(msg.targetMinor())
{
case CMMsg.TYP_GIVE:
case CMMsg.TYP_DEPOSIT:
if(CMLib.flags().isAliveAwakeMobileUnbound(mob,true))
{
String depositorName=getBankClientName(msg.source(),Clan.Function.DEPOSIT,false);
//if(msg.tool() instanceof Container)
// ((Container)msg.tool()).emptyPlease(true);
CMMsg msg2=CMClass.getMsg(msg.source(),msg.tool(),null,CMMsg.MSG_DROP|CMMsg.MASK_INTERMSG,null,CMMsg.MSG_DROP|CMMsg.MASK_INTERMSG,null,CMMsg.MSG_DROP|CMMsg.MASK_INTERMSG,null);
location().send(this,msg2);
msg2=CMClass.getMsg((MOB)msg.target(),msg.tool(),null,CMMsg.MSG_GET|CMMsg.MASK_INTERMSG,null,CMMsg.MSG_GET|CMMsg.MASK_INTERMSG,null,CMMsg.MSG_GET|CMMsg.MASK_INTERMSG,null);
location().send(this,msg2);
if(msg.tool() instanceof Coins)
{
final Coins older=(Coins)msg.tool();
double newValue=older.getTotalValue();
Item oldCoins=findDepositInventory(depositorName,""+Integer.MAX_VALUE);
if((oldCoins==null)
&&(!isSold(ShopKeeper.DEAL_CLANBANKER))
&&(msg.source().isMarriedToLiege()))
{
oldCoins=findDepositInventory(msg.source().getLiegeID(),""+Integer.MAX_VALUE);
if(oldCoins!=null)
{
final MOB owner=CMLib.players().getPlayer(msg.source().getLiegeID());
if(owner != null)
depositorName=owner.Name();
}
}
if((oldCoins!=null)&&(oldCoins instanceof Coins))
newValue+=((Coins)oldCoins).getTotalValue();
final Coins coins=CMLib.beanCounter().makeBestCurrency(CMLib.beanCounter().getCurrency(this),newValue);
bankLedger(depositorName,"Deposit of "+CMLib.beanCounter().nameCurrencyShort(this,newValue)+": "+msg.source().Name());
if(oldCoins!=null)
delDepositInventory(depositorName,oldCoins);
if(coins!=null)
addDepositInventory(depositorName,coins,null);
if(isSold(ShopKeeper.DEAL_CLANBANKER))
CMLib.commands().postSay(this,mob,L("Ok, @x1 now has a balance of @x2.",CMStrings.capitalizeFirstLetter(depositorName),CMLib.beanCounter().nameCurrencyLong(this,getBalance(depositorName))),true,false);
else
CMLib.commands().postSay(this,mob,L("Ok, your new balance is @x1.",CMLib.beanCounter().nameCurrencyLong(this,getBalance(depositorName))),true,false);
recoverPhyStats();
if(msg.sourceMessage()!=null)
msg.setSourceMessage(CMStrings.replaceAll(msg.sourceMessage(),"<O-NAME>",msg.tool().name()));
if(msg.targetMessage()!=null)
msg.setTargetMessage(CMStrings.replaceAll(msg.targetMessage(),"<O-NAME>",msg.tool().name()));
if(msg.othersMessage()!=null)
msg.setOthersMessage(CMStrings.replaceAll(msg.othersMessage(),"<O-NAME>",msg.tool().name()));
((Coins)msg.tool()).setNumberOfCoins(0); // prevents banker from accumulating wealth
final double riches=CMLib.beanCounter().getTotalAbsoluteNativeValue(this);
if(riches>0.0)
CMLib.beanCounter().subtractMoney(this,riches);
}
else
{
List<Item> items;
if(msg.tool() instanceof Container)
items=CMLib.utensils().deepCopyOf((Item)msg.tool());
else
items=new XVector<Item>((Item)msg.tool().copyOf());
for(Item I : items)
{
if(!I.amDestroyed())
{
addDepositInventory(depositorName,I,I.container());
}
else
{
CMLib.commands().postSay(this,mob,L("Whoops! Where'd it go?"),true,false);
return;
}
}
CMLib.commands().postSay(this,mob,L("Thank you, @x1 is safe with us.",items.get(0).name()),true,false);
((Item)msg.tool()).destroy();
}
}
return;
case CMMsg.TYP_BORROW:
if(CMLib.flags().isAliveAwakeMobileUnbound(mob,true))
{
final Item old=(Item)msg.tool();
if(old instanceof Coins)
{
final String borrowerName=getBankClientName(msg.source(),Clan.Function.WITHDRAW,false);
bankLedger(borrowerName,"Loan of "+old.Name()+": "+msg.source().Name());
addItem(old);
final double amt=((Coins)old).getTotalValue();
final CMMsg newMsg=CMClass.getMsg(this,msg.source(),old,CMMsg.MSG_GIVE,L("<S-NAME> give(s) <O-NAME> to <T-NAMESELF>."));
if(location().okMessage(this,newMsg))
{
location().send(this,newMsg);
((Coins)old).putCoinsBack();
}
else
CMLib.commands().postDrop(this,old,true,false,false);
final double interestRate=getLoanInterest();
int months=2;
while((months<(location().getArea().getTimeObj().getMonthsInYear()*10))
&&(CMath.div(amt,months)>250.0)) months++;
final long dueAt=System.currentTimeMillis()+(timeInterval()*months);
CMLib.beanCounter().adjustDebt(borrowerName,bankChain(),amt,"Bank Loan",interestRate,dueAt);
}
}
break;
case CMMsg.TYP_WITHDRAW:
if(CMLib.flags().isAliveAwakeMobileUnbound(mob,true))
{
String withdrawerName=getBankClientName(msg.source(),Clan.Function.WITHDRAW,false);
final Item old=(Item)msg.tool();
if((old instanceof Coins)&&(old.container()==null))
{
Item depositInventoryItem=findDepositInventory(withdrawerName,""+Integer.MAX_VALUE);
if((!isSold(ShopKeeper.DEAL_CLANBANKER))
&&(msg.source().isMarriedToLiege())
&&((depositInventoryItem==null)
||((depositInventoryItem instanceof Coins)
&&(((Coins)depositInventoryItem).getTotalValue()<((Coins)old).getTotalValue()))))
{
final Item item2=findDepositInventory(msg.source().getLiegeID(),""+Integer.MAX_VALUE);
if((item2!=null)&&(item2 instanceof Coins)&&(((Coins)item2).getTotalValue()>=((Coins)old).getTotalValue()))
{
depositInventoryItem=item2;
final MOB owner=CMLib.players().getPlayer(msg.source().getLiegeID());
if(owner!=null)
withdrawerName=owner.Name();
}
}
if((depositInventoryItem instanceof Coins)
&&(old instanceof Coins)
&&(((Coins)depositInventoryItem).getTotalValue()>=((Coins)old).getTotalValue()))
{
final Coins coins=CMLib.beanCounter().makeBestCurrency(this,((Coins)depositInventoryItem).getTotalValue()-((Coins)old).getTotalValue());
bankLedger(withdrawerName,"Withdrawl of "+CMLib.beanCounter().nameCurrencyShort(this,((Coins)old).getTotalValue())+": "+msg.source().Name());
delDepositInventory(withdrawerName,depositInventoryItem);
addItem(old);
final CMMsg newMsg=CMClass.getMsg(this,msg.source(),old,CMMsg.MSG_GIVE,L("<S-NAME> give(s) <O-NAME> to <T-NAMESELF>."));
if(location().okMessage(this,newMsg))
{
location().send(this,newMsg);
((Coins)old).putCoinsBack();
}
else
CMLib.commands().postDrop(this,old,true,false,false);
if((coins==null)||(coins.getNumberOfCoins()<=0))
{
if(isSold(ShopKeeper.DEAL_CLANBANKER))
CMLib.commands().postSay(this,mob,L("I have closed the account for @x1. Thanks for your business.",CMStrings.capitalizeFirstLetter(withdrawerName)),true,false);
else
CMLib.commands().postSay(this,mob,L("I have closed that account. Thanks for your business."),true,false);
return;
}
addDepositInventory(withdrawerName,coins,null);
if(isSold(ShopKeeper.DEAL_CLANBANKER))
CMLib.commands().postSay(this,mob,L("Ok, @x1 now has a balance of @x2.",CMStrings.capitalizeFirstLetter(withdrawerName),CMLib.beanCounter().nameCurrencyLong(this,coins.getTotalValue())),true,false);
else
CMLib.commands().postSay(this,mob,L("Ok, your new balance is @x1.",CMLib.beanCounter().nameCurrencyLong(this,coins.getTotalValue())),true,false);
}
else
if(depositInventoryItem!=null)
CMLib.commands().postSay(this,mob,L("But, your balance is @x1.",CMLib.beanCounter().nameCurrencyLong(this,((Coins)depositInventoryItem).getTotalValue())),true,false);
}
else
{
List<Item> deletedItems=delDepositInventory(withdrawerName,old);
if((deletedItems.size()==0)
&&(!isSold(ShopKeeper.DEAL_CLANBANKER))
&&(msg.source().isMarriedToLiege()))
deletedItems = delDepositInventory(msg.source().getLiegeID(),old);
CMLib.commands().postSay(this,mob,L("Thank you for your trust."),true,false);
for(Item I : deletedItems)
{
if((I instanceof Coins)&&(I.container()!=null))
{
mob.addItem(I);
}
else
{
final Container C=I.container();
if(location()!=null)
location().addItem(I,ItemPossessor.Expire.Player_Drop);
final CMMsg msg2=CMClass.getMsg(mob,I,this,CMMsg.MSG_GET,null);
if(location().okMessage(mob,msg2))
{
location().send(mob,msg2);
I.setContainer(C);
}
}
}
}
}
return;
case CMMsg.TYP_VALUE:
case CMMsg.TYP_SELL:
case CMMsg.TYP_VIEW:
super.executeMsg(myHost,msg);
return;
case CMMsg.TYP_BUY:
super.executeMsg(myHost,msg);
return;
case CMMsg.TYP_LIST:
{
super.executeMsg(myHost,msg);
if(CMLib.flags().isAliveAwakeMobileUnbound(mob,true))
{
final String listerName=getBankClientName(msg.source(),Clan.Function.DEPOSIT_LIST,false);
List<Item> V=null;
if(isSold(ShopKeeper.DEAL_CLANBANKER))
V=getDepositedItems(listerName);
else
{
V=getDepositedItems(listerName);
if(mob.isMarriedToLiege())
{
final List<Item> V2=getDepositedItems(mob.getLiegeID());
if((V2!=null)&&(V2.size()>0))
V.addAll(V2);
}
}
for(int v=V.size()-1;v>=0;v--)
{
if(V.get(v) instanceof LandTitle)
{
final LandTitle L=(LandTitle)V.get(v);
if(L.getOwnerObject()==null)
{
delDepositInventory(listerName,(Item)L);
V.remove(L);
}
}
}
final int COL_LEN=CMLib.lister().fixColWidth(34.0,mob);
StringBuffer str=new StringBuffer("");
str.append(L("\n\rAccount balance at '@x1'.\n\r",bankChain()));
final String c="^x[Item ] ";
str.append(c+c+"^.^N\n\r");
int colNum=0;
boolean otherThanCoins=false;
for(int i=0;i<V.size();i++)
{
final Item I=V.get(i);
if((!(I instanceof Coins))&&(I.container()==null))
{
otherThanCoins=true;
String col=null;
col="["+CMStrings.padRight(I.name(mob),COL_LEN)+"] ";
if((++colNum)>2)
{
str.append("\n\r");
colNum=1;
}
str.append(col);
}
}
if(!otherThanCoins)
str=new StringBuffer("\n\r^N");
else
str.append("\n\r\n\r");
final double balance=getBalance(listerName);
if(balance>0)
{
if(isSold(ShopKeeper.DEAL_CLANBANKER))
str.append(CMStrings.capitalizeFirstLetter(listerName)+" has a balance of ^H"+CMLib.beanCounter().nameCurrencyLong(this,balance)+"^?.");
else
str.append("Your balance is ^H"+CMLib.beanCounter().nameCurrencyLong(this,balance)+"^?.");
}
final Vector<MoneyLibrary.DebtItem> debts=CMLib.beanCounter().getDebt(listerName,bankChain());
if(debts!=null)
{
for(int d=0;d<debts.size();d++)
{
final MoneyLibrary.DebtItem debt=debts.elementAt(d);
final long debtDueAt=debt.due();
final double intRate=debt.interest();
final double dueAmount=debt.amt();
final long timeRemaining=debtDueAt-System.currentTimeMillis();
if(timeRemaining>0)
str.append(L("\n\r@x1 owe ^H@x2^? in debt.\n\rMonthly interest is @x3%. The loan must be paid in full in @x4 months.",((isSold(ShopKeeper.DEAL_CLANBANKER))?CMStrings.capitalizeFirstLetter(listerName):L("You")),CMLib.beanCounter().nameCurrencyLong(this,dueAmount),""+(intRate*100.0),""+(timeRemaining/timeInterval())));
}
}
if(coinInterest!=0.0)
{
final double cci=CMath.mul(Math.abs(coinInterest),100.0);
final String ci=((coinInterest>0.0)?"pay ":"charge ")+cci+"% interest ";
str.append(L("\n\rThey @x1monthly on money deposited here.",ci));
}
if(itemInterest!=0.0)
{
final double cci=CMath.mul(Math.abs(itemInterest),100.0);
final String ci=((itemInterest>0.0)?"pay ":"charge ")+cci+"% interest ";
str.append(L("\n\rThey @x1monthly on items deposited here.",ci));
}
mob.tell(str.toString()+"^T");
for(int i=0;i<V.size();i++)
{
final Item I=V.get(i);
if(I!=null)
I.destroy();
}
}
return;
}
default:
break;
}
}
else
if(msg.sourceMinor()==CMMsg.TYP_RETIRE)
delAllDeposits(msg.source().Name());
super.executeMsg(myHost,msg);
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
final MOB mob=msg.source();
if(msg.amITarget(this))
{
switch(msg.targetMinor())
{
case CMMsg.TYP_GIVE:
case CMMsg.TYP_DEPOSIT:
{
if(!CMLib.coffeeShops().ignoreIfNecessary(msg.source(),finalIgnoreMask(),this))
return false;
if(msg.tool()==null)
return false;
final String listerName=getBankClientName(msg.source(),Clan.Function.DEPOSIT,true);
if(listerName==null)
return false;
final double balance=getBalance(listerName);
if(msg.tool() instanceof Coins)
{
if((Double.MAX_VALUE-balance)<=((Coins)msg.tool()).getTotalValue())
{
CMLib.commands().postSay(this,mob,L("I'm sorry, the law prevents us from holding that much money in one account."),true,false);
return false;
}
if(!((Coins)msg.tool()).getCurrency().equalsIgnoreCase(CMLib.beanCounter().getCurrency(this)))
{
CMLib.commands().postSay(this,mob,L("I'm sorry, this bank only deals in @x1.",CMLib.beanCounter().getDenominationName(CMLib.beanCounter().getCurrency(this))),true,false);
return false;
}
return true;
}
if(!(msg.tool() instanceof Item))
{
mob.tell(L("@x1 doesn't look interested.",mob.charStats().HeShe()));
return false;
}
if(CMLib.flags().isEnspelled((Item)msg.tool()) || CMLib.flags().isOnFire((Item)msg.tool()))
{
mob.tell(this,msg.tool(),null,L("<S-HE-SHE> refuses to accept <T-NAME> for deposit."));
return false;
}
final double minbalance=(totalItemsWorth(listerName)/MIN_ITEM_BALANCE_DIVISOR)+CMath.div(((Item)msg.tool()).value(),MIN_ITEM_BALANCE_DIVISOR);
if(balance<minbalance)
{
if(isSold(ShopKeeper.DEAL_CLANBANKER))
CMLib.commands().postSay(this,mob,L("@x1 will need a total balance of @x2 for me to hold that.",CMStrings.capitalizeFirstLetter(listerName),CMLib.beanCounter().nameCurrencyShort(this,minbalance)),true,false);
else
CMLib.commands().postSay(this,mob,L("You'll need a total balance of @x1 for me to hold that.",CMLib.beanCounter().nameCurrencyShort(this,minbalance)),true,false);
return false;
}
}
return true;
case CMMsg.TYP_WITHDRAW:
{
if(!CMLib.coffeeShops().ignoreIfNecessary(msg.source(),finalIgnoreMask(),this))
return false;
String withdrawerName=getBankClientName(msg.source(),Clan.Function.WITHDRAW,true);
if(withdrawerName==null)
return false;
if((msg.tool()==null)||(!(msg.tool() instanceof Item)))
{
CMLib.commands().postSay(this,mob,L("What do you want? I'm busy!"),true,false);
return false;
}
if((msg.tool()!=null)&&(!msg.tool().okMessage(myHost,msg)))
return false;
MOB owner=msg.source();
double balance=getBalance(withdrawerName);
final double collateral=totalItemsWorth(withdrawerName);
if(msg.tool() instanceof Coins)
{
if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(this)))
{
CMLib.commands().postSay(this,mob,L("I'm sorry, I can only give you @x1.",CMLib.beanCounter().getDenominationName(CMLib.beanCounter().getCurrency(this))),true,false);
return false;
}
if((!isSold(ShopKeeper.DEAL_CLANBANKER))
&&(owner.isMarriedToLiege())
&&(balance<((Coins)msg.tool()).getTotalValue()))
{
final MOB M=CMLib.players().getLoadPlayer(owner.getLiegeID());
double b=0.0;
if(M!=null)
b=getBalance(M.Name());
if((M!=null)&&(b>=((Coins)msg.tool()).getTotalValue()))
{
owner=M;
balance=b;
withdrawerName=owner.Name();
}
}
}
else
if(findDepositInventory(withdrawerName,msg.tool().Name())==null)
{
if((!isSold(ShopKeeper.DEAL_CLANBANKER))
&&(msg.source().isMarriedToLiege())
&&(findDepositInventory(msg.source().getLiegeID(),msg.tool().Name())!=null))
owner=CMLib.players().getPlayer(msg.source().getLiegeID());
else
{
CMLib.commands().postSay(this,mob,L("You want WHAT?"),true,false);
return false;
}
}
else
if(msg.tool() instanceof Item)
{
final double debt=CMLib.beanCounter().getDebtOwed(withdrawerName,bankChain());
if((debt>0.0)
&&((collateral-((Item)msg.tool()).value())<debt))
{
CMLib.commands().postSay(this,mob,L("I'm sorry, but that item is being held as collateral against your debt at this time."),true,false);
return false;
}
}
final double minbalance=(collateral/MIN_ITEM_BALANCE_DIVISOR);
if(msg.tool() instanceof Coins)
{
if(((Coins)msg.tool()).getTotalValue()>balance)
{
if(isSold(ShopKeeper.DEAL_CLANBANKER))
CMLib.commands().postSay(this,mob,L("I'm sorry, @x1 has only @x2 in its account.",CMStrings.capitalizeFirstLetter(withdrawerName),CMLib.beanCounter().nameCurrencyShort(this,balance)),true,false);
else
CMLib.commands().postSay(this,mob,L("I'm sorry, you have only @x1 in that account.",CMLib.beanCounter().nameCurrencyShort(this,balance)),true,false);
return false;
}
if(minbalance==0)
return true;
if(((Coins)msg.tool()).getTotalValue()>(balance-minbalance))
{
if((balance-minbalance)>0)
CMLib.commands().postSay(this,mob,L("I'm sorry, you may only withdraw @x1 at this time.",CMLib.beanCounter().nameCurrencyShort(this,balance-minbalance)),true,false);
else
CMLib.commands().postSay(this,mob,L("I am holding other items in trust, so you may not withdraw funds at this time."),true,false);
return false;
}
}
}
return true;
case CMMsg.TYP_VALUE:
case CMMsg.TYP_SELL:
case CMMsg.TYP_VIEW:
return super.okMessage(myHost,msg);
case CMMsg.TYP_BUY:
return super.okMessage(myHost,msg);
case CMMsg.TYP_BORROW:
{
if(!CMLib.coffeeShops().ignoreIfNecessary(msg.source(),finalIgnoreMask(),this))
return false;
if(!(msg.tool() instanceof Coins))
{
CMLib.commands().postSay(this,mob,L("I'm sorry, only MONEY can be borrowed."),true,false);
return false;
}
final String withdrawerName=getBankClientName(msg.source(),Clan.Function.WITHDRAW,true);
if(withdrawerName==null)
return false;
if((numberDeposited(withdrawerName)==0)
&&((isSold(ShopKeeper.DEAL_CLANBANKER))
||(!msg.source().isMarriedToLiege())
||(numberDeposited(msg.source().getLiegeID())==0)))
{
final StringBuffer str=new StringBuffer("");
if(isSold(ShopKeeper.DEAL_CLANBANKER))
str.append(L("@x1 does not have an account with us, I'm afraid.",CMStrings.capitalizeFirstLetter(withdrawerName)));
else
str.append(L("You don't have an account with us, I'm afraid."));
CMLib.commands().postSay(this,mob,str.toString()+"^T",true,false);
return false;
}
final double debt=CMLib.beanCounter().getDebtOwed(withdrawerName,bankChain());
if(debt>0.0)
{
final StringBuffer str=new StringBuffer("");
if(isSold(ShopKeeper.DEAL_CLANBANKER))
str.append(L("@x1 already has a @x2 loan out with us.",CMStrings.capitalizeFirstLetter(withdrawerName),CMLib.beanCounter().nameCurrencyShort(this,debt)));
else
str.append(L("You already have a @x1 loan out with us.",CMLib.beanCounter().nameCurrencyShort(this,debt)));
CMLib.commands().postSay(this,mob,str.toString()+"^T",true,false);
return false;
}
final double collateralRemaining=((Coins)msg.tool()).getTotalValue()-totalItemsWorth(withdrawerName);
if(collateralRemaining>0)
{
final StringBuffer str=new StringBuffer("");
if(isSold(ShopKeeper.DEAL_CLANBANKER))
str.append(CMStrings.capitalizeFirstLetter(withdrawerName)+" ");
else
str.append("You ");
str.append(L("will need to deposit enough items with us as collateral. You'll need items worth @x1 more to qualify.",CMLib.beanCounter().nameCurrencyShort(this,collateralRemaining)));
CMLib.commands().postSay(this,mob,str.toString()+"^T",true,false);
return false;
}
return true;
}
case CMMsg.TYP_LIST:
{
if(!CMLib.coffeeShops().ignoreIfNecessary(msg.source(),finalIgnoreMask(),this))
return false;
final String listerName=getBankClientName(msg.source(),Clan.Function.DEPOSIT_LIST,true);
if(listerName==null)
return false;
if((numberDeposited(listerName)==0)
&&((isSold(ShopKeeper.DEAL_CLANBANKER))
||(!msg.source().isMarriedToLiege())
||(numberDeposited(msg.source().getLiegeID())==0)))
{
final StringBuffer str=new StringBuffer("");
if(isSold(ShopKeeper.DEAL_CLANBANKER))
str.append(L("@x1 does not have an account with us, I'm afraid.",CMStrings.capitalizeFirstLetter(listerName)));
else
str.append(L("You don't have an account with us, I'm afraid."));
if(coinInterest!=0.0)
{
final double cci=CMath.mul(Math.abs(coinInterest),100.0);
final String ci=((coinInterest>0.0)?"pay ":"charge ")+cci+"% interest ";
str.append(L("\n\rWe @x1monthly on money deposited here.",ci));
}
if(itemInterest!=0.0)
{
final double cci=CMath.mul(Math.abs(itemInterest),100.0);
final String ci=((itemInterest>0.0)?"pay ":"charge ")+cci+"% interest ";
str.append(L("\n\rWe @x1monthly on items kept with us.",ci));
}
if(bankChain().length()>0)
str.append(L("\n\rI am a banker for @x1.",bankChain()));
CMLib.commands().postSay(this,mob,str.toString()+"^T",true,false);
return false;
}
return true;
}
default:
break;
}
}
return super.okMessage(myHost,msg);
}
}
| |
package com.ote.keystore.credential;
import com.ote.keystore.credential.payload.CredentialPayload;
import com.ote.keystore.exceptionhandler.BeanInvalidationResult;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.SoftAssertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static com.ote.keystore.JSonUtils.serializeToJson;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@ActiveProfiles({"CredentialRepositoryMock", "CredentialRestControllerTest"})
@RunWith(SpringRunner.class)
@SpringBootTest
public class CredentialRestControllerTest {
private final static String SECRET_KEY = "forTest";
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private CredentialRepositoryMock credentialRepositoryMock;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@After
public void tearDown() {
credentialRepositoryMock.deleteAll();
}
//region read
@Test
public void reading_by_id_should_return_the_payload_when_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
// NB : payload will be updated and encrypted
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload)));
MvcResult result = mockMvc.perform(get("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY)).
andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
payload.setId(0);
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(payload));
assertions.assertAll();
}
@Test
public void reading_by_id_with_bad_secret_key_should_raise_decrypt_exception() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
// NB : payload will be updated and encrypted
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload)));
MvcResult result = mockMvc.perform(get("/v1/keys/credentials/0").param("secretKey", "BAD_KEY")).andReturn();
Assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo("An error occured while decrypting data");
}
@Test
public void reading_by_id_should_return_not_found_when_not_exist() throws Exception {
MvcResult result = mockMvc.perform(get("/v1/keys/credentials/0").param("secretKey", SECRET_KEY)).andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo("Unable to find user with id 0");
assertions.assertAll();
}
//endregion
//region create
@Test
public void creating_should_return_the_payload_with_a_new_id() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
MvcResult result = mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload))).andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
payload.setId(0);
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(payload));
assertions.assertAll();
}
@Test
public void creating_invalid_payload_should_raise_validation_exception() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword(null); // should raise validation exception
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
MvcResult result = mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload))).
andReturn();
BeanInvalidationResult expected = new BeanInvalidationResult();
expected.setTarget(payload);
expected.getInvalidations().add(new BeanInvalidationResult.Invalidation("password", "NotNull", "password may not be null"));
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertions.assertThat(result.getResponse().getContentAsString()).isNotNull();
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(expected));
System.out.println(result.getResponse().getContentAsString());
assertions.assertAll();
}
//endregion
//region test delete
@Test
public void deleting_by_id_should_return_not_found_when_not_exist() throws Exception {
MvcResult result = mockMvc.perform(delete("/v1/keys/credentials/0")).andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo("Unable to find user with id 0");
assertions.assertAll();
}
@Test
public void deleting_by_id_should_return_ok_when_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload))).
andReturn();
MvcResult result = mockMvc.perform(delete("/v1/keys/credentials/0")).andReturn();
Assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());
}
//endregion
//region update
@Test
public void putting_should_return_not_found_when_not_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
MvcResult result = mockMvc.perform(put("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload))).
andReturn();
Assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void patching_should_return_not_found_when_not_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
MvcResult result = mockMvc.perform(patch("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload))).
andReturn();
Assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void putting_should_replace_entity_when_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload)));
CredentialPayload payload2 = new CredentialPayload();
payload2.setId(0);
payload2.setLogin("newLoginTest");
payload2.setPassword("newPasswordTest");
mockMvc.perform(put("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload2)));
MvcResult result = mockMvc.perform(get("/v1/keys/credentials/0").param("secretKey", SECRET_KEY)).andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(payload2));
assertions.assertAll();
}
@Test
public void patching_should_merge_entity_when_exist() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
//create
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload)));
CredentialPayload payload2 = new CredentialPayload();
payload2.setLogin("newLoginTest");
payload2.setPassword("newPasswordTest");
mockMvc.perform(patch("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload2)));
MvcResult result = mockMvc.perform(get("/v1/keys/credentials/0").param("secretKey", SECRET_KEY)).andReturn();
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.OK.value());
payload.setId(0);
payload.setLogin(payload2.getLogin());
payload.setPassword(payload2.getPassword());
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(payload));
assertions.assertAll();
}
@Test
public void putting_invalid_payload_should_raise_validation_exception() throws Exception {
CredentialPayload payload = new CredentialPayload();
payload.setLogin("loginTest");
payload.setPassword("passwordTest");
payload.setApplication("applicationTest");
payload.setDescription("descriptionTest");
mockMvc.perform(post("/v1/keys/credentials").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload)));
CredentialPayload payload2 = new CredentialPayload();
payload2.setId(0);
payload2.setLogin("newLoginTest");
payload2.setPassword(null); // invalid
MvcResult result = mockMvc.perform(put("/v1/keys/credentials/0").
param("secretKey", SECRET_KEY).
contentType(MediaType.APPLICATION_JSON_VALUE).
content(serializeToJson(payload2))).andReturn();
BeanInvalidationResult expected = new BeanInvalidationResult();
expected.setTarget(payload2);
expected.getInvalidations().add(new BeanInvalidationResult.Invalidation("password", "NotNull", "password may not be null"));
SoftAssertions assertions = new SoftAssertions();
assertions.assertThat(result.getResponse().getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertions.assertThat(result.getResponse().getContentAsString()).isNotNull();
assertions.assertThat(result.getResponse().getContentAsString()).isEqualTo(serializeToJson(expected));
assertions.assertAll();
}
//endregion
}
| |
package fr.baloomba.geocoding;
import android.os.Parcel;
import android.os.Parcelable;
import org.json.JSONException;
import org.json.JSONObject;
import fr.baloomba.geocoding.helper.JSONHelper;
public class Geometry implements Parcelable {
// <editor-fold desc="VARIABLES">
private Location mLocation;
private String mLocationType;
private Area mViewport;
private Area mBounds;
// </editor-fold>
// <editor-fold desc="JSON KEYS">
private static final String LOCATION = "location";
private static final String LOCATION_TYPE = "location_type";
private static final String VIEWPORT = "viewport";
private static final String BOUNDS = "bounds";
// </editor-fold>
// <editor-fold desc="CONSTRUCTORS">
protected Geometry(Parcel in) {
mLocation = in.readParcelable(Location.class.getClassLoader());
mLocationType = in.readString();
mViewport = in.readParcelable(Area.class.getClassLoader());
mBounds = in.readParcelable(Area.class.getClassLoader());
}
protected Geometry(Init<?> builder) {
mLocation = builder.mLocation;
mLocationType = builder.mLocationType;
mViewport = builder.mViewport;
mBounds = builder.mBounds;
}
// </editor-fold>
//<editor-fold desc="PARCELABLE METHODS IMPLEMENTATION">
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeParcelable(mLocation, flags);
parcel.writeString(mLocationType);
parcel.writeParcelable(mViewport, flags);
parcel.writeParcelable(mBounds, flags);
}
public static final Creator<Geometry> CREATOR =
new Creator<Geometry>() {
@Override
public Geometry createFromParcel(Parcel source) {
return new Geometry(source);
}
@Override
public Geometry[] newArray(int size) {
return new Geometry[size];
}
};
//</editor-fold>
// <editor-fold desc="GETTERS">
public Location getLocation() {
return mLocation;
}
public String getLocationType() {
return mLocationType;
}
public Area getViewport() {
return mViewport;
}
public Area getBounds() {
return mBounds;
}
// </editor-fold>
// <editor-fold desc="SETTERS">
public void setLocation(Location location) {
mLocation = location;
}
public void setLocationType(String locationType) {
mLocationType = locationType;
}
public void setViewport(Area viewport) {
this.mViewport = viewport;
}
public void setBounds(Area bounds) {
mBounds = bounds;
}
// </editor-fold>
// <editor-fold desc="FACTORY CLASS">
public static class Factory {
// <editor-fold desc="VARIABLES">
private static Factory sInstance = new Factory();
// </editor-fold>
// <editor-fold desc="INSTANCE">
public static Factory getInstance() {
return sInstance;
}
// </editor-fold>
// <editor-fold desc="METHODS">
public Geometry fromJSON(JSONObject object) throws JSONException {
if (object == null)
return null;
return new Builder()
.setLocation(Location.Factory.getInstance()
.fromJSON(JSONHelper.getJSONObject(object, LOCATION)))
.setLocationType(JSONHelper.getString(object, LOCATION_TYPE))
.setViewport(Area.Factory.getInstance()
.fromJSON(JSONHelper.getJSONObject(object, VIEWPORT)))
.setBounds(Area.Factory.getInstance()
.fromJSON(JSONHelper.getJSONObject(object, BOUNDS)))
.build();
}
// </editor-fold>
}
// </editor-fold>
// <editor-fold desc="INIT BUILDER CLASS">
protected static abstract class Init<T extends Init<T>> {
// <editor-fold desc="VARIABLES">
private Location mLocation;
private String mLocationType;
private Area mViewport;
private Area mBounds;
// </editor-fold>
// <editor-fold desc="CONSTRUCTORS">
public Init() {
mLocation = null;
mLocationType = null;
mViewport = null;
mBounds = null;
}
// </editor-fold>
// <editor-fold desc="SETTERS">
public T setLocation(Location location) {
mLocation = location;
return self();
}
public T setLocationType(String locationType) {
mLocationType = locationType;
return self();
}
public T setViewport(Area viewport) {
mViewport = viewport;
return self();
}
public T setBounds(Area bounds) {
mBounds = bounds;
return self();
}
// </editor-fold>
// <editor-fold desc="METHODS">
protected abstract T self();
public Geometry build() {
return new Geometry(this);
}
// </editor-fold>
}
// </editor-fold>
// <editor-fold desc="BUILDER CLASS">
public static class Builder extends Init<Builder> {
// <editor-fold desc="CONSTRUCTORS">
public Builder() {
super();
}
// </editor-fold>
// <editor-fold desc="OVERRIDDEN INIT<BUILDER> METHODS">
@Override
protected Builder self() {
return this;
}
// </editor-fold>
}
// </editor-fold>
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.metadata;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.hadoop.hive.common.StringInternUtils;
import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils;
import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.OutputFormat;
/**
* A Hive Table Partition: is a fundamental storage unit within a Table.
*
* Please note that the ql code should always go through methods of this class to access the
* metadata, instead of directly accessing org.apache.hadoop.hive.metastore.api.Partition.
* This helps to isolate the metastore code and the ql code.
*/
public class Partition implements Serializable {
@SuppressWarnings("nls")
private static final Logger LOG = LoggerFactory
.getLogger("hive.ql.metadata.Partition");
private Table table;
private org.apache.hadoop.hive.metastore.api.Partition tPartition;
/**
* These fields are cached. The information comes from tPartition.
*/
private Deserializer deserializer;
private Class<? extends OutputFormat> outputFormatClass;
private Class<? extends InputFormat> inputFormatClass;
/**
* @return The values of the partition
* @see org.apache.hadoop.hive.metastore.api.Partition#getValues()
*/
public List<String> getValues() {
return tPartition.getValues();
}
/**
* Used only for serialization.
*/
public Partition() {
}
/**
* create an empty partition.
* SemanticAnalyzer code requires that an empty partition when the table is not partitioned.
*/
public Partition(Table tbl) throws HiveException {
org.apache.hadoop.hive.metastore.api.Partition tPart =
new org.apache.hadoop.hive.metastore.api.Partition();
if (!tbl.isView()) {
tPart.setSd(tbl.getTTable().getSd().deepCopy());
}
initialize(tbl, tPart);
}
public Partition(Table tbl, org.apache.hadoop.hive.metastore.api.Partition tp)
throws HiveException {
initialize(tbl, tp);
}
/**
* Create partition object with the given info.
*
* @param tbl
* Table the partition will be in.
* @param partSpec
* Partition specifications.
* @param location
* Location of the partition, relative to the table.
* @throws HiveException
* Thrown if we could not create the partition.
*/
public Partition(Table tbl, Map<String, String> partSpec, Path location) throws HiveException {
initialize(tbl, createMetaPartitionObject(tbl, partSpec, location));
}
public static org.apache.hadoop.hive.metastore.api.Partition createMetaPartitionObject(
Table tbl, Map<String, String> partSpec, Path location) throws HiveException {
List<String> pvals = new ArrayList<String>();
for (FieldSchema field : tbl.getPartCols()) {
String val = partSpec.get(field.getName());
if (val == null || val.isEmpty()) {
throw new HiveException("partition spec is invalid; field "
+ field.getName() + " does not exist or is empty");
}
pvals.add(val);
}
org.apache.hadoop.hive.metastore.api.Partition tpart =
new org.apache.hadoop.hive.metastore.api.Partition();
tpart.setDbName(tbl.getDbName());
tpart.setTableName(tbl.getTableName());
tpart.setValues(pvals);
if (!tbl.isView()) {
tpart.setSd(tbl.getSd().deepCopy());
tpart.getSd().setLocation((location != null) ? location.toString() : null);
}
return tpart;
}
/**
* Initializes this object with the given variables
*
* @param table
* Table the partition belongs to
* @param tPartition
* Thrift Partition object
* @throws HiveException
* Thrown if we cannot initialize the partition
*/
protected void initialize(Table table,
org.apache.hadoop.hive.metastore.api.Partition tPartition) throws HiveException {
this.table = table;
setTPartition(tPartition);
if (table.isView()) {
return;
}
if (table.isPartitioned()) {
try {
if (tPartition.getSd().getLocation() == null) {
// set default if location is not set and this is a physical
// table partition (not a view partition)
if (table.getDataLocation() != null) {
Path partPath = new Path(table.getDataLocation(), Warehouse.makePartName(table.getPartCols(), tPartition.getValues()));
tPartition.getSd().setLocation(partPath.toString());
}
}
// set default if columns are not set
if (tPartition.getSd().getCols() == null) {
if (table.getCols() != null) {
tPartition.getSd().setCols(table.getCols());
}
}
} catch (MetaException e) {
throw new HiveException("Invalid partition for table " + table.getTableName(),
e);
}
}
// Note that we do not set up fields like inputFormatClass, outputFormatClass
// and deserializer because the Partition needs to be accessed from across
// the metastore side as well, which will result in attempting to load
// the class associated with them, which might not be available, and
// the main reason to instantiate them would be to pre-cache them for
// performance. Since those fields are null/cache-check by their accessors
// anyway, that's not a concern.
}
public String getName() {
try {
return Warehouse.makePartName(table.getPartCols(), tPartition.getValues());
} catch (MetaException e) {
throw new RuntimeException(e);
}
}
public Path[] getPath() {
Path[] ret = new Path[]{getDataLocation()};
return ret;
}
public Path getPartitionPath() {
return getDataLocation();
}
public Path getDataLocation() {
if (table.isPartitioned()) {
if (tPartition.getSd() == null)
return null;
else
return new Path(tPartition.getSd().getLocation());
} else {
if (table.getTTable() == null || table.getTTable().getSd() == null)
return null;
else
return new Path(table.getTTable().getSd().getLocation());
}
}
final public Deserializer getDeserializer() {
if (deserializer == null) {
try {
deserializer = HiveMetaStoreUtils.getDeserializer(SessionState.getSessionConf(),
tPartition, table.getTTable());
} catch (MetaException e) {
throw new RuntimeException(e);
}
}
return deserializer;
}
public Properties getSchema() {
return MetaStoreUtils.getSchema(tPartition, table.getTTable());
}
public Properties getMetadataFromPartitionSchema() {
return MetaStoreUtils.getPartitionMetadata(tPartition, table.getTTable());
}
public Properties getSchemaFromTableSchema(Properties tblSchema) {
return MetaStoreUtils.getPartSchemaFromTableSchema(tPartition.getSd(),
tPartition.getParameters(),
tblSchema);
}
/**
* @param inputFormatClass
*/
public void setInputFormatClass(Class<? extends InputFormat> inputFormatClass) {
this.inputFormatClass = inputFormatClass;
tPartition.getSd().setInputFormat(inputFormatClass.getName());
}
/**
* @param outputFormatClass
*/
public void setOutputFormatClass(Class<? extends HiveOutputFormat> outputFormatClass) {
this.outputFormatClass = outputFormatClass;
tPartition.getSd().setOutputFormat(HiveFileFormatUtils
.getOutputFormatSubstitute(outputFormatClass).getName());
}
final public Class<? extends InputFormat> getInputFormatClass()
throws HiveException {
if (inputFormatClass == null) {
// sd can be null for views
String clsName = tPartition.getSd() == null ? null : tPartition.getSd().getInputFormat();
if (clsName == null) {
return inputFormatClass = table.getInputFormatClass();
}
try {
inputFormatClass = ((Class<? extends InputFormat>) Class.forName(clsName, true,
Utilities.getSessionSpecifiedClassLoader()));
} catch (ClassNotFoundException e) {
throw new HiveException("Class not found: " + clsName, e);
}
}
return inputFormatClass;
}
final public Class<? extends OutputFormat> getOutputFormatClass()
throws HiveException {
if (outputFormatClass == null) {
// sd can be null for views
String clsName = tPartition.getSd() == null ? null : tPartition.getSd().getOutputFormat();
if (clsName == null) {
return outputFormatClass = table.getOutputFormatClass();
}
try {
Class<?> c = Class.forName(clsName, true, Utilities.getSessionSpecifiedClassLoader());
// Replace FileOutputFormat for backward compatibility
outputFormatClass = HiveFileFormatUtils.getOutputFormatSubstitute(c);
} catch (ClassNotFoundException e) {
throw new HiveException("Class not found: " + clsName, e);
}
}
return outputFormatClass;
}
public int getBucketCount() {
return tPartition.getSd().getNumBuckets();
/*
* TODO: Keeping this code around for later use when we will support
* sampling on tables which are not created with CLUSTERED INTO clause
*
* // read from table meta data int numBuckets = this.table.getNumBuckets();
* if (numBuckets == -1) { // table meta data does not have bucket
* information // check if file system has multiple buckets(files) in this
* partition String pathPattern = this.partPath.toString() + "/*"; try {
* FileSystem fs = FileSystem.get(this.table.getDataLocation(),
* Hive.get().getConf()); FileStatus srcs[] = fs.globStatus(new
* Path(pathPattern), FileUtils.HIDDEN_FILES_PATH_FILTER); numBuckets = srcs.length; } catch (Exception e) {
* throw new RuntimeException("Cannot get bucket count for table " +
* this.table.getName(), e); } } return numBuckets;
*/
}
public void setBucketCount(int newBucketNum) {
tPartition.getSd().setNumBuckets(newBucketNum);
}
public List<String> getBucketCols() {
return tPartition.getSd().getBucketCols();
}
public List<Order> getSortCols() {
return tPartition.getSd().getSortCols();
}
public List<String> getSortColNames() {
return Utilities.getColumnNamesFromSortCols(getSortCols());
}
/**
* get all paths for this partition in a sorted manner
*/
@SuppressWarnings("nls")
public FileStatus[] getSortedPaths() {
try {
// Previously, this got the filesystem of the Table, which could be
// different from the filesystem of the partition.
FileSystem fs = getDataLocation().getFileSystem(SessionState.getSessionConf());
String pathPattern = getDataLocation().toString();
if (getBucketCount() > 0) {
pathPattern = pathPattern + "/*";
}
LOG.info("Path pattern = " + pathPattern);
FileStatus srcs[] = fs.globStatus(new Path(pathPattern), FileUtils.HIDDEN_FILES_PATH_FILTER);
Arrays.sort(srcs);
for (FileStatus src : srcs) {
LOG.info("Got file: " + src.getPath());
}
if (srcs.length == 0) {
return null;
}
return srcs;
} catch (Exception e) {
throw new RuntimeException("Cannot get path ", e);
}
}
/**
* mapping from bucket number to bucket path
*/
// TODO: add test case and clean it up
@SuppressWarnings("nls")
public Path getBucketPath(int bucketNum) {
// Note: this makes assumptions that won't work with MM tables, unions, etc.
FileStatus srcs[] = getSortedPaths();
if (srcs == null) {
return null;
}
// Compute bucketid from srcs and return the 1st match.
for (FileStatus src : srcs) {
String bucketName = src.getPath().getName();
String bucketIdStr = Utilities.getBucketFileNameFromPathSubString(bucketName);
int bucketId = Utilities.getBucketIdFromFile(bucketIdStr);
if (bucketId == bucketNum) {
// match, return
return src.getPath();
}
}
return null;
}
@SuppressWarnings("nls")
public Path[] getPath(Sample s) throws HiveException {
if (s == null) {
return getPath();
} else {
int bcount = getBucketCount();
if (bcount == 0) {
return getPath();
}
Dimension d = s.getSampleDimension();
if (!d.getDimensionId().equals(table.getBucketingDimensionId())) {
// if the bucket dimension is not the same as the sampling dimension
// we must scan all the data
return getPath();
}
int scount = s.getSampleFraction();
ArrayList<Path> ret = new ArrayList<Path>();
if (bcount == scount) {
ret.add(getBucketPath(s.getSampleNum() - 1));
} else if (bcount < scount) {
if ((scount / bcount) * bcount != scount) {
throw new HiveException("Sample Count" + scount
+ " is not a multiple of bucket count " + bcount + " for table "
+ table.getTableName());
}
// undersampling a bucket
ret.add(getBucketPath((s.getSampleNum() - 1) % bcount));
} else if (bcount > scount) {
if ((bcount / scount) * scount != bcount) {
throw new HiveException("Sample Count" + scount
+ " is not a divisor of bucket count " + bcount + " for table "
+ table.getTableName());
}
// sampling multiple buckets
for (int i = 0; i < bcount / scount; i++) {
ret.add(getBucketPath(i * scount + (s.getSampleNum() - 1)));
}
}
return (ret.toArray(new Path[ret.size()]));
}
}
public LinkedHashMap<String, String> getSpec() {
return table.createSpec(tPartition);
}
@SuppressWarnings("nls")
@Override
public String toString() {
String pn = "Invalid Partition";
try {
pn = Warehouse.makePartName(getSpec(), false);
} catch (MetaException e) {
// ignore as we most probably in an exception path already otherwise this
// error wouldn't occur
}
return table.toString() + "(" + pn + ")";
}
public Table getTable() {
return table;
}
/**
* Should be only used by serialization.
*/
public void setTable(Table table) {
this.table = table;
}
/**
* Should be only used by serialization.
*/
public org.apache.hadoop.hive.metastore.api.Partition getTPartition() {
return tPartition;
}
/**
* Should be only used by serialization.
*/
public void setTPartition(
org.apache.hadoop.hive.metastore.api.Partition partition) {
StringInternUtils.internStringsInList(partition.getValues());
tPartition = partition;
}
public Map<String, String> getParameters() {
return tPartition.getParameters();
}
public List<FieldSchema> getCols() {
return getColsInternal(false);
}
public List<FieldSchema> getColsForMetastore() {
return getColsInternal(true);
}
private List<FieldSchema> getColsInternal(boolean forMs) {
try {
String serializationLib = tPartition.getSd().getSerdeInfo().getSerializationLib();
// Do the lightweight check for general case.
if (Table.hasMetastoreBasedSchema(SessionState.getSessionConf(), serializationLib)) {
return tPartition.getSd().getCols();
} else if (forMs && !Table.shouldStoreFieldsInMetastore(
SessionState.getSessionConf(), serializationLib, table.getParameters())) {
return Hive.getFieldsFromDeserializerForMsStorage(table, getDeserializer());
}
return HiveMetaStoreUtils.getFieldsFromDeserializer(table.getTableName(), getDeserializer());
} catch (Exception e) {
LOG.error("Unable to get cols from serde: " +
tPartition.getSd().getSerdeInfo().getSerializationLib(), e);
}
return new ArrayList<FieldSchema>();
}
public String getLocation() {
if (tPartition.getSd() == null) {
return null;
} else {
return tPartition.getSd().getLocation();
}
}
public void setLocation(String location) {
tPartition.getSd().setLocation(location);
}
/**
* Set Partition's values
*
* @param partSpec
* Partition specifications.
* @throws HiveException
* Thrown if we could not create the partition.
*/
public void setValues(Map<String, String> partSpec)
throws HiveException {
List<String> pvals = new ArrayList<String>();
for (FieldSchema field : table.getPartCols()) {
String val = partSpec.get(field.getName());
if (val == null) {
throw new HiveException(
"partition spec is invalid. field.getName() does not exist in input.");
}
pvals.add(val.intern());
}
tPartition.setValues(pvals);
}
/**
* @return include the db name
*/
public String getCompleteName() {
return getTable().getCompleteName() + "@" + getName();
}
public int getLastAccessTime() {
return tPartition.getLastAccessTime();
}
public void setLastAccessTime(int lastAccessTime) {
tPartition.setLastAccessTime(lastAccessTime);
}
public boolean isStoredAsSubDirectories() {
return tPartition.getSd().isStoredAsSubDirectories();
}
public List<List<String>> getSkewedColValues(){
return tPartition.getSd().getSkewedInfo().getSkewedColValues();
}
public List<String> getSkewedColNames() {
LOG.debug("sd is " + tPartition.getSd().getClass().getName());
return tPartition.getSd().getSkewedInfo().getSkewedColNames();
}
public void setSkewedValueLocationMap(List<String> valList, String dirName)
throws HiveException {
Map<List<String>, String> mappings = tPartition.getSd().getSkewedInfo()
.getSkewedColValueLocationMaps();
if (null == mappings) {
mappings = new HashMap<List<String>, String>();
tPartition.getSd().getSkewedInfo().setSkewedColValueLocationMaps(mappings);
}
// Add or update new mapping
mappings.put(valList, dirName);
}
public Map<List<String>, String> getSkewedColValueLocationMaps() {
return tPartition.getSd().getSkewedInfo().getSkewedColValueLocationMaps();
}
public void checkValidity() throws HiveException {
if (!tPartition.getSd().equals(table.getSd())) {
Table.validateColumns(getCols(), table.getPartCols());
}
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.impl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.events.*;
import com.intellij.openapi.vfs.pointers.VirtualFilePointer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerContainer;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerListener;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import gnu.trove.THashMap;
import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntProcedure;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
public class VirtualFilePointerManagerImpl extends VirtualFilePointerManager implements ApplicationComponent, ModificationTracker, BulkFileListener {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl");
private final TempFileSystem TEMP_FILE_SYSTEM;
private final LocalFileSystem LOCAL_FILE_SYSTEM;
private final JarFileSystem JAR_FILE_SYSTEM;
// guarded by this
private final Map<VirtualFilePointerListener, FilePointerPartNode> myPointers = new LinkedHashMap<VirtualFilePointerListener, FilePointerPartNode>();
// compare by identity because VirtualFilePointerContainer has too smart equals
// guarded by myContainers
private final Set<VirtualFilePointerContainerImpl> myContainers = ContainerUtil.newIdentityTroveSet();
@NotNull private final VirtualFileManager myVirtualFileManager;
@NotNull private final MessageBus myBus;
private static final Comparator<String> URL_COMPARATOR = SystemInfo.isFileSystemCaseSensitive ? new Comparator<String>() {
@Override
public int compare(@NotNull String url1, @NotNull String url2) {
return url1.compareTo(url2);
}
} : new Comparator<String>() {
@Override
public int compare(@NotNull String url1, @NotNull String url2) {
return url1.compareToIgnoreCase(url2);
}
};
VirtualFilePointerManagerImpl(@NotNull VirtualFileManager virtualFileManager,
@NotNull MessageBus bus,
@NotNull TempFileSystem tempFileSystem,
@NotNull LocalFileSystem localFileSystem,
@NotNull JarFileSystem jarFileSystem) {
myVirtualFileManager = virtualFileManager;
myBus = bus;
bus.connect().subscribe(VirtualFileManager.VFS_CHANGES, this);
TEMP_FILE_SYSTEM = tempFileSystem;
LOCAL_FILE_SYSTEM = localFileSystem;
JAR_FILE_SYSTEM = jarFileSystem;
}
@Override
public void initComponent() {
}
@Override
public void disposeComponent() {
assertAllPointersDisposed();
}
@NotNull
@Override
public String getComponentName() {
return "VirtualFilePointerManager";
}
private static class EventDescriptor {
@NotNull private final VirtualFilePointerListener myListener;
@NotNull private final VirtualFilePointer[] myPointers;
private EventDescriptor(@NotNull VirtualFilePointerListener listener, @NotNull VirtualFilePointer[] pointers) {
myListener = listener;
myPointers = pointers;
}
private void fireBefore() {
if (myPointers.length != 0) {
myListener.beforeValidityChanged(myPointers);
}
}
private void fireAfter() {
if (myPointers.length != 0) {
myListener.validityChanged(myPointers);
}
}
}
@NotNull
private static VirtualFilePointer[] toPointers(@NotNull List<FilePointerPartNode> nodes) {
if (nodes.isEmpty()) return VirtualFilePointer.EMPTY_ARRAY;
List<VirtualFilePointer> list = new ArrayList<VirtualFilePointer>(nodes.size());
for (FilePointerPartNode node : nodes) {
node.addAllPointersTo(list);
}
return list.toArray(new VirtualFilePointer[list.size()]);
}
@TestOnly
VirtualFilePointer[] getPointersUnder(VirtualFile parent, String childName) {
List<FilePointerPartNode> nodes = new ArrayList<FilePointerPartNode>();
addPointersUnder(parent, true, childName, nodes);
return toPointers(nodes);
}
private void addPointersUnder(VirtualFile parent,
boolean separator,
@NotNull CharSequence childName,
@NotNull List<FilePointerPartNode> out) {
for (FilePointerPartNode root : myPointers.values()) {
root.addPointersUnder(parent, separator, childName, out);
}
}
@Override
@NotNull
public synchronized VirtualFilePointer create(@NotNull String url, @NotNull Disposable parent, @Nullable VirtualFilePointerListener listener) {
return create(null, url, parent, listener);
}
@Override
@NotNull
public synchronized VirtualFilePointer create(@NotNull VirtualFile file, @NotNull Disposable parent, @Nullable VirtualFilePointerListener listener) {
return create(file, null, parent, listener);
}
@NotNull
private VirtualFilePointer create(@Nullable("null means the pointer will be created from the (not null) url") VirtualFile file,
@Nullable("null means url has to be computed from the (not-null) file path") String url,
@NotNull Disposable parentDisposable,
@Nullable VirtualFilePointerListener listener) {
VirtualFileSystem fileSystem;
String protocol;
String path;
if (file == null) {
int protocolEnd = url.indexOf(URLUtil.SCHEME_SEPARATOR);
if (protocolEnd == -1) {
protocol = null;
fileSystem = null;
path = url;
}
else {
protocol = url.substring(0, protocolEnd);
fileSystem = myVirtualFileManager.getFileSystem(protocol);
path = url.substring(protocolEnd + URLUtil.SCHEME_SEPARATOR.length());
}
}
else {
fileSystem = file.getFileSystem();
protocol = fileSystem.getProtocol();
path = file.getPath();
url = VirtualFileManager.constructUrl(protocol, path);
}
if (fileSystem == TEMP_FILE_SYSTEM) {
// for tests, recreate always
VirtualFile found = file == null ? VirtualFileManager.getInstance().findFileByUrl(url) : file;
return new IdentityVirtualFilePointer(found, url);
}
boolean isJar = fileSystem == JAR_FILE_SYSTEM;
if (fileSystem != LOCAL_FILE_SYSTEM && !isJar) {
// we are unable to track alien file systems for now
VirtualFile found = fileSystem == null ? null : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url);
// if file is null, this pointer will never be alive
return getOrCreateIdentity(url, found);
}
if (file == null) {
String cleanPath = cleanupPath(path, isJar);
// if newly created path is the same as substringed from url one then the url did not change, we can reuse it
//noinspection StringEquality
if (cleanPath != path) {
url = VirtualFileManager.constructUrl(protocol, cleanPath);
path = cleanPath;
}
}
// else url has come from VirtualFile.getPath() and is good enough
VirtualFilePointerImpl pointer = getOrCreate(parentDisposable, listener, path, Pair.create(file, url));
DelegatingDisposable.registerDisposable(parentDisposable, pointer);
return pointer;
}
private final Map<String, IdentityVirtualFilePointer> myUrlToIdentity = new THashMap<String, IdentityVirtualFilePointer>();
@NotNull
private IdentityVirtualFilePointer getOrCreateIdentity(@NotNull String url, @Nullable VirtualFile found) {
IdentityVirtualFilePointer pointer = myUrlToIdentity.get(url);
if (pointer == null) {
pointer = new IdentityVirtualFilePointer(found, url);
myUrlToIdentity.put(url, pointer);
}
return pointer;
}
@NotNull
private static String cleanupPath(@NotNull String path, boolean isJar) {
path = FileUtil.normalize(path);
path = trimTrailingSeparators(path, isJar);
return path;
}
private static String trimTrailingSeparators(@NotNull String path, boolean isJar) {
while (StringUtil.endsWithChar(path, '/') && !(isJar && path.endsWith(JarFileSystem.JAR_SEPARATOR))) {
path = StringUtil.trimEnd(path, "/");
}
return path;
}
@NotNull
private VirtualFilePointerImpl getOrCreate(@NotNull Disposable parentDisposable,
@Nullable VirtualFilePointerListener listener,
@NotNull String path,
@NotNull Pair<VirtualFile, String> fileAndUrl) {
FilePointerPartNode root = myPointers.get(listener);
FilePointerPartNode node;
if (root == null) {
root = new FilePointerPartNode(path, null, fileAndUrl);
root.pointersUnder++;
myPointers.put(listener, root);
node = root;
}
else {
node = root.findPointerOrCreate(path, 0, fileAndUrl, 1);
}
VirtualFilePointerImpl pointer = node.getAnyPointer();
if (pointer == null) {
pointer = new VirtualFilePointerImpl(listener, parentDisposable, fileAndUrl);
node.associate(pointer, fileAndUrl);
}
pointer.myNode.incrementUsageCount(1);
root.checkConsistency();
return pointer;
}
@Override
@NotNull
public synchronized VirtualFilePointer duplicate(@NotNull VirtualFilePointer pointer,
@NotNull Disposable parent,
@Nullable VirtualFilePointerListener listener) {
VirtualFile file = pointer.getFile();
return file == null ? create(pointer.getUrl(), parent, listener) : create(file, parent, listener);
}
private synchronized void assertAllPointersDisposed() {
for (Map.Entry<VirtualFilePointerListener, FilePointerPartNode> entry : myPointers.entrySet()) {
FilePointerPartNode root = entry.getValue();
List<FilePointerPartNode> left = new ArrayList<FilePointerPartNode>();
List<VirtualFilePointerImpl> pointers = new ArrayList<VirtualFilePointerImpl>();
root.addPointersUnder(null, false, "", left);
for (FilePointerPartNode node : left) {
node.addAllPointersTo(pointers);
}
if (!pointers.isEmpty()) {
VirtualFilePointerImpl p = pointers.get(0);
try {
p.throwDisposalError("Not disposed pointer: "+p);
}
finally {
for (VirtualFilePointerImpl pointer : pointers) {
pointer.dispose();
}
}
}
}
synchronized (myContainers) {
if (!myContainers.isEmpty()) {
VirtualFilePointerContainerImpl container = myContainers.iterator().next();
container.throwDisposalError("Not disposed container");
}
}
}
private final Set<VirtualFilePointerImpl> myStoredPointers = ContainerUtil.newIdentityTroveSet();
@TestOnly
public void storePointers() {
myStoredPointers.clear();
addAllPointersTo(myStoredPointers);
}
@TestOnly
public void assertPointersAreDisposed() {
List<VirtualFilePointerImpl> pointers = new ArrayList<VirtualFilePointerImpl>();
addAllPointersTo(pointers);
try {
for (VirtualFilePointerImpl pointer : pointers) {
if (!myStoredPointers.contains(pointer)) {
pointer.throwDisposalError("Virtual pointer hasn't been disposed: "+pointer);
}
}
}
finally {
myStoredPointers.clear();
}
}
@TestOnly
private void addAllPointersTo(@NotNull Collection<VirtualFilePointerImpl> pointers) {
List<FilePointerPartNode> out = new ArrayList<FilePointerPartNode>();
for (FilePointerPartNode root : myPointers.values()) {
root.addPointersUnder(null, false, "", out);
}
for (FilePointerPartNode node : out) {
node.addAllPointersTo(pointers);
}
}
@Override
public void dispose() {
}
@Override
@NotNull
public VirtualFilePointerContainer createContainer(@NotNull Disposable parent) {
return createContainer(parent, null);
}
@Override
@NotNull
public synchronized VirtualFilePointerContainer createContainer(@NotNull Disposable parent, @Nullable VirtualFilePointerListener listener) {
return registerContainer(parent, new VirtualFilePointerContainerImpl(this, parent, listener));
}
@NotNull
private VirtualFilePointerContainer registerContainer(@NotNull Disposable parent, @NotNull final VirtualFilePointerContainerImpl virtualFilePointerContainer) {
synchronized (myContainers) {
myContainers.add(virtualFilePointerContainer);
}
Disposer.register(parent, new Disposable() {
@Override
public void dispose() {
Disposer.dispose(virtualFilePointerContainer);
boolean removed;
synchronized (myContainers) {
removed = myContainers.remove(virtualFilePointerContainer);
}
if (!ApplicationManager.getApplication().isUnitTestMode()) {
assert removed;
}
}
@Override
@NonNls
@NotNull
public String toString() {
return "Disposing container " + virtualFilePointerContainer;
}
});
return virtualFilePointerContainer;
}
private List<EventDescriptor> myEvents = Collections.emptyList();
private List<FilePointerPartNode> myNodesToUpdateUrl = Collections.emptyList();
private List<FilePointerPartNode> myNodesToFire = Collections.emptyList();
@Override
public void before(@NotNull final List<? extends VFileEvent> events) {
List<FilePointerPartNode> toFireEvents = new ArrayList<FilePointerPartNode>();
List<FilePointerPartNode> toUpdateUrl = new ArrayList<FilePointerPartNode>();
VirtualFilePointer[] toFirePointers;
synchronized (this) {
incModificationCount();
for (VFileEvent event : events) {
if (event instanceof VFileDeleteEvent) {
final VFileDeleteEvent deleteEvent = (VFileDeleteEvent)event;
addPointersUnder(deleteEvent.getFile(), false, "", toFireEvents);
}
else if (event instanceof VFileCreateEvent) {
final VFileCreateEvent createEvent = (VFileCreateEvent)event;
addPointersUnder(createEvent.getParent(), true, createEvent.getChildName(), toFireEvents);
}
else if (event instanceof VFileCopyEvent) {
final VFileCopyEvent copyEvent = (VFileCopyEvent)event;
addPointersUnder(copyEvent.getNewParent(), true, copyEvent.getFile().getName(), toFireEvents);
}
else if (event instanceof VFileMoveEvent) {
final VFileMoveEvent moveEvent = (VFileMoveEvent)event;
VirtualFile eventFile = moveEvent.getFile();
addPointersUnder(moveEvent.getNewParent(), true, eventFile.getName(), toFireEvents);
List<FilePointerPartNode> nodes = new ArrayList<FilePointerPartNode>();
addPointersUnder(eventFile, false, "", nodes);
for (FilePointerPartNode node : nodes) {
VirtualFilePointerImpl pointer = node.getAnyPointer();
VirtualFile file = pointer == null ? null : pointer.getFile();
if (file != null) {
toUpdateUrl.add(node);
}
}
}
else if (event instanceof VFilePropertyChangeEvent) {
final VFilePropertyChangeEvent change = (VFilePropertyChangeEvent)event;
if (VirtualFile.PROP_NAME.equals(change.getPropertyName())
&& !Comparing.equal(change.getOldValue(), change.getNewValue())) {
VirtualFile eventFile = change.getFile();
VirtualFile parent = eventFile.getParent(); // e.g. for LightVirtualFiles
addPointersUnder(parent, true, change.getNewValue().toString(), toFireEvents);
List<FilePointerPartNode> nodes = new ArrayList<FilePointerPartNode>();
addPointersUnder(eventFile, false, "", nodes);
for (FilePointerPartNode node : nodes) {
VirtualFilePointerImpl pointer = node.getAnyPointer();
VirtualFile file = pointer == null ? null : pointer.getFile();
if (file != null) {
toUpdateUrl.add(node);
}
}
}
}
}
myEvents = new ArrayList<EventDescriptor>();
toFirePointers = toPointers(toFireEvents);
for (final VirtualFilePointerListener listener : myPointers.keySet()) {
if (listener == null) continue;
List<VirtualFilePointer> filtered = ContainerUtil.filter(toFirePointers, new Condition<VirtualFilePointer>() {
@Override
public boolean value(VirtualFilePointer pointer) {
return ((VirtualFilePointerImpl)pointer).getListener() == listener;
}
});
if (!filtered.isEmpty()) {
EventDescriptor event = new EventDescriptor(listener, filtered.toArray(new VirtualFilePointer[filtered.size()]));
myEvents.add(event);
}
}
}
for (EventDescriptor descriptor : myEvents) {
descriptor.fireBefore();
}
if (!toFireEvents.isEmpty()) {
myBus.syncPublisher(VirtualFilePointerListener.TOPIC).beforeValidityChanged(toFirePointers);
}
myNodesToFire = toFireEvents;
myNodesToUpdateUrl = toUpdateUrl;
}
@Override
public void after(@NotNull final List<? extends VFileEvent> events) {
incModificationCount();
for (FilePointerPartNode node : myNodesToUpdateUrl) {
synchronized (this) {
String urlBefore = node.myFileAndUrl.second;
Pair<VirtualFile,String> after = node.update();
String urlAfter = after.second;
if (URL_COMPARATOR.compare(urlBefore, urlAfter) != 0) {
List<VirtualFilePointerImpl> myPointers = new SmartList<VirtualFilePointerImpl>();
node.addAllPointersTo(myPointers);
// url has changed, reinsert
int useCount = node.useCount;
FilePointerPartNode root = node.remove();
FilePointerPartNode newNode = root.findPointerOrCreate(VfsUtilCore.urlToPath(urlAfter), 0, after, myPointers.size());
VirtualFilePointer existingPointer = newNode.getAnyPointer();
if (existingPointer != null) {
// can happen when e.g. file renamed to the existing file
// merge two pointers
for (FilePointerPartNode n = newNode; n != null; n = n.parent) {
n.pointersUnder += myPointers.size();
}
}
newNode.addAllPointersTo(myPointers);
VirtualFilePointerImpl[] newMyPointers = myPointers.toArray(new VirtualFilePointerImpl[myPointers.size()]);
newNode.associate(newMyPointers, after);
newNode.incrementUsageCount(useCount);
}
}
}
VirtualFilePointer[] pointersToFireArray = toPointers(myNodesToFire);
for (VirtualFilePointer pointer : pointersToFireArray) {
((VirtualFilePointerImpl)pointer).myNode.update();
}
for (EventDescriptor event : myEvents) {
event.fireAfter();
}
if (pointersToFireArray.length != 0) {
myBus.syncPublisher(VirtualFilePointerListener.TOPIC).validityChanged(pointersToFireArray);
}
myNodesToUpdateUrl = Collections.emptyList();
myEvents = Collections.emptyList();
myNodesToFire = Collections.emptyList();
for (FilePointerPartNode root : myPointers.values()) {
root.checkConsistency();
}
}
void removeNode(@NotNull FilePointerPartNode node, VirtualFilePointerListener listener) {
FilePointerPartNode root = node.remove();
boolean rootNodeEmpty = root.children.length == 0 ;
if (rootNodeEmpty) {
myPointers.remove(listener);
}
else {
myPointers.get(listener).checkConsistency();
}
}
private static class DelegatingDisposable implements Disposable {
private static final ConcurrentMap<Disposable, DelegatingDisposable> ourInstances =
ContainerUtil.newConcurrentMap(ContainerUtil.<Disposable>identityStrategy());
private final TObjectIntHashMap<VirtualFilePointerImpl> myCounts = new TObjectIntHashMap<VirtualFilePointerImpl>();
private final Disposable myParent;
private DelegatingDisposable(@NotNull Disposable parent) {
myParent = parent;
}
private static void registerDisposable(@NotNull Disposable parentDisposable, @NotNull VirtualFilePointerImpl pointer) {
DelegatingDisposable result = ourInstances.get(parentDisposable);
if (result == null) {
DelegatingDisposable newDisposable = new DelegatingDisposable(parentDisposable);
result = ConcurrencyUtil.cacheOrGet(ourInstances, parentDisposable, newDisposable);
if (result == newDisposable) {
Disposer.register(parentDisposable, result);
}
}
synchronized (result) {
result.myCounts.put(pointer, result.myCounts.get(pointer) + 1);
}
}
@Override
public void dispose() {
ourInstances.remove(myParent);
synchronized (this) {
myCounts.forEachEntry(new TObjectIntProcedure<VirtualFilePointerImpl>() {
@Override
public boolean execute(VirtualFilePointerImpl pointer, int disposeCount) {
int after = pointer.myNode.incrementUsageCount(-disposeCount + 1);
LOG.assertTrue(after > 0, after);
pointer.dispose();
return true;
}
});
}
}
}
@TestOnly
int numberOfPointers() {
int number = 0;
for (FilePointerPartNode root : myPointers.values()) {
number = root.numberOfPointersUnder();
}
return number;
}
@TestOnly
int numberOfListeners() {
return myPointers.keySet().size();
}
}
| |
/*
* Copyright 2013 Nicolas Morel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nmorel.gwtjackson.client;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.github.nmorel.gwtjackson.client.deser.map.key.KeyDeserializer;
import com.github.nmorel.gwtjackson.client.ser.map.key.KeySerializer;
/**
* @author Nicolas Morel
*/
public abstract class AbstractConfiguration {
public class PrimitiveTypeConfiguration {
private final Class type;
private PrimitiveTypeConfiguration( Class type ) {
this.type = type;
}
public PrimitiveTypeConfiguration serializer( Class serializer ) {
mapTypeToSerializer.put( type, serializer );
return this;
}
public PrimitiveTypeConfiguration deserializer( Class deserializer ) {
mapTypeToDeserializer.put( type, deserializer );
return this;
}
}
public class TypeConfiguration<T> {
private final Class<T> type;
private TypeConfiguration( Class<T> type ) {
this.type = type;
}
public TypeConfiguration<T> serializer( Class<? extends JsonSerializer> serializer ) {
mapTypeToSerializer.put( type, serializer );
return this;
}
public TypeConfiguration<T> deserializer( Class<? extends JsonDeserializer> deserializer ) {
mapTypeToDeserializer.put( type, deserializer );
return this;
}
}
public class KeyTypeConfiguration<T> {
private final Class<T> type;
private KeyTypeConfiguration( Class<T> type ) {
this.type = type;
}
public KeyTypeConfiguration<T> serializer( Class<? extends KeySerializer> serializer ) {
mapTypeToKeySerializer.put( type, serializer );
return this;
}
public KeyTypeConfiguration<T> deserializer( Class<? extends KeyDeserializer> deserializer ) {
mapTypeToKeyDeserializer.put( type, deserializer );
return this;
}
}
private final Map<Class, Class> mapTypeToSerializer = new HashMap<Class, Class>();
private final Map<Class, Class> mapTypeToDeserializer = new HashMap<Class, Class>();
private final Map<Class, Class> mapTypeToKeySerializer = new HashMap<Class, Class>();
private final Map<Class, Class> mapTypeToKeyDeserializer = new HashMap<Class, Class>();
private final Map<Class, Class> mapMixInAnnotations = new HashMap<Class, Class>();
private final List<String> whitelist = new ArrayList<String>();
private JsonAutoDetect.Visibility fieldVisibility = JsonAutoDetect.Visibility.DEFAULT;
private JsonAutoDetect.Visibility getterVisibility = JsonAutoDetect.Visibility.DEFAULT;
private JsonAutoDetect.Visibility isGetterVisibility = JsonAutoDetect.Visibility.DEFAULT;
private JsonAutoDetect.Visibility setterVisibility = JsonAutoDetect.Visibility.DEFAULT;
private JsonAutoDetect.Visibility creatorVisibility = JsonAutoDetect.Visibility.DEFAULT;
protected AbstractConfiguration() {
configure();
}
/**
* Return a {@link PrimitiveTypeConfiguration} to configure serializer and/or deserializer for the given primitive type.
*/
protected PrimitiveTypeConfiguration primitiveType( Class type ) {
if ( !type.isPrimitive() ) {
throw new IllegalArgumentException( "Type " + type + " is not a primitive. Call type(Class) instead" );
}
return new PrimitiveTypeConfiguration( type );
}
/**
* Return a {@link TypeConfiguration} to configure serializer and/or deserializer for the given type.
*/
protected <T> TypeConfiguration<T> type( Class<T> type ) {
if ( type.isPrimitive() ) {
throw new IllegalArgumentException( "Type " + type + " is a primitive. Call primitiveType(Class) instead" );
}
return new TypeConfiguration<T>( type );
}
/**
* Return a {@link KeyTypeConfiguration} to configure key serializer and/or deserializer for the given type.
*/
protected <T> KeyTypeConfiguration<T> key( Class<T> type ) {
if ( type.isPrimitive() ) {
throw new IllegalArgumentException( "Primitive types cannot be used as a map's key" );
}
return new KeyTypeConfiguration<T>( type );
}
/**
* Method to use for adding mix-in annotations to use for augmenting
* specified class or interface. All annotations from
* <code>mixinSource</code> are taken to override annotations
* that <code>target</code> (or its supertypes) has.
*
* @param target Class (or interface) whose annotations to effectively override
* @param mixinSource Class (or interface) whose annotations are to
* be "added" to target's annotations, overriding as necessary
*/
protected AbstractConfiguration addMixInAnnotations( Class<?> target, Class<?> mixinSource ) {
mapMixInAnnotations.put( target, mixinSource );
return this;
}
/**
* Method to add a regex into whitelist.
* <p>
* All the types matching whitelist are added to the subtype list of {@link Object} and
* {@link Serializable} serializer/deserializer.
* </p>
*
* @param regex the regex to add
*/
protected AbstractConfiguration whitelist( String regex ) {
whitelist.add( regex );
return this;
}
/**
* Override the default behaviour of {@link JsonAutoDetect.Visibility#DEFAULT} for fields.
*
* @param visibility the new default behaviour
*/
protected AbstractConfiguration fieldVisibility( JsonAutoDetect.Visibility visibility ) {
this.fieldVisibility = visibility;
return this;
}
/**
* Override the default behaviour of {@link JsonAutoDetect.Visibility#DEFAULT} for getters.
*
* @param visibility the new default behaviour
*/
protected AbstractConfiguration getterVisibility( JsonAutoDetect.Visibility visibility ) {
this.getterVisibility = visibility;
return this;
}
/**
* Override the default behaviour of {@link JsonAutoDetect.Visibility#DEFAULT} for boolean getters.
*
* @param visibility the new default behaviour
*/
protected AbstractConfiguration isGetterVisibility( JsonAutoDetect.Visibility visibility ) {
this.isGetterVisibility = visibility;
return this;
}
/**
* Override the default behaviour of {@link JsonAutoDetect.Visibility#DEFAULT} for setters.
*
* @param visibility the new default behaviour
*/
protected AbstractConfiguration setterVisibility( JsonAutoDetect.Visibility visibility ) {
this.setterVisibility = visibility;
return this;
}
/**
* Override the default behaviour of {@link JsonAutoDetect.Visibility#DEFAULT} for creators.
*
* @param visibility the new default behaviour
*/
protected AbstractConfiguration creatorVisibility( JsonAutoDetect.Visibility visibility ) {
this.creatorVisibility = visibility;
return this;
}
protected abstract void configure();
public Map<Class, Class> getMapTypeToSerializer() {
return mapTypeToSerializer;
}
public Map<Class, Class> getMapTypeToDeserializer() {
return mapTypeToDeserializer;
}
public Map<Class, Class> getMapTypeToKeySerializer() {
return mapTypeToKeySerializer;
}
public Map<Class, Class> getMapTypeToKeyDeserializer() {
return mapTypeToKeyDeserializer;
}
public Map<Class, Class> getMapMixInAnnotations() {
return mapMixInAnnotations;
}
public List<String> getWhitelist() {
return whitelist;
}
public Visibility getFieldVisibility() {
return fieldVisibility;
}
public Visibility getGetterVisibility() {
return getterVisibility;
}
public Visibility getIsGetterVisibility() {
return isGetterVisibility;
}
public Visibility getSetterVisibility() {
return setterVisibility;
}
public Visibility getCreatorVisibility() {
return creatorVisibility;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.modules.session.internal.filter;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
import org.apache.geode.Delta;
import org.apache.geode.Instantiator;
import org.apache.geode.InvalidDeltaException;
import org.apache.geode.modules.session.internal.filter.attributes.AbstractSessionAttributes;
import org.apache.geode.modules.session.internal.filter.attributes.SessionAttributes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import org.apache.geode.modules.util.ClassLoaderObjectInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class which implements a Gemfire persisted {@code HttpSession}
*/
@SuppressWarnings("deprecation")
public class GemfireHttpSession implements HttpSession, DataSerializable, Delta {
private static transient final Logger LOG =
LoggerFactory.getLogger(GemfireHttpSession.class.getName());
/**
* Serial id
*/
private static final long serialVersionUID = 238915238964017823L;
/**
* Id for the session
*/
private String id;
/**
* Attributes really hold the essence of persistence.
*/
private SessionAttributes attributes;
private transient SessionManager manager;
private HttpSession nativeSession = null;
/**
* A session becomes invalid if it is explicitly invalidated or if it expires.
*/
private boolean isValid = true;
private boolean isNew = true;
private boolean isDirty = false;
/**
* This is set during serialization and then reset by the SessionManager when it is retrieved from
* the attributes.
*/
private AtomicBoolean serialized = new AtomicBoolean(false);
/**
* Register ourselves for de-serialization
*/
static {
registerInstantiator();
}
public static void registerInstantiator() {
Instantiator.register(new Instantiator(GemfireHttpSession.class, 27315) {
@Override
public DataSerializable newInstance() {
return new GemfireHttpSession();
}
});
}
/**
* Constructor used for de-serialization
*/
private GemfireHttpSession() {}
/**
* Constructor
*/
public GemfireHttpSession(String id, HttpSession nativeSession) {
this();
this.id = id;
this.nativeSession = nativeSession;
if (nativeSession != null) {
attributes.setMaxInactiveInterval(nativeSession.getMaxInactiveInterval());
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getAttribute(String name) {
if (!isValid) {
throw new IllegalStateException("Session is already invalidated");
}
Object obj = attributes.getAttribute(name);
if (obj != null) {
Object tmpObj = null;
ClassLoader loader = ((GemfireSessionManager) manager).getReferenceClassLoader();
if (obj.getClass().getClassLoader() != loader) {
LOG.debug("Attribute '{}' needs to be reconstructed with a new classloader", name);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
ObjectInputStream ois = new ClassLoaderObjectInputStream(
new ByteArrayInputStream(baos.toByteArray()), loader);
tmpObj = ois.readObject();
} catch (IOException e) {
LOG.error("Exception while recreating attribute '" + name + "'", e);
} catch (ClassNotFoundException e) {
LOG.error("Exception while recreating attribute '" + name + "'", e);
}
if (tmpObj != null) {
setAttribute(name, tmpObj);
obj = tmpObj;
}
}
}
return obj;
}
/**
* {@inheritDoc}
*/
@Override
public Enumeration getAttributeNames() {
if (!isValid) {
throw new IllegalStateException("Session is already invalidated");
}
return Collections.enumeration(attributes.getAttributeNames());
}
/**
* {@inheritDoc}
*/
@Override
public long getCreationTime() {
if (nativeSession != null) {
return nativeSession.getCreationTime();
} else {
return 0;
}
}
/**
* {@inheritDoc}
*/
@Override
public String getId() {
return id;
}
/**
* {@inheritDoc}
*/
@Override
public long getLastAccessedTime() {
if (!isValid) {
throw new IllegalStateException("Session is already invalidated");
}
return attributes.getLastAccessedTime();
}
/**
* {@inheritDoc}
*/
@Override
public ServletContext getServletContext() {
if (nativeSession != null) {
return nativeSession.getServletContext();
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public HttpSessionContext getSessionContext() {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Object getValue(String name) {
return getAttribute(name);
}
/**
* {@inheritDoc}
*/
@Override
public String[] getValueNames() {
return attributes.getAttributeNames().toArray(new String[0]);
}
/**
* {@inheritDoc}
*/
@Override
public void invalidate() {
nativeSession.invalidate();
manager.destroySession(id);
isValid = false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isNew() {
if (!isValid) {
throw new IllegalStateException("Session is already invalidated");
}
return isNew;
}
public void setIsNew(boolean isNew) {
this.isNew = isNew;
}
/**
* {@inheritDoc}
*/
@Override
public void setMaxInactiveInterval(int interval) {
if (nativeSession != null) {
nativeSession.setMaxInactiveInterval(interval);
}
attributes.setMaxInactiveInterval(interval);
isDirty = true;
}
/**
* {@inheritDoc}
*/
@Override
public int getMaxInactiveInterval() {
if (nativeSession != null) {
return nativeSession.getMaxInactiveInterval();
} else {
return attributes.getMaxIntactiveInterval();
}
}
/**
* {@inheritDoc}
*/
@Override
public void putValue(String name, Object value) {
setAttribute(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public void removeAttribute(final String name) {
LOG.debug("Session {} removing attribute {}", getId(), name);
nativeSession.removeAttribute(name);
attributes.removeAttribute(name);
}
/**
* {@inheritDoc}
*/
@Override
public void removeValue(String name) {
removeAttribute(name);
}
/**
* {@inheritDoc}
*/
@Override
public void setAttribute(final String name, final Object value) {
if (LOG.isDebugEnabled()) {
LOG.debug("Session {} setting attribute {} = '{}'", new Object[] {id, name, value});
}
isDirty = true;
nativeSession.setAttribute(name, value);
if (value == null) {
removeAttribute(name);
} else {
attributes.putAttribute(name, value);
}
}
/**
* Gemfire serialization {@inheritDoc}
*/
@Override
public void toData(DataOutput out) throws IOException {
DataSerializer.writeString(id, out);
DataSerializer.writeObject(attributes, out);
}
/**
* Gemfire de-serialization {@inheritDoc}
*/
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
id = DataSerializer.readString(in);
attributes = DataSerializer.readObject(in);
if (getNativeSession() != null) {
for (String s : attributes.getAttributeNames()) {
getNativeSession().setAttribute(s, attributes.getAttribute(s));
}
}
// Explicit sets
serialized.set(true);
attributes.setSession(this);
}
/**
* These three methods handle delta propagation and are deferred to the attribute object.
*/
@Override
public boolean hasDelta() {
return isDirty;
}
@Override
public void toDelta(DataOutput out) throws IOException {
if (attributes instanceof Delta) {
((Delta) attributes).toDelta(out);
} else {
toData(out);
}
}
@Override
public void fromDelta(DataInput in) throws IOException, InvalidDeltaException {
if (attributes instanceof Delta) {
((Delta) attributes).fromDelta(in);
} else {
try {
fromData(in);
} catch (ClassNotFoundException cex) {
throw new IOException("Unable to forward fromDelta() call " + "to fromData()", cex);
}
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[id=").append(id).append(", isNew=").append(isNew).append(", isValid=")
.append(isValid).append(", hasDelta=").append(hasDelta()).append(", lastAccessedTime=")
.append(attributes.getLastAccessedTime()).append(", jvmOwnerId=")
.append(attributes.getJvmOwnerId());
builder.append("]");
return builder.toString();
}
/**
* Flush the session object to the region
*/
public void putInRegion() {
manager.putSession(this);
isDirty = false;
}
/**
* Determine whether the session is still valid or whether it has expired.
*
* @return true or false
*/
public boolean isValid() {
if (!isValid) {
return false;
}
if (getMaxInactiveInterval() >= 0) {
long now = System.currentTimeMillis();
if (now - attributes.getLastAccessedTime() >= getMaxInactiveInterval() * 1000) {
return false;
}
}
return true;
}
/**
* Is this session dirty and should it be written to cache
*/
public boolean isDirty() {
return isDirty;
}
public void setManager(SessionManager manager) {
this.manager = manager;
}
/**
* For testing allow retrieval of the wrapped, native session.
*/
public HttpSession getNativeSession() {
return nativeSession;
}
public void setNativeSession(HttpSession session) {
this.nativeSession = session;
}
/**
* Handle the process of failing over the session to a new native session object.
*
* @param session
*/
public void failoverSession(HttpSession session) {
LOG.debug("Failing over session {} to {}", getId(), session.getId());
setNativeSession(session);
for (String name : attributes.getAttributeNames()) {
LOG.debug("Copying '{}' => {}", name, attributes.getAttribute(name));
session.setAttribute(name, attributes.getAttribute(name));
}
session.setMaxInactiveInterval(attributes.getMaxIntactiveInterval());
manager.putSession(this);
}
/**
* Update the last accessed time
*/
public void updateAccessTime() {
attributes.setLastAccessedTime(System.currentTimeMillis());
}
/**
* The {@code SessionManager} injects this when creating a new session.
*
* @param attributes
*/
public void setAttributes(AbstractSessionAttributes attributes) {
this.attributes = attributes;
}
/**
* This is called on deserialization. You can only call it once to get a meaningful value as it
* resets the serialized state. In other words, this call is not idempotent.
*
* @return whether this object has just been serialized
*/
public boolean justSerialized() {
return serialized.getAndSet(false);
}
/**
* Called when the session is about to go out of scope. If the session has been defined to use
* async queued attributes then they will be written out at this point.
*/
public void commit() {
attributes.setJvmOwnerId(manager.getJvmId());
attributes.flush();
}
public String getJvmOwnerId() {
if (attributes != null) {
return attributes.getJvmOwnerId();
}
return null;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.cli;
import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.cli.util.CLITestData;
import org.apache.hadoop.cli.util.CommandExecutor;
import org.apache.hadoop.cli.util.ComparatorBase;
import org.apache.hadoop.cli.util.ComparatorData;
import org.apache.hadoop.cli.util.CLITestData.TestCmd;
import org.apache.hadoop.cli.util.CLITestData.TestCmd.CommandType;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.security.authorize.HadoopPolicyProvider;
import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.security.authorize.ServiceAuthorizationManager;
import org.apache.hadoop.util.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Tests for the Command Line Interface (CLI)
*/
public class TestCLI extends TestCase {
private static final Log LOG =
LogFactory.getLog(TestCLI.class.getName());
// In this mode, it runs the command and compares the actual output
// with the expected output
public static final String TESTMODE_TEST = "test"; // Run the tests
// If it is set to nocompare, run the command and do not compare.
// This can be useful populate the testConfig.xml file the first time
// a new command is added
public static final String TESTMODE_NOCOMPARE = "nocompare";
public static final String TEST_CACHE_DATA_DIR =
System.getProperty("test.cache.data", "build/test/cache");
//By default, run the tests. The other mode is to run the commands and not
// compare the output
public static String testMode = TESTMODE_TEST;
// Storage for tests read in from the config file
static ArrayList<CLITestData> testsFromConfigFile = null;
static ArrayList<ComparatorData> testComparators = null;
static String testConfigFile = "testConf.xml";
String thisTestCaseName = null;
static ComparatorData comparatorData = null;
private static Configuration conf = null;
private static MiniDFSCluster dfsCluster = null;
private static DistributedFileSystem dfs = null;
private static MiniMRCluster mrCluster = null;
private static String namenode = null;
private static String jobtracker = null;
private static String clitestDataDir = null;
private static String username = null;
/**
* Read the test config file - testConfig.xml
*/
private void readTestConfigFile() {
if (testsFromConfigFile == null) {
boolean success = false;
testConfigFile = TEST_CACHE_DATA_DIR + File.separator + testConfigFile;
try {
SAXParser p = (SAXParserFactory.newInstance()).newSAXParser();
p.parse(testConfigFile, new TestConfigFileParser());
success = true;
} catch (Exception e) {
LOG.info("File: " + testConfigFile + " not found");
success = false;
}
assertTrue("Error reading test config file", success);
}
}
/*
* Setup
*/
public void setUp() throws Exception {
// Read the testConfig.xml file
readTestConfigFile();
// Start up the mini dfs cluster
boolean success = false;
conf = new Configuration();
conf.setClass(PolicyProvider.POLICY_PROVIDER_CONFIG,
HadoopPolicyProvider.class, PolicyProvider.class);
conf.setBoolean(ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG,
true);
dfsCluster = new MiniDFSCluster(conf, 1, true, null);
namenode = conf.get("fs.default.name", "file:///");
clitestDataDir = new File(TEST_CACHE_DATA_DIR).
toURI().toString().replace(' ', '+');
username = System.getProperty("user.name");
FileSystem fs = dfsCluster.getFileSystem();
assertTrue("Not a HDFS: "+fs.getUri(),
fs instanceof DistributedFileSystem);
dfs = (DistributedFileSystem) fs;
// Start up mini mr cluster
JobConf mrConf = new JobConf(conf);
mrCluster = new MiniMRCluster(1, dfsCluster.getFileSystem().getUri().toString(), 1,
null, null, mrConf);
jobtracker = mrCluster.createJobConf().get("mapred.job.tracker", "local");
success = true;
assertTrue("Error setting up Mini DFS & MR clusters", success);
}
/**
* Tear down
*/
public void tearDown() throws Exception {
boolean success = false;
mrCluster.shutdown();
dfs.close();
dfsCluster.shutdown();
success = true;
Thread.sleep(2000);
assertTrue("Error tearing down Mini DFS & MR clusters", success);
displayResults();
}
/**
* Expand the commands from the test config xml file
* @param cmd
* @return String expanded command
*/
private String expandCommand(final String cmd) {
String expCmd = cmd;
expCmd = expCmd.replaceAll("NAMENODE", namenode);
expCmd = expCmd.replaceAll("JOBTRACKER", jobtracker);
expCmd = expCmd.replaceAll("CLITEST_DATA", clitestDataDir);
expCmd = expCmd.replaceAll("USERNAME", username);
return expCmd;
}
/**
* Display the summarized results
*/
private void displayResults() {
LOG.info("Detailed results:");
LOG.info("----------------------------------\n");
for (int i = 0; i < testsFromConfigFile.size(); i++) {
CLITestData td = testsFromConfigFile.get(i);
boolean testResult = td.getTestResult();
// Display the details only if there is a failure
if (!testResult) {
LOG.info("-------------------------------------------");
LOG.info(" Test ID: [" + (i + 1) + "]");
LOG.info(" Test Description: [" + td.getTestDesc() + "]");
LOG.info("");
ArrayList<TestCmd> testCommands = td.getTestCommands();
for (TestCmd cmd : testCommands) {
LOG.info(" Test Commands: [" +
expandCommand(cmd.getCmd()) + "]");
}
LOG.info("");
ArrayList<TestCmd> cleanupCommands = td.getCleanupCommands();
for (TestCmd cmd : cleanupCommands) {
LOG.info(" Cleanup Commands: [" +
expandCommand(cmd.getCmd()) + "]");
}
LOG.info("");
ArrayList<ComparatorData> compdata = td.getComparatorData();
for (ComparatorData cd : compdata) {
boolean resultBoolean = cd.getTestResult();
LOG.info(" Comparator: [" +
cd.getComparatorType() + "]");
LOG.info(" Comparision result: [" +
(resultBoolean ? "pass" : "fail") + "]");
LOG.info(" Expected output: [" +
cd.getExpectedOutput() + "]");
LOG.info(" Actual output: [" +
cd.getActualOutput() + "]");
}
LOG.info("");
}
}
LOG.info("Summary results:");
LOG.info("----------------------------------\n");
boolean overallResults = true;
int totalPass = 0;
int totalFail = 0;
int totalComparators = 0;
for (int i = 0; i < testsFromConfigFile.size(); i++) {
CLITestData td = testsFromConfigFile.get(i);
totalComparators +=
testsFromConfigFile.get(i).getComparatorData().size();
boolean resultBoolean = td.getTestResult();
if (resultBoolean) {
totalPass ++;
} else {
totalFail ++;
}
overallResults &= resultBoolean;
}
LOG.info(" Testing mode: " + testMode);
LOG.info("");
LOG.info(" Overall result: " +
(overallResults ? "+++ PASS +++" : "--- FAIL ---"));
LOG.info(" # Tests pass: " + totalPass +
" (" + (100 * totalPass / (totalPass + totalFail)) + "%)");
LOG.info(" # Tests fail: " + totalFail +
" (" + (100 * totalFail / (totalPass + totalFail)) + "%)");
LOG.info(" # Validations done: " + totalComparators +
" (each test may do multiple validations)");
LOG.info("");
LOG.info("Failing tests:");
LOG.info("--------------");
int i = 0;
boolean foundTests = false;
for (i = 0; i < testsFromConfigFile.size(); i++) {
boolean resultBoolean = testsFromConfigFile.get(i).getTestResult();
if (!resultBoolean) {
LOG.info((i + 1) + ": " +
testsFromConfigFile.get(i).getTestDesc());
foundTests = true;
}
}
if (!foundTests) {
LOG.info("NONE");
}
foundTests = false;
LOG.info("");
LOG.info("Passing tests:");
LOG.info("--------------");
for (i = 0; i < testsFromConfigFile.size(); i++) {
boolean resultBoolean = testsFromConfigFile.get(i).getTestResult();
if (resultBoolean) {
LOG.info((i + 1) + ": " +
testsFromConfigFile.get(i).getTestDesc());
foundTests = true;
}
}
if (!foundTests) {
LOG.info("NONE");
}
assertTrue("One of the tests failed. " +
"See the Detailed results to identify " +
"the command that failed", overallResults);
}
/**
* Compare the actual output with the expected output
* @param compdata
* @return
*/
private boolean compareTestOutput(ComparatorData compdata) {
// Compare the output based on the comparator
String comparatorType = compdata.getComparatorType();
Class<?> comparatorClass = null;
// If testMode is "test", then run the command and compare the output
// If testMode is "nocompare", then run the command and dump the output.
// Do not compare
boolean compareOutput = false;
if (testMode.equals(TESTMODE_TEST)) {
try {
// Initialize the comparator class and run its compare method
comparatorClass = Class.forName("org.apache.hadoop.cli.util." +
comparatorType);
ComparatorBase comp = (ComparatorBase) comparatorClass.newInstance();
compareOutput = comp.compare(CommandExecutor.getLastCommandOutput(),
compdata.getExpectedOutput());
} catch (Exception e) {
LOG.info("Error in instantiating the comparator" + e);
}
}
return compareOutput;
}
/***********************************
************* TESTS
*********************************/
public void testAll() {
LOG.info("TestAll");
// Run the tests defined in the testConf.xml config file.
for (int index = 0; index < testsFromConfigFile.size(); index++) {
CLITestData testdata = (CLITestData) testsFromConfigFile.get(index);
// Execute the test commands
ArrayList<TestCmd> testCommands = testdata.getTestCommands();
for (TestCmd cmd : testCommands) {
try {
CommandExecutor.executeCommand(cmd, namenode, jobtracker);
} catch (Exception e) {
fail(StringUtils.stringifyException(e));
}
}
boolean overallTCResult = true;
// Run comparators
ArrayList<ComparatorData> compdata = testdata.getComparatorData();
for (ComparatorData cd : compdata) {
final String comptype = cd.getComparatorType();
boolean compareOutput = false;
if (! comptype.equalsIgnoreCase("none")) {
compareOutput = compareTestOutput(cd);
overallTCResult &= compareOutput;
}
cd.setExitCode(CommandExecutor.getLastExitCode());
cd.setActualOutput(CommandExecutor.getLastCommandOutput());
cd.setTestResult(compareOutput);
}
testdata.setTestResult(overallTCResult);
// Execute the cleanup commands
ArrayList<TestCmd> cleanupCommands = testdata.getCleanupCommands();
for (TestCmd cmd : cleanupCommands) {
try {
CommandExecutor.executeCommand(cmd, namenode, jobtracker);
} catch (Exception e) {
fail(StringUtils.stringifyException(e));
}
}
}
}
/*
* Parser class for the test config xml file
*/
static class TestConfigFileParser extends DefaultHandler {
String charString = null;
CLITestData td = null;
ArrayList<TestCmd> testCommands = null;
ArrayList<TestCmd> cleanupCommands = null;
@Override
public void startDocument() throws SAXException {
testsFromConfigFile = new ArrayList<CLITestData>();
}
@Override
public void startElement(String uri,
String localName,
String qName,
Attributes attributes) throws SAXException {
if (qName.equals("test")) {
td = new CLITestData();
} else if (qName.equals("test-commands")) {
testCommands = new ArrayList<TestCmd>();
} else if (qName.equals("cleanup-commands")) {
cleanupCommands = new ArrayList<TestCmd>();
} else if (qName.equals("comparators")) {
testComparators = new ArrayList<ComparatorData>();
} else if (qName.equals("comparator")) {
comparatorData = new ComparatorData();
}
charString = "";
}
@Override
public void endElement(String uri,
String localName,
String qName) throws SAXException {
if (qName.equals("description")) {
td.setTestDesc(charString);
} else if (qName.equals("test-commands")) {
td.setTestCommands(testCommands);
testCommands = null;
} else if (qName.equals("cleanup-commands")) {
td.setCleanupCommands(cleanupCommands);
cleanupCommands = null;
} else if (qName.equals("command")) {
if (testCommands != null) {
testCommands.add(new TestCmd(charString, CommandType.FS));
} else if (cleanupCommands != null) {
cleanupCommands.add(new TestCmd(charString, CommandType.FS));
}
} else if (qName.equals("dfs-admin-command")) {
if (testCommands != null) {
testCommands.add(new TestCmd(charString,CommandType.DFSADMIN));
} else if (cleanupCommands != null) {
cleanupCommands.add(new TestCmd(charString, CommandType.DFSADMIN));
}
} else if (qName.equals("mr-admin-command")) {
if (testCommands != null) {
testCommands.add(new TestCmd(charString,CommandType.MRADMIN));
} else if (cleanupCommands != null) {
cleanupCommands.add(new TestCmd(charString, CommandType.MRADMIN));
}
} else if (qName.equals("comparators")) {
td.setComparatorData(testComparators);
} else if (qName.equals("comparator")) {
testComparators.add(comparatorData);
} else if (qName.equals("type")) {
comparatorData.setComparatorType(charString);
} else if (qName.equals("expected-output")) {
comparatorData.setExpectedOutput(charString);
} else if (qName.equals("test")) {
testsFromConfigFile.add(td);
td = null;
} else if (qName.equals("mode")) {
testMode = charString;
if (!testMode.equals(TESTMODE_NOCOMPARE) &&
!testMode.equals(TESTMODE_TEST)) {
testMode = TESTMODE_TEST;
}
}
}
@Override
public void characters(char[] ch,
int start,
int length) throws SAXException {
String s = new String(ch, start, length);
charString += s;
}
}
}
| |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krms.impl.repository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krms.api.repository.term.TermDefinition;
import org.kuali.rice.krms.api.repository.term.TermResolverDefinition;
import org.kuali.rice.krms.api.repository.term.TermSpecificationDefinition;
import org.kuali.rice.krms.impl.util.KrmsImplConstants;
import org.kuali.rice.krms.impl.repository.ContextValidTermBo;
import org.kuali.rice.krms.impl.repository.TermSpecificationBo;
import org.springframework.util.CollectionUtils;
/**
* Implementation of {@link TermBoService}
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class TermBoServiceImpl implements TermBoService {
private BusinessObjectService businessObjectService;
/**
* @param businessObjectService the businessObjectService to set
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#getTermSpecificationById(java.lang.String)
*/
@Override
public TermSpecificationDefinition getTermSpecificationById(String id) {
TermSpecificationDefinition result = null;
if (StringUtils.isBlank(id)) {
throw new RiceIllegalArgumentException("id must not be blank or null");
}
TermSpecificationBo termSpecificationBo = businessObjectService.findBySinglePrimaryKey(
TermSpecificationBo.class, id);
if (termSpecificationBo != null) {
if (termSpecificationBo.getContextIds() != null
&& termSpecificationBo.getContextIds().isEmpty()
&& termSpecificationBo.getContexts() != null
&& !termSpecificationBo.getContexts().isEmpty()) {
List<String> contextIds = new ArrayList<String>();
for (ContextBo context : termSpecificationBo.getContexts()) {
contextIds.add(context.getId());
}
termSpecificationBo.setContextIds(contextIds);
}
result = TermSpecificationDefinition.Builder.create(termSpecificationBo).build();
}
return result;
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#createTermSpecification(org.kuali.rice.krms.api.repository.term.TermSpecificationDefinition)
*/
@Override
public TermSpecificationDefinition createTermSpecification(TermSpecificationDefinition termSpec) {
if (!StringUtils.isBlank(termSpec.getId())) {
throw new RiceIllegalArgumentException("for creation, TermSpecification.id must be null");
}
TermSpecificationBo termSpecBo = TermSpecificationBo.from(termSpec);
termSpecBo = businessObjectService.save(termSpecBo);
// save relations to the contexts on the BO
if (!CollectionUtils.isEmpty(termSpec.getContextIds())) {
for (String contextId : termSpec.getContextIds()) {
ContextValidTermBo contextValidTerm = new ContextValidTermBo();
contextValidTerm.setContextId(contextId);
contextValidTerm.setTermSpecificationId(termSpecBo.getId());
businessObjectService.save(contextValidTerm);
}
}
return TermSpecificationBo.to(termSpecBo);
}
@Override
public void updateTermSpecification(TermSpecificationDefinition termSpec) throws RiceIllegalArgumentException {
if (termSpec == null) {
throw new IllegalArgumentException("term specification is null");
}
// must already exist to be able to update
final String termSpecificationId = termSpec.getId();
final TermSpecificationBo existing = businessObjectService.findBySinglePrimaryKey(TermSpecificationBo.class,
termSpecificationId);
if (existing == null) {
throw new IllegalStateException("the term specification does not exist: " + termSpec);
}
final TermSpecificationDefinition toUpdate;
if (!existing.getId().equals(termSpec.getId())) {
// if passed in id does not match existing id, correct it
final TermSpecificationDefinition.Builder builder = TermSpecificationDefinition.Builder.create(termSpec);
builder.setId(existing.getId());
toUpdate = builder.build();
} else {
toUpdate = termSpec;
}
// copy all updateable fields to bo
TermSpecificationBo boToUpdate = TermSpecificationBo.from(toUpdate);
// // delete any old, existing attributes DOES NOT HAVE ANY
// Map<String, String> fields = new HashMap<String, String>(1);
// fields.put(KrmsImplConstants.PropertyNames.TermSpecification.TERM_SPECIFICATION_ID, toUpdate.getId());
// businessObjectService.deleteMatching(TermSpecificationAttributeBo.class, fields);
// update the rule and create new attributes
businessObjectService.save(boToUpdate);
}
@Override
public void deleteTermSpecification(String id) throws RiceIllegalArgumentException {
if (id == null) {
throw new RiceIllegalArgumentException("agendaId is null");
}
final TermSpecificationBo existing = businessObjectService.findBySinglePrimaryKey(TermSpecificationBo.class,
id);
if (existing == null) {
throw new IllegalStateException("the TermSpecification to delete does not exists: " + id);
}
businessObjectService.delete(existing);
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#createTerm(org.kuali.rice.krms.api.repository.term.TermDefinition)
*/
@Override
public TermDefinition createTerm(TermDefinition termDef) {
if (!StringUtils.isBlank(termDef.getId())) {
throw new RiceIllegalArgumentException("for creation, TermDefinition.id must be null");
}
TermBo termBo = TermBo.from(termDef);
businessObjectService.save(termBo);
return TermBo.to(termBo);
}
@Override
public void updateTerm(TermDefinition term) throws RiceIllegalArgumentException {
if (term == null) {
throw new IllegalArgumentException("term is null");
}
// must already exist to be able to update
final String termId = term.getId();
final TermBo existing = businessObjectService.findBySinglePrimaryKey(TermBo.class, termId);
if (existing == null) {
throw new IllegalStateException("the term resolver does not exist: " + term);
}
final TermDefinition toUpdate;
if (!existing.getId().equals(term.getId())) {
// if passed in id does not match existing id, correct it
final TermDefinition.Builder builder = TermDefinition.Builder.create(term);
builder.setId(existing.getId());
toUpdate = builder.build();
} else {
toUpdate = term;
}
// copy all updateable fields to bo
TermBo boToUpdate = TermBo.from(toUpdate);
// delete any old, existing parameters
Map<String, String> fields = new HashMap<String, String>(1);
fields.put(KrmsImplConstants.PropertyNames.Term.TERM_ID, toUpdate.getId());
businessObjectService.deleteMatching(TermParameterBo.class, fields);
// update the rule and create new attributes
businessObjectService.save(boToUpdate);
}
@Override
public void deleteTerm(String id) throws RiceIllegalArgumentException {
if (id == null) {
throw new RiceIllegalArgumentException("termId is null");
}
TermBo existing = businessObjectService.findBySinglePrimaryKey(TermBo.class, id);
if (existing == null) {
throw new IllegalStateException("the term to delete does not exists: " + id);
}
businessObjectService.delete(existing);
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#createTermResolver(org.kuali.rice.krms.api.repository.term.TermResolverDefinition)
*/
@Override
public TermResolverDefinition createTermResolver(TermResolverDefinition termResolver) {
if (!StringUtils.isBlank(termResolver.getId())) {
throw new RiceIllegalArgumentException("for creation, TermResolverDefinition.id must be null");
}
TermResolverBo termResolverBo = TermResolverBo.from(termResolver);
termResolverBo = (TermResolverBo) businessObjectService.save(termResolverBo);
return TermResolverBo.to(termResolverBo);
}
@Override
public void updateTermResolver(TermResolverDefinition termResolver) throws RiceIllegalArgumentException {
if (termResolver == null) {
throw new IllegalArgumentException("term resolver is null");
}
// must already exist to be able to update
final String termResolverId = termResolver.getId();
final TermResolverBo existing = businessObjectService.findBySinglePrimaryKey(TermResolverBo.class,
termResolverId);
if (existing == null) {
throw new IllegalStateException("the term resolver does not exist: " + termResolver);
}
final TermResolverDefinition toUpdate;
if (!existing.getId().equals(termResolver.getId())) {
// if passed in id does not match existing id, correct it
final TermResolverDefinition.Builder builder = TermResolverDefinition.Builder.create(termResolver);
builder.setId(existing.getId());
toUpdate = builder.build();
} else {
toUpdate = termResolver;
}
// copy all updateable fields to bo
TermResolverBo boToUpdate = TermResolverBo.from(toUpdate);
// delete any old, existing attributes
Map<String, String> fields = new HashMap<String, String>(1);
fields.put(KrmsImplConstants.PropertyNames.TermResolver.TERM_RESOLVER_ID, toUpdate.getId());
businessObjectService.deleteMatching(TermResolverAttributeBo.class, fields);
// update the rule and create new attributes
businessObjectService.save(boToUpdate);
}
@Override
public void deleteTermResolver(String id) throws RiceIllegalArgumentException {
if (id == null) {
throw new RiceIllegalArgumentException("agendaId is null");
}
TermSpecificationBo existing = businessObjectService.findBySinglePrimaryKey(TermSpecificationBo.class, id);
if (existing == null) {
throw new IllegalStateException("the TermResolver to delete does not exists: " + id);
}
businessObjectService.delete(existing);
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#getTerm(java.lang.String)
*/
@Override
public TermDefinition getTerm(String id) {
TermDefinition result = null;
if (StringUtils.isBlank(id)) {
throw new RiceIllegalArgumentException("id must not be blank or null");
}
TermBo termBo = businessObjectService.findBySinglePrimaryKey(TermBo.class, id);
if (termBo != null) {
result = TermBo.to(termBo);
}
return result;
}
/**
* @see org.kuali.rice.krms.impl.repository.TermBoService#getTermResolverById(java.lang.String)
*/
@Override
public TermResolverDefinition getTermResolverById(String id) {
TermResolverDefinition result = null;
if (StringUtils.isBlank(id)) {
throw new RiceIllegalArgumentException("id must not be blank or null");
}
TermResolverBo termResolverBo = businessObjectService.findBySinglePrimaryKey(TermResolverBo.class, id);
if (termResolverBo != null) {
result = TermResolverBo.to(termResolverBo);
}
return result;
}
@Override
public List<TermResolverDefinition> findTermResolversByOutputId(String id, String namespace) {
List<TermResolverDefinition> results = null;
if (StringUtils.isBlank(id)) {
throw new RiceIllegalArgumentException("id must not be blank or null");
}
if (StringUtils.isBlank(namespace)) {
throw new RiceIllegalArgumentException("namespace must not be blank or null");
}
Map<String, String> criteria = new HashMap<String, String>(2);
criteria.put("outputId", id);
criteria.put("namespace", namespace);
Collection<TermResolverBo> termResolverBos = businessObjectService.findMatching(TermResolverBo.class, criteria);
if (!CollectionUtils.isEmpty(termResolverBos)) {
results = new ArrayList<TermResolverDefinition>(termResolverBos.size());
for (TermResolverBo termResolverBo : termResolverBos) {
results.add(TermResolverBo.to(termResolverBo));
}
} else {
results = Collections.emptyList();
}
return results;
}
@Override
public List<TermResolverDefinition> findTermResolversByNamespace(String namespace) {
List<TermResolverDefinition> results = null;
if (StringUtils.isBlank(namespace)) {
throw new RiceIllegalArgumentException("namespace must not be blank or null");
}
Map fieldValues = new HashMap();
fieldValues.put("namespace", namespace);
Collection<TermResolverBo> termResolverBos = businessObjectService.findMatching(TermResolverBo.class,
fieldValues);
if (!CollectionUtils.isEmpty(termResolverBos)) {
results = new ArrayList<TermResolverDefinition>(termResolverBos.size());
for (TermResolverBo termResolverBo : termResolverBos) {
if (termResolverBo != null) {
results.add(TermResolverBo.to(termResolverBo));
}
}
} else {
results = Collections.emptyList();
}
return results;
}
@Override
public TermResolverDefinition getTermResolverByNameAndNamespace(String name,
String namespace) throws RiceIllegalArgumentException {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name is null or blank");
}
if (StringUtils.isBlank(namespace)) {
throw new IllegalArgumentException("namespace is null or blank");
}
final Map<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("namespace", namespace);
TermResolverBo bo = businessObjectService.findByPrimaryKey(TermResolverBo.class, map);
return TermResolverBo.to(bo);
}
@Override
public TermSpecificationDefinition getTermSpecificationByNameAndNamespace(String name,
String namespace) throws RiceIllegalArgumentException {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("name is null or blank");
}
if (StringUtils.isBlank(namespace)) {
throw new IllegalArgumentException("namespace is null or blank");
}
final Map<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("namespace", namespace);
TermSpecificationBo bo = businessObjectService.findByPrimaryKey(TermSpecificationBo.class, map);
return TermSpecificationBo.to(bo);
}
@Override
public List<TermSpecificationDefinition> findAllTermSpecificationsByContextId(String contextId) {
List<TermSpecificationDefinition> results = null;
if (StringUtils.isBlank(contextId)) {
throw new RiceIllegalArgumentException("contextId must not be blank or null");
}
Collection<ContextValidTermBo> contextValidTerms = businessObjectService.findMatching(ContextValidTermBo.class,
Collections.singletonMap("contextId", contextId));
if (!CollectionUtils.isEmpty(contextValidTerms)) {
results = new ArrayList<TermSpecificationDefinition>(contextValidTerms.size());
for (ContextValidTermBo validTerm : contextValidTerms) {
results.add(TermSpecificationBo.to(validTerm.getTermSpecification()));
}
} else {
results = Collections.emptyList();
}
return results;
}
}
| |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.Set;
/**
* Models an assignment that defines a variable and the removal of it.
*
*/
class DefinitionsRemover {
/**
* @return an {@link Definition} object if the node contains a definition or
* {@code null} otherwise.
*/
static Definition getDefinition(Node n, boolean isExtern) {
// TODO(user): Since we have parent pointers handy. A lot of constructors
// can be simplied.
Node parent = n.getParent();
if (parent == null) {
return null;
}
if (NodeUtil.isVarDeclaration(n) && n.hasChildren()) {
return new VarDefinition(n, isExtern);
} else if (NodeUtil.isFunction(parent) && parent.getFirstChild() == n) {
if (!NodeUtil.isFunctionExpression(parent)) {
return new NamedFunctionDefinition(parent, isExtern);
} else if (!n.getString().equals("")) {
return new FunctionExpressionDefinition(parent, isExtern);
}
} else if (NodeUtil.isAssign(parent) && parent.getFirstChild() == n) {
return new AssignmentDefinition(parent, isExtern);
} else if (NodeUtil.isObjectLitKey(n, parent)) {
return new ObjectLiteralPropertyDefinition(parent, n, n.getNext(),
isExtern);
} else if (parent.getType() == Token.LP) {
Node function = parent.getParent();
return new FunctionArgumentDefinition(function, n, isExtern);
}
return null;
}
static abstract class Definition {
private final boolean isExtern;
Definition(boolean isExtern) {
this.isExtern = isExtern;
}
/**
* Removes this definition from the AST if it is not an extern.
*
* This method should not be called on a definition for which isExtern()
* is true.
*/
public void remove() {
if (!isExtern) {
performRemove();
} else {
throw new IllegalStateException("Attempt to remove() an extern" +
" definition.");
}
}
/**
* Subclasses should override to remove the definition from the AST.
*/
protected abstract void performRemove();
/**
* Variable or property name represented by this definition.
* For example, in the case of assignments this method would
* return the NAME, GETPROP or GETELEM expression that acts as the
* assignment left hand side.
*
* @return the L-Value associated with this definition.
* The node's type is always NAME, GETPROP or GETELEM.
*/
public abstract Node getLValue();
/**
* Value expression that acts as the right hand side of the
* definition statement.
*/
public abstract Node getRValue();
/**
* Returns true if the definition is an extern.
*/
public boolean isExtern() {
return isExtern;
}
}
/**
* Represents an name-only external definition. The definition's
* rhs is missing.
*/
abstract static class IncompleteDefinition extends Definition {
private static final Set<Integer> ALLOWED_TYPES =
ImmutableSet.of(Token.NAME, Token.GETPROP, Token.GETELEM);
private final Node lValue;
IncompleteDefinition(Node lValue, boolean inExterns) {
super(inExterns);
Preconditions.checkNotNull(lValue);
Preconditions.checkArgument(
ALLOWED_TYPES.contains(lValue.getType()),
"Unexpected lValue type " + Token.name(lValue.getType()));
this.lValue = lValue;
}
@Override
public Node getLValue() {
return lValue;
}
@Override
public Node getRValue() {
return null;
}
}
/**
* Represents an unknown definition.
*/
static final class UnknownDefinition extends IncompleteDefinition {
UnknownDefinition(Node lValue, boolean inExterns) {
super(lValue, inExterns);
}
@Override
public void performRemove() {
throw new IllegalArgumentException("Can't remove an UnknownDefinition");
}
}
/**
* Represents an name-only external definition. The definition's
* rhs is missing.
*/
static final class ExternalNameOnlyDefinition extends IncompleteDefinition {
ExternalNameOnlyDefinition(Node lValue) {
super(lValue, true);
}
@Override
public void performRemove() {
throw new IllegalArgumentException(
"Can't remove external name-only definition");
}
}
/**
* Represents a function formal parameter. The definition's rhs is missing.
*/
static final class FunctionArgumentDefinition extends IncompleteDefinition {
FunctionArgumentDefinition(Node function,
Node argumentName,
boolean inExterns) {
super(argumentName, inExterns);
Preconditions.checkArgument(NodeUtil.isFunction(function));
Preconditions.checkArgument(NodeUtil.isName(argumentName));
}
@Override
public void performRemove() {
throw new IllegalArgumentException(
"Can't remove a FunctionArgumentDefinition");
}
}
/**
* Represents a function declaration or function expression.
*/
abstract static class FunctionDefinition extends Definition {
protected final Node function;
FunctionDefinition(Node node, boolean inExterns) {
super(inExterns);
Preconditions.checkArgument(NodeUtil.isFunction(node));
function = node;
}
@Override
public Node getLValue() {
return function.getFirstChild();
}
@Override
public Node getRValue() {
return function;
}
}
/**
* Represents a function declaration without assignment node such as
* {@code function foo()}.
*/
static final class NamedFunctionDefinition extends FunctionDefinition {
NamedFunctionDefinition(Node node, boolean inExterns) {
super(node, inExterns);
}
@Override
public void performRemove() {
function.detachFromParent();
}
}
/**
* Represents a function expression that acts as a rhs. The defined
* name is only reachable from within the function.
*/
static final class FunctionExpressionDefinition extends FunctionDefinition {
FunctionExpressionDefinition(Node node, boolean inExterns) {
super(node, inExterns);
Preconditions.checkArgument(
NodeUtil.isFunctionExpression(node));
}
@Override
public void performRemove() {
// replace internal name with ""
function.replaceChild(function.getFirstChild(),
Node.newString(Token.NAME, ""));
}
}
/**
* Represents a declaration within an assignment.
*/
static final class AssignmentDefinition extends Definition {
private final Node assignment;
AssignmentDefinition(Node node, boolean inExterns) {
super(inExterns);
Preconditions.checkArgument(NodeUtil.isAssign(node));
assignment = node;
}
@Override
public void performRemove() {
// A simple assignment. foo = bar() -> bar();
Node parent = assignment.getParent();
Node last = assignment.getLastChild();
assignment.removeChild(last);
parent.replaceChild(assignment, last);
}
@Override
public Node getLValue() {
return assignment.getFirstChild();
}
@Override
public Node getRValue() {
return assignment.getLastChild();
}
}
/**
* Represents member declarations using a object literal.
* Example: var x = { e : function() { } };
*/
static final class ObjectLiteralPropertyDefinition extends Definition {
private final Node literal;
private final Node name;
private final Node value;
ObjectLiteralPropertyDefinition(Node lit, Node name, Node value,
boolean isExtern) {
super(isExtern);
this.literal = lit;
this.name = name;
this.value = value;
}
@Override
public void performRemove() {
literal.removeChild(name);
literal.removeChild(value);
}
@Override
public Node getLValue() {
// TODO(user) revisit: object literal definitions are an example
// of definitions whose lhs doesn't correspond to a node that
// exists in the AST. We will have to change the return type of
// getLValue sooner or later in order to provide this added
// flexibility.
return new Node(Token.GETPROP,
new Node(Token.OBJECTLIT),
name.cloneNode());
}
@Override
public Node getRValue() {
return value;
}
}
/**
* Represents a VAR declaration with an assignment.
*/
static final class VarDefinition extends Definition {
private final Node name;
VarDefinition(Node node, boolean inExterns) {
super(inExterns);
Preconditions.checkArgument(NodeUtil.isVarDeclaration(node));
Preconditions.checkArgument(node.hasChildren(),
"VAR Declaration of " + node.getString() +
"should be assigned a value.");
name = node;
}
@Override
public void performRemove() {
Node var = name.getParent();
Preconditions.checkState(var.getFirstChild() == var.getLastChild(),
"AST should be normalized first");
Node parent = var.getParent();
Node rValue = name.removeFirstChild();
Preconditions.checkState(parent.getType() != Token.FOR);
parent.replaceChild(var, NodeUtil.newExpr(rValue));
}
@Override
public Node getLValue() {
return name;
}
@Override
public Node getRValue() {
return name.getFirstChild();
}
}
}
| |
/*
* Copyright (C) 2014 Haruki Hasegawa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.h6ah4i.android.media.opensl.audiofx;
import java.lang.ref.WeakReference;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.h6ah4i.android.media.audiofx.IVisualizer;
import com.h6ah4i.android.media.opensl.OpenSLMediaPlayer;
import com.h6ah4i.android.media.opensl.OpenSLMediaPlayerContext;
import com.h6ah4i.android.media.opensl.OpenSLMediaPlayerNativeLibraryLoader;
public class OpenSLVisualizer implements IVisualizer {
private static final String TAG = "Visualizer";
private long mNativeHandle;
private static final boolean HAS_NATIVE;
private int[] mParamIntBuff = new int[2];
private boolean[] mParamBoolBuff = new boolean[1];
private volatile InternalHandler mHandler;
private volatile OnDataCaptureListener mOnDataCaptureListener;
static {
// load native library
HAS_NATIVE = OpenSLMediaPlayerNativeLibraryLoader.loadLibraries();
}
public static int[] sGetCaptureSizeRange() {
int[] range = new int[2];
int result = getCaptureSizeRangeImplNative(range);
throwIllegalStateExceptionIfNeeded(result);
return range;
}
public static int sGetMaxCaptureRate() {
int[] rate = new int[1];
int result = getMaxCaptureRateImplNative(rate);
throwIllegalStateExceptionIfNeeded(result);
return rate[0];
}
public OpenSLVisualizer(OpenSLMediaPlayerContext context) {
if (context == null)
throw new IllegalArgumentException("The argument 'context' cannot be null");
if (HAS_NATIVE) {
mNativeHandle = createNativeImplHandle(
OpenSLMediaPlayer.Internal.getNativeHandle(context),
new WeakReference<OpenSLVisualizer>(this));
}
if (mNativeHandle == 0) {
throw new UnsupportedOperationException("Failed to initialize native layer");
}
mHandler = new InternalHandler(this);
}
@Override
protected void finalize() throws Throwable {
release();
super.finalize();
}
@Override
public void release() {
mOnDataCaptureListener = null;
try {
if (HAS_NATIVE && mNativeHandle != 0) {
deleteNativeImplHandle(mNativeHandle);
mNativeHandle = 0;
}
} catch (Exception e) {
Log.e(TAG, "release()", e);
}
if (mHandler != null) {
mHandler.release();
mHandler = null;
}
}
@Override
public boolean getEnabled() {
checkNativeImplIsAvailable();
final boolean[] enabled = mParamBoolBuff;
int result = getEnabledImplNative(mNativeHandle, enabled);
throwIllegalStateExceptionIfNeeded(result);
return enabled[0];
}
@Override
public int setEnabled(boolean enabled) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = setEnabledImplNative(mNativeHandle, enabled);
throwIllegalStateExceptionIfNeeded(result);
return translateErrorCode(result);
}
@Override
public int getSamplingRate() throws IllegalStateException {
checkNativeImplIsAvailable();
final int[] samplingRate = mParamIntBuff;
int result = getSamplingRateImplNative(mNativeHandle, samplingRate);
throwIllegalStateExceptionIfNeeded(result);
return samplingRate[0];
}
@Override
public int getFft(byte[] fft) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = getFftImplNative(mNativeHandle, fft);
if (result == OpenSLMediaPlayer.Internal.RESULT_ILLEGAL_STATE) {
throw new IllegalStateException("getFft() called while unexpected state");
}
return translateErrorCode(result);
}
@Override
public int getWaveForm(byte[] waveform) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = getWaveformImplNative(mNativeHandle, waveform);
if (result == OpenSLMediaPlayer.Internal.RESULT_ILLEGAL_STATE) {
throw new IllegalStateException("getWaveForm() called while unexpected state");
}
return translateErrorCode(result);
}
@Override
public int getCaptureSize() throws IllegalStateException {
checkNativeImplIsAvailable();
final int[] size = mParamIntBuff;
int result = getCaptureSizeImplNative(mNativeHandle, size);
throwIllegalStateExceptionIfNeeded(result);
return size[0];
}
@Override
public int setCaptureSize(int size) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = setCaptureSizeImplNative(mNativeHandle, size);
if (result == OpenSLMediaPlayer.Internal.RESULT_ILLEGAL_STATE) {
throw new IllegalStateException("setCaptureSize() called while unexpected state");
}
throwIllegalStateExceptionIfNeeded(result);
return translateErrorCode(result);
}
@Override
public int setDataCaptureListener(
OnDataCaptureListener listener,
int rate, boolean waveform, boolean fft) {
checkNativeImplIsAvailable();
if (listener == null) {
rate = 0;
waveform = false;
fft = false;
}
int result = setDataCaptureListenerImplNative(
mNativeHandle, rate, waveform, fft);
if (result == OpenSLMediaPlayer.Internal.RESULT_SUCCESS) {
mOnDataCaptureListener = listener;
}
throwIllegalStateExceptionIfNeeded(result);
return translateErrorCode(result);
}
@Override
public int[] getCaptureSizeRange() throws IllegalStateException {
checkNativeImplIsAvailable();
return sGetCaptureSizeRange();
}
@Override
public int getMaxCaptureRate() throws IllegalStateException {
checkNativeImplIsAvailable();
return sGetMaxCaptureRate();
}
@Override
public int getScalingMode() throws IllegalStateException {
checkNativeImplIsAvailable();
int[] mode = mParamIntBuff;
int result = getScalingModeImplNative(mNativeHandle, mode);
throwIllegalStateExceptionIfNeeded(result);
return mode[0];
}
@Override
public int setScalingMode(int mode) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = setScalingModeImplNative(mNativeHandle, mode);
throwIllegalStateExceptionIfNeeded(result);
return translateErrorCode(result);
}
@Override
public int getMeasurementMode() throws IllegalStateException {
checkNativeImplIsAvailable();
int[] mode = mParamIntBuff;
int result = getMeasurementModeImplNative(mNativeHandle, mode);
throwIllegalStateExceptionIfNeeded(result);
return mode[0];
}
@Override
public int setMeasurementMode(int mode) throws IllegalStateException {
checkNativeImplIsAvailable();
int result = setMeasurementModeImplNative(mNativeHandle, mode);
throwIllegalStateExceptionIfNeeded(result);
return translateErrorCode(result);
}
@Override
public int getMeasurementPeakRms(MeasurementPeakRms measurement) {
checkNativeImplIsAvailable();
if (measurement == null)
return ERROR_BAD_VALUE;
int[] measurementBuff = mParamIntBuff;
int result = getMeasurementPeakRmsImplNative(mNativeHandle, measurementBuff);
throwIllegalStateExceptionIfNeeded(result);
measurement.mPeak = measurementBuff[0];
measurement.mRms = measurementBuff[1];
return translateErrorCode(result);
}
//
// Utilities
//
private void checkNativeImplIsAvailable() throws IllegalStateException {
if (mNativeHandle == 0) {
throw new IllegalStateException("Native implemenation handle is not present");
}
}
private static void throwIllegalStateExceptionIfNeeded(int result) {
if (result == OpenSLMediaPlayer.Internal.RESULT_DEAD_OBJECT)
throw new IllegalStateException();
}
private static int translateErrorCode(int err) {
switch (err) {
case OpenSLMediaPlayer.Internal.RESULT_SUCCESS:
return IVisualizer.SUCCESS;
case OpenSLMediaPlayer.Internal.RESULT_INVALID_HANDLE:
return IVisualizer.ERROR_NO_INIT;
case OpenSLMediaPlayer.Internal.RESULT_ILLEGAL_STATE:
case OpenSLMediaPlayer.Internal.RESULT_CONTROL_LOST:
return IVisualizer.ERROR_INVALID_OPERATION;
case OpenSLMediaPlayer.Internal.RESULT_ILLEGAL_ARGUMENT:
return IVisualizer.ERROR_BAD_VALUE;
case OpenSLMediaPlayer.Internal.RESULT_MEMORY_ALLOCATION_FAILED:
case OpenSLMediaPlayer.Internal.RESULT_RESOURCE_ALLOCATION_FAILED:
return IVisualizer.ERROR_NO_MEMORY;
case OpenSLMediaPlayer.Internal.RESULT_DEAD_OBJECT:
return IVisualizer.ERROR_DEAD_OBJECT;
case OpenSLMediaPlayer.Internal.RESULT_ERROR:
case OpenSLMediaPlayer.Internal.RESULT_INTERNAL_ERROR:
case OpenSLMediaPlayer.Internal.RESULT_CONTENT_NOT_FOUND:
case OpenSLMediaPlayer.Internal.RESULT_CONTENT_UNSUPPORTED:
case OpenSLMediaPlayer.Internal.RESULT_IO_ERROR:
case OpenSLMediaPlayer.Internal.RESULT_PERMISSION_DENIED:
case OpenSLMediaPlayer.Internal.RESULT_TIMED_OUT:
case OpenSLMediaPlayer.Internal.RESULT_IN_ERROR_STATE:
default:
return IVisualizer.ERROR;
}
}
//
// JNI binder internal methods
//
private static final int EVENT_TYPE_ON_WAVEFORM_DATA_CAPTURE = 0;
private static final int EVENT_TYPE_ON_FFT_DATA_CAPTURE = 1;
@SuppressWarnings("unchecked")
private static void raiseCaptureEventFromNative(
Object ref, int type, byte[] data, int samplingRate) {
//
// This method is called from the native implementation
//
WeakReference<OpenSLVisualizer> weak_ref = (WeakReference<OpenSLVisualizer>) ref;
OpenSLVisualizer thiz = weak_ref.get();
if (thiz == null)
return;
InternalHandler handler = thiz.mHandler;
if (handler == null)
return;
switch (type) {
case EVENT_TYPE_ON_WAVEFORM_DATA_CAPTURE:
handler.sendMessage(
handler.obtainMessage(
InternalHandler.MSG_ON_WAVEFORM_DATA_CAPTURE,
samplingRate, 0, data));
break;
case EVENT_TYPE_ON_FFT_DATA_CAPTURE:
handler.sendMessage(
handler.obtainMessage(
InternalHandler.MSG_ON_FFT_DATA_CAPTURE,
samplingRate, 0, data));
break;
}
}
private static class InternalHandler extends Handler {
public static final int MSG_ON_WAVEFORM_DATA_CAPTURE = 1;
public static final int MSG_ON_FFT_DATA_CAPTURE = 2;
private WeakReference<OpenSLVisualizer> mHolder;
public InternalHandler(OpenSLVisualizer holder) {
mHolder = new WeakReference<OpenSLVisualizer>(holder);
}
@Override
public void handleMessage(Message msg) {
final OpenSLVisualizer holder = mHolder.get();
if (holder == null)
return;
final OnDataCaptureListener listener = holder.mOnDataCaptureListener;
if (listener == null)
return;
switch (msg.what) {
case MSG_ON_WAVEFORM_DATA_CAPTURE:
listener.onWaveFormDataCapture(holder, (byte[]) msg.obj, msg.arg1);
break;
case MSG_ON_FFT_DATA_CAPTURE:
listener.onFftDataCapture(holder, (byte[]) msg.obj, msg.arg1);
break;
}
}
public void release() {
removeMessages(MSG_ON_FFT_DATA_CAPTURE);
removeMessages(MSG_ON_WAVEFORM_DATA_CAPTURE);
mHolder.clear();
}
}
//
// Native methods
//
private static native long createNativeImplHandle(
long context_handle, WeakReference<OpenSLVisualizer> weak_thiz);
private static native void deleteNativeImplHandle(long handle);
private static native int setEnabledImplNative(long handle, boolean enabled);
private static native int getEnabledImplNative(long handle, boolean[] enabled);
private static native int getSamplingRateImplNative(long handle, int[] samplingRate);
private static native int getCaptureSizeImplNative(long handle, int[] size);
private static native int setCaptureSizeImplNative(long handle, int size);
private static native int getCaptureSizeRangeImplNative(int[] range);
private static native int getFftImplNative(long handle, byte[] fft);
private static native int getWaveformImplNative(long handle, byte[] waveform);
private static native int setDataCaptureListenerImplNative(
long handle, int rate, boolean waveform, boolean fft);
private static native int getMaxCaptureRateImplNative(int[] rate);
private static native int getScalingModeImplNative(long handle, int[] mode);
private static native int setScalingModeImplNative(long handle, int mode);
private static native int getMeasurementModeImplNative(long handle, int[] mode);
private static native int setMeasurementModeImplNative(long handle, int mode);
private static native int getMeasurementPeakRmsImplNative(long handle, int[] measurement);
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.api.ldap.model.schema.normalizers;
import static org.junit.Assert.assertEquals;
import com.mycila.junit.concurrent.Concurrency;
import com.mycila.junit.concurrent.ConcurrentJunitRunner;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.schema.Normalizer;
import org.apache.directory.api.ldap.model.schema.normalizers.DeepTrimNormalizer;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test the normalizer class
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
@RunWith(ConcurrentJunitRunner.class)
@Concurrency()
public class DeepTrimNormalizerTest
{
@Test
public void testDeepTrimNormalizerNull() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "", normalizer.normalize( ( String ) null ) );
}
@Test
public void testDeepTrimNormalizerEmpty() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "", normalizer.normalize( "" ) );
}
@Test
public void testDeepTrimNormalizerOneSpace() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( " ", normalizer.normalize( " " ) );
}
@Test
public void testDeepTrimNormalizerTwoSpaces() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( " ", normalizer.normalize( " " ) );
}
@Test
public void testDeepTrimNormalizerNSpaces() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( " ", normalizer.normalize( " " ) );
}
@Test
public void testInsignifiantSpacesStringOneChar() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "a", normalizer.normalize( "a" ) );
}
@Test
public void testInsignifiantSpacesStringTwoChars() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "aa", normalizer.normalize( "aa" ) );
}
@Test
public void testInsignifiantSpacesStringNChars() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "aaaaa", normalizer.normalize( "aaaaa" ) );
}
@Test
public void testInsignifiantSpacesStringOneCombining() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
char[] chars = new char[]
{ ' ', 0x0310 };
char[] expected = new char[]
{ ' ', 0x0310 };
assertEquals( new String( expected ), normalizer.normalize( new String( chars ) ) );
}
@Test
public void testInsignifiantSpacesStringNCombining() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
char[] chars = new char[]
{ ' ', 0x0310, ' ', 0x0311, ' ', 0x0312 };
char[] expected = new char[]
{ ' ', 0x0310, ' ', 0x0311, ' ', 0x0312 };
assertEquals( new String( expected ), normalizer.normalize( new String( chars ) ) );
}
@Test
public void testInsignifiantSpacesStringCharsSpaces() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "a", normalizer.normalize( " a" ) );
assertEquals( "a", normalizer.normalize( "a " ) );
assertEquals( "a", normalizer.normalize( " a " ) );
assertEquals( "a a", normalizer.normalize( "a a" ) );
assertEquals( "a a", normalizer.normalize( " a a" ) );
assertEquals( "a a", normalizer.normalize( "a a " ) );
assertEquals( "a a", normalizer.normalize( "a a" ) );
assertEquals( "a a", normalizer.normalize( " a a " ) );
assertEquals( "aaa aaa aaa", normalizer.normalize( " aaa aaa aaa " ) );
}
@Test
public void testNormalizeCharsCombiningSpaces() throws LdapException
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
char[] chars = new char[]
{ ' ', 0x0310, 'a', 'a', ' ', ' ', 0x0311, ' ', ' ', 'a', 0x0311, 0x0312 };
char[] expected = new char[]
{ ' ', 0x0310, 'a', 'a', ' ', ' ', 0x0311, ' ', 'a', 0x0311, 0x0312 };
assertEquals( new String( expected ), normalizer.normalize( new String( chars ) ) );
}
@Test
public void testNormalizeString() throws Exception
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
assertEquals( "abcd", normalizer.normalize( "abcd" ) );
}
@Test
public void testMapToSpace() throws Exception
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
char[] chars = new char[]
{ 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005,
0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x2028, 0x2029, 0x202F, 0x205F };
assertEquals( " ", normalizer.normalize( new String( chars ) ) );
}
@Test
public void testNormalizeIgnore() throws Exception
{
Normalizer normalizer = new DeepTrimNormalizer( "1.1.1" );
char[] chars = new char[58];
int pos = 0;
for ( char c = 0x0000; c < 0x0008; c++ )
{
chars[pos++] = c;
}
for ( char c = 0x000E; c < 0x001F; c++ )
{
chars[pos++] = c;
}
for ( char c = 0x007F; c < 0x0084; c++ )
{
chars[pos++] = c;
}
for ( char c = 0x0086; c < 0x009F; c++ )
{
chars[pos++] = c;
}
chars[pos++] = 0x00AD;
assertEquals( " ", normalizer.normalize( new String( chars ) ) );
}
/*
@Test
public void testSpeed() throws Exception
{
Normalizer normalizer = new DeepTrimNormalizer();
char[] chars = new char[]{ 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0085, 0x00A0, 0x1680,
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
0x2028, 0x2029, 0x202F, 0x205F };
String s = new String( chars );
assertEquals( "", normalizer.normalize( s ) );
String t = "xs crvtbynU Jikl7897790";
Normalizer normalizer2 = new DeepTrimToLowerNormalizer();
String s1 = (String)normalizer2.normalize( t );
long t0 = System.currentTimeMillis();
for ( int i = 0; i < 100000; i++ )
{
normalizer2.normalize( t );
}
long t1 = System.currentTimeMillis();
System.out.println( t1 - t0 );
String s2 = StringTools.deepTrimToLower( t );
t0 = System.currentTimeMillis();
for ( int i = 0; i < 100000; i++ )
{
StringTools.deepTrimToLower( t );
}
t1 = System.currentTimeMillis();
System.out.println( t1 - t0 );
}
*/
}
| |
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.commons.test.performance.dispatcher;
import static org.apache.commons.lang3.Validate.notNull;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openehealth.ipf.commons.test.http.client.Client;
import org.openehealth.ipf.commons.test.http.client.ResponseHandler;
import org.openehealth.ipf.commons.test.performance.MeasurementHistory;
import org.openehealth.ipf.commons.test.performance.MeasurementLostException;
import org.openehealth.ipf.commons.test.performance.StatisticsManager;
import org.springframework.beans.factory.InitializingBean;
import static org.openehealth.ipf.commons.test.performance.utils.MeasurementHistoryXMLUtils.marshall;
/**
* Used to dispatch performance measurements to either a
* <code>StatisticsManager</code>, set with
* {@link #setStatisticsManager(StatisticsManager)}, a performance measurement
* server, if such is configured with
* {@link #setPerformanceMeasurementServerURL(URL)} or both.
*
* @see StatisticsManager
* @author Mitko Kolev
*/
public abstract class MeasurementDispatcher implements InitializingBean {
public final static String CONTENT_ENCODING = "UTF-8";
private final static Logger LOG = LoggerFactory.getLogger(MeasurementDispatcher.class);
private StatisticsManager statisticsManager;
/**
* The client provides the settings of the HTTP Client
*/
private final Client client;
public MeasurementDispatcher() {
client = new Client();
client.setContentType("text/xml; charset=" + CONTENT_ENCODING);
client.setDefaultMaxConnectionsPerHost(5);
client.setHandler(new ResponseHandler() {
@Override
public void handleResponse(InputStream response) throws Exception {
// do nothing
}
});
}
/**
* Dispatches the measurementHistory.
*
* @param measurementHistory
*/
public abstract void dispatch(MeasurementHistory measurementHistory);
/**
* Default implementation
*
* @param measurementHistory
*/
public void defaultDispatch(MeasurementHistory measurementHistory) {
updateStatisticsManager(measurementHistory);
updatePerformanceMeasurementServer(measurementHistory);
}
/**
* The target statisticsManager
*
* @return
*/
public StatisticsManager getStatisticsManager() {
return statisticsManager;
}
/**
* Sets the statisticsManager to which measurement data will be dispatched
* on {@link #dispatch(MeasurementData)}.
*
* @param statisticsManager
* a StatisticsManager instance
*/
public void setStatisticsManager(StatisticsManager statisticsManager) {
notNull(statisticsManager, "The statisticsManager must not be null!");
this.statisticsManager = statisticsManager;
}
/**
* The dispatcher uses the given
* <code>performanceMeasurementServerURL</code> to dispatch the measurement
* history to the performance server, sending a HTTP post request to the
* given <code>performanceMeasurementServerURL</code>.
*
* @param performanceMeasurementServerURL
* the performanceMeasurementServerURL to set
*/
public void setPerformanceMeasurementServerURL(
URL performanceMeasurementServerURL) {
notNull(performanceMeasurementServerURL,
"The performanceMeasurementServerURL must not be null!");
client.setServerUrl(performanceMeasurementServerURL);
}
/**
* @return the performanceMeasurementServerURL
*/
public URL getPerformanceMeasurementServerURL() {
return client.getServerUrl();
}
/**
* @return The max connections per host of the HTTP client used by this
* dispatcher, to send measurements to the performance measurement
* server.
* @see HttpConnectionManagerParams#getDefaultMaxConnectionsPerHost()
*/
public int getDefaultMaxConnectionsPerHost() {
return client.getDefaultMaxConnectionsPerHost();
}
/**
* The max connections per host of the HTTP client used by this dispatcher,
* to send measurements to the performance measurement server. The default
* value is 5
*
* @param numConnections
* The number of connections to be used. The number must be
* greater than 2
*
* @see HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)
*/
public void setDefaultMaxConnectionsPerHost(int numConnections) {
if (numConnections < 2) {
throw new IllegalArgumentException(
"You must set more than 2 default max connections.");
}
client.setDefaultMaxConnectionsPerHost(numConnections);
}
/**
* Updates the contained statistics manager with the given
* <code>measurmentHistory</code>
*
* @param measurementHistory
* a <code>MeasurementHistory</code> object.
*/
protected void updateStatisticsManager(MeasurementHistory measurementHistory) {
if (!isUsingStatisticsManager()) {
return;
}
notNull(measurementHistory, "The measurementHistory must not be null!");
statisticsManager.updateStatistics(measurementHistory);
}
/**
* If a performance measurement server is configured (with URL
* {@link #setPerformanceMeasurementServerURL(String)}), sends an HTTP POST
* request with body the given <code>measurementHistory</code> to that URL.
*
* @param measurementHistory
* a <code>MeasurementHistory</code> object.
*/
protected void updatePerformanceMeasurementServer(
MeasurementHistory measurementHistory) {
if (!isUsingPerformanceMeasurementServer()) {
return;
}
notNull(measurementHistory, "The measurementHistory must not be null!");
try {
// marshal and send the current measurement history
String xml = marshall(measurementHistory);
client.execute(new ByteArrayInputStream(xml
.getBytes(CONTENT_ENCODING)));
} catch (Exception e) {
String msg = "Failed to send performance measurement to a performance measurement server at "
+ getPerformanceMeasurementServerURL();
LOG.error(msg, e);
throw new MeasurementLostException(msg, e);
}
}
/**
* Returns true if the dispatcher will send measurements to a performance
* measurement server, if such is configured with
* {@link #setPerformanceMeasurementServerURL(URL)}
*
* @return true if the {@link #getPerformanceMeasurementServerURL()} will
* return a not null or empty URL. Returns false otherwise.
*/
public boolean isUsingPerformanceMeasurementServer() {
return getPerformanceMeasurementServerURL() != null;
}
/**
* Returns true if the dispatcher will send measurements to a statistics
* manager. It makes sense to use a statistics manager if the application
* collects performance statistics. If this is not the case, a performance
* measurement server should be used.
*
* @return true if there is a statistics manager set with
* {@link #setStatisticsManager(StatisticsManager)}, false
* otherwise.
*/
public boolean isUsingStatisticsManager() {
return statisticsManager != null;
}
/**
* Logs the settings
*/
@Override
public void afterPropertiesSet() throws Exception {
if (isUsingStatisticsManager()) {
LOG.info("The class {} is using a statistics manager ", getClass().getSimpleName());
} else {
LOG.info("The class {} is not configured to use a statistics manager ",
MeasurementDispatcher.class.getSimpleName());
}
// initialize the performance measurement server client
if (isUsingPerformanceMeasurementServer()) {
LOG
.info(getClass().getSimpleName()
+ " is configured to use a performance measurement server with URL "
+ getPerformanceMeasurementServerURL());
} else {
LOG.info("Performance measurement server will not be used, because no URL is configured in {}",
getClass().getSimpleName());
}
}
}
| |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.woodblockwithoutco.beretained;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.JavaFile;
import com.woodblockwithouco.beretained.Retain;
import com.woodblockwithoutco.beretained.android.AndroidClasses;
import com.woodblockwithoutco.beretained.builder.BeRetainedFragmentClassBuilder;
import com.woodblockwithoutco.beretained.builder.FieldsRetainerClassBuilder;
import com.woodblockwithoutco.beretained.builder.NonSupportBeRetainedFragmentClassBuilder;
import com.woodblockwithoutco.beretained.builder.NonSupportFieldsRetainerClassBuilder;
import com.woodblockwithoutco.beretained.builder.SupportBeRetainedFragmentClassBuilder;
import com.woodblockwithoutco.beretained.builder.SupportFieldsRetainerClassBuilder;
import com.woodblockwithoutco.beretained.info.RetainedFieldDescription;
import com.woodblockwithoutco.beretained.utils.TypeMirrorInheritanceChecker;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.NOTE;
/**
* The annotation processor that handles @Retain annotations.
*/
@AutoService(Processor.class)
public class BeRetainedProcessor extends AbstractProcessor {
private enum EnclosingClassType {
SUPPORT,
NON_SUPPORT,
INVALID
}
private Messager messager;
private Filer filer;
private Types types;
private Elements elements;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
messager = processingEnv.getMessager();
types = processingEnv.getTypeUtils();
filer = processingEnv.getFiler();
elements = processingEnv.getElementUtils();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(Retain.class.getCanonicalName());
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_7;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Set<? extends Element> allElements = roundEnv.getElementsAnnotatedWith(Retain.class);
Set<VariableElement> retainedFields = ElementFilter.fieldsIn(allElements);
final Set<TypeMirror> retainEnabledClasses =
new HashSet<>(); //complete set of all retain-enabled classes
final Map<TypeMirror, List<RetainedFieldDescription>> classFieldMap =
new HashMap<>(); //retain-enabled-class -> list of retained fields
final Map<TypeMirror, EnclosingClassType> enclosingClassTypes = new HashMap<>();
for (VariableElement field : retainedFields) {
TypeMirror fieldType = field.asType();
String fieldName = field.getSimpleName().toString();
EnclosingClassType typeOfEnclosingClass = validateAndGetEnclosingClassType(field);
if (EnclosingClassType.INVALID.equals(typeOfEnclosingClass)) {
//stop the processing if field is invalid
return true;
}
TypeMirror enclosingClassType = field.getEnclosingElement().asType(); //type that contains retained fields
retainEnabledClasses.add(enclosingClassType);
enclosingClassTypes.put(enclosingClassType, typeOfEnclosingClass);
List<RetainedFieldDescription> fields = classFieldMap.get(enclosingClassType);
if (fields == null) {
fields = new ArrayList<>();
classFieldMap.put(enclosingClassType, fields);
}
//checking for @NonNull annotations
List<? extends AnnotationMirror> annotationMirrors = field.getAnnotationMirrors();
boolean nullAllowed = true;
for(AnnotationMirror annotationMirror : annotationMirrors) {
if(annotationMirror.toString().equals(AndroidClasses.ANDROID_SUPPORT_ANNOTATION_NON_NULL)) {
nullAllowed = false;
}
if(!nullAllowed) {
break;
}
}
fields.add(new RetainedFieldDescription(fieldType, fieldName, nullAllowed));
}
//now, after all the classes have been found, start actual code generation
for (TypeMirror enclosingType : classFieldMap.keySet()) {
//build the set that doesn't contain current type - it's used to search for inheritance
Set<TypeMirror> retainEnabledClassesWithoutEnclosingType = new HashSet<>(retainEnabledClasses);
retainEnabledClassesWithoutEnclosingType.remove(enclosingType);
writeBeRetainedClasses(classFieldMap.get(enclosingType),
enclosingType,
retainEnabledClassesWithoutEnclosingType,
enclosingClassTypes.get(enclosingType));
}
return true;
}
//validate field - it should not be final or private
private EnclosingClassType validateAndGetEnclosingClassType(VariableElement element) {
//must be package-accessible, protected or public
if (element.getModifiers().contains(Modifier.PRIVATE)) {
messager.printMessage(ERROR, element.getSimpleName() +
" in class " +
element.getEnclosingElement().asType().toString() +
" must have package, protected or public access modifier",
element);
return EnclosingClassType.INVALID;
}
//must not be final
if (element.getModifiers().contains(Modifier.FINAL)) {
messager.printMessage(ERROR, element.getSimpleName() +
" in class " +
element.getEnclosingElement().asType().toString() +
" must not be final",
element);
return EnclosingClassType.INVALID;
}
//this is something I can't imagine happening - fields that are not in the class - but let's check it,
//just to be sure
Element enclosingClass = element.getEnclosingElement();
TypeElement typeElement = elements.getTypeElement(enclosingClass.asType().toString());
if(typeElement == null) {
messager.printMessage(ERROR, "Enclosing type must be a class, but it's a " + enclosingClass.asType().toString(), element);
return EnclosingClassType.INVALID;
}
//check if fields marked with @Retain are in FragmentActivity or Activity
boolean enclosedInFragmentActivity = validateIsEnclosedInFragmentActivity(enclosingClass.asType());
boolean enclosedInActivity = validateIsEnclosedInActivity(enclosingClass.asType());
messager.printMessage(NOTE, "Enclosing class: " + enclosingClass.toString());
messager.printMessage(NOTE, "Is Activity: " + enclosedInActivity);
messager.printMessage(NOTE, "Is FragmentActivity: " + enclosedInFragmentActivity);
if(!enclosedInFragmentActivity && !enclosedInActivity) {
messager.printMessage(ERROR,
"Fields marked with @Retain annotation must be placed in " +
AndroidClasses.ANDROID_SUPPORT_V4_APP_FRAGMENT_ACTIVITY_CLASS_NAME +
" or " +
AndroidClasses.ANDROID_APP_ACTIVITY_CLASS_NAME +
" or their subclasses!",
element);
return EnclosingClassType.INVALID;
}
return enclosedInFragmentActivity ? EnclosingClassType.SUPPORT : EnclosingClassType.NON_SUPPORT;
}
//check if class containing @Retain fields is FragmentActivity or it's subclasses
private boolean validateIsEnclosedInFragmentActivity(TypeMirror enclosingType) {
return TypeMirrorInheritanceChecker.checkTypeMirrorInheritance(enclosingType,
AndroidClasses.ANDROID_SUPPORT_V4_APP_FRAGMENT_ACTIVITY_CLASS_NAME,
types);
}
//check if class containing @Retain fields is Activity or it's subclasses
private boolean validateIsEnclosedInActivity(TypeMirror enclosingType) {
return TypeMirrorInheritanceChecker.checkTypeMirrorInheritance(enclosingType,
AndroidClasses.ANDROID_APP_ACTIVITY_CLASS_NAME,
types);
}
private void writeBeRetainedClasses(List<RetainedFieldDescription> fields,
TypeMirror enclosingClass,
Collection<TypeMirror> retainEnabledClasses,
EnclosingClassType enclosingClassType) {
BeRetainedFragmentClassBuilder beRetainedFragmentClassBuilder = null;
FieldsRetainerClassBuilder bridgeClassBuilder = null;
switch (enclosingClassType) {
case SUPPORT:
beRetainedFragmentClassBuilder =
new SupportBeRetainedFragmentClassBuilder(
enclosingClass,
messager,
retainEnabledClasses,
types
);
bridgeClassBuilder = new SupportFieldsRetainerClassBuilder(enclosingClass, messager);
break;
case NON_SUPPORT:
beRetainedFragmentClassBuilder =
new NonSupportBeRetainedFragmentClassBuilder(
enclosingClass,
messager,
retainEnabledClasses,
types
);
bridgeClassBuilder = new NonSupportFieldsRetainerClassBuilder(enclosingClass, messager);
break;
case INVALID:
throw new IllegalArgumentException("Can't create BeRetained classes for INVALID EnclosingClassType");
}
//these calls must be in this exact order, otherwise addBody() won't have any fields to add
beRetainedFragmentClassBuilder.setFields(fields);
beRetainedFragmentClassBuilder.addBody();
JavaFile fragment = beRetainedFragmentClassBuilder.build();
writeJavaFile(fragment);
bridgeClassBuilder.addBody();
writeJavaFile(bridgeClassBuilder.build());
}
private void writeJavaFile(JavaFile javaFile) {
try {
javaFile.writeTo(filer);
} catch (IOException e) {
messager.printMessage(ERROR, "Error during writing generated class: " + e.getMessage());
}
}
}
| |
package com.msoderlund.litecoinminer;
import static com.msoderlund.litecoinminer.Constants.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.EditText;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActivity extends MainActivity {
EditText et_serv;
EditText et_user;
EditText et_pass;
EditText et_thread;
EditText et_scanTime;
EditText et_retryPause;
SeekBar sb_throttle;
TextView tv_throttle;
CheckBox cb_service;
CheckBox cb_donate;
Button btn_default;
Button btn_save;
Button btn_load;
Button btn_contact;
Spinner spn_priority;
boolean fresh_run=true;
public void loadDefault() {
StringBuilder sb=new StringBuilder();
et_serv.setText(sb.append(DEFAULT_URL).toString());
sb.setLength(0);
et_user.setText(sb.append(DEFAULT_USER).toString());
sb.setLength(0);
et_pass.setText(sb.append(DEFAULT_PASS).toString());
sb.setLength(0);
et_thread.setText(sb.append(DEFAULT_THREAD).toString());
sb.setLength(0);
et_scanTime.setText(sb.append(DEFAULT_SCANTIME).toString());
sb.setLength(0);
et_retryPause.setText(sb.append(DEFAULT_RETRYPAUSE).toString());
sb.setLength(0);
sb_throttle.setProgress((int) (DEFAULT_THROTTLE*100));
spn_priority.setSelection(0); // min priority
cb_service.setChecked(DEFAULT_BACKGROUND);
cb_donate.setChecked(DEFAULT_DONATE);
Log.i("LC", "Settings: defaults loaded");
Toast.makeText(getBaseContext(), "Defaults Loaded", Toast.LENGTH_SHORT).show();
}
public void saveSettings()
{
SharedPreferences settings = getSharedPreferences(PREF_TITLE, 0);
SharedPreferences.Editor editor = settings.edit();
StringBuilder sb= new StringBuilder();
if (verify()==true)
{
sb = new StringBuilder();
String url = sb.append(et_serv.getText()).toString();
sb.setLength(0);
String user = sb.append(et_user.getText()).toString();
sb.setLength(0);
String pass = sb.append(et_pass.getText()).toString();
sb.setLength(0);
int threads = Integer.parseInt(sb.append(et_thread.getText()).toString());
sb.setLength(0);
float throttle = (float) sb_throttle.getProgress()/ 100;
sb.setLength(0);
long scantime = Long.parseLong(sb.append(et_scanTime.getText()).toString());
sb.setLength(0);
long retrypause = Long.parseLong(sb.append(et_retryPause.getText()).toString());
settings = getSharedPreferences(PREF_TITLE, 0);
editor = settings.edit();
editor.putString(PREF_URL, url);
editor.putString(PREF_USER, user);
editor.putString(PREF_PASS, pass);
editor.putInt(PREF_THREAD, threads);
Log.i("LC","Settings: Throttle: "+throttle);
editor.putFloat(PREF_THROTTLE, throttle);
editor.putLong(PREF_SCANTIME, scantime);
editor.putLong(PREF_RETRYPAUSE, retrypause);
editor.putBoolean(PREF_BACKGROUND, cb_service.isChecked());
editor.putBoolean(PREF_DONATE, cb_donate.isChecked());
Log.i("LC", "Settings: Pri "+(String)spn_priority.getSelectedItem());
if (spn_priority.getSelectedItemPosition()==0) {editor.putInt(PREF_PRIORITY, Thread.MIN_PRIORITY); }
if (spn_priority.getSelectedItemPosition()==1) {editor.putInt(PREF_PRIORITY, Thread.NORM_PRIORITY); }
if (spn_priority.getSelectedItemPosition()==2) {editor.putInt(PREF_PRIORITY, Thread.MAX_PRIORITY); }
Log.i("LC", "Settings: Settings saved");
editor.commit();
Toast.makeText(getBaseContext(), "Settings Saved", Toast.LENGTH_SHORT).show();
}
else
{
Log.i("LC", "Settings: Invalid Input");
Toast.makeText(getBaseContext(), "Settings: Errors changed to red", Toast.LENGTH_SHORT).show();
}
editor.commit();
}
public void loadSettings()
{
// if does not exist load default
SharedPreferences settings = getSharedPreferences(PREF_TITLE, 0);
StringBuilder sb= new StringBuilder();
et_serv.setText(settings.getString(PREF_URL, DEFAULT_URL));
et_user.setText(settings.getString(PREF_USER, DEFAULT_USER));
et_pass.setText(settings.getString(PREF_PASS, DEFAULT_PASS));
et_thread.setText( sb.append( settings.getInt(PREF_THREAD, DEFAULT_THREAD)).toString());
sb.setLength(0);
sb_throttle.setProgress( (int) (settings.getFloat(PREF_THROTTLE, DEFAULT_THROTTLE)*100));
et_scanTime.setText( sb.append( settings.getLong(PREF_SCANTIME, DEFAULT_SCANTIME)).toString());
sb.setLength(0);
et_retryPause.setText( sb.append( settings.getLong(PREF_RETRYPAUSE, DEFAULT_RETRYPAUSE)).toString());
cb_service.setChecked( settings.getBoolean(PREF_BACKGROUND, DEFAULT_BACKGROUND));
cb_donate.setChecked( settings.getBoolean(PREF_DONATE, DEFAULT_DONATE));
if(settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY)==Thread.MIN_PRIORITY) {spn_priority.setSelection(0);}
if(settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY)==Thread.NORM_PRIORITY) {spn_priority.setSelection(1);}
if(settings.getInt(PREF_PRIORITY, DEFAULT_PRIORITY)==Thread.MAX_PRIORITY) {spn_priority.setSelection(2);}
Toast.makeText(getBaseContext(), "Settings Loaded", Toast.LENGTH_SHORT).show();
}
public boolean verify()
{
boolean success=true;
StringBuilder sb=new StringBuilder();
//Attempt to verify url
if(et_serv.getText()!=null) {
sb.append(et_serv.getText());
try {
URL url = new URL(sb.toString());
et_serv.setShadowLayer(0, 0, 0, Color.TRANSPARENT);
}
catch (MalformedURLException e) {
Log.i("LC","Settings Error: Invalid URL");
et_serv.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
}
//Verify user
if(et_user.getText()==null) {
Log.i("LC", "Settings Error: no username");
et_user.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else { et_user.setShadowLayer(0, 0, 0, Color.TRANSPARENT); }
//Verify password
if(et_pass.getText()==null) {
Log.i("LC", "Settings Error: no password");
et_pass.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else { et_user.setShadowLayer(0, 0, 0, Color.TRANSPARENT); }
//Verify thread field
if(et_thread.getText()==null) {
Log.i("LC", "Settings Error: no threads");
et_thread.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else {
sb=new StringBuilder();
sb.append(et_thread.getText());
int thread=Integer.parseInt(sb.toString());
if (thread<1) {
Log.i("LC", "Settings Error: must have atleast 1 thread");
et_thread.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else { et_thread.setShadowLayer(0, 0, 0, Color.TRANSPARENT); }
}
// Verify non-0 throttle
if(sb_throttle.getProgress()==0) {sb_throttle.setProgress(1);}
// Verify scantime
if(et_scanTime.getText()==null) {
Log.i("LC", "Settings Error: no scan time");
et_scanTime.setShadowLayer(1, 1, 1, Color.RED);
success = false;
}
else {
sb=new StringBuilder();
sb.append(et_scanTime.getText());
int scanTime=Integer.parseInt(sb.toString());
if (scanTime<1)
{
Log.i("LC", "Settings Error: scantime must be greater than 1ms");
et_scanTime.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else { et_scanTime.setShadowLayer(0, 0, 0, Color.TRANSPARENT); }
}
// Verify retry pause
if(et_retryPause.getText()==null) {
Log.i("LC", "Settings Error: no retry pause");
et_retryPause.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else {
sb=new StringBuilder();
sb.append(et_retryPause.getText());
int scanTime=Integer.parseInt(sb.toString());
if (scanTime<1)
{
Log.i("LC", "Settings Error: retry pause must be greater than 1ms");
et_retryPause.setShadowLayer(1, 1, 1, Color.RED);
success=false;
}
else { et_retryPause.setShadowLayer(0, 0, 0, Color.TRANSPARENT); }
}
Log.i("LC", "Settings: Settings Verified");
// warn about max priority threads
if (spn_priority.getSelectedItemPosition()==2)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Warning");
builder.setMessage("Setting to Thread.MAX_PRIORITY may cause instability");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
builder.show();
}
return success;
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i("LC", "Settings: onCreate");
setContentView(R.layout.activity_settings);
super.onCreate(savedInstanceState);
et_serv =(EditText) findViewById(R.id.settings_editText_server);
et_user =(EditText) findViewById(R.id.settings_editText_user);
et_pass =(EditText) findViewById(R.id.settings_editText_pass);
et_thread = (EditText) findViewById(R.id.settings_editText_threads);
et_scanTime = (EditText) findViewById(R.id.settings_editText_scantime);
et_retryPause= (EditText) findViewById(R.id.settings_editText_retrypause);
sb_throttle = (SeekBar) findViewById(R.id.settings_seekBar_throttle);
cb_service = (CheckBox) findViewById(R.id.settings_checkBox_background);
cb_donate = (CheckBox) findViewById(R.id.settings_checkBox_donate);
btn_default = (Button) findViewById(R.id.settings_btn_default);
btn_save = (Button) findViewById(R.id.settings_btn_save);
btn_load = (Button) findViewById(R.id.settings_btn_load);
tv_throttle=(TextView) findViewById(R.id.settings_textView_throttle_lbl);
spn_priority = (Spinner) findViewById(R.id.settings_spinner_priority);
//Setup throttle seek bar
sb_throttle.setMax(100);
sb_throttle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar.getProgress()<1) {
seekBar.setProgress(1);
}
tv_throttle.setText("Throttle: "+progress+"%");
}
});
// Setup buttons
btn_default.setOnClickListener( new Button.OnClickListener() {
public void onClick(View v) {
loadDefault();
}
});
btn_save.setOnClickListener( new Button.OnClickListener() {
public void onClick(View v) {
saveSettings();
}
});
btn_load.setOnClickListener( new Button.OnClickListener() {
public void onClick(View v) {
loadSettings();
}
});
//Setup nav spinner
Spinner spn_nav = (Spinner) findViewById(R.id.settings_spinner_nav);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
R.array.nav, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spn_nav.setAdapter(adapter);
spn_nav.setSelection(1);
spn_nav.setOnItemSelectedListener(new SpinnerListener(1));
//Setup thread spinner
Spinner spn_pri = (Spinner) findViewById(R.id.settings_spinner_priority);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<?> adapter2 = ArrayAdapter.createFromResource(this,
R.array.priority, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spn_pri.setAdapter(adapter2);
spn_pri.setSelection(1);
//Load Defaults
if (fresh_run==true) {loadSettings();}
fresh_run=false;
}
}
| |
package com.nightlynexus.xkcd;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.ShareActionProvider;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class ComicFragment extends Fragment {
private static final String ENDPOINT = "http://xkcd.com";
private static final String DIRECTORY_NAME = "xkcd";
private static final String KEY_MAX = "KEY_MAX";
private static final String KEY_POSITION = "KEY_POSITION";
private ComicService mRestService;
private View mRetryFrame;
private View mNavBarComic;
private EditText mNumberPicker;
private View mPreviousView;
private View mNextView;
private ViewPager mViewPager;
private PagerAdapter mAdapter;
private ShareActionProvider mShareActionProvider = null;
private int mPendngRequestedComicNumber = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.build();
mRestService = restAdapter.create(ComicService.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_comic, container, false);
mNavBarComic = rootView.findViewById(R.id.nav_bar_comic);
mNumberPicker = (EditText) rootView.findViewById(R.id.number_picker);
mPreviousView = rootView.findViewById(R.id.previous);
mNextView = rootView.findViewById(R.id.next);
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mRetryFrame = rootView.findViewById(R.id.retry_frame);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setNavBarComicAndChildrenEnabled(false);
if (savedInstanceState != null && savedInstanceState.getInt(KEY_MAX) >= 0
&& savedInstanceState.getInt(KEY_POSITION) >= 0) {
setupNumberPicker(savedInstanceState.getInt(KEY_MAX));
setupAdapter(savedInstanceState.getInt(KEY_MAX),
savedInstanceState.getInt(KEY_POSITION));
} else {
mRestService.getComicLatest(new Callback<Comic>() {
private final Callback<Comic> mCallback = this;
@Override
public void success(Comic comic, Response response) {
if (!isAdded()) return;
mRetryFrame.setVisibility(View.GONE);
mViewPager.setVisibility(View.VISIBLE);
setupNumberPicker(comic.getNum());
setupAdapter(comic.getNum(),
getSafeComicIndex(comic.getNum(), comic.getNum()));
}
@Override
public void failure(RetrofitError retrofitError) {
if (!isAdded()) return;
mRetryFrame.findViewById(R.id.retry_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
mRestService.getComicLatest(mCallback);
}
});
mViewPager.setVisibility(View.GONE);
mRetryFrame.setVisibility(View.VISIBLE);
}
});
}
}
private void setupNumberPicker(final int numMax) {
final InputFilter filters[] = new InputFilter[] { new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
final String str = dest.toString().substring(0, dstart)
+ source.toString().substring(start, end)
+ dest.toString().substring(dend);
if (str.length() == 0) return source.subSequence(start, end);
try {
final int number = Integer.parseInt(str);
if (number < 1 || number > numMax) {
return dest.subSequence(dstart, dend);
}
return source.subSequence(start, end);
} catch (NumberFormatException nfe) {
return dest.subSequence(dstart, dend);
}
}
} };
mNumberPicker.setFilters(filters);
mNumberPicker.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
mViewPager.setCurrentItem(Integer.parseInt(s.toString()) - 1);
}
}
});
mPreviousView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
}
});
mNextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
}
});
setNavBarComicAndChildrenEnabled(true);
}
private void setupAdapter(final int num, int position) {
if (mPendngRequestedComicNumber >= 0) {
position = getSafeComicIndex(mPendngRequestedComicNumber, num);
mPendngRequestedComicNumber = -1;
}
mAdapter = new PagerAdapter() {
@Override
public Object instantiateItem(ViewGroup container, final int position) {
final SwipeRefreshLayout swipeRefreshLayout
= new SwipeRefreshLayout(getActivity());
final ScrollView sv = new ScrollView(getActivity());
sv.setFillViewport(true);
final LinearLayout ll = new LinearLayout(getActivity());
final int hp = (int) getResources().getDimension(R.dimen.activity_horizontal_margin);
final int vp = (int) getResources().getDimension(R.dimen.activity_vertical_margin);
ll.setPadding(hp, vp, hp, vp);
final TextView titleView = new TextView(getActivity());
final ProgressBar progress = new ProgressBar(getActivity());
final Button failedButton = new Button(getActivity());
final String[] interblag = getResources().getStringArray(R.array.internet_names);
failedButton.setText(getString(R.string.retry_button_text_comic,
interblag[new Random().nextInt(interblag.length)]));
failedButton.setVisibility(View.GONE);
final TextView tv = new TextView(getActivity());
final ScrollView.LayoutParams params1 = new ScrollView.LayoutParams(
ScrollView.LayoutParams.MATCH_PARENT,
ScrollView.LayoutParams.WRAP_CONTENT);
ll.setLayoutParams(params1);
ll.setGravity(Gravity.CENTER);
ll.setOrientation(LinearLayout.VERTICAL);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
progress.setLayoutParams(params);
failedButton.setLayoutParams(params);
titleView.setLayoutParams(params);
titleView.setPadding(0, 0, 0,
(int) getResources().getDimension(R.dimen.padding_bottom_title));
titleView.setGravity(Gravity.CENTER);
titleView.setTextAppearance(getActivity(), R.style.TitleText);
progress.setVisibility(View.VISIBLE);
final ImageView iv = getImageView();
iv.setVisibility(View.GONE);
final TextView dateView = getDateView();
tv.setLayoutParams(params);
tv.setPadding(0,
(int) getResources().getDimension(R.dimen.padding_top_alt_text), 0, 0);
tv.setGravity(Gravity.CENTER);
tv.setTextIsSelectable(true);
mRestService.getComic(position + 1, new Callback<Comic>() {
private final Callback<Comic> mCallback = this;
@Override
public void success(final Comic comic, Response response) {
if (!isAdded()) return;
titleView.setText(comic.getTitle());
tv.setText(comic.getAlt());
dateView.setText(comic.getDate());
final Target target = new Target() {
@Override
public void onBitmapLoaded(final Bitmap bitmap,
Picasso.LoadedFrom from) {
if (!isAdded()) return;
progress.setVisibility(View.GONE);
iv.setImageBitmap(bitmap);
iv.setTag(false);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((Boolean) iv.getTag()) {
iv.setImageBitmap(bitmap);
iv.setTag(false);
} else {
iv.setImageBitmap(invert(bitmap));
iv.setTag(true);
}
}
});
iv.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final Bitmap bitmapSave
= (Boolean) iv.getTag() ? invert(bitmap) : bitmap;
final String comicName
= position + 1 + " -- " + comic.getTitle();
if (saveBitmap(bitmapSave, comicName)) {
Toast.makeText(getActivity(),
getString(R.string.saved_comic_confirmation,
comicName),
Toast.LENGTH_LONG).show();
}
return true;
}
});
iv.setVisibility(View.VISIBLE);
}
@Override
public void onBitmapFailed(Drawable drawable) {
if (!isAdded()) return;
onFailure();
}
@Override
public void onPrepareLoad(Drawable drawable) {
if (!isAdded()) return;
}
};
tv.setTag(target);
Picasso.with(getActivity()).load(comic.getImg()).into(target);
}
@Override
public void failure(RetrofitError retrofitError) {
if (!isAdded()) return;
onFailure();
}
private void onFailure() {
failedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
failedButton.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
mRestService.getComic(position + 1, mCallback);
}
});
progress.setVisibility(View.GONE);
failedButton.setVisibility(View.VISIBLE);
}
});
ll.addView(titleView);
ll.addView(progress);
ll.addView(failedButton);
ll.addView(iv);
ll.addView(tv);
ll.addView(dateView);
sv.addView(ll);
swipeRefreshLayout.addView(sv);
swipeRefreshLayout.setColorSchemeResources(android.R.color.black);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
final Random random = new Random();
final int position = random.nextInt(num);
mViewPager.setCurrentItem(position, false);
swipeRefreshLayout.setRefreshing(false);
}
});
container.addView(swipeRefreshLayout);
return swipeRefreshLayout;
}
@Override public void destroyItem(ViewGroup container, int position,
Object view) {
container.removeView((View) view);
}
@Override
public int getCount() {
return num;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
};
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageSelected(int i) {
if (mShareActionProvider != null)
mShareActionProvider.setShareIntent(getShareIntent());
mNumberPicker.setText(String.valueOf(i + 1));
mNumberPicker.setSelection(mNumberPicker.length());
mPreviousView.setEnabled(i > 0);
mNextView.setEnabled(i < num - 1);
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
mViewPager.setCurrentItem(position);
}
private void setNavBarComicAndChildrenEnabled(final boolean enabled) {
mNumberPicker.setEnabled(enabled);
mPreviousView.setEnabled(enabled);
mNextView.setEnabled(enabled);
mNavBarComic.setEnabled(enabled);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.comic, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
mShareActionProvider.setShareIntent(getShareIntent());
}
private Intent getShareIntent() {
// hacky to get link
final String link = mAdapter == null
? ENDPOINT : ENDPOINT + "/" + (mViewPager.getCurrentItem() + 1);
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
intent.putExtra(Intent.EXTRA_SUBJECT, ENDPOINT);
intent.putExtra(Intent.EXTRA_TEXT, link);
return intent;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_MAX, mAdapter == null ? -1 : mAdapter.getCount());
outState.putInt(KEY_POSITION, mAdapter == null ? -1 : mViewPager.getCurrentItem());
super.onSaveInstanceState(outState);
}
private static int getSafeComicIndex(final int comicNumber, final int comicNumberMax) {
return ((comicNumber > 0 && comicNumber <= comicNumberMax)
? comicNumber : comicNumberMax) - 1;
}
public void requestComicNumber(final int comicNumber) {
if (mAdapter != null) {
if (comicNumber > mAdapter.getCount()) {
final Intent intentRestart = new Intent(getActivity(), ComicActivity.class);
intentRestart.setAction(ComicActivity.ACTION_UPDATE_COMIC);
getActivity().finish();
getActivity().startActivity(intentRestart);
} else {
mViewPager.setCurrentItem(
getSafeComicIndex(comicNumber, mAdapter.getCount()), false);
}
} else {
mPendngRequestedComicNumber = comicNumber;
}
}
private ImageView getImageView() {
final LinearLayout.LayoutParams paramsImage = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final ImageView iv = new ImageView(getActivity());
iv.setLayoutParams(paramsImage);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setAdjustViewBounds(true);
iv.setContentDescription(getString(
R.string.comic_content_description));
return iv;
}
private TextView getDateView() {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.END;
final TextView dateView = new TextView(getActivity());
dateView.setLayoutParams(params);
dateView.setPadding(0,
(int) getResources().getDimension(R.dimen.padding_top_date), 0, 0);
dateView.setGravity(Gravity.CENTER);
dateView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
return dateView;
}
private static Bitmap invert(Bitmap original) {
// Create mutable Bitmap to invert, argument true makes it mutable
Bitmap inversion = original.copy(Bitmap.Config.ARGB_4444, true);
// Get info about Bitmap
int width = inversion.getWidth();
int height = inversion.getHeight();
int pixels = width * height;
// Get original pixels
int[] pixel = new int[pixels];
inversion.getPixels(pixel, 0, width, 0, 0, width, height);
// Modify pixels
final int RGB_MASK = 0x00FFFFFF;
for (int i = 0; i < pixels; i++)
pixel[i] ^= RGB_MASK;
inversion.setPixels(pixel, 0, width, 0, 0, width, height);
// Return inverted Bitmap
return inversion;
}
private boolean saveBitmap(final Bitmap bmp, final String comicName) {
final String filename = Environment.getExternalStorageDirectory().getPath()
+ "/" + DIRECTORY_NAME + "/" + comicName + ".png";
boolean success = false;
FileOutputStream out = null;
try {
new File(filename).getParentFile().mkdirs();
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return success;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/enums/frequency_cap_event_type.proto
package com.google.ads.googleads.v8.enums;
/**
* <pre>
* Container for enum describing the type of event that the cap applies to.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum}
*/
public final class FrequencyCapEventTypeEnum extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)
FrequencyCapEventTypeEnumOrBuilder {
private static final long serialVersionUID = 0L;
// Use FrequencyCapEventTypeEnum.newBuilder() to construct.
private FrequencyCapEventTypeEnum(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private FrequencyCapEventTypeEnum() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new FrequencyCapEventTypeEnum();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private FrequencyCapEventTypeEnum(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeProto.internal_static_google_ads_googleads_v8_enums_FrequencyCapEventTypeEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeProto.internal_static_google_ads_googleads_v8_enums_FrequencyCapEventTypeEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.class, com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.Builder.class);
}
/**
* <pre>
* The type of event that the cap applies to (e.g. impression).
* </pre>
*
* Protobuf enum {@code google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.FrequencyCapEventType}
*/
public enum FrequencyCapEventType
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
UNSPECIFIED(0),
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
UNKNOWN(1),
/**
* <pre>
* The cap applies on ad impressions.
* </pre>
*
* <code>IMPRESSION = 2;</code>
*/
IMPRESSION(2),
/**
* <pre>
* The cap applies on video ad views.
* </pre>
*
* <code>VIDEO_VIEW = 3;</code>
*/
VIDEO_VIEW(3),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Not specified.
* </pre>
*
* <code>UNSPECIFIED = 0;</code>
*/
public static final int UNSPECIFIED_VALUE = 0;
/**
* <pre>
* Used for return value only. Represents value unknown in this version.
* </pre>
*
* <code>UNKNOWN = 1;</code>
*/
public static final int UNKNOWN_VALUE = 1;
/**
* <pre>
* The cap applies on ad impressions.
* </pre>
*
* <code>IMPRESSION = 2;</code>
*/
public static final int IMPRESSION_VALUE = 2;
/**
* <pre>
* The cap applies on video ad views.
* </pre>
*
* <code>VIDEO_VIEW = 3;</code>
*/
public static final int VIDEO_VIEW_VALUE = 3;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static FrequencyCapEventType valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static FrequencyCapEventType forNumber(int value) {
switch (value) {
case 0: return UNSPECIFIED;
case 1: return UNKNOWN;
case 2: return IMPRESSION;
case 3: return VIDEO_VIEW;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<FrequencyCapEventType>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
FrequencyCapEventType> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<FrequencyCapEventType>() {
public FrequencyCapEventType findValueByNumber(int number) {
return FrequencyCapEventType.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.getDescriptor().getEnumTypes().get(0);
}
private static final FrequencyCapEventType[] VALUES = values();
public static FrequencyCapEventType valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private FrequencyCapEventType(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.FrequencyCapEventType)
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)) {
return super.equals(obj);
}
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum other = (com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum) obj;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Container for enum describing the type of event that the cap applies to.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnumOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeProto.internal_static_google_ads_googleads_v8_enums_FrequencyCapEventTypeEnum_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeProto.internal_static_google_ads_googleads_v8_enums_FrequencyCapEventTypeEnum_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.class, com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.Builder.class);
}
// Construct using com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeProto.internal_static_google_ads_googleads_v8_enums_FrequencyCapEventTypeEnum_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum getDefaultInstanceForType() {
return com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum build() {
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum buildPartial() {
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum result = new com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum(this);
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum) {
return mergeFrom((com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum other) {
if (other == com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum)
private static final com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum();
}
public static com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<FrequencyCapEventTypeEnum>
PARSER = new com.google.protobuf.AbstractParser<FrequencyCapEventTypeEnum>() {
@java.lang.Override
public FrequencyCapEventTypeEnum parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new FrequencyCapEventTypeEnum(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<FrequencyCapEventTypeEnum> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<FrequencyCapEventTypeEnum> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v8.enums.FrequencyCapEventTypeEnum getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
< * Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.onlinesectioning.custom.purdue;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.joda.time.DateTime;
import org.unitime.timetable.onlinesectioning.AcademicSessionInfo;
import org.unitime.timetable.onlinesectioning.custom.ExternalTermProvider;
/**
* @author Tomas Muller
*/
public class SpecialRegistrationInterface {
/** Possible values of the status field in the Spec Reg API responses */
// FIXME: Are there any other values that can be returned?
public static enum ResponseStatus {
success, // call succeeded, data field is filled in
error, // there was an error, see message for details
failure, //TODO: is this status used?
Failed, // present in outJson.status when the validation failed
;
}
/** Possible values for the Spec Reg API mode */
public static enum ApiMode {
PREREG, // pre-registration (Course Requests page is used)
REG, // registration (Scheduling Assistant page is used)
WAITL, // wait-listing (Scheduling Assistant page is used)
;
}
/** Possible values for the requestor role */
public static enum RequestorRole {
STUDENT, // request is done by the student
MANAGER, // request is done by the admin or the advisor on behalf of the student
;
}
/** Completion status of a special registration request */
public static enum CompletionStatus {
inProgress, // there is at least one change (order) that has not been approved, denied or canceled
completed, // all the changes are either approved or denied
cancelled, // all the changes are either approved, denied, or canceled and there is at least one that is canceled
;
}
/** Possible status values of a single override request ({@link Change}, work order in the Spec Reg terms) */
// FIXME: Could there be any other values returned?
public static enum ChangeStatus {
inProgress, // override has been posted, no change has been done to it yet
approved, // override has been approved
denied, // override has been denied
cancelled, // override has been cancelled
deferred, // override has been deferred (it is in progress for UniTime)
escalated, // override has been escalated (it is in progress for UniTime)
;
}
/** Basic format of (mostly all) responses from Spec Reg API */
public static class Response<T> {
/** Response data, depends on the call */
public T data;
/** Success / error message */
public String message;
/** Response status, success or error */
public ResponseStatus status;
}
/** Base representation of a special registration request that is used both during pre-registration and registration */
// submitRegistration request (PREREG, REG)
public static class SpecialRegistration {
/** Special registration request id, only returned */
public String regRequestId;
/** Student PUID including the leading zero */
public String studentId;
/** Banner term (e.g., 201910 for Fall 2018) */
public String term;
/** Banner campus (e.g., PWL) */
public String campus;
/** Special Registration API mode (REG or PREREG) */
public ApiMode mode;
/** List of changes that the student needs overrides for */
public List<Change> changes;
/** Request creation date */
public DateTime dateCreated;
/** Max credit needed (only filled in when max override needs to be increased!) */
public Float maxCredit;
/** Student message provided with the request */
public String requestorNotes;
/** Request completion status (only read, never sent) */
public CompletionStatus completionStatus;
/** Validation request */
public RestrictionsCheckRequest validation;
}
/** Possible operations for a change (work order) */
public static enum ChangeOperation {
ADD, // sections (or the course in case of pre-reg) are being added
DROP, // sections are being dropped (only during registration)
KEEP, // sections are being unchanged, but a registration error was reported on them (e.g., co-requisite, only during registration)
CHGMODE, // change grade mode
CHGVARCR, // change variable credit
CHGVARTL, // request variable title course
;
}
/** Class representing one change (in a signle course) */
public static class Change {
/** Subject area (can be null in case of the MAXI error) */
public String subject;
/** Course number (can be null in case of the MAXI error) */
public String courseNbr;
/** Banner's campus (can be null in case of the MAXI error) */
public String bannerCourseCampus;
/** Banner's subject area (can be null in case of the MAXI error) */
public String bannerSubject;
/** Banner's course number (can be null in case of the MAXI error) */
public String bannerCourseNbr;
/** Comma separated list of crns (only used during registration) */
public String crn;
/** Change operation */
public ChangeOperation operation;
/** Registration errors */
public List<ChangeError> errors;
/** Status of the change */
public ChangeStatus status;
/** Notes attached to the change (only the last one is needed by UniTime) */
public List<ChangeNote> notes;
/** Credit value associated with the course / change, populated by UniTime (only during registration) */
public String credit;
/** Current grade mode (only used when operation = CHGMODE) */
public String currentGradeMode;
/** New grade mode (only used when operation = CHGMODE or CHGVARTL) */
public String selectedGradeMode;
/** New grade mode description (only used when operation = CHGMODE) */
public String selectedGradeModeDescription;
/** Current credit hours (only used when operation = CHGVARCR) */
public String currentCreditHour;
/** Selected credit hours (only used when operation = CHGVARCR or CHGVARTL) */
public String selectedCreditHour;
/** Selected course title (only used when operation = CHGVARTL) */
public String selectedTitle;
/** Selected instructor (only used when operation = CHGVARTL) */
public String selectedInstructor;
/** Selected instructor name (only used when operation = CHGVARTL) */
public String selectedInstructorName;
/** Selected instructor email (only used when operation = CHGVARTL) */
public String selectedInstructorEmail;
/** Selected start date (only used when operation = CHGVARTL, format MM/dd/yy) */
public String selectedStartDate;
/** Selected end date (only used when operation = CHGVARTL, format MM/dd/yy) */
public String selectedEndDate;
/** UniTime's academic session year (only used when operation = CHGVARTL) */
public String apiYear;
/** UniTime's academic session term (only used when operation = CHGVARTL) */
public String apiTerm;
public void setCourse(String subject, String courseNbr, ExternalTermProvider ext, AcademicSessionInfo session) {
this.subject = subject;
this.courseNbr = courseNbr;
if (ext != null && session != null) {
this.bannerSubject = ext.getExternalSubject(session, subject, courseNbr);
this.bannerCourseNbr = ext.getExternalCourseNumber(session, subject, courseNbr);
this.bannerCourseCampus = ext.getExternalCourseCampus(session, subject, courseNbr);
} else {
if (subject.indexOf(" - ") >= 0) {
this.bannerSubject = subject.substring(subject.indexOf(" - ") + 3);
this.bannerCourseCampus = subject.substring(0, subject.indexOf(" - "));
} else {
this.bannerSubject = subject;
this.bannerCourseCampus = session.getCampus();
}
if (courseNbr.length() > 5)
this.bannerCourseNbr = courseNbr.substring(0, 5);
else
this.bannerCourseNbr = courseNbr;
}
}
}
/** Registration error for which there needs to be an override */
public static class ChangeError {
/** Error code */
String code;
/** error message (shown to the student) */
String message;
}
/** Change note */
public static class ChangeNote {
/** Time stamp of the note */
public DateTime dateCreated;
/** Name of the person that provided the note (not used by UniTime) */
public String fullName;
/** Text note */
public String notes;
/** Purpose of the note (not used by UniTime) */
public String purpose;
}
/* - Sumbit Registration -------------------------------------------------- */
// POST /submitRegistration
// Request: SpecialRegistrationRequest
// Returns: SubmitRegistrationResponse
/**
* Payload message for the /submitRegistration request
*/
public static class SpecialRegistrationRequest extends SpecialRegistration {
/**
* PUID (including the leading zero) of the user posting the request (may be a student or an admin/advisor).
* Only sent, not needed in the response.
*/
public String requestorId;
/**
* Role of the requestor (STUDENT or MANAGER).
* Only sent, not needed in the response.
*/
public RequestorRole requestorRole;
/**
* Course requests at the time when the override request was created (only used when mode = PREREG, only sent, not needed in the response)
*/
public List<CourseCredit> courseCreditHrs;
/**
* Alternate course requests at the time when the override request was created (only used when mode = PREREG, only sent, not needed in the response)
*/
public List<CourseCredit> alternateCourseCreditHrs;
}
/**
* Course or alternate requests during pre-registration.
*/
public static class CourseCredit {
/** Subject area */
public String subject;
/** Course number */
public String courseNbr;
/** Banner's campus (can be null in case of the MAXI error) */
public String bannerCourseCampus;
/** Banner's subject area (can be null in case of the MAXI error) */
public String bannerSubject;
/** Banner's course number (can be null in case of the MAXI error) */
public String bannerCourseNbr;
/** Course title */
public String title;
/** Lower bound on the credit */
public Float creditHrs;
/** Alternatives, if provided */
public List<CourseCredit> alternatives;
public void setCourse(String subject, String courseNbr, ExternalTermProvider ext, AcademicSessionInfo session) {
this.subject = subject;
this.courseNbr = courseNbr;
if (ext != null && session != null) {
this.bannerSubject = ext.getExternalSubject(session, subject, courseNbr);
this.bannerCourseNbr = ext.getExternalCourseNumber(session, subject, courseNbr);
this.bannerCourseCampus = ext.getExternalCourseCampus(session, subject, courseNbr);
} else {
if (subject.indexOf(" - ") >= 0) {
this.bannerSubject = subject.substring(subject.indexOf(" - ") + 3);
this.bannerCourseCampus = subject.substring(0, subject.indexOf(" - "));
} else {
this.bannerSubject = subject;
this.bannerCourseCampus = session.getCampus();
}
if (courseNbr.length() > 5)
this.bannerCourseNbr = courseNbr.substring(0, 5);
else
this.bannerCourseNbr = courseNbr;
}
}
}
/** Class representing a special registration that has been cancelled */
public static class CancelledRequest {
/** Subject area */
public String subject;
/** Course number */
public String courseNbr;
/** Comma separated list of CRNs */
public String crn;
/** Special registration request id */
public String regRequestId;
}
/**
* Special registrations for the /submitRegistration response
*
*/
public static class SubmitRegistrationResponse extends SpecialRegistration {
}
/**
* Response message for the /submitRegistration call
* In pre-registration, a separate special registration request is created for each course (plus one for the max credit increase, if needed).
* In registration, a single special registration request
*/
public static class SpecialRegistrationResponseList extends Response<List<SubmitRegistrationResponse>> {
/**
* List of special registrations that have been cancelled (to create these requests).
* (only read, never sent; only used in submitRegistration response during grade mode change)
*/
public List<CancelledRequest> cancelledRequests;
}
/* - Check Special Registration Status ------------------------------------ */
// GET /checkSpecialRegistrationStatus?term=<TERM>&campus=<CAMPUS>&studentId=<PUID>&mode=<REG|PREREG>
// Returns: SpecialRegistrationStatusResponse
/**
* Special registration status for the /checkSpecialRegistrationStatus response
*/
public static class SpecialRegistrationStatus {
/** List of special registrations of the student (of given mode) */
public List<SpecialRegistration> requests;
/** Max credits that the student is allowed at the moment */
public Float maxCredit;
/** Student PUID including the leading zero (needed only in /checkAllSpecialRegistrationStatus) */
public String studentId;
}
/**
* Response message for the /checkSpecialRegistrationStatus call
*/
public static class SpecialRegistrationStatusResponse extends Response<SpecialRegistrationStatus> {
}
/* - Check All Special Registration Status -------------------------------- */
// GET /checkAllSpecialRegistrationStatus?term=<TERM>&campus=<CAMPUS>&studentIds=<PUID1,PUID2,...>&mode=PREREG
// Returns: SpecialRegistrationMultipleStatusResponse
/** Data message for the /checkAllSpecialRegistrationStatus call */
public static class SpecialRegistrationMultipleStatus {
public List<SpecialRegistrationStatus> students;
}
/**
* Response message for the /checkAllSpecialRegistrationStatus call (used only during pre-registration)
*/
public static class SpecialRegistrationMultipleStatusResponse extends Response<SpecialRegistrationMultipleStatus>{
}
/* - Check Eligibility ---------------------------------------------------- */
// GET /checkEligibility?term=<TERM>&campus=<CAMPUS>&studentId=<PUID>&mode=<REG|PREREG>
// Returns: CheckEligibilityResponse
/**
* Student eligibility response for the /checkEligibility response
*/
public static class SpecialRegistrationEligibility {
/** Student PUID including the leading zero */
public String studentId;
/** Banner term */
public String term;
/** Banner campus */
public String campus;
/** Is student eligible to register (pre-reg). Is student eligible to request overrides (reg). */
public Boolean eligible;
/** Detected eligibility problems (in pre-reg: e.g., student has a HOLD) */
public List<EligibilityProblem> eligibilityProblems;
/** Student PIN (NA when not available) */
public String PIN;
}
/**
* Detected student eligibility problem
*/
public static class EligibilityProblem {
/** Problem code (e.g., HOLD) */
String code;
/** Problem message (description) that can bedisplayed to the student */
String message;
}
/**
* Response message for the /checkSpecialRegistrationStatus call
*/
public static class CheckEligibilityResponse extends Response<SpecialRegistrationEligibility> {
/** Registration errors for which overrides can be requested (only used during registration) */
public Set<String> overrides;
/** Student max credit (only used during registration) */
public Float maxCredit;
/** Are there any not-cancelled requests for the student (only used during registration. indication that the Requested Overrides table should be shown) */
public Boolean hasNonCanceledRequest;
}
/* - Schedule Validation -------------------------------------------------- */
// POST /checkRestrictions
// request: CheckRestrictionsRequest
// returns: CheckRestrictionsResponse
/** Registrationn error */
public static class Problem {
/** Error code */
String code;
/** Error message */
String message;
/** Section affected */
String crn;
}
/** Data returned from the schedule validation */
public static class ScheduleRestrictions {
/** List of detected problems */
public List<Problem> problems;
/** Student PUID including the leading zero */
public String sisId;
/** Validation status */
// FIXME: what are the possible values?
public ResponseStatus status;
/** Banner term */
public String term;
/** Computed credit hours */
public Float maxHoursCalc;
/** Error message */
public String message;
}
/** Possible values for the includeReg parameter */
public enum IncludeReg {
Y, // do include students current schedule in the validation
N, // do NOT include students current schedule in the validation
;
}
/** Possible values for the validation mode */
public static enum ValidationMode {
REG, // registration changes
ALT, // alternate changes
WAITL, // wait-list changes
;
}
/** Possible values for the validation operation */
public static enum ValidationOperation {
ADD, // add CRNs
DROP, // drop CRNs
;
}
/** Representation of a single CRN */
public static class Crn {
/** CRN */
String crn;
}
/** Data provided to the schedule validation */
public static class RestrictionsCheckRequest {
/** Student PUID including the leading zero */
public String sisId;
/** Banner term */
public String term;
/** Banner campus */
public String campus;
/** Include the current student's schedule in the validation */
public IncludeReg includeReg;
/** Validation mode (REG or ALT) */
public ValidationMode mode;
/** Schedule changes */
public Map<ValidationOperation, List<Crn>> actions;
}
/** Overrides that have been denied for the student (matching the validation request) */
public static class DeniedRequest {
/** Subject area */
public String subject;
/** Course number */
public String courseNbr;
/** Comma separated lists of CRNs */
public String crn;
/** Registration error code */
public String code;
/** Registration error message */
public String errorMessage;
/** Special Registration API mode (REG or PREREG) */
public ApiMode mode;
}
/** Max credit override that have been denied for the student */
public static class DeniedMaxCredit {
/** Registration error code */
public String code;
/** Registration error message */
public String errorMessage;
/** Max credit denied */
public Float maxCredit;
/** Special Registration API mode (REG or PREREG) */
public ApiMode mode;
}
/** Request message for the /checkRestrictions call */
public static class CheckRestrictionsRequest {
/** Student PUID including the leading zero */
public String studentId;
/** Banner term */
public String term;
/** Banner campus */
public String campus;
/** Special Registration API mode (REG or PREREG) */
public ApiMode mode;
/** Schedule changes */
public RestrictionsCheckRequest changes;
/** Alternatives (only used in pre-registration) */
public RestrictionsCheckRequest alternatives;
}
/** Response message for the /checkRestrictions call */
public static class CheckRestrictionsResponse {
/** Special registrations that would be cancelled if such a request is submitted (used only during registration) */
public List<SpecialRegistration> cancelRegistrationRequests;
/** Matching special registrations that has been denied already (used only during registration) */
public List<DeniedRequest> deniedRequests;
/** Max credit requests that have been denied (student should request that much credit) */
public List<DeniedMaxCredit> deniedMaxCreditRequests;
/** Student eligibility check (used only during registration) */
public SpecialRegistrationEligibility eligible;
/** Student's current max credit (used only during registration) */
public Float maxCredit;
/** Validation response for the schedule changes */
public ScheduleRestrictions outJson;
/** Validation response for the alternative schedule changes (only used in pre-registration) */
public ScheduleRestrictions outJsonAlternatives;
/** List of registrations errors for which the student is allowed to request overrides (used only during registration) */
public Set<String> overrides;
/** Response status, success or error */
public ResponseStatus status;
/** Error message when the validation request fails */
public String message;
}
/* - Cancel Registration Request ------------------------------------------ */
// GET /cancelRegistrationRequestFromUniTime?term=<TERM>&campus=<CAMPUS>&studentId=<PUID>&mode=REG
// Returns: SpecialRegistrationCancelResponse
/**
* Response message for the /cancelRegistrationRequestFromUniTime call
*/
public static class SpecialRegistrationCancelResponse extends Response<String> {
}
/**
* Response message for the /checkStudentGradeModes call
*/
public static class SpecialRegistrationCheckGradeModesResponse extends Response<SpecialRegistrationCheckGradeModes> {
}
/**
* Response message for the /updateRequestorNote call
*/
public static class SpecialRegistrationUpdateResponse extends Response<String> {
}
/**
* List of available grade modes
*/
public static class SpecialRegistrationCheckGradeModes {
/** Student PUID including the leading zero */
public String studentId;
/** Banner term (e.g., 201910 for Fall 2018) */
public String term;
/** Banner campus (e.g., PWL) */
public String campus;
/** List of available grade modes */
List<SpecialRegistrationCurrentGradeMode> gradingModes;
/** List of available variable credits changes */
List<SpecialRegistrationVariableCredit> varCredits;
/** Student's current credit */
public Float currentCredit;
/** Student's max credit */
public Float maxCredit;
}
/**
* Current grade mode of a section with the list of available grade mode changes
*/
public static class SpecialRegistrationCurrentGradeMode {
/** Section CRN */
public String crn;
/** Current grade mode code */
public String gradingMode;
/** Current grade mode desctiption */
public String gradingModeDescription;
/** List of available grading mode changes */
public List<SpecialRegistrationAvailableGradeMode> availableGradingModes;
}
/**
* Variable credit change
*/
public static class SpecialRegistrationVariableCredit {
/** Section CRN */
public String crn;
/** Credit min */
public String creditHrLow;
/** Credit max */
public String creditHrHigh;
/** Credit indicator */
public String creditHrInd;
/** Approvals needed, null or empty when no approvals are not needed */
public List<String> approvals;
}
public static class SpecialRegistrationAvailableGradeMode {
/** Approvals needed, null or empty when no approvals are not needed */
public List<String> approvals;
/** Available grade mode code */
public String gradingMode;
/** Available grade mode desctiption */
public String gradingModeDescription;
}
}
| |
package net.bytebuddy.description.field;
import net.bytebuddy.description.annotation.AnnotationList;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.test.packaging.VisibilityFieldTestHelper;
import org.junit.Before;
import org.junit.Test;
import org.mockito.asm.Type;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class AbstractFieldDescriptionTest {
private Field first, second;
protected abstract FieldDescription describe(Field field);
@Before
public void setUp() throws Exception {
first = FirstSample.class.getDeclaredField("first");
second = SecondSample.class.getDeclaredField("second");
}
@Test
public void testPrecondition() throws Exception {
assertThat(describe(first), not(equalTo(describe(second))));
assertThat(describe(first), equalTo(describe(first)));
assertThat(describe(second), equalTo(describe(second)));
assertThat(describe(first), is((FieldDescription) new FieldDescription.ForLoadedField(first)));
assertThat(describe(second), is((FieldDescription) new FieldDescription.ForLoadedField(second)));
}
@Test
public void testFieldType() throws Exception {
assertThat(describe(first).getFieldType(), is((TypeDescription) new TypeDescription.ForLoadedType(first.getType())));
assertThat(describe(second).getFieldType(), is((TypeDescription) new TypeDescription.ForLoadedType(second.getType())));
}
@Test
public void testFieldName() throws Exception {
assertThat(describe(first).getName(), is(first.getName()));
assertThat(describe(second).getName(), is(second.getName()));
assertThat(describe(first).getInternalName(), is(first.getName()));
assertThat(describe(second).getInternalName(), is(second.getName()));
}
@Test
public void testDescriptor() throws Exception {
assertThat(describe(first).getDescriptor(), is(Type.getDescriptor(first.getType())));
assertThat(describe(second).getDescriptor(), is(Type.getDescriptor(second.getType())));
}
@Test
public void testFieldModifier() throws Exception {
assertThat(describe(first).getModifiers(), is(first.getModifiers()));
assertThat(describe(second).getModifiers(), is(second.getModifiers()));
}
@Test
public void testFieldDeclaringType() throws Exception {
assertThat(describe(first).getDeclaringType(), is((TypeDescription) new TypeDescription.ForLoadedType(first.getDeclaringClass())));
assertThat(describe(second).getDeclaringType(), is((TypeDescription) new TypeDescription.ForLoadedType(second.getDeclaringClass())));
}
@Test
public void testHashCode() throws Exception {
assertThat(describe(first).hashCode(), is(new TypeDescription.ForLoadedType(FirstSample.class).hashCode() + 31 * first.getName().hashCode()));
assertThat(describe(second).hashCode(), is(new TypeDescription.ForLoadedType(SecondSample.class).hashCode() + 31 * second.getName().hashCode()));
assertThat(describe(first).hashCode(), is(describe(first).hashCode()));
assertThat(describe(second).hashCode(), is(describe(second).hashCode()));
assertThat(describe(first).hashCode(), not(is(describe(second).hashCode())));
}
@Test
public void testEquals() throws Exception {
FieldDescription identical = describe(first);
assertThat(identical, equalTo(identical));
FieldDescription equalFirst = mock(FieldDescription.class);
when(equalFirst.getName()).thenReturn(first.getName());
when(equalFirst.getDeclaringType()).thenReturn(new TypeDescription.ForLoadedType(FirstSample.class));
assertThat(describe(first), equalTo(equalFirst));
FieldDescription equalSecond = mock(FieldDescription.class);
when(equalSecond.getName()).thenReturn(second.getName());
when(equalSecond.getDeclaringType()).thenReturn(new TypeDescription.ForLoadedType(SecondSample.class));
assertThat(describe(second), equalTo(equalSecond));
FieldDescription equalFirstTypeOnly = mock(FieldDescription.class);
when(equalFirstTypeOnly.getName()).thenReturn(second.getName());
when(equalFirstTypeOnly.getDeclaringType()).thenReturn(new TypeDescription.ForLoadedType(FirstSample.class));
assertThat(describe(first), not(equalTo(equalFirstTypeOnly)));
FieldDescription equalFirstNameOnly = mock(FieldDescription.class);
when(equalFirstNameOnly.getName()).thenReturn(first.getName());
when(equalFirstNameOnly.getDeclaringType()).thenReturn(new TypeDescription.ForLoadedType(SecondSample.class));
assertThat(describe(first), not(equalTo(equalFirstNameOnly)));
assertThat(describe(first), not(equalTo(equalSecond)));
assertThat(describe(first), not(equalTo(new Object())));
assertThat(describe(first), not(equalTo(null)));
}
@Test
public void testToString() throws Exception {
assertThat(describe(first).toString(), is(first.toString()));
assertThat(describe(second).toString(), is(second.toString()));
}
@Test
public void testSynthetic() throws Exception {
assertThat(describe(first).isSynthetic(), is(first.isSynthetic()));
assertThat(describe(second).isSynthetic(), is(second.isSynthetic()));
}
@Test
public void testIsVisibleTo() throws Exception {
assertThat(describe(PublicType.class.getDeclaredField("publicField"))
.isVisibleTo(new TypeDescription.ForLoadedType(PublicType.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("protectedField"))
.isVisibleTo(new TypeDescription.ForLoadedType(PublicType.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("packagePrivateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(PublicType.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("privateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(PublicType.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("publicField"))
.isVisibleTo(new TypeDescription.ForLoadedType(FirstSample.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("protectedField"))
.isVisibleTo(new TypeDescription.ForLoadedType(FirstSample.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("packagePrivateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(FirstSample.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("privateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(FirstSample.class)), is(false));
assertThat(describe(PublicType.class.getDeclaredField("publicField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("protectedField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PublicType.class.getDeclaredField("packagePrivateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PublicType.class.getDeclaredField("privateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PublicType.class.getDeclaredField("publicField"))
.isVisibleTo(new TypeDescription.ForLoadedType(VisibilityFieldTestHelper.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("protectedField"))
.isVisibleTo(new TypeDescription.ForLoadedType(VisibilityFieldTestHelper.class)), is(true));
assertThat(describe(PublicType.class.getDeclaredField("packagePrivateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(VisibilityFieldTestHelper.class)), is(false));
assertThat(describe(PublicType.class.getDeclaredField("privateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(VisibilityFieldTestHelper.class)), is(false));
assertThat(describe(PackagePrivateType.class.getDeclaredField("publicField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PackagePrivateType.class.getDeclaredField("protectedField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PackagePrivateType.class.getDeclaredField("packagePrivateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PackagePrivateType.class.getDeclaredField("privateField"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(describe(PackagePrivateFieldType.class.getDeclaredField("packagePrivateType"))
.isVisibleTo(new TypeDescription.ForLoadedType(PackagePrivateFieldType.class)), is(true));
assertThat(describe(PackagePrivateFieldType.class.getDeclaredField("packagePrivateType"))
.isVisibleTo(new TypeDescription.ForLoadedType(Object.class)), is(false));
}
@Test
public void testAnnotations() throws Exception {
assertThat(describe(first).getDeclaredAnnotations(), is((AnnotationList) new AnnotationList.Empty()));
assertThat(describe(second).getDeclaredAnnotations(),
is((AnnotationList) new AnnotationList.ForLoadedAnnotation(second.getDeclaredAnnotations())));
}
@Retention(RetentionPolicy.RUNTIME)
private @interface SampleAnnotation {
}
protected static class FirstSample {
private Void first;
}
protected static class SecondSample {
@SampleAnnotation
int second;
}
public static class PublicType {
public Void publicField;
protected Void protectedField;
Void packagePrivateField;
private Void privateField;
}
static class PackagePrivateType {
public Void publicField;
protected Void protectedField;
Void packagePrivateField;
private Void privateField;
}
public static class PackagePrivateFieldType {
public PackagePrivateType packagePrivateType;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.lang;
import org.apache.groovy.internal.util.UncheckedThrow;
import org.codehaus.groovy.reflection.ReflectionCache;
import org.codehaus.groovy.reflection.stdclasses.CachedClosureClass;
import org.codehaus.groovy.runtime.ComposedClosure;
import org.codehaus.groovy.runtime.CurriedClosure;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.codehaus.groovy.runtime.callsite.BooleanClosureWrapper;
import org.codehaus.groovy.runtime.memoize.LRUCache;
import org.codehaus.groovy.runtime.memoize.Memoize;
import org.codehaus.groovy.runtime.memoize.UnlimitedConcurrentCache;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
/**
* Represents any closure object in Groovy.
* <p>
* Groovy allows instances of Closures to be called in a
* short form. For example:
* <pre class="groovyTestCase">
* def a = 1
* def c = { a }
* assert c() == 1
* </pre>
* To be able to use a Closure in this way with your own
* subclass, you need to provide a doCall method with any
* signature you want to. This ensures that
* {@link #getMaximumNumberOfParameters()} and
* {@link #getParameterTypes()} will work too without any
* additional code. If no doCall method is provided a
* closure must be used in its long form like
* <pre class="groovyTestCase">
* def a = 1
* def c = {a}
* assert c.call() == 1
* </pre>
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author <a href="mailto:tug@wilson.co.uk">John Wilson</a>
* @author <a href="mailto:blackdrag@gmx.org">Jochen Theodorou</a>
* @author Graeme Rocher
* @author Paul King
*/
public abstract class Closure<V> extends GroovyObjectSupport implements Cloneable, Runnable, GroovyCallable<V>, Serializable {
/**
* With this resolveStrategy set the closure will attempt to resolve property references and methods to the
* owner first, then the delegate (<b>this is the default strategy</b>).
*
* For example the following code:
* <pre>
* class Test {
* def x = 30
* def y = 40
*
* def run() {
* def data = [ x: 10, y: 20 ]
* def cl = { y = x + y }
* cl.delegate = data
* cl()
* assert x == 30
* assert y == 70
* assert data == [x:10, y:20]
* }
* }
*
* new Test().run()
* </pre>
* Will succeed, because the x and y fields declared in the Test class shadow the variables in the delegate.<p>
* <i>Note that local variables are always looked up first, independently of the resolution strategy.</i>
*/
public static final int OWNER_FIRST = 0;
/**
* With this resolveStrategy set the closure will attempt to resolve property references and methods to the
* delegate first then the owner.
*
* For example the following code:
* <pre class="groovyTestCase">
* class Test {
* def x = 30
* def y = 40
*
* def run() {
* def data = [ x: 10, y: 20 ]
* def cl = { y = x + y }
* cl.delegate = data
* cl.resolveStrategy = Closure.DELEGATE_FIRST
* cl()
* assert x == 30
* assert y == 40
* assert data == [x:10, y:30]
* }
* }
*
* new Test().run()
* </pre>
* This will succeed, because the x and y variables declared in the delegate shadow the fields in the owner class.<p>
* <i>Note that local variables are always looked up first, independently of the resolution strategy.</i>
*/
public static final int DELEGATE_FIRST = 1;
/**
* With this resolveStrategy set the closure will resolve property references and methods to the owner only
* and not call the delegate at all. For example the following code :
*
* <pre>
* class Test {
* def x = 30
* def y = 40
*
* def run() {
* def data = [ x: 10, y: 20, z: 30 ]
* def cl = { y = x + y + z }
* cl.delegate = data
* cl.resolveStrategy = Closure.OWNER_ONLY
* cl()
* println x
* println y
* println data
* }
* }
*
* new Test().run()
* </pre>
*
* will throw "No such property: z" error because even if the z variable is declared in the delegate, no
* lookup is made.<p>
* <i>Note that local variables are always looked up first, independently of the resolution strategy.</i>
*/
public static final int OWNER_ONLY = 2;
/**
* With this resolveStrategy set the closure will resolve property references and methods to the delegate
* only and entirely bypass the owner. For example the following code :
*
* <pre>
* class Test {
* def x = 30
* def y = 40
* def z = 50
*
* def run() {
* def data = [ x: 10, y: 20 ]
* def cl = { y = x + y + z }
* cl.delegate = data
* cl.resolveStrategy = Closure.DELEGATE_ONLY
* cl()
* println x
* println y
* println data
* }
* }
*
* new Test().run()
* </pre>
*
* will throw an error because even if the owner declares a "z" field, the resolution strategy will bypass
* lookup in the owner.<p>
* <i>Note that local variables are always looked up first, independently of the resolution strategy.</i>
*/
public static final int DELEGATE_ONLY = 3;
/**
* With this resolveStrategy set the closure will resolve property references to itself and go
* through the usual MetaClass look-up process. This means that properties and methods are neither resolved
* from the owner nor the delegate, but only on the closure object itself. This allows the developer to
* override getProperty using ExpandoMetaClass of the closure itself.<p>
* <i>Note that local variables are always looked up first, independently of the resolution strategy.</i>
*/
public static final int TO_SELF = 4;
public static final int DONE = 1, SKIP = 2;
private static final Object[] EMPTY_OBJECT_ARRAY = {};
public static final Closure IDENTITY = new Closure<Object>(null) {
public Object doCall(Object args) {
return args;
}
};
private Object delegate;
private Object owner;
private Object thisObject;
private int resolveStrategy = OWNER_FIRST;
private int directive;
protected Class[] parameterTypes;
protected int maximumNumberOfParameters;
private static final long serialVersionUID = 4368710879820278874L;
private BooleanClosureWrapper bcw;
public Closure(Object owner, Object thisObject) {
this.owner = owner;
this.delegate = owner;
this.thisObject = thisObject;
final CachedClosureClass cachedClass = (CachedClosureClass) ReflectionCache.getCachedClass(getClass());
parameterTypes = cachedClass.getParameterTypes();
maximumNumberOfParameters = cachedClass.getMaximumNumberOfParameters();
}
/**
* Constructor used when the "this" object for the Closure is null.
* This is rarely the case in normal Groovy usage.
*
* @param owner the Closure owner
*/
public Closure(Object owner) {
this(owner, null);
}
/**
* Sets the strategy which the closure uses to resolve property references and methods.
* The default is Closure.OWNER_FIRST
*
* @param resolveStrategy The resolve strategy to set
*
* @see groovy.lang.Closure#DELEGATE_FIRST
* @see groovy.lang.Closure#DELEGATE_ONLY
* @see groovy.lang.Closure#OWNER_FIRST
* @see groovy.lang.Closure#OWNER_ONLY
* @see groovy.lang.Closure#TO_SELF
*/
public void setResolveStrategy(int resolveStrategy) {
this.resolveStrategy = resolveStrategy;
}
/**
* Gets the strategy which the closure uses to resolve methods and properties
*
* @return The resolve strategy
*
* @see groovy.lang.Closure#DELEGATE_FIRST
* @see groovy.lang.Closure#DELEGATE_ONLY
* @see groovy.lang.Closure#OWNER_FIRST
* @see groovy.lang.Closure#OWNER_ONLY
* @see groovy.lang.Closure#TO_SELF
*/
public int getResolveStrategy() {
return resolveStrategy;
}
public Object getThisObject(){
return thisObject;
}
public Object getProperty(final String property) {
if ("delegate".equals(property)) {
return getDelegate();
} else if ("owner".equals(property)) {
return getOwner();
} else if ("maximumNumberOfParameters".equals(property)) {
return getMaximumNumberOfParameters();
} else if ("parameterTypes".equals(property)) {
return getParameterTypes();
} else if ("metaClass".equals(property)) {
return getMetaClass();
} else if ("class".equals(property)) {
return getClass();
} else if ("directive".equals(property)) {
return getDirective();
} else if ("resolveStrategy".equals(property)) {
return getResolveStrategy();
} else if ("thisObject".equals(property)) {
return getThisObject();
} else {
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
}
}
private Object getPropertyDelegateFirst(String property) {
if (delegate == null) return getPropertyOwnerFirst(property);
return getPropertyTryThese(property, this.delegate, this.owner);
}
private Object getPropertyOwnerFirst(String property) {
return getPropertyTryThese(property, this.owner, this.delegate);
}
private Object getPropertyTryThese(String property, Object firstTry, Object secondTry) {
try {
// let's try getting the property on the first object
return InvokerHelper.getProperty(firstTry, property);
} catch (MissingPropertyException e1) {
if (secondTry != null && firstTry != this && firstTry != secondTry) {
try {
// let's try getting the property on the second object
return InvokerHelper.getProperty(secondTry, property);
} catch (GroovyRuntimeException e2) {
// ignore, we'll throw e1
}
}
throw e1;
} catch (MissingFieldException e2) { // see GROOVY-5875
if (secondTry != null && firstTry != this && firstTry != secondTry) {
try {
// let's try getting the property on the second object
return InvokerHelper.getProperty(secondTry, property);
} catch (GroovyRuntimeException e3) {
// ignore, we'll throw e2
}
}
throw e2;
}
}
public void setProperty(String property, Object newValue) {
if ("delegate".equals(property)) {
setDelegate(newValue);
} else if ("metaClass".equals(property)) {
setMetaClass((MetaClass) newValue);
} else if ("resolveStrategy".equals(property)) {
setResolveStrategy(((Number) newValue).intValue());
} else if ("directive".equals(property)) {
setDirective(((Number) newValue).intValue());
} else {
switch(resolveStrategy) {
case DELEGATE_FIRST:
setPropertyDelegateFirst(property, newValue);
break;
case DELEGATE_ONLY:
InvokerHelper.setProperty(this.delegate, property, newValue);
break;
case OWNER_ONLY:
InvokerHelper.setProperty(this.owner, property, newValue);
break;
case TO_SELF:
super.setProperty(property, newValue);
break;
default:
setPropertyOwnerFirst(property, newValue);
}
}
}
private void setPropertyDelegateFirst(String property, Object newValue) {
if (delegate == null) setPropertyOwnerFirst(property, newValue);
else setPropertyTryThese(property, newValue, this.delegate, this.owner);
}
private void setPropertyOwnerFirst(String property, Object newValue) {
setPropertyTryThese(property, newValue, this.owner, this.delegate);
}
private void setPropertyTryThese(String property, Object newValue, Object firstTry, Object secondTry) {
try {
// let's try setting the property on the first object
InvokerHelper.setProperty(firstTry, property, newValue);
} catch (GroovyRuntimeException e1) {
if (firstTry != null && firstTry != this && firstTry != secondTry) {
try {
// let's try setting the property on the second object
InvokerHelper.setProperty(secondTry, property, newValue);
return;
} catch (GroovyRuntimeException e2) {
// ignore, we'll throw e1
}
}
throw e1;
}
}
public boolean isCase(Object candidate){
if (bcw==null) {
bcw = new BooleanClosureWrapper(this);
}
return bcw.call(candidate);
}
/**
* Invokes the closure without any parameters, returning any value if applicable.
*
* @return the value if applicable or null if there is no return statement in the closure
*/
public V call() {
final Object[] NOARGS = EMPTY_OBJECT_ARRAY;
return call(NOARGS);
}
@SuppressWarnings("unchecked")
public V call(Object... args) {
try {
return (V) getMetaClass().invokeMethod(this,"doCall",args);
} catch (InvokerInvocationException e) {
UncheckedThrow.rethrow(e.getCause());
return null; // unreachable statement
} catch (Exception e) {
return (V) throwRuntimeException(e);
}
}
/**
* Invokes the closure, returning any value if applicable.
*
* @param arguments could be a single value or a List of values
* @return the value if applicable or null if there is no return statement in the closure
*/
public V call(final Object arguments) {
return call(new Object[]{arguments});
}
protected static Object throwRuntimeException(Throwable throwable) {
if (throwable instanceof RuntimeException) {
throw (RuntimeException) throwable;
} else {
throw new GroovyRuntimeException(throwable.getMessage(), throwable);
}
}
/**
* @return the owner Object to which method calls will go which is
* typically the outer class when the closure is constructed
*/
public Object getOwner() {
return this.owner;
}
/**
* @return the delegate Object to which method calls will go which is
* typically the outer class when the closure is constructed
*/
public Object getDelegate() {
return this.delegate;
}
/**
* Allows the delegate to be changed such as when performing markup building
*
* @param delegate the new delegate
*/
public void setDelegate(Object delegate) {
this.delegate = delegate;
}
/**
* @return the parameter types of the longest doCall method
* of this closure
*/
public Class[] getParameterTypes() {
return parameterTypes;
}
/**
* @return the maximum number of parameters a doCall method
* of this closure can take
*/
public int getMaximumNumberOfParameters() {
return maximumNumberOfParameters;
}
/**
* @return a version of this closure which implements Writable. Note that
* the returned Writable also overrides {@link #toString()} in order
* to allow rendering the result directly to a String.
*/
public Closure asWritable() {
return new WritableClosure();
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
call();
}
/**
* Support for Closure currying.
* <p>
* Typical usage:
* <pre class="groovyTestCase">
* def multiply = { a, b -> a * b }
* def doubler = multiply.curry(2)
* assert doubler(4) == 8
* </pre>
* Note: special treatment is given to Closure vararg-style capability.
* If you curry a vararg parameter, you don't consume the entire vararg array
* but instead the first parameter of the vararg array as the following example shows:
* <pre class="groovyTestCase">
* def a = { one, two, Object[] others -> one + two + others.sum() }
* assert a.parameterTypes.name == ['java.lang.Object', 'java.lang.Object', '[Ljava.lang.Object;']
* assert a(1,2,3,4) == 10
* def b = a.curry(1)
* assert b.parameterTypes.name == ['java.lang.Object', '[Ljava.lang.Object;']
* assert b(2,3,4) == 10
* def c = b.curry(2)
* assert c.parameterTypes.name == ['[Ljava.lang.Object;']
* assert c(3,4) == 10
* def d = c.curry(3)
* assert d.parameterTypes.name == ['[Ljava.lang.Object;']
* assert d(4) == 10
* def e = d.curry(4)
* assert e.parameterTypes.name == ['[Ljava.lang.Object;']
* assert e() == 10
* assert e(5) == 15
* </pre>
*
*
* @param arguments the arguments to bind
* @return the new closure with its arguments bound
*/
public Closure<V> curry(final Object... arguments) {
return new CurriedClosure<V>(this, arguments);
}
/**
* Support for Closure currying.
*
* @param argument the argument to bind
* @return the new closure with the argument bound
* @see #curry(Object...)
*/
public Closure<V> curry(final Object argument) {
return curry(new Object[]{argument});
}
/**
* Support for Closure "right" currying.
* Parameters are supplied on the right rather than left as per the normal curry() method.
* Typical usage:
* <pre class="groovyTestCase">
* def divide = { a, b -> a / b }
* def halver = divide.rcurry(2)
* assert halver(8) == 4
* </pre>
*
* The position of the curried parameters will be calculated lazily, for example,
* if two overloaded doCall methods are available, the supplied arguments plus the
* curried arguments will be concatenated and the result used for method selection.
*
* @param arguments the arguments to bind
* @return the new closure with its arguments bound
* @see #curry(Object...)
*/
public Closure<V> rcurry(final Object... arguments) {
return new CurriedClosure<V>(-arguments.length, this, arguments);
}
/**
* Support for Closure "right" currying.
*
* @param argument the argument to bind
* @return the new closure with the argument bound
* @see #rcurry(Object...)
*/
public Closure<V> rcurry(final Object argument) {
return rcurry(new Object[]{argument});
}
/**
* Support for Closure currying at a given index.
* Parameters are supplied from index position "n".
* Typical usage:
* <pre>
* def caseInsensitive = { a, b -> a.toLowerCase() <=> b.toLowerCase() } as Comparator
* def caseSensitive = { a, b -> a <=> b } as Comparator
* def animals1 = ['ant', 'dog', 'BEE']
* def animals2 = animals1 + ['Cat']
* // curry middle param of this utility method:
* // Collections#binarySearch(List list, Object key, Comparator c)
* def catSearcher = Collections.&binarySearch.ncurry(1, "cat")
* [[animals1, animals2], [caseInsensitive, caseSensitive]].combinations().each{ a, c ->
* def idx = catSearcher(a.sort(c), c)
* print a.sort(c).toString().padRight(22)
* if (idx < 0) println "Not found but would belong in position ${-idx - 1}"
* else println "Found at index $idx"
* }
* // =>
* // [ant, BEE, dog] Not found but would belong in position 2
* // [ant, BEE, Cat, dog] Found at index 2
* // [BEE, ant, dog] Not found but would belong in position 2
* // [BEE, Cat, ant, dog] Not found but would belong in position 3
* </pre>
*
* The position of the curried parameters will be calculated eagerly
* and implies all arguments prior to the specified n index are supplied.
* Default parameter values prior to the n index will not be available.
*
* @param n the index from which to bind parameters (may be -ve in which case it will be normalized)
* @param arguments the arguments to bind
* @return the new closure with its arguments bound
* @see #curry(Object...)
*/
public Closure<V> ncurry(int n, final Object... arguments) {
return new CurriedClosure<V>(n, this, arguments);
}
/**
* Support for Closure currying at a given index.
*
* @param argument the argument to bind
* @return the new closure with the argument bound
* @see #ncurry(int, Object...)
*/
public Closure<V> ncurry(int n, final Object argument) {
return ncurry(n, new Object[]{argument});
}
/**
* Support for Closure forward composition.
* <p>
* Typical usage:
* <pre class="groovyTestCase">
* def times2 = { a -> a * 2 }
* def add3 = { a -> a + 3 }
* def timesThenAdd = times2 >> add3
* // equivalent: timesThenAdd = { a -> add3(times2(a)) }
* assert timesThenAdd(3) == 9
* </pre>
*
* @param other the Closure to compose with the current Closure
* @return the new composed Closure
*/
public <W> Closure<W> rightShift(final Closure<W> other) {
return new ComposedClosure<W>(this, other);
}
/**
* Support for Closure reverse composition.
* <p>
* Typical usage:
* <pre class="groovyTestCase">
* def times2 = { a -> a * 2 }
* def add3 = { a -> a + 3 }
* def addThenTimes = times2 << add3
* // equivalent: addThenTimes = { a -> times2(add3(a)) }
* assert addThenTimes(3) == 12
* </pre>
*
* @param other the Closure to compose with the current Closure
* @return the new composed Closure
*/
public Closure<V> leftShift(final Closure other) {
return new ComposedClosure<V>(other, this);
}
/* *
* Alias for calling a Closure for non-closure arguments.
* <p>
* Typical usage:
* <pre class="groovyTestCase">
* def times2 = { a -> a * 2 }
* def add3 = { a -> a * 3 }
* assert add3 << times2 << 3 == 9
* </pre>
*
* @param arg the argument to call the closure with
* @return the result of calling the Closure
*/
public V leftShift(final Object arg) {
return call(arg);
}
/**
* Creates a caching variant of the closure.
* Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache
* making subsequent calls with the same arguments fast.
* This variant will keep all cached values forever, i.e. till the closure gets garbage-collected.
* The returned function can be safely used concurrently from multiple threads, however, the implementation
* values high average-scenario performance and so concurrent calls on the memoized function with identical argument values
* may not necessarily be able to benefit from each other's cached return value. With this having been mentioned,
* the performance trade-off still makes concurrent use of memoized functions safe and highly recommended.
*
* The cache gets garbage-collected together with the memoized closure.
*
* @return A new closure forwarding to the original one while caching the results
*/
public Closure<V> memoize() {
return Memoize.buildMemoizeFunction(new UnlimitedConcurrentCache(), this);
}
/**
* Creates a caching variant of the closure with upper limit on the cache size.
* Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache
* making subsequent calls with the same arguments fast.
* This variant will keep all values until the upper size limit is reached. Then the values in the cache start rotating
* using the LRU (Last Recently Used) strategy.
* The returned function can be safely used concurrently from multiple threads, however, the implementation
* values high average-scenario performance and so concurrent calls on the memoized function with identical argument values
* may not necessarily be able to benefit from each other's cached return value. With this having been mentioned,
* the performance trade-off still makes concurrent use of memoized functions safe and highly recommended.
*
* The cache gets garbage-collected together with the memoized closure.
*
* @param maxCacheSize The maximum size the cache can grow to
* @return A new function forwarding to the original one while caching the results
*/
public Closure<V> memoizeAtMost(final int maxCacheSize) {
if (maxCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the maxCacheSize parameter for memoizeAtMost.");
return Memoize.buildMemoizeFunction(new LRUCache(maxCacheSize), this);
}
/**
* Creates a caching variant of the closure with automatic cache size adjustment and lower limit
* on the cache size.
* Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache
* making subsequent calls with the same arguments fast.
* This variant allows the garbage collector to release entries from the cache and at the same time allows
* the user to specify how many entries should be protected from the eventual gc-initiated eviction.
* Cached entries exceeding the specified preservation threshold are made available for eviction based on
* the LRU (Last Recently Used) strategy.
* Given the non-deterministic nature of garbage collector, the actual cache size may grow well beyond the limits
* set by the user if memory is plentiful.
* The returned function can be safely used concurrently from multiple threads, however, the implementation
* values high average-scenario performance and so concurrent calls on the memoized function with identical argument values
* may not necessarily be able to benefit from each other's cached return value. Also the protectedCacheSize parameter
* might not be respected accurately in such scenarios for some periods of time. With this having been mentioned,
* the performance trade-off still makes concurrent use of memoized functions safe and highly recommended.
*
* The cache gets garbage-collected together with the memoized closure.
* @param protectedCacheSize Number of cached return values to protect from garbage collection
* @return A new function forwarding to the original one while caching the results
*/
public Closure<V> memoizeAtLeast(final int protectedCacheSize) {
if (protectedCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the protectedCacheSize parameter for memoizeAtLeast.");
return Memoize.buildSoftReferenceMemoizeFunction(protectedCacheSize, new UnlimitedConcurrentCache(), this);
}
/**
* Creates a caching variant of the closure with automatic cache size adjustment and lower and upper limits
* on the cache size.
* Whenever the closure is called, the mapping between the parameters and the return value is preserved in cache
* making subsequent calls with the same arguments fast.
* This variant allows the garbage collector to release entries from the cache and at the same time allows
* the user to specify how many entries should be protected from the eventual gc-initiated eviction.
* Cached entries exceeding the specified preservation threshold are made available for eviction based on
* the LRU (Last Recently Used) strategy.
* Given the non-deterministic nature of garbage collector, the actual cache size may grow well beyond the protected
* size limits set by the user, if memory is plentiful.
* Also, this variant will never exceed in size the upper size limit. Once the upper size limit has been reached,
* the values in the cache start rotating using the LRU (Last Recently Used) strategy.
* The returned function can be safely used concurrently from multiple threads, however, the implementation
* values high average-scenario performance and so concurrent calls on the memoized function with identical argument values
* may not necessarily be able to benefit from each other's cached return value. Also the protectedCacheSize parameter
* might not be respected accurately in such scenarios for some periods of time. With this having been mentioned,
* the performance trade-off still makes concurrent use of memoized functions safe and highly recommended.
*
* The cache gets garbage-collected together with the memoized closure.
* @param protectedCacheSize Number of cached return values to protect from garbage collection
* @param maxCacheSize The maximum size the cache can grow to
* @return A new function forwarding to the original one while caching the results
*/
public Closure<V> memoizeBetween(final int protectedCacheSize, final int maxCacheSize) {
if (protectedCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the protectedCacheSize parameter for memoizeBetween.");
if (maxCacheSize < 0) throw new IllegalArgumentException("A non-negative number is required as the maxCacheSize parameter for memoizeBetween.");
if (protectedCacheSize > maxCacheSize) throw new IllegalArgumentException("The maxCacheSize parameter to memoizeBetween is required to be greater or equal to the protectedCacheSize parameter.");
return Memoize.buildSoftReferenceMemoizeFunction(protectedCacheSize, new LRUCache(maxCacheSize), this);
}
/**
* Builds a trampolined variant of the current closure.
* To prevent stack overflow due to deep recursion, functions can instead leverage the trampoline mechanism
* and avoid recursive calls altogether. Under trampoline, the function is supposed to perform one step of
* the calculation and, instead of a recursive call to itself or another function, it return back a new closure,
* which will be executed by the trampoline as the next step.
* Once a non-closure value is returned, the trampoline stops and returns the value as the final result.
* Here is an example:
* <pre>
* def fact
* fact = { n, total ->
* n == 0 ? total : fact.trampoline(n - 1, n * total)
* }.trampoline()
* def factorial = { n -> fact(n, 1G)}
* println factorial(20) // => 2432902008176640000
* </pre>
*
* @param args Parameters to the closure, so as the trampoline mechanism can call it
* @return A closure, which will execute the original closure on a trampoline.
*/
public Closure<V> trampoline(final Object... args) {
return new TrampolineClosure<V>(this.curry(args));
}
/**
* Builds a trampolined variant of the current closure.
* To prevent stack overflow due to deep recursion, functions can instead leverage the trampoline mechanism
* and avoid recursive calls altogether. Under trampoline, the function is supposed to perform one step of
* the calculation and, instead of a recursive call to itself or another function, it return back a new closure,
* which will be executed by the trampoline as the next step.
* Once a non-closure value is returned, the trampoline stops and returns the value as the final result.
* @return A closure, which will execute the original closure on a trampoline.
* @see #trampoline(Object...)
*/
public Closure<V> trampoline() {
return new TrampolineClosure<V>(this);
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Object clone() {
try {
return super.clone();
} catch (final CloneNotSupportedException e) {
return null;
}
}
/*
* Implementation note:
* This has to be an inner class!
*
* Reason:
* Closure.this.call will call the outer call method, but
* with the inner class as executing object. This means any
* invokeMethod or getProperty call will be called on this
* inner class instead of the outer!
*/
private class WritableClosure extends Closure implements Writable {
public WritableClosure() {
super(Closure.this);
}
/* (non-Javadoc)
* @see groovy.lang.Writable#writeTo(java.io.Writer)
*/
public Writer writeTo(Writer out) throws IOException {
Closure.this.call(new Object[]{out});
return out;
}
/* (non-Javadoc)
* @see groovy.lang.GroovyObject#invokeMethod(java.lang.String, java.lang.Object)
*/
public Object invokeMethod(String method, Object arguments) {
if ("clone".equals(method)) {
return clone();
} else if ("curry".equals(method)) {
return curry((Object[]) arguments);
} else if ("asWritable".equals(method)) {
return asWritable();
} else {
return Closure.this.invokeMethod(method, arguments);
}
}
/* (non-Javadoc)
* @see groovy.lang.GroovyObject#getProperty(java.lang.String)
*/
public Object getProperty(String property) {
return Closure.this.getProperty(property);
}
/* (non-Javadoc)
* @see groovy.lang.GroovyObject#setProperty(java.lang.String, java.lang.Object)
*/
public void setProperty(String property, Object newValue) {
Closure.this.setProperty(property, newValue);
}
/* (non-Javadoc)
* @see groovy.lang.Closure#call()
*/
public Object call() {
return ((Closure) getOwner()).call();
}
/* (non-Javadoc)
* @see groovy.lang.Closure#call(java.lang.Object)
*/
public Object call(Object arguments) {
return ((Closure) getOwner()).call(arguments);
}
public Object call(Object... args) {
return ((Closure) getOwner()).call(args);
}
public Object doCall(Object... args) {
return call(args);
}
/* (non-Javadoc)
* @see groovy.lang.Closure#getDelegate()
*/
public Object getDelegate() {
return Closure.this.getDelegate();
}
/* (non-Javadoc)
* @see groovy.lang.Closure#setDelegate(java.lang.Object)
*/
public void setDelegate(Object delegate) {
Closure.this.setDelegate(delegate);
}
/* (non-Javadoc)
* @see groovy.lang.Closure#getParameterTypes()
*/
public Class[] getParameterTypes() {
return Closure.this.getParameterTypes();
}
/* (non-Javadoc)
* @see groovy.lang.Closure#getParameterTypes()
*/
public int getMaximumNumberOfParameters() {
return Closure.this.getMaximumNumberOfParameters();
}
/* (non-Javadoc)
* @see groovy.lang.Closure#asWritable()
*/
public Closure asWritable() {
return this;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
Closure.this.run();
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Object clone() {
return ((Closure) Closure.this.clone()).asWritable();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return Closure.this.hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object arg0) {
return Closure.this.equals(arg0);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
final StringWriter writer = new StringWriter();
try {
writeTo(writer);
} catch (IOException e) {
return null;
}
return writer.toString();
}
public Closure curry(final Object... arguments) {
return (new CurriedClosure(this, arguments)).asWritable();
}
public void setResolveStrategy(int resolveStrategy) {
Closure.this.setResolveStrategy(resolveStrategy);
}
public int getResolveStrategy() {
return Closure.this.getResolveStrategy();
}
}
/**
* @return Returns the directive.
*/
public int getDirective() {
return directive;
}
/**
* @param directive The directive to set.
*/
public void setDirective(int directive) {
this.directive = directive;
}
/**
* Returns a copy of this closure where the "owner", "delegate" and "thisObject"
* fields are null, allowing proper serialization when one of them is not serializable.
*
* @return a serializable closure.
*
* @since 1.8.5
*/
@SuppressWarnings("unchecked")
public Closure<V> dehydrate() {
Closure<V> result = (Closure<V>) this.clone();
result.delegate = null;
result.owner = null;
result.thisObject = null;
return result;
}
/**
* Returns a copy of this closure for which the delegate, owner and thisObject are
* replaced with the supplied parameters. Use this when you want to rehydrate a
* closure which has been made serializable thanks to the {@link #dehydrate()}
* method.
* @param delegate the closure delegate
* @param owner the closure owner
* @param thisObject the closure "this" object
* @return a copy of this closure where owner, delegate and thisObject are replaced
*
* @since 1.8.5
*/
@SuppressWarnings("unchecked")
public Closure<V> rehydrate(Object delegate, Object owner, Object thisObject) {
Closure<V> result = (Closure<V>) this.clone();
result.delegate = delegate;
result.owner = owner;
result.thisObject = thisObject;
return result;
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vgrechka.phizdetsidea.phizdets.psi.types.functionalParser;
import com.intellij.openapi.util.Pair;
import com.intellij.reference.SoftReference;
import com.intellij.util.Function;
import com.intellij.util.containers.hash.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author vlan
*/
public abstract class FunctionalParserBase<R, T> implements FunctionalParser<R, T> {
@Nullable private String myName = null;
@Override
public String toString() {
return myName != null ? String.format("<%s>", myName) : super.toString();
}
@NotNull
@Override
public R parse(@NotNull List<Token<T>> tokens) throws ParserException {
return parse(tokens, new State()).getFirst();
}
@NotNull
public static <T> FunctionalParser<Token<T>, T> token(@NotNull T type) {
return token(type, null);
}
@NotNull
public static <T> FunctionalParser<Token<T>, T> token(@NotNull final T type, @Nullable final String text) {
return new TokenParser<>(type, text);
}
@NotNull
public static <R, T> FunctionalParser<List<R>, T> many(@NotNull final FunctionalParser<R, T> parser) {
return new ManyParser<>(parser);
}
@NotNull
public static <R, T> FunctionalParser<R, T> maybe(@NotNull final FunctionalParser<R, T> parser) {
return parser.or(FunctionalParserBase.<R, T>pure(null));
}
@NotNull
@Override
public FunctionalParser<R, T> endOfInput() {
return this.thenSkip(FunctionalParserBase.<T>finished());
}
@NotNull
@Override
public FunctionalParser<R, T> named(@NotNull String name) {
myName = name;
return this;
}
@NotNull
@Override
public FunctionalParser<R, T> cached() {
return new CachedParser<>(this);
}
@NotNull
@Override
public <R2> FunctionalParser<Pair<R, R2>, T> then(@NotNull final FunctionalParser<R2, T> parser) {
return new ThenParser<>(this, parser);
}
@NotNull
@Override
public <R2> FunctionalParser<R2, T> skipThen(@NotNull final FunctionalParser<R2, T> parser) {
return second(this.then(parser));
}
@NotNull
@Override
public <R2> FunctionalParser<R, T> thenSkip(@NotNull FunctionalParser<R2, T> parser) {
return first(this.then(parser));
}
@NotNull
@Override
public FunctionalParser<R, T> or(@NotNull final FunctionalParser<R, T> parser) {
return new OrParser<>(this, parser);
}
@NotNull
@Override
public <R2> FunctionalParser<R2, T> map(@NotNull final Function<R, R2> f) {
return new MapParser<>(this, f);
}
@NotNull
private static <R, R2, T> FunctionalParser<R, T> first(@NotNull final FunctionalParser<Pair<R, R2>, T> parser) {
return new FirstParser<>(parser);
}
@NotNull
private static <R, R2, T> FunctionalParser<R2, T> second(@NotNull final FunctionalParser<Pair<R, R2>, T> parser) {
return new SecondParser<>(parser);
}
@NotNull
private static <T> FunctionalParser<Object, T> finished() {
return new FinishedParser<>();
}
@NotNull
private static <R, T> FunctionalParser<R, T> pure(@Nullable final R value) {
return new PureParser<>(value);
}
private static class TokenParser<T> extends FunctionalParserBase<Token<T>, T> {
@NotNull private final T myType;
@Nullable private final String myText;
public TokenParser(@NotNull T type, @Nullable String text) {
myType = type;
myText = text;
}
@NotNull
@Override
public Pair<Token<T>, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final int pos = state.getPos();
if (pos >= tokens.size()) {
throw new ParserException("No tokens left", state);
}
final Token<T> token = tokens.get(pos);
if (token.getType().equals(myType) && (myText == null || token.getText().equals(myText))) {
final int newPos = pos + 1;
final State newState = new State(state, newPos, Math.max(newPos, state.getMax()));
return Pair.create(token, newState);
}
final String expected = myText != null ? String.format("Token(<%s>, \"%s\")", myType, myText) : String.format("Token(<%s>)", myType);
throw new ParserException(String.format("Expected %s, found %s", expected, token), state);
}
}
private static class ManyParser<R, T> extends FunctionalParserBase<List<R>, T> {
@NotNull private final FunctionalParser<R, T> myParser;
public ManyParser(@NotNull FunctionalParser<R, T> parser) {
myParser = parser;
}
@NotNull
@Override
public Pair<List<R>, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final List<R> list = new ArrayList<>();
try {
//noinspection InfiniteLoopStatement
while (true) {
final Pair<R, State> result = myParser.parse(tokens, state);
state = result.getSecond();
list.add(result.getFirst());
}
}
catch (ParserException e) {
return Pair.create(list, new State(state, state.getPos(), e.getState().getMax()));
}
}
}
private static class CachedParser<R, T> extends FunctionalParserBase<R, T> {
@NotNull private final FunctionalParser<R, T> myParser;
@Nullable private Object myKey;
@NotNull private Map<Integer, SoftReference<Pair<R, State>>> myCache;
public CachedParser(@NotNull FunctionalParser<R, T> parser) {
myParser = parser;
myKey = null;
myCache = new HashMap<>();
}
@NotNull
@Override
public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
if (myKey != state.getKey()) {
myKey = state.getKey();
myCache.clear();
}
final SoftReference<Pair<R, State>> ref = myCache.get(state.getPos());
final Pair<R, State> cached = SoftReference.dereference(ref);
if (cached != null) {
return cached;
}
final Pair<R, State> result = myParser.parse(tokens, state);
myCache.put(state.getPos(), new SoftReference<>(result));
return result;
}
}
private static class OrParser<R, T> extends FunctionalParserBase<R, T> {
@NotNull private final FunctionalParserBase<R, T> myFirst;
@NotNull private final FunctionalParser<R, T> mySecond;
public OrParser(@NotNull FunctionalParserBase<R, T> first, @NotNull FunctionalParser<R, T> second) {
myFirst = first;
mySecond = second;
}
@NotNull
@Override
public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
try {
return myFirst.parse(tokens, state);
}
catch (ParserException e) {
return mySecond.parse(tokens, new State(state, state.getPos(), e.getState().getMax()));
}
}
}
private static class FirstParser<R, T, R2> extends FunctionalParserBase<R, T> {
@NotNull private final FunctionalParser<Pair<R, R2>, T> myParser;
public FirstParser(@NotNull FunctionalParser<Pair<R, R2>, T> parser) {
myParser = parser;
}
@NotNull
@Override
public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final Pair<Pair<R, R2>, State> result = myParser.parse(tokens, state);
return Pair.create(result.getFirst().getFirst(), result.getSecond());
}
}
private static class SecondParser<R2, T, R> extends FunctionalParserBase<R2, T> {
@NotNull private final FunctionalParser<Pair<R, R2>, T> myParser;
public SecondParser(@NotNull FunctionalParser<Pair<R, R2>, T> parser) {
myParser = parser;
}
@NotNull
@Override
public Pair<R2, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final Pair<Pair<R, R2>, State> result = myParser.parse(tokens, state);
return Pair.create(result.getFirst().getSecond(), result.getSecond());
}
}
private static class FinishedParser<T> extends FunctionalParserBase<Object, T> {
@NotNull
@Override
public Pair<Object, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final int pos = state.getPos();
if (pos >= tokens.size()) {
return Pair.create(null, state);
}
throw new ParserException(String.format("Expected end of input, found %s", tokens.get(pos)), state);
}
}
private static class PureParser<R, T> extends FunctionalParserBase<R, T> {
@Nullable private final R myValue;
public PureParser(@Nullable R value) {
myValue = value;
}
@NotNull
@Override
public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
return Pair.create(myValue, state);
}
}
private static class ThenParser<R, R2, T> extends FunctionalParserBase<Pair<R, R2>, T> {
@NotNull private final FunctionalParser<R, T> myFirst;
@NotNull private final FunctionalParser<R2, T> mySecond;
public ThenParser(@NotNull FunctionalParser<R, T> first, @NotNull FunctionalParser<R2, T> second) {
myFirst = first;
mySecond = second;
}
@NotNull
@Override
public Pair<Pair<R, R2>, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final Pair<R, State> result1 = myFirst.parse(tokens, state);
final Pair<R2, State> result2 = mySecond.parse(tokens, result1.getSecond());
return Pair.create(Pair.create(result1.getFirst(), result2.getFirst()), result2.getSecond());
}
}
private static class MapParser<R2, T, R> extends FunctionalParserBase<R2, T> {
@NotNull private final FunctionalParserBase<R, T> myParser;
@NotNull private final Function<R, R2> myFunction;
public MapParser(@NotNull FunctionalParserBase<R, T> parser, @NotNull Function<R, R2> function) {
myParser = parser;
myFunction = function;
}
@NotNull
@Override
public Pair<R2, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
final Pair<R, State> result = myParser.parse(tokens, state);
return Pair.create(myFunction.fun(result.getFirst()), result.getSecond());
}
}
}
| |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tcl.simpletv.launcher2;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;
/**
* TextView that draws a bubble behind the text. We cannot use a LineBackgroundSpan
* because we want to make the bubble taller than the text and TextView's clip is
* too aggressive.
*/
public class BubbleTextView extends TextView {
static final float CORNER_RADIUS = 4.0f;
static final float SHADOW_LARGE_RADIUS = 4.0f;
static final float SHADOW_SMALL_RADIUS = 1.75f;
static final float SHADOW_Y_OFFSET = 2.0f;
static final int SHADOW_LARGE_COLOUR = 0xDD000000;
static final int SHADOW_SMALL_COLOUR = 0xCC000000;
static final float PADDING_H = 8.0f;
static final float PADDING_V = 3.0f;
private int mPrevAlpha = -1;
private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
private final Canvas mTempCanvas = new Canvas();
private final Rect mTempRect = new Rect();
private boolean mDidInvalidateForPressedState;
private Bitmap mPressedOrFocusedBackground;
private int mFocusedOutlineColor;
private int mFocusedGlowColor;
private int mPressedOutlineColor;
private int mPressedGlowColor;
private boolean mBackgroundSizeChanged;
private Drawable mBackground;
private boolean mStayPressed;
private CheckLongPressHelper mLongPressHelper;
public BubbleTextView(Context context) {
super(context);
init();
}
public BubbleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mLongPressHelper = new CheckLongPressHelper(this);
mBackground = getBackground();
final Resources res = getContext().getResources();
mFocusedOutlineColor = mFocusedGlowColor = mPressedOutlineColor = mPressedGlowColor =
res.getColor(android.R.color.holo_blue_light);
setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
}
public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) {
Bitmap b = info.getIcon(iconCache);
setCompoundDrawablesWithIntrinsicBounds(null,
new FastBitmapDrawable(b),
null, null);
setText(info.title);
setTag(info);
}
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
if (getLeft() != left || getRight() != right || getTop() != top || getBottom() != bottom) {
mBackgroundSizeChanged = true;
}
return super.setFrame(left, top, right, bottom);
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mBackground || super.verifyDrawable(who);
}
@Override
public void setTag(Object tag) {
if (tag != null) {
LauncherModel.checkItemInfo((ItemInfo) tag);
}
super.setTag(tag);
}
@Override
protected void drawableStateChanged() {
if (isPressed()) {
// In this case, we have already created the pressed outline on ACTION_DOWN,
// so we just need to do an invalidate to trigger draw
if (!mDidInvalidateForPressedState) {
setCellLayoutPressedOrFocusedIcon();
}
} else {
// Otherwise, either clear the pressed/focused background, or create a background
// for the focused state
final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null;
if (!mStayPressed) {
mPressedOrFocusedBackground = null;
}
if (isFocused()) {
if (getLayout() == null) {
// In some cases, we get focus before we have been layed out. Set the
// background to null so that it will get created when the view is drawn.
mPressedOrFocusedBackground = null;
} else {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor);
}
mStayPressed = false;
setCellLayoutPressedOrFocusedIcon();
}
final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null;
if (!backgroundEmptyBefore && backgroundEmptyNow) {
setCellLayoutPressedOrFocusedIcon();
}
}
Drawable d = mBackground;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
super.drawableStateChanged();
}
/**
* Draw this BubbleTextView into the given Canvas.
*
* @param destCanvas the canvas to draw on
* @param padding the horizontal and vertical padding to use when drawing
*/
private void drawWithPadding(Canvas destCanvas, int padding) {
final Rect clipRect = mTempRect;
getDrawingRect(clipRect);
// adjust the clip rect so that we don't include the text label
clipRect.bottom =
getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0);
// Draw the View into the bitmap.
// The translate of scrollX and scrollY is necessary when drawing TextViews, because
// they set scrollX and scrollY to large values to achieve centered text
destCanvas.save();
destCanvas.scale(getScaleX(), getScaleY(),
(getWidth() + padding) / 2, (getHeight() + padding) / 2);
destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2);
destCanvas.clipRect(clipRect, Op.REPLACE);
draw(destCanvas);
destCanvas.restore();
}
/**
* Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) {
final int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
final Bitmap b = Bitmap.createBitmap(
getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
drawWithPadding(canvas, padding);
mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor);
canvas.setBitmap(null);
return b;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// So that the pressed outline is visible immediately when isPressed() is true,
// we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time
// to create it)
if (mPressedOrFocusedBackground == null) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mPressedGlowColor, mPressedOutlineColor);
}
// Invalidate so the pressed state is visible, or set a flag so we know that we
// have to call invalidate as soon as the state is "pressed"
if (isPressed()) {
mDidInvalidateForPressedState = true;
setCellLayoutPressedOrFocusedIcon();
} else {
mDidInvalidateForPressedState = false;
}
mLongPressHelper.postCheckForLongPress();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// If we've touched down and up on an item, and it's still not "pressed", then
// destroy the pressed outline
if (!isPressed()) {
mPressedOrFocusedBackground = null;
}
mLongPressHelper.cancelLongPress();
break;
}
return result;
}
void setStayPressed(boolean stayPressed) {
mStayPressed = stayPressed;
if (!stayPressed) {
mPressedOrFocusedBackground = null;
}
setCellLayoutPressedOrFocusedIcon();
}
void setCellLayoutPressedOrFocusedIcon() {
if (getParent() instanceof ShortcutAndWidgetContainer) {
ShortcutAndWidgetContainer parent = (ShortcutAndWidgetContainer) getParent();
if (parent != null) {
CellLayout layout = (CellLayout) parent.getParent();
layout.setPressedOrFocusedIcon((mPressedOrFocusedBackground != null) ? this : null);
}
}
}
void clearPressedOrFocusedBackground() {
mPressedOrFocusedBackground = null;
setCellLayoutPressedOrFocusedIcon();
}
Bitmap getPressedOrFocusedBackground() {
return mPressedOrFocusedBackground;
}
int getPressedOrFocusedBackgroundPadding() {
return HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
}
@Override
public void draw(Canvas canvas) {
final Drawable background = mBackground;
if (background != null) {
final int scrollX = getScrollX();
final int scrollY = getScrollY();
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, getRight() - getLeft(), getBottom() - getTop());
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// If text is transparent, don't draw any shadow
if (getCurrentTextColor() == getResources().getColor(android.R.color.transparent)) {
getPaint().clearShadowLayer();
super.draw(canvas);
return;
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(getScrollX(), getScrollY() + getExtendedPaddingTop(),
getScrollX() + getWidth(),
getScrollY() + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mBackground != null) mBackground.setCallback(null);
}
@Override
protected boolean onSetAlpha(int alpha) {
if (mPrevAlpha != alpha) {
mPrevAlpha = alpha;
super.onSetAlpha(alpha);
}
return true;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mLongPressHelper.cancelLongPress();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.vector.complex;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.exec.expr.fn.impl.MappifyUtility;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.vector.complex.reader.FieldReader;
import org.apache.drill.exec.vector.complex.writer.BaseWriter;
public class MapUtility {
private final static String TYPE_MISMATCH_ERROR = " does not support heterogeneous value types. All values in the input map must be of the same type. The field [%s] has a differing type [%s].";
/*
* Function to read a value from the field reader, detect the type, construct the appropriate value holder
* and use the value holder to write to the Map.
*/
// TODO : This should be templatized and generated using freemarker
public static void writeToMapFromReader(FieldReader fieldReader, BaseWriter.MapWriter mapWriter, String caller) {
try {
MajorType valueMajorType = fieldReader.getType();
MinorType valueMinorType = valueMajorType.getMinorType();
boolean repeated = false;
if (valueMajorType.getMode() == TypeProtos.DataMode.REPEATED) {
repeated = true;
}
switch (valueMinorType) {
case TINYINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).tinyInt());
} else {
fieldReader.copyAsValue(mapWriter.tinyInt(MappifyUtility.fieldValue));
}
break;
case SMALLINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).smallInt());
} else {
fieldReader.copyAsValue(mapWriter.smallInt(MappifyUtility.fieldValue));
}
break;
case BIGINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).bigInt());
} else {
fieldReader.copyAsValue(mapWriter.bigInt(MappifyUtility.fieldValue));
}
break;
case INT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).integer());
} else {
fieldReader.copyAsValue(mapWriter.integer(MappifyUtility.fieldValue));
}
break;
case UINT1:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).uInt1());
} else {
fieldReader.copyAsValue(mapWriter.uInt1(MappifyUtility.fieldValue));
}
break;
case UINT2:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).uInt2());
} else {
fieldReader.copyAsValue(mapWriter.uInt2(MappifyUtility.fieldValue));
}
break;
case UINT4:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).uInt4());
} else {
fieldReader.copyAsValue(mapWriter.uInt4(MappifyUtility.fieldValue));
}
break;
case UINT8:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).uInt8());
} else {
fieldReader.copyAsValue(mapWriter.uInt8(MappifyUtility.fieldValue));
}
break;
case DECIMAL9:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).decimal9());
} else {
fieldReader.copyAsValue(mapWriter.decimal9(MappifyUtility.fieldValue));
}
break;
case DECIMAL18:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).decimal18());
} else {
fieldReader.copyAsValue(mapWriter.decimal18(MappifyUtility.fieldValue));
}
break;
case DECIMAL28SPARSE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).decimal28Sparse());
} else {
fieldReader.copyAsValue(mapWriter.decimal28Sparse(MappifyUtility.fieldValue));
}
break;
case DECIMAL38SPARSE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).decimal38Sparse());
} else {
fieldReader.copyAsValue(mapWriter.decimal38Sparse(MappifyUtility.fieldValue));
}
break;
case VARDECIMAL:
if (repeated) {
fieldReader.copyAsValue(
mapWriter.list(MappifyUtility.fieldValue)
.varDecimal(valueMajorType.getScale(), valueMajorType.getPrecision()));
} else {
fieldReader.copyAsValue(
mapWriter.varDecimal(MappifyUtility.fieldValue, valueMajorType.getScale(), valueMajorType.getPrecision()));
}
break;
case DATE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).date());
} else {
fieldReader.copyAsValue(mapWriter.date(MappifyUtility.fieldValue));
}
break;
case TIME:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).time());
} else {
fieldReader.copyAsValue(mapWriter.time(MappifyUtility.fieldValue));
}
break;
case TIMESTAMP:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).timeStamp());
} else {
fieldReader.copyAsValue(mapWriter.timeStamp(MappifyUtility.fieldValue));
}
break;
case INTERVAL:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).interval());
} else {
fieldReader.copyAsValue(mapWriter.interval(MappifyUtility.fieldValue));
}
break;
case INTERVALDAY:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).intervalDay());
} else {
fieldReader.copyAsValue(mapWriter.intervalDay(MappifyUtility.fieldValue));
}
break;
case INTERVALYEAR:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).intervalYear());
} else {
fieldReader.copyAsValue(mapWriter.intervalYear(MappifyUtility.fieldValue));
}
break;
case FLOAT4:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).float4());
} else {
fieldReader.copyAsValue(mapWriter.float4(MappifyUtility.fieldValue));
}
break;
case FLOAT8:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).float8());
} else {
fieldReader.copyAsValue(mapWriter.float8(MappifyUtility.fieldValue));
}
break;
case BIT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).bit());
} else {
fieldReader.copyAsValue(mapWriter.bit(MappifyUtility.fieldValue));
}
break;
case VARCHAR:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).varChar());
} else {
fieldReader.copyAsValue(mapWriter.varChar(MappifyUtility.fieldValue));
}
break;
case VARBINARY:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).varBinary());
} else {
fieldReader.copyAsValue(mapWriter.varBinary(MappifyUtility.fieldValue));
}
break;
case MAP:
if (valueMajorType.getMode() == TypeProtos.DataMode.REPEATED) {
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).map());
} else {
fieldReader.copyAsValue(mapWriter.map(MappifyUtility.fieldValue));
}
break;
case LIST:
fieldReader.copyAsValue(mapWriter.list(MappifyUtility.fieldValue).list());
break;
default:
throw new DrillRuntimeException(String.format(caller
+ " does not support input of type: %s", valueMinorType));
}
} catch (ClassCastException e) {
final MaterializedField field = fieldReader.getField();
throw new DrillRuntimeException(String.format(caller + TYPE_MISMATCH_ERROR, field.getName(), field.getType()));
}
}
public static void writeToMapFromReader(FieldReader fieldReader, BaseWriter.MapWriter mapWriter,
String fieldName, String caller) {
try {
MajorType valueMajorType = fieldReader.getType();
MinorType valueMinorType = valueMajorType.getMinorType();
boolean repeated = false;
if (valueMajorType.getMode() == TypeProtos.DataMode.REPEATED) {
repeated = true;
}
switch (valueMinorType) {
case TINYINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).tinyInt());
} else {
fieldReader.copyAsValue(mapWriter.tinyInt(fieldName));
}
break;
case SMALLINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).smallInt());
} else {
fieldReader.copyAsValue(mapWriter.smallInt(fieldName));
}
break;
case BIGINT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).bigInt());
} else {
fieldReader.copyAsValue(mapWriter.bigInt(fieldName));
}
break;
case INT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).integer());
} else {
fieldReader.copyAsValue(mapWriter.integer(fieldName));
}
break;
case UINT1:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).uInt1());
} else {
fieldReader.copyAsValue(mapWriter.uInt1(fieldName));
}
break;
case UINT2:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).uInt2());
} else {
fieldReader.copyAsValue(mapWriter.uInt2(fieldName));
}
break;
case UINT4:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).uInt4());
} else {
fieldReader.copyAsValue(mapWriter.uInt4(fieldName));
}
break;
case UINT8:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).uInt8());
} else {
fieldReader.copyAsValue(mapWriter.uInt8(fieldName));
}
break;
case DECIMAL9:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).decimal9());
} else {
fieldReader.copyAsValue(mapWriter.decimal9(fieldName));
}
break;
case DECIMAL18:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).decimal18());
} else {
fieldReader.copyAsValue(mapWriter.decimal18(fieldName));
}
break;
case DECIMAL28SPARSE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).decimal28Sparse());
} else {
fieldReader.copyAsValue(mapWriter.decimal28Sparse(fieldName));
}
break;
case DECIMAL38SPARSE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).decimal38Sparse());
} else {
fieldReader.copyAsValue(mapWriter.decimal38Sparse(fieldName));
}
break;
case VARDECIMAL:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).varDecimal(valueMajorType.getScale(), valueMajorType.getPrecision()));
} else {
fieldReader.copyAsValue(mapWriter.varDecimal(fieldName, valueMajorType.getScale(), valueMajorType.getPrecision()));
}
break;
case DATE:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).date());
} else {
fieldReader.copyAsValue(mapWriter.date(fieldName));
}
break;
case TIME:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).time());
} else {
fieldReader.copyAsValue(mapWriter.time(fieldName));
}
break;
case TIMESTAMP:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).timeStamp());
} else {
fieldReader.copyAsValue(mapWriter.timeStamp(fieldName));
}
break;
case INTERVAL:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).interval());
} else {
fieldReader.copyAsValue(mapWriter.interval(fieldName));
}
break;
case INTERVALDAY:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).intervalDay());
} else {
fieldReader.copyAsValue(mapWriter.intervalDay(fieldName));
}
break;
case INTERVALYEAR:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).intervalYear());
} else {
fieldReader.copyAsValue(mapWriter.intervalYear(fieldName));
}
break;
case FLOAT4:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).float4());
} else {
fieldReader.copyAsValue(mapWriter.float4(fieldName));
}
break;
case FLOAT8:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).float8());
} else {
fieldReader.copyAsValue(mapWriter.float8(fieldName));
}
break;
case BIT:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).bit());
} else {
fieldReader.copyAsValue(mapWriter.bit(fieldName));
}
break;
case VARCHAR:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).varChar());
} else {
fieldReader.copyAsValue(mapWriter.varChar(fieldName));
}
break;
case VARBINARY:
if (repeated) {
fieldReader.copyAsValue(mapWriter.list(fieldName).varBinary());
} else {
fieldReader.copyAsValue(mapWriter.varBinary(fieldName));
}
break;
case MAP:
if (valueMajorType.getMode() == TypeProtos.DataMode.REPEATED) {
fieldReader.copyAsValue(mapWriter.list(fieldName).map());
} else {
fieldReader.copyAsValue(mapWriter.map(fieldName));
}
break;
case LIST:
fieldReader.copyAsValue(mapWriter.list(fieldName).list());
break;
default:
throw new DrillRuntimeException(String.format(caller
+ " does not support input of type: %s", valueMinorType));
}
} catch (ClassCastException e) {
final MaterializedField field = fieldReader.getField();
throw new DrillRuntimeException(String.format(caller + TYPE_MISMATCH_ERROR, field.getName(), field.getType()));
}
}
public static void writeToListFromReader(FieldReader fieldReader, BaseWriter.ListWriter listWriter, String caller) {
try {
MajorType valueMajorType = fieldReader.getType();
MinorType valueMinorType = valueMajorType.getMinorType();
boolean repeated = false;
if (valueMajorType.getMode() == TypeProtos.DataMode.REPEATED) {
repeated = true;
}
switch (valueMinorType) {
case TINYINT:
fieldReader.copyAsValue(listWriter.tinyInt());
break;
case SMALLINT:
fieldReader.copyAsValue(listWriter.smallInt());
break;
case BIGINT:
fieldReader.copyAsValue(listWriter.bigInt());
break;
case INT:
fieldReader.copyAsValue(listWriter.integer());
break;
case UINT1:
fieldReader.copyAsValue(listWriter.uInt1());
break;
case UINT2:
fieldReader.copyAsValue(listWriter.uInt2());
break;
case UINT4:
fieldReader.copyAsValue(listWriter.uInt4());
break;
case UINT8:
fieldReader.copyAsValue(listWriter.uInt8());
break;
case DECIMAL9:
fieldReader.copyAsValue(listWriter.decimal9());
break;
case DECIMAL18:
fieldReader.copyAsValue(listWriter.decimal18());
break;
case DECIMAL28SPARSE:
fieldReader.copyAsValue(listWriter.decimal28Sparse());
break;
case DECIMAL38SPARSE:
fieldReader.copyAsValue(listWriter.decimal38Sparse());
break;
case VARDECIMAL:
fieldReader.copyAsValue(listWriter.varDecimal(valueMajorType.getScale(), valueMajorType.getPrecision()));
break;
case DATE:
fieldReader.copyAsValue(listWriter.date());
break;
case TIME:
fieldReader.copyAsValue(listWriter.time());
break;
case TIMESTAMP:
fieldReader.copyAsValue(listWriter.timeStamp());
break;
case INTERVAL:
fieldReader.copyAsValue(listWriter.interval());
break;
case INTERVALDAY:
fieldReader.copyAsValue(listWriter.intervalDay());
break;
case INTERVALYEAR:
fieldReader.copyAsValue(listWriter.intervalYear());
break;
case FLOAT4:
fieldReader.copyAsValue(listWriter.float4());
break;
case FLOAT8:
fieldReader.copyAsValue(listWriter.float8());
break;
case BIT:
fieldReader.copyAsValue(listWriter.bit());
break;
case VARCHAR:
fieldReader.copyAsValue(listWriter.varChar());
break;
case VARBINARY:
fieldReader.copyAsValue(listWriter.varBinary());
break;
case MAP:
fieldReader.copyAsValue(listWriter.map());
break;
case LIST:
fieldReader.copyAsValue(listWriter.list());
break;
default:
throw new DrillRuntimeException(String.format(caller
+ " function does not support input of type: %s", valueMinorType));
}
} catch (ClassCastException e) {
final MaterializedField field = fieldReader.getField();
throw new DrillRuntimeException(String.format(caller + TYPE_MISMATCH_ERROR, field.getName(), field.getType()));
}
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.v4.runtime.atn;
import org.antlr.v4.runtime.dfa.DFAState;
import org.antlr.v4.runtime.misc.IntervalSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.UUID;
public abstract class ATNSimulator {
/**
* @deprecated Use {@link ATNDeserializer#SERIALIZED_VERSION} instead.
*/
@Deprecated
public static final int SERIALIZED_VERSION;
static {
SERIALIZED_VERSION = ATNDeserializer.SERIALIZED_VERSION;
}
/**
* This is the current serialized UUID.
* @deprecated Use {@link ATNDeserializer#checkCondition(boolean)} instead.
*/
@Deprecated
public static final UUID SERIALIZED_UUID;
static {
SERIALIZED_UUID = ATNDeserializer.SERIALIZED_UUID;
}
/** Must distinguish between missing edge and edge we know leads nowhere */
public static final DFAState ERROR;
public final ATN atn;
/** The context cache maps all PredictionContext objects that are equals()
* to a single cached copy. This cache is shared across all contexts
* in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet
* to use only cached nodes/graphs in addDFAState(). We don't want to
* fill this during closure() since there are lots of contexts that
* pop up but are not used ever again. It also greatly slows down closure().
*
* <p>This cache makes a huge difference in memory and a little bit in speed.
* For the Java grammar on java.*, it dropped the memory requirements
* at the end from 25M to 16M. We don't store any of the full context
* graphs in the DFA because they are limited to local context only,
* but apparently there's a lot of repetition there as well. We optimize
* the config contexts before storing the config set in the DFA states
* by literally rebuilding them with cached subgraphs only.</p>
*
* <p>I tried a cache for use during closure operations, that was
* whacked after each adaptivePredict(). It cost a little bit
* more time I think and doesn't save on the overall footprint
* so it's not worth the complexity.</p>
*/
protected final PredictionContextCache sharedContextCache;
static {
ERROR = new DFAState(new ATNConfigSet());
ERROR.stateNumber = Integer.MAX_VALUE;
}
public ATNSimulator(ATN atn,
PredictionContextCache sharedContextCache)
{
this.atn = atn;
this.sharedContextCache = sharedContextCache;
}
public abstract void reset();
/**
* Clear the DFA cache used by the current instance. Since the DFA cache may
* be shared by multiple ATN simulators, this method may affect the
* performance (but not accuracy) of other parsers which are being used
* concurrently.
*
* @throws UnsupportedOperationException if the current instance does not
* support clearing the DFA.
*
* @since 4.3
*/
public void clearDFA() {
throw new UnsupportedOperationException("This ATN simulator does not support clearing the DFA.");
}
public PredictionContextCache getSharedContextCache() {
return sharedContextCache;
}
public PredictionContext getCachedContext(PredictionContext context) {
if ( sharedContextCache==null ) return context;
synchronized (sharedContextCache) {
IdentityHashMap<PredictionContext, PredictionContext> visited =
new IdentityHashMap<PredictionContext, PredictionContext>();
return PredictionContext.getCachedContext(context,
sharedContextCache,
visited);
}
}
/**
* @deprecated Use {@link ATNDeserializer#deserialize} instead.
*/
@Deprecated
public static ATN deserialize(char[] data) {
return new ATNDeserializer().deserialize(data);
}
/**
* @deprecated Use {@link ATNDeserializer#checkCondition(boolean)} instead.
*/
@Deprecated
public static void checkCondition(boolean condition) {
new ATNDeserializer().checkCondition(condition);
}
/**
* @deprecated Use {@link ATNDeserializer#checkCondition(boolean, String)} instead.
*/
@Deprecated
public static void checkCondition(boolean condition, String message) {
new ATNDeserializer().checkCondition(condition, message);
}
/**
* @deprecated Use {@link ATNDeserializer#toInt} instead.
*/
@Deprecated
public static int toInt(char c) {
return ATNDeserializer.toInt(c);
}
/**
* @deprecated Use {@link ATNDeserializer#toInt32} instead.
*/
@Deprecated
public static int toInt32(char[] data, int offset) {
return ATNDeserializer.toInt32(data, offset);
}
/**
* @deprecated Use {@link ATNDeserializer#toLong} instead.
*/
@Deprecated
public static long toLong(char[] data, int offset) {
return ATNDeserializer.toLong(data, offset);
}
/**
* @deprecated Use {@link ATNDeserializer#toUUID} instead.
*/
@Deprecated
public static UUID toUUID(char[] data, int offset) {
return ATNDeserializer.toUUID(data, offset);
}
/**
* @deprecated Use {@link ATNDeserializer#edgeFactory} instead.
*/
@Deprecated
public static Transition edgeFactory(ATN atn,
int type, int src, int trg,
int arg1, int arg2, int arg3,
List<IntervalSet> sets)
{
return new ATNDeserializer().edgeFactory(atn, type, src, trg, arg1, arg2, arg3, sets);
}
/**
* @deprecated Use {@link ATNDeserializer#stateFactory} instead.
*/
@Deprecated
public static ATNState stateFactory(int type, int ruleIndex) {
return new ATNDeserializer().stateFactory(type, ruleIndex);
}
}
| |
package antlr;
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/RIGHTS.html
*
* $Id: HTMLCodeGenerator.java,v 1.1 2003/06/04 20:54:24 greg Exp $
*/
import java.util.Enumeration;
import antlr.collections.impl.BitSet;
import antlr.collections.impl.Vector;
import java.io.PrintWriter; //SAS: changed for proper text file io
import java.io.IOException;
import java.io.FileWriter;
/**Generate P.html, a cross-linked representation of P with or without actions */
public class HTMLCodeGenerator extends CodeGenerator {
/** non-zero if inside syntactic predicate generation */
protected int syntacticPredLevel = 0;
/** true during lexer generation, false during parser generation */
protected boolean doingLexRules = false;
protected boolean firstElementInAlt;
protected AlternativeElement prevAltElem = null; // what was generated last?
/** Create a Diagnostic code-generator using the given Grammar
* The caller must still call setTool, setBehavior, and setAnalyzer
* before generating code.
*/
public HTMLCodeGenerator() {
super();
charFormatter = new JavaCharFormatter();
}
/** Encode a string for printing in a HTML document..
* e.g. encode '<' '>' and similar stuff
* @param s the string to encode
*/
static String HTMLEncode(String s) {
StringBuffer buf = new StringBuffer();
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
if (c == '&')
buf.append("&");
else if (c == '\"')
buf.append(""");
else if (c == '\'')
buf.append("'");
else if (c == '<')
buf.append("<");
else if (c == '>')
buf.append(">");
else
buf.append(c);
}
return buf.toString();
}
public void gen() {
// Do the code generation
try {
// Loop over all grammars
Enumeration grammarIter = behavior.grammars.elements();
while (grammarIter.hasMoreElements()) {
Grammar g = (Grammar)grammarIter.nextElement();
// Connect all the components to each other
/*
g.setGrammarAnalyzer(analyzer);
analyzer.setGrammar(g);
*/
g.setCodeGenerator(this);
// To get right overloading behavior across hetrogeneous grammars
g.generate();
if (antlrTool.hasError()) {
antlrTool.fatalError("Exiting due to errors.");
}
}
}
catch (IOException e) {
antlrTool.reportException(e, null);
}
}
/** Generate code for the given grammar element.
* @param blk The {...} action to generate
*/
public void gen(ActionElement action) {
// no-op
}
/** Generate code for the given grammar element.
* @param blk The "x|y|z|..." block to generate
*/
public void gen(AlternativeBlock blk) {
genGenericBlock(blk, "");
}
/** Generate code for the given grammar element.
* @param blk The block-end element to generate. Block-end
* elements are synthesized by the grammar parser to represent
* the end of a block.
*/
public void gen(BlockEndElement end) {
// no-op
}
/** Generate code for the given grammar element.
* @param blk The character literal reference to generate
*/
public void gen(CharLiteralElement atom) {
if (atom.not) {
_print("~");
}
_print(HTMLEncode(atom.atomText) + " ");
}
/** Generate code for the given grammar element.
* @param blk The character-range reference to generate
*/
public void gen(CharRangeElement r) {
print(r.beginText + ".." + r.endText + " ");
}
/** Generate the lexer HTML file */
public void gen(LexerGrammar g) throws IOException {
setGrammar(g);
antlrTool.reportProgress("Generating " + grammar.getClassName() + TokenTypesFileExt);
currentOutput = antlrTool.openOutputFile(grammar.getClassName() + TokenTypesFileExt);
//SAS: changed for proper text file io
tabs = 0;
doingLexRules = true;
// Generate header common to all TXT output files
genHeader();
// Output the user-defined lexer premamble
// RK: guess not..
// println(grammar.preambleAction.getText());
// Generate lexer class definition
println("");
// print javadoc comment if any
if (grammar.comment != null) {
_println(HTMLEncode(grammar.comment));
}
println("Definition of lexer " + grammar.getClassName() + ", which is a subclass of " + grammar.getSuperClass() + ".");
// Generate user-defined parser class members
// printAction(grammar.classMemberAction.getText());
/*
// Generate string literals
println("");
println("*** String literals used in the parser");
println("The following string literals were used in the parser.");
println("An actual code generator would arrange to place these literals");
println("into a table in the generated lexer, so that actions in the");
println("generated lexer could match token text against the literals.");
println("String literals used in the lexer are not listed here, as they");
println("are incorporated into the mainstream lexer processing.");
tabs++;
// Enumerate all of the symbols and look for string literal symbols
Enumeration ids = grammar.getSymbols();
while ( ids.hasMoreElements() ) {
GrammarSymbol sym = (GrammarSymbol)ids.nextElement();
// Only processing string literals -- reject other symbol entries
if ( sym instanceof StringLiteralSymbol ) {
StringLiteralSymbol s = (StringLiteralSymbol)sym;
println(s.getId() + " = " + s.getTokenType());
}
}
tabs--;
println("*** End of string literals used by the parser");
*/
// Generate nextToken() rule.
// nextToken() is a synthetic lexer rule that is the implicit OR of all
// user-defined lexer rules.
genNextToken();
// Generate code for each rule in the lexer
Enumeration ids = grammar.rules.elements();
while (ids.hasMoreElements()) {
RuleSymbol rs = (RuleSymbol)ids.nextElement();
if (!rs.id.equals("mnextToken")) {
genRule(rs);
}
}
// Close the lexer output file
currentOutput.close();
currentOutput = null;
doingLexRules = false;
}
/** Generate code for the given grammar element.
* @param blk The (...)+ block to generate
*/
public void gen(OneOrMoreBlock blk) {
genGenericBlock(blk, "+");
}
/** Generate the parser HTML file */
public void gen(ParserGrammar g) throws IOException {
setGrammar(g);
// Open the output stream for the parser and set the currentOutput
antlrTool.reportProgress("Generating " + grammar.getClassName() + ".html");
currentOutput = antlrTool.openOutputFile(grammar.getClassName() + ".html");
tabs = 0;
// Generate the header common to all output files.
genHeader();
// Generate parser class definition
println("");
// print javadoc comment if any
if (grammar.comment != null) {
_println(HTMLEncode(grammar.comment));
}
println("Definition of parser " + grammar.getClassName() + ", which is a subclass of " + grammar.getSuperClass() + ".");
// Enumerate the parser rules
Enumeration rules = grammar.rules.elements();
while (rules.hasMoreElements()) {
println("");
// Get the rules from the list and downcast it to proper type
GrammarSymbol sym = (GrammarSymbol)rules.nextElement();
// Only process parser rules
if (sym instanceof RuleSymbol) {
genRule((RuleSymbol)sym);
}
}
tabs--;
println("");
genTail();
// Close the parser output stream
currentOutput.close();
currentOutput = null;
}
/** Generate code for the given grammar element.
* @param blk The rule-reference to generate
*/
public void gen(RuleRefElement rr) {
RuleSymbol rs = (RuleSymbol)grammar.getSymbol(rr.targetRule);
// Generate the actual rule description
_print("<a href=\"" + grammar.getClassName() + ".html#" + rr.targetRule + "\">");
_print(rr.targetRule);
_print("</a>");
// RK: Leave out args..
// if (rr.args != null) {
// _print("["+rr.args+"]");
// }
_print(" ");
}
/** Generate code for the given grammar element.
* @param blk The string-literal reference to generate
*/
public void gen(StringLiteralElement atom) {
if (atom.not) {
_print("~");
}
_print(HTMLEncode(atom.atomText));
_print(" ");
}
/** Generate code for the given grammar element.
* @param blk The token-range reference to generate
*/
public void gen(TokenRangeElement r) {
print(r.beginText + ".." + r.endText + " ");
}
/** Generate code for the given grammar element.
* @param blk The token-reference to generate
*/
public void gen(TokenRefElement atom) {
if (atom.not) {
_print("~");
}
_print(atom.atomText);
_print(" ");
}
public void gen(TreeElement t) {
print(t + " ");
}
/** Generate the tree-walker TXT file */
public void gen(TreeWalkerGrammar g) throws IOException {
setGrammar(g);
// Open the output stream for the parser and set the currentOutput
antlrTool.reportProgress("Generating " + grammar.getClassName() + ".html");
currentOutput = antlrTool.openOutputFile(grammar.getClassName() + ".html");
//SAS: changed for proper text file io
tabs = 0;
// Generate the header common to all output files.
genHeader();
// Output the user-defined parser premamble
println("");
// println("*** Tree-walker Preamble Action.");
// println("This action will appear before the declaration of your tree-walker class:");
// tabs++;
// println(grammar.preambleAction.getText());
// tabs--;
// println("*** End of tree-walker Preamble Action");
// Generate tree-walker class definition
println("");
// print javadoc comment if any
if (grammar.comment != null) {
_println(HTMLEncode(grammar.comment));
}
println("Definition of tree parser " + grammar.getClassName() + ", which is a subclass of " + grammar.getSuperClass() + ".");
// Generate user-defined tree-walker class members
// println("");
// println("*** User-defined tree-walker class members:");
// println("These are the member declarations that you defined for your class:");
// tabs++;
// printAction(grammar.classMemberAction.getText());
// tabs--;
// println("*** End of user-defined tree-walker class members");
// Generate code for each rule in the grammar
println("");
// println("*** tree-walker rules:");
tabs++;
// Enumerate the tree-walker rules
Enumeration rules = grammar.rules.elements();
while (rules.hasMoreElements()) {
println("");
// Get the rules from the list and downcast it to proper type
GrammarSymbol sym = (GrammarSymbol)rules.nextElement();
// Only process tree-walker rules
if (sym instanceof RuleSymbol) {
genRule((RuleSymbol)sym);
}
}
tabs--;
println("");
// println("*** End of tree-walker rules");
// println("");
// println("*** End of tree-walker");
// Close the tree-walker output stream
currentOutput.close();
currentOutput = null;
}
/** Generate a wildcard element */
public void gen(WildcardElement wc) {
/*
if ( wc.getLabel()!=null ) {
_print(wc.getLabel()+"=");
}
*/
_print(". ");
}
/** Generate code for the given grammar element.
* @param blk The (...)* block to generate
*/
public void gen(ZeroOrMoreBlock blk) {
genGenericBlock(blk, "*");
}
protected void genAlt(Alternative alt) {
if (alt.getTreeSpecifier() != null) {
_print(alt.getTreeSpecifier().getText());
}
prevAltElem = null;
for (AlternativeElement elem = alt.head;
!(elem instanceof BlockEndElement);
elem = elem.next) {
elem.generate();
firstElementInAlt = false;
prevAltElem = elem;
}
}
/** Generate the header for a block, which may be a RuleBlock or a
* plain AlternativeBLock. This generates any variable declarations,
* init-actions, and syntactic-predicate-testing variables.
* @blk The block for which the preamble is to be generated.
*/
// protected void genBlockPreamble(AlternativeBlock blk) {
// RK: don't dump out init actions
// dump out init action
// if ( blk.initAction!=null ) {
// printAction("{" + blk.initAction + "}");
// }
// }
/**Generate common code for a block of alternatives; return a postscript
* that needs to be generated at the end of the block. Other routines
* may append else-clauses and such for error checking before the postfix
* is generated.
*/
public void genCommonBlock(AlternativeBlock blk) {
for (int i = 0; i < blk.alternatives.size(); i++) {
Alternative alt = blk.getAlternativeAt(i);
AlternativeElement elem = alt.head;
// dump alt operator |
if (i > 0 && blk.alternatives.size() > 1) {
_println("");
print("|\t");
}
// Dump the alternative, starting with predicates
//
boolean save = firstElementInAlt;
firstElementInAlt = true;
tabs++; // in case we do a newline in alt, increase the tab indent
// RK: don't dump semantic/syntactic predicates
// only obscures grammar.
//
// Dump semantic predicates
//
// if (alt.semPred != null) {
// println("{" + alt.semPred + "}?");
// }
// Dump syntactic predicate
// if (alt.synPred != null) {
// genSynPred(alt.synPred);
// }
genAlt(alt);
tabs--;
firstElementInAlt = save;
}
}
/** Generate a textual representation of the follow set
* for a block.
* @param blk The rule block of interest
*/
public void genFollowSetForRuleBlock(RuleBlock blk) {
Lookahead follow = grammar.theLLkAnalyzer.FOLLOW(1, blk.endNode);
printSet(grammar.maxk, 1, follow);
}
protected void genGenericBlock(AlternativeBlock blk, String blkOp) {
if (blk.alternatives.size() > 1) {
// make sure we start on a new line
if (!firstElementInAlt) {
// only do newline if the last element wasn't a multi-line block
if (prevAltElem == null ||
!(prevAltElem instanceof AlternativeBlock) ||
((AlternativeBlock)prevAltElem).alternatives.size() == 1) {
_println("");
print("(\t");
}
else {
_print("(\t");
}
// _println("");
// print("(\t");
}
else {
_print("(\t");
}
}
else {
_print("( ");
}
// RK: don't dump init actions
// genBlockPreamble(blk);
genCommonBlock(blk);
if (blk.alternatives.size() > 1) {
_println("");
print(")" + blkOp + " ");
// if not last element of alt, need newline & to indent
if (!(blk.next instanceof BlockEndElement)) {
_println("");
print("");
}
}
else {
_print(")" + blkOp + " ");
}
}
/** Generate a header that is common to all TXT files */
protected void genHeader() {
println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
println("<HTML>");
println("<HEAD>");
println("<TITLE>Grammar " + antlrTool.grammarFile + "</TITLE>");
println("</HEAD>");
println("<BODY>");
println("<table summary=\"\" border=\"1\" cellpadding=\"5\">");
println("<tr>");
println("<td>");
println("<font size=\"+2\">Grammar " + grammar.getClassName() + "</font><br>");
println("<a href=\"http://www.ANTLR.org\">ANTLR</a>-generated HTML file from " + antlrTool.grammarFile);
println("<p>");
println("Terence Parr, <a href=\"http://www.magelang.com\">MageLang Institute</a>");
println("<br>ANTLR Version " + antlrTool.version + "; 1989-1999");
println("</td>");
println("</tr>");
println("</table>");
println("<PRE>");
// RK: see no reason for printing include files and stuff...
// tabs++;
// printAction(behavior.getHeaderAction(""));
// tabs--;
}
/**Generate the lookahead set for an alternate. */
protected void genLookaheadSetForAlt(Alternative alt) {
if (doingLexRules && alt.cache[1].containsEpsilon()) {
println("MATCHES ALL");
return;
}
int depth = alt.lookaheadDepth;
if (depth == GrammarAnalyzer.NONDETERMINISTIC) {
// if the decision is nondeterministic, do the best we can: LL(k)
// any predicates that are around will be generated later.
depth = grammar.maxk;
}
for (int i = 1; i <= depth; i++) {
Lookahead lookahead = alt.cache[i];
printSet(depth, i, lookahead);
}
}
/** Generate a textual representation of the lookahead set
* for a block.
* @param blk The block of interest
*/
public void genLookaheadSetForBlock(AlternativeBlock blk) {
// Find the maximal lookahead depth over all alternatives
int depth = 0;
for (int i = 0; i < blk.alternatives.size(); i++) {
Alternative alt = blk.getAlternativeAt(i);
if (alt.lookaheadDepth == GrammarAnalyzer.NONDETERMINISTIC) {
depth = grammar.maxk;
break;
}
else if (depth < alt.lookaheadDepth) {
depth = alt.lookaheadDepth;
}
}
for (int i = 1; i <= depth; i++) {
Lookahead lookahead = grammar.theLLkAnalyzer.look(i, blk);
printSet(depth, i, lookahead);
}
}
/** Generate the nextToken rule.
* nextToken is a synthetic lexer rule that is the implicit OR of all
* user-defined lexer rules.
*/
public void genNextToken() {
println("");
println("/** Lexer nextToken rule:");
println(" * The lexer nextToken rule is synthesized from all of the user-defined");
println(" * lexer rules. It logically consists of one big alternative block with");
println(" * each user-defined rule being an alternative.");
println(" */");
// Create the synthesized rule block for nextToken consisting
// of an alternate block containing all the user-defined lexer rules.
RuleBlock blk = MakeGrammar.createNextTokenRule(grammar, grammar.rules, "nextToken");
// Define the nextToken rule symbol
RuleSymbol nextTokenRs = new RuleSymbol("mnextToken");
nextTokenRs.setDefined();
nextTokenRs.setBlock(blk);
nextTokenRs.access = "private";
grammar.define(nextTokenRs);
/*
// Analyze the synthesized block
if (!grammar.theLLkAnalyzer.deterministic(blk))
{
println("The grammar analyzer has determined that the synthesized");
println("nextToken rule is non-deterministic (i.e., it has ambiguities)");
println("This means that there is some overlap of the character");
println("lookahead for two or more of your lexer rules.");
}
*/
genCommonBlock(blk);
}
/** Generate code for a named rule block
* @param s The RuleSymbol describing the rule to generate
*/
public void genRule(RuleSymbol s) {
if (s == null || !s.isDefined()) return; // undefined rule
println("");
if (s.comment != null) {
_println(HTMLEncode(s.comment));
}
if (s.access.length() != 0) {
if (!s.access.equals("public")) {
_print(s.access + " ");
}
}
_print("<a name=\"" + s.getId() + "\">");
_print(s.getId());
_print("</a>");
// Get rule return type and arguments
RuleBlock rblk = s.getBlock();
// RK: for HTML output not of much value...
// Gen method return value(s)
// if (rblk.returnAction != null) {
// _print("["+rblk.returnAction+"]");
// }
// Gen arguments
// if (rblk.argAction != null)
// {
// _print(" returns [" + rblk.argAction+"]");
// }
_println("");
tabs++;
print(":\t");
// Dump any init-action
// genBlockPreamble(rblk);
// Dump the alternates of the rule
genCommonBlock(rblk);
_println("");
println(";");
tabs--;
}
/** Generate the syntactic predicate. This basically generates
* the alternative block, buts tracks if we are inside a synPred
* @param blk The syntactic predicate block
*/
protected void genSynPred(SynPredBlock blk) {
syntacticPredLevel++;
genGenericBlock(blk, " =>");
syntacticPredLevel--;
}
public void genTail() {
println("</PRE>");
println("</BODY>");
println("</HTML>");
}
/** Generate the token types TXT file */
protected void genTokenTypes(TokenManager tm) throws IOException {
// Open the token output TXT file and set the currentOutput stream
antlrTool.reportProgress("Generating " + tm.getName() + TokenTypesFileSuffix + TokenTypesFileExt);
currentOutput = antlrTool.openOutputFile(tm.getName() + TokenTypesFileSuffix + TokenTypesFileExt);
//SAS: changed for proper text file io
tabs = 0;
// Generate the header common to all diagnostic files
genHeader();
// Generate a string for each token. This creates a static
// array of Strings indexed by token type.
println("");
println("*** Tokens used by the parser");
println("This is a list of the token numeric values and the corresponding");
println("token identifiers. Some tokens are literals, and because of that");
println("they have no identifiers. Literals are double-quoted.");
tabs++;
// Enumerate all the valid token types
Vector v = tm.getVocabulary();
for (int i = Token.MIN_USER_TYPE; i < v.size(); i++) {
String s = (String)v.elementAt(i);
if (s != null) {
println(s + " = " + i);
}
}
// Close the interface
tabs--;
println("*** End of tokens used by the parser");
// Close the tokens output file
currentOutput.close();
currentOutput = null;
}
/** Get a string for an expression to generate creation of an AST subtree.
* @param v A Vector of String, where each element is an expression in the target language yielding an AST node.
*/
public String getASTCreateString(Vector v) {
return null;
}
/** Get a string for an expression to generate creating of an AST node
* @param str The arguments to the AST constructor
*/
public String getASTCreateString(GrammarAtom atom, String str) {
return null;
}
/** Map an identifier to it's corresponding tree-node variable.
* This is context-sensitive, depending on the rule and alternative
* being generated
* @param id The identifier name to map
* @param forInput true if the input tree node variable is to be returned, otherwise the output variable is returned.
*/
public String mapTreeId(String id, ActionTransInfo tInfo) {
return id;
}
/// unused.
protected String processActionForSpecialSymbols(String actionStr,
int line,
RuleBlock currentRule,
ActionTransInfo tInfo) {
return actionStr;
}
/** Format a lookahead or follow set.
* @param depth The depth of the entire lookahead/follow
* @param k The lookahead level to print
* @param lookahead The lookahead/follow set to print
*/
public void printSet(int depth, int k, Lookahead lookahead) {
int numCols = 5;
int[] elems = lookahead.fset.toArray();
if (depth != 1) {
print("k==" + k + ": {");
}
else {
print("{ ");
}
if (elems.length > numCols) {
_println("");
tabs++;
print("");
}
int column = 0;
for (int i = 0; i < elems.length; i++) {
column++;
if (column > numCols) {
_println("");
print("");
column = 0;
}
if (doingLexRules) {
_print(charFormatter.literalChar(elems[i]));
}
else {
_print((String)grammar.tokenManager.getVocabulary().elementAt(elems[i]));
}
if (i != elems.length - 1) {
_print(", ");
}
}
if (elems.length > numCols) {
_println("");
tabs--;
print("");
}
_println(" }");
}
}
| |
package model.resources;
import model.ability_management.ability_set.AbilitySet;
import model.resources.resourceVisitor.InnerResourceVisitor;
import model.resources.resourceVisitor.ResourceVisitor;
import java.util.ArrayList;
import java.util.List;
/**
* Created by TheNotoriousOOP on 4/12/2017.
* Class Description:
* Responsibilities:
*/
public abstract class ResourceStorage {
//keeps track of abilities of that set
private AbilitySet abilitySet = new AbilitySet();
// Size
private int size = 0;
//Resource ArrayLists
private ArrayList<Gold> goldArrayList = new ArrayList<>();
private ArrayList<Coins> coinsArrayList = new ArrayList<>();
private ArrayList<Stock> stockArrayList = new ArrayList<>();
private ArrayList<Trunks> trunksArrayList = new ArrayList<>();
private ArrayList<Iron> ironArrayList = new ArrayList<>();
private ArrayList<Fuel> fuelArrayList = new ArrayList<>();
private ArrayList<Clay> clayArrayList = new ArrayList<>();
private ArrayList<Stone> stoneArrayList = new ArrayList<>();
private ArrayList<Boards> boardsArrayList = new ArrayList<>();
private ArrayList<Goose> gooseArrayList = new ArrayList<>();
private ArrayList<Paper> paperArrayList = new ArrayList<>();
// Constructor
public ResourceStorage(){
}
// Get count of resources in storage
public int getSize() {
int size = 0;
size += goldArrayList.size();
size += coinsArrayList.size();
size += stockArrayList.size();
size += trunksArrayList.size();
size += ironArrayList.size();
size += fuelArrayList.size();
size += clayArrayList.size();
size += stoneArrayList.size();
size += boardsArrayList.size();
size += gooseArrayList.size();
size += paperArrayList.size();
return size;
}
// Check if the resource storage object is empty
public boolean isEmpty() {
return (getSize() == 0) ? true : false;
}
public abstract void addResource(Resource resource);
public abstract void addGold(Gold gold);
public abstract void addCoins(Coins coins);
public abstract void addStock(Stock stock);
public abstract void addTrunks(Trunks trunks);
public abstract void addFuel(Fuel fuel);
public abstract void addIron(Iron iron);
public abstract void addClay(Clay clay);
public abstract void addStone(Stone stone);
public abstract void addBoards(Boards boards);
public abstract void addGoose(Goose goose);
public abstract void addPaper(Paper paper);
public abstract Gold removeGold();
public abstract Coins removeCoins();
public abstract Stock removeStock();
public abstract Trunks removeTrunks();
public abstract Fuel removeFuel();
public abstract Iron removeIron();
public abstract Clay removeClay();
public abstract Stone removeStone();
public abstract Boards removeBoards();
public abstract Goose removeGoose();
public abstract Paper removePaper();
public ArrayList<Gold> getGoldArrayList() {
return goldArrayList;
}
public ArrayList<Coins> getCoinsArrayList() {
return coinsArrayList;
}
public ArrayList<Stock> getStockArrayList() {
return stockArrayList;
}
public ArrayList<Trunks> getTrunksArrayList() {
return trunksArrayList;
}
public ArrayList<Iron> getIronArrayList() {
return ironArrayList;
}
public ArrayList<Fuel> getFuelArrayList() {
return fuelArrayList;
}
public ArrayList<Clay> getClayArrayList() {
return clayArrayList;
}
public ArrayList<Stone> getStoneArrayList() {
return stoneArrayList;
}
public ArrayList<Boards> getBoardsArrayList() {
return boardsArrayList;
}
public ArrayList<Goose> getGooseArrayList() {
return gooseArrayList;
}
public ArrayList<Paper> getPaperArrayList() { return paperArrayList; }
public abstract boolean exchangeFuel(Fuel fuel);
public abstract boolean exchangeCoin(Coins coin);
public abstract boolean exchangePaper(Paper paper);
public abstract boolean exchangeBoards(Boards firstBoard, Boards secondBoard);
public abstract boolean exchangeStock(Stock stockBond);
public abstract boolean exchangeStone(Stone firstStone, Stone secondStone);
protected boolean canMakeFuel(){
if((boardsArrayList.size() + trunksArrayList.size()) >= 2)
return true;
return false;
}
protected void removeFuelCost(){
int counter = 0;
while(boardsArrayList.size() > 0){
boardsArrayList.remove(trunksArrayList.size()-1);
counter++;
if(counter == 2)
return;
}
while(trunksArrayList.size() > 0){
trunksArrayList.remove(trunksArrayList.size()-1);
counter++;
if(counter == 2)
return;
}
}
protected boolean canMakeCoin() {
if(goldArrayList.size() >= 2 && fuelArrayList.size() >= 1)
return true;
return false;
}
protected void removeCoinCost(){
goldArrayList.remove(1);
goldArrayList.remove(0);
fuelArrayList.remove(0);
}
protected boolean canMakePaper(){
if((boardsArrayList.size() + trunksArrayList.size()) >= 2){
return true;
}
return false;
}
protected void removePaperCost(){
int counter = 0;
while(boardsArrayList.size() > 0){
boardsArrayList.remove(trunksArrayList.size()-1);
counter++;
if(counter == 2)
return;
}
while(trunksArrayList.size() > 0){
trunksArrayList.remove(trunksArrayList.size()-1);
counter++;
if(counter == 2)
return;
}
}
protected boolean canMakeBoard(){
if(trunksArrayList.size() >= 1)
return true;
return false;
}
protected void removeBoardCost(){
trunksArrayList.remove(0);
}
public AbilitySet getAbilitySet() {
return abilitySet;
}
protected boolean canMakeStock(){
if(paperArrayList.size() >= 1 && coinsArrayList.size() >= 2)
return true;
return false;
}
protected void removeStockCost(){
paperArrayList.remove(0);
coinsArrayList.remove(1);
coinsArrayList.remove(0);
}
protected boolean canMakeStone(){
if(clayArrayList.size() >= 1)
return true;
return false;
}
protected void removeStoneCost(){
clayArrayList.remove(0);
}
public List<String> getResourceStrings() {
List<String> resourceStrings = new ArrayList<>();
resourceStrings.add("Gold: " + goldArrayList.size());
resourceStrings.add("Coins: " + coinsArrayList.size());
resourceStrings.add("Stock: " + stockArrayList.size());
resourceStrings.add("Trunks: " + trunksArrayList.size());
resourceStrings.add("Iron: " + ironArrayList.size());
resourceStrings.add("Fuel: " + fuelArrayList.size());
resourceStrings.add("Clay: " + clayArrayList.size());
resourceStrings.add("Stone: " + stoneArrayList.size());
resourceStrings.add("Boards: " + boardsArrayList.size());
resourceStrings.add("Goose: " + gooseArrayList.size());
resourceStrings.add("Paper: " + paperArrayList.size());
return resourceStrings;
}
//top-tier code
public void accept(ResourceVisitor visitor) { visitor.visitResourceStorage(this);}
public void acceptToAdd(InnerResourceVisitor visitor) {
visitor.visitResourceStorageToAdd(this);
}
public void acceptToRemove(InnerResourceVisitor visitor) { visitor.visitResourceStorageToRemove(this);}
public int acceptToCount(InnerResourceVisitor visitor) { return visitor.visitResourceStorageToCount(this);}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 05.12.2006
* Time: 19:39:22
*/
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.FilterComponent;
import com.intellij.ui.LightColors;
import com.intellij.util.AsynchConsumer;
import com.intellij.util.BufferedListConsumer;
import com.intellij.util.Consumer;
import com.intellij.util.WaitForProgressToShow;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvider, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.committed.CommittedChangesPanel");
private final CommittedChangesTreeBrowser myBrowser;
private final Project myProject;
private CommittedChangesProvider myProvider;
private ChangeBrowserSettings mySettings;
private final RepositoryLocation myLocation;
private int myMaxCount = 0;
private final MyFilterComponent myFilterComponent = new MyFilterComponent();
private final JCheckBox myRegexCheckbox;
private final List<Runnable> myShouldBeCalledOnDispose;
private volatile boolean myDisposed;
private volatile boolean myInLoad;
private Consumer<String> myIfNotCachedReloader;
private boolean myChangesLoaded;
public CommittedChangesPanel(Project project, final CommittedChangesProvider provider, final ChangeBrowserSettings settings,
@Nullable final RepositoryLocation location, @Nullable ActionGroup extraActions) {
super(new BorderLayout());
mySettings = settings;
myProject = project;
myProvider = provider;
myLocation = location;
myShouldBeCalledOnDispose = new ArrayList<Runnable>();
myBrowser = new CommittedChangesTreeBrowser(project, new ArrayList<CommittedChangeList>());
Disposer.register(this, myBrowser);
add(myBrowser, BorderLayout.CENTER);
final VcsCommittedViewAuxiliary auxiliary = provider.createActions(myBrowser, location);
JPanel toolbarPanel = new JPanel();
toolbarPanel.setLayout(new BoxLayout(toolbarPanel, BoxLayout.X_AXIS));
ActionGroup group = (ActionGroup) ActionManager.getInstance().getAction("CommittedChangesToolbar");
ActionToolbar toolBar = myBrowser.createGroupFilterToolbar(project, group, extraActions,
auxiliary != null ? auxiliary.getToolbarActions() : Collections.<AnAction>emptyList());
toolbarPanel.add(toolBar.getComponent());
toolbarPanel.add(Box.createHorizontalGlue());
myRegexCheckbox = new JCheckBox(VcsBundle.message("committed.changes.regex.title"));
myRegexCheckbox.setSelected(false);
myRegexCheckbox.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
myFilterComponent.filter();
}
});
toolbarPanel.add(myFilterComponent);
toolbarPanel.add(myRegexCheckbox);
myFilterComponent.setMinimumSize(myFilterComponent.getPreferredSize());
myFilterComponent.setMaximumSize(myFilterComponent.getPreferredSize());
myBrowser.setToolBar(toolbarPanel);
if (auxiliary != null) {
myShouldBeCalledOnDispose.add(auxiliary.getCalledOnViewDispose());
myBrowser.setTableContextMenu(group, auxiliary.getPopupActions());
} else {
myBrowser.setTableContextMenu(group, Collections.<AnAction>emptyList());
}
EmptyAction.registerWithShortcutSet("CommittedChanges.Refresh", CommonShortcuts.getRerun(), this);
myBrowser.addFilter(myFilterComponent);
myIfNotCachedReloader = myLocation == null ? null : new Consumer<String>() {
@Override
public void consume(String s) {
refreshChanges(false);
}
};
}
public RepositoryLocation getRepositoryLocation() {
return myLocation;
}
public void setMaxCount(final int maxCount) {
myMaxCount = maxCount;
}
public void setProvider(final CommittedChangesProvider provider) {
if (myProvider != provider) {
myProvider = provider;
mySettings = provider.createDefaultSettings();
}
}
public void refreshChanges(final boolean cacheOnly) {
if (myLocation != null) {
refreshChangesFromLocation();
}
else {
refreshChangesFromCache(cacheOnly);
}
}
private void refreshChangesFromLocation() {
myBrowser.reset();
myInLoad = true;
myBrowser.setLoading(true);
ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Loading changes", true) {
public void run(@NotNull final ProgressIndicator indicator) {
try {
final AsynchConsumer<List<CommittedChangeList>> appender = new AsynchConsumer<List<CommittedChangeList>>() {
public void finished() {
}
public void consume(final List<CommittedChangeList> list) {
new AbstractCalledLater(myProject, ModalityState.stateForComponent(myBrowser)) {
public void run() {
myBrowser.append(list);
}
}.callMe();
}
};
final BufferedListConsumer<CommittedChangeList> bufferedListConsumer = new BufferedListConsumer<CommittedChangeList>(30, appender,-1);
myProvider.loadCommittedChanges(mySettings, myLocation, myMaxCount, new AsynchConsumer<CommittedChangeList>() {
public void finished() {
bufferedListConsumer.flush();
}
public void consume(CommittedChangeList committedChangeList) {
if (myDisposed) {
indicator.cancel();
}
ProgressManager.checkCanceled();
bufferedListConsumer.consumeOne(committedChangeList);
}
});
}
catch (final VcsException e) {
LOG.info(e);
WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() {
public void run() {
Messages.showErrorDialog(myProject, "Error refreshing view: " + StringUtil.join(e.getMessages(), "\n"), "Committed Changes");
}
}, null, myProject);
} finally {
myInLoad = false;
myBrowser.setLoading(false);
}
}
});
}
public void clearCaches() {
final CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
cache.clearCaches(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
updateFilteredModel(Collections.<CommittedChangeList>emptyList(), true);
}
}, ModalityState.NON_MODAL, myProject.getDisposed());
}
});
}
private void refreshChangesFromCache(final boolean cacheOnly) {
final CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
cache.hasCachesForAnyRoot(new Consumer<Boolean>() {
public void consume(final Boolean notEmpty) {
if (! notEmpty) {
if (cacheOnly) {
myBrowser.getEmptyText().setText(VcsBundle.message("committed.changes.not.loaded.message"));
return;
}
if (!CacheSettingsDialog.showSettingsDialog(myProject)) return;
}
cache.getProjectChangesAsync(mySettings, myMaxCount, cacheOnly,
new Consumer<List<CommittedChangeList>>() {
public void consume(final List<CommittedChangeList> committedChangeLists) {
updateFilteredModel(committedChangeLists, false);
}
},
new Consumer<List<VcsException>>() {
public void consume(final List<VcsException> vcsExceptions) {
AbstractVcsHelper.getInstance(myProject).showErrors(vcsExceptions, "Error refreshing VCS history");
}
});
}
});
}
private interface FilterHelper {
boolean filter(@NotNull final CommittedChangeList cl);
}
private class RegexFilterHelper implements FilterHelper {
private final Pattern myPattern;
RegexFilterHelper(@NotNull final String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
pattern = null;
myBrowser.getEmptyText().setText(VcsBundle.message("committed.changes.incorrect.regex.message"));
}
this.myPattern = pattern;
}
@Override
public boolean filter(@NotNull CommittedChangeList cl) {
return changeListMatches(cl);
}
private boolean changeListMatches(@NotNull CommittedChangeList cl) {
if (myPattern == null) {
return false;
}
boolean commentMatches = myPattern.matcher(cl.getComment()).find();
boolean committerMatches = myPattern.matcher(cl.getCommitterName()).find();
boolean revisionMatches = myPattern.matcher(Long.toString(cl.getNumber())).find();
return commentMatches || committerMatches || revisionMatches;
}
}
private static class WordMatchFilterHelper implements FilterHelper {
private final String[] myParts;
WordMatchFilterHelper(final String filterString) {
myParts = filterString.split(" ");
for(int i = 0; i < myParts.length; ++ i) {
myParts [i] = myParts [i].toLowerCase();
}
}
public boolean filter(@NotNull final CommittedChangeList cl) {
return changeListMatches(cl, myParts);
}
private static boolean changeListMatches(@NotNull final CommittedChangeList changeList, final String[] filterWords) {
for(String word: filterWords) {
final String comment = changeList.getComment();
final String committer = changeList.getCommitterName();
if ((comment != null && comment.toLowerCase().contains(word)) ||
(committer != null && committer.toLowerCase().contains(word)) ||
Long.toString(changeList.getNumber()).contains(word)) {
return true;
}
}
return false;
}
}
private void updateFilteredModel(List<CommittedChangeList> committedChangeLists, final boolean reset) {
if (committedChangeLists == null) {
return;
}
myChangesLoaded = !reset;
setEmptyMessage(myChangesLoaded);
myBrowser.setItems(committedChangeLists, CommittedChangesBrowserUseCase.COMMITTED);
}
private void setEmptyMessage(boolean changesLoaded) {
String emptyText;
if (!changesLoaded) {
emptyText = VcsBundle.message("committed.changes.not.loaded.message");
} else {
emptyText = VcsBundle.message("committed.changes.empty.message");
}
myBrowser.getEmptyText().setText(emptyText);
}
public void setChangesFilter() {
CommittedChangesFilterDialog filterDialog = new CommittedChangesFilterDialog(myProject, myProvider.createFilterUI(true), mySettings);
if (filterDialog.showAndGet()) {
mySettings = filterDialog.getSettings();
refreshChanges(false);
}
}
public void calcData(DataKey key, DataSink sink) {
if (key.equals(VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER)) {
sink.put(VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER, myIfNotCachedReloader);
} else if (VcsDataKeys.REMOTE_HISTORY_LOCATION.equals(key)) {
sink.put(VcsDataKeys.REMOTE_HISTORY_LOCATION, myLocation);
}
//if (key.equals(VcsDataKeys.CHANGES) || key.equals(VcsDataKeys.CHANGE_LISTS)) {
myBrowser.calcData(key, sink);
//}
}
public void dispose() {
for (Runnable runnable : myShouldBeCalledOnDispose) {
runnable.run();
}
myDisposed = true;
}
private void setRegularFilterBackground() {
myFilterComponent.getTextEditor().setBackground(UIUtil.getTextFieldBackground());
}
private void setNotFoundFilterBackground() {
myFilterComponent.getTextEditor().setBackground(LightColors.RED);
}
private class MyFilterComponent extends FilterComponent implements ChangeListFilteringStrategy {
private final List<ChangeListener> myList = ContainerUtil.createLockFreeCopyOnWriteList();
public MyFilterComponent() {
super("COMMITTED_CHANGES_FILTER_HISTORY", 20);
}
@Override
public CommittedChangesFilterKey getKey() {
return new CommittedChangesFilterKey("text", CommittedChangesFilterPriority.TEXT);
}
public void filter() {
for (ChangeListener changeListener : myList) {
changeListener.stateChanged(new ChangeEvent(this));
}
}
public JComponent getFilterUI() {
return null;
}
public void setFilterBase(List<CommittedChangeList> changeLists) {
}
public void addChangeListener(ChangeListener listener) {
myList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
myList.remove(listener);
}
public void resetFilterBase() {
}
public void appendFilterBase(List<CommittedChangeList> changeLists) {
}
@NotNull
public List<CommittedChangeList> filterChangeLists(List<CommittedChangeList> changeLists) {
final FilterHelper filterHelper;
setEmptyMessage(myChangesLoaded);
if (myRegexCheckbox.isSelected()) {
filterHelper = new RegexFilterHelper(myFilterComponent.getFilter());
} else {
filterHelper = new WordMatchFilterHelper(myFilterComponent.getFilter());
}
final List<CommittedChangeList> result = new ArrayList<CommittedChangeList>();
for (CommittedChangeList list : changeLists) {
if (filterHelper.filter(list)) {
result.add(list);
}
}
if (result.size() == 0 && !myFilterComponent.getFilter().isEmpty()) {
setNotFoundFilterBackground();
} else {
setRegularFilterBackground();
}
return result;
}
}
public void passCachedListsToListener(final VcsConfigurationChangeListener.DetailedNotification notification,
final Project project, final VirtualFile root) {
final LinkedList<CommittedChangeList> resultList = new LinkedList<CommittedChangeList>();
myBrowser.reportLoadedLists(new CommittedChangeListsListener() {
public void onBeforeStartReport() {
}
public boolean report(CommittedChangeList list) {
resultList.add(list);
return false;
}
public void onAfterEndReport() {
if (! resultList.isEmpty()) {
notification.execute(project, root, resultList);
}
}
});
}
public boolean isInLoad() {
return myInLoad;
}
}
| |
/*
* Copyright 2006 IONA Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.codehaus.xharness.tasks;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectComponent;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;
import org.apache.tools.ant.UnknownElement;
import org.apache.tools.ant.UnsupportedAttributeException;
import org.apache.tools.ant.UnsupportedElementException;
import org.codehaus.xharness.exceptions.AssertionWarningException;
import org.codehaus.xharness.exceptions.FatalException;
import org.codehaus.xharness.exceptions.TestSkippedException;
import org.codehaus.xharness.log.TaskRegistry;
/**
* {@link org.apache.tools.ant.TaskContainer} implementation for Tasks within
* the XHarness framework. Implements reference infrastructure for the retrieval
* of (service) task references and initializes child tasks.
*
* @author Gregor Heine
*/
public class TestGroupTask extends Task implements TaskContainer {
private List children = new LinkedList();
private String groupName;
//
// ---- TaskContainer implementation
//
/**
* Add a nested task to this TaskContainer.
*
* @param nestedTask Nested task to execute sequentially
*/
public void addTask(Task nestedTask) {
if (nestedTask != null) {
children.add(nestedTask);
}
}
public List getNestedTasks() {
return children;
}
//
// ---- Resultable implementation
//
/**
* Set the name of this Task, used for Result reporting.
*
* @param name The name this Task
*/
public void setName(String name) {
groupName = name;
}
/**
* Get the name of this Task.
*
* @return This Task's name.
*/
public String getName() {
return groupName;
}
//
// ---- Task overrides
//
/**
* Do the execution of this Task.
*
* @throws BuildException If an exception occurs while executing a child Task.
* throws TestSkippedException If the test doesn't match the test pattern.
*/
public void execute() throws BuildException {
if (!TaskRegistry.matchesPattern(this)) {
String msg = toString() + " doesn't match pattern. Skipped.";
log(msg, Project.MSG_INFO);
throw new TestSkippedException(msg, true);
}
log("Performing " + toString(), Project.MSG_INFO);
BuildException error = null;
AssertionWarningException warning = null;
Iterator iter = children.iterator();
while (iter.hasNext()) {
Task currentTask = (Task)iter.next();
try {
currentTask.perform();
} catch (FatalException ex) {
log("Fatal: " + ex.getMessage(), Project.MSG_ERR);
throw ex;
} catch (UnsupportedElementException ex) {
log("Fatal: " + ex.getMessage(), Project.MSG_ERR);
throw ex;
} catch (UnsupportedAttributeException ex) {
log("Fatal: " + ex.getMessage(), Project.MSG_ERR);
throw ex;
} catch (TestSkippedException ex) {
currentTask = unwrapTask(currentTask);
if (!(currentTask instanceof TestGroupTask)) {
throw ex;
}
} catch (AssertionWarningException ex) {
if (ex.getMessage() != null) {
log(ex.getMessage(), Project.MSG_ERR);
} else {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
log(sw.toString(), Project.MSG_ERR);
}
if (warning == null) {
TaskRegistry.setErrorProperty(ex);
currentTask = unwrapTask(currentTask);
if (currentTask instanceof ServiceDef) {
String name = ((ServiceDef)currentTask).getName();
warning = new AssertionWarningException("Warning in Service " + name, ex);
} else if (currentTask instanceof ServiceInstance) {
String name = currentTask.getTaskName();
warning = new AssertionWarningException("Warning in Service " + name, ex);
} else if (currentTask instanceof TestGroupTask) {
String name = ((TestGroupTask)currentTask).getName();
if (currentTask instanceof TestCaseTask) {
warning = new AssertionWarningException("Warning in Testcase " + name,
ex);
} else if (failOnError()) {
warning = new AssertionWarningException("Warning in Testgroup " + name,
ex);
}
} else {
String name = currentTask.getTaskName();
warning = new AssertionWarningException("Warning in Task " + name, ex);
}
}
} catch (Exception ex) {
if (ex instanceof BuildException && ex.getMessage() != null) {
log(ex.getMessage(), Project.MSG_ERR);
} else {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
log(sw.toString(), Project.MSG_ERR);
}
if (error == null) {
TaskRegistry.setErrorProperty(ex);
currentTask = unwrapTask(currentTask);
if (currentTask instanceof ServiceDef) {
String name = ((ServiceDef)currentTask).getName();
error = new BuildException("Service " + name + " failed", ex);
} else if (currentTask instanceof ServiceInstance) {
String name = currentTask.getTaskName();
error = new BuildException("Service " + name + " failed", ex);
} else if (currentTask instanceof TestGroupTask) {
String name = ((TestGroupTask)currentTask).getName();
if (currentTask instanceof TestCaseTask) {
error = new BuildException("Testcase " + name + " failed", ex);
} else if (failOnError()) {
error = new BuildException("Testgroup " + name + " failed", ex);
}
} else {
String name = "<unknown>";
if (currentTask != null) {
name = currentTask.getTaskName();
}
error = new BuildException("Task " + name + " failed", ex);
}
if (failOnError()) {
throw error;
}
}
}
}
if (error != null) {
throw error;
}
if (warning != null) {
throw warning;
}
}
public String toString() {
return "testgroup " + getName();
}
/**
* Determines if the execution of this Task's children is interrupted, if
* one of the children fails.
*
* @return false. TestGroup's continue to execute children even if they fail.
*/
protected boolean failOnError() {
return false;
}
/**
* A compare function to compare this with another
* NestedSequential.
* It calls similar on the nested unknown elements.
*
* @param other the nested sequential to compare with.
* @return true if they are similar, false otherwise
*/
public boolean similar(TestGroupTask other) {
if (groupName == null && other.getName() != null || !groupName.equals(other.getName())) {
return false;
}
if (children.size() != other.children.size()) {
return false;
}
Iterator iter1 = children.iterator();
Iterator iter2 = other.children.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
Task t1 = (Task)iter1.next();
Task t2 = (Task)iter2.next();
if (t1 instanceof UnknownElement && t2 instanceof UnknownElement) {
if (!((UnknownElement)t1).similar((UnknownElement)t2)) {
return false;
}
} else {
if (t1.getRuntimeConfigurableWrapper() != t2.getRuntimeConfigurableWrapper()) {
return false;
}
}
}
return true;
}
private Task unwrapTask(Task task) {
ProjectComponent comp = TaskRegistry.unwrapComponent(task);
if (comp != task && comp instanceof Task) {
return (Task)comp;
}
return task;
}
}
| |
/*******************************************************************************
* Copyright (c) 2009 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - Initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.parser.tests.ast2;
import java.util.BitSet;
import junit.framework.TestSuite;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarationListOwner;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IField;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.parser.IScanner;
import org.eclipse.cdt.core.parser.ParserLanguage;
/**
* Testcases for inactive code in ast.
*/
public class ASTInactiveCodeTests extends AST2TestBase {
public static TestSuite suite() {
return suite(ASTInactiveCodeTests.class);
}
public ASTInactiveCodeTests() {
super();
}
public ASTInactiveCodeTests(String name) {
super(name);
}
@Override
protected void configureScanner(IScanner scanner) {
super.configureScanner(scanner);
scanner.setProcessInactiveCode(true);
}
// #if %
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
public void testIfBranches() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.C, i);
}
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i);
}
}
private void testBranches(String codeTmpl, ParserLanguage lang, int bits) throws Exception {
testBranches(codeTmpl, lang, bits, 0);
}
private void testBranches(String codeTmpl, ParserLanguage lang, int bits, int level) throws Exception {
BitSet bs= convert(bits);
char[] chars= codeTmpl.toCharArray();
int pos= codeTmpl.indexOf('%', 0);
int i= 0;
while (pos >= 0) {
chars[pos]= bs.get(i++) ? '1' : '0';
pos= codeTmpl.indexOf('%', pos+1);
}
IASTDeclarationListOwner tu= parse(new String(chars), lang);
while (level-- > 0) {
final IASTDeclaration decl = tu.getDeclarations(true)[0];
if (decl instanceof IASTSimpleDeclaration) {
tu= (IASTDeclarationListOwner) ((IASTSimpleDeclaration) decl).getDeclSpecifier();
} else {
tu= (IASTDeclarationListOwner) decl;
}
}
IASTDeclaration[] decl= tu.getDeclarations(true);
assertEquals(8, decl.length);
assertEquals(bs.get(0), decl[0].isActive());
assertEquals(!bs.get(0) && bs.get(1), decl[1].isActive());
assertEquals(!bs.get(0) && bs.get(1) && bs.get(2), decl[2].isActive());
assertEquals(!bs.get(0) && bs.get(1) && !bs.get(2) && bs.get(3), decl[3].isActive());
assertEquals(!bs.get(0) && bs.get(1) && !bs.get(2) && !bs.get(3), decl[4].isActive());
assertEquals(!bs.get(0) && bs.get(1), decl[5].isActive());
assertEquals(!bs.get(0) && !bs.get(1), decl[6].isActive());
assertEquals(true, decl[7].isActive());
}
private BitSet convert(int bits) {
BitSet result= new BitSet(32);
for (int i = 0; i < 32; i++) {
if ((bits & (1 << i)) != 0) {
result.set(i);
}
}
return result;
}
// #define A1
// #ifdef A%
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
public void testIfdefBranches() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.C, i);
}
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i);
}
}
// #define A0
// #ifndef A%
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
public void testIfndefBranches() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.C, i);
}
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i);
}
}
// struct S {
// #if %
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
// };
public void testStructs() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.C, i, 1);
}
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i, 1);
}
}
// extern "C" {
// #if %
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
// };
public void testExternC() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i, 1);
}
}
// namespace ns {
// #if %
// int a0;
// #elif %
// int a1;
// #if %
// int a2;
// #elif %
// int a3;
// #else
// int a4;
// #endif
// int a5;
// #else
// int a6;
// #endif
// int a7;
// }
public void testNamespace() throws Exception {
String codeTmpl= getAboveComment();
for (int i= 0; i < (1<<4); i++) {
testBranches(codeTmpl, ParserLanguage.CPP, i, 1);
}
}
// typedef int TInt;
// const int value= 12;
// #if 0
// int f(TInt);
// int g(value);
// #endif
public void testAmbiguity() throws Exception {
String code= getAboveComment();
IASTTranslationUnit tu= parseAndCheckBindings(code, ParserLanguage.CPP);
IASTDeclaration[] decls = tu.getDeclarations(true);
IASTSimpleDeclaration decl= (IASTSimpleDeclaration) decls[2];
assertTrue(decl.getDeclarators()[0] instanceof IASTFunctionDeclarator);
decl= (IASTSimpleDeclaration) decls[3];
assertFalse(decl.getDeclarators()[0] instanceof IASTFunctionDeclarator);
}
// int a; // 1
// #if 0
// int a; // 2
// #if 0
// int a; // 3
// #endif
// int b; // 1
// #endif
// int b; // 2
public void testDuplicateDefinition() throws Exception {
String code= getAboveComment();
BindingAssertionHelper bh= new BindingAssertionHelper(code, false);
bh.assertNonProblem("a; // 1", 1);
bh.assertNonProblem("a; // 2", 1);
bh.assertNonProblem("a; // 3", 1);
bh.assertNonProblem("b; // 1", 1);
bh.assertNonProblem("b; // 2", 1);
bh= new BindingAssertionHelper(code, true);
bh.assertNonProblem("a; // 1", 1);
bh.assertNonProblem("a; // 2", 1);
bh.assertNonProblem("a; // 3", 1);
bh.assertNonProblem("b; // 1", 1);
bh.assertNonProblem("b; // 2", 1);
parseAndCheckBindings(code, ParserLanguage.C);
parseAndCheckBindings(code, ParserLanguage.CPP);
}
// struct S {
// #if 0
// int a;
// };
// #else
// int b;
// };
// #endif
public void testInactiveClosingBrace() throws Exception {
String code= getAboveComment();
BindingAssertionHelper bh= new BindingAssertionHelper(code, false);
IField a= bh.assertNonProblem("a;", 1);
IField b= bh.assertNonProblem("b;", 1);
assertSame(a.getOwner(), b.getOwner());
bh= new BindingAssertionHelper(code, true);
a= bh.assertNonProblem("a;", 1);
b= bh.assertNonProblem("b;", 1);
assertSame(a.getOwner(), b.getOwner());
}
// struct S
// #if 1
// {
// int a;
// #else
// int b;
// #endif
// int c;
// #if 0
// int d;
// #endif
// };
public void testOpenBraceInActiveBranch() throws Exception {
String code= getAboveComment();
BindingAssertionHelper bh= new BindingAssertionHelper(code, false);
IField a= bh.assertNonProblem("a;", 1);
bh.assertNoName("b;", 1);
IField c= bh.assertNonProblem("c;", 1);
IField d= bh.assertNonProblem("d;", 1);
assertSame(a.getOwner(), c.getOwner());
assertSame(a.getOwner(), d.getOwner());
bh= new BindingAssertionHelper(code, true);
a= bh.assertNonProblem("a;", 1);
bh.assertNoName("b;", 1);
c= bh.assertNonProblem("c;", 1);
d= bh.assertNonProblem("d;", 1);
assertSame(a.getOwner(), c.getOwner());
assertSame(a.getOwner(), d.getOwner());
}
// #if 0
// struct S {
// #if 1
// int a;
// #else
// int b;
// #endif
// #elif 0
// int c;
// #endif
// int d;
public void testOpenBraceInInactiveBranch() throws Exception {
String code= getAboveComment();
BindingAssertionHelper bh= new BindingAssertionHelper(code, false);
IField a= bh.assertNonProblem("a;", 1);
IField b= bh.assertNonProblem("b;", 1);
IVariable c= bh.assertNonProblem("c;", 1); // part of a different non-nested branch
IVariable d= bh.assertNonProblem("d;", 1);
assertSame(a.getOwner(), b.getOwner());
assertNull(c.getOwner());
assertNull(d.getOwner());
bh= new BindingAssertionHelper(code, true);
a= bh.assertNonProblem("a;", 1);
b= bh.assertNonProblem("b;", 1);
c= bh.assertNonProblem("c;", 1); // part of a different non-nested branch
d= bh.assertNonProblem("d;", 1);
assertSame(a.getOwner(), b.getOwner());
assertNull(c.getOwner());
assertNull(d.getOwner());
}
// #if 0
// void f() {
// #if 1
// int a;
// #elif 0
// int b;
// #endif
// }
// #endif
public void testUnexpectedBranchesInInactiveCode() throws Exception {
String code= getAboveComment();
BindingAssertionHelper bh= new BindingAssertionHelper(code, false);
IFunction f= bh.assertNonProblem("f()", 1);
bh.assertNoName("a;", 1);
bh.assertNoName("b;", 1);
bh= new BindingAssertionHelper(code, true);
f= bh.assertNonProblem("f()", 1);
bh.assertNoName("a;", 1);
bh.assertNoName("b;", 1);
}
}
| |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.wsdl.parser;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.stream.buffer.MutableXMLStreamBuffer;
import com.sun.xml.internal.stream.buffer.XMLStreamBuffer;
import com.sun.xml.internal.stream.buffer.XMLStreamBufferMark;
import com.sun.xml.internal.stream.buffer.stax.StreamReaderBufferCreator;
import com.sun.xml.internal.ws.api.BindingID;
import com.sun.xml.internal.ws.api.BindingIDFactory;
import com.sun.xml.internal.ws.api.SOAPVersion;
import com.sun.xml.internal.ws.api.EndpointAddress;
import com.sun.xml.internal.ws.api.WSDLLocator;
import com.sun.xml.internal.ws.api.policy.PolicyResolver;
import com.sun.xml.internal.ws.api.policy.PolicyResolverFactory;
import com.sun.xml.internal.ws.api.addressing.AddressingVersion;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference;
import com.sun.xml.internal.ws.api.model.ParameterBinding;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLDescriptorKind;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLModel;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundFault;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundOperation;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLBoundPortType;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLFault;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLInput;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLMessage;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLModel;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLOperation;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLOutput;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLPart;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLPort;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLPortType;
import com.sun.xml.internal.ws.api.model.wsdl.editable.EditableWSDLService;
import com.sun.xml.internal.ws.api.server.Container;
import com.sun.xml.internal.ws.api.server.ContainerResolver;
import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import com.sun.xml.internal.ws.api.wsdl.parser.MetaDataResolver;
import com.sun.xml.internal.ws.api.wsdl.parser.MetadataResolverFactory;
import com.sun.xml.internal.ws.api.wsdl.parser.ServiceDescriptor;
import com.sun.xml.internal.ws.api.wsdl.parser.WSDLParserExtension;
import com.sun.xml.internal.ws.api.wsdl.parser.XMLEntityResolver;
import com.sun.xml.internal.ws.api.wsdl.parser.XMLEntityResolver.Parser;
import com.sun.xml.internal.ws.model.wsdl.*;
import com.sun.xml.internal.ws.resources.ClientMessages;
import com.sun.xml.internal.ws.resources.WsdlmodelMessages;
import com.sun.xml.internal.ws.streaming.SourceReaderFactory;
import com.sun.xml.internal.ws.streaming.TidyXMLStreamReader;
import com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil;
import com.sun.xml.internal.ws.util.ServiceFinder;
import com.sun.xml.internal.ws.util.xml.XmlUtil;
import com.sun.xml.internal.ws.policy.jaxws.PolicyWSDLParserExtension;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.namespace.QName;
import javax.xml.stream.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FilterInputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.logging.Logger;
/**
* Parses WSDL and builds {@link com.sun.xml.internal.ws.api.model.wsdl.WSDLModel}.
*
* @author Vivek Pandey
* @author Rama Pulavarthi
*/
public class RuntimeWSDLParser {
private final EditableWSDLModel wsdlDoc;
/**
* Target namespace URI of the WSDL that we are currently parsing.
*/
private String targetNamespace;
/**
* System IDs of WSDLs that are already read.
*/
private final Set<String> importedWSDLs = new HashSet<String>();
/**
* Must not be null.
*/
private final XMLEntityResolver resolver;
private final PolicyResolver policyResolver;
/**
* The {@link WSDLParserExtension}. Always non-null.
*/
private final WSDLParserExtension extensionFacade;
private final WSDLParserExtensionContextImpl context;
List<WSDLParserExtension> extensions;
//Capture namespaces declared on the ancestors of wsa:EndpointReference, so that valid XmlStreamBuffer is created
// from the EndpointReference fragment.
Map<String, String> wsdldef_nsdecl = new HashMap<String, String>();
Map<String, String> service_nsdecl = new HashMap<String, String>();
Map<String, String> port_nsdecl = new HashMap<String, String>();
/**
* Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL
* document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found
* then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'.
*
* @param wsdlLoc
* Either this or <tt>wsdl</tt> parameter must be given.
* Null location means the system won't be able to resolve relative references in the WSDL,
*/
public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver,
boolean isClientSide, Container container,
WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
return parse(wsdlLoc, wsdlSource, resolver, isClientSide, container, Service.class, PolicyResolverFactory.create(),extensions);
}
/**
* Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL
* document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found
* then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'.
*
* @param wsdlLoc
* Either this or <tt>wsdl</tt> parameter must be given.
* Null location means the system won't be able to resolve relative references in the WSDL,
*/
public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver,
boolean isClientSide, Container container, Class serviceClass,
WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
return parse(wsdlLoc, wsdlSource, resolver, isClientSide, container, serviceClass, PolicyResolverFactory.create(),extensions);
}
/**
* Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL
* document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found
* then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'.
*
* @param wsdlLoc
* Either this or <tt>wsdl</tt> parameter must be given.
* Null location means the system won't be able to resolve relative references in the WSDL,
*/
public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver,
boolean isClientSide, Container container, @NotNull PolicyResolver policyResolver,
WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
return parse(wsdlLoc, wsdlSource, resolver, isClientSide, container, Service.class, policyResolver, extensions);
}
/**
* Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL
* document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found
* then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'.
*
* @param wsdlLoc
* Either this or <tt>wsdl</tt> parameter must be given.
* Null location means the system won't be able to resolve relative references in the WSDL,
*/
public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver,
boolean isClientSide, Container container, Class serviceClass,
@NotNull PolicyResolver policyResolver,
WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
return parse(wsdlLoc, wsdlSource, resolver, isClientSide, container, serviceClass, policyResolver, false, extensions);
}
/**
* Parses the WSDL and gives WSDLModel. If wsdl parameter is null, then wsdlLoc is used to get the WSDL. If the WSDL
* document could not be obtained then {@link MetadataResolverFactory} is tried to get the WSDL document, if not found
* then as last option, if the wsdlLoc has no '?wsdl' as query parameter then it is tried by appending '?wsdl'.
*
* @param wsdlLoc
* Either this or <tt>wsdl</tt> parameter must be given.
* Null location means the system won't be able to resolve relative references in the WSDL,
*/
public static WSDLModel parse(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, @NotNull EntityResolver resolver,
boolean isClientSide, Container container, Class serviceClass,
@NotNull PolicyResolver policyResolver,
boolean isUseStreamFromEntityResolverWrapper,
WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
assert resolver != null;
RuntimeWSDLParser wsdlParser = new RuntimeWSDLParser(wsdlSource.getSystemId(), new EntityResolverWrapper(resolver, isUseStreamFromEntityResolverWrapper), isClientSide, container, policyResolver, extensions);
Parser parser;
try{
parser = wsdlParser.resolveWSDL(wsdlLoc, wsdlSource, serviceClass);
if(!hasWSDLDefinitions(parser.parser)){
throw new XMLStreamException(ClientMessages.RUNTIME_WSDLPARSER_INVALID_WSDL(parser.systemId,
WSDLConstants.QNAME_DEFINITIONS, parser.parser.getName(), parser.parser.getLocation()));
}
}catch(XMLStreamException e){
//Try MEX if there is WSDLLoc available
if(wsdlLoc == null)
throw e;
return tryWithMex(wsdlParser, wsdlLoc, resolver, isClientSide, container, e, serviceClass, policyResolver, extensions);
}catch(IOException e){
//Try MEX if there is WSDLLoc available
if(wsdlLoc == null)
throw e;
return tryWithMex(wsdlParser, wsdlLoc, resolver, isClientSide, container, e, serviceClass, policyResolver, extensions);
}
wsdlParser.extensionFacade.start(wsdlParser.context);
wsdlParser.parseWSDL(parser, false);
wsdlParser.wsdlDoc.freeze();
wsdlParser.extensionFacade.finished(wsdlParser.context);
wsdlParser.extensionFacade.postFinished(wsdlParser.context);
if(wsdlParser.wsdlDoc.getServices().isEmpty())
throw new WebServiceException(ClientMessages.WSDL_CONTAINS_NO_SERVICE(wsdlLoc));
return wsdlParser.wsdlDoc;
}
private static WSDLModel tryWithMex(@NotNull RuntimeWSDLParser wsdlParser, @NotNull URL wsdlLoc, @NotNull EntityResolver resolver, boolean isClientSide, Container container, Throwable e, Class serviceClass, PolicyResolver policyResolver, WSDLParserExtension... extensions) throws SAXException, XMLStreamException {
ArrayList<Throwable> exceptions = new ArrayList<Throwable>();
try {
WSDLModel wsdlModel = wsdlParser.parseUsingMex(wsdlLoc, resolver, isClientSide, container, serviceClass, policyResolver,extensions);
if(wsdlModel == null){
throw new WebServiceException(ClientMessages.FAILED_TO_PARSE(wsdlLoc.toExternalForm(), e.getMessage()), e);
}
return wsdlModel;
} catch (URISyntaxException e1) {
exceptions.add(e);
exceptions.add(e1);
} catch(IOException e1){
exceptions.add(e);
exceptions.add(e1);
}
throw new InaccessibleWSDLException(exceptions);
}
private WSDLModel parseUsingMex(@NotNull URL wsdlLoc, @NotNull EntityResolver resolver, boolean isClientSide, Container container, Class serviceClass, PolicyResolver policyResolver, WSDLParserExtension[] extensions) throws IOException, SAXException, XMLStreamException, URISyntaxException {
//try MEX
MetaDataResolver mdResolver = null;
ServiceDescriptor serviceDescriptor = null;
RuntimeWSDLParser wsdlParser = null;
//Currently we try the first available MetadataResolverFactory that gives us a WSDL document
for (MetadataResolverFactory resolverFactory : ServiceFinder.find(MetadataResolverFactory.class)) {
mdResolver = resolverFactory.metadataResolver(resolver);
serviceDescriptor = mdResolver.resolve(wsdlLoc.toURI());
//we got the ServiceDescriptor, now break
if (serviceDescriptor != null)
break;
}
if (serviceDescriptor != null) {
List<? extends Source> wsdls = serviceDescriptor.getWSDLs();
wsdlParser = new RuntimeWSDLParser(wsdlLoc.toExternalForm(), new MexEntityResolver(wsdls), isClientSide, container, policyResolver, extensions);
wsdlParser.extensionFacade.start(wsdlParser.context);
for(Source src: wsdls ) {
String systemId = src.getSystemId();
Parser parser = wsdlParser.resolver.resolveEntity(null, systemId);
wsdlParser.parseWSDL(parser, false);
}
}
//Incase that mex is not present or it couldn't get the metadata, try by appending ?wsdl and give
// it a last shot else fail
if ((mdResolver == null || serviceDescriptor == null) && (wsdlLoc.getProtocol().equals("http") || wsdlLoc.getProtocol().equals("https")) && (wsdlLoc.getQuery() == null)) {
String urlString = wsdlLoc.toExternalForm();
urlString += "?wsdl";
wsdlLoc = new URL(urlString);
wsdlParser = new RuntimeWSDLParser(wsdlLoc.toExternalForm(),new EntityResolverWrapper(resolver), isClientSide, container, policyResolver, extensions);
wsdlParser.extensionFacade.start(wsdlParser.context);
Parser parser = resolveWSDL(wsdlLoc, new StreamSource(wsdlLoc.toExternalForm()), serviceClass);
wsdlParser.parseWSDL(parser, false);
}
if(wsdlParser == null)
return null;
wsdlParser.wsdlDoc.freeze();
wsdlParser.extensionFacade.finished(wsdlParser.context);
wsdlParser.extensionFacade.postFinished(wsdlParser.context);
return wsdlParser.wsdlDoc;
}
private static boolean hasWSDLDefinitions(XMLStreamReader reader) {
XMLStreamReaderUtil.nextElementContent(reader);
return reader.getName().equals(WSDLConstants.QNAME_DEFINITIONS);
}
public static WSDLModel parse(XMLEntityResolver.Parser wsdl, XMLEntityResolver resolver, boolean isClientSide, Container container, PolicyResolver policyResolver, WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
assert resolver != null;
RuntimeWSDLParser parser = new RuntimeWSDLParser( wsdl.systemId.toExternalForm(), resolver, isClientSide, container, policyResolver, extensions);
parser.extensionFacade.start(parser.context);
parser.parseWSDL(wsdl, false);
parser.wsdlDoc.freeze();
parser.extensionFacade.finished(parser.context);
parser.extensionFacade.postFinished(parser.context);
return parser.wsdlDoc;
}
public static WSDLModel parse(XMLEntityResolver.Parser wsdl, XMLEntityResolver resolver, boolean isClientSide, Container container, WSDLParserExtension... extensions) throws IOException, XMLStreamException, SAXException {
assert resolver != null;
RuntimeWSDLParser parser = new RuntimeWSDLParser( wsdl.systemId.toExternalForm(), resolver, isClientSide, container, PolicyResolverFactory.create(), extensions);
parser.extensionFacade.start(parser.context);
parser.parseWSDL(wsdl, false);
parser.wsdlDoc.freeze();
parser.extensionFacade.finished(parser.context);
parser.extensionFacade.postFinished(parser.context);
return parser.wsdlDoc;
}
private RuntimeWSDLParser(@NotNull String sourceLocation, XMLEntityResolver resolver, boolean isClientSide, Container container, PolicyResolver policyResolver, WSDLParserExtension... extensions) {
this.wsdlDoc = sourceLocation!=null ? new WSDLModelImpl(sourceLocation) : new WSDLModelImpl();
this.resolver = resolver;
this.policyResolver = policyResolver;
this.extensions = new ArrayList<WSDLParserExtension>();
this.context = new WSDLParserExtensionContextImpl(wsdlDoc, isClientSide, container, policyResolver);
boolean isPolicyExtensionFound = false;
for (WSDLParserExtension e : extensions) {
if (e instanceof com.sun.xml.internal.ws.api.wsdl.parser.PolicyWSDLParserExtension)
isPolicyExtensionFound = true;
register(e);
}
// register handlers for default extensions
if (!isPolicyExtensionFound)
register(new PolicyWSDLParserExtension());
register(new MemberSubmissionAddressingWSDLParserExtension());
register(new W3CAddressingWSDLParserExtension());
register(new W3CAddressingMetadataWSDLParserExtension());
this.extensionFacade = new WSDLParserExtensionFacade(this.extensions.toArray(new WSDLParserExtension[0]));
}
private Parser resolveWSDL(@Nullable URL wsdlLoc, @NotNull Source wsdlSource, Class serviceClass) throws IOException, SAXException, XMLStreamException {
String systemId = wsdlSource.getSystemId();
XMLEntityResolver.Parser parser = resolver.resolveEntity(null, systemId);
if (parser == null && wsdlLoc != null) {
String exForm = wsdlLoc.toExternalForm();
parser = resolver.resolveEntity(null, exForm);
if (parser == null && serviceClass != null) {
URL ru = serviceClass.getResource(".");
if (ru != null) {
String ruExForm = ru.toExternalForm();
if (exForm.startsWith(ruExForm)) {
parser = resolver.resolveEntity(null, exForm.substring(ruExForm.length()));
}
}
}
}
if (parser == null) {
//If a WSDL source is provided that is known to be readable, then
//prioritize that over the URL - this avoids going over the network
//an additional time if a valid WSDL Source is provided - Deva Sagar 09/20/2011
if (isKnownReadableSource(wsdlSource)) {
parser = new Parser(wsdlLoc, createReader(wsdlSource));
} else if (wsdlLoc != null) {
parser = new Parser(wsdlLoc, createReader(wsdlLoc, serviceClass));
}
//parser could still be null if isKnownReadableSource returns
//false and wsdlLoc is also null. Fall back to using Source based
//parser since Source is not null
if (parser == null) {
parser = new Parser(wsdlLoc, createReader(wsdlSource));
}
}
return parser;
}
private boolean isKnownReadableSource(Source wsdlSource) {
if (wsdlSource instanceof StreamSource) {
return (((StreamSource) wsdlSource).getInputStream() != null ||
((StreamSource) wsdlSource).getReader() != null);
} else {
return false;
}
}
private XMLStreamReader createReader(@NotNull Source src) throws XMLStreamException {
return new TidyXMLStreamReader(SourceReaderFactory.createSourceReader(src, true), null);
}
private void parseImport(@NotNull URL wsdlLoc) throws XMLStreamException, IOException, SAXException {
String systemId = wsdlLoc.toExternalForm();
XMLEntityResolver.Parser parser = resolver.resolveEntity(null, systemId);
if (parser == null) {
parser = new Parser(wsdlLoc, createReader(wsdlLoc));
}
parseWSDL(parser, true);
}
private void parseWSDL(Parser parser, boolean imported) throws XMLStreamException, IOException, SAXException {
XMLStreamReader reader = parser.parser;
try {
// avoid processing the same WSDL twice.
// if no system ID is given, the check won't work
if (parser.systemId != null && !importedWSDLs.add(parser.systemId.toExternalForm()))
return;
if(reader.getEventType() == XMLStreamConstants.START_DOCUMENT)
XMLStreamReaderUtil.nextElementContent(reader);
if (WSDLConstants.QNAME_DEFINITIONS.equals(reader.getName())) {
readNSDecl(wsdldef_nsdecl, reader);
}
if (reader.getEventType()!= XMLStreamConstants.END_DOCUMENT && reader.getName().equals(WSDLConstants.QNAME_SCHEMA)) {
if (imported) {
// wsdl:import could be a schema. Relaxing BP R2001 requirement.
LOGGER.warning(WsdlmodelMessages.WSDL_IMPORT_SHOULD_BE_WSDL(parser.systemId));
return;
}
}
//get the targetNamespace of the service
String tns = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_TNS);
final String oldTargetNamespace = targetNamespace;
targetNamespace = tns;
while (XMLStreamReaderUtil.nextElementContent(reader) !=
XMLStreamConstants.END_ELEMENT) {
if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)
break;
QName name = reader.getName();
if (WSDLConstants.QNAME_IMPORT.equals(name)) {
parseImport(parser.systemId, reader);
} else if (WSDLConstants.QNAME_MESSAGE.equals(name)) {
parseMessage(reader);
} else if (WSDLConstants.QNAME_PORT_TYPE.equals(name)) {
parsePortType(reader);
} else if (WSDLConstants.QNAME_BINDING.equals(name)) {
parseBinding(reader);
} else if (WSDLConstants.QNAME_SERVICE.equals(name)) {
parseService(reader);
} else {
extensionFacade.definitionsElements(reader);
}
}
targetNamespace = oldTargetNamespace;
} finally {
this.wsdldef_nsdecl = new HashMap<String,String>();
reader.close();
}
}
private void parseService(XMLStreamReader reader) {
service_nsdecl.putAll(wsdldef_nsdecl);
readNSDecl(service_nsdecl,reader);
String serviceName = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
EditableWSDLService service = new WSDLServiceImpl(reader,wsdlDoc,new QName(targetNamespace, serviceName));
extensionFacade.serviceAttributes(service, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (WSDLConstants.QNAME_PORT.equals(name)) {
parsePort(reader, service);
if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
XMLStreamReaderUtil.next(reader);
}
} else {
extensionFacade.serviceElements(service, reader);
}
}
wsdlDoc.addService(service);
service_nsdecl = new HashMap<String, String>();
}
private void parsePort(XMLStreamReader reader, EditableWSDLService service) {
port_nsdecl.putAll(service_nsdecl);
readNSDecl(port_nsdecl,reader);
String portName = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
String binding = ParserUtil.getMandatoryNonEmptyAttribute(reader, "binding");
QName bindingName = ParserUtil.getQName(reader, binding);
QName portQName = new QName(service.getName().getNamespaceURI(), portName);
EditableWSDLPort port = new WSDLPortImpl(reader,service, portQName, bindingName);
extensionFacade.portAttributes(port, reader);
String location;
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (SOAPConstants.QNAME_ADDRESS.equals(name) || SOAPConstants.QNAME_SOAP12ADDRESS.equals(name)) {
location = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_LOCATION);
if (location != null) {
try {
port.setAddress(new EndpointAddress(location));
} catch (URISyntaxException e) {
//Lets not throw any exception, latter on it should be thrown when invocation happens. At this
// time user has option to set the endopint address using request contexxt property.
}
}
XMLStreamReaderUtil.next(reader);
} else if (AddressingVersion.W3C.nsUri.equals(name.getNamespaceURI()) &&
"EndpointReference".equals(name.getLocalPart())) {
try {
StreamReaderBufferCreator creator = new StreamReaderBufferCreator(new MutableXMLStreamBuffer());
XMLStreamBuffer eprbuffer = new XMLStreamBufferMark(port_nsdecl, creator);
creator.createElementFragment(reader, false);
WSEndpointReference wsepr = new WSEndpointReference(eprbuffer, AddressingVersion.W3C);
//wsepr.toSpec().writeTo(new StreamResult(System.out));
port.setEPR(wsepr);
/** XMLStreamBuffer.createNewBufferFromXMLStreamReader(reader) called from inside WSEndpointReference()
* consumes the complete EPR infoset and moves to the next element. This breaks the normal wsdl parser
* processing where it expects anyone reading the infoset to move to the end of the element that its reading
* and not to the next element.
*/
if(reader.getEventType() == XMLStreamConstants.END_ELEMENT && reader.getName().equals(WSDLConstants.QNAME_PORT))
break;
} catch (XMLStreamException e) {
throw new WebServiceException(e);
}
} else {
extensionFacade.portElements(port, reader);
}
}
if (port.getAddress() == null) {
try {
port.setAddress(new EndpointAddress(""));
} catch (URISyntaxException e) {
//Lets not throw any exception, latter on it should be thrown when invocation happens. At this
//time user has option to set the endopint address using request contexxt property.
}
}
service.put(portQName, port);
port_nsdecl =new HashMap<String, String>();
}
private void parseBinding(XMLStreamReader reader) {
String bindingName = ParserUtil.getMandatoryNonEmptyAttribute(reader, "name");
String portTypeName = ParserUtil.getMandatoryNonEmptyAttribute(reader, "type");
if ((bindingName == null) || (portTypeName == null)) {
//TODO: throw exception?
//
// wsdl:binding element for now
XMLStreamReaderUtil.skipElement(reader);
return;
}
EditableWSDLBoundPortType binding = new WSDLBoundPortTypeImpl(reader,wsdlDoc, new QName(targetNamespace, bindingName),
ParserUtil.getQName(reader, portTypeName));
extensionFacade.bindingAttributes(binding, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (WSDLConstants.NS_SOAP_BINDING.equals(name)) {
String transport = reader.getAttributeValue(null, WSDLConstants.ATTR_TRANSPORT);
binding.setBindingId(createBindingId(transport, SOAPVersion.SOAP_11));
String style = reader.getAttributeValue(null, "style");
if ((style != null) && (style.equals("rpc"))) {
binding.setStyle(Style.RPC);
} else {
binding.setStyle(Style.DOCUMENT);
}
goToEnd(reader);
} else if (WSDLConstants.NS_SOAP12_BINDING.equals(name)) {
String transport = reader.getAttributeValue(null, WSDLConstants.ATTR_TRANSPORT);
binding.setBindingId(createBindingId(transport, SOAPVersion.SOAP_12));
String style = reader.getAttributeValue(null, "style");
if ((style != null) && (style.equals("rpc"))) {
binding.setStyle(Style.RPC);
} else {
binding.setStyle(Style.DOCUMENT);
}
goToEnd(reader);
} else if (WSDLConstants.QNAME_OPERATION.equals(name)) {
parseBindingOperation(reader, binding);
} else {
extensionFacade.bindingElements(binding, reader);
}
}
}
private static BindingID createBindingId(String transport, SOAPVersion soapVersion) {
if (!transport.equals(SOAPConstants.URI_SOAP_TRANSPORT_HTTP)) {
for( BindingIDFactory f : ServiceFinder.find(BindingIDFactory.class) ) {
BindingID bindingId = f.create(transport, soapVersion);
if(bindingId!=null) {
return bindingId;
}
}
}
return soapVersion.equals(SOAPVersion.SOAP_11)?BindingID.SOAP11_HTTP:BindingID.SOAP12_HTTP;
}
private void parseBindingOperation(XMLStreamReader reader, EditableWSDLBoundPortType binding) {
String bindingOpName = ParserUtil.getMandatoryNonEmptyAttribute(reader, "name");
if (bindingOpName == null) {
//TODO: throw exception?
//skip wsdl:binding element for now
XMLStreamReaderUtil.skipElement(reader);
return;
}
QName opName = new QName(binding.getPortTypeName().getNamespaceURI(), bindingOpName);
EditableWSDLBoundOperation bindingOp = new WSDLBoundOperationImpl(reader,binding, opName);
binding.put(opName, bindingOp);
extensionFacade.bindingOperationAttributes(bindingOp, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
String style = null;
if (WSDLConstants.QNAME_INPUT.equals(name)) {
parseInputBinding(reader, bindingOp);
} else if (WSDLConstants.QNAME_OUTPUT.equals(name)) {
parseOutputBinding(reader, bindingOp);
} else if (WSDLConstants.QNAME_FAULT.equals(name)) {
parseFaultBinding(reader, bindingOp);
} else if (SOAPConstants.QNAME_OPERATION.equals(name) ||
SOAPConstants.QNAME_SOAP12OPERATION.equals(name)) {
style = reader.getAttributeValue(null, "style");
String soapAction = reader.getAttributeValue(null, "soapAction");
if (soapAction != null)
bindingOp.setSoapAction(soapAction);
goToEnd(reader);
} else {
extensionFacade.bindingOperationElements(bindingOp, reader);
}
/**
* If style attribute is present set it otherwise set the style as defined
* on the <soap:binding> element
*/
if (style != null) {
if (style.equals("rpc"))
bindingOp.setStyle(Style.RPC);
else
bindingOp.setStyle(Style.DOCUMENT);
} else {
bindingOp.setStyle(binding.getStyle());
}
}
}
private void parseInputBinding(XMLStreamReader reader, EditableWSDLBoundOperation bindingOp) {
boolean bodyFound = false;
extensionFacade.bindingOperationInputAttributes(bindingOp, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if ((SOAPConstants.QNAME_BODY.equals(name) || SOAPConstants.QNAME_SOAP12BODY.equals(name)) && !bodyFound) {
bodyFound = true;
bindingOp.setInputExplicitBodyParts(parseSOAPBodyBinding(reader, bindingOp, BindingMode.INPUT));
goToEnd(reader);
} else if ((SOAPConstants.QNAME_HEADER.equals(name) || SOAPConstants.QNAME_SOAP12HEADER.equals(name))) {
parseSOAPHeaderBinding(reader, bindingOp.getInputParts());
} else if (MIMEConstants.QNAME_MULTIPART_RELATED.equals(name)) {
parseMimeMultipartBinding(reader, bindingOp, BindingMode.INPUT);
} else {
extensionFacade.bindingOperationInputElements(bindingOp, reader);
}
}
}
private void parseOutputBinding(XMLStreamReader reader, EditableWSDLBoundOperation bindingOp) {
boolean bodyFound = false;
extensionFacade.bindingOperationOutputAttributes(bindingOp, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if ((SOAPConstants.QNAME_BODY.equals(name) || SOAPConstants.QNAME_SOAP12BODY.equals(name)) && !bodyFound) {
bodyFound = true;
bindingOp.setOutputExplicitBodyParts(parseSOAPBodyBinding(reader, bindingOp, BindingMode.OUTPUT));
goToEnd(reader);
} else if ((SOAPConstants.QNAME_HEADER.equals(name) || SOAPConstants.QNAME_SOAP12HEADER.equals(name))) {
parseSOAPHeaderBinding(reader, bindingOp.getOutputParts());
} else if (MIMEConstants.QNAME_MULTIPART_RELATED.equals(name)) {
parseMimeMultipartBinding(reader, bindingOp, BindingMode.OUTPUT);
} else {
extensionFacade.bindingOperationOutputElements(bindingOp, reader);
}
}
}
private void parseFaultBinding(XMLStreamReader reader, EditableWSDLBoundOperation bindingOp) {
String faultName = ParserUtil.getMandatoryNonEmptyAttribute(reader, "name");
EditableWSDLBoundFault wsdlBoundFault = new WSDLBoundFaultImpl(reader, faultName, bindingOp);
bindingOp.addFault(wsdlBoundFault);
extensionFacade.bindingOperationFaultAttributes(wsdlBoundFault, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
extensionFacade.bindingOperationFaultElements(wsdlBoundFault, reader);
}
}
private enum BindingMode {
INPUT, OUTPUT, FAULT}
private static boolean parseSOAPBodyBinding(XMLStreamReader reader, EditableWSDLBoundOperation op, BindingMode mode) {
String namespace = reader.getAttributeValue(null, "namespace");
if (mode == BindingMode.INPUT) {
op.setRequestNamespace(namespace);
return parseSOAPBodyBinding(reader, op.getInputParts());
}
//resp
op.setResponseNamespace(namespace);
return parseSOAPBodyBinding(reader, op.getOutputParts());
}
/**
* Returns true if body has explicit parts declaration
*/
private static boolean parseSOAPBodyBinding(XMLStreamReader reader, Map<String, ParameterBinding> parts) {
String partsString = reader.getAttributeValue(null, "parts");
if (partsString != null) {
List<String> partsList = XmlUtil.parseTokenList(partsString);
if (partsList.isEmpty()) {
parts.put(" ", ParameterBinding.BODY);
} else {
for (String part : partsList) {
parts.put(part, ParameterBinding.BODY);
}
}
return true;
}
return false;
}
private static void parseSOAPHeaderBinding(XMLStreamReader reader, Map<String, ParameterBinding> parts) {
String part = reader.getAttributeValue(null, "part");
//if(part == null| part.equals("")||message == null || message.equals("")){
if (part == null || part.equals("")) {
return;
}
//lets not worry about message attribute for now, probably additional headers wont be there
//String message = reader.getAttributeValue(null, "message");
//QName msgName = ParserUtil.getQName(reader, message);
parts.put(part, ParameterBinding.HEADER);
goToEnd(reader);
}
private static void parseMimeMultipartBinding(XMLStreamReader reader, EditableWSDLBoundOperation op, BindingMode mode) {
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (MIMEConstants.QNAME_PART.equals(name)) {
parseMIMEPart(reader, op, mode);
} else {
XMLStreamReaderUtil.skipElement(reader);
}
}
}
private static void parseMIMEPart(XMLStreamReader reader, EditableWSDLBoundOperation op, BindingMode mode) {
boolean bodyFound = false;
Map<String, ParameterBinding> parts = null;
if (mode == BindingMode.INPUT) {
parts = op.getInputParts();
} else if (mode == BindingMode.OUTPUT) {
parts = op.getOutputParts();
} else if (mode == BindingMode.FAULT) {
parts = op.getFaultParts();
}
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (SOAPConstants.QNAME_BODY.equals(name) && !bodyFound) {
bodyFound = true;
parseSOAPBodyBinding(reader, op, mode);
XMLStreamReaderUtil.next(reader);
} else if (SOAPConstants.QNAME_HEADER.equals(name)) {
bodyFound = true;
parseSOAPHeaderBinding(reader, parts);
XMLStreamReaderUtil.next(reader);
} else if (MIMEConstants.QNAME_CONTENT.equals(name)) {
String part = reader.getAttributeValue(null, "part");
String type = reader.getAttributeValue(null, "type");
if ((part == null) || (type == null)) {
XMLStreamReaderUtil.skipElement(reader);
continue;
}
ParameterBinding sb = ParameterBinding.createAttachment(type);
if (parts != null && sb != null && part != null)
parts.put(part, sb);
XMLStreamReaderUtil.next(reader);
} else {
XMLStreamReaderUtil.skipElement(reader);
}
}
}
protected void parseImport(@Nullable URL baseURL, XMLStreamReader reader) throws IOException, SAXException, XMLStreamException {
// expand to the absolute URL of the imported WSDL.
String importLocation =
ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_LOCATION);
URL importURL;
if(baseURL!=null)
importURL = new URL(baseURL, importLocation);
else // no base URL. this better be absolute
importURL = new URL(importLocation);
parseImport(importURL);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
XMLStreamReaderUtil.skipElement(reader);
}
}
private void parsePortType(XMLStreamReader reader) {
String portTypeName = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
if (portTypeName == null) {
//TODO: throw exception?
//skip wsdl:portType element for now
XMLStreamReaderUtil.skipElement(reader);
return;
}
EditableWSDLPortType portType = new WSDLPortTypeImpl(reader,wsdlDoc, new QName(targetNamespace, portTypeName));
extensionFacade.portTypeAttributes(portType, reader);
wsdlDoc.addPortType(portType);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (WSDLConstants.QNAME_OPERATION.equals(name)) {
parsePortTypeOperation(reader, portType);
} else {
extensionFacade.portTypeElements(portType, reader);
}
}
}
private void parsePortTypeOperation(XMLStreamReader reader, EditableWSDLPortType portType) {
String operationName = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
if (operationName == null) {
//TODO: throw exception?
//skip wsdl:portType element for now
XMLStreamReaderUtil.skipElement(reader);
return;
}
QName operationQName = new QName(portType.getName().getNamespaceURI(), operationName);
EditableWSDLOperation operation = new WSDLOperationImpl(reader,portType, operationQName);
extensionFacade.portTypeOperationAttributes(operation, reader);
String parameterOrder = ParserUtil.getAttribute(reader, "parameterOrder");
operation.setParameterOrder(parameterOrder);
portType.put(operationName, operation);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (name.equals(WSDLConstants.QNAME_INPUT)) {
parsePortTypeOperationInput(reader, operation);
} else if (name.equals(WSDLConstants.QNAME_OUTPUT)) {
parsePortTypeOperationOutput(reader, operation);
} else if (name.equals(WSDLConstants.QNAME_FAULT)) {
parsePortTypeOperationFault(reader, operation);
} else {
extensionFacade.portTypeOperationElements(operation, reader);
}
}
}
private void parsePortTypeOperationFault(XMLStreamReader reader, EditableWSDLOperation operation) {
String msg = ParserUtil.getMandatoryNonEmptyAttribute(reader, "message");
QName msgName = ParserUtil.getQName(reader, msg);
String name = ParserUtil.getMandatoryNonEmptyAttribute(reader, "name");
EditableWSDLFault fault = new WSDLFaultImpl(reader,name, msgName, operation);
operation.addFault(fault);
extensionFacade.portTypeOperationFaultAttributes(fault, reader);
extensionFacade.portTypeOperationFault(operation, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
extensionFacade.portTypeOperationFaultElements(fault, reader);
}
}
private void parsePortTypeOperationInput(XMLStreamReader reader, EditableWSDLOperation operation) {
String msg = ParserUtil.getMandatoryNonEmptyAttribute(reader, "message");
QName msgName = ParserUtil.getQName(reader, msg);
String name = ParserUtil.getAttribute(reader, "name");
EditableWSDLInput input = new WSDLInputImpl(reader, name, msgName, operation);
operation.setInput(input);
extensionFacade.portTypeOperationInputAttributes(input, reader);
extensionFacade.portTypeOperationInput(operation, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
extensionFacade.portTypeOperationInputElements(input, reader);
}
}
private void parsePortTypeOperationOutput(XMLStreamReader reader, EditableWSDLOperation operation) {
String msg = ParserUtil.getAttribute(reader, "message");
QName msgName = ParserUtil.getQName(reader, msg);
String name = ParserUtil.getAttribute(reader, "name");
EditableWSDLOutput output = new WSDLOutputImpl(reader,name, msgName, operation);
operation.setOutput(output);
extensionFacade.portTypeOperationOutputAttributes(output, reader);
extensionFacade.portTypeOperationOutput(operation, reader);
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
extensionFacade.portTypeOperationOutputElements(output, reader);
}
}
private void parseMessage(XMLStreamReader reader) {
String msgName = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
EditableWSDLMessage msg = new WSDLMessageImpl(reader,new QName(targetNamespace, msgName));
extensionFacade.messageAttributes(msg, reader);
int partIndex = 0;
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
QName name = reader.getName();
if (WSDLConstants.QNAME_PART.equals(name)) {
String part = ParserUtil.getMandatoryNonEmptyAttribute(reader, WSDLConstants.ATTR_NAME);
String desc = null;
int index = reader.getAttributeCount();
WSDLDescriptorKind kind = WSDLDescriptorKind.ELEMENT;
for (int i = 0; i < index; i++) {
QName descName = reader.getAttributeName(i);
if (descName.getLocalPart().equals("element"))
kind = WSDLDescriptorKind.ELEMENT;
else if (descName.getLocalPart().equals("type"))
kind = WSDLDescriptorKind.TYPE;
if (descName.getLocalPart().equals("element") || descName.getLocalPart().equals("type")) {
desc = reader.getAttributeValue(i);
break;
}
}
if (desc != null) {
EditableWSDLPart wsdlPart = new WSDLPartImpl(reader, part, partIndex, new WSDLPartDescriptorImpl(reader,ParserUtil.getQName(reader, desc), kind));
msg.add(wsdlPart);
}
if (reader.getEventType() != XMLStreamConstants.END_ELEMENT)
goToEnd(reader);
} else {
extensionFacade.messageElements(msg, reader);
}
}
wsdlDoc.addMessage(msg);
if (reader.getEventType() != XMLStreamConstants.END_ELEMENT)
goToEnd(reader);
}
private static void goToEnd(XMLStreamReader reader) {
while (XMLStreamReaderUtil.nextElementContent(reader) != XMLStreamConstants.END_ELEMENT) {
XMLStreamReaderUtil.skipElement(reader);
}
}
/**
* Make sure to return a "fresh" reader each time it is called because
* more than one active reader may be needed within a single thread
* to parse a WSDL file.
*/
private static XMLStreamReader createReader(URL wsdlLoc) throws IOException, XMLStreamException {
return createReader(wsdlLoc, null);
}
/**
* Make sure to return a "fresh" reader each time it is called because
* more than one active reader may be needed within a single thread
* to parse a WSDL file.
*/
private static XMLStreamReader createReader(URL wsdlLoc, Class<Service> serviceClass) throws IOException, XMLStreamException {
InputStream stream;
try {
stream = wsdlLoc.openStream();
} catch (IOException io) {
out:
do {
if (serviceClass != null) {
WSDLLocator locator = ContainerResolver.getInstance().getContainer().getSPI(WSDLLocator.class);
if (locator != null) {
String exForm = wsdlLoc.toExternalForm();
URL ru = serviceClass.getResource(".");
String loc = wsdlLoc.getPath();
if (ru != null) {
String ruExForm = ru.toExternalForm();
if (exForm.startsWith(ruExForm)) {
loc = exForm.substring(ruExForm.length());
}
}
wsdlLoc = locator.locateWSDL(serviceClass, loc);
if (wsdlLoc != null) {
stream = new FilterInputStream(wsdlLoc.openStream()) {
boolean closed;
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
byte[] buf = new byte[8192];
while(read(buf) != -1);
super.close();
}
}
};
break out;
}
}
}
throw io;
} while(true);
}
return new TidyXMLStreamReader(XMLStreamReaderFactory.create(wsdlLoc.toExternalForm(), stream, false), stream);
}
private void register(WSDLParserExtension e) {
// protect JAX-WS RI from broken parser extension
extensions.add(new FoolProofParserExtension(e));
}
/**
* Reads the namespace declarations from the reader's current position in to the map. The reader is expected to be
* on the start element.
*
* @param ns_map
* @param reader
*/
private static void readNSDecl(Map<String, String> ns_map, XMLStreamReader reader) {
if (reader.getNamespaceCount() > 0) {
for (int i = 0; i < reader.getNamespaceCount(); i++) {
ns_map.put(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
}
}
}
private static final Logger LOGGER = Logger.getLogger(RuntimeWSDLParser.class.getName());
}
| |
package org.glob3.mobile.specific;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.glob3.mobile.generated.IImage;
import org.glob3.mobile.generated.Vector2I;
import android.graphics.Bitmap;
public final class Image_Android
extends
IImage {
private static final boolean DEBUG = false;
private static String createCallStackString() {
final Exception e = new Exception();
final StringWriter wr = new StringWriter();
final PrintWriter err = new PrintWriter(wr);
e.printStackTrace(err);
err.flush();
return wr.toString() //
.replace("org.glob3.mobile.specific.", "") //
.replace("org.glob3.mobile.generated.", "") //
.replace("android.opengl.", "") //
.replace("at", "") //
.replace("java.lang.Exception\n", "");
}
private static class BitmapHolder {
private Bitmap _bitmap;
private int _referencesCount;
@SuppressWarnings("unused")
private final String _createdAt;
private final List<String> _retainedAt = new ArrayList<String>();
private final List<String> _releasedAt = new ArrayList<String>();
private BitmapHolder(final Bitmap bitmap) {
_bitmap = bitmap;
_referencesCount = 1;
_createdAt = DEBUG ? createCallStackString() : null;
}
private void _retain() {
synchronized (this) {
_referencesCount++;
if (DEBUG) {
_retainedAt.add(createCallStackString());
}
}
}
private void _release() {
synchronized (this) {
_referencesCount--;
if (_referencesCount == 0) {
_bitmap.recycle();
_bitmap = null;
}
if (DEBUG) {
_releasedAt.add(createCallStackString());
}
}
}
// @Override
// protected void finalize() throws Throwable {
// if (DEBUG) {
// if (_referencesCount != 0) {
// synchronized (ILogger.instance()) {
// ILogger.instance().logError("=======");
// ILogger.instance().logError("***** BitmapHolder deleted with invalid _referencesCount=" + _referencesCount);
//
// final StringBuffer msg = new StringBuffer();
// msg.append("Created At:\n");
// msg.append(_createdAt);
// msg.append("Retained At:\n");
// for (final String e : _retainedAt) {
// msg.append(e);
// msg.append("---\n");
// }
// msg.append("Released At:\n");
// for (final String e : _releasedAt) {
// msg.append(e);
// msg.append("---\n");
// }
// msg.append("=======\n");
//
// ILogger.instance().logError(msg.toString());
// }
// }
// }
// super.finalize();
// }
}
final private BitmapHolder _bitmapHolder;
private byte[] _source;
@SuppressWarnings("unused")
private boolean _bitmapHolderReleased = false;
@SuppressWarnings("unused")
private final String _createdAt;
public Image_Android(final Bitmap bitmap,
final byte[] source) {
_createdAt = DEBUG ? createCallStackString() : null;
if (bitmap == null) {
throw new RuntimeException("Can't create an Image_Android with a null bitmap");
}
_bitmapHolder = new BitmapHolder(bitmap);
_source = source;
}
private Image_Android(final BitmapHolder bitmapHolder,
final byte[] source) {
_createdAt = DEBUG ? createCallStackString() : null;
if (bitmapHolder == null) {
throw new RuntimeException("Can't create an Image_Android with a null bitmap");
}
bitmapHolder._retain();
_bitmapHolder = bitmapHolder;
_source = source;
}
public Bitmap getBitmap() {
return _bitmapHolder._bitmap;
}
@Override
public int getWidth() {
return (_bitmapHolder._bitmap == null) ? 0 : _bitmapHolder._bitmap.getWidth();
}
@Override
public int getHeight() {
return (_bitmapHolder._bitmap == null) ? 0 : _bitmapHolder._bitmap.getHeight();
}
@Override
public boolean isPremultiplied() {
return (_bitmapHolder._bitmap == null) ? false : true; // TODO fix this correctly
}
@Override
public Vector2I getExtent() {
return new Vector2I(getWidth(), getHeight());
}
@Override
public String description() {
return "Image_Android " + getWidth() + " x " + getHeight() + ", _image=(" + _bitmapHolder._bitmap.describeContents() + ")";
}
public byte[] getSourceBuffer() {
return _source;
}
public void releaseSourceBuffer() {
_source = null;
}
@Override
public Image_Android shallowCopy() {
return new Image_Android(_bitmapHolder, _source);
}
@Override
public void dispose() {
synchronized (this) {
_bitmapHolderReleased = true;
_bitmapHolder._release();
}
super.dispose();
}
// @Override
// protected void finalize() throws Throwable {
// if (DEBUG) {
// if (!_bitmapHolderReleased) {
// synchronized (ILogger.instance()) {
// final StringBuffer msg = new StringBuffer();
// msg.append("************\n");
// msg.append("Image_Android finalized without releasing the _bitmapHolder created at: \n");
// msg.append(_createdAt);
// msg.append("************\n");
// ILogger.instance().logError(msg.toString());
// }
// }
// }
// super.finalize();
// }
}
| |
package com.prolificcoder;
import java.util.List;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.ParseQuery;
import com.parse.ParseUser;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends Activity {
ParseUser curUser=null;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mUserName;
private String mPassword;
// UI references.
private EditText mUserNameView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUserNameView = (EditText) findViewById(R.id.username);
mUserNameView.setText(mUserName);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUserNameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mUserName = mUserNameView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
curUser = ParseUser.logIn(mUserName, mPassword);
Log.d("from app", "done logging");
return true;
} catch (com.parse.ParseException e) {
if(e.getMessage() == "invalid login credentials")
{
try {
ParseQuery<ParseUser> userquery = ParseUser.getQuery();
userquery.whereContains("username", mUserName);
List<ParseUser> userResults = userquery.find();
if (userResults.size() != 0)
{
return false;
}
else
{
ParseUser user = new ParseUser();
user.setUsername(mUserName);
user.setPassword(mPassword);
user.signUp();
curUser = ParseUser.logIn(mUserName, mPassword);
return true;
}
} catch (com.parse.ParseException e1) {
Toast.makeText(getApplicationContext(), "Unable to sign up or login)", Toast.LENGTH_LONG).show();
return false;
}
}
Log.d("from app",e.getMessage());
}
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.nutz.repo.org.objectweb.asm;
/**
* Defines the JVM opcodes, access flags and array type codes. This interface
* does not define all the JVM opcodes because some opcodes are automatically
* handled. For example, the xLOAD and xSTORE opcodes are automatically replaced
* by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and xSTORE_n
* opcodes are therefore not defined in this interface. Likewise for LDC,
* automatically replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and
* JSR_W.
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
public interface Opcodes {
// versions
int V1_1 = 3 << 16 | 45;
int V1_2 = 0 << 16 | 46;
int V1_3 = 0 << 16 | 47;
int V1_4 = 0 << 16 | 48;
int V1_5 = 0 << 16 | 49;
int V1_6 = 0 << 16 | 50;
int V1_7 = 0 << 16 | 51;
// access flags
int ACC_PUBLIC = 0x0001; // class, field, method
int ACC_PRIVATE = 0x0002; // class, field, method
int ACC_PROTECTED = 0x0004; // class, field, method
int ACC_STATIC = 0x0008; // field, method
int ACC_FINAL = 0x0010; // class, field, method
int ACC_SUPER = 0x0020; // class
int ACC_SYNCHRONIZED = 0x0020; // method
int ACC_VOLATILE = 0x0040; // field
int ACC_BRIDGE = 0x0040; // method
int ACC_VARARGS = 0x0080; // method
int ACC_TRANSIENT = 0x0080; // field
int ACC_NATIVE = 0x0100; // method
int ACC_INTERFACE = 0x0200; // class
int ACC_ABSTRACT = 0x0400; // class, method
int ACC_STRICT = 0x0800; // method
int ACC_SYNTHETIC = 0x1000; // class, field, method
int ACC_ANNOTATION = 0x2000; // class
int ACC_ENUM = 0x4000; // class(?) field inner
// ASM specific pseudo access flags
int ACC_DEPRECATED = 0x20000; // class, field, method
// types for NEWARRAY
int T_BOOLEAN = 4;
int T_CHAR = 5;
int T_FLOAT = 6;
int T_DOUBLE = 7;
int T_BYTE = 8;
int T_SHORT = 9;
int T_INT = 10;
int T_LONG = 11;
// stack map frame types
/**
* Represents an expanded frame. See {@link ClassReader#EXPAND_FRAMES}.
*/
int F_NEW = -1;
/**
* Represents a compressed frame with complete frame data.
*/
int F_FULL = 0;
/**
* Represents a compressed frame where locals are the same as the locals in
* the previous frame, except that additional 1-3 locals are defined, and
* with an empty stack.
*/
int F_APPEND = 1;
/**
* Represents a compressed frame where locals are the same as the locals in
* the previous frame, except that the last 1-3 locals are absent and with
* an empty stack.
*/
int F_CHOP = 2;
/**
* Represents a compressed frame with exactly the same locals as the
* previous frame and with an empty stack.
*/
int F_SAME = 3;
/**
* Represents a compressed frame with exactly the same locals as the
* previous frame and with a single value on the stack.
*/
int F_SAME1 = 4;
Integer TOP = new Integer(0);
Integer INTEGER = new Integer(1);
Integer FLOAT = new Integer(2);
Integer DOUBLE = new Integer(3);
Integer LONG = new Integer(4);
Integer NULL = new Integer(5);
Integer UNINITIALIZED_THIS = new Integer(6);
/**
* Represents a owner of an invokedynamic call.
*/
String INVOKEDYNAMIC_OWNER = "java/lang/dyn/Dynamic";
// opcodes // visit method (- = idem)
int NOP = 0; // visitInsn
int ACONST_NULL = 1; // -
int ICONST_M1 = 2; // -
int ICONST_0 = 3; // -
int ICONST_1 = 4; // -
int ICONST_2 = 5; // -
int ICONST_3 = 6; // -
int ICONST_4 = 7; // -
int ICONST_5 = 8; // -
int LCONST_0 = 9; // -
int LCONST_1 = 10; // -
int FCONST_0 = 11; // -
int FCONST_1 = 12; // -
int FCONST_2 = 13; // -
int DCONST_0 = 14; // -
int DCONST_1 = 15; // -
int BIPUSH = 16; // visitIntInsn
int SIPUSH = 17; // -
int LDC = 18; // visitLdcInsn
// int LDC_W = 19; // -
// int LDC2_W = 20; // -
int ILOAD = 21; // visitVarInsn
int LLOAD = 22; // -
int FLOAD = 23; // -
int DLOAD = 24; // -
int ALOAD = 25; // -
// int ILOAD_0 = 26; // -
// int ILOAD_1 = 27; // -
// int ILOAD_2 = 28; // -
// int ILOAD_3 = 29; // -
// int LLOAD_0 = 30; // -
// int LLOAD_1 = 31; // -
// int LLOAD_2 = 32; // -
// int LLOAD_3 = 33; // -
// int FLOAD_0 = 34; // -
// int FLOAD_1 = 35; // -
// int FLOAD_2 = 36; // -
// int FLOAD_3 = 37; // -
// int DLOAD_0 = 38; // -
// int DLOAD_1 = 39; // -
// int DLOAD_2 = 40; // -
// int DLOAD_3 = 41; // -
// int ALOAD_0 = 42; // -
// int ALOAD_1 = 43; // -
// int ALOAD_2 = 44; // -
// int ALOAD_3 = 45; // -
int IALOAD = 46; // visitInsn
int LALOAD = 47; // -
int FALOAD = 48; // -
int DALOAD = 49; // -
int AALOAD = 50; // -
int BALOAD = 51; // -
int CALOAD = 52; // -
int SALOAD = 53; // -
int ISTORE = 54; // visitVarInsn
int LSTORE = 55; // -
int FSTORE = 56; // -
int DSTORE = 57; // -
int ASTORE = 58; // -
// int ISTORE_0 = 59; // -
// int ISTORE_1 = 60; // -
// int ISTORE_2 = 61; // -
// int ISTORE_3 = 62; // -
// int LSTORE_0 = 63; // -
// int LSTORE_1 = 64; // -
// int LSTORE_2 = 65; // -
// int LSTORE_3 = 66; // -
// int FSTORE_0 = 67; // -
// int FSTORE_1 = 68; // -
// int FSTORE_2 = 69; // -
// int FSTORE_3 = 70; // -
// int DSTORE_0 = 71; // -
// int DSTORE_1 = 72; // -
// int DSTORE_2 = 73; // -
// int DSTORE_3 = 74; // -
// int ASTORE_0 = 75; // -
// int ASTORE_1 = 76; // -
// int ASTORE_2 = 77; // -
// int ASTORE_3 = 78; // -
int IASTORE = 79; // visitInsn
int LASTORE = 80; // -
int FASTORE = 81; // -
int DASTORE = 82; // -
int AASTORE = 83; // -
int BASTORE = 84; // -
int CASTORE = 85; // -
int SASTORE = 86; // -
int POP = 87; // -
int POP2 = 88; // -
int DUP = 89; // -
int DUP_X1 = 90; // -
int DUP_X2 = 91; // -
int DUP2 = 92; // -
int DUP2_X1 = 93; // -
int DUP2_X2 = 94; // -
int SWAP = 95; // -
int IADD = 96; // -
int LADD = 97; // -
int FADD = 98; // -
int DADD = 99; // -
int ISUB = 100; // -
int LSUB = 101; // -
int FSUB = 102; // -
int DSUB = 103; // -
int IMUL = 104; // -
int LMUL = 105; // -
int FMUL = 106; // -
int DMUL = 107; // -
int IDIV = 108; // -
int LDIV = 109; // -
int FDIV = 110; // -
int DDIV = 111; // -
int IREM = 112; // -
int LREM = 113; // -
int FREM = 114; // -
int DREM = 115; // -
int INEG = 116; // -
int LNEG = 117; // -
int FNEG = 118; // -
int DNEG = 119; // -
int ISHL = 120; // -
int LSHL = 121; // -
int ISHR = 122; // -
int LSHR = 123; // -
int IUSHR = 124; // -
int LUSHR = 125; // -
int IAND = 126; // -
int LAND = 127; // -
int IOR = 128; // -
int LOR = 129; // -
int IXOR = 130; // -
int LXOR = 131; // -
int IINC = 132; // visitIincInsn
int I2L = 133; // visitInsn
int I2F = 134; // -
int I2D = 135; // -
int L2I = 136; // -
int L2F = 137; // -
int L2D = 138; // -
int F2I = 139; // -
int F2L = 140; // -
int F2D = 141; // -
int D2I = 142; // -
int D2L = 143; // -
int D2F = 144; // -
int I2B = 145; // -
int I2C = 146; // -
int I2S = 147; // -
int LCMP = 148; // -
int FCMPL = 149; // -
int FCMPG = 150; // -
int DCMPL = 151; // -
int DCMPG = 152; // -
int IFEQ = 153; // visitJumpInsn
int IFNE = 154; // -
int IFLT = 155; // -
int IFGE = 156; // -
int IFGT = 157; // -
int IFLE = 158; // -
int IF_ICMPEQ = 159; // -
int IF_ICMPNE = 160; // -
int IF_ICMPLT = 161; // -
int IF_ICMPGE = 162; // -
int IF_ICMPGT = 163; // -
int IF_ICMPLE = 164; // -
int IF_ACMPEQ = 165; // -
int IF_ACMPNE = 166; // -
int GOTO = 167; // -
int JSR = 168; // -
int RET = 169; // visitVarInsn
int TABLESWITCH = 170; // visiTableSwitchInsn
int LOOKUPSWITCH = 171; // visitLookupSwitch
int IRETURN = 172; // visitInsn
int LRETURN = 173; // -
int FRETURN = 174; // -
int DRETURN = 175; // -
int ARETURN = 176; // -
int RETURN = 177; // -
int GETSTATIC = 178; // visitFieldInsn
int PUTSTATIC = 179; // -
int GETFIELD = 180; // -
int PUTFIELD = 181; // -
int INVOKEVIRTUAL = 182; // visitMethodInsn
int INVOKESPECIAL = 183; // -
int INVOKESTATIC = 184; // -
int INVOKEINTERFACE = 185; // -
int INVOKEDYNAMIC = 186; // -
int NEW = 187; // visitTypeInsn
int NEWARRAY = 188; // visitIntInsn
int ANEWARRAY = 189; // visitTypeInsn
int ARRAYLENGTH = 190; // visitInsn
int ATHROW = 191; // -
int CHECKCAST = 192; // visitTypeInsn
int INSTANCEOF = 193; // -
int MONITORENTER = 194; // visitInsn
int MONITOREXIT = 195; // -
// int WIDE = 196; // NOT VISITED
int MULTIANEWARRAY = 197; // visitMultiANewArrayInsn
int IFNULL = 198; // visitJumpInsn
int IFNONNULL = 199; // -
// int GOTO_W = 200; // -
// int JSR_W = 201; // -
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.datanode;
import java.io.IOException;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.server.datanode.FSDataset.FSVolume;
import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
import org.junit.Assert;
import org.junit.Test;
/** Test if FSDataset#append, writeToRbw, and writeToTmp */
public class TestWriteToReplica {
final private static int FINALIZED = 0;
final private static int TEMPORARY = 1;
final private static int RBW = 2;
final private static int RWR = 3;
final private static int RUR = 4;
final private static int NON_EXISTENT = 5;
// test close
@Test
public void testClose() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(new HdfsConfiguration()).build();
try {
cluster.waitActive();
DataNode dn = cluster.getDataNodes().get(0);
FSDataset dataSet = (FSDataset)dn.data;
// set up replicasMap
String bpid = cluster.getNamesystem().getBlockPoolId();
ExtendedBlock[] blocks = setup(bpid, dataSet);
// test close
testClose(dataSet, blocks);
} finally {
cluster.shutdown();
}
}
// test append
@Test
public void testAppend() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(new HdfsConfiguration()).build();
try {
cluster.waitActive();
DataNode dn = cluster.getDataNodes().get(0);
FSDataset dataSet = (FSDataset)dn.data;
// set up replicasMap
String bpid = cluster.getNamesystem().getBlockPoolId();
ExtendedBlock[] blocks = setup(bpid, dataSet);
// test append
testAppend(bpid, dataSet, blocks);
} finally {
cluster.shutdown();
}
}
// test writeToRbw
@Test
public void testWriteToRbw() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(new HdfsConfiguration()).build();
try {
cluster.waitActive();
DataNode dn = cluster.getDataNodes().get(0);
FSDataset dataSet = (FSDataset)dn.data;
// set up replicasMap
String bpid = cluster.getNamesystem().getBlockPoolId();
ExtendedBlock[] blocks = setup(bpid, dataSet);
// test writeToRbw
testWriteToRbw(dataSet, blocks);
} finally {
cluster.shutdown();
}
}
// test writeToTemporary
@Test
public void testWriteToTempoary() throws Exception {
MiniDFSCluster cluster = new MiniDFSCluster.Builder(new HdfsConfiguration()).build();
try {
cluster.waitActive();
DataNode dn = cluster.getDataNodes().get(0);
FSDataset dataSet = (FSDataset)dn.data;
// set up replicasMap
String bpid = cluster.getNamesystem().getBlockPoolId();
ExtendedBlock[] blocks = setup(bpid, dataSet);
// test writeToTemporary
testWriteToTemporary(dataSet, blocks);
} finally {
cluster.shutdown();
}
}
/**
* Generate testing environment and return a collection of blocks
* on which to run the tests.
*
* @param bpid Block pool ID to generate blocks for
* @param dataSet Namespace in which to insert blocks
* @return Contrived blocks for further testing.
* @throws IOException
*/
private ExtendedBlock[] setup(String bpid, FSDataset dataSet) throws IOException {
// setup replicas map
ExtendedBlock[] blocks = new ExtendedBlock[] {
new ExtendedBlock(bpid, 1, 1, 2001), new ExtendedBlock(bpid, 2, 1, 2002),
new ExtendedBlock(bpid, 3, 1, 2003), new ExtendedBlock(bpid, 4, 1, 2004),
new ExtendedBlock(bpid, 5, 1, 2005), new ExtendedBlock(bpid, 6, 1, 2006)
};
ReplicasMap replicasMap = dataSet.volumeMap;
FSVolume vol = dataSet.volumes.getNextVolume(0);
ReplicaInfo replicaInfo = new FinalizedReplica(
blocks[FINALIZED].getLocalBlock(), vol, vol.getDir());
replicasMap.add(bpid, replicaInfo);
replicaInfo.getBlockFile().createNewFile();
replicaInfo.getMetaFile().createNewFile();
replicasMap.add(bpid, new ReplicaInPipeline(
blocks[TEMPORARY].getBlockId(),
blocks[TEMPORARY].getGenerationStamp(), vol,
vol.createTmpFile(bpid, blocks[TEMPORARY].getLocalBlock()).getParentFile()));
replicaInfo = new ReplicaBeingWritten(blocks[RBW].getLocalBlock(), vol,
vol.createRbwFile(bpid, blocks[RBW].getLocalBlock()).getParentFile(), null);
replicasMap.add(bpid, replicaInfo);
replicaInfo.getBlockFile().createNewFile();
replicaInfo.getMetaFile().createNewFile();
replicasMap.add(bpid, new ReplicaWaitingToBeRecovered(
blocks[RWR].getLocalBlock(), vol, vol.createRbwFile(bpid,
blocks[RWR].getLocalBlock()).getParentFile()));
replicasMap.add(bpid, new ReplicaUnderRecovery(new FinalizedReplica(blocks[RUR]
.getLocalBlock(), vol, vol.getDir()), 2007));
return blocks;
}
private void testAppend(String bpid, FSDataset dataSet, ExtendedBlock[] blocks) throws IOException {
long newGS = blocks[FINALIZED].getGenerationStamp()+1;
FSVolume v = dataSet.volumeMap.get(bpid, blocks[FINALIZED].getLocalBlock())
.getVolume();
long available = v.getCapacity()-v.getDfsUsed();
long expectedLen = blocks[FINALIZED].getNumBytes();
try {
v.decDfsUsed(bpid, -available);
blocks[FINALIZED].setNumBytes(expectedLen+100);
dataSet.append(blocks[FINALIZED], newGS, expectedLen);
Assert.fail("Should not have space to append to an RWR replica" + blocks[RWR]);
} catch (DiskOutOfSpaceException e) {
Assert.assertTrue(e.getMessage().startsWith(
"Insufficient space for appending to "));
}
v.decDfsUsed(bpid, available);
blocks[FINALIZED].setNumBytes(expectedLen);
newGS = blocks[RBW].getGenerationStamp()+1;
dataSet.append(blocks[FINALIZED], newGS,
blocks[FINALIZED].getNumBytes()); // successful
blocks[FINALIZED].setGenerationStamp(newGS);
try {
dataSet.append(blocks[TEMPORARY], blocks[TEMPORARY].getGenerationStamp()+1,
blocks[TEMPORARY].getNumBytes());
Assert.fail("Should not have appended to a temporary replica "
+ blocks[TEMPORARY]);
} catch (ReplicaNotFoundException e) {
Assert.assertEquals(ReplicaNotFoundException.UNFINALIZED_REPLICA +
blocks[TEMPORARY], e.getMessage());
}
try {
dataSet.append(blocks[RBW], blocks[RBW].getGenerationStamp()+1,
blocks[RBW].getNumBytes());
Assert.fail("Should not have appended to an RBW replica" + blocks[RBW]);
} catch (ReplicaNotFoundException e) {
Assert.assertEquals(ReplicaNotFoundException.UNFINALIZED_REPLICA +
blocks[RBW], e.getMessage());
}
try {
dataSet.append(blocks[RWR], blocks[RWR].getGenerationStamp()+1,
blocks[RBW].getNumBytes());
Assert.fail("Should not have appended to an RWR replica" + blocks[RWR]);
} catch (ReplicaNotFoundException e) {
Assert.assertEquals(ReplicaNotFoundException.UNFINALIZED_REPLICA +
blocks[RWR], e.getMessage());
}
try {
dataSet.append(blocks[RUR], blocks[RUR].getGenerationStamp()+1,
blocks[RUR].getNumBytes());
Assert.fail("Should not have appended to an RUR replica" + blocks[RUR]);
} catch (ReplicaNotFoundException e) {
Assert.assertEquals(ReplicaNotFoundException.UNFINALIZED_REPLICA +
blocks[RUR], e.getMessage());
}
try {
dataSet.append(blocks[NON_EXISTENT],
blocks[NON_EXISTENT].getGenerationStamp(),
blocks[NON_EXISTENT].getNumBytes());
Assert.fail("Should not have appended to a non-existent replica " +
blocks[NON_EXISTENT]);
} catch (ReplicaNotFoundException e) {
Assert.assertEquals(ReplicaNotFoundException.NON_EXISTENT_REPLICA +
blocks[NON_EXISTENT], e.getMessage());
}
newGS = blocks[FINALIZED].getGenerationStamp()+1;
dataSet.recoverAppend(blocks[FINALIZED], newGS,
blocks[FINALIZED].getNumBytes()); // successful
blocks[FINALIZED].setGenerationStamp(newGS);
try {
dataSet.recoverAppend(blocks[TEMPORARY], blocks[TEMPORARY].getGenerationStamp()+1,
blocks[TEMPORARY].getNumBytes());
Assert.fail("Should not have appended to a temporary replica "
+ blocks[TEMPORARY]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
newGS = blocks[RBW].getGenerationStamp()+1;
dataSet.recoverAppend(blocks[RBW], newGS, blocks[RBW].getNumBytes());
blocks[RBW].setGenerationStamp(newGS);
try {
dataSet.recoverAppend(blocks[RWR], blocks[RWR].getGenerationStamp()+1,
blocks[RBW].getNumBytes());
Assert.fail("Should not have appended to an RWR replica" + blocks[RWR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
try {
dataSet.recoverAppend(blocks[RUR], blocks[RUR].getGenerationStamp()+1,
blocks[RUR].getNumBytes());
Assert.fail("Should not have appended to an RUR replica" + blocks[RUR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
try {
dataSet.recoverAppend(blocks[NON_EXISTENT],
blocks[NON_EXISTENT].getGenerationStamp(),
blocks[NON_EXISTENT].getNumBytes());
Assert.fail("Should not have appended to a non-existent replica " +
blocks[NON_EXISTENT]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_EXISTENT_REPLICA));
}
}
private void testClose(FSDataset dataSet, ExtendedBlock [] blocks) throws IOException {
long newGS = blocks[FINALIZED].getGenerationStamp()+1;
dataSet.recoverClose(blocks[FINALIZED], newGS,
blocks[FINALIZED].getNumBytes()); // successful
blocks[FINALIZED].setGenerationStamp(newGS);
try {
dataSet.recoverClose(blocks[TEMPORARY], blocks[TEMPORARY].getGenerationStamp()+1,
blocks[TEMPORARY].getNumBytes());
Assert.fail("Should not have recovered close a temporary replica "
+ blocks[TEMPORARY]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
newGS = blocks[RBW].getGenerationStamp()+1;
dataSet.recoverClose(blocks[RBW], newGS, blocks[RBW].getNumBytes());
blocks[RBW].setGenerationStamp(newGS);
try {
dataSet.recoverClose(blocks[RWR], blocks[RWR].getGenerationStamp()+1,
blocks[RBW].getNumBytes());
Assert.fail("Should not have recovered close an RWR replica" + blocks[RWR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
try {
dataSet.recoverClose(blocks[RUR], blocks[RUR].getGenerationStamp()+1,
blocks[RUR].getNumBytes());
Assert.fail("Should not have recovered close an RUR replica" + blocks[RUR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.UNFINALIZED_AND_NONRBW_REPLICA));
}
try {
dataSet.recoverClose(blocks[NON_EXISTENT],
blocks[NON_EXISTENT].getGenerationStamp(),
blocks[NON_EXISTENT].getNumBytes());
Assert.fail("Should not have recovered close a non-existent replica " +
blocks[NON_EXISTENT]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_EXISTENT_REPLICA));
}
}
private void testWriteToRbw(FSDataset dataSet, ExtendedBlock[] blocks) throws IOException {
try {
dataSet.recoverRbw(blocks[FINALIZED],
blocks[FINALIZED].getGenerationStamp()+1,
0L, blocks[FINALIZED].getNumBytes());
Assert.fail("Should not have recovered a finalized replica " +
blocks[FINALIZED]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_RBW_REPLICA));
}
try {
dataSet.createRbw(blocks[FINALIZED]);
Assert.fail("Should not have created a replica that's already " +
"finalized " + blocks[FINALIZED]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.recoverRbw(blocks[TEMPORARY],
blocks[TEMPORARY].getGenerationStamp()+1,
0L, blocks[TEMPORARY].getNumBytes());
Assert.fail("Should not have recovered a temporary replica " +
blocks[TEMPORARY]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_RBW_REPLICA));
}
try {
dataSet.createRbw(blocks[TEMPORARY]);
Assert.fail("Should not have created a replica that had created as " +
"temporary " + blocks[TEMPORARY]);
} catch (ReplicaAlreadyExistsException e) {
}
dataSet.recoverRbw(blocks[RBW], blocks[RBW].getGenerationStamp()+1,
0L, blocks[RBW].getNumBytes()); // expect to be successful
try {
dataSet.createRbw(blocks[RBW]);
Assert.fail("Should not have created a replica that had created as RBW " +
blocks[RBW]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.recoverRbw(blocks[RWR], blocks[RWR].getGenerationStamp()+1,
0L, blocks[RWR].getNumBytes());
Assert.fail("Should not have recovered a RWR replica " + blocks[RWR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_RBW_REPLICA));
}
try {
dataSet.createRbw(blocks[RWR]);
Assert.fail("Should not have created a replica that was waiting to be " +
"recovered " + blocks[RWR]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.recoverRbw(blocks[RUR], blocks[RUR].getGenerationStamp()+1,
0L, blocks[RUR].getNumBytes());
Assert.fail("Should not have recovered a RUR replica " + blocks[RUR]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(e.getMessage().startsWith(
ReplicaNotFoundException.NON_RBW_REPLICA));
}
try {
dataSet.createRbw(blocks[RUR]);
Assert.fail("Should not have created a replica that was under recovery " +
blocks[RUR]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.recoverRbw(blocks[NON_EXISTENT],
blocks[NON_EXISTENT].getGenerationStamp()+1,
0L, blocks[NON_EXISTENT].getNumBytes());
Assert.fail("Cannot recover a non-existent replica " +
blocks[NON_EXISTENT]);
} catch (ReplicaNotFoundException e) {
Assert.assertTrue(
e.getMessage().contains(ReplicaNotFoundException.NON_EXISTENT_REPLICA));
}
dataSet.createRbw(blocks[NON_EXISTENT]);
}
private void testWriteToTemporary(FSDataset dataSet, ExtendedBlock[] blocks) throws IOException {
try {
dataSet.createTemporary(blocks[FINALIZED]);
Assert.fail("Should not have created a temporary replica that was " +
"finalized " + blocks[FINALIZED]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.createTemporary(blocks[TEMPORARY]);
Assert.fail("Should not have created a replica that had created as" +
"temporary " + blocks[TEMPORARY]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.createTemporary(blocks[RBW]);
Assert.fail("Should not have created a replica that had created as RBW " +
blocks[RBW]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.createTemporary(blocks[RWR]);
Assert.fail("Should not have created a replica that was waiting to be " +
"recovered " + blocks[RWR]);
} catch (ReplicaAlreadyExistsException e) {
}
try {
dataSet.createTemporary(blocks[RUR]);
Assert.fail("Should not have created a replica that was under recovery " +
blocks[RUR]);
} catch (ReplicaAlreadyExistsException e) {
}
dataSet.createTemporary(blocks[NON_EXISTENT]);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.FSInputChecker;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.net.Peer;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil;
import org.apache.hadoop.hdfs.protocol.datatransfer.PacketHeader;
import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ReadOpChecksumInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
import org.apache.hadoop.hdfs.protocolPB.PBHelper;
import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.DataChecksum;
/**
* @deprecated this is an old implementation that is being left around
* in case any issues spring up with the new {@link RemoteBlockReader2} implementation.
* It will be removed in the next release.
*/
@InterfaceAudience.Private
@Deprecated
public class RemoteBlockReader extends FSInputChecker implements BlockReader {
private final Peer peer;
private final DatanodeID datanodeID;
private final DataInputStream in;
private DataChecksum checksum;
/** offset in block of the last chunk received */
private long lastChunkOffset = -1;
private long lastChunkLen = -1;
private long lastSeqNo = -1;
/** offset in block where reader wants to actually read */
private long startOffset;
/** offset in block of of first chunk - may be less than startOffset
if startOffset is not chunk-aligned */
private final long firstChunkOffset;
private final int bytesPerChecksum;
private final int checksumSize;
/**
* The total number of bytes we need to transfer from the DN.
* This is the amount that the user has requested plus some padding
* at the beginning so that the read can begin on a chunk boundary.
*/
private final long bytesNeededToFinish;
/**
* True if we are reading from a local DataNode.
*/
private final boolean isLocal;
private boolean eos = false;
private boolean sentStatusCode = false;
byte[] skipBuf = null;
ByteBuffer checksumBytes = null;
/** Amount of unread data in the current received packet */
int dataLeft = 0;
private final PeerCache peerCache;
/* FSInputChecker interface */
/* same interface as inputStream java.io.InputStream#read()
* used by DFSInputStream#read()
* This violates one rule when there is a checksum error:
* "Read should not modify user buffer before successful read"
* because it first reads the data to user buffer and then checks
* the checksum.
*/
@Override
public synchronized int read(byte[] buf, int off, int len)
throws IOException {
// This has to be set here, *before* the skip, since we can
// hit EOS during the skip, in the case that our entire read
// is smaller than the checksum chunk.
boolean eosBefore = eos;
//for the first read, skip the extra bytes at the front.
if (lastChunkLen < 0 && startOffset > firstChunkOffset && len > 0) {
// Skip these bytes. But don't call this.skip()!
int toSkip = (int)(startOffset - firstChunkOffset);
if ( skipBuf == null ) {
skipBuf = new byte[bytesPerChecksum];
}
if ( super.read(skipBuf, 0, toSkip) != toSkip ) {
// should never happen
throw new IOException("Could not skip required number of bytes");
}
}
int nRead = super.read(buf, off, len);
// if eos was set in the previous read, send a status code to the DN
if (eos && !eosBefore && nRead >= 0) {
if (needChecksum()) {
sendReadResult(peer, Status.CHECKSUM_OK);
} else {
sendReadResult(peer, Status.SUCCESS);
}
}
return nRead;
}
@Override
public synchronized long skip(long n) throws IOException {
/* How can we make sure we don't throw a ChecksumException, at least
* in majority of the cases?. This one throws. */
if ( skipBuf == null ) {
skipBuf = new byte[bytesPerChecksum];
}
long nSkipped = 0;
while ( nSkipped < n ) {
int toSkip = (int)Math.min(n-nSkipped, skipBuf.length);
int ret = read(skipBuf, 0, toSkip);
if ( ret <= 0 ) {
return nSkipped;
}
nSkipped += ret;
}
return nSkipped;
}
@Override
public int read() throws IOException {
throw new IOException("read() is not expected to be invoked. " +
"Use read(buf, off, len) instead.");
}
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
/* Checksum errors are handled outside the BlockReader.
* DFSInputStream does not always call 'seekToNewSource'. In the
* case of pread(), it just tries a different replica without seeking.
*/
return false;
}
@Override
public void seek(long pos) throws IOException {
throw new IOException("Seek() is not supported in BlockInputChecker");
}
@Override
protected long getChunkPosition(long pos) {
throw new RuntimeException("getChunkPosition() is not supported, " +
"since seek is not required");
}
/**
* Makes sure that checksumBytes has enough capacity
* and limit is set to the number of checksum bytes needed
* to be read.
*/
private void adjustChecksumBytes(int dataLen) {
int requiredSize =
((dataLen + bytesPerChecksum - 1)/bytesPerChecksum)*checksumSize;
if (checksumBytes == null || requiredSize > checksumBytes.capacity()) {
checksumBytes = ByteBuffer.wrap(new byte[requiredSize]);
} else {
checksumBytes.clear();
}
checksumBytes.limit(requiredSize);
}
@Override
protected synchronized int readChunk(long pos, byte[] buf, int offset,
int len, byte[] checksumBuf)
throws IOException {
// Read one chunk.
if (eos) {
// Already hit EOF
return -1;
}
// Read one DATA_CHUNK.
long chunkOffset = lastChunkOffset;
if ( lastChunkLen > 0 ) {
chunkOffset += lastChunkLen;
}
// pos is relative to the start of the first chunk of the read.
// chunkOffset is relative to the start of the block.
// This makes sure that the read passed from FSInputChecker is the
// for the same chunk we expect to be reading from the DN.
if ( (pos + firstChunkOffset) != chunkOffset ) {
throw new IOException("Mismatch in pos : " + pos + " + " +
firstChunkOffset + " != " + chunkOffset);
}
// Read next packet if the previous packet has been read completely.
if (dataLeft <= 0) {
//Read packet headers.
PacketHeader header = new PacketHeader();
header.readFields(in);
if (LOG.isDebugEnabled()) {
LOG.debug("DFSClient readChunk got header " + header);
}
// Sanity check the lengths
if (!header.sanityCheck(lastSeqNo)) {
throw new IOException("BlockReader: error in packet header " +
header);
}
lastSeqNo = header.getSeqno();
dataLeft = header.getDataLen();
adjustChecksumBytes(header.getDataLen());
if (header.getDataLen() > 0) {
IOUtils.readFully(in, checksumBytes.array(), 0,
checksumBytes.limit());
}
}
// Sanity checks
assert len >= bytesPerChecksum;
assert checksum != null;
assert checksumSize == 0 || (checksumBuf.length % checksumSize == 0);
int checksumsToRead, bytesToRead;
if (checksumSize > 0) {
// How many chunks left in our packet - this is a ceiling
// since we may have a partial chunk at the end of the file
int chunksLeft = (dataLeft - 1) / bytesPerChecksum + 1;
// How many chunks we can fit in databuffer
// - note this is a floor since we always read full chunks
int chunksCanFit = Math.min(len / bytesPerChecksum,
checksumBuf.length / checksumSize);
// How many chunks should we read
checksumsToRead = Math.min(chunksLeft, chunksCanFit);
// How many bytes should we actually read
bytesToRead = Math.min(
checksumsToRead * bytesPerChecksum, // full chunks
dataLeft); // in case we have a partial
} else {
// no checksum
bytesToRead = Math.min(dataLeft, len);
checksumsToRead = 0;
}
if ( bytesToRead > 0 ) {
// Assert we have enough space
assert bytesToRead <= len;
assert checksumBytes.remaining() >= checksumSize * checksumsToRead;
assert checksumBuf.length >= checksumSize * checksumsToRead;
IOUtils.readFully(in, buf, offset, bytesToRead);
checksumBytes.get(checksumBuf, 0, checksumSize * checksumsToRead);
}
dataLeft -= bytesToRead;
assert dataLeft >= 0;
lastChunkOffset = chunkOffset;
lastChunkLen = bytesToRead;
// If there's no data left in the current packet after satisfying
// this read, and we have satisfied the client read, we expect
// an empty packet header from the DN to signify this.
// Note that pos + bytesToRead may in fact be greater since the
// DN finishes off the entire last chunk.
if (dataLeft == 0 &&
pos + bytesToRead >= bytesNeededToFinish) {
// Read header
PacketHeader hdr = new PacketHeader();
hdr.readFields(in);
if (!hdr.isLastPacketInBlock() ||
hdr.getDataLen() != 0) {
throw new IOException("Expected empty end-of-read packet! Header: " +
hdr);
}
eos = true;
}
if ( bytesToRead == 0 ) {
return -1;
}
return bytesToRead;
}
private RemoteBlockReader(String file, String bpid, long blockId,
DataInputStream in, DataChecksum checksum, boolean verifyChecksum,
long startOffset, long firstChunkOffset, long bytesToRead, Peer peer,
DatanodeID datanodeID, PeerCache peerCache) {
// Path is used only for printing block and file information in debug
super(new Path("/blk_" + blockId + ":" + bpid + ":of:"+ file)/*too non path-like?*/,
1, verifyChecksum,
checksum.getChecksumSize() > 0? checksum : null,
checksum.getBytesPerChecksum(),
checksum.getChecksumSize());
this.isLocal = DFSClient.isLocalAddress(NetUtils.
createSocketAddr(datanodeID.getXferAddr()));
this.peer = peer;
this.datanodeID = datanodeID;
this.in = in;
this.checksum = checksum;
this.startOffset = Math.max( startOffset, 0 );
// The total number of bytes that we need to transfer from the DN is
// the amount that the user wants (bytesToRead), plus the padding at
// the beginning in order to chunk-align. Note that the DN may elect
// to send more than this amount if the read starts/ends mid-chunk.
this.bytesNeededToFinish = bytesToRead + (startOffset - firstChunkOffset);
this.firstChunkOffset = firstChunkOffset;
lastChunkOffset = firstChunkOffset;
lastChunkLen = -1;
bytesPerChecksum = this.checksum.getBytesPerChecksum();
checksumSize = this.checksum.getChecksumSize();
this.peerCache = peerCache;
}
/**
* Create a new BlockReader specifically to satisfy a read.
* This method also sends the OP_READ_BLOCK request.
*
* @param sock An established Socket to the DN. The BlockReader will not close it normally
* @param file File location
* @param block The block object
* @param blockToken The block token for security
* @param startOffset The read offset, relative to block head
* @param len The number of bytes to read
* @param bufferSize The IO buffer size (not the client buffer size)
* @param verifyChecksum Whether to verify checksum
* @param clientName Client name
* @return New BlockReader instance, or null on error.
*/
public static RemoteBlockReader newBlockReader(String file,
ExtendedBlock block,
Token<BlockTokenIdentifier> blockToken,
long startOffset, long len,
int bufferSize, boolean verifyChecksum,
String clientName, Peer peer,
DatanodeID datanodeID,
PeerCache peerCache,
CachingStrategy cachingStrategy)
throws IOException {
// in and out will be closed when sock is closed (by the caller)
final DataOutputStream out =
new DataOutputStream(new BufferedOutputStream(peer.getOutputStream()));
new Sender(out).readBlock(block, blockToken, clientName, startOffset, len,
verifyChecksum, cachingStrategy);
//
// Get bytes in block, set streams
//
DataInputStream in = new DataInputStream(
new BufferedInputStream(peer.getInputStream(), bufferSize));
BlockOpResponseProto status = BlockOpResponseProto.parseFrom(
PBHelper.vintPrefixed(in));
RemoteBlockReader2.checkSuccess(status, peer, block, file);
ReadOpChecksumInfoProto checksumInfo =
status.getReadOpChecksumInfo();
DataChecksum checksum = DataTransferProtoUtil.fromProto(
checksumInfo.getChecksum());
//Warning when we get CHECKSUM_NULL?
// Read the first chunk offset.
long firstChunkOffset = checksumInfo.getChunkOffset();
if ( firstChunkOffset < 0 || firstChunkOffset > startOffset ||
firstChunkOffset <= (startOffset - checksum.getBytesPerChecksum())) {
throw new IOException("BlockReader: error in first chunk offset (" +
firstChunkOffset + ") startOffset is " +
startOffset + " for file " + file);
}
return new RemoteBlockReader(file, block.getBlockPoolId(), block.getBlockId(),
in, checksum, verifyChecksum, startOffset, firstChunkOffset, len,
peer, datanodeID, peerCache);
}
@Override
public synchronized void close() throws IOException {
startOffset = -1;
checksum = null;
if (peerCache != null & sentStatusCode) {
peerCache.put(datanodeID, peer);
} else {
peer.close();
}
// in will be closed when its Socket is closed.
}
@Override
public void readFully(byte[] buf, int readOffset, int amtToRead)
throws IOException {
IOUtils.readFully(this, buf, readOffset, amtToRead);
}
@Override
public int readAll(byte[] buf, int offset, int len) throws IOException {
return readFully(this, buf, offset, len);
}
/**
* When the reader reaches end of the read, it sends a status response
* (e.g. CHECKSUM_OK) to the DN. Failure to do so could lead to the DN
* closing our connection (which we will re-open), but won't affect
* data correctness.
*/
void sendReadResult(Peer peer, Status statusCode) {
assert !sentStatusCode : "already sent status code to " + peer;
try {
RemoteBlockReader2.writeReadResult(peer.getOutputStream(), statusCode);
sentStatusCode = true;
} catch (IOException e) {
// It's ok not to be able to send this. But something is probably wrong.
LOG.info("Could not send read status (" + statusCode + ") to datanode " +
peer.getRemoteAddressString() + ": " + e.getMessage());
}
}
@Override
public int read(ByteBuffer buf) throws IOException {
throw new UnsupportedOperationException("readDirect unsupported in RemoteBlockReader");
}
@Override
public int available() throws IOException {
// An optimistic estimate of how much data is available
// to us without doing network I/O.
return DFSClient.TCP_WINDOW_SIZE;
}
@Override
public boolean isLocal() {
return isLocal;
}
@Override
public boolean isShortCircuit() {
return false;
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.codec.http2;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
import static io.netty.handler.codec.http2.Http2Exception.connectionError;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import java.util.ArrayDeque;
/**
* Default implementation of {@link Http2ConnectionEncoder}.
*/
public class DefaultHttp2ConnectionEncoder implements Http2ConnectionEncoder {
private final Http2FrameWriter frameWriter;
private final Http2Connection connection;
private final Http2LifecycleManager lifecycleManager;
// We prefer ArrayDeque to LinkedList because later will produce more GC.
// This initial capacity is plenty for SETTINGS traffic.
private final ArrayDeque<Http2Settings> outstandingLocalSettingsQueue = new ArrayDeque<Http2Settings>(4);
/**
* Builder for new instances of {@link DefaultHttp2ConnectionEncoder}.
*/
public static class Builder implements Http2ConnectionEncoder.Builder {
protected Http2FrameWriter frameWriter;
protected Http2Connection connection;
protected Http2LifecycleManager lifecycleManager;
@Override
public Builder connection(
Http2Connection connection) {
this.connection = connection;
return this;
}
@Override
public Builder lifecycleManager(
Http2LifecycleManager lifecycleManager) {
this.lifecycleManager = lifecycleManager;
return this;
}
@Override
public Http2LifecycleManager lifecycleManager() {
return lifecycleManager;
}
@Override
public Builder frameWriter(Http2FrameWriter frameWriter) {
this.frameWriter = frameWriter;
return this;
}
@Override
public Http2ConnectionEncoder build() {
return new DefaultHttp2ConnectionEncoder(this);
}
}
public static Builder newBuilder() {
return new Builder();
}
protected DefaultHttp2ConnectionEncoder(Builder builder) {
connection = checkNotNull(builder.connection, "connection");
frameWriter = checkNotNull(builder.frameWriter, "frameWriter");
lifecycleManager = checkNotNull(builder.lifecycleManager, "lifecycleManager");
if (connection.remote().flowController() == null) {
connection.remote().flowController(new DefaultHttp2RemoteFlowController(connection, frameWriter));
}
}
@Override
public Http2FrameWriter frameWriter() {
return frameWriter;
}
@Override
public Http2Connection connection() {
return connection;
}
@Override
public final Http2RemoteFlowController flowController() {
return connection().remote().flowController();
}
@Override
public void remoteSettings(Http2Settings settings) throws Http2Exception {
Boolean pushEnabled = settings.pushEnabled();
Http2FrameWriter.Configuration config = configuration();
Http2HeaderTable outboundHeaderTable = config.headerTable();
Http2FrameSizePolicy outboundFrameSizePolicy = config.frameSizePolicy();
if (pushEnabled != null) {
if (!connection.isServer()) {
throw connectionError(PROTOCOL_ERROR, "Client received SETTINGS frame with ENABLE_PUSH specified");
}
connection.remote().allowPushTo(pushEnabled);
}
Long maxConcurrentStreams = settings.maxConcurrentStreams();
if (maxConcurrentStreams != null) {
connection.local().maxStreams((int) Math.min(maxConcurrentStreams, Integer.MAX_VALUE));
}
Long headerTableSize = settings.headerTableSize();
if (headerTableSize != null) {
outboundHeaderTable.maxHeaderTableSize((int) Math.min(headerTableSize, Integer.MAX_VALUE));
}
Integer maxHeaderListSize = settings.maxHeaderListSize();
if (maxHeaderListSize != null) {
outboundHeaderTable.maxHeaderListSize(maxHeaderListSize);
}
Integer maxFrameSize = settings.maxFrameSize();
if (maxFrameSize != null) {
outboundFrameSizePolicy.maxFrameSize(maxFrameSize);
}
Integer initialWindowSize = settings.initialWindowSize();
if (initialWindowSize != null) {
flowController().initialWindowSize(initialWindowSize);
}
}
@Override
public ChannelFuture writeData(final ChannelHandlerContext ctx, final int streamId, ByteBuf data, int padding,
final boolean endOfStream, ChannelPromise promise) {
Http2Stream stream;
try {
if (connection.isGoAway()) {
throw new IllegalStateException("Sending data after connection going away.");
}
stream = connection.requireStream(streamId);
if (stream.isResetSent()) {
throw new IllegalStateException("Sending data after sending RST_STREAM.");
}
if (stream.isEndOfStreamSent()) {
throw new IllegalStateException("Sending data after sending END_STREAM.");
}
// Verify that the stream is in the appropriate state for sending DATA frames.
switch (stream.state()) {
case OPEN:
case HALF_CLOSED_REMOTE:
// Allowed sending DATA frames in these states.
break;
default:
throw new IllegalStateException(String.format(
"Stream %d in unexpected state: %s", stream.id(), stream.state()));
}
if (endOfStream) {
// Indicate that we have sent END_STREAM.
stream.endOfStreamSent();
}
} catch (Throwable e) {
data.release();
return promise.setFailure(e);
}
// Hand control of the frame to the flow controller.
ChannelFuture future =
flowController().sendFlowControlledFrame(ctx, stream, data, padding, endOfStream, promise);
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
// The write failed, handle the error.
lifecycleManager.onException(ctx, future.cause());
} else if (endOfStream) {
// Close the local side of the stream if this is the last frame
Http2Stream stream = connection.stream(streamId);
lifecycleManager.closeLocalSide(stream, ctx.newPromise());
}
}
});
return future;
}
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
boolean endStream, ChannelPromise promise) {
return writeHeaders(ctx, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false, padding, endStream, promise);
}
@Override
public ChannelFuture writeHeaders(final ChannelHandlerContext ctx, final int streamId,
final Http2Headers headers, final int streamDependency, final short weight,
final boolean exclusive, final int padding, final boolean endOfStream,
final ChannelPromise promise) {
Http2Stream stream = connection.stream(streamId);
ChannelFuture lastDataWrite = stream != null ? flowController().lastFlowControlledFrameSent(stream) : null;
try {
if (connection.isGoAway()) {
throw connectionError(PROTOCOL_ERROR, "Sending headers after connection going away.");
}
if (stream == null) {
stream = connection.createLocalStream(streamId).open(endOfStream);
} else {
if (stream.isResetSent()) {
throw new IllegalStateException("Sending headers after sending RST_STREAM.");
}
if (stream.isEndOfStreamSent()) {
throw new IllegalStateException("Sending headers after sending END_STREAM.");
}
// An existing stream...
switch (stream.state()) {
case RESERVED_LOCAL:
case IDLE:
stream.open(endOfStream);
break;
case OPEN:
case HALF_CLOSED_REMOTE:
// Allowed sending headers in these states.
break;
default:
throw new IllegalStateException(String.format(
"Stream %d in unexpected state: %s", stream.id(), stream.state()));
}
}
if (lastDataWrite != null && !endOfStream) {
throw new IllegalStateException(
"Sending non-trailing headers after data has been sent for stream: "
+ streamId);
}
} catch (Http2NoMoreStreamIdsException e) {
lifecycleManager.onException(ctx, e);
return promise.setFailure(e);
} catch (Throwable e) {
return promise.setFailure(e);
}
if (lastDataWrite == null) {
// No previous DATA frames to keep in sync with, just send it now.
return writeHeaders(ctx, stream, headers, streamDependency, weight, exclusive, padding,
endOfStream, promise);
}
// There were previous DATA frames sent. We need to send the HEADERS only after the most
// recent DATA frame to keep them in sync...
// Only write the HEADERS frame after the previous DATA frame has been written.
final Http2Stream theStream = stream;
lastDataWrite.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
// The DATA write failed, also fail this write.
promise.setFailure(future.cause());
return;
}
// Perform the write.
writeHeaders(ctx, theStream, headers, streamDependency, weight, exclusive, padding,
endOfStream, promise);
}
});
return promise;
}
/**
* Writes the given {@link Http2Headers} to the remote endpoint and updates stream state if appropriate.
*/
private ChannelFuture writeHeaders(ChannelHandlerContext ctx, Http2Stream stream,
Http2Headers headers, int streamDependency, short weight, boolean exclusive,
int padding, boolean endOfStream, ChannelPromise promise) {
ChannelFuture future =
frameWriter.writeHeaders(ctx, stream.id(), headers, streamDependency, weight,
exclusive, padding, endOfStream, promise);
ctx.flush();
// If the headers are the end of the stream, close it now.
if (endOfStream) {
stream.endOfStreamSent();
lifecycleManager.closeLocalSide(stream, promise);
}
return future;
}
@Override
public ChannelFuture writePriority(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
boolean exclusive, ChannelPromise promise) {
try {
if (connection.isGoAway()) {
throw connectionError(PROTOCOL_ERROR, "Sending priority after connection going away.");
}
// Update the priority on this stream.
Http2Stream stream = connection.stream(streamId);
if (stream == null) {
stream = connection.createLocalStream(streamId);
}
stream.setPriority(streamDependency, weight, exclusive);
} catch (Throwable e) {
return promise.setFailure(e);
}
ChannelFuture future = frameWriter.writePriority(ctx, streamId, streamDependency, weight, exclusive, promise);
ctx.flush();
return future;
}
@Override
public ChannelFuture writeRstStream(ChannelHandlerContext ctx, int streamId, long errorCode,
ChannelPromise promise) {
// Delegate to the lifecycle manager for proper updating of connection state.
return lifecycleManager.writeRstStream(ctx, streamId, errorCode, promise);
}
/**
* Writes a RST_STREAM frame to the remote endpoint.
* @param ctx the context to use for writing.
* @param streamId the stream for which to send the frame.
* @param errorCode the error code indicating the nature of the failure.
* @param promise the promise for the write.
* @param writeIfNoStream
* <ul>
* <li>{@code true} will force a write of a RST_STREAM even if the stream object does not exist locally.</li>
* <li>{@code false} will only send a RST_STREAM only if the stream is known about locally</li>
* </ul>
* @return the future for the write.
*/
public ChannelFuture writeRstStream(ChannelHandlerContext ctx, int streamId, long errorCode,
ChannelPromise promise, boolean writeIfNoStream) {
Http2Stream stream = connection.stream(streamId);
if (stream == null && !writeIfNoStream) {
// The stream may already have been closed ... ignore.
promise.setSuccess();
return promise;
}
ChannelFuture future = frameWriter.writeRstStream(ctx, streamId, errorCode, promise);
ctx.flush();
if (stream != null) {
stream.resetSent();
lifecycleManager.closeStream(stream, promise);
}
return future;
}
@Override
public ChannelFuture writeSettings(ChannelHandlerContext ctx, Http2Settings settings,
ChannelPromise promise) {
outstandingLocalSettingsQueue.add(settings);
try {
if (connection.isGoAway()) {
throw connectionError(PROTOCOL_ERROR, "Sending settings after connection going away.");
}
Boolean pushEnabled = settings.pushEnabled();
if (pushEnabled != null && connection.isServer()) {
throw connectionError(PROTOCOL_ERROR, "Server sending SETTINGS frame with ENABLE_PUSH specified");
}
} catch (Throwable e) {
return promise.setFailure(e);
}
ChannelFuture future = frameWriter.writeSettings(ctx, settings, promise);
ctx.flush();
return future;
}
@Override
public ChannelFuture writeSettingsAck(ChannelHandlerContext ctx, ChannelPromise promise) {
ChannelFuture future = frameWriter.writeSettingsAck(ctx, promise);
ctx.flush();
return future;
}
@Override
public ChannelFuture writePing(ChannelHandlerContext ctx, boolean ack, ByteBuf data,
ChannelPromise promise) {
if (connection.isGoAway()) {
data.release();
return promise.setFailure(connectionError(PROTOCOL_ERROR, "Sending ping after connection going away."));
}
ChannelFuture future = frameWriter.writePing(ctx, ack, data, promise);
ctx.flush();
return future;
}
@Override
public ChannelFuture writePushPromise(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
Http2Headers headers, int padding, ChannelPromise promise) {
try {
if (connection.isGoAway()) {
throw connectionError(PROTOCOL_ERROR, "Sending push promise after connection going away.");
}
// Reserve the promised stream.
Http2Stream stream = connection.requireStream(streamId);
connection.local().reservePushStream(promisedStreamId, stream);
} catch (Throwable e) {
return promise.setFailure(e);
}
ChannelFuture future = frameWriter.writePushPromise(ctx, streamId, promisedStreamId, headers, padding, promise);
ctx.flush();
return future;
}
@Override
public ChannelFuture writeGoAway(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData,
ChannelPromise promise) {
return lifecycleManager.writeGoAway(ctx, lastStreamId, errorCode, debugData, promise);
}
@Override
public ChannelFuture writeWindowUpdate(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement,
ChannelPromise promise) {
return promise.setFailure(new UnsupportedOperationException("Use the Http2[Inbound|Outbound]FlowController" +
" objects to control window sizes"));
}
@Override
public ChannelFuture writeFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
ByteBuf payload, ChannelPromise promise) {
return frameWriter.writeFrame(ctx, frameType, streamId, flags, payload, promise);
}
@Override
public void close() {
frameWriter.close();
}
@Override
public Http2Settings pollSentSettings() {
return outstandingLocalSettingsQueue.poll();
}
@Override
public Configuration configuration() {
return frameWriter.configuration();
}
}
| |
package com.compomics.rover.gui.multiwizard;
import org.apache.log4j.Logger;
import com.compomics.rover.general.interfaces.WizardPanel;
import com.compomics.rover.general.quantitation.MergedRatioType;
import com.compomics.rover.gui.multiwizard.WizardFrameHolder;
import javax.swing.*;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: Niklaas
* Date: 11-Dec-2009
* Time: 10:33:05
* To change this template use File | Settings | File Templates.
*/
public class MatchRatiosPanel implements WizardPanel {
// Class specific log4j logger for MatchRatiosPanel instances.
private static Logger logger = Logger.getLogger(MatchRatiosPanel.class);
private WizardFrameHolder iParent;
private JPanel jpanContent;
private JList list1;
private JLabel lblSet;
private JLabel lblRatioLabelCount;
private JLabel lblLabel;
private JButton linkToSelectedMergedButton;
private JButton linkToANewlyButton;
private JTextField newlyCreatedRatioTypeTextField;
private JCheckBox invertRatioCheckBox;
private Vector<MergedRatioType> iRatioTypes = new Vector<MergedRatioType>();
private Vector<String[]> iCollectionsRatios = new Vector<String[]>();
private Vector<String[]> iCollectionsComponents = new Vector<String[]>();
private int iIndexCounter = 0;
private int iRatioTypeCounter = 0;
public void nextRatio() {
if (iRatioTypeCounter < iCollectionsRatios.get(iIndexCounter).length - 1) {
//we must select the next ratio type
iRatioTypeCounter = iRatioTypeCounter + 1;
lblRatioLabelCount.setText("Ratio type " + (iRatioTypeCounter + 1) + "/" + iCollectionsRatios.get(iIndexCounter).length);
lblLabel.setText(iCollectionsRatios.get(iIndexCounter)[iRatioTypeCounter]);
invertRatioCheckBox.setSelected(false);
} else {
//we must select the next index
iIndexCounter = iIndexCounter + 1;
if (iIndexCounter == iCollectionsRatios.size()) {
//no more data sets
linkToANewlyButton.setVisible(false);
linkToSelectedMergedButton.setVisible(false);
newlyCreatedRatioTypeTextField.setVisible(false);
invertRatioCheckBox.setVisible(false);
iParent.setNextButtonEnabled(true);
lblSet.setText("All set");
lblLabel.setText("Click next");
lblRatioLabelCount.setText("");
iParent.clickNextButton();
} else {
linkToANewlyButton.setEnabled(false);
linkToSelectedMergedButton.setEnabled(true);
//we will show the next data set
iRatioTypeCounter = 0;
lblSet.setText(iParent.getTitle(iIndexCounter) + " : set " + (iIndexCounter + 1) + "/" + iCollectionsRatios.size());
lblRatioLabelCount.setText("Ratio type " + (iRatioTypeCounter + 1) + "/" + iCollectionsRatios.get(iIndexCounter).length);
lblLabel.setText(iCollectionsRatios.get(iIndexCounter)[iRatioTypeCounter]);
}
}
}
public MatchRatiosPanel(WizardFrameHolder aParent) {
this.iParent = aParent;
$$$setupUI$$$();
linkToANewlyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String lName = newlyCreatedRatioTypeTextField.getText();
if (lName.equalsIgnoreCase("Newly created ratio type name")) {
//the given name was the default name
JOptionPane.showMessageDialog(iParent, "Set a valid name for the newly created ratio type!", "ERROR", JOptionPane.WARNING_MESSAGE);
newlyCreatedRatioTypeTextField.setText("");
newlyCreatedRatioTypeTextField.requestFocus();
} else {
//check if the name does not exists
boolean lAlreadyUsed = false;
for (int i = 0; i < iRatioTypes.size(); i++) {
if (iRatioTypes.get(i).toString().equalsIgnoreCase(lName)) {
lAlreadyUsed = true;
}
}
if (lAlreadyUsed) {
JOptionPane.showMessageDialog(iParent, "Set a valid name for the newly created ratio type!\n" + lName + " was already used.", "ERROR", JOptionPane.WARNING_MESSAGE);
newlyCreatedRatioTypeTextField.setText("");
newlyCreatedRatioTypeTextField.requestFocus();
} else {
MergedRatioType lMerged = new MergedRatioType(lName);
if (invertRatioCheckBox.isSelected()) {
lMerged.addRatioType(iIndexCounter, iCollectionsRatios.get(iIndexCounter)[iRatioTypeCounter], true);
} else {
lMerged.addRatioType(iIndexCounter, lblLabel.getText(), false);
}
iRatioTypes.add(lMerged);
list1.updateUI();
nextRatio();
newlyCreatedRatioTypeTextField.setText("");
newlyCreatedRatioTypeTextField.requestFocus();
}
}
}
});
linkToSelectedMergedButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MergedRatioType lMerged = (MergedRatioType) list1.getSelectedValue();
if (lMerged != null) {
if (invertRatioCheckBox.isSelected()) {
lMerged.addRatioType(iIndexCounter, iCollectionsRatios.get(iIndexCounter)[iRatioTypeCounter], true);
} else {
lMerged.addRatioType(iIndexCounter, lblLabel.getText(), false);
}
nextRatio();
} else {
JOptionPane.showMessageDialog(iParent, "No ratio type was selected!", "ERROR", JOptionPane.WARNING_MESSAGE);
}
}
});
invertRatioCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (invertRatioCheckBox.isSelected()) {
String lLabelText = lblLabel.getText();
lLabelText = "(" + lLabelText + ")^-1";
lblLabel.setText(lLabelText);
} else {
lblLabel.setText(iCollectionsRatios.get(iIndexCounter)[iRatioTypeCounter]);
}
}
});
}
public JPanel getContentPane() {
return jpanContent;
}
public void backClicked() {
//To change body of implemented methods use File | Settings | File Templates.
}
public void nextClicked() {
iParent.setRatioTypes(iRatioTypes);
}
public boolean feasableToProceed() {
return true;
}
public String getNotFeasableReason() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void construct() {
iCollectionsComponents = iParent.getCollectionsComponents();
iCollectionsRatios = iParent.getCollectionsRatios();
lblLabel.setText(iCollectionsRatios.get(0)[0]);
lblSet.setText(iParent.getTitle(iIndexCounter) + " : set " + (iIndexCounter + 1) + "/" + iCollectionsRatios.size());
lblRatioLabelCount.setText("Ratio type 1/" + iCollectionsRatios.get(0).length);
linkToSelectedMergedButton.setEnabled(false);
iParent.setNextButtonEnabled(false);
}
private void createUIComponents() {
list1 = new JList(iRatioTypes);
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
jpanContent = new JPanel();
jpanContent.setLayout(new GridBagLayout());
jpanContent.setDoubleBuffered(false);
final JLabel label1 = new JLabel();
label1.setDoubleBuffered(false);
label1.setFont(new Font(label1.getFont().getName(), Font.BOLD, 16));
label1.setText("Merge ratio types from different sources");
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(label1, gbc);
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setDoubleBuffered(false);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridheight = 4;
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(scrollPane1, gbc);
list1.setDoubleBuffered(false);
scrollPane1.setViewportView(list1);
lblSet = new JLabel();
lblSet.setDoubleBuffered(false);
lblSet.setText("Set 1");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.5;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(lblSet, gbc);
lblRatioLabelCount = new JLabel();
lblRatioLabelCount.setDoubleBuffered(false);
lblRatioLabelCount.setText("Ratio type 1");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(lblRatioLabelCount, gbc);
lblLabel = new JLabel();
lblLabel.setDoubleBuffered(false);
lblLabel.setFont(new Font(lblLabel.getFont().getName(), Font.BOLD, 20));
lblLabel.setHorizontalAlignment(0);
lblLabel.setHorizontalTextPosition(0);
lblLabel.setText("L/H");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(lblLabel, gbc);
linkToSelectedMergedButton = new JButton();
linkToSelectedMergedButton.setDoubleBuffered(false);
linkToSelectedMergedButton.setText("Link to selected merged ratio type");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(linkToSelectedMergedButton, gbc);
linkToANewlyButton = new JButton();
linkToANewlyButton.setDoubleBuffered(false);
linkToANewlyButton.setText("Link to a newly created merged ratio type");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 6;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(linkToANewlyButton, gbc);
newlyCreatedRatioTypeTextField = new JTextField();
newlyCreatedRatioTypeTextField.setDoubleBuffered(false);
newlyCreatedRatioTypeTextField.setText("Newly created ratio type name");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 7;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(newlyCreatedRatioTypeTextField, gbc);
invertRatioCheckBox = new JCheckBox();
invertRatioCheckBox.setText("invert ratio");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 5, 5, 5);
jpanContent.add(invertRatioCheckBox, gbc);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return jpanContent;
}
}
| |
/**
* Copyright 2010 Dain Sundstrom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.weakref.jmx;
import javax.management.Descriptor;
import javax.management.ImmutableDescriptor;
import javax.management.MBeanAttributeInfo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.weakref.jmx.ReflectionUtils.isValidGetter;
import static org.weakref.jmx.ReflectionUtils.isValidSetter;
public class MBeanAttributeBuilder
{
private static final Pattern getterOrSetterPattern = Pattern.compile("(get|set|is)(.+)");
private Object target;
private String name;
private Method concreteGetter;
private Method annotatedGetter;
private Method concreteSetter;
private Method annotatedSetter;
private boolean flatten;
private boolean nested;
public MBeanAttributeBuilder onInstance(Object target)
{
if (target == null) {
throw new NullPointerException("target is null");
}
this.target = target;
return this;
}
public MBeanAttributeBuilder named(String name)
{
if (name == null) {
throw new NullPointerException("name is null");
}
this.name = name;
return this;
}
public MBeanAttributeBuilder withConcreteGetter(Method concreteGetter)
{
if (concreteGetter == null) {
throw new NullPointerException("concreteGetter is null");
}
if (!isValidGetter(concreteGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + concreteGetter);
}
this.concreteGetter = concreteGetter;
return this;
}
public MBeanAttributeBuilder withAnnotatedGetter(Method annotatedGetter)
{
if (annotatedGetter == null) {
throw new NullPointerException("annotatedGetter is null");
}
if (!isValidGetter(annotatedGetter)) {
throw new IllegalArgumentException("Method is not a valid getter: " + annotatedGetter);
}
this.annotatedGetter = annotatedGetter;
return this;
}
public MBeanAttributeBuilder withConcreteSetter(Method concreteSetter)
{
if (concreteSetter == null) {
throw new NullPointerException("concreteSetter is null");
}
if (!isValidSetter(concreteSetter)) {
throw new IllegalArgumentException("Method is not a valid setter: " + concreteSetter);
}
this.concreteSetter = concreteSetter;
return this;
}
public MBeanAttributeBuilder withAnnotatedSetter(Method annotatedSetter)
{
if (annotatedSetter == null) {
throw new NullPointerException("annotatedSetter is null");
}
if (!isValidSetter(annotatedSetter)) {
throw new IllegalArgumentException("Method is not a valid setter: " + annotatedSetter);
}
this.annotatedSetter = annotatedSetter;
return this;
}
public MBeanAttributeBuilder flatten()
{
this.flatten = true;
return this;
}
public MBeanAttributeBuilder nested()
{
this.nested = true;
return this;
}
public Collection<? extends MBeanFeature> build()
{
if (target == null) {
throw new IllegalArgumentException("JmxAttribute must have a target object");
}
// Name
String attributeName = name;
if (attributeName == null) {
attributeName = getAttributeName(concreteGetter, concreteSetter, annotatedGetter, annotatedSetter);
}
if (flatten || AnnotationUtils.isFlatten(annotatedGetter)) {
// must have a getter
if (concreteGetter == null) {
throw new IllegalArgumentException("Flattened JmxAttribute must have a concrete getter");
}
Object value = null;
try {
value = concreteGetter.invoke(target);
}
catch (Exception e) {
// todo log me
}
if (value == null) {
return Collections.emptySet();
}
MBean mbean = new MBeanBuilder(value).build();
ArrayList<MBeanFeature> features = new ArrayList<>();
features.addAll(mbean.getAttributes());
features.addAll(mbean.getOperations());
return Collections.unmodifiableCollection(features);
}
else if (nested || AnnotationUtils.isNested(annotatedGetter)) {
// must have a getter
if (concreteGetter == null) {
throw new IllegalArgumentException("Nested JmxAttribute must have a concrete getter");
}
Object value = null;
try {
value = concreteGetter.invoke(target);
}
catch (Exception e) {
// todo log me
}
if (value == null) {
return Collections.emptySet();
}
MBean mbean = new MBeanBuilder(value).build();
ArrayList<MBeanFeature> features = new ArrayList<>();
for (MBeanAttribute attribute : mbean.getAttributes()) {
features.add(new NestedMBeanAttribute(attributeName, attribute));
}
for (MBeanOperation operation : mbean.getOperations()) {
features.add(new NestedMBeanOperation(attributeName, operation));
}
return Collections.unmodifiableCollection(features);
}
else {
// We must have a getter or a setter
if (concreteGetter == null && concreteSetter == null) {
throw new IllegalArgumentException("JmxAttribute must have a concrete getter or setter method");
}
// Type
Class<?> attributeType;
if (concreteGetter != null) {
attributeType = concreteGetter.getReturnType();
}
else {
attributeType = concreteSetter.getParameterTypes()[0];
}
// Descriptor
Descriptor descriptor = null;
if (annotatedGetter != null) {
descriptor = AnnotationUtils.buildDescriptor(annotatedGetter);
}
if (annotatedSetter != null) {
Descriptor setterDescriptor = AnnotationUtils.buildDescriptor(annotatedSetter);
if (descriptor == null) {
descriptor = setterDescriptor;
}
else {
descriptor = ImmutableDescriptor.union(descriptor, setterDescriptor);
}
}
// Description
String description = AnnotationUtils.getDescription(descriptor, annotatedGetter, annotatedSetter);
MBeanAttributeInfo mbeanAttributeInfo = new MBeanAttributeInfo(
attributeName,
attributeType.getName(),
description,
concreteGetter != null,
concreteSetter != null,
concreteGetter != null && concreteGetter.getName().startsWith("is"),
descriptor);
return Collections.singleton(new ReflectionMBeanAttribute(mbeanAttributeInfo, target, concreteGetter, concreteSetter));
}
}
private static String getAttributeName(Method... methods)
{
for (Method method : methods) {
if (method != null) {
Matcher matcher = getterOrSetterPattern.matcher(method.getName());
if (matcher.matches()) {
return matcher.group(2);
}
}
}
// just use the name of the first non-null method
for (Method method : methods) {
if (method != null) {
return method.getName();
}
}
return null;
}
}
| |
// Copyright (C) 2021 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.acceptance.server.change;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.acceptance.PushOneCommit.FILE_NAME;
import static com.google.gerrit.entities.Patch.COMMIT_MSG;
import static com.google.gerrit.entities.Patch.MERGE_LIST;
import static com.google.gerrit.entities.Patch.PATCHSET_LEVEL;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.MoreCollectors;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PushOneCommit;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.extensions.api.changes.DraftInput;
import com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput;
import com.google.gerrit.extensions.client.Comment;
import com.google.gerrit.extensions.client.Side;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.ChangeInput;
import com.google.gerrit.extensions.common.CommentInfo;
import com.google.gerrit.extensions.common.ContextLineInfo;
import com.google.gerrit.server.change.FileContentUtil;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.eclipse.jgit.lib.ObjectId;
import org.junit.Before;
import org.junit.Test;
@NoHttpd
public class CommentContextIT extends AbstractDaemonTest {
/** The commit message of a single commit. */
private static final String SUBJECT =
String.join(
"\n",
"Commit Header",
"",
"This commit is doing something extremely important",
"",
"Footer: value");
private static final String FILE_CONTENT =
String.join("\n", "Line 1 of file", "", "Line 3 of file", "", "", "Line 6 of file");
private static final ObjectId dummyCommit =
ObjectId.fromString("93e2901bc0b4719ef6081ee6353b49c9cdd97614");
@Inject private RequestScopeOperations requestScopeOperations;
@Before
public void setup() throws Exception {
requestScopeOperations.setApiUser(user.id());
}
@Test
public void commentContextForGitSubmoduleFiles() throws Exception {
String submodulePath = "submodule_path";
PushOneCommit push =
pushFactory.create(admin.newIdent(), testRepo).addGitSubmodule(submodulePath, dummyCommit);
PushOneCommit.Result pushResult = push.to("refs/for/master");
String changeId = pushResult.getChangeId();
CommentInput comment =
CommentsUtil.newComment(submodulePath, Side.REVISION, 1, "comment", false);
CommentsUtil.addComments(gApi, changeId, pushResult.getCommit().name(), comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).path).isEqualTo(submodulePath);
assertThat(comments.get(0).contextLines)
.isEqualTo(createContextLines("1", "Subproject commit " + dummyCommit.getName()));
}
@Test
public void commentContextForRootCommitOnParentSideReturnsEmptyContext() throws Exception {
// Create a change in a new branch, making the patchset commit a root commit
ChangeInfo changeInfo = createChangeInNewBranch("newBranch");
String changeId = changeInfo.changeId;
String revision = changeInfo.revisions.keySet().iterator().next();
// Write a comment on the parent side of the commit message. Set parent=1 because if unset, our
// handler in PostReview assumes we want to write on the auto-merge commit and fails the
// pre-condition.
CommentInput comment = CommentsUtil.newComment(COMMIT_MSG, Side.PARENT, 0, "comment", false);
comment.parent = 1;
CommentsUtil.addComments(gApi, changeId, revision, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
CommentInfo c = comments.stream().collect(MoreCollectors.onlyElement());
assertThat(c.commitId).isEqualTo(ObjectId.zeroId().name());
assertThat(c.contextLines).isEmpty();
}
@Test
public void commentContextForCommitMessageForLineComment() throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, FILE_CONTENT, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment = CommentsUtil.newComment(COMMIT_MSG, Side.REVISION, 7, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
// The first few lines of the commit message are the headers, e.g.
// Parent: ...
// Author: ...
// AuthorDate: ...
// etc...
assertThat(comments.get(0).contextLines)
.containsExactlyElementsIn(createContextLines("7", "Commit Header"));
}
@Test
public void commentContextForMergeList() throws Exception {
PushOneCommit.Result result = createMergeCommitChange("refs/for/master");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment = CommentsUtil.newComment(MERGE_LIST, Side.REVISION, 1, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).contextLines)
.containsExactlyElementsIn(createContextLines("1", "Merge List:"));
}
@Test
public void commentContextForCommitMessageForRangeComment() throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, FILE_CONTENT, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment =
CommentsUtil.newComment(
COMMIT_MSG, Side.REVISION, createCommentRange(7, 9), "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
// The first few lines of the commit message are the headers, e.g.
// Parent: ...
// Author: ...
// AuthorDate: ...
// etc...
assertThat(comments.get(0).contextLines)
.containsExactlyElementsIn(
createContextLines(
"7",
"Commit Header",
"8",
"",
"9",
"This commit is doing something extremely important"));
}
@Test
public void commentContextForCommitMessageInvalidLine() throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, FILE_CONTENT, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment =
CommentsUtil.newComment(COMMIT_MSG, Side.REVISION, 100, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).contextLines).isEmpty();
}
@Test
public void listChangeCommentsWithContextEnabled() throws Exception {
PushOneCommit.Result r1 = createChange();
ImmutableList.Builder<String> content = ImmutableList.builder();
for (int i = 1; i <= 10; i++) {
content.add("line_" + i);
}
PushOneCommit.Result r2 =
pushFactory
.create(
admin.newIdent(),
testRepo,
PushOneCommit.SUBJECT,
FILE_NAME,
content.build().stream().collect(Collectors.joining("\n")),
r1.getChangeId())
.to("refs/for/master");
CommentsUtil.addCommentOnLine(gApi, r2, "nit: please fix", 1);
CommentsUtil.addCommentOnRange(gApi, r2, "looks good", createCommentRange(2, 5));
List<CommentInfo> comments =
gApi.changes().id(r2.getChangeId()).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(2);
assertThat(
comments.stream()
.filter(c -> c.message.equals("nit: please fix"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(createContextLines("1", "line_1"));
assertThat(
comments.stream()
.filter(c -> c.message.equals("looks good"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(
createContextLines("2", "line_2", "3", "line_3", "4", "line_4", "5", "line_5"));
}
@Test
public void listChangeDraftsWithContextEnabled() throws Exception {
PushOneCommit.Result r1 = createChange();
PushOneCommit.Result r2 =
pushFactory
.create(
admin.newIdent(),
testRepo,
PushOneCommit.SUBJECT,
FILE_NAME,
"line_1\nline_2\nline_3",
r1.getChangeId())
.to("refs/for/master");
DraftInput in = CommentsUtil.newDraft(FILE_NAME, Side.REVISION, 2, "comment 1");
gApi.changes().id(r2.getChangeId()).revision(r2.getCommit().name()).createDraft(in);
// Test the getAsList interface
List<CommentInfo> comments =
gApi.changes().id(r2.getChangeId()).draftsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).message).isEqualTo("comment 1");
assertThat(comments.get(0).contextLines)
.containsExactlyElementsIn(createContextLines("2", "line_2"));
// Also test the get interface
Map<String, List<CommentInfo>> commentsMap =
gApi.changes().id(r2.getChangeId()).draftsRequest().withContext(true).get();
assertThat(commentsMap).hasSize(1);
assertThat(commentsMap.values().iterator().next()).hasSize(1);
CommentInfo onlyComment = commentsMap.values().iterator().next().get(0);
assertThat(onlyComment.message).isEqualTo("comment 1");
assertThat(onlyComment.contextLines)
.containsExactlyElementsIn(createContextLines("2", "line_2"));
}
@Test
public void commentContextForCommentsOnDifferentPatchsets() throws Exception {
PushOneCommit.Result r1 = createChange();
ImmutableList.Builder<String> content = ImmutableList.builder();
for (int i = 1; i <= 10; i++) {
content.add("line_" + i);
}
PushOneCommit.Result r2 =
pushFactory
.create(
admin.newIdent(),
testRepo,
PushOneCommit.SUBJECT,
FILE_NAME,
String.join("\n", content.build()),
r1.getChangeId())
.to("refs/for/master");
PushOneCommit.Result r3 =
pushFactory
.create(
admin.newIdent(),
testRepo,
PushOneCommit.SUBJECT,
FILE_NAME,
content.build().stream().collect(Collectors.joining("\n")),
r1.getChangeId())
.to("refs/for/master");
CommentsUtil.addCommentOnLine(gApi, r2, "r2: please fix", 1);
CommentsUtil.addCommentOnRange(gApi, r2, "r2: looks good", createCommentRange(2, 3));
CommentsUtil.addCommentOnLine(gApi, r3, "r3: please fix", 6);
CommentsUtil.addCommentOnRange(gApi, r3, "r3: looks good", createCommentRange(7, 8));
List<CommentInfo> comments =
gApi.changes().id(r2.getChangeId()).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(4);
assertThat(
comments.stream()
.filter(c -> c.message.equals("r2: please fix"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(createContextLines("1", "line_1"));
assertThat(
comments.stream()
.filter(c -> c.message.equals("r2: looks good"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(createContextLines("2", "line_2", "3", "line_3"));
assertThat(
comments.stream()
.filter(c -> c.message.equals("r3: please fix"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(createContextLines("6", "line_6"));
assertThat(
comments.stream()
.filter(c -> c.message.equals("r3: looks good"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(createContextLines("7", "line_7", "8", "line_8"));
}
@Test
public void commentContextIsEmptyForPatchsetLevelComments() throws Exception {
PushOneCommit.Result result = createChange();
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment =
CommentsUtil.newCommentWithOnlyMandatoryFields(PATCHSET_LEVEL, "comment");
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).contextLines).isEmpty();
}
@Test
public void commentContextWithZeroPadding() throws Exception {
String changeId = createChangeWithComment(3, 4);
assertContextLines(changeId, /* contextPadding= */ 0, ImmutableList.of(3, 4));
}
@Test
public void commentContextWithSmallPadding() throws Exception {
String changeId = createChangeWithComment(3, 4);
assertContextLines(changeId, /* contextPadding= */ 1, ImmutableList.of(2, 3, 4, 5));
}
@Test
public void commentContextWithSmallPaddingAtTheBeginningOfFile() throws Exception {
String changeId = createChangeWithComment(1, 2);
assertContextLines(changeId, /* contextPadding= */ 2, ImmutableList.of(1, 2, 3, 4));
}
@Test
public void commentContextWithPaddingLargerThanFileSize() throws Exception {
String changeId = createChangeWithComment(3, 3);
assertContextLines(
changeId,
/* contextPadding= */ 20,
ImmutableList.of(1, 2, 3, 4, 5, 6)); // file only contains six lines.
}
@Test
public void commentContextWithLargePaddingReturnsAdjustedMaximumPadding() throws Exception {
String changeId = createChangeWithCommentLarge(250, 250);
assertContextLines(
changeId,
/* contextPadding= */ 300,
IntStream.range(200, 301).boxed().collect(ImmutableList.toImmutableList()));
}
@Test
public void commentContextReturnsCorrectContentTypeForCommitMessage() throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, FILE_CONTENT, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment = CommentsUtil.newComment(COMMIT_MSG, Side.REVISION, 7, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).path).isEqualTo(COMMIT_MSG);
assertThat(comments.get(0).sourceContentType)
.isEqualTo(FileContentUtil.TEXT_X_GERRIT_COMMIT_MESSAGE);
}
@Test
public void commentContextReturnsCorrectContentType_java() throws Exception {
String javaContent =
"public class Main {\n"
+ " public static void main(String[]args){\n"
+ " if(args==null){\n"
+ " System.err.println(\"Something\");\n"
+ " }\n"
+ " }\n"
+ " }";
String fileName = "src.java";
String changeId = createChangeWithContent(fileName, javaContent, /* line= */ 4);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).path).isEqualTo(fileName);
assertThat(comments.get(0).contextLines)
.isEqualTo(createContextLines("4", " System.err.println(\"Something\");"));
assertThat(comments.get(0).sourceContentType).isEqualTo("text/x-java");
}
@Test
public void commentContextReturnsCorrectContentType_cpp() throws Exception {
String cppContent =
"#include <iostream>\n"
+ "\n"
+ "int main() {\n"
+ " std::cout << \"Hello World!\";\n"
+ " return 0;\n"
+ "}";
String fileName = "src.cpp";
String changeId = createChangeWithContent(fileName, cppContent, /* line= */ 4);
List<CommentInfo> comments =
gApi.changes().id(changeId).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(1);
assertThat(comments.get(0).path).isEqualTo(fileName);
assertThat(comments.get(0).contextLines)
.isEqualTo(createContextLines("4", " std::cout << \"Hello World!\";"));
assertThat(comments.get(0).sourceContentType).isEqualTo("text/x-c++src");
}
@Test
public void listChangeCommentsWithContextEnabled_twoRangeCommentsWithTheSameContext()
throws Exception {
PushOneCommit.Result r1 = createChange();
ImmutableList.Builder<String> content = ImmutableList.builder();
for (int i = 1; i <= 10; i++) {
content.add("line_" + i);
}
PushOneCommit.Result r2 =
pushFactory
.create(
admin.newIdent(),
testRepo,
PushOneCommit.SUBJECT,
FILE_NAME,
content.build().stream().collect(Collectors.joining("\n")),
r1.getChangeId())
.to("refs/for/master");
CommentsUtil.addCommentOnRange(gApi, r2, "looks good", createCommentRange(2, 5));
CommentsUtil.addCommentOnRange(gApi, r2, "are you sure?", createCommentRange(2, 5));
List<CommentInfo> comments =
gApi.changes().id(r2.getChangeId()).commentsRequest().withContext(true).getAsList();
assertThat(comments).hasSize(2);
assertThat(
comments.stream()
.filter(c -> c.message.equals("looks good"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(
createContextLines("2", "line_2", "3", "line_3", "4", "line_4", "5", "line_5"));
assertThat(
comments.stream()
.filter(c -> c.message.equals("are you sure?"))
.collect(MoreCollectors.onlyElement())
.contextLines)
.containsExactlyElementsIn(
createContextLines("2", "line_2", "3", "line_3", "4", "line_4", "5", "line_5"));
}
private String createChangeWithContent(String fileName, String fileContent, int line)
throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, fileName, fileContent, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
CommentInput comment = CommentsUtil.newComment(fileName, Side.REVISION, line, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
return changeId;
}
private String createChangeWithComment(int startLine, int endLine) throws Exception {
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, FILE_CONTENT, "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
Comment.Range commentRange = createCommentRange(startLine, endLine);
CommentInput comment =
CommentsUtil.newComment(FILE_NAME, Side.REVISION, commentRange, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
return changeId;
}
private String createChangeWithCommentLarge(int startLine, int endLine) throws Exception {
StringBuilder largeContent = new StringBuilder();
for (int i = 0; i < 1000; i++) {
largeContent.append("line " + i + "\n");
}
PushOneCommit.Result result =
createChange(testRepo, "master", SUBJECT, FILE_NAME, largeContent.toString(), "topic");
String changeId = result.getChangeId();
String ps1 = result.getCommit().name();
Comment.Range commentRange = createCommentRange(startLine, endLine);
CommentInput comment =
CommentsUtil.newComment(FILE_NAME, Side.REVISION, commentRange, "comment", false);
CommentsUtil.addComments(gApi, changeId, ps1, comment);
return changeId;
}
private void assertContextLines(
String changeId, int contextPadding, ImmutableList<Integer> expectedLines) throws Exception {
List<CommentInfo> comments =
gApi.changes()
.id(changeId)
.commentsRequest()
.withContext(true)
.contextPadding(contextPadding)
.getAsList();
assertThat(comments).hasSize(1);
assertThat(
comments.get(0).contextLines.stream()
.map(c -> c.lineNumber)
.collect(Collectors.toList()))
.containsExactlyElementsIn(expectedLines);
}
private Comment.Range createCommentRange(int startLine, int endLine) {
Comment.Range range = new Comment.Range();
range.startLine = startLine;
range.endLine = endLine;
return range;
}
private List<ContextLineInfo> createContextLines(String... args) {
List<ContextLineInfo> result = new ArrayList<>();
for (int i = 0; i < args.length; i += 2) {
int lineNbr = Integer.parseInt(args[i]);
String contextLine = args[i + 1];
ContextLineInfo info = new ContextLineInfo(lineNbr, contextLine);
result.add(info);
}
return result;
}
private ChangeInfo createChangeInNewBranch(String branchName) throws Exception {
ChangeInput in = new ChangeInput();
in.project = project.get();
in.branch = branchName;
in.newBranch = true;
in.subject = "New changes";
return gApi.changes().create(in).get();
}
}
| |
package com.mapbox.mapboxsdk.overlay;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.Log;
import com.mapbox.mapboxsdk.tileprovider.MapTile;
import com.mapbox.mapboxsdk.tileprovider.MapTileLayerBase;
import com.mapbox.mapboxsdk.util.GeometryMath;
import com.mapbox.mapboxsdk.util.TileLooper;
import com.mapbox.mapboxsdk.util.constants.UtilConstants;
import com.mapbox.mapboxsdk.views.MapView;
import com.mapbox.mapboxsdk.views.safecanvas.ISafeCanvas;
import com.mapbox.mapboxsdk.views.safecanvas.SafePaint;
import com.mapbox.mapboxsdk.views.util.Projection;
import java.util.HashMap;
import uk.co.senab.bitmapcache.CacheableBitmapDrawable;
/**
* These objects are the principle consumer of map tiles.
* <p/>
* see {@link MapTile} for an overview of how tiles are acquired by this overlay.
*/
public class TilesOverlay extends SafeDrawOverlay {
private static final String TAG = "TilesOverlay";
public static final int MENU_OFFLINE = getSafeMenuId();
private int mNuberOfTiles;
/**
* Current tile source
*/
protected final MapTileLayerBase mTileProvider;
/* to avoid allocations during draw */
protected static SafePaint mDebugPaint = null;
protected static SafePaint mLoadingTilePaint = null;
protected static Bitmap mLoadingTileBitmap = null;
protected Paint mLoadingPaint = null;
private final Rect mTileRect = new Rect();
private final Rect mViewPort = new Rect();
private final Rect mClipRect = new Rect();
float mCurrentZoomFactor = 1;
private float mRescaleZoomDiffMax = 4;
private boolean isAnimating = false;
private boolean mOptionsMenuEnabled = true;
private int mWorldSize_2;
private int mLoadingBackgroundColor = Color.rgb(216, 208, 208);
private int mLoadingLineColor = Color.rgb(200, 192, 192);
private boolean mDrawLoadingTile = true;
public TilesOverlay(final MapTileLayerBase aTileProvider) {
super();
if (aTileProvider == null) {
throw new IllegalArgumentException("You must pass a valid tile provider to the tiles overlay.");
}
this.mTileProvider = aTileProvider;
if (UtilConstants.DEBUGMODE) {
getDebugPaint();
}
mLoadingPaint = new Paint();
mLoadingPaint.setAntiAlias(true);
mLoadingPaint.setFilterBitmap(true);
mLoadingPaint.setColor(mLoadingLineColor);
mLoadingPaint.setStrokeWidth(0);
mNuberOfTiles = 0;
}
public static SafePaint getDebugPaint() {
if (mDebugPaint == null) {
mDebugPaint = new SafePaint();
mDebugPaint.setAntiAlias(true);
mDebugPaint.setFilterBitmap(true);
mDebugPaint.setColor(Color.RED);
mDebugPaint.setStyle(Paint.Style.STROKE);
}
return mDebugPaint;
}
@Override
public void onDetach(final MapView pMapView) {
this.mTileProvider.detach();
}
public float getMinimumZoomLevel() {
return mTileProvider.getMinimumZoomLevel();
}
public float getMaximumZoomLevel() {
return mTileProvider.getMaximumZoomLevel();
}
/**
* Whether to use the network connection if it's available.
*
* @return true if this uses a data connection
*/
public boolean useDataConnection() {
return mTileProvider.useDataConnection();
}
/**
* Set whether to use the network connection if it's available.
*
* @param aMode if true use the network connection if it's available. if false don't use the
* network connection even if it's available.
*/
public void setUseDataConnection(final boolean aMode) {
mTileProvider.setUseDataConnection(aMode);
}
@Override
protected void drawSafe(final ISafeCanvas c, final MapView mapView, final boolean shadow) {
if (shadow) {
return;
}
//Commented for now. It needs heavy testing to see if we actually need it
isAnimating = mapView.isAnimating();
// Calculate the half-world size
final Projection pj = mapView.getProjection();
c.getClipBounds(mClipRect);
float zoomDelta = (float) (Math.log(mapView.getScale()) / Math.log(2d));
final float zoomLevel = pj.getZoomLevel();
mWorldSize_2 = pj.getHalfWorldSize();
GeometryMath.viewPortRectForTileDrawing(pj, mViewPort);
int tileSize = Projection.getTileSize();
// Draw the tiles!
if (tileSize > 0) {
if (mDrawLoadingTile) {
drawLoadingTile(c.getSafeCanvas(), mapView, zoomLevel, mClipRect);
}
drawTiles(c.getSafeCanvas(), zoomLevel, tileSize, mViewPort, mClipRect);
}
if (UtilConstants.DEBUGMODE && mapView.getScrollableAreaLimit() != null) {
SafePaint paint = new SafePaint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
Rect rect = new Rect();
mapView.getScrollableAreaLimit().round(rect);
if (mapView.getScrollableAreaLimit() != null) {
c.drawRect(rect, paint);
}
}
}
/**
* Draw a loading tile image to make in-progress tiles easier to deal with.
*
* @param c
* @param mapView
* @param zoomLevel
* @param viewPort
*/
public void drawLoadingTile(final Canvas c, final MapView mapView, final float zoomLevel, final Rect viewPort) {
ISafeCanvas canvas = (ISafeCanvas) c;
canvas.save();
canvas.translate(-mapView.getScrollX(), -mapView.getScrollY());
canvas.drawPaint(getLoadingTilePaint());
canvas.restore();
}
/**
* This is meant to be a "pure" tile drawing function that doesn't take into account
* osmdroid-specific characteristics (like osmdroid's canvas's having 0,0 as the center rather
* than the upper-left corner). Once the tile is ready to be drawn, it is passed to
* onTileReadyToDraw where custom manipulations can be made before drawing the tile.
*/
public void drawTiles(final Canvas c, final float zoomLevel, final int tileSizePx,
final Rect viewPort, final Rect pClipRect) {
mNuberOfTiles = mTileLooper.loop(c, mTileProvider.getCacheKey(), zoomLevel, tileSizePx, viewPort, pClipRect);
// draw a cross at center in debug mode
if (UtilConstants.DEBUGMODE) {
ISafeCanvas canvas = (ISafeCanvas) c;
final Point centerPoint =
new Point(viewPort.centerX() - mWorldSize_2, viewPort.centerY() - mWorldSize_2);
canvas.drawLine(centerPoint.x, centerPoint.y - 9, centerPoint.x, centerPoint.y + 9,
getDebugPaint());
canvas.drawLine(centerPoint.x - 9, centerPoint.y, centerPoint.x + 9, centerPoint.y,
getDebugPaint());
}
}
private final TileLooper mTileLooper = new TileLooper() {
@Override
public void initializeLoop(final float pZoomLevel, final int pTileSizePx) {
final int roundedZoom = (int) Math.floor(pZoomLevel);
if (roundedZoom != pZoomLevel) {
final int mapTileUpperBound = 1 << roundedZoom;
mCurrentZoomFactor =
(float) Projection.mapSize(pZoomLevel) / mapTileUpperBound / pTileSizePx;
} else {
mCurrentZoomFactor = 1.0f;
}
}
@Override
public void handleTile(final Canvas pCanvas, final String pCacheKey, final int pTileSizePx,
final MapTile pTile, final int pX, final int pY, final Rect pClipRect) {
final double factor = pTileSizePx * mCurrentZoomFactor;
double x = pX * factor - mWorldSize_2;
double y = pY * factor - mWorldSize_2;
mTileRect.set((int) x, (int) y, (int) (x + factor), (int) (y + factor));
if (!Rect.intersects(mTileRect, pClipRect)) {
return;
}
pTile.setTileRect(mTileRect);
Drawable drawable = mTileProvider.getMapTile(pTile, !isAnimating);
boolean isReusable = drawable instanceof CacheableBitmapDrawable;
if (drawable != null) {
if (isReusable) {
mBeingUsedDrawables.add((CacheableBitmapDrawable) drawable);
}
drawable.setBounds(mTileRect);
drawable.draw(pCanvas);
} else {
mTileProvider.memoryCacheNeedsMoreMemory(mNuberOfTiles);
//Log.w(TAG, "tile should have been drawn to canvas, but it was null. tile = '" + pTile + "'");
}
if (UtilConstants.DEBUGMODE) {
ISafeCanvas canvas = (ISafeCanvas) pCanvas;
canvas.drawText(pTile.toString(), mTileRect.left + 1, mTileRect.top + getDebugPaint().getTextSize(), getDebugPaint());
canvas.drawRect(mTileRect, getDebugPaint());
}
}
};
public int getLoadingBackgroundColor() {
return mLoadingBackgroundColor;
}
/**
* Set the color to use to draw the background while we're waiting for the tile to load.
*
* @param pLoadingBackgroundColor the color to use. If the value is {@link Color#TRANSPARENT}
* then there will be no
* loading tile.
*/
public void setLoadingBackgroundColor(final int pLoadingBackgroundColor) {
if (mLoadingBackgroundColor != pLoadingBackgroundColor) {
mLoadingBackgroundColor = pLoadingBackgroundColor;
clearLoadingTile();
}
}
public int getLoadingLineColor() {
return mLoadingLineColor;
}
public void setLoadingLineColor(final int pLoadingLineColor) {
if (mLoadingLineColor != pLoadingLineColor) {
mLoadingLineColor = pLoadingLineColor;
mLoadingPaint.setColor(mLoadingLineColor);
clearLoadingTile();
}
}
/**
* Set whether or not the default loading tile background should be drawn.
* If it shouldn't be, then a transparent background will be displayed.
* @param pDrawLoadingTile True if loading tiles should be displayed (default), False if not (aka: transparent background)
*/
public void setDrawLoadingTile(final boolean pDrawLoadingTile) {
this.mDrawLoadingTile = pDrawLoadingTile;
}
/**
* Draw a 'loading' placeholder with a canvas.
*/
private SafePaint getLoadingTilePaint() {
if (mLoadingTilePaint == null && mLoadingBackgroundColor != Color.TRANSPARENT) {
try {
final int tileSize =
mTileProvider.getTileSource() != null ? mTileProvider.getTileSource()
.getTileSizePixels() : 256;
mLoadingTileBitmap =
Bitmap.createBitmap(tileSize, tileSize, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(mLoadingTileBitmap);
canvas.drawColor(mLoadingBackgroundColor);
final int lineSize = tileSize / 16;
for (int a = 0; a < tileSize; a += lineSize) {
canvas.drawLine(0, a, tileSize, a, mLoadingPaint);
canvas.drawLine(a, 0, a, tileSize, mLoadingPaint);
}
mLoadingTilePaint = new SafePaint();
mLoadingTilePaint.setShader(new BitmapShader(mLoadingTileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
} catch (final OutOfMemoryError e) {
Log.e(TAG, "OutOfMemoryError getting loading tile: " + e.toString());
System.gc();
}
}
return mLoadingTilePaint;
}
private void clearLoadingTile() {
mLoadingTilePaint = null;
// Only recycle if we are running on a project less than 2.3.3 Gingerbread.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
if (mLoadingTileBitmap != null) {
mLoadingTileBitmap.recycle();
mLoadingTileBitmap = null;
}
}
}
/**
* Recreate the cache using scaled versions of the tiles currently in it
*
* @param pNewZoomLevel the zoom level that we need now
* @param pOldZoomLevel the previous zoom level that we should get the tiles to rescale
* @param projection the projection to compute view port
*/
public void rescaleCache(final float pNewZoomLevel, final float pOldZoomLevel,
final Projection projection) {
if (mTileProvider.hasNoSource() || Math.floor(pNewZoomLevel) == Math.floor(pOldZoomLevel) || projection == null || Math.abs(pOldZoomLevel - pNewZoomLevel) > mRescaleZoomDiffMax) {
return;
}
final long startMs = System.currentTimeMillis();
if (UtilConstants.DEBUGMODE) {
Log.d(TAG, "rescale tile cache from " + pOldZoomLevel + " to " + pNewZoomLevel);
}
final int tileSize = Projection.getTileSize();
final Rect viewPort =
GeometryMath.viewPortRectForTileDrawing(pNewZoomLevel, projection, null);
final ScaleTileLooper tileLooper =
pNewZoomLevel > pOldZoomLevel ? new ZoomInTileLooper(pOldZoomLevel)
: new ZoomOutTileLooper(pOldZoomLevel);
tileLooper.loop(null, mTileProvider.getCacheKey(), pNewZoomLevel, tileSize, viewPort, null);
final long endMs = System.currentTimeMillis();
if (UtilConstants.DEBUGMODE) {
Log.d(TAG, "Finished rescale in " + (endMs - startMs) + "ms");
}
}
private abstract class ScaleTileLooper extends TileLooper {
/**
* new (scaled) tiles to add to cache
* NB first generate all and then put all in cache,
* otherwise the ones we need will be pushed out
*/
protected final HashMap<MapTile, Bitmap> mNewTiles;
protected final float mOldZoomLevel;
protected final int mOldZoomRound;
protected final int mOldTileUpperBound;
protected float mDiff;
protected int mTileSize_2;
protected Rect mSrcRect;
protected Rect mDestRect;
protected Paint mDebugPaint;
public ScaleTileLooper(final float pOldZoomLevel) {
mOldZoomLevel = pOldZoomLevel;
mOldZoomRound = (int) Math.floor(mOldZoomLevel);
mOldTileUpperBound = 1 << mOldZoomRound;
mNewTiles = new HashMap<MapTile, Bitmap>();
mSrcRect = new Rect();
mDestRect = new Rect();
mDebugPaint = new Paint();
}
@Override
public void initializeLoop(final float pZoomLevel, final int pTileSizePx) {
mDiff = (float) Math.abs(Math.floor(pZoomLevel) - Math.floor(mOldZoomLevel));
mTileSize_2 = (int) GeometryMath.rightShift(pTileSizePx, mDiff);
}
@Override
public void handleTile(final Canvas pCanvas, final String pCacheKey, final int pTileSizePx,
final MapTile pTile, final int pX, final int pY, final Rect pClipRect) {
// Get tile from cache.
// If it's found then no need to created scaled version.
// If not found (null) them we've initiated a new request for it,
// and now we'll create a scaled version until the request completes.
final Drawable requestedTile = mTileProvider.getMapTile(pTile, !isAnimating);
if (requestedTile == null) {
try {
handleScaleTile(pCacheKey, pTileSizePx, pTile, pX, pY);
} catch (final OutOfMemoryError e) {
Log.e(TAG, "OutOfMemoryError rescaling cache");
}
}
}
@Override
public void finalizeLoop() {
super.finalizeLoop();
// now add the new ones, pushing out the old ones
while (!mNewTiles.isEmpty()) {
final MapTile tile = mNewTiles.keySet().iterator().next();
final Bitmap bitmap = mNewTiles.remove(tile);
mTileProvider.putExpiredTileIntoCache(tile, bitmap);
}
}
protected abstract void handleScaleTile(final String pCacheKey, final int pTileSizePx,
final MapTile pTile, final int pX, final int pY);
}
private class ZoomInTileLooper extends ScaleTileLooper {
public ZoomInTileLooper(final float pOldZoomLevel) {
super(pOldZoomLevel);
}
@Override
public void handleScaleTile(final String pCacheKey, final int pTileSizePx,
final MapTile pTile, final int pX, final int pY) {
int oldTileX = GeometryMath.mod((int) GeometryMath.rightShift(pX, mDiff), mOldTileUpperBound);
int oldTileY = GeometryMath.mod((int) GeometryMath.rightShift(pY, mDiff), mOldTileUpperBound);
// get the correct fraction of the tile from cache and scale up
final MapTile oldTile = new MapTile(pCacheKey,
mOldZoomRound, oldTileX, oldTileY);
final Drawable oldDrawable = mTileProvider.getMapTileFromMemory(oldTile);
if (oldDrawable instanceof BitmapDrawable) {
final boolean isReusable = oldDrawable instanceof CacheableBitmapDrawable;
if (isReusable) {
((CacheableBitmapDrawable) oldDrawable).setBeingUsed(true);
mBeingUsedDrawables.add((CacheableBitmapDrawable) oldDrawable);
}
final Bitmap oldBitmap = ((BitmapDrawable) oldDrawable).getBitmap();
if (oldBitmap != null) {
final int xx = (pX % (int) GeometryMath.leftShift(1, mDiff)) * mTileSize_2;
final int yy = (pY % (int) GeometryMath.leftShift(1, mDiff)) * mTileSize_2;
mSrcRect.set(xx, yy, xx + mTileSize_2, yy + mTileSize_2);
mDestRect.set(0, 0, pTileSizePx, pTileSizePx);
// Try to get a bitmap from the pool, otherwise allocate a new one
Bitmap bitmap = mTileProvider.getBitmapFromRemoved(pTileSizePx, pTileSizePx);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(pTileSizePx, pTileSizePx, Bitmap.Config.ARGB_8888);
}
final Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(oldBitmap, mSrcRect, mDestRect, null);
mNewTiles.put(pTile, bitmap);
}
}
}
}
private class ZoomOutTileLooper extends ScaleTileLooper {
private static final int MAX_ZOOM_OUT_DIFF = 8;
public ZoomOutTileLooper(final float pOldZoomLevel) {
super(pOldZoomLevel);
}
@Override
protected void handleScaleTile(final String pCacheKey, final int pTileSizePx,
final MapTile pTile, final int pX, final int pY) {
if (mDiff >= MAX_ZOOM_OUT_DIFF) {
return;
}
// get many tiles from cache and make one tile from them
final int xx = (int) GeometryMath.leftShift(pX, mDiff);
final int yy = (int) GeometryMath.leftShift(pY, mDiff);
final int numTiles = (int) GeometryMath.leftShift(1, mDiff);
int oldTileX, oldTileY;
Bitmap bitmap = null;
Canvas canvas = null;
for (int x = 0; x < numTiles; x++) {
for (int y = 0; y < numTiles; y++) {
oldTileY = GeometryMath.mod(yy + y, mOldTileUpperBound);
oldTileX = GeometryMath.mod(xx + x, mOldTileUpperBound);
final MapTile oldTile = new MapTile(pCacheKey,
mOldZoomRound, oldTileX, oldTileY);
Drawable oldDrawable = mTileProvider.getMapTileFromMemory(oldTile);
if (oldDrawable instanceof BitmapDrawable) {
final boolean isReusable = oldDrawable instanceof CacheableBitmapDrawable;
if (isReusable) {
((CacheableBitmapDrawable) oldDrawable).setBeingUsed(true);
mBeingUsedDrawables.add((CacheableBitmapDrawable) oldDrawable);
}
final Bitmap oldBitmap = ((BitmapDrawable) oldDrawable).getBitmap();
if (oldBitmap != null) {
if (bitmap == null) {
// Try to get a bitmap from the pool, otherwise allocate a new one
bitmap = mTileProvider.getBitmapFromRemoved(pTileSizePx,
pTileSizePx);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(pTileSizePx, pTileSizePx,
Bitmap.Config.ARGB_8888);
}
canvas = new Canvas(bitmap);
}
mDestRect.set(x * mTileSize_2, y * mTileSize_2, (x + 1) * mTileSize_2,
(y + 1) * mTileSize_2);
canvas.drawBitmap(oldBitmap, null, mDestRect, null);
}
}
}
}
if (bitmap != null) {
mNewTiles.put(pTile, bitmap);
}
}
}
}
| |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/recommender/v1beta1/recommendation.proto
package com.google.cloud.recommender.v1beta1;
/**
*
*
* <pre>
* Contains metadata about how much money a recommendation can save or incur.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1beta1.CostProjection}
*/
public final class CostProjection extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recommender.v1beta1.CostProjection)
CostProjectionOrBuilder {
private static final long serialVersionUID = 0L;
// Use CostProjection.newBuilder() to construct.
private CostProjection(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CostProjection() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CostProjection();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private CostProjection(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.type.Money.Builder subBuilder = null;
if (cost_ != null) {
subBuilder = cost_.toBuilder();
}
cost_ = input.readMessage(com.google.type.Money.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(cost_);
cost_ = subBuilder.buildPartial();
}
break;
}
case 18:
{
com.google.protobuf.Duration.Builder subBuilder = null;
if (duration_ != null) {
subBuilder = duration_.toBuilder();
}
duration_ =
input.readMessage(com.google.protobuf.Duration.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(duration_);
duration_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1beta1.RecommendationOuterClass
.internal_static_google_cloud_recommender_v1beta1_CostProjection_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1beta1.RecommendationOuterClass
.internal_static_google_cloud_recommender_v1beta1_CostProjection_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1beta1.CostProjection.class,
com.google.cloud.recommender.v1beta1.CostProjection.Builder.class);
}
public static final int COST_FIELD_NUMBER = 1;
private com.google.type.Money cost_;
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*
* @return Whether the cost field is set.
*/
@java.lang.Override
public boolean hasCost() {
return cost_ != null;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*
* @return The cost.
*/
@java.lang.Override
public com.google.type.Money getCost() {
return cost_ == null ? com.google.type.Money.getDefaultInstance() : cost_;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
@java.lang.Override
public com.google.type.MoneyOrBuilder getCostOrBuilder() {
return getCost();
}
public static final int DURATION_FIELD_NUMBER = 2;
private com.google.protobuf.Duration duration_;
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*
* @return Whether the duration field is set.
*/
@java.lang.Override
public boolean hasDuration() {
return duration_ != null;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*
* @return The duration.
*/
@java.lang.Override
public com.google.protobuf.Duration getDuration() {
return duration_ == null ? com.google.protobuf.Duration.getDefaultInstance() : duration_;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.DurationOrBuilder getDurationOrBuilder() {
return getDuration();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (cost_ != null) {
output.writeMessage(1, getCost());
}
if (duration_ != null) {
output.writeMessage(2, getDuration());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (cost_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getCost());
}
if (duration_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getDuration());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.recommender.v1beta1.CostProjection)) {
return super.equals(obj);
}
com.google.cloud.recommender.v1beta1.CostProjection other =
(com.google.cloud.recommender.v1beta1.CostProjection) obj;
if (hasCost() != other.hasCost()) return false;
if (hasCost()) {
if (!getCost().equals(other.getCost())) return false;
}
if (hasDuration() != other.hasDuration()) return false;
if (hasDuration()) {
if (!getDuration().equals(other.getDuration())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasCost()) {
hash = (37 * hash) + COST_FIELD_NUMBER;
hash = (53 * hash) + getCost().hashCode();
}
if (hasDuration()) {
hash = (37 * hash) + DURATION_FIELD_NUMBER;
hash = (53 * hash) + getDuration().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommender.v1beta1.CostProjection parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.recommender.v1beta1.CostProjection prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Contains metadata about how much money a recommendation can save or incur.
* </pre>
*
* Protobuf type {@code google.cloud.recommender.v1beta1.CostProjection}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recommender.v1beta1.CostProjection)
com.google.cloud.recommender.v1beta1.CostProjectionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommender.v1beta1.RecommendationOuterClass
.internal_static_google_cloud_recommender_v1beta1_CostProjection_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommender.v1beta1.RecommendationOuterClass
.internal_static_google_cloud_recommender_v1beta1_CostProjection_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommender.v1beta1.CostProjection.class,
com.google.cloud.recommender.v1beta1.CostProjection.Builder.class);
}
// Construct using com.google.cloud.recommender.v1beta1.CostProjection.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (costBuilder_ == null) {
cost_ = null;
} else {
cost_ = null;
costBuilder_ = null;
}
if (durationBuilder_ == null) {
duration_ = null;
} else {
duration_ = null;
durationBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.recommender.v1beta1.RecommendationOuterClass
.internal_static_google_cloud_recommender_v1beta1_CostProjection_descriptor;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.CostProjection getDefaultInstanceForType() {
return com.google.cloud.recommender.v1beta1.CostProjection.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.CostProjection build() {
com.google.cloud.recommender.v1beta1.CostProjection result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.CostProjection buildPartial() {
com.google.cloud.recommender.v1beta1.CostProjection result =
new com.google.cloud.recommender.v1beta1.CostProjection(this);
if (costBuilder_ == null) {
result.cost_ = cost_;
} else {
result.cost_ = costBuilder_.build();
}
if (durationBuilder_ == null) {
result.duration_ = duration_;
} else {
result.duration_ = durationBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.recommender.v1beta1.CostProjection) {
return mergeFrom((com.google.cloud.recommender.v1beta1.CostProjection) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.recommender.v1beta1.CostProjection other) {
if (other == com.google.cloud.recommender.v1beta1.CostProjection.getDefaultInstance())
return this;
if (other.hasCost()) {
mergeCost(other.getCost());
}
if (other.hasDuration()) {
mergeDuration(other.getDuration());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.recommender.v1beta1.CostProjection parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.recommender.v1beta1.CostProjection) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.type.Money cost_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder>
costBuilder_;
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*
* @return Whether the cost field is set.
*/
public boolean hasCost() {
return costBuilder_ != null || cost_ != null;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*
* @return The cost.
*/
public com.google.type.Money getCost() {
if (costBuilder_ == null) {
return cost_ == null ? com.google.type.Money.getDefaultInstance() : cost_;
} else {
return costBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public Builder setCost(com.google.type.Money value) {
if (costBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
cost_ = value;
onChanged();
} else {
costBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public Builder setCost(com.google.type.Money.Builder builderForValue) {
if (costBuilder_ == null) {
cost_ = builderForValue.build();
onChanged();
} else {
costBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public Builder mergeCost(com.google.type.Money value) {
if (costBuilder_ == null) {
if (cost_ != null) {
cost_ = com.google.type.Money.newBuilder(cost_).mergeFrom(value).buildPartial();
} else {
cost_ = value;
}
onChanged();
} else {
costBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public Builder clearCost() {
if (costBuilder_ == null) {
cost_ = null;
onChanged();
} else {
cost_ = null;
costBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public com.google.type.Money.Builder getCostBuilder() {
onChanged();
return getCostFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
public com.google.type.MoneyOrBuilder getCostOrBuilder() {
if (costBuilder_ != null) {
return costBuilder_.getMessageOrBuilder();
} else {
return cost_ == null ? com.google.type.Money.getDefaultInstance() : cost_;
}
}
/**
*
*
* <pre>
* An approximate projection on amount saved or amount incurred. Negative cost
* units indicate cost savings and positive cost units indicate increase.
* See google.type.Money documentation for positive/negative units.
* A user's permissions may affect whether the cost is computed using list
* prices or custom contract prices.
* </pre>
*
* <code>.google.type.Money cost = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder>
getCostFieldBuilder() {
if (costBuilder_ == null) {
costBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.type.Money,
com.google.type.Money.Builder,
com.google.type.MoneyOrBuilder>(getCost(), getParentForChildren(), isClean());
cost_ = null;
}
return costBuilder_;
}
private com.google.protobuf.Duration duration_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>
durationBuilder_;
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*
* @return Whether the duration field is set.
*/
public boolean hasDuration() {
return durationBuilder_ != null || duration_ != null;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*
* @return The duration.
*/
public com.google.protobuf.Duration getDuration() {
if (durationBuilder_ == null) {
return duration_ == null ? com.google.protobuf.Duration.getDefaultInstance() : duration_;
} else {
return durationBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public Builder setDuration(com.google.protobuf.Duration value) {
if (durationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
duration_ = value;
onChanged();
} else {
durationBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public Builder setDuration(com.google.protobuf.Duration.Builder builderForValue) {
if (durationBuilder_ == null) {
duration_ = builderForValue.build();
onChanged();
} else {
durationBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public Builder mergeDuration(com.google.protobuf.Duration value) {
if (durationBuilder_ == null) {
if (duration_ != null) {
duration_ =
com.google.protobuf.Duration.newBuilder(duration_).mergeFrom(value).buildPartial();
} else {
duration_ = value;
}
onChanged();
} else {
durationBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public Builder clearDuration() {
if (durationBuilder_ == null) {
duration_ = null;
onChanged();
} else {
duration_ = null;
durationBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public com.google.protobuf.Duration.Builder getDurationBuilder() {
onChanged();
return getDurationFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
public com.google.protobuf.DurationOrBuilder getDurationOrBuilder() {
if (durationBuilder_ != null) {
return durationBuilder_.getMessageOrBuilder();
} else {
return duration_ == null ? com.google.protobuf.Duration.getDefaultInstance() : duration_;
}
}
/**
*
*
* <pre>
* Duration for which this cost applies.
* </pre>
*
* <code>.google.protobuf.Duration duration = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>
getDurationFieldBuilder() {
if (durationBuilder_ == null) {
durationBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>(
getDuration(), getParentForChildren(), isClean());
duration_ = null;
}
return durationBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.recommender.v1beta1.CostProjection)
}
// @@protoc_insertion_point(class_scope:google.cloud.recommender.v1beta1.CostProjection)
private static final com.google.cloud.recommender.v1beta1.CostProjection DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.recommender.v1beta1.CostProjection();
}
public static com.google.cloud.recommender.v1beta1.CostProjection getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CostProjection> PARSER =
new com.google.protobuf.AbstractParser<CostProjection>() {
@java.lang.Override
public CostProjection parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CostProjection(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CostProjection> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CostProjection> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.recommender.v1beta1.CostProjection getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
package org.jboss.resteasy.test.finegrain.resource;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.test.EmbeddedContainer;
import org.jboss.resteasy.util.HttpHeaderNames;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import java.util.GregorianCalendar;
import static org.jboss.resteasy.test.TestPortProvider.*;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class PreconditionTest
{
private static Dispatcher dispatcher;
@BeforeClass
public static void before() throws Exception
{
dispatcher = EmbeddedContainer.start().getDispatcher();
dispatcher.getRegistry().addPerRequestResource(LastModifiedResource.class);
dispatcher.getRegistry().addPerRequestResource(EtagResource.class);
}
@AfterClass
public static void after() throws Exception
{
EmbeddedContainer.stop();
}
@Path("/")
public static class LastModifiedResource
{
@GET
public Response doGet(@Context Request request)
{
GregorianCalendar lastModified = new GregorianCalendar(2007, 0, 0, 0, 0, 0);
Response.ResponseBuilder rb = request.evaluatePreconditions(lastModified.getTime());
if (rb != null)
return rb.build();
return Response.ok("foo", "text/plain").build();
}
}
@Test
public void testIfUnmodifiedSinceBeforeLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(412, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfUnmodifiedSinceAfterLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfModifiedSinceBeforeLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfModifiedSinceAfterLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfUnmodifiedSinceBeforeLastModified_IfModifiedSinceBeforeLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(412, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfUnmodifiedSinceBeforeLastModified_IfModifiedSinceAfterLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfUnmodifiedSinceAfterLastModified_IfModifiedSinceAfterLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Test
public void testIfUnmodifiedSinceAfterLastModified_IfModifiedSinceBeforeLastModified()
{
ClientRequest request = new ClientRequest(generateURL("/"));
request.header(HttpHeaderNames.IF_UNMODIFIED_SINCE, "Tue, 2 Jan 2007 00:00:00 GMT");
request.header(HttpHeaderNames.IF_MODIFIED_SINCE, "Sat, 30 Dec 2006 00:00:00 GMT");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(200, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
@Path("/etag")
public static class EtagResource
{
@GET
public Response doGet(@Context Request request)
{
Response.ResponseBuilder rb = request.evaluatePreconditions(new EntityTag("1"));
if (rb != null)
return rb.build();
return Response.ok("foo", "text/plain").build();
}
@Context
Request myRequest;
@GET
@Path("/fromField")
public Response doGet()
{
Response.ResponseBuilder rb = myRequest.evaluatePreconditions(new EntityTag("1"));
if (rb != null)
return rb.build();
return Response.ok("foo", "text/plain").build();
}
}
@Test
public void testIfMatchWithMatchingETag()
{
testIfMatchWithMatchingETag("");
testIfMatchWithMatchingETag("/fromField");
}
@Test
public void testIfMatchWithoutMatchingETag()
{
testIfMatchWithoutMatchingETag("");
testIfMatchWithoutMatchingETag("/fromField");
}
@Test
public void testIfMatchWildCard()
{
testIfMatchWildCard("");
testIfMatchWildCard("/fromField");
}
@Test
public void testIfNonMatchWithMatchingETag()
{
testIfNonMatchWithMatchingETag("");
testIfNonMatchWithMatchingETag("/fromField");
}
@Test
public void testIfNonMatchWithoutMatchingETag()
{
testIfNonMatchWithoutMatchingETag("");
testIfNonMatchWithoutMatchingETag("/fromField");
}
@Test
public void testIfNonMatchWildCard()
{
testIfNonMatchWildCard("");
testIfNonMatchWildCard("/fromField");
}
@Test
public void testIfMatchWithMatchingETag_IfNonMatchWithMatchingETag()
{
testIfMatchWithMatchingETag_IfNonMatchWithMatchingETag("");
testIfMatchWithMatchingETag_IfNonMatchWithMatchingETag("/fromField");
}
@Test
public void testIfMatchWithMatchingETag_IfNonMatchWithoutMatchingETag()
{
testIfMatchWithMatchingETag_IfNonMatchWithoutMatchingETag("");
testIfMatchWithMatchingETag_IfNonMatchWithoutMatchingETag("/fromField");
}
@Test
public void testIfMatchWithoutMatchingETag_IfNonMatchWithMatchingETag()
{
testIfMatchWithoutMatchingETag_IfNonMatchWithMatchingETag("");
testIfMatchWithoutMatchingETag_IfNonMatchWithMatchingETag("/fromField");
}
@Test
public void testIfMatchWithoutMatchingETag_IfNonMatchWithoutMatchingETag()
{
testIfMatchWithoutMatchingETag_IfNonMatchWithoutMatchingETag("");
testIfMatchWithoutMatchingETag_IfNonMatchWithoutMatchingETag("/fromField");
}
////////////
public void testIfMatchWithMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "\"1\"");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWithoutMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "\"2\"");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(412, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWildCard(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "*");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfNonMatchWithMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_NONE_MATCH, "\"1\"");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
Assert.assertEquals("1", response.getHeaders().getFirst(HttpHeaderNames.ETAG));
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfNonMatchWithoutMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_NONE_MATCH, "2");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfNonMatchWildCard(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_NONE_MATCH, "*");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
Assert.assertEquals("1", response.getHeaders().getFirst(HttpHeaderNames.ETAG));
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWithMatchingETag_IfNonMatchWithMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "1");
request.header(HttpHeaderNames.IF_NONE_MATCH, "1");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(304, response.getStatus());
Assert.assertEquals("1", response.getHeaders().getFirst(HttpHeaderNames.ETAG));
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWithMatchingETag_IfNonMatchWithoutMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "1");
request.header(HttpHeaderNames.IF_NONE_MATCH, "2");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(200, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWithoutMatchingETag_IfNonMatchWithMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "2");
request.header(HttpHeaderNames.IF_NONE_MATCH, "1");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(412, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void testIfMatchWithoutMatchingETag_IfNonMatchWithoutMatchingETag(String fromField)
{
ClientRequest request = new ClientRequest(generateURL("/etag" + fromField));
request.header(HttpHeaderNames.IF_MATCH, "2");
request.header(HttpHeaderNames.IF_NONE_MATCH, "2");
try
{
ClientResponse<?> response = request.get();
Assert.assertEquals(412, response.getStatus());
shutdownConnections(request);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
private void shutdownConnections(ClientRequest request)
{
ApacheHttpClient4Executor executor = (ApacheHttpClient4Executor) request.getExecutor();
executor.getHttpClient().getConnectionManager().shutdown();
// try
// {
// request.getExecutor().close();
// } catch (Exception e)
// {
// throw new RuntimeException(e);
// }
}
}
| |
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gapid.image;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gapid.proto.image.Image;
import com.google.gapid.proto.stream.Stream;
import com.google.gapid.util.Streams;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.DPIUtil;
import java.util.Set;
/**
* Utilities to deal with images.
*/
public class Images {
public static final Image.Format FMT_RGBA_U8_NORM = Image.Format.newBuilder()
.setUncompressed(Image.FmtUncompressed.newBuilder().setFormat(Streams.FMT_RGBA_U8_NORM))
.build();
public static final Image.Format FMT_DEPTH_U8_NORM = Image.Format.newBuilder()
.setUncompressed(Image.FmtUncompressed.newBuilder().setFormat(Streams.FMT_DEPTH_U8_NORM))
.build();
public static final Image.Format FMT_RGBA_FLOAT = Image.Format.newBuilder()
.setUncompressed(Image.FmtUncompressed.newBuilder().setFormat(Streams.FMT_RGBA_FLOAT))
.build();
public static final Image.Format FMT_LUMINANCE_FLOAT = Image.Format.newBuilder()
.setUncompressed(Image.FmtUncompressed.newBuilder().setFormat(Streams.FMT_LUMINANCE_FLOAT))
.build();
public static final Image.Format FMT_DEPTH_FLOAT = Image.Format.newBuilder()
.setUncompressed(Image.FmtUncompressed.newBuilder().setFormat(Streams.FMT_DEPTH_FLOAT))
.build();
public static final Set<Stream.Channel> COLOR_CHANNELS = ImmutableSet.of(
Stream.Channel.Red, Stream.Channel.Green, Stream.Channel.Blue, Stream.Channel.Alpha,
Stream.Channel.Luminance, Stream.Channel.ChromaU, Stream.Channel.ChromaV);
public static final Set<Stream.Channel> DEPTH_CHANNELS = ImmutableSet.of(Stream.Channel.Depth);
private Images() {
}
public static ImageData createImageData(int width, int height, boolean hasAlpha) {
ImageData result =
new ImageData(width, height, 24, new PaletteData(0xFF0000, 0x00FF00, 0x0000FF));
result.alphaData = hasAlpha ? new byte[width * height] : null;
return result;
}
/**
* Auto scales the given image to the devices DPI setting.
*/
public static org.eclipse.swt.graphics.Image createAutoScaledImage(
Device device, ImageData data) {
return new org.eclipse.swt.graphics.Image(device, data);
}
/**
* Auto scales the given image to the devices DPI setting.
*/
public static org.eclipse.swt.graphics.Image createAutoScaledImage(
ResourceManager resources, ImageData data) {
return resources.createImage(ImageDescriptor.createFromImageData(data));
}
public static org.eclipse.swt.graphics.Image createNonScaledImage(Device device, ImageData data) {
return new org.eclipse.swt.graphics.Image(device,
new DPIUtil.AutoScaleImageDataProvider(device, data, DPIUtil.getDeviceZoom()));
}
public static org.eclipse.swt.graphics.Image createNonScaledImage(
ResourceManager resources, ImageData data) {
return resources.createImage(new ImageDescriptor() {
@Override
public org.eclipse.swt.graphics.Image createImage(boolean ignored, Device device) {
return createNonScaledImage(device, data);
}
@Override
public ImageData getImageData() {
throw new AssertionError();
}
});
}
public static Point getSize(org.eclipse.swt.graphics.Image image) {
Rectangle bounds = image.getBounds();
return new Point(bounds.width, bounds.height);
}
public static ListenableFuture<ImageData> noAlpha(ListenableFuture<ImageData> image) {
return Futures.transform(image, data -> {
data.alphaData = null;
return data;
});
}
public static Image.Format getFormatToRequest(Image.Format format) {
boolean color = isColorFormat(format);
int channels = getChannelCount(format, color ? COLOR_CHANNELS : DEPTH_CHANNELS);
boolean is8bit = are8BitsEnough(format, color ? COLOR_CHANNELS : DEPTH_CHANNELS);
if (is8bit) {
return color ? FMT_RGBA_U8_NORM : FMT_DEPTH_U8_NORM;
} else if (channels == 1) {
return color ? FMT_LUMINANCE_FLOAT : FMT_DEPTH_FLOAT;
} else {
return FMT_RGBA_FLOAT;
}
}
public static int getChannelCount(Image.Format format, Set<Stream.Channel> interestedChannels) {
switch (format.getFormatCase()) {
case UNCOMPRESSED:
return getChannelCount(format.getUncompressed().getFormat(), interestedChannels);
case ETC2_R_U11_NORM:
case ETC2_R_S11_NORM:
return 1;
case ETC2_RG_U11_NORM:
case ETC2_RG_S11_NORM:
return 2;
case ATC_RGB_AMD:
case ETC1_RGB_U8_NORM:
case ETC2_RGB_U8_NORM:
case S3_DXT1_RGB:
return 3;
case ASTC:
case ATC_RGBA_EXPLICIT_ALPHA_AMD:
case ATC_RGBA_INTERPOLATED_ALPHA_AMD:
case ETC2_RGBA_U8_NORM:
case ETC2_RGBA_U8U8U8U1_NORM:
case PNG:
case S3_DXT1_RGBA:
case S3_DXT3_RGBA:
case S3_DXT5_RGBA:
return 4;
default:
return 0;
}
}
public static int getChannelCount(Stream.Format format, Set<Stream.Channel> interestedChannels) {
int result = 0;
for (Stream.Component c : format.getComponentsList()) {
if (interestedChannels.contains(c.getChannel())) {
result++;
}
}
return result;
}
public static boolean are8BitsEnough(
Image.Format format, Set<Stream.Channel> interestedChannels) {
switch (format.getFormatCase()) {
case UNCOMPRESSED:
return are8BitsEnough(format.getUncompressed().getFormat(), interestedChannels);
default:
// All Compressed formats can fully be represented as 8 bits (at this time).
return true;
}
}
public static boolean are8BitsEnough(
Stream.Format format, Set<Stream.Channel> interestedChannels) {
for (Stream.Component c : format.getComponentsList()) {
if (interestedChannels.contains(c.getChannel()) && !are8BitsEnough(c.getDataType())) {
return false;
}
}
return true;
}
public static boolean are8BitsEnough(Stream.DataType type) {
switch (type.getKindCase()) {
case INTEGER:
return type.getInteger().getBits() <= (type.getSigned() ? 7 : 8);
default:
// TODO: some small floats could actually be represented as 8bit...?
return false;
}
}
public static boolean isColorFormat(Image.Format format) {
switch (format.getFormatCase()) {
case UNCOMPRESSED: return isColorFormat(format.getUncompressed().getFormat());
default: return true; // Compressed images have RGBA converters.
}
}
public static boolean isColorFormat(Stream.Format format) {
for (Stream.Component c : format.getComponentsList()) {
if (!COLOR_CHANNELS.contains(c.getChannel())) {
return false;
}
}
return true;
}
/**
* Image formats handled by the UI.
*/
public static enum Format {
Color8(FMT_RGBA_U8_NORM, 4 * 1) {
@Override
protected ArrayImageBuffer build(int width, int height, byte[] data) {
return new ArrayImageBuffer.RGBA8ImageBuffer(width, height, data);
}
},
Depth8(FMT_DEPTH_U8_NORM, 1 *1) {
@Override
protected ArrayImageBuffer build(int width, int height, byte[] data) {
return new ArrayImageBuffer.Luminance8ImageBuffer(width, height, data);
}
},
ColorFloat(FMT_RGBA_FLOAT, 4 * 4) {
@Override
protected ArrayImageBuffer build(int width, int height, byte[] data) {
return new ArrayImageBuffer.RGBAFloatImageBuffer(width, height, data);
}
},
DepthFloat(FMT_DEPTH_FLOAT, 1 * 4) {
@Override
protected ArrayImageBuffer build(int width, int height, byte[] data) {
return new ArrayImageBuffer.LuminanceFloatImageBuffer(width, height, data);
}
},
LuminanceFloat(FMT_LUMINANCE_FLOAT, 1 * 4) {
@Override
protected ArrayImageBuffer build(int width, int height, byte[] data) {
return new ArrayImageBuffer.LuminanceFloatImageBuffer(width, height, data);
}
};
public final Image.Format format;
public final int pixelSize;
private Format(Image.Format format, int pixelSize) {
this.format = format;
this.pixelSize = pixelSize;
}
public static Format from(Image.Format format) {
boolean color = isColorFormat(format);
int channels = getChannelCount(format, color ? COLOR_CHANNELS : DEPTH_CHANNELS);
boolean is8bit = are8BitsEnough(format, color ? COLOR_CHANNELS : DEPTH_CHANNELS);
if (is8bit) {
return color ? Color8 : Depth8;
} else if (channels == 1) {
return color ? LuminanceFloat : DepthFloat;
} else {
return ColorFloat;
}
}
public ArrayImageBuffer.Builder builder(int width, int height) {
return new ArrayImageBuffer.Builder(width, height, pixelSize) {
@Override
protected ArrayImageBuffer build() {
return Format.this.build(width, height, data);
}
};
}
protected abstract ArrayImageBuffer build(int width, int height, byte[] data);
}
}
| |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.core.dsl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.springframework.cloud.dataflow.core.dsl.GraphGeneratorVisitor.Context.TransitionTarget;
import org.springframework.cloud.dataflow.core.dsl.graph.Graph;
import org.springframework.cloud.dataflow.core.dsl.graph.Link;
import org.springframework.cloud.dataflow.core.dsl.graph.Node;
/**
* Visitor that produces a Graph representation of a parsed task definition. This is
* suprisingly complicated due to the ability to use labels.
*
* @author Andy Clement
*/
public class GraphGeneratorVisitor extends TaskVisitor {
private int nextNodeId = 0;
// As the visit proceeds different contexts are entered/exited - into a
// flow, into a split, etc.
private Stack<GraphGeneratorVisitor.Context> contexts = new Stack<>();
// The sequences built during the visit
private List<GraphGeneratorVisitor.Sequence> sequences = new ArrayList<>();
// Which sequence is currently being visited
private int currentSequence;
// When visiting transitions, this is the id of the task app node most
// recently visited
private String currentTaskAppId;
private Map<String, Node> existingNodesToReuse;
public Graph getGraph() {
if (sequences.size() == 0) {
List<Node> nodes = new ArrayList<>();
List<Link> links = new ArrayList<>();
nodes.add(new Node("0", "START"));
nodes.add(new Node("1", "END"));
links.add(new Link("0", "1"));
return new Graph(nodes, links);
}
else {
GraphGeneratorVisitor.Sequence s = sequences.get(0);
Graph g = new Graph(s.nodes, s.links);
return g;
}
}
private String nextId() {
return Integer.toString(nextNodeId++);
}
@Override
public boolean preVisitSequence(LabelledTaskNode firstNode, int sequenceNumber) {
Node sequenceStartNode = new Node(nextId(), "START");
currentSequence = sequenceNumber;
sequences.add(new Sequence(sequenceNumber, firstNode.getLabelString(), sequenceStartNode));
contexts.push(new Context(true, false, sequenceStartNode.id, null));
return true;
}
@Override
public void postVisitSequence(LabelledTaskNode firstNode, int sequenceNumber) {
String endId = nextId();
Node endNode = new Node(endId, "END");
addLinks(endId);
addNode(endNode);
contexts.pop();
}
private void addLink(Link link) {
sequences.get(currentSequence).links.add(link);
}
private void addNode(Node node) {
sequences.get(currentSequence).nodes.add(node);
}
private void addLinks(String target) {
List<String> openNodes = currentContext().getDanglingNodes();
for (int i = 0; i < openNodes.size(); i++) {
addLink(new Link(openNodes.get(i), target));
}
}
@Override
public void endVisit() {
if (sequences.size() > 0) {
GraphGeneratorVisitor.Sequence mainSequence = sequences.get(0);
// iterate until nothing left to do
int tooMany = 0;
while (!mainSequence.outstandingTransitions.isEmpty() && tooMany < 50) {
List<Context.TransitionTarget> nextTransitions = findNextTransitions(
mainSequence.outstandingTransitions);
mainSequence.outstandingTransitions.removeAll(nextTransitions);
GraphGeneratorVisitor.Sequence sequence = findSequence(nextTransitions.get(0).label);
if (sequence == null) {
throw new IllegalStateException("Out of flow transition? " + nextTransitions.get(0));
}
inline(mainSequence, sequence, nextTransitions);
// Some transitions might be satisfiable now
Iterator<TransitionTarget> iter = mainSequence.outstandingTransitions.iterator();
while (iter.hasNext()) {
TransitionTarget transitionTarget = iter.next();
FlowNode flowInWhichTransitionOccurring = transitionTarget.flow;
Map<String, Node> candidates = mainSequence.labeledNodesInEachFlow
.get(flowInWhichTransitionOccurring);
for (Map.Entry<String, Node> candidate : candidates.entrySet()) {
if (candidate.getKey().equals(transitionTarget.label)) {
// This is the right one!
mainSequence.links.add(new Link(transitionTarget.nodeId, candidate.getValue().id,
transitionTarget.onState));
iter.remove();
}
}
}
tooMany++;
}
}
}
/**
* Pick a transition and find if there are any others with the same target. If so
* return them all, otherwise just return the picked one.
*
* @param transitions a list of transitions that might share common targets
* @return a single transition (if there are any) and any others with the same target
*/
private List<Context.TransitionTarget> findNextTransitions(List<Context.TransitionTarget> transitions) {
if (transitions.size() == 0) {
return Collections.emptyList();
}
List<Context.TransitionTarget> sameTarget = new ArrayList<>();
sameTarget.add(transitions.get(0));
for (int i = 1; i < transitions.size(); i++) {
Context.TransitionTarget tt = transitions.get(i);
if (transitions.get(0).flow.equals(tt.flow) && transitions.get(0).label.equals(tt.label)) {
sameTarget.add(tt);
}
}
return sameTarget;
}
private GraphGeneratorVisitor.Sequence findSequence(String label) {
for (GraphGeneratorVisitor.Sequence sequence : sequences) {
if (label.equals(sequence.label)) {
return sequence;
}
}
return null;
}
private void inline(GraphGeneratorVisitor.Sequence mainSequence, GraphGeneratorVisitor.Sequence sequence,
List<Context.TransitionTarget> transitionTargets) {
// Record a map of ids in the sequence to the new node ids to use when creating
// new links
Map<String, String> nodeIds = new HashMap<>();
// Create copies of all the nodes - except the START and END
Node startNode = sequence.nodes.get(0);
Node endNode = sequence.nodes.get(sequence.nodes.size() - 1);
for (int i = 1; i < (sequence.nodes.size() - 1); i++) {
Node n = sequence.nodes.get(i);
Node newNode = new Node(nextId(), n.name, n.properties);
nodeIds.put(n.id, newNode.id);
mainSequence.nodes.add(newNode);
}
// Now copy links
for (int i = 0; i < sequence.links.size(); i++) {
Link existingLink = sequence.links.get(i);
String existingLinkFrom = existingLink.from;
String existingLinkTo = existingLink.to;
Link newLink = null;
if (existingLinkFrom.equals(startNode.id)) {
// This link need replacing with links from the transition points to the
// same
// target
for (Context.TransitionTarget tt : transitionTargets) {
newLink = new Link(tt.nodeId, nodeIds.get(existingLinkTo), tt.onState);
mainSequence.links.add(newLink);
}
}
else if (existingLinkTo.equals(endNode.id)) {
// This link needs replacing with links from the final copied node in the
// sequence
// to the end node in the main sequence
Context.TransitionTarget tt = transitionTargets.get(0);
// assert all the transitionTargets have the same lastNodeId
String finalNodeInMainSequence = tt.lastNodeId;
List<Link> newLinks = new ArrayList<>();
for (Link l : mainSequence.links) {
if (l.from.equals(finalNodeInMainSequence)) {
newLinks.add(new Link(nodeIds.get(existingLinkFrom), l.to, l.getTransitionName()));
}
}
mainSequence.links.addAll(newLinks);
}
else {
newLink = new Link(nodeIds.get(existingLinkFrom), nodeIds.get(existingLinkTo),
existingLink.getTransitionName());
mainSequence.links.add(newLink);
}
}
// After inlining the sequence, the mainSequence may have inherited new
// outstanding transitions
List<Context.TransitionTarget> rewrittenTransitions = new ArrayList<>();
for (Context.TransitionTarget looseEnd : sequence.outstandingTransitions) {
Context.TransitionTarget tt = new Context.TransitionTarget(nodeIds.get(looseEnd.nodeId), looseEnd.onState,
looseEnd.label);
// They should have the same 'flow' as the sequence they are injected into
tt.flow = transitionTargets.get(0).flow;
tt.lastNodeId = transitionTargets.get(0).lastNodeId;// nodeIds.get(looseEnd.lastNodeId);
rewrittenTransitions.add(tt);
}
mainSequence.outstandingTransitions.addAll(rewrittenTransitions);
// The copy of this secondary sequence is being inserted into a particular flow.
FlowNode flowBeingInsertedInto = transitionTargets.get(0).flow;
Map<String, Node> relevantFlowMapToUpdate = mainSequence.labeledNodesInEachFlow.get(flowBeingInsertedInto);
Map<FlowNode, Map<String, Node>> labeledNodesInSequenceBeingInlined = sequence.labeledNodesInEachFlow;
FlowNode primaryFlowInSequenceBeingInlined = sequence.primaryFlow;
for (Map.Entry<FlowNode, Map<String, Node>> entry : labeledNodesInSequenceBeingInlined.entrySet()) {
if (entry.getKey() == primaryFlowInSequenceBeingInlined) {
// these should be remapped
for (Map.Entry<String, Node> entry2 : entry.getValue().entrySet()) {
Node n2 = new Node(nodeIds.get(entry2.getKey()), entry2.getValue().name);
n2.setLabel(entry2.getValue().getLabel());
relevantFlowMapToUpdate.put(entry2.getKey(), n2);
}
}
else {
// these can just be copied direct
Map<String, Node> newMap = new HashMap<>();
for (Map.Entry<String, Node> entry2 : entry.getValue().entrySet()) {
Node n2 = new Node(nodeIds.get(entry2.getKey()), entry2.getValue().name);
n2.setLabel(entry2.getValue().getLabel());
newMap.put(entry2.getKey(), n2);
}
mainSequence.labeledNodesInEachFlow.put(entry.getKey(), newMap);
}
}
}
@Override
public boolean preVisit(SplitNode split) {
List<String> open = currentContext().getDanglingNodes();
String startId = (open.size() == 0 ? currentContext().startNodeId : open.get(0));
// If there are multiple open nodes, we need a sync node !
if (open.size() > 1) {
String syncId = nextId();
Node node = new Node(syncId, "SYNC");
addNode(node);
for (String openid : open) {
addLink(new Link(openid, syncId));
}
startId = syncId;
}
contexts.push(new Context(false, true, startId, split));
return true;
}
@Override
public void postVisit(SplitNode split) {
List<String> openAtEndOfFlow = currentContext().getDanglingNodes();
contexts.pop();
currentContext().addDanglingNodes(true, openAtEndOfFlow);
}
@Override
public boolean preVisit(FlowNode flow) {
contexts.push(new Context(true, false, currentContext().startNodeId, flow));
currentSequence().primaryFlow = flow;
return true;
}
@Override
public void postVisit(FlowNode flow) {
// What label references were not resolved within the flow?
List<Context.TransitionTarget> transitionTargets = currentContext().getTransitionTargets();
// For all outstanding transitions, mark them indicating which flow they came from
// and the last node of that flow. Thus when they are processed later, after the
// transition completes it knows where to join the output to.
for (Context.TransitionTarget tt : transitionTargets) {
tt.lastNodeId = currentContext().getDanglingNodes().get(0);
tt.flow = flow;
}
sequences.get(currentSequence).outstandingTransitions.addAll(transitionTargets);
currentSequence().labeledNodesInEachFlow.put(flow, currentContext().nodesWithLabels);
List<String> openAtEndOfFlow = currentContext().getDanglingNodes();
List<String> otherExitNodes = currentContext().otherExits;
contexts.pop();
currentContext().addDanglingNodes(false, openAtEndOfFlow);
currentContext().addDanglingNodes(false, otherExitNodes);
}
private Node findOrMakeNode(String name) {
Node node = existingNodesToReuse.get(name);
if (node == null) {
node = new Node(nextId(), name);
existingNodesToReuse.put(name, node);
addNode(node);
}
return node;
}
@Override
public void visit(TransitionNode transition) {
if (transition.isTargetApp()) {
if (transition.isSpecialTransition()) {
if (transition.isFailTransition()) {
Node failNode = findOrMakeNode("$FAIL");
addLink(new Link(currentTaskAppId, failNode.id, transition.getStatusToCheck()));
}
else if (transition.isEndTransition()) {
Node endNode = findOrMakeNode("$END");
addLink(new Link(currentTaskAppId, endNode.id, transition.getStatusToCheck()));
}
}
else {
String key = toKey(transition.getTargetApp());
Node n = existingNodesToReuse.get(key);
boolean isCreated = false;
if (n == null) {
String nextId = nextId();
n = new Node(nextId, transition.getTargetApp().getName(),
toMap(transition.getTargetApp().getArguments()));
if (transition.getTargetApp().hasLabel()) {
n.setLabel(transition.getTargetApp().getLabelString());
}
existingNodesToReuse.put(key, n);
addNode(n);
isCreated = true;
}
addLink(new Link(currentTaskAppId, n.id, transition.getStatusToCheck()));
if (isCreated) {
if (currentContext().isFlow) {
currentContext().addOtherExit(n.id);
}
else {
currentContext().addDanglingNodes(false, n.id);
}
}
}
}
else {
// Check if it is a transition to something labeled earlier in this flow
Node existingNode = currentContext().getNodeLabeled(transition.getTargetLabel());
if (existingNode != null) {
addLink(new Link(currentTaskAppId, existingNode.id, transition.getStatusToCheck()));
}
else {
// Record a new transition attempted
currentContext().addTransitionTarget(currentTaskAppId, transition.getStatusToCheck(),
transition.getTargetLabel());
}
}
}
private Map<String, String> toMap(ArgumentNode[] arguments) {
if (arguments == null) {
return null;
}
Map<String, String> argumentsMap = new HashMap<>();
for (ArgumentNode argument : arguments) {
argumentsMap.put(argument.getName(), argument.getValue());
}
return argumentsMap;
}
/**
* Create a unique map key for a given target app and options.
*/
private String toKey(TaskAppNode targetApp) {
StringBuilder key = new StringBuilder();
if (targetApp.hasLabel()) {
key.append(targetApp.getLabel()).append(">");
}
key.append(targetApp.getName());
for (Map.Entry<String, String> argument : targetApp.getArgumentsAsMap().entrySet()) {
key.append(":").append(argument.getKey()).append("=").append(argument.getValue());
}
return key.toString();
}
public GraphGeneratorVisitor.Context currentContext() {
return contexts.peek();
}
public GraphGeneratorVisitor.Context parentContext() {
if (contexts.size() < 2) {
return null;
}
else {
return contexts.get(contexts.size() - 2);
}
}
public Sequence currentSequence() {
return sequences.get(currentSequence);
}
@Override
public void visit(TaskAppNode taskApp) {
String nextId = nextId();
currentTaskAppId = nextId;
Node node = new Node(nextId, taskApp.getName(), toMap(taskApp.getArguments()));
addNode(node);
if (taskApp.hasLabel()) {
node.setLabel(taskApp.getLabelString());
currentContext().addNodeWithLabel(taskApp.getLabelString(), node);
}
if (currentContext().isFlow) {
// Are there any outstanding transitions that need to be connected
// to this?
if (taskApp.hasLabel()) {
// If this one has a label, try to connect hanging transitions to it
for (Iterator<Context.TransitionTarget> iterator = currentContext().getTransitionTargets()
.iterator(); iterator.hasNext();) {
Context.TransitionTarget tt = iterator.next();
if (tt.label.equals(taskApp.getLabelString())) {
// Target found!
addLink(new Link(tt.nodeId, nextId, tt.onState));
iterator.remove();
}
}
}
List<String> danglingNodes = currentContext().getDanglingNodes();
if (danglingNodes.size() == 0) {
// This app is the first in the flow and will create the first dangling
// node
addLink(new Link(currentContext().startNodeId, nextId));
}
else {
// Everything outstanding needs joining to this node
for (int i = 0; i < danglingNodes.size(); i++) {
addLink(new Link(danglingNodes.get(i), nextId));
}
}
currentContext().addDanglingNodes(true, nextId);
}
else if (currentContext().isSplit) {
// Any flow containing this split can transition to this split if it
// is labeled. This code
// isn't complete as it will only link it to the first one in the
// split, when it needs to
// link to all of them. Or we create a sync node and link to that.
if (currentContext().containingNode.hasLabel() && (parentContext() != null && parentContext().isFlow)) {
// A surrounding flow can target a split with a transition
// target
}
// If visiting a taskapp in a split, it means there is no
// surrounding flow
addLink(new Link(currentContext().startNodeId, nextId));
currentContext().addDanglingNodes(false, nextId);
}
existingNodesToReuse = (currentContext().isFlow ? currentContext().extraNodes : new HashMap<>());
}
// Gathers knowledge about a sequence during visiting
static class Sequence {
// Which sequence number is this
final int sequenceNumber;
// Name of this sequence (all but the first must have a label)
final String label;
// Nodes in this sequence
final List<Node> nodes = new ArrayList<>();
// Links in this sequence
final List<Link> links = new ArrayList<>();
// Transitions made from inside this sequence which are not satisfied
final List<Context.TransitionTarget> outstandingTransitions = new ArrayList<>();
final Map<FlowNode, Map<String, Node>> labeledNodesInEachFlow = new HashMap<>();
FlowNode primaryFlow;
Sequence(int sequenceNumber, String label, Node sequenceStartNode) {
this.sequenceNumber = sequenceNumber;
this.label = label;
nodes.add(sequenceStartNode);
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Node n : nodes) {
s.append("[").append(n.id).append(":").append(n.name).append("]");
}
for (Link l : links) {
s.append("[" + (l.getTransitionName() == null ? "" : l.getTransitionName() + ":") + l.from + "-" + l.to
+ "]");
}
s.append(" transitions:").append(outstandingTransitions);
s.append(" flowLabelsMap:").append(labeledNodesInEachFlow);
return s.toString();
}
}
static class Context {
// Nodes in this sequence that are labeled are recorded here
final Map<String, Node> nodesWithLabels = new HashMap<>();
// When a transition branch is taken to some other app within a flow,
// this records the app node that must be joined to the exit path
// from the entire flow.
public List<String> otherExits = new ArrayList<>();
// For forward references this keeps track of them so that they can be
// filled in later. The reference must be satisfied within the same flow
// or by a separate sequence. If that secondary sequence routes back
// to the primary, it must be within the same flow!
public List<Context.TransitionTarget> transitionTargets = new ArrayList<>();
public Map<String, Node> extraNodes = new HashMap<>();
// Within a flow, transitions to the 'same job' would share a node
// target, as would all transitions to an $END or $FAIL node. This
// keeps track of what has been created so it can be reused.
Map<String, Node> nodesSharedInFlow = new LinkedHashMap<String, Node>();
// When processing apps in a real Flow or Split, this is the Ast node
// for that Flow or Split.
LabelledTaskNode containingNode;
// Tracking what kind of context we are in
boolean isFlow = false;
boolean isSplit = false;
// Id of the first node in this context (start of a flow, start of a
// split)
private String startNodeId;
// As a flow/split is processed gradually we accumulate dangling nodes,
// those that need connecting to whatever comes next. For a flow there might
// just be one, but for a split multiple.
private List<String> currentDanglingNodes = new ArrayList<>();
Context(boolean isFlow, boolean isSplit, String startNodeId, LabelledTaskNode split) {
this.isFlow = isFlow;
this.isSplit = isSplit;
this.startNodeId = startNodeId;
this.containingNode = split;
}
public void addDanglingNodes(boolean replaceExisting, String... is) {
if (replaceExisting) {
currentDanglingNodes.clear();
}
for (String i : is) {
currentDanglingNodes.add(i);
}
}
public void addDanglingNodes(boolean replaceExisting, List<String> newDanglingNodes) {
if (replaceExisting) {
currentDanglingNodes.clear();
}
currentDanglingNodes.addAll(newDanglingNodes);
}
public List<String> getDanglingNodes() {
return currentDanglingNodes;
}
public void clearDanglingNodes() {
currentDanglingNodes.clear();
}
public void addTransitionTarget(String fromNodeId, String fromOnState, String targetLabel) {
Context.TransitionTarget tt = new TransitionTarget(fromNodeId, fromOnState, targetLabel);
transitionTargets.add(tt);
}
public List<TransitionTarget> getTransitionTargets() {
return this.transitionTargets;
}
public void addOtherExit(String nextId) {
otherExits.add(nextId);
}
public Node getNodeLabeled(String label) {
return nodesWithLabels.get(label);
}
public void addNodeWithLabel(String label, Node node) {
nodesWithLabels.put(label, node);
}
static class TransitionTarget {
// The node to transition from
String nodeId;
// The state to be checked that would cause this transition
String onState;
// The label to be connected to
String label;
// Last node in flow, when joining things up, anywhere this got
// joined to, the inserted stuff will need to be joined to
String lastNodeId;
// Which flow was this transition in
FlowNode flow;
TransitionTarget(String fromNodeId, String fromOnState, String targetLabel) {
this.nodeId = fromNodeId;
this.onState = fromOnState;
this.label = targetLabel;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(nodeId).append(":").append(onState).append("->").append(label);
return s.toString();
}
}
}
}
| |
package net.didion.jwnl.utilities;
import net.didion.jwnl.JWNL;
import net.didion.jwnl.data.*;
import net.didion.jwnl.dictionary.AbstractCachingDictionary;
import net.didion.jwnl.dictionary.Dictionary;
import net.didion.jwnl.dictionary.database.ConnectionManager;
import net.didion.jwnl.util.MessageLog;
import net.didion.jwnl.util.MessageLogLevel;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* DictionaryToDatabase is used to transfer a WordNet file database into an actual
* database structure.
* @author brett
*
*/
public class DictionaryToDatabase
{
/**
* Our message log.
*/
private static final MessageLog LOG;
private static int INTERNAL_ID = 0;
private static long TIME = 0L;
/**
* The database connection.
*/
private Connection connection;
/**
* Mapping of database id's to synset offset id's. 1 to 1.
*/
private Map idToSynsetOffset;
/**
* Mapping of synset offset id's to database id's. 1:1.
*/
private Map synsetOffsetToId;
/**
* Run the program, requires 4 arguments. See DictionaryToDatabase.txt for more documentation.
* @param args
*/
public static void main(String args[])
{
final String basePath = "/home/xavi/workspace/___nlp___/wordnet/jwnl14-rc2/";
args = new String[4];
args[0]= basePath + "config/file_properties.xml";
args[1]= basePath + "sql/create.sql";
args[2]= "com.mysql.jdbc.Driver";
args[3]= "jdbc:mysql://localhost/jwnl?user=root";
if(args.length < 4)
{
System.out.println("java net.didion.jwnl.utilities.DictionaryToDatabase <property file> <create tables script> <driver class> <connection url> [username [password]]");
System.exit(-1);
}
try
{
JWNL.initialize(new FileInputStream(args[0]));
}
catch(Exception ex)
{
ex.printStackTrace();
System.exit(-1);
}
Connection conn = null;
try
{
String scriptFileName = args[1];
ConnectionManager mgr = new ConnectionManager(args[2], args[3], args.length <= 4 ? null : args[4], args.length <= 5 ? null : args[5]);
conn = mgr.getConnection();
DictionaryToDatabase d2d = new DictionaryToDatabase(conn);
// d2d.createTables(scriptFileName);
d2d.insertData();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(-1);
}
finally
{
if(conn != null)
try
{
conn.close();
}
catch(SQLException ex) {
ex.printStackTrace();
}
}
}
private static synchronized int nextId()
{
INTERNAL_ID++;
if(LOG.isLevelEnabled(MessageLogLevel.DEBUG) && INTERNAL_ID % 1000 == 0)
{
long temp = System.currentTimeMillis();
LOG.log(MessageLogLevel.DEBUG, "inserted " + INTERNAL_ID + "th entry");
LOG.log(MessageLogLevel.DEBUG, "free memory: " + Runtime.getRuntime().freeMemory());
LOG.log(MessageLogLevel.DEBUG, "time: " + (temp - TIME));
TIME = System.currentTimeMillis();
}
return INTERNAL_ID;
}
/**
* Create a new DictionaryToDatabase with a database connection. JWNL already initialized.
* @param conn - the database connection
*/
public DictionaryToDatabase(Connection conn)
{
idToSynsetOffset = new HashMap();
synsetOffsetToId = new HashMap();
connection = conn;
((AbstractCachingDictionary)Dictionary.getInstance()).setCachingEnabled(false);
}
/**
* Create the database tables.
* @param scriptFilePath - the sql script filename
* @throws java.io.IOException
* @throws java.sql.SQLException
*/
public void createTables(String scriptFilePath)
throws IOException, SQLException
{
LOG.log(MessageLogLevel.INFO, "creating tables");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(scriptFilePath)));
StringBuffer buf = new StringBuffer();
for(String line = reader.readLine(); line != null; line = reader.readLine())
{
line = line.trim();
if(line.length() <= 0)
continue;
buf.append(line);
if(line.endsWith(";"))
{
System.out.println(buf.toString());
connection.prepareStatement(buf.toString()).execute();
buf = new StringBuffer();
} else
{
buf.append(" ");
}
}
LOG.log(MessageLogLevel.INFO, "creating tables");
}
/**
* Inserts the data into the database. Iterates through the various POS,
* then stores all the index words, synsets, exceptions of that POS.
* @throws Exception
*/
public void insertData()
throws Exception
{
TIME = System.currentTimeMillis();
POS pos;
for(Iterator posItr = POS.getAllPOS().iterator(); posItr.hasNext(); LOG.log(MessageLogLevel.INFO, "done inserting data for pos " + pos))
{
pos = (POS)posItr.next();
LOG.log(MessageLogLevel.INFO, "inserting data for pos " + pos);
// storeIndexWords(Dictionary.getInstance().getIndexWordIterator(pos));
storeSynsets(Dictionary.getInstance().getSynsetIterator(pos));
storeIndexWordSynsets();
storeExceptions(Dictionary.getInstance().getExceptionIterator(pos));
idToSynsetOffset.clear();
synsetOffsetToId.clear();
}
}
/**
* Store all the index words.
* @param itr - the part of speech iterator
* @throws java.sql.SQLException
*/
private void storeIndexWords(Iterator itr)
throws SQLException
{
LOG.log(MessageLogLevel.INFO, "storing index words");
PreparedStatement iwStmt = connection.prepareStatement("INSERT INTO IndexWord VALUES(?,?,?)");
int count = 0;
do
{
if(!itr.hasNext()) {
break;
}
IndexWord iw = (IndexWord)itr.next();
int id = nextId();
iwStmt.setInt(1, id);
iwStmt.setString(2, iw.getLemma());
iwStmt.setString(3, iw.getPOS().getKey());
iwStmt.execute();
idToSynsetOffset.put(new Integer(id), iw.getSynsetOffsets());
if(count++ % 1000 == 0)
System.out.println(count);
} while(true);
}
/**
* Store all of the synsets in the database.
* @param itr
* @throws java.sql.SQLException
*/
private void storeSynsets(Iterator itr)
throws SQLException
{
PreparedStatement synsetStmt = connection.prepareStatement("INSERT INTO Synset VALUES(?,?,?,?,?)");
PreparedStatement synsetWordStmt = connection.prepareStatement("INSERT INTO SynsetWord VALUES(?,?,?,?)");
PreparedStatement synsetPointerStmt = connection.prepareStatement("INSERT INTO SynsetPointer VALUES(?,?,?,?,?,?,?)");
PreparedStatement synsetVerbFrameStmt = connection.prepareStatement("INSERT INTO SynsetVerbFrame VALUES(?,?,?,?)");
LOG.log(MessageLogLevel.INFO, "storing synsets");
int count = 0;
while(itr.hasNext())
{
if(count++ % 1000 == 0)
System.out.println("synset: " + count);
Synset synset = (Synset)itr.next();
int id = nextId();
synsetOffsetToId.put(new Long(synset.getOffset()), new Integer(id));
synsetStmt.setInt(1, id);
synsetStmt.setLong(2, synset.getOffset());
synsetStmt.setString(3, synset.getPOS().getKey());
synsetStmt.setBoolean(4, synset.isAdjectiveCluster());
synsetStmt.setString(5, synset.getGloss());
synsetStmt.execute();
Word words[] = synset.getWords();
synsetWordStmt.setInt(2, id);
synsetVerbFrameStmt.setInt(2, id);
for(int i = 0; i < words.length; i++)
{
int wordId = nextId();
synsetWordStmt.setInt(1, wordId);
synsetWordStmt.setString(3, words[i].getLemma());
synsetWordStmt.setInt(4, words[i].getIndex());
synsetWordStmt.execute();
if(!(words[i] instanceof Verb))
continue;
synsetVerbFrameStmt.setInt(4, words[i].getIndex());
int flags[] = ((Verb)words[i]).getVerbFrameIndicies();
for(int j = 0; j < flags.length; j++)
{
synsetVerbFrameStmt.setInt(1, nextId());
synsetVerbFrameStmt.setInt(3, flags[j]);
synsetVerbFrameStmt.execute();
}
}
Pointer pointers[] = synset.getPointers();
synsetPointerStmt.setInt(2, id);
int i = 0;
while(i < pointers.length)
{
synsetPointerStmt.setInt(1, nextId());
synsetPointerStmt.setString(3, pointers[i].getType().getKey());
synsetPointerStmt.setLong(4, pointers[i].getTargetOffset());
synsetPointerStmt.setString(5, pointers[i].getTargetPOS().getKey());
synsetPointerStmt.setInt(6, pointers[i].getSourceIndex());
synsetPointerStmt.setInt(7, pointers[i].getTargetIndex());
synsetPointerStmt.execute();
i++;
}
}
}
/**
* Store the index word synsets.
* @throws java.sql.SQLException
*/
private void storeIndexWordSynsets()
throws SQLException
{
LOG.log(MessageLogLevel.INFO, "storing index word synsets");
PreparedStatement iwsStmt = connection.prepareStatement("INSERT INTO IndexWordSynset VALUES(?,?,?)");
for(Iterator itr = idToSynsetOffset.entrySet().iterator(); itr.hasNext();)
{
Map.Entry entry = (Map.Entry)itr.next();
int iwId = ((Integer)entry.getKey()).intValue();
iwsStmt.setInt(2, iwId);
long offsets[] = (long[])entry.getValue();
int i = 0;
while(i < offsets.length)
{
Integer offset = (Integer)synsetOffsetToId.get(new Long(offsets[i]));
int synsetId = offset.intValue();
iwsStmt.setInt(1, nextId());
iwsStmt.setLong(3, synsetId);
iwsStmt.execute();
i++;
}
}
}
/**
* Store the exceptions file.
* @param itr
* @throws java.sql.SQLException
*/
private void storeExceptions(Iterator itr)
throws SQLException
{
LOG.log(MessageLogLevel.INFO, "storing exceptions");
PreparedStatement exStmt = connection.prepareStatement("INSERT INTO SynsetException VALUES(?,?,?,?)");
while(itr.hasNext())
{
Exc exc = (Exc)itr.next();
exStmt.setString(4, exc.getLemma());
Iterator excItr = exc.getExceptions().iterator();
while(excItr.hasNext())
{
exStmt.setInt(1, nextId());
exStmt.setString(2, exc.getPOS().getKey());
exStmt.setString(3, (String)excItr.next());
exStmt.execute();
}
}
}
static
{
LOG = new MessageLog(net.didion.jwnl.utilities.DictionaryToDatabase.class);
}
}
| |
package org.vasttrafik.wso2.carbon.community.api.beans;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotNull;
/**
*
* @author Lars Andersson
*
*/
public final class Topic {
private Long id = null;
private Integer categoryId = null;
private String categoryName = null;
@NotNull(message = "{topic.forum.notnull}")
private Integer forumId = null;
private String forumName = null;
@NotNull(message = "{topic.subject.notnull}")
private String subject = null;
private Date createDate = null;
private Date lastPostDate = null;
private Member createdBy = null;
private List<Tag> tags = new ArrayList<Tag>();
@NotNull(message = "{topic.posts.notnull}")
private List<Post> posts = new ArrayList<Post>();
private Post firstPost = null;
private Post lastPost = null;
private Date closedDate = null;
private Member closedBy = null;
private Short numberOfPosts = null;
private Short numberOfViews = null;
private Short numberOfAnswers = null;
private Long answeredByPostId = null;
private Boolean isDeleted = null;
/**
* Topic id
**/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
/**
* The forum this topic was created in
**/
public Integer getForumId() {
return forumId;
}
public void setForumId(Integer forumId) {
this.forumId = forumId;
}
public String getForumName() {
return forumName;
}
public void setForumName(String forumName) {
this.forumName = forumName;
}
/**
* Topic subject
**/
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
/**
* Date and time when the topic was created
**/
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* Date and time when the last post as posted to this topic
* This is only applicable from using view
**/
public Date getLastPostDate() {
return lastPostDate;
}
public void setLastPostDate(Date lastPostDate) {
this.lastPostDate = lastPostDate;
}
/**
* The user that created the topic
**/
public Member getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Member createdBy) {
this.createdBy = createdBy;
}
/**
* Tags for the topic
**/
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
/**
* Posts in the topic
**/
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
/**
* The last post in the forum
**/
public Post getFirstPost() {
return firstPost;
}
public void setFirstPost(Post firstPost) {
this.firstPost = firstPost;
}
/**
* The last post in the forum
**/
public Post getLastPost() {
return lastPost;
}
public void setLastPost(Post lastPost) {
this.lastPost = lastPost;
}
public Date getClosedDate() {
return closedDate;
}
public void setClosedDate(Date closedDate) {
this.closedDate = closedDate;
}
/**
* The user that created the topic
**/
public Member getClosedBy() {
return closedBy;
}
public void setClosedBy(Member closedBy) {
this.closedBy = closedBy;
}
public Short getNumberOfPosts() {
return numberOfPosts;
}
public void setNumberOfPosts(Short numberOfPosts) {
this.numberOfPosts = numberOfPosts;
}
public Short getNumberOfViews() {
return numberOfViews;
}
public void setNumberOfViews(Short numberOfViews) {
this.numberOfViews = numberOfViews;
}
public Short getNumberOfAnswers() {
return numberOfAnswers;
}
public void setNumberOfAnswers(Short numberOfAnswers) {
this.numberOfAnswers = numberOfAnswers;
}
public Long getAnsweredByPostId() {
return answeredByPostId;
}
public void setAnsweredByPostId(Long answeredByPostId) {
this.answeredByPostId = answeredByPostId;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Topic {\n");
sb.append(" id: ").append(id).append("\n");
sb.append(" categoryId: ").append(categoryId).append("\n");
sb.append(" categoryName: ").append(categoryName).append("\n");
sb.append(" forumId: ").append(forumId).append("\n");
sb.append(" forumName: ").append(forumName).append("\n");
sb.append(" subject: ").append(subject).append("\n");
sb.append(" createDate: ").append(createDate).append("\n");
sb.append(" createdBy: ").append(createdBy).append("\n");
sb.append(" tags: ").append(tags).append("\n");
sb.append(" posts: ").append(posts).append("\n");
sb.append(" firstPost: ").append(firstPost).append("\n");
sb.append(" lastPost: ").append(lastPost).append("\n");
sb.append(" numberOfPosts: ").append(numberOfPosts).append("\n");
sb.append(" numberOfViews: ").append(numberOfViews).append("\n");
sb.append(" numberOfAnswers: ").append(numberOfAnswers).append("\n");
sb.append("}\n");
return sb.toString();
}
}
| |
/*
* Copyright 2016-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.pcepio.types;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Objects;
import org.jboss.netty.buffer.ChannelBuffer;
import org.onosproject.pcepio.exceptions.PcepParseException;
import org.onosproject.pcepio.protocol.PcepVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
/**
* Provides LinkAttributesTlv.
*/
public class LinkAttributesTlv implements PcepValueType {
/*
* Reference :draft-dhodylee-pce-pcep-ls-01, section 9.2.8.2.
* 0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type=[TBD27] | Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
// Link Attributes Sub-TLVs (variable) //
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
private static final Logger log = LoggerFactory.getLogger(LinkAttributesTlv.class);
public static final short TYPE = (short) 65286;
short hLength;
public static final int TLV_HEADER_LENGTH = 4;
// LinkDescriptors Sub-TLVs (variable)
private List<PcepValueType> llLinkAttributesSubTLVs;
/**
* Constructor to initialize Link Attributes Sub TLVs.
*
* @param llLinkAttributesSubTLVs linked list of PcepValueType
*/
public LinkAttributesTlv(List<PcepValueType> llLinkAttributesSubTLVs) {
this.llLinkAttributesSubTLVs = llLinkAttributesSubTLVs;
}
/**
* Returns object of TE Link Attributes TLV.
*
* @param llLinkAttributesSubTLVs linked list of Link Attribute of Sub TLV
* @return object of LinkAttributesTlv
*/
public static LinkAttributesTlv of(final List<PcepValueType> llLinkAttributesSubTLVs) {
return new LinkAttributesTlv(llLinkAttributesSubTLVs);
}
/**
* Returns linked list of Link Attribute of Sub TLV.
*
* @return llLinkAttributesSubTLVs linked list of Link Attribute of Sub TLV
*/
public List<PcepValueType> getllLinkAttributesSubTLVs() {
return llLinkAttributesSubTLVs;
}
@Override
public PcepVersion getVersion() {
return PcepVersion.PCEP_1;
}
@Override
public short getType() {
return TYPE;
}
@Override
public short getLength() {
return hLength;
}
@Override
public int hashCode() {
return Objects.hash(llLinkAttributesSubTLVs.hashCode());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
/*
* Here we have a list of Tlv so to compare each sub tlv between the object
* we have to take a list iterator so one by one we can get each sub tlv object
* and can compare them.
* it may be possible that the size of 2 lists is not equal so we have to first check
* the size, if both are same then we should check for the subtlv objects otherwise
* we should return false.
*/
if (obj instanceof LinkAttributesTlv) {
int countObjSubTlv = 0;
int countOtherSubTlv = 0;
boolean isCommonSubTlv = true;
LinkAttributesTlv other = (LinkAttributesTlv) obj;
Iterator<PcepValueType> objListIterator = ((LinkAttributesTlv) obj).llLinkAttributesSubTLVs.iterator();
countObjSubTlv = ((LinkAttributesTlv) obj).llLinkAttributesSubTLVs.size();
countOtherSubTlv = other.llLinkAttributesSubTLVs.size();
if (countObjSubTlv != countOtherSubTlv) {
return false;
} else {
while (objListIterator.hasNext() && isCommonSubTlv) {
PcepValueType subTlv = objListIterator.next();
isCommonSubTlv = Objects.equals(llLinkAttributesSubTLVs.contains(subTlv),
other.llLinkAttributesSubTLVs.contains(subTlv));
}
return isCommonSubTlv;
}
}
return false;
}
@Override
public int write(ChannelBuffer c) {
int tlvStartIndex = c.writerIndex();
c.writeShort(TYPE);
int tlvLenIndex = c.writerIndex();
hLength = 0;
c.writeShort(hLength);
ListIterator<PcepValueType> listIterator = llLinkAttributesSubTLVs.listIterator();
while (listIterator.hasNext()) {
PcepValueType tlv = listIterator.next();
if (tlv == null) {
log.debug("TLV is null from subTlv list");
continue;
}
tlv.write(c);
// need to take care of padding
int pad = tlv.getLength() % 4;
if (0 != pad) {
pad = 4 - pad;
for (int i = 0; i < pad; ++i) {
c.writeByte((byte) 0);
}
}
}
hLength = (short) (c.writerIndex() - tlvStartIndex);
c.setShort(tlvLenIndex, (hLength - TLV_HEADER_LENGTH));
return c.writerIndex() - tlvStartIndex;
}
/**
* Reads channel buffer and returns object of TE Link Attributes TLV.
*
* @param c input channel buffer
* @param hLength length
* @return object of LinkAttributesTlv
* @throws PcepParseException if mandatory fields are missing
*/
public static PcepValueType read(ChannelBuffer c, short hLength) throws PcepParseException {
// Node Descriptor Sub-TLVs (variable)
List<PcepValueType> llLinkAttributesSubTLVs = new LinkedList<>();
ChannelBuffer tempCb = c.readBytes(hLength);
while (TLV_HEADER_LENGTH <= tempCb.readableBytes()) {
PcepValueType tlv;
short hType = tempCb.readShort();
int iValue = 0;
short length = tempCb.readShort();
switch (hType) {
case IPv4RouterIdOfLocalNodeSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new IPv4RouterIdOfLocalNodeSubTlv(iValue);
break;
case IPv6RouterIdofLocalNodeSubTlv.TYPE:
byte[] ipv6LValue = new byte[IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH];
tempCb.readBytes(ipv6LValue, 0, IPv6RouterIdofLocalNodeSubTlv.VALUE_LENGTH);
tlv = new IPv6RouterIdofLocalNodeSubTlv(ipv6LValue);
break;
case IPv4RouterIdOfRemoteNodeSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new IPv4RouterIdOfRemoteNodeSubTlv(iValue);
break;
case IPv6RouterIdofRemoteNodeSubTlv.TYPE:
byte[] ipv6RValue = new byte[IPv6RouterIdofRemoteNodeSubTlv.VALUE_LENGTH];
tempCb.readBytes(ipv6RValue, 0, IPv6RouterIdofRemoteNodeSubTlv.VALUE_LENGTH);
tlv = new IPv6RouterIdofRemoteNodeSubTlv(ipv6RValue);
break;
case LinkLocalRemoteIdentifiersSubTlv.TYPE:
tlv = LinkLocalRemoteIdentifiersSubTlv.read(tempCb);
break;
case AdministrativeGroupSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new AdministrativeGroupSubTlv(iValue);
break;
case MaximumLinkBandwidthSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new MaximumLinkBandwidthSubTlv(iValue);
break;
case MaximumReservableLinkBandwidthSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new MaximumReservableLinkBandwidthSubTlv(iValue);
break;
case UnreservedBandwidthSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new UnreservedBandwidthSubTlv(iValue);
break;
case TEDefaultMetricSubTlv.TYPE:
iValue = tempCb.readInt();
tlv = new TEDefaultMetricSubTlv(iValue);
break;
case LinkProtectionTypeSubTlv.TYPE:
tlv = LinkProtectionTypeSubTlv.read(tempCb);
break;
case MplsProtocolMaskSubTlv.TYPE:
byte cValue = tempCb.readByte();
tlv = new MplsProtocolMaskSubTlv(cValue);
break;
case IgpMetricSubTlv.TYPE:
tlv = IgpMetricSubTlv.read(tempCb, length);
break;
case SharedRiskLinkGroupSubTlv.TYPE:
tlv = SharedRiskLinkGroupSubTlv.read(tempCb, length);
break;
case OpaqueLinkAttributeSubTlv.TYPE:
tlv = OpaqueLinkAttributeSubTlv.read(tempCb, length);
break;
case LinkNameAttributeSubTlv.TYPE:
tlv = LinkNameAttributeSubTlv.read(tempCb, length);
break;
default:
throw new PcepParseException("Unsupported Sub TLV type :" + hType);
}
// Check for the padding
int pad = length % 4;
if (0 < pad) {
pad = 4 - pad;
if (pad <= tempCb.readableBytes()) {
tempCb.skipBytes(pad);
}
}
llLinkAttributesSubTLVs.add(tlv);
}
if (0 < tempCb.readableBytes()) {
throw new PcepParseException("Sub Tlv parsing error. Extra bytes received.");
}
return new LinkAttributesTlv(llLinkAttributesSubTLVs);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("Type", TYPE)
.add("Length", hLength)
.add("LinkAttributesSubTLVs", llLinkAttributesSubTLVs)
.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kafka;
import kafka.admin.AdminUtils;
import kafka.api.PartitionMetadata;
import kafka.common.KafkaException;
import kafka.network.SocketServer;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.io.FileUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.streaming.api.operators.StreamSink;
import org.apache.flink.streaming.connectors.kafka.internals.KafkaTopicPartitionLeader;
import org.apache.flink.streaming.connectors.kafka.internals.ZookeeperOffsetHandler;
import org.apache.flink.streaming.connectors.kafka.partitioner.FlinkKafkaPartitioner;
import org.apache.flink.streaming.connectors.kafka.testutils.ZooKeeperStringSerializer;
import org.apache.flink.streaming.util.serialization.KeyedDeserializationSchema;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchema;
import org.apache.flink.util.NetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.Seq;
import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import static org.apache.flink.util.NetUtils.hostAndPortToUrlString;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* An implementation of the KafkaServerProvider for Kafka 0.8
*/
public class KafkaTestEnvironmentImpl extends KafkaTestEnvironment {
protected static final Logger LOG = LoggerFactory.getLogger(KafkaTestEnvironmentImpl.class);
private File tmpZkDir;
private File tmpKafkaParent;
private List<File> tmpKafkaDirs;
private List<KafkaServer> brokers;
private TestingServer zookeeper;
private String zookeeperConnectionString;
private String brokerConnectionString = "";
private Properties standardProps;
private Properties additionalServerProperties;
public String getBrokerConnectionString() {
return brokerConnectionString;
}
@Override
public Properties getStandardProperties() {
return standardProps;
}
@Override
public Properties getSecureProperties() {
return null;
}
@Override
public String getVersion() {
return "0.8";
}
@Override
public List<KafkaServer> getBrokers() {
return brokers;
}
@Override
public <T> FlinkKafkaConsumerBase<T> getConsumer(List<String> topics, KeyedDeserializationSchema<T> readSchema, Properties props) {
return new FlinkKafkaConsumer08<>(topics, readSchema, props);
}
@Override
public <T> StreamSink<T> getProducerSink(
String topic,
KeyedSerializationSchema<T> serSchema,
Properties props,
FlinkKafkaPartitioner<T> partitioner) {
FlinkKafkaProducer08<T> prod = new FlinkKafkaProducer08<>(
topic,
serSchema,
props,
partitioner);
prod.setFlushOnCheckpoint(true);
return new StreamSink<>(prod);
}
@Override
public <T> DataStreamSink<T> produceIntoKafka(DataStream<T> stream, String topic, KeyedSerializationSchema<T> serSchema, Properties props, FlinkKafkaPartitioner<T> partitioner) {
FlinkKafkaProducer08<T> prod = new FlinkKafkaProducer08<>(topic, serSchema, props, partitioner);
prod.setFlushOnCheckpoint(true);
return stream.addSink(prod);
}
@Override
public KafkaOffsetHandler createOffsetHandler() {
return new KafkaOffsetHandlerImpl();
}
@Override
public void restartBroker(int leaderId) throws Exception {
brokers.set(leaderId, getKafkaServer(leaderId, tmpKafkaDirs.get(leaderId)));
}
@Override
public int getLeaderToShutDown(String topic) throws Exception {
ZkClient zkClient = createZkClient();
PartitionMetadata firstPart = null;
do {
if (firstPart != null) {
LOG.info("Unable to find leader. error code {}", firstPart.errorCode());
// not the first try. Sleep a bit
Thread.sleep(150);
}
Seq<PartitionMetadata> partitionMetadata = AdminUtils.fetchTopicMetadataFromZk(topic, zkClient).partitionsMetadata();
firstPart = partitionMetadata.head();
}
while (firstPart.errorCode() != 0);
zkClient.close();
return firstPart.leader().get().id();
}
@Override
public int getBrokerId(KafkaServer server) {
return server.socketServer().brokerId();
}
@Override
public boolean isSecureRunSupported() {
return false;
}
@Override
public void prepare(int numKafkaServers, Properties additionalServerProperties, boolean secureMode) {
this.additionalServerProperties = additionalServerProperties;
File tempDir = new File(System.getProperty("java.io.tmpdir"));
tmpZkDir = new File(tempDir, "kafkaITcase-zk-dir-" + (UUID.randomUUID().toString()));
try {
Files.createDirectories(tmpZkDir.toPath());
} catch (IOException e) {
fail("cannot create zookeeper temp dir: " + e.getMessage());
}
tmpKafkaParent = new File(tempDir, "kafkaITcase-kafka-dir" + (UUID.randomUUID().toString()));
try {
Files.createDirectories(tmpKafkaParent.toPath());
} catch (IOException e) {
fail("cannot create kafka temp dir: " + e.getMessage());
}
tmpKafkaDirs = new ArrayList<>(numKafkaServers);
for (int i = 0; i < numKafkaServers; i++) {
File tmpDir = new File(tmpKafkaParent, "server-" + i);
assertTrue("cannot create kafka temp dir", tmpDir.mkdir());
tmpKafkaDirs.add(tmpDir);
}
zookeeper = null;
brokers = null;
try {
LOG.info("Starting Zookeeper");
zookeeper = new TestingServer(-1, tmpZkDir);
zookeeperConnectionString = zookeeper.getConnectString();
LOG.info("Starting KafkaServer");
brokers = new ArrayList<>(numKafkaServers);
for (int i = 0; i < numKafkaServers; i++) {
brokers.add(getKafkaServer(i, tmpKafkaDirs.get(i)));
SocketServer socketServer = brokers.get(i).socketServer();
String host = socketServer.host() == null ? "localhost" : socketServer.host();
brokerConnectionString += hostAndPortToUrlString(host, socketServer.port()) + ",";
}
LOG.info("ZK and KafkaServer started.");
}
catch (Throwable t) {
t.printStackTrace();
fail("Test setup failed: " + t.getMessage());
}
standardProps = new Properties();
standardProps.setProperty("zookeeper.connect", zookeeperConnectionString);
standardProps.setProperty("bootstrap.servers", brokerConnectionString);
standardProps.setProperty("group.id", "flink-tests");
standardProps.setProperty("auto.commit.enable", "false");
standardProps.setProperty("zookeeper.session.timeout.ms", "30000"); // 6 seconds is default. Seems to be too small for travis.
standardProps.setProperty("zookeeper.connection.timeout.ms", "30000");
standardProps.setProperty("auto.offset.reset", "smallest"); // read from the beginning. (smallest is kafka 0.8)
standardProps.setProperty("fetch.message.max.bytes", "256"); // make a lot of fetches (MESSAGES MUST BE SMALLER!)
}
@Override
public void shutdown() {
if (brokers != null) {
for (KafkaServer broker : brokers) {
if (broker != null) {
broker.shutdown();
}
}
brokers.clear();
}
if (zookeeper != null) {
try {
zookeeper.stop();
zookeeper.close();
}
catch (Exception e) {
LOG.warn("ZK.stop() failed", e);
}
zookeeper = null;
}
// clean up the temp spaces
if (tmpKafkaParent != null && tmpKafkaParent.exists()) {
try {
FileUtils.deleteDirectory(tmpKafkaParent);
}
catch (Exception e) {
// ignore
}
}
if (tmpZkDir != null && tmpZkDir.exists()) {
try {
FileUtils.deleteDirectory(tmpZkDir);
}
catch (Exception e) {
// ignore
}
}
}
@Override
public void createTestTopic(String topic, int numberOfPartitions, int replicationFactor, Properties topicConfig) {
// create topic with one client
LOG.info("Creating topic {}", topic);
ZkClient creator = createZkClient();
AdminUtils.createTopic(creator, topic, numberOfPartitions, replicationFactor, topicConfig);
creator.close();
// validate that the topic has been created
final long deadline = System.nanoTime() + 30_000_000_000L;
do {
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
// restore interrupted state
}
List<KafkaTopicPartitionLeader> partitions = FlinkKafkaConsumer08.getPartitionsForTopic(Collections.singletonList(topic), standardProps);
if (partitions != null && partitions.size() > 0) {
return;
}
}
while (System.nanoTime() < deadline);
fail ("Test topic could not be created");
}
@Override
public void deleteTestTopic(String topic) {
LOG.info("Deleting topic {}", topic);
ZkClient zk = createZkClient();
AdminUtils.deleteTopic(zk, topic);
zk.close();
}
private ZkClient createZkClient() {
return new ZkClient(zookeeperConnectionString, Integer.valueOf(standardProps.getProperty("zookeeper.session.timeout.ms")),
Integer.valueOf(standardProps.getProperty("zookeeper.connection.timeout.ms")), new ZooKeeperStringSerializer());
}
/**
* Only for the 0.8 server we need access to the zk client.
*/
public CuratorFramework createCuratorClient() {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(100, 10);
CuratorFramework curatorClient = CuratorFrameworkFactory.newClient(standardProps.getProperty("zookeeper.connect"), retryPolicy);
curatorClient.start();
return curatorClient;
}
/**
* Copied from com.github.sakserv.minicluster.KafkaLocalBrokerIntegrationTest (ASL licensed)
*/
protected KafkaServer getKafkaServer(int brokerId, File tmpFolder) throws Exception {
LOG.info("Starting broker with id {}", brokerId);
Properties kafkaProperties = new Properties();
// properties have to be Strings
kafkaProperties.put("advertised.host.name", KAFKA_HOST);
kafkaProperties.put("broker.id", Integer.toString(brokerId));
kafkaProperties.put("log.dir", tmpFolder.toString());
kafkaProperties.put("zookeeper.connect", zookeeperConnectionString);
kafkaProperties.put("message.max.bytes", String.valueOf(50 * 1024 * 1024));
kafkaProperties.put("replica.fetch.max.bytes", String.valueOf(50 * 1024 * 1024));
// for CI stability, increase zookeeper session timeout
kafkaProperties.put("zookeeper.session.timeout.ms", "30000");
kafkaProperties.put("zookeeper.connection.timeout.ms", "30000");
if(additionalServerProperties != null) {
kafkaProperties.putAll(additionalServerProperties);
}
final int numTries = 5;
for (int i = 1; i <= numTries; i++) {
int kafkaPort = NetUtils.getAvailablePort();
kafkaProperties.put("port", Integer.toString(kafkaPort));
KafkaConfig kafkaConfig = new KafkaConfig(kafkaProperties);
try {
KafkaServer server = new KafkaServer(kafkaConfig, new KafkaLocalSystemTime());
server.startup();
return server;
}
catch (KafkaException e) {
if (e.getCause() instanceof BindException) {
// port conflict, retry...
LOG.info("Port conflict when starting Kafka Broker. Retrying...");
}
else {
throw e;
}
}
}
throw new Exception("Could not start Kafka after " + numTries + " retries due to port conflicts.");
}
private class KafkaOffsetHandlerImpl implements KafkaOffsetHandler {
private final CuratorFramework offsetClient;
private final String groupId;
public KafkaOffsetHandlerImpl() {
offsetClient = createCuratorClient();
groupId = standardProps.getProperty("group.id");
}
@Override
public Long getCommittedOffset(String topicName, int partition) {
try {
return ZookeeperOffsetHandler.getOffsetFromZooKeeper(offsetClient, groupId, topicName, partition);
} catch (Exception e) {
throw new RuntimeException("Exception when getting offsets from Zookeeper", e);
}
}
@Override
public void setCommittedOffset(String topicName, int partition, long offset) {
try {
ZookeeperOffsetHandler.setOffsetInZooKeeper(offsetClient, groupId, topicName, partition, offset);
} catch (Exception e) {
throw new RuntimeException("Exception when writing offsets to Zookeeper", e);
}
}
@Override
public void close() {
offsetClient.close();
}
}
}
| |
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The XAMJ Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: info@xamjwg.org
*/
/*
* Created on Apr 16, 2005
*/
package org.xamjwg.html.renderer;
import java.awt.*;
import org.xamjwg.util.Diagnostics;
//import org.apache.log4j.*;
/**
* @author J. H. S.
*/
public class MarkupUtilities {
//private static final Logger logger = Logger.getLogger(MarkupUtilities.class);
// public static final int MODE_ABOVE_OR_AT = 0;
// public static final int MODE_BELOW_OR_AT = 1;
// public static final int MODE_LEFT_OR_AT = 0;
// public static final int MODE_RIGHT_OR_AT = 1;
/**
*
*/
private MarkupUtilities() {
super();
}
public static BoundableRenderable findRenderable(Renderable[] renderables, Point point, boolean vertical) {
return findRenderable(renderables, point, 0, renderables.length, vertical);
}
public static BoundableRenderable findRenderable(Renderable[] renderables, int x, int y, boolean vertical) {
return findRenderable(renderables, x, y, 0, renderables.length, vertical);
}
private static BoundableRenderable findRenderable(Renderable[] renderables, Point point, int firstIndex, int length, boolean vertical) {
return findRenderable(renderables, point.x, point.y, firstIndex, length, vertical);
}
private static BoundableRenderable findRenderable(Renderable[] renderables, int x, int y, int firstIndex, int length, boolean vertical) {
if(length == 0) {
return null;
}
if(length == 1) {
Renderable r = renderables[firstIndex];
if(!(r instanceof BoundableRenderable)) {
return null;
}
BoundableRenderable br = (BoundableRenderable) r;
Rectangle rbounds = br.getBounds();
return rbounds.contains(x, y) ? br : null;
}
else {
int middleIndex = firstIndex + length / 2;
Renderable r = renderables[middleIndex];
Rectangle rbounds;
if(r instanceof BoundableRenderable) {
rbounds = ((BoundableRenderable) r).getBounds();
}
else {
BoundableRenderable rleft = findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical);
if(rleft != null) {
return rleft;
}
return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical);
}
if(rbounds.contains(x, y)) {
return (BoundableRenderable) r;
}
if(vertical) {
if(y < rbounds.y) {
return findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical);
}
else {
return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical);
}
}
else {
if(x < rbounds.x) {
return findRenderable(renderables, x, y, firstIndex, middleIndex - firstIndex, vertical);
}
else {
return findRenderable(renderables, x, y, middleIndex + 1, length - (middleIndex - firstIndex + 1), vertical);
}
}
}
}
public static Range findRenderables(Renderable[] renderables, Rectangle clipArea, boolean vertical) {
return findRenderables(renderables, clipArea, 0, renderables.length, vertical);
}
private static Range findRenderables(Renderable[] renderables, Rectangle clipArea, int firstIndex, int length, boolean vertical) {
if(length == 0) {
return new Range(0, 0);
}
int offset1 = findFirstIndex(renderables, clipArea, firstIndex, length, vertical);
int offset2 = findLastIndex(renderables, clipArea, firstIndex, length, vertical);
if(offset1 == -1 && offset2 == -1) {
//if(logger.isDebugEnabled()) logger.debug("findRenderables(): Range not found for clipArea=" + clipArea + ",length=" + length);
//for(int i = firstIndex; i < length; i++) {
//logger.debug("findRenderables(): renderable.bounds=" + renderables[i].getBounds());
//}
return new Range(0, 0);
}
if(offset1 == -1) {
offset1 = firstIndex;
}
if(offset2 == -1) {
offset2 = firstIndex + length - 1;
}
return new Range(offset1, offset2 - offset1 + 1);
}
private static int findFirstIndex(Renderable[] renderables, Rectangle clipArea, int index, int length, boolean vertical) {
Diagnostics.Assert(length > 0, "length=" + length);
if(length == 1) {
Renderable r = renderables[index];
Rectangle rbounds;
if(r instanceof BoundableRenderable) {
rbounds = ((BoundableRenderable) r).getBounds();
}
else {
return -1;
}
if(intersects(rbounds, clipArea, vertical)) {
return index;
}
else {
return -1;
}
}
else {
int middleIndex = index + length / 2;
Renderable r = renderables[middleIndex];
Rectangle rbounds;
if(r instanceof BoundableRenderable) {
rbounds = ((BoundableRenderable) r).getBounds();
}
else {
int leftIndex = findFirstIndex(renderables, clipArea, index, middleIndex - index, vertical);
if(leftIndex != -1) {
return leftIndex;
}
return findFirstIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical);
}
if(vertical) {
if(rbounds.y + rbounds.height < clipArea.y) {
int newLen = length - (middleIndex - index + 1);
return newLen == 0 ? -1 : findFirstIndex(renderables, clipArea, middleIndex + 1, newLen, vertical);
}
else {
int newLen = middleIndex - index;
int resultIdx = newLen == 0 ? -1 : findFirstIndex(renderables, clipArea, index, newLen, vertical);
if(resultIdx == -1) {
if(intersects(clipArea, rbounds, vertical)) {
return middleIndex;
}
}
return resultIdx;
}
}
else {
if(rbounds.x + rbounds.width < clipArea.x) {
return findFirstIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index), vertical);
}
else {
int resultIdx = findFirstIndex(renderables, clipArea, index, middleIndex - index, vertical);
if(resultIdx == -1) {
if(intersects(clipArea, rbounds, vertical)) {
return middleIndex;
}
}
return resultIdx;
}
}
}
}
private static int findLastIndex(Renderable[] renderables, Rectangle clipArea, int index, int length, boolean vertical) {
Diagnostics.Assert(length > 0, "length<=0");
if(length == 1) {
Renderable r = renderables[index];
Rectangle rbounds;
if(r instanceof BoundableRenderable) {
rbounds = ((BoundableRenderable) r).getBounds();
}
else {
return -1;
}
if(intersects(clipArea, rbounds, vertical)) {
return index;
}
else {
return -1;
}
}
else {
int middleIndex = index + length / 2;
Renderable r = renderables[middleIndex];
Rectangle rbounds;
if(r instanceof BoundableRenderable) {
rbounds = ((BoundableRenderable) r).getBounds();
}
else {
int rightIndex = findLastIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical);
if(rightIndex != -1) {
return rightIndex;
}
return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical);
}
if(vertical) {
if(rbounds.y > clipArea.y + clipArea.height) {
return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical);
}
else {
int newLen = length - (middleIndex - index + 1);
int resultIdx = newLen == 0 ? -1 : findLastIndex(renderables, clipArea, middleIndex + 1, newLen, vertical);
if(resultIdx == -1) {
if(intersects(clipArea, rbounds, vertical)) {
return middleIndex;
}
}
return resultIdx;
}
}
else {
if(rbounds.x > clipArea.x + clipArea.width) {
return findLastIndex(renderables, clipArea, index, middleIndex - index, vertical);
}
else {
int resultIdx = findLastIndex(renderables, clipArea, middleIndex + 1, length - (middleIndex - index + 1), vertical);
if(resultIdx == -1) {
if(intersects(clipArea, rbounds, vertical)) {
return middleIndex;
}
}
return resultIdx;
}
}
}
}
private static boolean intersects(Rectangle rect1, Rectangle rect2, boolean vertical) {
if(vertical) {
return !(
(rect1.y > rect2.y + rect2.height) ||
(rect2.y > rect1.y + rect1.height)
);
}
else {
return !(
(rect1.x > rect2.x + rect2.width) ||
(rect2.x > rect1.x + rect1.width)
);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.ReplChangeManager;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.messaging.json.gzip.GzipJSONMessageEncoder;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.exec.repl.ReplAck;
import org.apache.hadoop.hive.ql.exec.repl.ReplDumpWork;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
import org.apache.hadoop.hive.ql.parse.repl.load.DumpMetaData;
import org.apache.hadoop.hive.ql.parse.repl.metric.MetricCollector;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.ReplicationMetric;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Metric;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Metadata;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Progress;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Stage;
import org.apache.hadoop.hive.ql.parse.repl.metric.event.Status;
import org.apache.hadoop.hive.ql.scheduled.ScheduledQueryExecutionService;
import org.apache.hadoop.hive.shims.Utils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.Before;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.Ignore;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import static org.apache.hadoop.hive.metastore.ReplChangeManager.SOURCE_OF_REPLICATION;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
/**
* TestScheduledReplicationScenarios - test scheduled replication .
*/
public class TestScheduledReplicationScenarios extends BaseReplicationScenariosAcidTables {
private static final long DEFAULT_PROBE_TIMEOUT = 5 * 60 * 1000L; // 5 minutes
@BeforeClass
public static void classLevelSetup() throws Exception {
Map<String, String> overrides = new HashMap<>();
overrides.put(MetastoreConf.ConfVars.EVENT_MESSAGE_FACTORY.getHiveName(),
GzipJSONMessageEncoder.class.getCanonicalName());
overrides.put(HiveConf.ConfVars.HIVE_SCHEDULED_QUERIES_EXECUTOR_IDLE_SLEEP_TIME.varname, "1s");
overrides.put(HiveConf.ConfVars.HIVE_SCHEDULED_QUERIES_EXECUTOR_PROGRESS_REPORT_INTERVAL.varname,
"1s");
overrides.put(HiveConf.ConfVars.REPL_INCLUDE_EXTERNAL_TABLES.varname, "true");
overrides.put(HiveConf.ConfVars.HIVE_DISTCP_DOAS_USER.varname,
UserGroupInformation.getCurrentUser().getUserName());
internalBeforeClassSetup(overrides, TestScheduledReplicationScenarios.class);
}
static void internalBeforeClassSetup(Map<String, String> overrides,
Class clazz) throws Exception {
conf = new HiveConf(clazz);
conf.set("dfs.client.use.datanode.hostname", "true");
conf.set("hadoop.proxyuser." + Utils.getUGI().getShortUserName() + ".hosts", "*");
MiniDFSCluster miniDFSCluster =
new MiniDFSCluster.Builder(conf).numDataNodes(2).format(true).build();
Map<String, String> acidEnableConf = new HashMap<String, String>() {{
put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString());
put("hive.support.concurrency", "true");
put("hive.txn.manager", "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager");
put("hive.metastore.client.capability.check", "false");
put("hive.repl.bootstrap.dump.open.txn.timeout", "1s");
put("hive.strict.checks.bucketing", "false");
put("hive.mapred.mode", "nonstrict");
put("mapred.input.dir.recursive", "true");
put("hive.metastore.disallow.incompatible.col.type.changes", "false");
put("hive.in.repl.test", "true");
}};
acidEnableConf.putAll(overrides);
primary = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf);
acidEnableConf.put(MetastoreConf.ConfVars.REPLDIR.getHiveName(), primary.repldDir);
replica = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf);
}
@Before
public void setup() throws Throwable {
super.setup();
}
@After
public void tearDown() throws Throwable {
primary.run("drop database if exists " + primaryDbName + " cascade");
replica.run("drop database if exists " + replicatedDbName + " cascade");
primary.run("drop database if exists " + primaryDbName + "_extra cascade");
}
@Test
@Ignore("HIVE-23395")
public void testAcidTablesReplLoadBootstrapIncr() throws Throwable {
// Bootstrap
primary.run("use " + primaryDbName)
.run("create table t1 (id int) clustered by(id) into 3 buckets stored as orc " +
"tblproperties (\"transactional\"=\"true\")")
.run("insert into t1 values(1)")
.run("insert into t1 values(2)");
try (ScheduledQueryExecutionService schqS =
ScheduledQueryExecutionService.startScheduledQueryExecutorService(primary.hiveConf)) {
int next = -1;
ReplDumpWork.injectNextDumpDirForTest(String.valueOf(next), true);
primary.run("create scheduled query s1_t1 every 5 seconds as repl dump " + primaryDbName);
replica.run("create scheduled query s2_t1 every 5 seconds as repl load " + primaryDbName + " INTO "
+ replicatedDbName);
Path dumpRoot = new Path(primary.hiveConf.getVar(HiveConf.ConfVars.REPLDIR),
Base64.getEncoder().encodeToString(primaryDbName.toLowerCase().getBytes(StandardCharsets.UTF_8.name())));
FileSystem fs = FileSystem.get(dumpRoot.toUri(), primary.hiveConf);
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
Path ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName)
.run("show tables like 't1'")
.verifyResult("t1")
.run("select id from t1 order by id")
.verifyResults(new String[]{"1", "2"});
// First incremental, after bootstrap
primary.run("use " + primaryDbName)
.run("insert into t1 values(3)")
.run("insert into t1 values(4)");
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName)
.run("show tables like 't1'")
.verifyResult("t1")
.run("select id from t1 order by id")
.verifyResults(new String[]{"1", "2", "3", "4"});
// Second incremental
primary.run("use " + primaryDbName)
.run("insert into t1 values(5)")
.run("insert into t1 values(6)");
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName)
.run("show tables like 't1'")
.verifyResult("t1")
.run("select id from t1 order by id")
.verifyResults(new String[]{"1", "2", "3", "4", "5", "6"})
.run("drop table t1");
} finally {
primary.run("drop scheduled query s1_t1");
replica.run("drop scheduled query s2_t1");
}
}
@Test
@Ignore("HIVE-23395")
public void testExternalTablesReplLoadBootstrapIncr() throws Throwable {
// Bootstrap
String withClause = " WITH('" + HiveConf.ConfVars.REPL_INCLUDE_AUTHORIZATION_METADATA
+ "' = 'true' ,'" + HiveConf.ConfVars.REPL_INCLUDE_ATLAS_METADATA + "' = 'true' , '"
+ HiveConf.ConfVars.HIVE_IN_TEST + "' = 'true'" + ",'"+ HiveConf.ConfVars.REPL_ATLAS_ENDPOINT
+ "' = 'http://localhost:21000/atlas'" + ",'"+ HiveConf.ConfVars.REPL_ATLAS_REPLICATED_TO_DB + "' = 'tgt'"
+ ",'"+ HiveConf.ConfVars.REPL_SOURCE_CLUSTER_NAME + "' = 'cluster0'"
+ ",'"+ HiveConf.ConfVars.REPL_TARGET_CLUSTER_NAME + "' = 'cluster1')";
primary.run("use " + primaryDbName)
.run("create external table t2 (id int)")
.run("insert into t2 values(1)")
.run("insert into t2 values(2)");
try (ScheduledQueryExecutionService schqS =
ScheduledQueryExecutionService.startScheduledQueryExecutorService(primary.hiveConf)) {
int next = -1;
ReplDumpWork.injectNextDumpDirForTest(String.valueOf(next), true);
primary.run("create scheduled query s1_t2 every 5 seconds as repl dump " + primaryDbName + withClause);
replica.run("create scheduled query s2_t2 every 5 seconds as repl load " + primaryDbName + " INTO "
+ replicatedDbName + withClause);
Path dumpRoot = new Path(primary.hiveConf.getVar(HiveConf.ConfVars.REPLDIR),
Base64.getEncoder().encodeToString(primaryDbName.toLowerCase().getBytes(StandardCharsets.UTF_8.name())));
FileSystem fs = FileSystem.get(dumpRoot.toUri(), primary.hiveConf);
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
Path ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName)
.run("show tables like 't2'")
.verifyResult("t2")
.run("select id from t2 order by id")
.verifyResults(new String[]{"1", "2"});
long lastReplId = Long.parseLong(primary.status(replicatedDbName).getOutput().get(0));
DumpMetaData dumpMetaData = new DumpMetaData(ackPath.getParent(), primary.hiveConf);
List<ReplicationMetric> replicationMetrics = MetricCollector.getInstance().getMetrics();
Assert.assertEquals(2, replicationMetrics.size());
//Generate expected metrics
List<ReplicationMetric> expectedReplicationMetrics = new ArrayList<>();
expectedReplicationMetrics.add(generateExpectedMetric("s1_t2", 0, primaryDbName,
Metadata.ReplicationType.BOOTSTRAP, ackPath.getParent().toString(), lastReplId, Status.SUCCESS,
generateDumpStages(true)));
expectedReplicationMetrics.add(generateExpectedMetric("s2_t2",
dumpMetaData.getDumpExecutionId(), replicatedDbName,
Metadata.ReplicationType.BOOTSTRAP, ackPath.getParent().toString(), lastReplId, Status.SUCCESS,
generateLoadStages(true)));
checkMetrics(expectedReplicationMetrics, replicationMetrics);
// First incremental, after bootstrap
primary.run("use " + primaryDbName)
.run("insert into t2 values(3)")
.run("insert into t2 values(4)");
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName)
.run("show tables like 't2'")
.verifyResult("t2")
.run("select id from t2 order by id")
.verifyResults(new String[]{"1", "2", "3", "4"});
} finally {
primary.run("drop scheduled query s1_t2");
replica.run("drop scheduled query s2_t2");
}
}
@Test
@Ignore("HIVE-25720")
public void testCompleteFailoverWithReverseBootstrap() throws Throwable {
String withClause = "'" + HiveConf.ConfVars.HIVE_IN_TEST + "' = 'true','"
+ HiveConf.ConfVars.REPL_RETAIN_PREV_DUMP_DIR + "'='true'" ;
String sourceDbName = "sourceDbName";
String replicaDbName = "replicaDbName";
// Create a table with some data at source DB.
primary.run("create database " + sourceDbName + " with dbproperties('repl.source.for'='a')")
.run("use " + sourceDbName)
.run("create table t2 (id int)").run("insert into t2 values(1)").run("insert into t2 values(2)");
// Schedule Dump & Load and verify the data is replicated properly.
try (ScheduledQueryExecutionService schqS = ScheduledQueryExecutionService
.startScheduledQueryExecutorService(primary.hiveConf)) {
int next = -1;
ReplDumpWork.injectNextDumpDirForTest(String.valueOf(next), true);
primary.run("create scheduled query repl_dump_p1 every 5 seconds as repl dump "
+ sourceDbName + " WITH(" + withClause + ')');
replica.run("create scheduled query repl_load_p1 every 5 seconds as repl load "
+ sourceDbName + " INTO " + replicaDbName + " WITH(" + withClause + ')');
Path dumpRoot = ReplUtils.getEncodedDumpRootPath(primary.hiveConf, sourceDbName.toLowerCase());
FileSystem fs = FileSystem.get(dumpRoot.toUri(), primary.hiveConf);
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
Path ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicaDbName).run("show tables like 't2'")
.verifyResult("t2").run("select id from t2 order by id")
.verifyResults(new String[] {"1", "2"});
//Start failover from here.
String startFailoverClause = withClause.concat(",'" + HiveConf.ConfVars.HIVE_REPL_FAILOVER_START + "'='true'");
primary.run("alter scheduled query repl_dump_p1 defined as repl dump " + sourceDbName + " WITH(" + startFailoverClause + ')');
replica.run("alter scheduled query repl_load_p1 defined as repl load "
+ sourceDbName + " INTO " + replicaDbName + " WITH(" + startFailoverClause + ')');
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot,
String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
Path failoverReadyMarker = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.FAILOVER_READY_MARKER.toString());
assertTrue(fs.exists(failoverReadyMarker));
assertTrue(MetaStoreUtils.isDbBeingFailedOverAtEndpoint(primary.getDatabase(sourceDbName),
MetaStoreUtils.FailoverEndpoint.SOURCE));
assertTrue(MetaStoreUtils.isDbBeingFailedOverAtEndpoint(replica.getDatabase(replicaDbName),
MetaStoreUtils.FailoverEndpoint.TARGET));
primary.run("alter scheduled query repl_dump_p1 disabled")
.run("alter scheduled query repl_dump_p1 defined as repl dump "
+ sourceDbName + " WITH(" + withClause + ')')
.run("alter database " + sourceDbName + " set dbproperties('" + SOURCE_OF_REPLICATION + "'='')")
.run("drop database " + sourceDbName + " cascade");
assertTrue(primary.getDatabase(sourceDbName) == null);
replica.run("alter scheduled query repl_load_p1 disabled")
.run("alter scheduled query repl_load_p1 defined as repl load "
+ sourceDbName + " INTO " + replicaDbName + " WITH(" + withClause + ')')
.run("create scheduled query repl_dump_p2 every 5 seconds as repl dump " + replicaDbName + " WITH(" + withClause + ')');
primary.run("create scheduled query repl_load_p2 every 5 seconds as repl load "
+ replicaDbName + " INTO " + sourceDbName + " WITH(" + withClause + ')');
dumpRoot = ReplUtils.getEncodedDumpRootPath(replica.hiveConf, replicaDbName.toLowerCase());
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot,
String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
assertFalse(MetaStoreUtils.isTargetOfReplication(replica.getDatabase(replicaDbName)));
Database primaryDb = primary.getDatabase(sourceDbName);
assertFalse(primaryDb == null);
assertTrue(MetaStoreUtils.isTargetOfReplication(primaryDb));
assertFalse(MetaStoreUtils.isDbBeingFailedOver(primaryDb));
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot,
String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
assertFalse(ReplUtils.isFirstIncPending(primary.getDatabase(sourceDbName).getParameters()));
assertFalse(MetaStoreUtils.isDbBeingFailedOver(replica.getDatabase(replicaDbName)));
//Start failback from here.
replica.run("alter scheduled query repl_dump_p2 defined as repl dump " + replicaDbName + " WITH(" + startFailoverClause + ')');
primary.run("alter scheduled query repl_load_p2 defined as repl load "
+ replicaDbName + " INTO " + sourceDbName + " WITH(" + startFailoverClause + ')');
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
failoverReadyMarker = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.FAILOVER_READY_MARKER.toString());
assertTrue(fs.exists(failoverReadyMarker));
assertTrue(MetaStoreUtils.isDbBeingFailedOverAtEndpoint(replica.getDatabase(replicaDbName),
MetaStoreUtils.FailoverEndpoint.SOURCE));
assertTrue(MetaStoreUtils.isDbBeingFailedOverAtEndpoint(primary.getDatabase(sourceDbName),
MetaStoreUtils.FailoverEndpoint.TARGET));
replica.run("alter scheduled query repl_dump_p2 disabled")
.run("alter scheduled query repl_dump_p2 defined as repl dump "
+ replicaDbName + " WITH(" + withClause + ')')
.run("alter database " + replicaDbName + " set dbproperties('" + SOURCE_OF_REPLICATION + "'='')")
.run("drop database " + replicaDbName + " cascade")
.run("alter scheduled query repl_load_p1 enabled");
assertTrue(replica.getDatabase(replicaDbName) == null);
primary.run("alter scheduled query repl_load_p2 disabled")
.run("alter scheduled query repl_load_p2 defined as repl load "
+ replicaDbName + " INTO " + sourceDbName + " WITH(" + withClause + ')')
.run("alter scheduled query repl_dump_p1 enabled");
dumpRoot = ReplUtils.getEncodedDumpRootPath(primary.hiveConf, sourceDbName.toLowerCase());
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot, String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
assertFalse(MetaStoreUtils.isTargetOfReplication(primary.getDatabase(sourceDbName)));
Database replicaDb = replica.getDatabase(replicaDbName);
assertFalse(replicaDb == null);
assertTrue(MetaStoreUtils.isTargetOfReplication(replicaDb));
assertFalse(MetaStoreUtils.isDbBeingFailedOver(replicaDb));
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
ackPath = new Path(dumpRoot,
String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
assertFalse(ReplUtils.isFirstIncPending(replica.getDatabase(replicaDbName).getParameters()));
assertFalse(MetaStoreUtils.isDbBeingFailedOver(primary.getDatabase(sourceDbName)));
} finally {
primary.run("drop database if exists " + sourceDbName + " cascade").run("drop scheduled query repl_dump_p1");
replica.run("drop database if exists " + replicaDbName + " cascade").run("drop scheduled query repl_load_p1");
primary.run("drop scheduled query repl_load_p2");
replica.run("drop scheduled query repl_dump_p2");
}
}
@Test
@Ignore("HIVE-25720")
public void testSetPolicyId() throws Throwable {
String withClause =
" WITH('" + HiveConf.ConfVars.HIVE_IN_TEST + "' = 'true'" + ",'"
+ HiveConf.ConfVars.REPL_SOURCE_CLUSTER_NAME + "' = 'cluster0'"
+ ",'" + HiveConf.ConfVars.REPL_TARGET_CLUSTER_NAME
+ "' = 'cluster1')";
// Create a table with some data at source DB.
primary.run("use " + primaryDbName).run("create table t2 (id int)")
.run("insert into t2 values(1)").run("insert into t2 values(2)");
// Remove the SOURCE_OF_REPLICATION property from the database.
primary.run("ALTER DATABASE " + primaryDbName + " Set DBPROPERTIES ( '"
+ SOURCE_OF_REPLICATION + "' = '')");
assertFalse(ReplChangeManager.isSourceOfReplication(primary.getDatabase(primaryDbName)));
// Schedule Dump & Load and verify the data is replicated properly.
try (ScheduledQueryExecutionService schqS = ScheduledQueryExecutionService
.startScheduledQueryExecutorService(primary.hiveConf)) {
int next = -1;
ReplDumpWork.injectNextDumpDirForTest(String.valueOf(next), true);
primary.run("create scheduled query s1_t2 every 5 seconds as repl dump " + primaryDbName + withClause);
replica.run("create scheduled query s2_t2 every 5 seconds as repl load "
+ primaryDbName + " INTO " + replicatedDbName + withClause);
Path dumpRoot = ReplUtils.getEncodedDumpRootPath(primary.hiveConf, primaryDbName.toLowerCase());
FileSystem fs = FileSystem.get(dumpRoot.toUri(), primary.hiveConf);
next = Integer.parseInt(ReplDumpWork.getTestInjectDumpDir()) + 1;
Path ackPath = new Path(dumpRoot,
String.valueOf(next) + File.separator + ReplUtils.REPL_HIVE_BASE_DIR
+ File.separator + ReplAck.LOAD_ACKNOWLEDGEMENT.toString());
waitForAck(fs, ackPath, DEFAULT_PROBE_TIMEOUT);
replica.run("use " + replicatedDbName).run("show tables like 't2'")
.verifyResult("t2").run("select id from t2 order by id")
.verifyResults(new String[] {"1", "2"});
// Check the database got the SOURCE_OF_REPLICATION property set.
assertTrue(ReplChangeManager.getReplPolicyIdString(primary.getDatabase(primaryDbName)).equals("s1_t2"));
// Remove the SOURCE_OF_REPLICATION property from the database.
primary.run("ALTER DATABASE " + primaryDbName + " Set DBPROPERTIES ( '" + SOURCE_OF_REPLICATION + "' = '')");
assertFalse(ReplChangeManager.isSourceOfReplication(primary.getDatabase(primaryDbName)));
//Test to ensure that repl.source.for is added in incremental iteration of replication also.
GenericTestUtils.waitFor(() -> {
try {
return ReplChangeManager.getReplPolicyIdString(primary.getDatabase(primaryDbName)).equals("s1_t2");
} catch (Throwable e) {
return false;
}
}, 100, 10000);
// Test the new policy id is appended
primary.run("drop scheduled query s1_t2");
fs.delete(dumpRoot, true);
primary.run("create scheduled query s1_t2_new every 5 seconds as repl " + "dump " + primaryDbName + withClause);
GenericTestUtils.waitFor(() -> {
try {
return ReplChangeManager.getReplPolicyIdString(primary.getDatabase(primaryDbName)).equals("s1_t2, s1_t2_new");
} catch (Throwable e) {
return false;
}
}, 100, 10000);
} finally {
primary.run("drop scheduled query s1_t2_new");
replica.run("drop scheduled query s2_t2");
}
}
private void checkMetrics(List<ReplicationMetric> expectedReplicationMetrics,
List<ReplicationMetric> actualMetrics) {
Assert.assertEquals(expectedReplicationMetrics.size(), actualMetrics.size());
int metricCounter = 0;
for (ReplicationMetric actualMetric : actualMetrics) {
for (ReplicationMetric expecMetric : expectedReplicationMetrics) {
if (actualMetric.getPolicy().equalsIgnoreCase(expecMetric.getPolicy())) {
Assert.assertEquals(expecMetric.getDumpExecutionId(), actualMetric.getDumpExecutionId());
Assert.assertEquals(expecMetric.getMetadata().getDbName(), actualMetric.getMetadata().getDbName());
Assert.assertEquals(expecMetric.getMetadata().getLastReplId(),
actualMetric.getMetadata().getLastReplId());
Assert.assertEquals(expecMetric.getMetadata().getStagingDir(),
actualMetric.getMetadata().getStagingDir());
Assert.assertEquals(expecMetric.getMetadata().getReplicationType(),
actualMetric.getMetadata().getReplicationType());
Assert.assertEquals(expecMetric.getProgress().getStatus(), actualMetric.getProgress().getStatus());
Assert.assertEquals(expecMetric.getProgress().getStages().size(),
actualMetric.getProgress().getStages().size());
List<Stage> expectedStages = expecMetric.getProgress().getStages();
List<Stage> actualStages = actualMetric.getProgress().getStages();
int counter = 0;
for (Stage actualStage : actualStages) {
for (Stage expeStage : expectedStages) {
if (actualStage.getName().equalsIgnoreCase(expeStage.getName())) {
Assert.assertEquals(expeStage.getStatus(), actualStage.getStatus());
Assert.assertEquals(expeStage.getMetrics().size(), actualStage.getMetrics().size());
for (Metric actMetric : actualStage.getMetrics()) {
for (Metric expMetric : expeStage.getMetrics()) {
if (actMetric.getName().equalsIgnoreCase(expMetric.getName())) {
Assert.assertEquals(expMetric.getTotalCount(), actMetric.getTotalCount());
Assert.assertEquals(expMetric.getCurrentCount(), actMetric.getCurrentCount());
}
}
}
counter++;
if (counter == actualStages.size()) {
break;
}
}
}
}
metricCounter++;
if (metricCounter == actualMetrics.size()) {
break;
}
}
}
}
}
private List<Stage> generateLoadStages(boolean isBootstrap) {
List<Stage> stages = new ArrayList<>();
//Ranger
Stage rangerDump = new Stage("RANGER_LOAD", Status.SUCCESS, 0);
Metric rangerMetric = new Metric(ReplUtils.MetricName.POLICIES.name(), 0);
rangerDump.addMetric(rangerMetric);
stages.add(rangerDump);
//Atlas
Stage atlasDump = new Stage("ATLAS_LOAD", Status.SUCCESS, 0);
Metric atlasMetric = new Metric(ReplUtils.MetricName.ENTITIES.name(), 0);
atlasDump.addMetric(atlasMetric);
stages.add(atlasDump);
//Hive
Stage replDump = new Stage("REPL_LOAD", Status.SUCCESS, 0);
if (isBootstrap) {
Metric hiveMetric = new Metric(ReplUtils.MetricName.TABLES.name(), 1);
hiveMetric.setCurrentCount(1);
replDump.addMetric(hiveMetric);
hiveMetric = new Metric(ReplUtils.MetricName.FUNCTIONS.name(), 0);
replDump.addMetric(hiveMetric);
} else {
Metric hiveMetric = new Metric(ReplUtils.MetricName.EVENTS.name(), 1);
hiveMetric.setCurrentCount(1);
replDump.addMetric(hiveMetric);
}
stages.add(replDump);
return stages;
}
private List<Stage> generateDumpStages(boolean isBootstrap) {
List<Stage> stages = new ArrayList<>();
//Ranger
Stage rangerDump = new Stage("RANGER_DUMP", Status.SUCCESS, 0);
Metric rangerMetric = new Metric(ReplUtils.MetricName.POLICIES.name(), 0);
rangerDump.addMetric(rangerMetric);
stages.add(rangerDump);
//Atlas
Stage atlasDump = new Stage("ATLAS_DUMP", Status.SUCCESS, 0);
Metric atlasMetric = new Metric(ReplUtils.MetricName.ENTITIES.name(), 0);
atlasDump.addMetric(atlasMetric);
stages.add(atlasDump);
//Hive
Stage replDump = new Stage("REPL_DUMP", Status.SUCCESS, 0);
if (isBootstrap) {
Metric hiveMetric = new Metric(ReplUtils.MetricName.TABLES.name(), 1);
hiveMetric.setCurrentCount(1);
replDump.addMetric(hiveMetric);
hiveMetric = new Metric(ReplUtils.MetricName.FUNCTIONS.name(), 0);
replDump.addMetric(hiveMetric);
} else {
Metric hiveMetric = new Metric(ReplUtils.MetricName.EVENTS.name(), 1);
hiveMetric.setCurrentCount(1);
replDump.addMetric(hiveMetric);
}
stages.add(replDump);
return stages;
}
private ReplicationMetric generateExpectedMetric(String policy, long dumpExecId, String dbName,
Metadata.ReplicationType replicationType, String staging,
long lastReplId, Status status, List<Stage> stages) {
Metadata metadata = new Metadata(dbName, replicationType, staging);
metadata.setLastReplId(lastReplId);
ReplicationMetric replicationMetric = new ReplicationMetric(0, policy, dumpExecId, metadata);
Progress progress = new Progress();
progress.setStatus(status);
for (Stage stage : stages) {
progress.addStage(stage);
}
replicationMetric.setProgress(progress);
return replicationMetric;
}
private void waitForAck(FileSystem fs, Path ackFile, long timeout) throws IOException {
long oldTime = System.currentTimeMillis();
long sleepInterval = 2;
while(true) {
if (fs.exists(ackFile)) {
return;
}
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
//no-op
}
if (System.currentTimeMillis() - oldTime > timeout) {
break;
}
}
throw new IOException("Timed out waiting for the ack file: " + ackFile.toString());
}
}
| |
package ca.uhn.fhir.util;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2021 Smile CDR, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.primitive.StringDt;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseParameters;
import org.hl7.fhir.instance.model.api.IBaseReference;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
/**
* Utilities for dealing with parameters resources in a version indepenedent way
*/
public class ParametersUtil {
public static List<String> getNamedParameterValuesAsString(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
Function<IPrimitiveType<?>, String> mapper = t -> defaultIfBlank(t.getValueAsString(), null);
return extractNamedParameters(theCtx, theParameters, theParameterName, mapper);
}
public static List<Integer> getNamedParameterValuesAsInteger(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
Function<IPrimitiveType<?>, Integer> mapper = t -> (Integer) t.getValue();
return extractNamedParameters(theCtx, theParameters, theParameterName, mapper);
}
public static Optional<Integer> getNamedParameterValueAsInteger(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
return getNamedParameterValuesAsInteger(theCtx, theParameters, theParameterName).stream().findFirst();
}
public static List<IBase> getNamedParameters(FhirContext theCtx, IBaseResource theParameters, String theParameterName) {
Validate.notNull(theParameters, "theParameters must not be null");
RuntimeResourceDefinition resDef = theCtx.getResourceDefinition(theParameters.getClass());
BaseRuntimeChildDefinition parameterChild = resDef.getChildByName("parameter");
List<IBase> parameterReps = parameterChild.getAccessor().getValues(theParameters);
return parameterReps
.stream()
.filter(param -> {
BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(param.getClass());
BaseRuntimeChildDefinition nameChild = nextParameterDef.getChildByName("name");
List<IBase> nameValues = nameChild.getAccessor().getValues(param);
Optional<? extends IPrimitiveType<?>> nameValue = nameValues
.stream()
.filter(t -> t instanceof IPrimitiveType<?>)
.map(t -> ((IPrimitiveType<?>) t))
.findFirst();
if (!nameValue.isPresent() || !theParameterName.equals(nameValue.get().getValueAsString())) {
return false;
}
return true;
})
.collect(Collectors.toList());
}
public static Optional<IBase> getParameterPart(FhirContext theCtx, IBase theParameter, String theParameterName) {
BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(theParameter.getClass());
BaseRuntimeChildDefinition valueChild = nextParameterDef.getChildByName("part");
List<IBase> parts = valueChild.getAccessor().getValues(theParameter);
for (IBase nextPart : parts) {
Optional<IPrimitiveType> name = theCtx.newTerser().getSingleValue(nextPart, "name", IPrimitiveType.class);
if (name.isPresent() && theParameterName.equals(name.get().getValueAsString())) {
return Optional.of(nextPart);
}
}
return Optional.empty();
}
public static Optional<IBase> getParameterPartValue(FhirContext theCtx, IBase theParameter, String theParameterName) {
Optional<IBase> part = getParameterPart(theCtx, theParameter, theParameterName);
if (part.isPresent()) {
return theCtx.newTerser().getSingleValue(part.get(), "value[x]", IBase.class);
} else {
return Optional.empty();
}
}
public static String getParameterPartValueAsString(FhirContext theCtx, IBase theParameter, String theParameterName) {
return getParameterPartValue(theCtx, theParameter, theParameterName).map(t -> (IPrimitiveType<?>) t).map(t -> t.getValueAsString()).orElse(null);
}
private static <T> List<T> extractNamedParameters(FhirContext theCtx, IBaseParameters theParameters, String theParameterName, Function<IPrimitiveType<?>, T> theMapper) {
List<T> retVal = new ArrayList<>();
List<IBase> namedParameters = getNamedParameters(theCtx, theParameters, theParameterName);
for (IBase nextParameter : namedParameters) {
BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(nextParameter.getClass());
BaseRuntimeChildDefinition valueChild = nextParameterDef.getChildByName("value[x]");
List<IBase> valueValues = valueChild.getAccessor().getValues(nextParameter);
valueValues
.stream()
.filter(t -> t instanceof IPrimitiveType<?>)
.map(t -> ((IPrimitiveType<?>) t))
.map(theMapper)
.filter(t -> t != null)
.forEach(retVal::add);
}
return retVal;
}
private static void addClientParameter(FhirContext theContext, Object theValue, IBaseResource theTargetResource, BaseRuntimeChildDefinition paramChild, BaseRuntimeElementCompositeDefinition<?> paramChildElem, String theName) {
Validate.notNull(theValue, "theValue must not be null");
if (theValue instanceof IBaseResource) {
IBase parameter = createParameterRepetition(theContext, theTargetResource, paramChild, paramChildElem, theName);
paramChildElem.getChildByName("resource").getMutator().addValue(parameter, (IBaseResource) theValue);
} else if (theValue instanceof IBaseDatatype) {
IBase parameter = createParameterRepetition(theContext, theTargetResource, paramChild, paramChildElem, theName);
paramChildElem.getChildByName("value[x]").getMutator().addValue(parameter, (IBaseDatatype) theValue);
} else if (theValue instanceof Collection) {
Collection<?> collection = (Collection<?>) theValue;
for (Object next : collection) {
addClientParameter(theContext, next, theTargetResource, paramChild, paramChildElem, theName);
}
} else {
throw new IllegalArgumentException("Don't know how to handle value of type " + theValue.getClass() + " for parameter " + theName);
}
}
/**
* Add a parameter value to a Parameters resource
*
* @param theContext The FhirContext
* @param theParameters The Parameters resource
* @param theName The parametr name
* @param theValue The parameter value (can be a {@link IBaseResource resource} or a {@link IBaseDatatype datatype})
*/
public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, Object theValue) {
RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
addClientParameter(theContext, theValue, theParameters, paramChild, paramChildElem, theName);
}
/**
* Add a parameter value to a Parameters resource
*
* @param theContext The FhirContext
* @param theParameters The Parameters resource
* @param theName The parameter name
* @param thePrimitiveDatatype The datatype, e.g. "string", or "uri"
* @param theValue The value
*/
public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, String thePrimitiveDatatype, String theValue) {
Validate.notBlank(thePrimitiveDatatype, "thePrimitiveDatatype must not be null or empty");
BaseRuntimeElementDefinition<?> datatypeDef = theContext.getElementDefinition(thePrimitiveDatatype);
IPrimitiveType<?> value = (IPrimitiveType<?>) datatypeDef.newInstance();
value.setValueAsString(theValue);
addParameterToParameters(theContext, theParameters, theName, value);
}
private static IBase createParameterRepetition(FhirContext theContext, IBaseResource theTargetResource, BaseRuntimeChildDefinition paramChild, BaseRuntimeElementCompositeDefinition<?> paramChildElem, String theName) {
IBase parameter = paramChildElem.newInstance();
paramChild.getMutator().addValue(theTargetResource, parameter);
IPrimitiveType<?> value;
value = createString(theContext, theName);
paramChildElem.getChildByName("name").getMutator().addValue(parameter, value);
return parameter;
}
public static IPrimitiveType<?> createString(FhirContext theContext, String theValue) {
IPrimitiveType<?> value;
if (theContext.getVersion().getVersion().isRi()) {
value = (IPrimitiveType<?>) theContext.getElementDefinition("string").newInstance(theValue);
} else {
value = new StringDt(theValue);
}
return value;
}
public static IPrimitiveType<?> createUri(FhirContext theContext, String theValue) {
IPrimitiveType<?> value = (IPrimitiveType<?>) theContext.getElementDefinition("uri").newInstance(theValue);
return value;
}
public static IPrimitiveType<?> createCode(FhirContext theContext, String theValue) {
IPrimitiveType<?> value = (IPrimitiveType<?>) theContext.getElementDefinition("code").newInstance(theValue);
return value;
}
public static IBaseParameters newInstance(FhirContext theContext) {
Validate.notNull(theContext, "theContext must not be null");
return (IBaseParameters) theContext.getResourceDefinition("Parameters").newInstance();
}
@SuppressWarnings("unchecked")
public static void addParameterToParametersBoolean(FhirContext theCtx, IBaseParameters theParameters, String theName, boolean theValue) {
IPrimitiveType<Boolean> value = (IPrimitiveType<Boolean>) theCtx.getElementDefinition("boolean").newInstance();
value.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, value);
}
@SuppressWarnings("unchecked")
public static void addParameterToParametersCode(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("code").newInstance();
value.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, value);
}
@SuppressWarnings("unchecked")
public static void addParameterToParametersInteger(FhirContext theCtx, IBaseParameters theParameters, String theName, int theValue) {
IPrimitiveType<Integer> count = (IPrimitiveType<Integer>) theCtx.getElementDefinition("integer").newInstance();
count.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, count);
}
public static void addParameterToParametersLong(FhirContext theCtx, IBaseParameters theParameters, String theName, long theValue) {
addParameterToParametersDecimal(theCtx, theParameters, theName, BigDecimal.valueOf(theValue));
}
public static void addParameterToParametersDecimal(FhirContext theCtx, IBaseParameters theParameters, String theName, BigDecimal theValue) {
IPrimitiveType<BigDecimal> count = (IPrimitiveType<BigDecimal>) theCtx.getElementDefinition("decimal").newInstance();
count.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, count);
}
public static void addParameterToParametersReference(FhirContext theCtx, IBaseParameters theParameters, String theName, String theReference) {
IBaseReference target = (IBaseReference) theCtx.getElementDefinition("reference").newInstance();
target.setReference(theReference);
addParameterToParameters(theCtx, theParameters, theName, target);
}
@SuppressWarnings("unchecked")
public static void addParameterToParametersString(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("string").newInstance();
value.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, value);
}
@SuppressWarnings("unchecked")
public static void addParameterToParametersUri(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("uri").newInstance();
value.setValue(theValue);
addParameterToParameters(theCtx, theParameters, theName, value);
}
/**
* Add a parameter with no value (typically because we'll be adding sub-parameters)
*/
public static IBase addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName) {
RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
return createParameterRepetition(theContext, theParameters, paramChild, paramChildElem, theName);
}
public static void addPartCode(FhirContext theContext, IBase theParameter, String theName, String theCode) {
IPrimitiveType<String> value = (IPrimitiveType<String>) theContext.getElementDefinition("code").newInstance();
value.setValue(theCode);
addPart(theContext, theParameter, theName, value);
}
public static void addPartInteger(FhirContext theContext, IBase theParameter, String theName, Integer theInteger) {
IPrimitiveType<Integer> value = (IPrimitiveType<Integer>) theContext.getElementDefinition("integer").newInstance();
value.setValue(theInteger);
addPart(theContext, theParameter, theName, value);
}
public static void addPartString(FhirContext theContext, IBase theParameter, String theName, String theValue) {
IPrimitiveType<String> value = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
value.setValue(theValue);
addPart(theContext, theParameter, theName, value);
}
public static void addPartBoolean(FhirContext theContext, IBase theParameter, String theName, Boolean theValue) {
IPrimitiveType<Boolean> value = (IPrimitiveType<Boolean>) theContext.getElementDefinition("boolean").newInstance();
value.setValue(theValue);
addPart(theContext, theParameter, theName, value);
}
public static void addPartDecimal(FhirContext theContext, IBase theParameter, String theName, Double theValue) {
IPrimitiveType<BigDecimal> value = (IPrimitiveType<BigDecimal>) theContext.getElementDefinition("decimal").newInstance();
value.setValue(theValue == null ? null : new BigDecimal(theValue));
addPart(theContext, theParameter, theName, value);
}
public static void addPartCoding(FhirContext theContext, IBase theParameter, String theName, String theSystem, String theCode, String theDisplay) {
IBase coding = theContext.getElementDefinition("coding").newInstance();
BaseRuntimeElementCompositeDefinition<?> codingDef = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(coding.getClass());
codingDef.getChildByName("system").getMutator().addValue(coding, createUri(theContext, theSystem));
codingDef.getChildByName("code").getMutator().addValue(coding, createCode(theContext, theCode));
codingDef.getChildByName("display").getMutator().addValue(coding, createString(theContext, theDisplay));
addPart(theContext, theParameter, theName, coding);
}
public static void addPart(FhirContext theContext, IBase theParameter, String theName, IBase theValue) {
BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(theParameter.getClass());
BaseRuntimeChildDefinition partChild = def.getChildByName("part");
BaseRuntimeElementCompositeDefinition<?> partChildElem = (BaseRuntimeElementCompositeDefinition<?>) partChild.getChildByName("part");
IBase part = partChildElem.newInstance();
partChild.getMutator().addValue(theParameter, part);
IPrimitiveType<String> name = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
name.setValue(theName);
partChildElem.getChildByName("name").getMutator().addValue(part, name);
if (theValue instanceof IBaseResource) {
partChildElem.getChildByName("resource").getMutator().addValue(part, theValue);
} else {
partChildElem.getChildByName("value[x]").getMutator().addValue(part, theValue);
}
}
public static void addPartResource(FhirContext theContext, IBase theParameter, String theName, IBaseResource theValue) {
BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(theParameter.getClass());
BaseRuntimeChildDefinition partChild = def.getChildByName("part");
BaseRuntimeElementCompositeDefinition<?> partChildElem = (BaseRuntimeElementCompositeDefinition<?>) partChild.getChildByName("part");
IBase part = partChildElem.newInstance();
partChild.getMutator().addValue(theParameter, part);
IPrimitiveType<String> name = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
name.setValue(theName);
partChildElem.getChildByName("name").getMutator().addValue(part, name);
partChildElem.getChildByName("resource").getMutator().addValue(part, theValue);
}
public static List<String> getNamedParameterPartAsString(FhirContext theCtx, IBaseParameters theParameters, String thePartName, String theParameterName) {
return extractNamedParameterPartsAsString(theCtx, theParameters, thePartName, theParameterName);
}
// TODO KHS need to consolidate duplicated functionality that came in from different branches
private static List<String> extractNamedParameterPartsAsString(FhirContext theCtx, IBaseParameters theParameters, String thePartName, String theParameterName) {
List<IBase> parameterReps = getParameterReps(theCtx, theParameters);
List<String> retVal = new ArrayList<>();
for (IBase nextParameter : parameterReps) {
BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(nextParameter.getClass());
Optional<? extends IPrimitiveType<?>> nameValue = getNameValue(nextParameter, nextParameterDef);
if (!nameValue.isPresent() || !thePartName.equals(nameValue.get().getValueAsString())) {
continue;
}
BaseRuntimeChildDefinition partChild = nextParameterDef.getChildByName("part");
List<IBase> partValues = partChild.getAccessor().getValues(nextParameter);
for (IBase partValue : partValues) {
BaseRuntimeElementCompositeDefinition<?> partParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(partValue.getClass());
Optional<? extends IPrimitiveType<?>> partNameValue = getNameValue(partValue, partParameterDef);
if (!partNameValue.isPresent() || !theParameterName.equals(partNameValue.get().getValueAsString())) {
continue;
}
BaseRuntimeChildDefinition valueChild = partParameterDef.getChildByName("value[x]");
List<IBase> valueValues = valueChild.getAccessor().getValues(partValue);
valueValues
.stream()
.filter(t -> t instanceof IPrimitiveType<?>)
.map(t -> ((IPrimitiveType<String>) t))
.map(t -> defaultIfBlank(t.getValueAsString(), null))
.filter(t -> t != null)
.forEach(retVal::add);
}
}
return retVal;
}
private static List<IBase> getParameterReps(FhirContext theCtx, IBaseParameters theParameters) {
Validate.notNull(theParameters, "theParameters must not be null");
RuntimeResourceDefinition resDef = theCtx.getResourceDefinition(theParameters.getClass());
BaseRuntimeChildDefinition parameterChild = resDef.getChildByName("parameter");
return parameterChild.getAccessor().getValues(theParameters);
}
private static Optional<? extends IPrimitiveType<?>> getNameValue(IBase nextParameter, BaseRuntimeElementCompositeDefinition<?> theNextParameterDef) {
BaseRuntimeChildDefinition nameChild = theNextParameterDef.getChildByName("name");
List<IBase> nameValues = nameChild.getAccessor().getValues(nextParameter);
return nameValues
.stream()
.filter(t -> t instanceof IPrimitiveType<?>)
.map(t -> ((IPrimitiveType<?>) t))
.findFirst();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.examples.ajax.builtin;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.IClusterable;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
/**
* Ajax todo list without having to write any JavaScript yourself.
*
* @author Martijn Dashorst
*/
public class TodoList extends BasePage
{
/**
* The todo object.
*/
public static class TodoItem implements IClusterable
{
private static final long serialVersionUID = 1L;
/** Is the item done? */
private boolean checked;
/** Description of the item. */
private String text;
/** Constructor. */
public TodoItem()
{
}
/**
* Copy constructor.
*
* @param item
* the item to copy the values from.
*/
public TodoItem(TodoItem item)
{
text = item.text;
}
/**
* @return Returns the checked property.
*/
public boolean isChecked()
{
return checked;
}
/**
* Sets the checked property.
*
* @param checked
* The checked property to set.
*/
public void setChecked(boolean checked)
{
this.checked = checked;
}
/**
* Gets the description of the item.
*
* @return Returns the text.
*/
public String getText()
{
return text;
}
/**
* Sets the description of the item.
*
* @param text
* The text to set.
*/
public void setText(String text)
{
this.text = text;
}
}
/**
* Container for displaying the todo items in a list.
*/
public class TodoItemsContainer extends WebMarkupContainer
{
/**
* Constructor.
*
* @param id
* the component identifier.
*/
public TodoItemsContainer(String id)
{
super(id);
// let wicket generate a markup-id so the contents can be
// updated through an AJAX call.
setOutputMarkupId(true);
// add the listview to the container
add(new ListView<TodoItem>("item", items)
{
@Override
protected void populateItem(ListItem<TodoItem> item)
{
// add an AJAX checkbox to the item
item.add(new AjaxCheckBox("check", new PropertyModel<Boolean>(
item.getDefaultModel(), "checked"))
{
@Override
protected void onUpdate(AjaxRequestTarget target)
{
// no need to do anything, the model is updated by
// itself, and we don't have to re-render a
// component (the client already has the correct
// state).
}
});
// display the text of the todo item
item.add(new Label("text", new PropertyModel<String>(item.getDefaultModel(),
"text")));
}
});
}
}
/**
* Container for showing either the add link, or the addition form.
*/
public class AddItemsContainer extends WebMarkupContainer
{
/** Visibility toggle so that either the link or the form is visible. */
private boolean linkVisible = true;
/** Link for displaying the AddTodo form. */
private final class AddTodoLink extends AjaxFallbackLink
{
/** Constructor. */
private AddTodoLink(String id)
{
super(id);
}
/**
* onclick handler.
*
* @param target
* the request target.
*/
@Override
public void onClick(AjaxRequestTarget target)
{
onShowForm(target);
}
/**
* Toggles the visibility with the add form.
*
* @return <code>true</code> when the add links is visible and the form isn't.
*/
@Override
public boolean isVisible()
{
return linkVisible;
}
}
/**
* Link for removing all completed todos from the list, this link follows the same
* visibility rules as the add link.
*/
private final class RemoveCompletedTodosLink extends AjaxFallbackLink
{
/**
* Constructor.
*
* @param id
* component id
*/
public RemoveCompletedTodosLink(String id)
{
super(id);
}
/**
* @see AjaxFallbackLink#onClick(AjaxRequestTarget)
*/
@Override
public void onClick(AjaxRequestTarget target)
{
onRemoveCompletedTodos(target);
}
/**
* Toggles the visibility with the add form.
*
* @return <code>true</code> when the add links is visible and the form isn't.
*/
@Override
public boolean isVisible()
{
return linkVisible;
}
}
/**
* Displays a form which offers an edit field and two buttons: one for adding the todo item,
* and one for canceling the addition. The visibility of this component is mutual exclusive
* with the visibility of the add-link.
*/
private final class AddTodoForm extends Form<TodoItem>
{
/**
* Constructor.
*
* @param id
* the component id.
*/
public AddTodoForm(String id)
{
super(id, new CompoundPropertyModel<TodoItem>(new TodoItem()));
setOutputMarkupId(true);
add(new TextField<String>("text"));
add(new AjaxButton("add", this)
{
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
// retrieve the todo item
TodoItem item = (TodoItem)getParent().getDefaultModelObject();
// add the item
onAdd(item, target);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
}
});
add(new AjaxButton("cancel", this)
{
@Override
public void onSubmit(AjaxRequestTarget target, Form<?> form)
{
onCancelTodo(target);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
}
});
}
/**
* Toggles the visibility with the add link. When the link is visible, the form isn't.
*
* @return true when the form is visible and the link isn't.
*/
@Override
public boolean isVisible()
{
return !linkVisible;
}
}
/**
* Constructor.
*
* @param id
* the component id.
*/
public AddItemsContainer(String id)
{
super(id);
// let wicket generate a markup-id so the contents can be
// updated through an AJAX call.
setOutputMarkupId(true);
add(new AddTodoLink("link"));
add(new RemoveCompletedTodosLink("remove"));
add(new AddTodoForm("form"));
}
/**
* Called then the add link was clicked, shows the form, and hides the link.
*
* @param target
* the request target.
*/
void onShowForm(AjaxRequestTarget target)
{
// toggle the visibility
linkVisible = false;
// redraw the add container.
target.add(this);
}
void onRemoveCompletedTodos(AjaxRequestTarget target)
{
List<TodoItem> ready = new ArrayList<TodoItem>();
for (TodoItem todo : items)
{
if (todo.isChecked())
{
ready.add(todo);
}
}
items.removeAll(ready);
// repaint our panel
target.add(this);
// repaint the listview as there was a new item added.
target.add(showItems);
}
/**
* Called when the form is submitted through the add button, stores the todo item, hides the
* form, displays the add link and updates the listview.
*
* @param target
* the request target
*/
void onAdd(TodoItem item, AjaxRequestTarget target)
{
// add the item
items.add(new TodoItem(item));
// reset the model
item.setChecked(false);
item.setText("");
// toggle the visibility
linkVisible = true;
// repaint our panel
target.add(this);
// repaint the listview as there was a new item added.
target.add(showItems);
}
/**
* Called when adding a new todo item was canceled. Hides the add form and displays the add
* link.
*
* @param target
* the request target.
*/
void onCancelTodo(AjaxRequestTarget target)
{
// toggle the visibility
linkVisible = true;
// repaint the panel.
target.add(this);
}
}
/**
* Container for redrawing the todo items list with an AJAX call.
*/
private final WebMarkupContainer showItems;
/**
* The list of todo items.
*/
final List<TodoItem> items = new ArrayList<TodoItem>();
/**
* Constructor.
*/
public TodoList()
{
// add the listview container for the todo items.
showItems = new TodoItemsContainer("showItems");
add(showItems);
add(new AjaxFallbackLink<Void>("ajaxback")
{
/**
* @see org.apache.wicket.ajax.markup.html.AjaxFallbackLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
*/
@Override
public void onClick(AjaxRequestTarget target)
{
setResponsePage(getPage());
}
});
// add the add container for the todo items.
add(new AddItemsContainer("addItems"));
}
}
| |
package com.apruve.models;
import static com.apruve.Utilities.hasText;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import com.apruve.ApruveClient;
import com.apruve.ApruveResponse;
import com.apruve.JsonUtil;
import com.apruve.ShaUtil;
import com.apruve.Utilities;
/**
* A request to a payer for payment on behalf of a shopper. In order to provide
* the prospective payer with as much information as possible, and enhance the
* likelihood for approval, as much detail should be provided as possible.
*
* @author neal
*
*/
@XmlRootElement
public class PaymentRequest {
protected static final String PAYMENT_REQUESTS_PATH = "/payment_requests/";
private static final String FINALIZE_PATH = PAYMENT_REQUESTS_PATH
+ "%reqId/finalize";
@XmlJavaTypeAdapter(value = PaymentRequestStatusAdapter.class)
public static enum PaymentRequestStatus {
NEW, READY, PENDING, APPROVED, REJECTED, CANCELED;
public String getDisplay() {
return StringUtils.capitalize(this.toString());
}
}
private static class PaymentRequestStatusAdapter extends
XmlAdapter<String, PaymentRequestStatus> {
@Override
public PaymentRequestStatus unmarshal(String v) throws Exception {
return v == null ? null : PaymentRequestStatus.valueOf(v
.toUpperCase());
}
@Override
public String marshal(PaymentRequestStatus v) throws Exception {
return v == null ? null : v.toString().toLowerCase();
}
}
private String id;
@XmlElement(name = "merchant_id")
private String merchantId;
@XmlElement(name = "username")
private String username;
private PaymentRequestStatus status = PaymentRequestStatus.NEW;
@XmlElement(name = "merchant_order_id")
private String merchantOrderId;
@XmlElement(name = "amount_cents")
private Integer amountCents;
@XmlElement(name = "tax_cents")
private Integer taxCents;
@XmlElement(name = "shipping_cents")
private Integer shippingCents;
@XmlElement(name = "currency")
private String currency;
@XmlElement(name = "line_items")
private List<LineItem> lineItems;
@XmlElement(name = "api_url")
private URL apiUrl;
@XmlElement(name = "view_url")
private URL viewUrl;
@XmlElement(name = "created_at")
private Date createdAt;
@XmlElement(name = "updated_at")
private Date updatedAt;
@XmlElement(name = "expires_at")
private Date expiresAt;
protected PaymentRequest() {
// Required for JAXB
this.lineItems = new ArrayList<LineItem>();
}
public PaymentRequest(String merchantId) {
this();
this.merchantId = merchantId;
}
/**
* Fetches the PaymentRequest with the given ID from Apruve.
*
* @see <a
* href="https://www.apruve.com/doc/developers/rest-api/">https://www.apruve.com/doc/developers/rest-api/</a>
* @param paymentRequestId
* @return PaymentRequest, or null if not found
*/
public static ApruveResponse<PaymentRequest> get(String paymentRequestId) {
return ApruveClient.getInstance().get(
PAYMENT_REQUESTS_PATH + paymentRequestId, PaymentRequest.class);
}
/**
* Updates the PaymentRequest state at Apruve to match the current object
* state.
* <p>
* Only the following fields are updated by this API call, and then only if
* the payment request status is NEW:
* <ul>
* <li>merchantOrderId</li>
* <li>amountCents</li>
* <li>taxCents</li>
* <li>shippingCents</li>
* </ul>
*
* Changes to any other fields are ignored.
*
* @see <a
* href="https://www.apruve.com/doc/developers/rest-api/">https://www.apruve.com/doc/developers/rest-api/</a>
* @return PaymentRequestUpdateResponse, or null if the request does not
* exist
*/
public ApruveResponse<PaymentRequestUpdateResponse> update() {
return ApruveClient.getInstance().put(PAYMENT_REQUESTS_PATH + this.id,
this, PaymentRequestUpdateResponse.class);
}
/**
* Invokes the "finalize" action on the payment request. This allows you to
* escalate the request to the payer without creating a Payment first.
*
* @see <a
* href="https://www.apruve.com/doc/developers/rest-api/">https://www.apruve.com/doc/developers/rest-api/</a>
* @return PaymentRequestUpdateResponse, or null if the request does not
* exist
*/
public ApruveResponse<PaymentRequestUpdateResponse> finalizeRequest() {
return ApruveClient.getInstance().post(getFinalizePath(this.id), "",
PaymentRequestUpdateResponse.class);
}
@Override
public String toString() {
return toJson();
}
/**
* Returns the JSON string for a PaymentRequest.
*
* Notably, this is suitable for merchants using the apruve.js JavaScript
* library. Use this to populate the value of apruve.paymentRequest.
*
* @param paymentRequest
* @return
*/
public String toJson() {
return JsonUtil.getInstance().toJson(this);
}
/**
* For use by merchants, and depends on proper initialization of
* ApruveClient. Returns the secure hash for a PaymentRequest, suitable for
* use with the property of apruve.js JavaScript library on a merchant
* checkout page. Use this to populate the value of apruve.secureHash.
*
* @return
*/
public String toSecureHash() {
String apiKey = ApruveClient.getInstance().getApiKey();
String shaInput = apiKey + toValueString();
return ShaUtil.getDigest(shaInput);
}
protected String toValueString() {
StringBuilder buf = new StringBuilder();
buf.append(StringUtils.defaultString(merchantId));
buf.append(StringUtils.defaultString(merchantOrderId));
if (amountCents != null)
buf.append(amountCents);
if (currency != null)
buf.append(currency);
if (taxCents != null)
buf.append(taxCents);
if (shippingCents != null)
buf.append(shippingCents);
if (expiresAt != null)
{
buf.append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(expiresAt));
}
for (LineItem line : lineItems) {
buf.append(line.toValueString());
}
return buf.toString();
}
public void addLineItem(LineItem item) {
this.lineItems.add(item);
}
//////////////////////
// Getters and Setters
//////////////////////
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the merchantId
*/
public String getMerchantId() {
return merchantId;
}
/**
* @param merchantId
* the merchantId to set
*/
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
/**
* @return the status
*/
public PaymentRequestStatus getStatus() {
return status;
}
/**
* @param status
* the status to set
*/
protected void setStatus(PaymentRequestStatus status) {
this.status = status;
}
/**
* @param status
* the status to set
*/
public void setStatus(String status) {
this.status = PaymentRequestStatus.valueOf(status.toUpperCase());
}
/**
* @return the merchantOrderId
*/
public String getMerchantOrderId() {
return merchantOrderId;
}
/**
* @param merchantOrderId
* the merchantOrderId to set
*/
public void setMerchantOrderId(String merchantOrderId) {
this.merchantOrderId = merchantOrderId;
}
/**
* @return the amountCents
*/
public Integer getAmountCents() {
return amountCents;
}
/**
* @param amountCents
* the amountCents to set
*/
public void setAmountCents(Integer amountCents) {
this.amountCents = amountCents;
}
/**
* @param amountCents
* the amountCents to set
*/
public void setAmountCents(String amountCents) {
this.amountCents = hasText(amountCents) ? new Integer(amountCents)
: null;
}
/**
* @return the taxCents
*/
public Integer getTaxCents() {
return taxCents;
}
/**
* @param taxCents
* the taxCents to set
*/
public void setTaxCents(Integer taxCents) {
this.taxCents = taxCents;
}
/**
* @param taxCents
* the taxCents to set
*/
public void setTaxCents(String taxCents) {
this.taxCents = hasText(taxCents) ? new Integer(taxCents) : null;
}
/**
* @return the shippingCents
*/
public Integer getShippingCents() {
return shippingCents;
}
/**
* @param shippingCents
* the shippingCents to set
*/
public void setShippingCents(Integer shippingCents) {
this.shippingCents = shippingCents;
}
/**
* @param shippingCents
*/
public void setShippingCents(String shippingCents) {
this.shippingCents = hasText(shippingCents) ? new Integer(shippingCents)
: null;
}
/**
* @return the currency
*/
public Currency getCurrency() {
return Currency.getInstance(currency);
}
/**
* @param currency
* the currency to set
*/
public void setCurrency(Currency currency) {
this.currency = currency.getCurrencyCode();
}
/**
* @param currency
* the currency to set
*/
public void setCurrency(String currency) {
this.currency = hasText(currency) ? Currency.getInstance(currency).getCurrencyCode()
: null;
}
/**
* @return the lineItems
*/
public List<LineItem> getLineItems() {
return lineItems;
}
/**
* @param lineItems
* the lineItems to set
*/
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
/**
* @return the apiUrl
*/
public URL getApiUrl() {
return apiUrl;
}
/**
* @param apiUrl
* the apiUrl to set
*/
protected void setApiUrl(URL apiUrl) {
this.apiUrl = apiUrl;
}
/**
* @param apiUrl
* the apiUrl to set
* @throws MalformedURLException
*/
protected void setApiUrl(String apiUrl) throws MalformedURLException {
this.apiUrl = hasText(apiUrl) ? new URL(apiUrl) : null;
}
/**
* @return the viewUrl
*/
public URL getViewUrl() {
return viewUrl;
}
/**
* @param viewUrl
* the viewUrl to set
*/
protected void setViewUrl(URL viewUrl) {
this.viewUrl = viewUrl;
}
/**
* @param viewUrl
* the viewUrl to set
* @throws MalformedURLException
*/
protected void setViewUrl(String viewUrl) throws MalformedURLException {
this.viewUrl = hasText(viewUrl) ? new URL(viewUrl) : null;
}
/**
* @return the createdAt
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @param createdAt
* the createdAt to set
*/
protected void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* @param createdAt
* the createdAt to set
*/
protected void setCreatedAt(String createdAt) {
this.createdAt = Utilities.parseTimestamp(createdAt);
}
/**
* @return the updatedAt
*/
public Date getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt
* the updatedAt to set
*/
protected void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
/**
* @param updatedAt
*/
protected void setUpdatedAt(String updatedAt) {
this.updatedAt = Utilities.parseTimestamp(updatedAt);
}
/**
* @return the expiresAt
*/
public Date getExpiresAt() {
return expiresAt;
}
/**
* @param expiresAt
*/
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
/**
* @param expiresAt
*/
public void setExpiresAt(String expiresAt) {
this.expiresAt = Utilities.parseTimestamp(expiresAt);
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
public static String getPaymentRequestsPath() {
return PAYMENT_REQUESTS_PATH;
}
public static String getFinalizePath(String paymentRequestId) {
return FINALIZE_PATH.replace("%reqId", paymentRequestId);
}
}
| |
package org.odata4j.producer.resources;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ContextResolver;
import org.odata4j.core.ODataConstants;
import org.odata4j.core.ODataHttpMethod;
import org.odata4j.core.ODataVersion;
import org.odata4j.core.OEntity;
import org.odata4j.core.OEntityId;
import org.odata4j.core.OEntityIds;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OFunctionParameter;
import org.odata4j.core.OFunctionParameters;
import org.odata4j.edm.EdmCollectionType;
import org.odata4j.edm.EdmDataServices;
import org.odata4j.edm.EdmEntitySet;
import org.odata4j.edm.EdmEntityType;
import org.odata4j.edm.EdmFunctionImport;
import org.odata4j.edm.EdmFunctionParameter;
import org.odata4j.edm.EdmProperty.CollectionKind;
import org.odata4j.edm.EdmType;
import org.odata4j.exceptions.MethodNotAllowedException;
import org.odata4j.exceptions.NotImplementedException;
import org.odata4j.format.FormatParser;
import org.odata4j.format.FormatParserFactory;
import org.odata4j.format.FormatType;
import org.odata4j.format.FormatWriter;
import org.odata4j.format.FormatWriterFactory;
import org.odata4j.format.Parameters;
import org.odata4j.format.Settings;
import org.odata4j.format.jsonlite.OdataJsonLiteConstant;
import org.odata4j.producer.BaseResponse;
import org.odata4j.producer.CollectionResponse;
import org.odata4j.producer.ComplexObjectResponse;
import org.odata4j.producer.EntitiesResponse;
import org.odata4j.producer.EntityResponse;
import org.odata4j.producer.OBindingResolverExtension;
import org.odata4j.producer.OBindingResolverExtensions;
import org.odata4j.producer.ODataContext;
import org.odata4j.producer.ODataContextImpl;
import org.odata4j.producer.ODataProducer;
import org.odata4j.producer.PropertyResponse;
import org.odata4j.producer.QueryInfo;
import org.odata4j.producer.Responses;
import org.odata4j.producer.SimpleResponse;
/**
* Handles function calls.
*
* <p>Unfortunately the OData URI scheme makes it
* impossible to differentiate a function call "resource" from an EntitySet.
* So, we hack: EntitiesRequestResource and EntityRequestResource
* delegates to this class if it determines that a function is being referenced.
*
* <ul>TODO:
* <li>function parameter facets (required, value ranges, etc). For now, all
* validation is up to the function handler in the producer.
* <li>non-simple function parameter types
* <li>make sure this works for GET and POST
*/
public class FunctionResource extends BaseResource {
@GET
@Produces({
ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response callBoundFunction(
@Context HttpHeaders httpHeaders,
@Context UriInfo uriInfo,
@Context ContextResolver<ODataProducer> producerResolver,
@Context SecurityContext securityContext,
@PathParam("entitySetName") String entitySetName,
@PathParam("id") String id,
@PathParam("navProp") String fqFunction,
@QueryParam("$inlinecount") String inlineCount,
@QueryParam("$top") String top,
@QueryParam("$skip") String skip,
@QueryParam("$filter") String filter,
@QueryParam("$orderby") String orderBy,
@QueryParam("$format") String format,
@QueryParam("$callback") String callback,
@QueryParam("$skiptoken") String skipToken,
@QueryParam("$expand") String expand,
@QueryParam("$select") String select) throws Exception {
ODataProducer producer = producerResolver.getContext(ODataProducer.class);
QueryInfo query = new QueryInfo(
OptionsQueryParser.parseInlineCount(inlineCount),
OptionsQueryParser.parseTop(top),
OptionsQueryParser.parseSkip(skip),
OptionsQueryParser.parseFilter(filter),
OptionsQueryParser.parseOrderBy(orderBy),
OptionsQueryParser.parseSkipToken(skipToken),
OptionsQueryParser.parseCustomOptions(uriInfo),
OptionsQueryParser.parseExpand(expand),
OptionsQueryParser.parseSelect(select));
int separatorPos = fqFunction.indexOf(".");
String functionName = fqFunction.substring(separatorPos + 1);
OEntityKey key = null;
if (id != null){
key = OEntityKey.parse(id);
}
if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
// functions that return collections of entities should support the
// same set of query options as entity set queries so give them everything.
return callFunction(
ODataHttpMethod.GET,
httpHeaders,
uriInfo,
securityContext,
producer,
functionName,
format,
callback,
query,
entitySetName,
key,
null);
}
return Response.status(Status.NOT_FOUND).build();
}
@POST
@Produces({
ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
public Response callBoundAction(
@Context HttpHeaders httpHeaders,
@Context UriInfo uriInfo,
@Context ContextResolver<ODataProducer> producerResolver,
@Context SecurityContext securityContext,
@PathParam("entitySetName") String entitySetName,
@PathParam("id") String id,
@PathParam("navProp") String fqAction,
@QueryParam("$inlinecount") String inlineCount,
@QueryParam("$top") String top,
@QueryParam("$skip") String skip,
@QueryParam("$filter") String filter,
@QueryParam("$orderby") String orderBy,
@QueryParam("$format") String format,
@QueryParam("$callback") String callback,
@QueryParam("$skiptoken") String skipToken,
@QueryParam("$expand") String expand,
@QueryParam("$select") String select,
InputStream payload) throws Exception {
ODataProducer producer = producerResolver.getContext(ODataProducer.class);
QueryInfo query = new QueryInfo(
OptionsQueryParser.parseInlineCount(inlineCount),
OptionsQueryParser.parseTop(top),
OptionsQueryParser.parseSkip(skip),
OptionsQueryParser.parseFilter(filter),
OptionsQueryParser.parseOrderBy(orderBy),
OptionsQueryParser.parseSkipToken(skipToken),
OptionsQueryParser.parseCustomOptions(uriInfo),
OptionsQueryParser.parseExpand(expand),
OptionsQueryParser.parseSelect(select));
int separatorPos = fqAction.indexOf(".");
String functionName = fqAction.substring(separatorPos + 1);
OEntityKey key = OEntityKey.parse(id);
if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
// functions that return collections of entities should support the
// same set of query options as entity set queries so give them everything.
return callFunction(
ODataHttpMethod.POST,
httpHeaders,
uriInfo,
securityContext,
producer,
functionName,
format,
callback,
query,
entitySetName,
key,
payload);
}
return Response.status(Status.NOT_FOUND).build();
}
/**
* Handles function call resource access by gathering function call info from
* the request and delegating to the producer.
*/
public static Response callFunction(
ODataHttpMethod callingMethod,
HttpHeaders httpHeaders,
UriInfo uriInfo,
SecurityContext securityContext,
ODataProducer producer,
String functionName,
String format,
String callback,
QueryInfo queryInfo) throws Exception {
return callFunction(callingMethod, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, queryInfo, null, null, null);
}
/**
* Handles function call resource access by gathering function call info from
* the request and delegating to the producer.
*/
@SuppressWarnings("rawtypes")
public static Response callFunction(
ODataHttpMethod callingMethod,
HttpHeaders httpHeaders,
UriInfo uriInfo,
SecurityContext securityContext,
ODataProducer producer,
String functionName,
String format,
String callback,
QueryInfo queryInfo,
String boundEntitySetName,
OEntityKey boundEntityKey,
InputStream payload) throws Exception {
// do we have this function?
EdmType bindingType = null;
if (boundEntitySetName != null) {
EdmEntitySet entitySet = producer.getMetadata().findEdmEntitySet(boundEntitySetName);
if (entitySet != null){
bindingType = entitySet.getType();
if (boundEntityKey == null) {
// The binding type is a collection as we don't have the entity key
bindingType = new EdmCollectionType(CollectionKind.Collection, bindingType);
}
}
}
EdmFunctionImport function = producer.getMetadata().findEdmFunctionImport(functionName, bindingType);
if (function == null) {
return Response.status(Status.NOT_FOUND).build();
}
ODataContext context = ODataContextImpl.builder().aspect(httpHeaders).aspect(securityContext).aspect(producer).build();
// Check HTTP method
String expectedHttpMethodString = function.getHttpMethod();
if (expectedHttpMethodString != null && !"".equals(expectedHttpMethodString)) {
ODataHttpMethod expectedHttpMethod = ODataHttpMethod.fromString(expectedHttpMethodString);
if (expectedHttpMethod != callingMethod) {
throw new MethodNotAllowedException("Method " + callingMethod + " not allowed, expecting " + expectedHttpMethodString);
}
}
// Prepare binding resolver
OBindingResolverExtension resolverExtension = producer.findExtension(OBindingResolverExtension.class);
if (resolverExtension == null){
resolverExtension = OBindingResolverExtensions.getPartialBindingResolver();
}
// First take the parameters from the query
Map<String, OFunctionParameter> parameters = getFunctionParameters(function, queryInfo.customOptions, resolverExtension, context, queryInfo);
// Then try the payload if any
if (payload != null) {
parameters.putAll(getFunctionParameters(producer.getMetadata(), function, payload, httpHeaders.getAcceptableMediaTypes()));
}
// Use the bound parameter if any
if (boundEntitySetName != null && function.isBindable()) {
OFunctionParameter boundParam = resolverExtension.resolveBindingParameter(context, function, boundEntitySetName, boundEntityKey, queryInfo);
parameters.put(boundParam.getName(), boundParam);
}
// Execute the call
BaseResponse response = producer.callFunction(context, function, parameters, queryInfo);
if (response == null) {
return Response.status(Status.NO_CONTENT).build();
}
ODataVersion version = ODataConstants.DATA_SERVICE_VERSION;
StringWriter sw = new StringWriter();
FormatWriter<?> fwBase;
// hmmh...we are missing an abstraction somewhere..
if (response instanceof ComplexObjectResponse) {
FormatWriter<ComplexObjectResponse> fw =
FormatWriterFactory.getFormatWriter(
ComplexObjectResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, (ComplexObjectResponse) response);
fwBase = fw;
} else if (response instanceof CollectionResponse) {
CollectionResponse<?> collectionResponse = (CollectionResponse<?>) response;
if (collectionResponse.getCollection().getType() instanceof EdmEntityType) {
FormatWriter<EntitiesResponse> fw = FormatWriterFactory.getFormatWriter(
EntitiesResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
// collection of entities.
// Does anyone else see this in the v2 spec? I sure don't. This seems
// reasonable though given that inlinecount and skip tokens might be included...
ArrayList<OEntity> entities = new ArrayList<OEntity>(collectionResponse.getCollection().size());
Iterator iter = collectionResponse.getCollection().iterator();
while (iter.hasNext()) {
entities.add((OEntity) iter.next());
}
EntitiesResponse er = Responses.entities(entities,
collectionResponse.getEntitySet(),
collectionResponse.getInlineCount(),
collectionResponse.getSkipToken());
fw.write(uriInfo, sw, er);
fwBase = fw;
} else {
// non-entities
FormatWriter<CollectionResponse> fw = FormatWriterFactory.getFormatWriter(
CollectionResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, collectionResponse);
fwBase = fw;
}
} else if (response instanceof EntitiesResponse) {
FormatWriter<EntitiesResponse> fw = FormatWriterFactory.getFormatWriter(
EntitiesResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, (EntitiesResponse) response);
fwBase = fw;
} else if (response instanceof PropertyResponse) {
FormatWriter<PropertyResponse> fw =
FormatWriterFactory.getFormatWriter(
PropertyResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, (PropertyResponse) response);
fwBase = fw;
} else if (response instanceof SimpleResponse) {
FormatWriter<SimpleResponse> fw =
FormatWriterFactory.getFormatWriter(
SimpleResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, (SimpleResponse) response);
fwBase = fw;
} else if (response instanceof EntityResponse) {
FormatWriter<EntityResponse> fw =
FormatWriterFactory.getFormatWriter(
EntityResponse.class,
httpHeaders.getAcceptableMediaTypes(),
format,
callback);
fw.write(uriInfo, sw, (EntityResponse) response);
fwBase = fw;
} else {
// TODO add in other response types.
throw new NotImplementedException("Unknown BaseResponse type: " + response.getClass().getName());
}
String entity = sw.toString();
return Response.ok(entity, fwBase.getContentType())
.header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString)
.build();
}
/**
* Takes a Map<String,String> filled with the request URIs custom parameters and
* turns them into a map of strongly-typed OFunctionParameter objects.
*
* @param function the current function
* @param opts the query string
* @param resolver a binding resolver
* @param context the current context
* @param queryInfo the current queryInfo
* @return a map of function parameters
*/
private static Map<String, OFunctionParameter> getFunctionParameters(
EdmFunctionImport function,
Map<String, String> opts,
OBindingResolverExtension resolver,
ODataContext context,
QueryInfo queryInfo) {
// first get the producer, we need it to get metadata to pase entity and collections
ODataProducer producer = context.getContextAspect(ODataProducer.class);
Map<String, OFunctionParameter> m = new HashMap<String, OFunctionParameter>();
for (EdmFunctionParameter p : function.getParameters()) {
String val = opts.get(p.getName());
if (function.isBindable() && p.isBound() && val != null){
String entitySetName = null;
OEntityKey entityKey = null;
if (p.getType() instanceof EdmCollectionType){
entitySetName = val;
} else {
OEntityId entityId = OEntityIds.parse(val);
entitySetName = entityId.getEntitySetName();
entityKey = entityId.getEntityKey();
}
m.put(p.getName(), resolver.resolveBindingParameter(context, function, entitySetName, entityKey, queryInfo));
} else {
m.put(p.getName(), val == null ? null : OFunctionParameters.parse(producer.getMetadata(), p.getName(), p.getType(), val));
}
}
return m;
}
/**
* Takes the payload and turns it into a map of strongly-typed
* OFunctionParameter objects.
*
* @param dataServices the service metadata
* @param function the function being called
* @param payload the post payload
* @param acceptTypes the accept types
* @return the function parameters
*/
private static Map<String, OFunctionParameter> getFunctionParameters(EdmDataServices dataServices, EdmFunctionImport function, InputStream payload, List<MediaType> acceptTypes) {
Map<String, OFunctionParameter> m = new HashMap<String, OFunctionParameter>();
Settings settings = new Settings(ODataConstants.DATA_SERVICE_VERSION, dataServices, null, null, null, false, null, function);
FormatType type = FormatType.JSONVERBOSE;
for (MediaType acceptType : acceptTypes) {
if (acceptType.getType().equals(MediaType.APPLICATION_JSON_TYPE.getType()) &&
acceptType.getSubtype().equals(MediaType.APPLICATION_JSON_TYPE.getSubtype())) {
Map<String, String> parameters = acceptType.getParameters();
if (parameters.containsValue(OdataJsonLiteConstant.VERBOSE_VALUE)) {
type = FormatType.JSONVERBOSE;
break;
}
else {
type = FormatType.JSON;
break;
}
}
}
FormatParser<Parameters> parser = FormatParserFactory.getParser(Parameters.class, type, settings);
Parameters params = parser.parse(new InputStreamReader(payload));
for (OFunctionParameter param : params.getParameters()) {
m.put(param.getName(), param);
}
return m;
}
}
| |
package mil.nga.mapcache.preferences;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import mil.nga.mapcache.R;
/**
* Fragment giving the user a way to modify a saved list of URLs, which will be used in the create
* tile layer wizard
*/
public class BasemapSettingsFragment extends PreferenceFragmentCompat
implements Preference.OnPreferenceChangeListener {
/**
* The model.
*/
private BasemapSettings model = new BasemapSettings();
/**
* The controller.
*/
private BasemapSettingsController controller;
/**
* The list of available basemaps.
*/
private ExpandableListView listView;
/**
* Used to create each row view.
*/
private LayoutInflater inflater;
/**
* The activity.
*/
private Activity activity;
/**
* List of the default map layers.
*/
private List<Button> exclusiveButtons = new ArrayList<>();
/**
* The no grid radio button.
*/
private RadioButton gridNone;
/**
* The GARS grid radio button.
*/
private RadioButton gridGARS;
/**
* The MGRS grid radio button.
*/
private RadioButton gridMGRS;
/**
* Constructor.
*
* @param activity The activity.
*/
public BasemapSettingsFragment(Activity activity) {
this.activity = activity;
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
}
/**
* Create the parent view and set up listeners
*
* @param inflater Layout inflator
* @param container Main container
* @param savedInstanceState Saved instance state
* @return Parent view for the fragment
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflater = inflater;
View basemapView = inflater.inflate(R.layout.base_map_settings, container, false);
listView = basemapView.findViewById(R.id.expandableListView);
this.controller = new BasemapSettingsController(
activity,
getPreferenceManager().getSharedPreferences(),
model);
listView.setAdapter(new BasemapExpandableListAdapter(inflater, model));
Button mapButton = basemapView.findViewById(R.id.mapButton);
mapButton.setOnClickListener(view -> exclusiveMapClicked(view));
mapButton.setOnTouchListener((view, motionEvent) -> keepPressed(view, motionEvent));
mapButton.setPressed(true);
exclusiveButtons.add(mapButton);
Button satButton = basemapView.findViewById(R.id.satButton);
satButton.setOnClickListener(view -> exclusiveMapClicked(view));
satButton.setOnTouchListener((view, motionEvent) -> keepPressed(view, motionEvent));
exclusiveButtons.add(satButton);
Button terrainButton = basemapView.findViewById(R.id.terrainButton);
terrainButton.setOnClickListener(view -> exclusiveMapClicked(view));
terrainButton.setOnTouchListener((view, motionEvent) -> keepPressed(view, motionEvent));
exclusiveButtons.add(terrainButton);
this.gridNone = basemapView.findViewById(R.id.gridNone);
this.gridNone.setOnCheckedChangeListener((button, isChecked) -> {
if (isChecked) {
this.model.getGridOverlaySettings().setSelectedGrid(GridType.NONE);
}
});
this.gridGARS = basemapView.findViewById(R.id.gridGars);
this.gridGARS.setOnCheckedChangeListener((button, isChecked) -> {
if (isChecked) {
this.model.getGridOverlaySettings().setSelectedGrid(GridType.GARS);
}
});
this.gridMGRS = basemapView.findViewById(R.id.gridMGRS);
this.gridMGRS.setOnCheckedChangeListener((button, isChecked) -> {
if (isChecked) {
this.model.getGridOverlaySettings().setSelectedGrid(GridType.MGRS);
}
});
model.addObserver((observable, o) -> modelUpdate(observable, o));
model.getGridOverlaySettings().addObserver((observable, o) -> modelUpdate(observable, o));
updateButtonColors();
updateGridChecked();
Button newServerButton = basemapView.findViewById(R.id.button);
newServerButton.setOnClickListener(view -> launchSavedUrls());
return basemapView;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return false;
}
@Override
public void onResume() {
super.onResume();
this.controller.loadModel();
}
/**
* Called when any of the exclusive basemap buttons are clicked.
*
* @param view The button.
*/
private void exclusiveMapClicked(View view) {
Button button = (Button) view;
BasemapServerModel mapModel = getExclusiveModel(button.getText().toString());
if (mapModel != null) {
addExclusiveToSelected(mapModel);
}
}
/**
* Gets the exclusive server model based on its name.
*
* @param name The name of the server to get.
* @return The exclusive server model or null.
*/
private BasemapServerModel getExclusiveModel(String name) {
BasemapServerModel theOne = null;
for (BasemapServerModel server : model.getExclusiveServers()) {
if (server.getName().toLowerCase(Locale.ROOT).equals(name.toLowerCase(Locale.ROOT))) {
theOne = server;
break;
}
}
return theOne;
}
/**
* Adds the base map to the list of selected basemaps.
*
* @param exclusive The base map to add to selection and replace existing exclusive base map.
*/
private void addExclusiveToSelected(BasemapServerModel exclusive) {
BasemapServerModel[] selected = model.getSelectedBasemap();
if (selected == null || selected.length == 0) {
selected = new BasemapServerModel[1];
}
selected[0] = exclusive;
model.setSelectedBasemap(selected);
}
/**
* Called whenever the model changes.
*
* @param observable The model.
* @param o The property that changed.
*/
private void modelUpdate(Observable observable, Object o) {
if (BasemapSettings.SELECTED_BASEMAP_PROP.equals(o)
|| BasemapSettings.EXCLUSIVE_SERVERS_PROP.equals(o)) {
updateButtonColors();
} else if (GridSettingsModel.SELECTED_GRID_PROPERTY.equals(o)) {
updateGridChecked();
}
}
/**
* Keeps the buttons in a pressed state.
*
* @param view The button.
* @param motionEvent The event.
* @return True.
*/
private boolean keepPressed(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
Button button = (Button) view;
button.setPressed(true);
exclusiveMapClicked(view);
}
return true;
}
/**
* Launches the saved urls settings page to allow user to add more tile servers.
*/
private void launchSavedUrls() {
Intent myIntent = new Intent(this.activity, TileUrlActivity.class);
this.activity.startActivity(myIntent);
}
/**
* Updates the button colors to reflect which base map is currently the defaulted one.
*/
private void updateButtonColors() {
if (model.getSelectedBasemap() != null && model.getSelectedBasemap().length > 0
&& model.getExclusiveServers() != null) {
BasemapServerModel exclusiveLayer = model.getSelectedBasemap()[0];
String name = "";
for (BasemapServerModel anExclusive : model.getExclusiveServers()) {
if (anExclusive.getServerUrl().equals(exclusiveLayer.getServerUrl())) {
name = anExclusive.getName();
break;
}
}
for (Button exclusiveButton : exclusiveButtons) {
if (exclusiveButton.getText().toString().equals(name)) {
exclusiveButton.setPressed(true);
} else {
exclusiveButton.setPressed(false);
}
}
}
}
/**
* Updates which grid is selected.
*/
private void updateGridChecked() {
if (model.getGridOverlaySettings().getSelectedGrid() == GridType.NONE) {
this.gridNone.setChecked(true);
} else if (model.getGridOverlaySettings().getSelectedGrid() == GridType.GARS) {
this.gridGARS.setChecked(true);
} else if (model.getGridOverlaySettings().getSelectedGrid() == GridType.MGRS) {
this.gridMGRS.setChecked(true);
}
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.xml;
import com.intellij.openapi.util.Pair;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.xml.impl.DomInvocationHandler;
import com.intellij.util.xml.impl.DomManagerImpl;
import com.intellij.util.xml.reflect.AbstractDomChildrenDescription;
import net.sf.cglib.proxy.AdvancedProxy;
import net.sf.cglib.proxy.InvocationHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
/**
* @author peter
*/
public final class ModelMergerImpl implements ModelMerger {
private final List<Pair<InvocationStrategy, Class<?>>> myInvocationStrategies = new ArrayList<>();
private final List<MergingStrategy> myMergingStrategies = new ArrayList<>();
private final List<Class<?>> myMergingStrategyClasses = new ArrayList<>();
private static final Class<MergedObject> MERGED_OBJECT_CLASS = MergedObject.class;
private final ConcurrentMap<Method, List<Pair<InvocationStrategy,Class<?>>>> myAcceptsCache = ConcurrentFactoryMap.createMap(method-> {
List<Pair<InvocationStrategy, Class<?>>> result = new ArrayList<>();
for (int i = myInvocationStrategies.size() - 1; i >= 0; i--) {
final Pair<InvocationStrategy, Class<?>> pair = myInvocationStrategies.get(i);
if (pair.first.accepts(method)) {
result.add(pair);
}
}
return result;
}
);
public ModelMergerImpl() {
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return true;
}
@Override
public Object invokeMethod(final JavaMethod javaMethod, final Object proxy, final Object[] args, final List<?> implementations)
throws IllegalAccessException, InvocationTargetException {
final Method method = javaMethod.getMethod();
List<Object> results =
getMergedImplementations(method, args, method.getReturnType(), implementations, isIntersectionMethod(javaMethod));
return results.isEmpty() ? null : results.get(0);
}
});
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return Collection.class.isAssignableFrom(method.getReturnType());
}
@Override
public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations)
throws IllegalAccessException, InvocationTargetException {
final Type type = DomReflectionUtil.extractCollectionElementType(method.getGenericReturnType());
assert type != null : "No generic return type in method " + method;
return getMergedImplementations(method.getMethod(), args, ReflectionUtil.getRawType(type), implementations,
isIntersectionMethod(method));
}
});
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return Object.class.equals(method.getDeclaringClass());
}
@Override
public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations) {
@NonNls String methodName = method.getName();
if ("toString".equals(methodName)) {
return "Merger: " + implementations;
}
if ("hashCode".equals(methodName)) {
int result = 1;
for (Object element : implementations) {
result = 31 * result + element.hashCode();
}
return result;
}
if ("equals".equals(methodName)) {
final Object arg = args[0];
return arg instanceof MergedObject && implementations.equals(((MergedObject)arg).getImplementations());
}
return null;
}
});
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return "isValid".equals(method.getName());
}
@Override
public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations) {
for (final Object implementation : implementations) {
if (!((Boolean)method.invoke(implementation, args))) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
});
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return void.class.equals(method.getReturnType());
}
@Override
public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations) {
for (final Object t : implementations) {
method.invoke(t, args);
}
return null;
}
});
addInvocationStrategy(Object.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return MERGED_OBJECT_CLASS.equals(method.getDeclaringClass());
}
@Override
public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations) {
assert "getImplementations".equals(method.getName());
return implementations;
}
});
addInvocationStrategy(DomElement.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return DomInvocationHandler.ACCEPT_METHOD.equals(method);
}
@Override
public Object invokeMethod(final JavaMethod method,
final DomElement proxy,
final Object[] args,
final List<? extends DomElement> implementations) {
final DomElementVisitor visitor = (DomElementVisitor)args[0];
((DomManagerImpl)implementations.get(0).getManager()).getApplicationComponent().getVisitorDescription(visitor.getClass())
.acceptElement(visitor, proxy);
return null;
}
});
addInvocationStrategy(DomElement.class, new InvocationStrategy<>() {
@Override
public boolean accepts(final Method method) {
return DomInvocationHandler.ACCEPT_CHILDREN_METHOD.equals(method);
}
@Override
public Object invokeMethod(final JavaMethod method,
final DomElement proxy,
final Object[] args,
final List<? extends DomElement> implementations) {
final DomElementVisitor visitor = (DomElementVisitor)args[0];
for (final AbstractDomChildrenDescription description : implementations.get(0).getGenericInfo().getChildrenDescriptions()) {
for (final DomElement value : description.getValues(proxy)) {
value.accept(visitor);
}
}
return null;
}
});
}
private static boolean isIntersectionMethod(final JavaMethod javaMethod) {
return javaMethod.getMethod().getAnnotation(Intersect.class) != null;
}
@Override
public <T> void addInvocationStrategy(Class<T> aClass, InvocationStrategy<T> strategy) {
myInvocationStrategies.add(Pair.create(strategy, aClass));
}
@Override
public <T> void addMergingStrategy(Class<T> aClass, MergingStrategy<T> strategy) {
myMergingStrategies.add(strategy);
myMergingStrategyClasses.add(aClass);
}
@Override
public <T> T mergeModels(final Class<T> aClass, final T... implementations) {
if (implementations.length == 1) return implementations[0];
final MergingInvocationHandler<T> handler = new MergingInvocationHandler<>(aClass, Arrays.asList(implementations));
return _mergeModels(aClass, handler, implementations);
}
@Override
public <T> T mergeModels(final Class<T> aClass, final Collection<? extends T> implementations) {
return (T)mergeModels((Class)aClass, implementations.toArray());
}
private <T> T _mergeModels(final Class<? super T> aClass, final MergingInvocationHandler<T> handler, final T... implementations) {
final Set<Class<?>> commonClasses = getCommonClasses(new HashSet<>(), implementations);
commonClasses.add(MERGED_OBJECT_CLASS);
commonClasses.add(aClass);
return AdvancedProxy.createProxy(handler, null, commonClasses.toArray(ArrayUtil.EMPTY_CLASS_ARRAY));
}
private static <T extends Collection<Class<?>>> T getCommonClasses(final T result, final Object... implementations) {
if (implementations.length > 0) {
DomUtil.getAllInterfaces(implementations[0].getClass(), result);
for (int i = 1; i < implementations.length; i++) {
final ArrayList<Class<?>> list1 = new ArrayList<>();
DomUtil.getAllInterfaces(implementations[i].getClass(), list1);
result.retainAll(list1);
}
}
return result;
}
private static final Map<Class<?>, Method> ourPrimaryKeyMethods = new HashMap<>();
public class MergingInvocationHandler<T> implements InvocationHandler {
private final Class<? super T> myClass;
private List<? extends T> myImplementations;
public MergingInvocationHandler(final Class<T> aClass, final List<? extends T> implementations) {
this(aClass);
for (final T implementation : implementations) {
if (implementation instanceof StableElement) {
throw new AssertionError("Stable values merging is prohibited: " + implementation);
}
}
myImplementations = implementations;
}
public MergingInvocationHandler(final Class<T> aClass) {
myClass = aClass;
}
@NotNull
private InvocationStrategy findStrategy(final Object proxy, final Method method) {
for (Pair<InvocationStrategy, Class<?>> pair : myAcceptsCache.get(method)) {
if (Object.class.equals(pair.second) || pair.second.isInstance(proxy)) {
return pair.first;
}
}
throw new AssertionError("impossible");
}
@Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
try {
return findStrategy(proxy, method).invokeMethod(getJavaMethod(method), proxy, args, myImplementations);
}
catch (InvocationTargetException e) {
throw e.getCause();
}
}
private JavaMethod getJavaMethod(final Method method) {
if (ReflectionUtil.isAssignable(MERGED_OBJECT_CLASS, method.getDeclaringClass())) {
return JavaMethod.getMethod(MERGED_OBJECT_CLASS, method);
}
if (ReflectionUtil.isAssignable(method.getDeclaringClass(), myClass)) {
return JavaMethod.getMethod(myClass, method);
}
return JavaMethod.getMethod(method.getDeclaringClass(), method);
}
}
@Nullable
private static Object getPrimaryKey(Object implementation, final boolean singleValuedInvocation) {
final Method method = getPrimaryKeyMethod(implementation.getClass());
if (method != null) {
final Object o = DomReflectionUtil.invokeMethod(method, implementation);
return ReflectionUtil.isAssignable(GenericValue.class, method.getReturnType()) ? ((GenericValue)o).getValue() : o;
}
else {
if (implementation instanceof GenericValue) {
return singleValuedInvocation? Boolean.TRUE : ((GenericValue)implementation).getValue();
}
else {
return null;
}
}
}
@Nullable
private static Method getPrimaryKeyMethod(final Class<?> aClass) {
Method method = ourPrimaryKeyMethods.get(aClass);
if (method == null) {
if (ourPrimaryKeyMethods.containsKey(aClass)) return null;
for (final Method method1 : ReflectionUtil.getClassPublicMethods(aClass)) {
if ((method = findPrimaryKeyAnnotatedMethod(method1, aClass)) != null) {
break;
}
}
ourPrimaryKeyMethods.put(aClass, method);
}
return method;
}
@Nullable
private static Method findPrimaryKeyAnnotatedMethod(@NotNull Method sampleMethod, @NotNull Class<?> aClass) {
if (sampleMethod.getParameterCount() != 0 || sampleMethod.getReturnType() == void.class) {
return null;
}
return JavaMethodSignature.findMethod(sampleMethod, aClass, method -> method.isAnnotationPresent(PrimaryKey.class));
}
private List<Object> getMergedImplementations(final Method method,
final Object[] args,
final Class returnType,
final List<?> implementations,
final boolean intersect) throws IllegalAccessException, InvocationTargetException {
final List<Object> results = new ArrayList<>();
if (returnType.isInterface()) {
final List<Object> orderedPrimaryKeys = new SmartList<>();
final Map<Object, List<Set<Object>>> map = FactoryMap.create(key -> {
orderedPrimaryKeys.add(key);
return new SmartList<>();
});
final Map<Object, int[]> counts = FactoryMap.create(key -> new int[implementations.size()]);
for (int i = 0; i < implementations.size(); i++) {
Object t = implementations.get(i);
final Object o = method.invoke(t, args);
if (o instanceof Collection) {
for (final Object o1 : (Collection)o) {
addToMaps(o1, counts, map, i, results, false, intersect);
}
}
else if (o != null) {
addToMaps(o, counts, map, i, results, true, intersect);
}
}
for (final Object primaryKey : orderedPrimaryKeys) {
for (final Set<Object> objects : map.get(primaryKey)) {
results.add(mergeImplementations(returnType, new ArrayList<>(objects)));
}
}
}
else {
HashSet<Object> map = new HashSet<>();
for (final Object t : implementations) {
final Object o = method.invoke(t, args);
if (o instanceof Collection) {
map.addAll((Collection<Object>)o);
}
else if (o != null) {
map.add(o);
break;
}
}
results.addAll(map);
}
return results;
}
private Object mergeImplementations(final Class returnType, final List<Object> implementations) {
for (int i = myMergingStrategies.size() - 1; i >= 0; i--) {
if (ReflectionUtil.isAssignable(myMergingStrategyClasses.get(i), returnType)) {
final Object o = myMergingStrategies.get(i).mergeChildren(returnType, implementations);
if (o != null) {
return o;
}
}
}
if (implementations.size() == 1) {
return implementations.get(0);
}
return mergeModels(returnType, implementations);
}
private static boolean addToMaps(final Object o,
final Map<Object, int[]> counts,
final Map<Object, List<Set<Object>>> map,
final int index,
final List<Object> results,
final boolean singleValuedInvocation,
final boolean intersect) {
final Object primaryKey = getPrimaryKey(o, singleValuedInvocation);
if (primaryKey != null || singleValuedInvocation) {
final List<Set<Object>> list = map.get(primaryKey);
final int[] indices = counts.get(primaryKey);
int objIndex = intersect? indices[index] : indices[index]++;
if (list.size() <= objIndex) {
list.add(new LinkedHashSet<>());
}
list.get(objIndex).add(o);
return false;
}
results.add(o);
return true;
}
}
| |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.impl.protocol.sip;
import java.util.*;
import net.java.sip.communicator.service.credentialsstorage.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.sip.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* A SIP implementation of the protocol provider factory interface.
*
* @author Emil Ivov
*/
public class ProtocolProviderFactorySipImpl
extends ProtocolProviderFactory
{
private static final Logger logger =
Logger.getLogger(ProtocolProviderFactorySipImpl.class);
/**
* Constructs a new instance of the ProtocolProviderFactorySipImpl.
*/
public ProtocolProviderFactorySipImpl()
{
super(SipActivator.getBundleContext(), ProtocolNames.SIP);
}
/**
* Overrides the original in order not to save the OPT_CLIST_PASSWORD field.
*
* @param accountID the account identifier.
*/
@Override
protected void storeAccount(AccountID accountID)
{
storeXCapPassword(accountID);
super.storeAccount(accountID);
}
/**
* Stores OPT_CLIST_PASSWORD property.
*
* @param accountID the account identifier.
*/
private void storeXCapPassword(AccountID accountID)
{
// don't use getAccountPropertyString as it will query
// credential storage, use getAccountProperty to see is there such
// property in the account properties provided.
// if xcap password property exist, store it through credentialsStorage
// service
String password
= accountID.getAccountPropertyString(
SipAccountID.OPT_CLIST_PASSWORD);
if (password != null)
{
CredentialsStorageService credentialsStorage
= ServiceUtils.getService(
getBundleContext(),
CredentialsStorageService.class);
String accountPrefix = accountID.getAccountUniqueID() + ".xcap";
credentialsStorage.storePassword(accountPrefix, password);
// remove unsecured property
accountID.removeAccountProperty(
SipAccountIDImpl.OPT_CLIST_PASSWORD);
}
}
/**
* Initializes and creates an account corresponding to the specified
* accountProperties and registers the resulting ProtocolProvider in the
* <tt>context</tt> BundleContext parameter.
*
* @param userIDStr the user identifier uniquely representing the newly
* created account within the protocol namespace.
* @param accountProperties a set of protocol (or implementation)
* specific properties defining the new account.
* @return the AccountID of the newly created account.
* @throws IllegalArgumentException if userID does not correspond to an
* identifier in the context of the underlying protocol or if
* accountProperties does not contain a complete set of account
* installation properties.
* @throws IllegalStateException if the account has already been
* installed.
* @throws NullPointerException if any of the arguments is null.
*/
@Override
public AccountID installAccount( String userIDStr,
Map<String, String> accountProperties)
{
BundleContext context = SipActivator.getBundleContext();
if (context == null)
throw new NullPointerException("The specified BundleContext was null");
if (userIDStr == null)
throw new NullPointerException("The specified AccountID was null");
if (accountProperties == null)
throw new NullPointerException("The specified property map was null");
accountProperties.put(USER_ID, userIDStr);
if (!accountProperties.containsKey(PROTOCOL))
accountProperties.put(PROTOCOL, ProtocolNames.SIP);
AccountID accountID = createAccountID(userIDStr, accountProperties);
//make sure we haven't seen this account id before.
if( registeredAccounts.containsKey(accountID) )
throw new IllegalStateException(
"An account for id " + userIDStr + " was already installed!");
//first store the account and only then load it as the load generates
//an osgi event, the osgi event triggers (through the UI) a call to
//the register() method and it needs to access the configuration service
//and check for a password.
this.storeAccount(accountID, false);
try
{
accountID = loadAccount(accountProperties);
}
catch(RuntimeException exc)
{
//it might happen that load-ing the account fails because of a bad
//initialization. if this is the case, make sure we remove it.
this.removeStoredAccount(accountID);
throw exc;
}
return accountID;
}
/**
* Modifies the account corresponding to the specified accountID. This
* method is meant to be used to change properties of already existing
* accounts. Note that if the given accountID doesn't correspond to any
* registered account this method would do nothing.
*
* @param protocolProvider the protocol provider service corresponding to
* the modified account.
* @param accountProperties a set of protocol (or implementation) specific
* properties defining the new account.
*
* @throws java.lang.NullPointerException if any of the arguments is null.
*/
@Override
public void modifyAccount( ProtocolProviderService protocolProvider,
Map<String, String> accountProperties)
{
BundleContext context
= SipActivator.getBundleContext();
if (context == null)
throw new NullPointerException(
"The specified BundleContext was null");
if (protocolProvider == null)
throw new NullPointerException(
"The specified Protocol Provider was null");
SipAccountIDImpl accountID
= (SipAccountIDImpl) protocolProvider.getAccountID();
// If the given accountID doesn't correspond to an existing account
// we return.
if(!registeredAccounts.containsKey(accountID))
return;
ServiceRegistration registration = registeredAccounts.get(accountID);
// kill the service
if (registration != null)
{
// unregister provider before removing it.
try
{
// shutdown even if its not registered, a port maybe wrong
// shutdown will clean everything and we will start clean
//if(protocolProvider.isRegistered())
{
protocolProvider.shutdown();
}
} catch (Throwable e)
{
// we don't care for this, cause we are modifying and
// will unregister the service and will register again
}
registration.unregister();
}
if (accountProperties == null)
throw new NullPointerException(
"The specified property map was null");
// serverAddress == null is OK because of registrarless support
if (!accountProperties.containsKey(PROTOCOL))
accountProperties.put(PROTOCOL, ProtocolNames.SIP);
// make a backup of the account properties to restore them if a failure
// occurs with the new ones
Map<String,String> oldAcccountProps = accountID.getAccountProperties();
accountID.setAccountProperties(accountProperties);
// First store the account and only then load it as the load generates
// an osgi event, the osgi event triggers (through the UI) a call to
// the register() method and it needs to access the configuration service
// and check for a password.
this.storeAccount(accountID);
String userIDStr = accountProperties.get(USER_ID);
Hashtable<String, String> properties = new Hashtable<String, String>();
properties.put(PROTOCOL, ProtocolNames.SIP);
properties.put(USER_ID, userIDStr);
try
{
Exception initializationException = null;
try
{
((ProtocolProviderServiceSipImpl)protocolProvider)
.initialize(userIDStr, accountID);
}
catch (Exception ex)
{
initializationException = ex;
accountID.setAccountProperties(oldAcccountProps);
}
// We store again the account in order to store all properties added
// during the protocol provider initialization. Do this even if the
// initialization failed - after all we're _modifying_ an account
this.storeAccount(accountID);
registration
= context.registerService(
ProtocolProviderService.class.getName(),
protocolProvider,
properties);
registeredAccounts.put(accountID, registration);
if (initializationException != null)
throw initializationException;
}
catch (Exception ex)
{
logger.error("Failed to initialize account", ex);
throw new IllegalArgumentException("Failed to initialize account. "
+ ex.getMessage());
}
}
/**
* Creates a new <code>SipAccountIDImpl</code> instance with a specific user
* ID to represent a given set of account properties.
*
* @param userID the user ID of the new instance
* @param accountProperties the set of properties to be represented by the
* new instance
* @return a new <code>AccountID</code> instance with the specified user ID
* representing the given set of account properties
*/
@Override
protected AccountID createAccountID(String userID, Map<String, String> accountProperties)
{
// serverAddress == null is OK because of registrarless support
String serverAddress = accountProperties.get(SERVER_ADDRESS);
return new SipAccountIDImpl(userID, accountProperties, serverAddress);
}
/**
* Initializes a new <code>ProtocolProviderServiceSipImpl</code> instance
* with a specific user ID to represent a specific <code>AccountID</code>.
*
* @param userID the user ID to initialize the new instance with
* @param accountID the <code>AccountID</code> to be represented by the new
* instance
* @return a new <code>ProtocolProviderService</code> instance with the
* specific user ID representing the specified
* <code>AccountID</code>
*/
@Override
protected ProtocolProviderService createService(String userID,
AccountID accountID)
{
ProtocolProviderServiceSipImpl service
= new ProtocolProviderServiceSipImpl();
try
{
service.initialize(userID, (SipAccountIDImpl) accountID);
// We store again the account in order to store all properties added
// during the protocol provider initialization.
storeAccount(accountID);
}
catch (OperationFailedException ex)
{
logger.error("Failed to initialize account", ex);
throw new IllegalArgumentException("Failed to initialize account"
+ ex.getMessage());
}
return service;
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import javax.crypto.NoSuchPaddingException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSessionContext;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static io.netty.util.internal.ObjectUtil.*;
/**
* An {@link SslContext} which uses JDK's SSL/TLS implementation.
*/
public class JdkSslContext extends SslContext {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(JdkSslContext.class);
static final String PROTOCOL = "TLS";
static final String[] PROTOCOLS;
static final List<String> DEFAULT_CIPHERS;
static final Set<String> SUPPORTED_CIPHERS;
static {
SSLContext context;
int i;
try {
context = SSLContext.getInstance(PROTOCOL);
context.init(null, null, null);
} catch (Exception e) {
throw new Error("failed to initialize the default SSL context", e);
}
SSLEngine engine = context.createSSLEngine();
// Choose the sensible default list of protocols.
final String[] supportedProtocols = engine.getSupportedProtocols();
Set<String> supportedProtocolsSet = new HashSet<String>(supportedProtocols.length);
for (i = 0; i < supportedProtocols.length; ++i) {
supportedProtocolsSet.add(supportedProtocols[i]);
}
List<String> protocols = new ArrayList<String>();
addIfSupported(
supportedProtocolsSet, protocols,
"TLSv1.2", "TLSv1.1", "TLSv1");
if (!protocols.isEmpty()) {
PROTOCOLS = protocols.toArray(new String[protocols.size()]);
} else {
PROTOCOLS = engine.getEnabledProtocols();
}
// Choose the sensible default list of cipher suites.
final String[] supportedCiphers = engine.getSupportedCipherSuites();
SUPPORTED_CIPHERS = new HashSet<String>(supportedCiphers.length);
for (i = 0; i < supportedCiphers.length; ++i) {
SUPPORTED_CIPHERS.add(supportedCiphers[i]);
}
List<String> ciphers = new ArrayList<String>();
addIfSupported(
SUPPORTED_CIPHERS, ciphers,
// XXX: Make sure to sync this list with OpenSslEngineFactory.
// GCM (Galois/Counter Mode) requires JDK 8.
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
// AES256 requires JCE unlimited strength jurisdiction policy files.
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
// GCM (Galois/Counter Mode) requires JDK 8.
"TLS_RSA_WITH_AES_128_GCM_SHA256",
"TLS_RSA_WITH_AES_128_CBC_SHA",
// AES256 requires JCE unlimited strength jurisdiction policy files.
"TLS_RSA_WITH_AES_256_CBC_SHA",
"SSL_RSA_WITH_3DES_EDE_CBC_SHA");
if (ciphers.isEmpty()) {
// Use the default from JDK as fallback.
for (String cipher : engine.getEnabledCipherSuites()) {
if (cipher.contains("_RC4_")) {
continue;
}
ciphers.add(cipher);
}
}
DEFAULT_CIPHERS = Collections.unmodifiableList(ciphers);
if (logger.isDebugEnabled()) {
logger.debug("Default protocols (JDK): {} ", Arrays.asList(PROTOCOLS));
logger.debug("Default cipher suites (JDK): {}", DEFAULT_CIPHERS);
}
}
private static void addIfSupported(Set<String> supported, List<String> enabled, String... names) {
for (String n: names) {
if (supported.contains(n)) {
enabled.add(n);
}
}
}
private final String[] cipherSuites;
private final List<String> unmodifiableCipherSuites;
private final JdkApplicationProtocolNegotiator apn;
private final ClientAuth clientAuth;
private final SSLContext sslContext;
private final boolean isClient;
/**
* Creates a new {@link JdkSslContext} from a pre-configured {@link SSLContext}.
*
* @param sslContext the {@link SSLContext} to use.
* @param isClient {@code true} if this context should create {@link SSLEngine}s for client-side usage.
* @param clientAuth the {@link ClientAuth} to use. This will only be used when {@param isClient} is {@code false}.
*/
public JdkSslContext(SSLContext sslContext, boolean isClient,
ClientAuth clientAuth) {
this(sslContext, isClient, null, IdentityCipherSuiteFilter.INSTANCE,
JdkDefaultApplicationProtocolNegotiator.INSTANCE, clientAuth);
}
/**
* Creates a new {@link JdkSslContext} from a pre-configured {@link SSLContext}.
*
* @param sslContext the {@link SSLContext} to use.
* @param isClient {@code true} if this context should create {@link SSLEngine}s for client-side usage.
* @param ciphers the ciphers to use or {@code null} if the standart should be used.
* @param cipherFilter the filter to use.
* @param apn the {@link ApplicationProtocolConfig} to use.
* @param clientAuth the {@link ClientAuth} to use. This will only be used when {@param isClient} is {@code false}.
*/
public JdkSslContext(SSLContext sslContext, boolean isClient, Iterable<String> ciphers,
CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
ClientAuth clientAuth) {
this(sslContext, isClient, ciphers, cipherFilter, toNegotiator(apn, !isClient), clientAuth);
}
JdkSslContext(SSLContext sslContext, boolean isClient, Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
JdkApplicationProtocolNegotiator apn, ClientAuth clientAuth) {
this.apn = checkNotNull(apn, "apn");
this.clientAuth = checkNotNull(clientAuth, "clientAuth");
cipherSuites = checkNotNull(cipherFilter, "cipherFilter").filterCipherSuites(
ciphers, DEFAULT_CIPHERS, SUPPORTED_CIPHERS);
unmodifiableCipherSuites = Collections.unmodifiableList(Arrays.asList(cipherSuites));
this.sslContext = checkNotNull(sslContext, "sslContext");
this.isClient = isClient;
}
/**
* Returns the JDK {@link SSLContext} object held by this context.
*/
public final SSLContext context() {
return sslContext;
}
@Override
public final boolean isClient() {
return isClient;
}
/**
* Returns the JDK {@link SSLSessionContext} object held by this context.
*/
@Override
public final SSLSessionContext sessionContext() {
if (isServer()) {
return context().getServerSessionContext();
} else {
return context().getClientSessionContext();
}
}
@Override
public final List<String> cipherSuites() {
return unmodifiableCipherSuites;
}
@Override
public final long sessionCacheSize() {
return sessionContext().getSessionCacheSize();
}
@Override
public final long sessionTimeout() {
return sessionContext().getSessionTimeout();
}
@Override
public final SSLEngine newEngine(ByteBufAllocator alloc) {
return configureAndWrapEngine(context().createSSLEngine());
}
@Override
public final SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
return configureAndWrapEngine(context().createSSLEngine(peerHost, peerPort));
}
private SSLEngine configureAndWrapEngine(SSLEngine engine) {
engine.setEnabledCipherSuites(cipherSuites);
engine.setEnabledProtocols(PROTOCOLS);
engine.setUseClientMode(isClient());
if (isServer()) {
switch (clientAuth) {
case OPTIONAL:
engine.setWantClientAuth(true);
break;
case REQUIRE:
engine.setNeedClientAuth(true);
break;
}
}
return apn.wrapperFactory().wrapSslEngine(engine, apn, isServer());
}
@Override
public final JdkApplicationProtocolNegotiator applicationProtocolNegotiator() {
return apn;
}
/**
* Translate a {@link ApplicationProtocolConfig} object to a {@link JdkApplicationProtocolNegotiator} object.
* @param config The configuration which defines the translation
* @param isServer {@code true} if a server {@code false} otherwise.
* @return The results of the translation
*/
static JdkApplicationProtocolNegotiator toNegotiator(ApplicationProtocolConfig config, boolean isServer) {
if (config == null) {
return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
}
switch(config.protocol()) {
case NONE:
return JdkDefaultApplicationProtocolNegotiator.INSTANCE;
case ALPN:
if (isServer) {
switch(config.selectorFailureBehavior()) {
case FATAL_ALERT:
return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
case NO_ADVERTISE:
return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectorFailureBehavior()).append(" failure behavior").toString());
}
} else {
switch(config.selectedListenerFailureBehavior()) {
case ACCEPT:
return new JdkAlpnApplicationProtocolNegotiator(false, config.supportedProtocols());
case FATAL_ALERT:
return new JdkAlpnApplicationProtocolNegotiator(true, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
}
}
case NPN:
if (isServer) {
switch(config.selectedListenerFailureBehavior()) {
case ACCEPT:
return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
case FATAL_ALERT:
return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectedListenerFailureBehavior()).append(" failure behavior").toString());
}
} else {
switch(config.selectorFailureBehavior()) {
case FATAL_ALERT:
return new JdkNpnApplicationProtocolNegotiator(true, config.supportedProtocols());
case NO_ADVERTISE:
return new JdkNpnApplicationProtocolNegotiator(false, config.supportedProtocols());
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.selectorFailureBehavior()).append(" failure behavior").toString());
}
}
default:
throw new UnsupportedOperationException(new StringBuilder("JDK provider does not support ")
.append(config.protocol()).append(" protocol").toString());
}
}
/**
* Build a {@link KeyManagerFactory} based upon a key file, key file password, and a certificate chain.
* @param certChainFile a X.509 certificate chain file in PEM format
* @param keyFile a PKCS#8 private key file in PEM format
* @param keyPassword the password of the {@code keyFile}.
* {@code null} if it's not password-protected.
* @param kmf The existing {@link KeyManagerFactory} that will be used if not {@code null}
* @return A {@link KeyManagerFactory} based upon a key file, key file password, and a certificate chain.
* @deprecated will be removed.
*/
@Deprecated
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword,
KeyManagerFactory kmf)
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException,
CertificateException, KeyException, IOException {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf);
}
static KeyManagerFactory buildKeyManagerFactory(X509Certificate[] certChain, PrivateKey key, String keyPassword,
KeyManagerFactory kmf)
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
return buildKeyManagerFactory(certChain, algorithm, key, keyPassword, kmf);
}
/**
* Build a {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
* and a certificate chain.
* @param certChainFile a X.509 certificate chain file in PEM format
* @param keyAlgorithm the standard name of the requested algorithm. See the Java Secure Socket Extension
* Reference Guide for information about standard algorithm names.
* @param keyFile a PKCS#8 private key file in PEM format
* @param keyPassword the password of the {@code keyFile}.
* {@code null} if it's not password-protected.
* @param kmf The existing {@link KeyManagerFactory} that will be used if not {@code null}
* @return A {@link KeyManagerFactory} based upon a key algorithm, key file, key file password,
* and a certificate chain.
* @deprecated will be removed.
*/
@Deprecated
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile,
String keyAlgorithm, File keyFile, String keyPassword, KeyManagerFactory kmf)
throws KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeySpecException, InvalidAlgorithmParameterException, IOException,
CertificateException, KeyException, UnrecoverableKeyException {
return buildKeyManagerFactory(toX509Certificates(certChainFile), keyAlgorithm,
toPrivateKey(keyFile, keyPassword), keyPassword, kmf);
}
static KeyManagerFactory buildKeyManagerFactory(X509Certificate[] certChainFile,
String keyAlgorithm, PrivateKey key,
String keyPassword, KeyManagerFactory kmf)
throws KeyStoreException, NoSuchAlgorithmException, IOException,
CertificateException, UnrecoverableKeyException {
char[] keyPasswordChars = keyPassword == null ? EmptyArrays.EMPTY_CHARS : keyPassword.toCharArray();
KeyStore ks = buildKeyStore(certChainFile, key, keyPasswordChars);
// Set up key manager factory to use our key store
if (kmf == null) {
kmf = KeyManagerFactory.getInstance(keyAlgorithm);
}
kmf.init(ks, keyPasswordChars);
return kmf;
}
}
| |
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl.operationservice.impl;
import com.hazelcast.internal.nio.Packet;
import com.hazelcast.internal.server.ServerConnection;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.impl.InboundResponseHandlerSupplier.AsyncMultithreadedResponseHandler;
import com.hazelcast.spi.impl.operationservice.impl.InboundResponseHandlerSupplier.AsyncSingleThreadedResponseHandler;
import com.hazelcast.spi.impl.operationservice.impl.responses.NormalResponse;
import com.hazelcast.spi.impl.sequence.CallIdSequenceWithoutBackpressure;
import com.hazelcast.spi.properties.ClusterProperty;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Properties;
import java.util.function.Consumer;
import static com.hazelcast.internal.nio.Packet.FLAG_OP_RESPONSE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class InboundResponseHandlerSupplierTest extends HazelcastTestSupport {
private InternalSerializationService serializationService;
private InvocationRegistry invocationRegistry;
private NodeEngine nodeEngine;
private InboundResponseHandlerSupplier supplier;
@Before
public void setup() {
ILogger logger = Logger.getLogger(getClass());
HazelcastProperties properties = new HazelcastProperties(new Properties());
invocationRegistry = new InvocationRegistry(logger, new CallIdSequenceWithoutBackpressure(), properties);
serializationService = new DefaultSerializationServiceBuilder().build();
nodeEngine = mock(NodeEngine.class);
when(nodeEngine.getLogger(any(Class.class))).thenReturn(logger);
when(nodeEngine.getSerializationService()).thenReturn(serializationService);
}
@After
public void after() {
if (supplier != null) {
supplier.shutdown();
}
}
@Test
public void get_whenZeroResponseThreads() {
supplier = newSupplier(0);
assertInstanceOf(InboundResponseHandler.class, supplier.get());
}
@Test
public void get_whenResponseThreads() {
supplier = newSupplier(1);
assertInstanceOf(AsyncSingleThreadedResponseHandler.class, supplier.get());
}
@Test
public void get_whenMultipleResponseThreads() {
supplier = newSupplier(2);
assertInstanceOf(AsyncMultithreadedResponseHandler.class, supplier.get());
}
@Test(expected = IllegalArgumentException.class)
public void get_whenNegativeResponseThreads() {
newSupplier(-1);
}
private InboundResponseHandlerSupplier newSupplier(int threadCount) {
Properties props = new Properties();
props.put(ClusterProperty.RESPONSE_THREAD_COUNT.getName(), "" + threadCount);
HazelcastProperties properties = new HazelcastProperties(props);
when(nodeEngine.getProperties()).thenReturn(properties);
return new InboundResponseHandlerSupplier(
getClass().getClassLoader(), invocationRegistry, "hz", nodeEngine);
}
@Test
public void whenNoProblemPacket_andZeroResponseThreads() {
whenNoProblemPacket(0);
}
@Test
public void whenNoProblemPacket_andOneResponseThreads() {
whenNoProblemPacket(1);
}
@Test
public void whenNoProblemPacket_andMultipleResponseThreads() {
whenNoProblemPacket(2);
}
private void whenNoProblemPacket(int threadCount) {
supplier = newSupplier(threadCount);
supplier.start();
final Invocation invocation = newInvocation();
invocationRegistry.register(invocation);
final long callId = invocation.op.getCallId();
final Packet response = new Packet(serializationService.toBytes(new NormalResponse("foo", callId, 0, false)))
.setPacketType(Packet.Type.OPERATION)
.raiseFlags(FLAG_OP_RESPONSE)
.setConn(mock(ServerConnection.class));
supplier.get().accept(response);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
Invocation inv = invocationRegistry.get(callId);
System.out.println(inv);
assertNull(inv);
}
});
assertEquals(1, supplier.responsesNormal());
assertEquals(0, supplier.responsesBackup());
assertEquals(0, supplier.responsesError());
assertEquals(0, supplier.responsesMissing());
assertEquals(0, supplier.responsesTimeout());
assertEquals(0, supplier.responseQueueSize());
}
// test that is a bad response is send, the processing loop isn't broken
// This test isn't terribly exciting since responses are constructed by
// the system and unlikely to fail.
@Test
public void whenPacketThrowsException() {
supplier = newSupplier(1);
supplier.start();
// create a registered invocation
final Invocation invocation = newInvocation();
invocationRegistry.register(invocation);
final long callId = invocation.op.getCallId();
// the response flag isn't set; so an exception is thrown.
Packet badResponse = new Packet(serializationService.toBytes(new NormalResponse("bad", 1, 0, false)))
.setPacketType(Packet.Type.OPERATION)
.setConn(mock(ServerConnection.class));
Consumer<Packet> responseConsumer = supplier.get();
responseConsumer.accept(badResponse);
final Packet goodResponse = new Packet(serializationService.toBytes(new NormalResponse("foo", callId, 0, false)))
.setPacketType(Packet.Type.OPERATION)
.raiseFlags(FLAG_OP_RESPONSE)
.setConn(mock(ServerConnection.class));
responseConsumer.accept(goodResponse);
assertTrueEventually(() -> {
Invocation inv = invocationRegistry.get(callId);
System.out.println(inv);
assertNull(inv);
});
}
private Invocation newInvocation() {
Invocation.Context context = new Invocation.Context(
null, null, null, null, null, 0, invocationRegistry, null, null, null, null, null, null, null, null, null, null, null, null);
Operation op = new DummyOperation();
return new PartitionInvocation(context, op, 0, 0, 0, false, false);
}
}
| |
package com.gdn.venice.facade;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import com.gdn.venice.facade.callback.SessionCallback;
import com.gdn.venice.facade.finder.FinderReturn;
import com.gdn.venice.persistence.FinRolledUpJournalStatus;
import com.djarum.raf.utilities.JPQLAdvancedQueryCriteria;
import com.djarum.raf.utilities.JPQLQueryStringBuilder;
import com.djarum.raf.utilities.Log4jLoggerFactory;
/**
* Session Bean implementation class FinRolledUpJournalStatusSessionEJBBean
*
* <p>
* <b>author:</b> <a href="mailto:david@pwsindonesia.com">David Forden</a>
* <p>
* <b>version:</b> 1.0
* <p>
* <b>since:</b> 2011
*
*/
@Stateless(mappedName = "FinRolledUpJournalStatusSessionEJBBean")
public class FinRolledUpJournalStatusSessionEJBBean implements FinRolledUpJournalStatusSessionEJBRemote,
FinRolledUpJournalStatusSessionEJBLocal {
/*
* Implements an IOC model for pre/post callbacks to persist, merge, and
* remove operations. The onPrePersist, onPostPersist, onPreMerge,
* onPostMerge, onPreRemove and OnPostRemove operations must be implemented
* by the callback class.
*/
private String _sessionCallbackClassName = null;
// A reference to the callback object that has been instantiated
private SessionCallback _callback = null;
protected static Logger _log = null;
// The configuration file to use
private String _configFile = System.getenv("VENICE_HOME")
+ "/conf/module-config.xml";
//The binding array used when binding variables into a JPQL query
private Object[] bindingArray = null;
@PersistenceContext(unitName = "GDN-Venice-Persistence", type = PersistenceContextType.TRANSACTION)
protected EntityManager em;
/**
* Default constructor.
*/
public FinRolledUpJournalStatusSessionEJBBean() {
super();
Log4jLoggerFactory loggerFactory = new Log4jLoggerFactory();
_log = loggerFactory
.getLog4JLogger("com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBBean");
// If the configuration is successful then instantiate the callback
if (this.configure())
this.instantiateTriggerCallback();
}
/**
* Reads the venice configuration file and configures the EJB's
* triggerCallbackClassName
*/
private Boolean configure() {
_log.debug("Venice Configuration File:" + _configFile);
try {
XMLConfiguration config = new XMLConfiguration(_configFile);
/*
* Get the index entry for the adapter configuration from the
* configuration file - there will be multiple adapter
* configurations
*/
@SuppressWarnings({ "rawtypes" })
List callbacks = config
.getList("sessionBeanConfig.callback.[@name]");
Integer beanConfigIndex = new Integer(Integer.MAX_VALUE);
@SuppressWarnings("rawtypes")
Iterator i = callbacks.iterator();
while (i.hasNext()) {
String beanName = (String) i.next();
if (this.getClass().getSimpleName().equals(beanName)) {
beanConfigIndex = callbacks.indexOf(beanName);
_log.debug("Bean configuration for " + beanName
+ " found at " + beanConfigIndex);
}
}
this._sessionCallbackClassName = config
.getString("sessionBeanConfig.callback(" + beanConfigIndex + ").[@class]");
_log.debug("Loaded configuration for _sessionCallbackClassName:"
+ _sessionCallbackClassName);
} catch (ConfigurationException e) {
_log.error("A ConfigurationException occured when processing the configuration file"
+ e.getMessage());
e.printStackTrace();
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* Instantiates the trigger callback handler class
*
* @return
*/
Boolean instantiateTriggerCallback() {
if (_sessionCallbackClassName != null
&& !_sessionCallbackClassName.isEmpty())
try {
Class<?> c = Class.forName(_sessionCallbackClassName);
_callback = (SessionCallback) c.newInstance();
} catch (ClassNotFoundException e) {
_log.error("A ClassNotFoundException occured when trying to instantiate:"
+ this._sessionCallbackClassName);
e.printStackTrace();
return Boolean.FALSE;
} catch (InstantiationException e) {
_log.error("A InstantiationException occured when trying to instantiate:"
+ this._sessionCallbackClassName);
e.printStackTrace();
return Boolean.FALSE;
} catch (IllegalAccessException e) {
_log.error("A IllegalAccessException occured when trying to instantiate:"
+ this._sessionCallbackClassName);
e.printStackTrace();
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#queryByRange(java.lang
* .String, int, int)
*/
@Override
@SuppressWarnings({ "unchecked" })
public List<FinRolledUpJournalStatus> queryByRange(String jpqlStmt, int firstResult,
int maxResults) {
Long startTime = System.currentTimeMillis();
_log.debug("queryByRange()");
Query query = null;
try {
query = em.createQuery(jpqlStmt);
if(this.bindingArray != null){
for(int i = 0; i < bindingArray.length; ++i){
if(bindingArray[i] != null){
query.setParameter(i+1, bindingArray[i]);
}
}
}
} catch (Exception e) {
_log.error("An exception occured when calling em.createQuery():"
+ e.getMessage());
throw new EJBException(e);
}
try {
if (firstResult > 0) {
query = query.setFirstResult(firstResult);
}
if (maxResults > 0) {
query = query.setMaxResults(maxResults);
}
} catch (Exception e) {
_log.error("An exception occured when accessing the result set of a query:"
+ e.getMessage());
throw new EJBException(e);
}
List<FinRolledUpJournalStatus> returnList = (List<FinRolledUpJournalStatus>)query.getResultList();
this.bindingArray = null;
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("queryByRange() duration:" + duration + "ms");
return returnList;
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#persistFinRolledUpJournalStatus(com
* .gdn.venice.persistence.FinRolledUpJournalStatus)
*/
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FinRolledUpJournalStatus persistFinRolledUpJournalStatus(FinRolledUpJournalStatus finRolledUpJournalStatus) {
Long startTime = System.currentTimeMillis();
_log.debug("persistFinRolledUpJournalStatus()");
// Call the onPrePersist() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPrePersist(finRolledUpJournalStatus)) {
_log.error("An onPrePersist callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPrePersist callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
FinRolledUpJournalStatus existingFinRolledUpJournalStatus = null;
if (finRolledUpJournalStatus != null && finRolledUpJournalStatus.getJournalEntryStatusId() != null) {
_log.debug("persistFinRolledUpJournalStatus:em.find()");
try {
existingFinRolledUpJournalStatus = em.find(FinRolledUpJournalStatus.class,
finRolledUpJournalStatus.getJournalEntryStatusId());
} catch (Exception e) {
_log.error("An exception occured when calling em.find():"
+ e.getMessage());
throw new EJBException(e);
}
}
if (existingFinRolledUpJournalStatus == null) {
_log.debug("persistFinRolledUpJournalStatus:em.persist()");
try {
em.persist(finRolledUpJournalStatus);
} catch (Exception e) {
_log.error("An exception occured when calling em.persist():"
+ e.getMessage());
throw new EJBException(e);
}
_log.debug("persistFinRolledUpJournalStatus:em.flush()");
try {
em.flush();
em.clear();
} catch (Exception e) {
_log.error("An exception occured when calling em.flush():"
+ e.getMessage());
throw new EJBException(e);
}
// Call the onPostPersist() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPostPersist(finRolledUpJournalStatus)) {
_log.error("An onPostPersist callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPostPersist callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("persistFinRolledUpJournalStatus() duration:" + duration + "ms");
return finRolledUpJournalStatus;
} else {
throw new EJBException("FinRolledUpJournalStatus exists!. FinRolledUpJournalStatus = "
+ finRolledUpJournalStatus.getJournalEntryStatusId());
}
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#persistFinRolledUpJournalStatusList
* (java.util.List)
*/
@Override
@SuppressWarnings("rawtypes")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public ArrayList<FinRolledUpJournalStatus> persistFinRolledUpJournalStatusList(
List<FinRolledUpJournalStatus> finRolledUpJournalStatusList) {
_log.debug("persistFinRolledUpJournalStatusList()");
Iterator i = finRolledUpJournalStatusList.iterator();
while (i.hasNext()) {
this.persistFinRolledUpJournalStatus((FinRolledUpJournalStatus) i.next());
}
return (ArrayList<FinRolledUpJournalStatus>)finRolledUpJournalStatusList;
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#mergeFinRolledUpJournalStatus(com.
* gdn.venice.persistence.FinRolledUpJournalStatus)
*/
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public FinRolledUpJournalStatus mergeFinRolledUpJournalStatus(FinRolledUpJournalStatus finRolledUpJournalStatus) {
Long startTime = System.currentTimeMillis();
_log.debug("mergeFinRolledUpJournalStatus()");
// Call the onPreMerge() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPreMerge(finRolledUpJournalStatus)) {
_log.error("An onPreMerge callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPreMerge callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
FinRolledUpJournalStatus existing = null;
if (finRolledUpJournalStatus.getJournalEntryStatusId() != null){
_log.debug("mergeFinRolledUpJournalStatus:em.find()");
existing = em.find(FinRolledUpJournalStatus.class, finRolledUpJournalStatus.getJournalEntryStatusId());
}
if (existing == null) {
return this.persistFinRolledUpJournalStatus(finRolledUpJournalStatus);
} else {
_log.debug("mergeFinRolledUpJournalStatus:em.merge()");
try {
em.merge(finRolledUpJournalStatus);
} catch (Exception e) {
_log.error("An exception occured when calling em.merge():"
+ e.getMessage());
throw new EJBException(e);
}
_log.debug("mergeFinRolledUpJournalStatus:em.flush()");
try {
em.flush();
em.clear();
} catch (Exception e) {
_log.error("An exception occured when calling em.flush():"
+ e.getMessage());
throw new EJBException(e);
}
FinRolledUpJournalStatus newobject = em.find(FinRolledUpJournalStatus.class,
finRolledUpJournalStatus.getJournalEntryStatusId());
_log.debug("mergeFinRolledUpJournalStatus():em.refresh");
try {
em.refresh(newobject);
} catch (Exception e) {
_log.error("An exception occured when calling em.refresh():"
+ e.getMessage());
throw new EJBException(e);
}
// Call the onPostMerge() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPostMerge(newobject)) {
_log.error("An onPostMerge callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPostMerge callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("mergeFinRolledUpJournalStatus() duration:" + duration + "ms");
return newobject;
}
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#mergeFinRolledUpJournalStatusList(
* java.util.List)
*/
@Override
@SuppressWarnings("rawtypes")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public ArrayList<FinRolledUpJournalStatus> mergeFinRolledUpJournalStatusList(
List<FinRolledUpJournalStatus> finRolledUpJournalStatusList) {
_log.debug("mergeFinRolledUpJournalStatusList()");
Iterator i = finRolledUpJournalStatusList.iterator();
while (i.hasNext()) {
this.mergeFinRolledUpJournalStatus((FinRolledUpJournalStatus) i.next());
}
return (ArrayList<FinRolledUpJournalStatus>)finRolledUpJournalStatusList;
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#removeFinRolledUpJournalStatus(com.
* gdn.venice.persistence.FinRolledUpJournalStatus)
*/
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeFinRolledUpJournalStatus(FinRolledUpJournalStatus finRolledUpJournalStatus) {
Long startTime = System.currentTimeMillis();
_log.debug("removeFinRolledUpJournalStatus()");
// Call the onPreRemove() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPreRemove(finRolledUpJournalStatus)) {
_log.error("An onPreRemove callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPreRemove callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
_log.debug("removeFinRolledUpJournalStatus:em.find()");
finRolledUpJournalStatus = em.find(FinRolledUpJournalStatus.class, finRolledUpJournalStatus.getJournalEntryStatusId());
try {
_log.debug("removeFinRolledUpJournalStatus:em.remove()");
em.remove(finRolledUpJournalStatus);
} catch (Exception e) {
_log.error("An exception occured when calling em.remove():"
+ e.getMessage());
throw new EJBException(e);
}
// Call the onPostRemove() callback and throw an exception if it fails
if (this._callback != null) {
if (!this._callback.onPostRemove(finRolledUpJournalStatus)) {
_log.error("An onPostRemove callback operation failed for:"
+ this._sessionCallbackClassName);
throw new EJBException(
"An onPostRemove callback operation failed for:"
+ this._sessionCallbackClassName);
}
}
_log.debug("removeFinRolledUpJournalStatus:em.flush()");
em.flush();
em.clear();
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("removeFinRolledUpJournalStatus() duration:" + duration + "ms");
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#removeFinRolledUpJournalStatusList(
* java.util.List)
*/
@Override
@SuppressWarnings("rawtypes")
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeFinRolledUpJournalStatusList(List<FinRolledUpJournalStatus> finRolledUpJournalStatusList) {
_log.debug("removeFinRolledUpJournalStatusList()");
Iterator i = finRolledUpJournalStatusList.iterator();
while (i.hasNext()) {
this.removeFinRolledUpJournalStatus((FinRolledUpJournalStatus) i.next());
}
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#findByFinRolledUpJournalStatusLike(
* com.gdn.venice.persistence.FinRolledUpJournalStatus, int, int)
*/
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<FinRolledUpJournalStatus> findByFinRolledUpJournalStatusLike(FinRolledUpJournalStatus finRolledUpJournalStatus,
JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults) {
Long startTime = System.currentTimeMillis();
_log.debug("findByFinRolledUpJournalStatusLike()");
JPQLQueryStringBuilder qb = new JPQLQueryStringBuilder(finRolledUpJournalStatus);
HashMap complexTypeBindings = new HashMap();
String stmt = qb.buildQueryString(complexTypeBindings, criteria);
if(criteria != null){
/*
* Get the binding array from the query builder and make
* it available to the queryByRange method
*/
this.bindingArray = qb.getBindingArray();
for(int i = 0; i < qb.getBindingArray().length; i++){
System.out.println("Bindings:" + i + ":" + qb.getBindingArray()[i]);
}
List<FinRolledUpJournalStatus> finRolledUpJournalStatusList = this.queryByRange(stmt, firstResult, maxResults);
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("findByFinRolledUpJournalStatusLike() duration:" + duration + "ms");
return finRolledUpJournalStatusList;
}else{
String errMsg = "A query has been initiated with null criteria.";
_log.error(errMsg);
throw new EJBException(errMsg);
}
}
/*
* (non-Javadoc)
*
* @see
* com.gdn.venice.facade.FinRolledUpJournalStatusSessionEJBRemote#findByFinRolledUpJournalStatusLikeFR(
* com.gdn.venice.persistence.FinRolledUpJournalStatus, int, int)
*/
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public FinderReturn findByFinRolledUpJournalStatusLikeFR(FinRolledUpJournalStatus finRolledUpJournalStatus,
JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults) {
Long startTime = System.currentTimeMillis();
_log.debug("findByFinRolledUpJournalStatusLikeFR()");
JPQLQueryStringBuilder qb = new JPQLQueryStringBuilder(finRolledUpJournalStatus);
HashMap complexTypeBindings = new HashMap();
String stmt = qb.buildQueryString(complexTypeBindings, criteria);
if(criteria != null){
/*
* Get the binding array from the query builder and make
* it available to the queryByRange method
*/
this.bindingArray = qb.getBindingArray();
for(int i = 0; i < qb.getBindingArray().length; i++){
System.out.println("Bindings:" + i + ":" + qb.getBindingArray()[i]);
}
//Set the finder return object with the count of the total query rows
FinderReturn fr = new FinderReturn();
String countStmt = "select count(o) " + stmt.substring(stmt.indexOf("from"));
Query query = null;
try {
query = em.createQuery(countStmt);
if(this.bindingArray != null){
for(int i = 0; i < bindingArray.length; ++i){
if(bindingArray[i] != null){
query.setParameter(i+1, bindingArray[i]);
}
}
}
Long totalRows = (Long)query.getSingleResult();
fr.setNumQueryRows(totalRows);
} catch (Exception e) {
_log.error("An exception occured when calling em.createQuery():"
+ e.getMessage());
throw new EJBException(e);
}
//Set the finder return object with the query list
fr.setResultList(this.queryByRange(stmt, firstResult, maxResults));
Long endTime = System.currentTimeMillis();
Long duration = startTime - endTime;
_log.debug("findByFinRolledUpJournalStatusLike() duration:" + duration + "ms");
return fr;
}else{
String errMsg = "A query has been initiated with null criteria.";
_log.error(errMsg);
throw new EJBException(errMsg);
}
}
}
| |
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cdlflex.ui.markup.html.nav;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.cdlflex.ui.behavior.CssClassNameAppender;
import org.cdlflex.ui.util.Collections;
/**
* A Bootstrap Navbar that renders {@link INavbarComponent} providers as navbar items.
*/
public class Navbar extends Panel {
private static final long serialVersionUID = 1L;
private List<INavbarComponent<? extends Component>> components;
public Navbar(String id) {
this(id, null);
}
public Navbar(String id, IModel<?> model) {
this(id, model, new ArrayList<INavbarComponent<? extends Component>>());
}
public Navbar(String id, IModel<?> model, List<INavbarComponent<? extends Component>> components) {
super(id, model);
this.components = components;
}
/**
* Uses the given INavbarComponent to create a component within the bar.
*
* @param component the component factory
* @param <T> the component type
* @return this for chaining
*/
public <T extends Component> Navbar add(INavbarComponent<T> component) {
this.components.add(component);
return this;
}
/**
* Uses the given INavbarComponent to create a component within the bar.
*
* @param components the component factories
* @return this for chaining
*/
public Navbar add(Collection<? extends INavbarComponent<? extends Component>> components) {
this.components.addAll(components);
return this;
}
@Override
protected void onInitialize() {
super.onInitialize();
add(newContainer("navbar-container"));
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.put("role", "navigation");
CssClassNameAppender.append(tag, "navbar", "navbar-default");
}
/**
* Creates the outermost navbar container wrapper within the <code><nav></code> component.
*
* @param id component id
* @return a component
*/
protected Component newContainer(String id) {
WebMarkupContainer container = new WebMarkupContainer(id);
container.add(newNavbarHeader("navbar-header"));
container.add(newNavLeft("nav-left"));
container.add(newNavRight("nav-right"));
return container;
}
/**
* Creates the navbar header that contains the brand link.
*
* @param id component id
* @return a component
*/
protected Component newNavbarHeader(String id) {
WebMarkupContainer header = new WebMarkupContainer(id);
Component brand = newBrandLink("brand-link");
if (brand == null) {
brand = new WebMarkupContainer("brand-link").setVisible(false);
}
header.add(brand);
return header;
}
/**
* Creates the brand link of the navbar header. May return null, causing nothing to be rendered.
*
* @param id component id
* @return a component
*/
protected Component newBrandLink(String id) {
return null;
}
/**
* Creates the container that contains the navigation items on the left side.
*
* @param id component id
* @return a component
*/
protected Component newNavLeft(String id) {
return newNav(id, Collections.filter(components, new PositionFilter(Position.LEFT)));
}
/**
* Creates the container that contains the navigation items on the right side.
*
* @param id component id
* @return a component
*/
protected Component newNavRight(String id) {
return newNav(id, Collections.filter(components, new PositionFilter(Position.RIGHT)));
}
private Component newNav(String id, List<INavbarComponent<? extends Component>> components) {
return new ListView<INavbarComponent<? extends Component>>(id, components) {
private static final long serialVersionUID = 1L;
@Override
protected ListItem<INavbarComponent<? extends Component>> newItem(int index,
IModel<INavbarComponent<? extends Component>> itemModel) {
return super.newItem(index, itemModel);
}
@Override
protected void populateItem(ListItem<INavbarComponent<? extends Component>> item) {
INavbarComponent<? extends Component> navbarComponent = item.getModelObject();
item.add(newNavElement("nav-component-container", navbarComponent));
navbarComponent.onAfterPopulateItem(item);
}
};
}
private <T extends Component> Component newNavElement(String id, INavbarComponent<T> navbarComponent) {
T component = navbarComponent.create("nav-component");
return wrapComponent(id, navbarComponent, component);
}
private <T extends Component> Component wrapComponent(String id, INavbarComponent<T> navbarComponent, T component) {
WebMarkupContainer container;
if (navbarComponent instanceof NavbarDropDown) {
container = new Fragment(id, "nav-transparent", this);
} else if (navbarComponent instanceof NavbarLink) {
container = new Fragment(id, "nav-link", this);
} else {
container = new Fragment(id, "nav-transparent", this);
}
return container.add(component);
}
/**
* Filters a list of {@link INavbarComponent} by their position, i.e. the return value of
* {@link org.cdlflex.ui.markup.html.nav.INavbarComponent#getPosition()}.
*/
protected static class PositionFilter implements Collections.Predicate<INavbarComponent<? extends Component>> {
private final Position position;
public PositionFilter(Position position) {
this.position = position;
}
@Override
public Boolean call(INavbarComponent<? extends Component> object) {
return position.equals(object.getPosition());
}
}
}
| |
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.client.remote;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import com.orientechnologies.common.concur.lock.OModificationLock;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy;
import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.ORecordMetadata;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.storage.OStorageProxy;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.version.ORecordVersion;
import com.orientechnologies.orient.core.version.OVersionFactory;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryAsynchClient;
import com.orientechnologies.orient.enterprise.channel.binary.ORemoteServerEventListener;
/**
* Wrapper of OStorageRemote that maintains the sessionId. It's bound to the ODatabase and allow to use the shared OStorageRemote.
*/
@SuppressWarnings("unchecked")
public class OStorageRemoteThread implements OStorageProxy {
private static AtomicInteger sessionSerialId = new AtomicInteger(-1);
private final OStorageRemote delegate;
private String serverURL;
private int sessionId;
private byte[] token;
public OStorageRemoteThread(final OStorageRemote iSharedStorage) {
delegate = iSharedStorage;
serverURL = null;
sessionId = sessionSerialId.decrementAndGet();
}
public OStorageRemoteThread(final OStorageRemote iSharedStorage, final int iSessionId) {
delegate = iSharedStorage;
serverURL = null;
sessionId = iSessionId;
}
public static int getNextConnectionId() {
return sessionSerialId.decrementAndGet();
}
public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iOptions) {
pushSession();
try {
delegate.open(iUserName, iUserPassword, iOptions);
} finally {
popSession();
}
}
/**
* {@inheritDoc}
*/
@Override
public OModificationLock getModificationLock() {
return null;
}
@Override
public boolean isDistributed() {
return delegate.isDistributed();
}
@Override
public Class<? extends OSBTreeCollectionManager> getCollectionManagerClass() {
return delegate.getCollectionManagerClass();
}
public void create(final Map<String, Object> iOptions) {
pushSession();
try {
delegate.create(iOptions);
} finally {
popSession();
}
}
public void close(boolean iForce, boolean onDelete) {
pushSession();
try {
delegate.close(iForce, false);
Orient.instance().unregisterStorage(this);
} finally {
popSession();
}
}
public boolean dropCluster(final String iClusterName, final boolean iTruncate) {
pushSession();
try {
return delegate.dropCluster(iClusterName, iTruncate);
} finally {
popSession();
}
}
public int getUsers() {
pushSession();
try {
return delegate.getUsers();
} finally {
popSession();
}
}
public int addUser() {
pushSession();
try {
return delegate.addUser();
} finally {
popSession();
}
}
public void setSessionId(final String iServerURL, final int iSessionId, byte[] iToken) {
serverURL = iServerURL;
sessionId = iSessionId;
token = iToken;
delegate.setSessionId(serverURL, iSessionId, iToken);
}
public void reload() {
pushSession();
try {
delegate.reload();
} finally {
popSession();
}
}
public boolean exists() {
pushSession();
try {
return delegate.exists();
} finally {
popSession();
}
}
public int removeUser() {
pushSession();
try {
return delegate.removeUser();
} finally {
popSession();
}
}
public void close() {
pushSession();
try {
delegate.close();
Orient.instance().unregisterStorage(this);
} finally {
popSession();
}
}
public void delete() {
pushSession();
try {
delegate.delete();
Orient.instance().unregisterStorage(this);
} finally {
popSession();
}
}
@Override
public OStorage getUnderlying() {
return delegate;
}
@Override
public boolean isRemote() {
return true;
}
public Set<String> getClusterNames() {
pushSession();
try {
return delegate.getClusterNames();
} finally {
popSession();
}
}
@Override
public List<String> backup(OutputStream out, Map<String, Object> options, final Callable<Object> callable, final OCommandOutputListener iListener, int compressionLevel, int bufferSize) throws IOException {
throw new UnsupportedOperationException("backup");
}
@Override
public void restore(InputStream in, Map<String, Object> options, final Callable<Object> callable,
final OCommandOutputListener iListener) throws IOException {
throw new UnsupportedOperationException("restore");
}
public OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId iRid, final byte[] iContent,
ORecordVersion iRecordVersion, final byte iRecordType, final int iMode, ORecordCallback<Long> iCallback) {
pushSession();
try {
return delegate.createRecord(iRid, iContent, OVersionFactory.instance().createVersion(), iRecordType, iMode, iCallback);
} finally {
popSession();
}
}
public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache,
ORecordCallback<ORawBuffer> iCallback) {
pushSession();
try {
return delegate.readRecord(iRid, iFetchPlan, iIgnoreCache, null);
} finally {
popSession();
}
}
@Override
public OStorageOperationResult<ORawBuffer> readRecordIfVersionIsNotLatest(ORecordId rid, String fetchPlan, boolean ignoreCache,
ORecordVersion recordVersion) throws ORecordNotFoundException {
pushSession();
try {
return delegate.readRecordIfVersionIsNotLatest(rid, fetchPlan, ignoreCache, recordVersion);
} finally {
popSession();
}
}
public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRid, boolean updateContent, final byte[] iContent,
final ORecordVersion iVersion, final byte iRecordType, final int iMode, ORecordCallback<ORecordVersion> iCallback) {
pushSession();
try {
return delegate.updateRecord(iRid, updateContent, iContent, iVersion, iRecordType, iMode, iCallback);
} finally {
popSession();
}
}
public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRid, final ORecordVersion iVersion, final int iMode,
ORecordCallback<Boolean> iCallback) {
pushSession();
try {
return delegate.deleteRecord(iRid, iVersion, iMode, iCallback);
} finally {
popSession();
}
}
@Override
public OStorageOperationResult<Boolean> hideRecord(ORecordId recordId, int mode, ORecordCallback<Boolean> callback) {
pushSession();
try {
return delegate.hideRecord(recordId, mode, callback);
} finally {
popSession();
}
}
@Override
public OCluster getClusterByName(String clusterName) {
return delegate.getClusterByName(clusterName);
}
@Override
public ORecordConflictStrategy getConflictStrategy() {
throw new UnsupportedOperationException("getConflictStrategy");
}
@Override
public void setConflictStrategy(ORecordConflictStrategy iResolver) {
throw new UnsupportedOperationException("setConflictStrategy");
}
@Override
public ORecordMetadata getRecordMetadata(ORID rid) {
pushSession();
try {
return delegate.getRecordMetadata(rid);
} finally {
popSession();
}
}
@Override
public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) {
pushSession();
try {
return delegate.cleanOutRecord(recordId, recordVersion, iMode, callback);
} finally {
popSession();
}
}
public long count(final int iClusterId) {
pushSession();
try {
return delegate.count(iClusterId);
} finally {
popSession();
}
}
@Override
public long count(int iClusterId, boolean countTombstones) {
pushSession();
try {
return delegate.count(iClusterId, countTombstones);
} finally {
popSession();
}
}
@Override
public long count(int[] iClusterIds, boolean countTombstones) {
pushSession();
try {
return delegate.count(iClusterIds, countTombstones);
} finally {
popSession();
}
}
public String toString() {
return delegate.toString();
}
public long[] getClusterDataRange(final int iClusterId) {
pushSession();
try {
return delegate.getClusterDataRange(iClusterId);
} finally {
popSession();
}
}
@Override
public OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
pushSession();
try {
return delegate.higherPhysicalPositions(currentClusterId, physicalPosition);
} finally {
popSession();
}
}
@Override
public OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
pushSession();
try {
return delegate.lowerPhysicalPositions(currentClusterId, physicalPosition);
} finally {
popSession();
}
}
@Override
public OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
pushSession();
try {
return delegate.ceilingPhysicalPositions(clusterId, physicalPosition);
} finally {
popSession();
}
}
@Override
public OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
pushSession();
try {
return delegate.floorPhysicalPositions(clusterId, physicalPosition);
} finally {
popSession();
}
}
public long getSize() {
pushSession();
try {
return delegate.getSize();
} finally {
popSession();
}
}
public long countRecords() {
pushSession();
try {
return delegate.countRecords();
} finally {
popSession();
}
}
public long count(final int[] iClusterIds) {
pushSession();
try {
return delegate.count(iClusterIds);
} finally {
popSession();
}
}
public Object command(final OCommandRequestText iCommand) {
pushSession();
try {
return delegate.command(iCommand);
} finally {
popSession();
}
}
public void commit(final OTransaction iTx, Runnable callback) {
pushSession();
try {
delegate.commit(iTx, null);
} finally {
popSession();
}
}
public void rollback(OTransaction iTx) {
pushSession();
try {
delegate.rollback(iTx);
} finally {
popSession();
}
}
public int getClusterIdByName(final String iClusterName) {
pushSession();
try {
return delegate.getClusterIdByName(iClusterName);
} finally {
popSession();
}
}
public int getDefaultClusterId() {
pushSession();
try {
return delegate.getDefaultClusterId();
} finally {
popSession();
}
}
public void setDefaultClusterId(final int defaultClusterId) {
pushSession();
try {
delegate.setDefaultClusterId(defaultClusterId);
} finally {
popSession();
}
}
public int addCluster(final String iClusterName, boolean forceListBased, final Object... iArguments) {
pushSession();
try {
return delegate.addCluster(iClusterName, false, iArguments);
} finally {
popSession();
}
}
public int addCluster(String iClusterName, int iRequestedId, boolean forceListBased, Object... iParameters) {
pushSession();
try {
return delegate.addCluster(iClusterName, iRequestedId, forceListBased, iParameters);
} finally {
popSession();
}
}
public boolean dropCluster(final int iClusterId, final boolean iTruncate) {
pushSession();
try {
return delegate.dropCluster(iClusterId, iTruncate);
} finally {
popSession();
}
}
public void synch() {
pushSession();
try {
delegate.synch();
} finally {
popSession();
}
}
public String getPhysicalClusterNameById(final int iClusterId) {
pushSession();
try {
return delegate.getPhysicalClusterNameById(iClusterId);
} finally {
popSession();
}
}
public int getClusters() {
pushSession();
try {
return delegate.getClusterMap();
} finally {
popSession();
}
}
public Collection<OCluster> getClusterInstances() {
pushSession();
try {
return delegate.getClusterInstances();
} finally {
popSession();
}
}
public OCluster getClusterById(final int iId) {
pushSession();
try {
return delegate.getClusterById(iId);
} finally {
popSession();
}
}
public long getVersion() {
pushSession();
try {
return delegate.getVersion();
} finally {
popSession();
}
}
public boolean isPermanentRequester() {
pushSession();
try {
return delegate.isPermanentRequester();
} finally {
popSession();
}
}
public void updateClusterConfiguration(final String iCurrentURL, final byte[] iContent) {
pushSession();
try {
delegate.updateClusterConfiguration(iCurrentURL, iContent);
} finally {
popSession();
}
}
public OStorageConfiguration getConfiguration() {
pushSession();
try {
return delegate.getConfiguration();
} finally {
popSession();
}
}
public boolean isClosed() {
return (sessionId < 0 && token == null) || delegate.isClosed();
}
public boolean checkForRecordValidity(final OPhysicalPosition ppos) {
pushSession();
try {
return delegate.checkForRecordValidity(ppos);
} finally {
popSession();
}
}
@Override
public boolean isAssigningClusterIds() {
return false;
}
public String getName() {
pushSession();
try {
return delegate.getName();
} finally {
popSession();
}
}
public String getURL() {
return delegate.getURL();
}
public void beginResponse(final OChannelBinaryAsynchClient iNetwork) throws IOException {
pushSession();
try {
delegate.beginResponse(iNetwork);
} finally {
popSession();
}
}
@Override
public OCurrentStorageComponentsFactory getComponentsFactory() {
return delegate.getComponentsFactory();
}
@Override
public long getLastOperationId() {
return 0;
}
public boolean existsResource(final String iName) {
return delegate.existsResource(iName);
}
public synchronized <T> T getResource(final String iName, final Callable<T> iCallback) {
return (T) delegate.getResource(iName, iCallback);
}
public <T> T removeResource(final String iName) {
return (T) delegate.removeResource(iName);
}
public ODocument getClusterConfiguration() {
return delegate.getClusterConfiguration();
}
public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) {
return delegate.callInLock(iCallable, iExclusiveLock);
}
public ORemoteServerEventListener getRemoteServerEventListener() {
return delegate.getAsynchEventListener();
}
public void setRemoteServerEventListener(final ORemoteServerEventListener iListener) {
delegate.setAsynchEventListener(iListener);
}
public void removeRemoteServerEventListener() {
delegate.removeRemoteServerEventListener();
}
@Override
public void checkForClusterPermissions(final String iClusterName) {
delegate.checkForClusterPermissions(iClusterName);
}
public STATUS getStatus() {
return delegate.getStatus();
}
@Override
public String getUserName() {
return delegate.getUserName();
}
@Override
public Object indexGet(final String iIndexName, final Object iKey, final String iFetchPlan) {
return delegate.indexGet(iIndexName, iKey, iFetchPlan);
}
@Override
public void indexPut(final String iIndexName, Object iKey, final OIdentifiable iValue) {
delegate.indexPut(iIndexName, iKey, iValue);
}
@Override
public boolean indexRemove(final String iIndexName, final Object iKey) {
return delegate.indexRemove(iIndexName, iKey);
}
@Override
public String getType() {
return delegate.getType();
}
@Override
public boolean equals(final Object iOther) {
if (iOther instanceof OStorageRemoteThread)
return iOther == this;
if (iOther instanceof OStorageRemote)
return iOther == delegate;
return false;
}
protected void handleException(final OChannelBinaryAsynchClient iNetwork, final String iMessage, final Exception iException) {
delegate.handleException(iNetwork, iMessage, iException);
}
protected void pushSession() {
delegate.setSessionId(serverURL, sessionId, token);
}
protected void popSession() {
serverURL = delegate.getServerURL();
sessionId = delegate.getSessionId();
token = delegate.getSessionToken();
// delegate.clearSession();
}
}
| |
package com.enonic.app.logbrowser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.enonic.xp.script.bean.BeanContext;
import com.enonic.xp.script.bean.ScriptBean;
public class LogFileHandler
implements ScriptBean
{
private static int CR = 0xD;
private static int LF = 0xA;
private Long lineCount;
private Long from;
private String action;
private String search;
private Boolean regex = false;
private Boolean matchCase = false;
public void setLineCount( final Long lineCount )
{
this.lineCount = lineCount;
}
public void setFrom( final Long from )
{
this.from = from;
}
public void setAction( final String action )
{
this.action = action;
}
public void setSearch( final String search )
{
this.search = search;
}
public void setRegex( final Boolean regex )
{
this.regex = regex == null ? this.regex : regex;
}
public void setMatchCase( final Boolean matchCase )
{
this.matchCase = matchCase == null ? this.matchCase : matchCase;
}
public LogLinesMapper getLines()
throws IOException
{
return new LogLinesMapper( readLog() );
}
private LogContext readLog()
throws IOException
{
final Path logPath = LogHelper.getLogPath();
if ( !Files.exists( logPath ) )
{
return new LogContext( 0 );
}
try (final RandomAccessFile raf = new RandomAccessFile( logPath.toFile(), "r" ))
{
final List<LogLine> lines = readLines( raf, this.action, this.lineCount, this.from );
final long size = raf.length();
return new LogContext( lines, size );
}
}
private List<LogLine> readLines( final RandomAccessFile raf, final String action, final long lineCount, final long from )
throws IOException
{
if ( "searchForward".equals( action ) )
{
final long searchMatchPos = findText( raf, from, this.search, ReadDirection.FORWARDS );
if ( searchMatchPos == -1 )
{
return Collections.emptyList();
}
final List<LogLine> lines = readLines( raf, lineCount, searchMatchPos, ReadDirection.FORWARDS );
return lines;
}
if ( "searchBackward".equals( action ) )
{
final long searchMatchPos = findText( raf, from, this.search, ReadDirection.BACKWARDS );
if ( searchMatchPos == -1 )
{
return Collections.emptyList();
}
final List<LogLine> lines = readLines( raf, lineCount, searchMatchPos, ReadDirection.FORWARDS );
return lines;
}
else if ( "forward".equals( action ) )
{
final List<LogLine> lines = readLines( raf, lineCount, from, ReadDirection.FORWARDS );
if ( !lines.isEmpty() )
{
return lines;
}
return readLines( raf, "end", 1, 0 );
}
else if ( "backward".equals( action ) )
{
final List<LogLine> logLines = readLines( raf, lineCount, from, ReadDirection.BACKWARDS );
if ( logLines.size() > 0 && logLines.size() < lineCount )
{
final List<LogLine> nextLines =
readLines( raf, lineCount - logLines.size(), logLines.get( logLines.size() - 1 ).end + 2, ReadDirection.FORWARDS );
logLines.addAll( nextLines );
}
return logLines;
}
else if ( "end".equals( action ) )
{
return readLines( raf, lineCount, raf.length() - 1, ReadDirection.BACKWARDS );
}
else if ( "seek".equals( action ) )
{
final long lineStart;
if ( from == 0 )
{
return readLines( raf, lineCount, from, ReadDirection.FORWARDS );
}
else if ( from == 1000 )
{
return readLines( raf, lineCount, raf.length() - 1, ReadDirection.BACKWARDS );
}
else
{
lineStart = findNextLineStart( raf, ( raf.length() / 1000 ) * from );
return readLines( raf, lineCount, lineStart, ReadDirection.FORWARDS );
}
}
else
{
return Collections.emptyList();
}
}
private long findText( final RandomAccessFile file, long fromOffset, final String search, final ReadDirection direction )
throws IOException
{
if ( search == null || search.length() == 0 )
{
return -1;
}
final long fileLength = file.length() - 1;
ByteArrayOutputStream lineBytes = new ByteArrayOutputStream();
final boolean forward = direction == ReadDirection.FORWARDS;
if ( !forward && fromOffset <= 0 )
{
return -1;
}
if ( forward && fromOffset >= fileLength )
{
return -1;
}
fromOffset = fromOffset < 0 ? 0 : fromOffset;
fromOffset = fromOffset > fileLength ? fileLength : fromOffset;
long lineStart = fromOffset;
final String searchText = matchCase ? search : search.toUpperCase();
final Pattern regexPattern;
try
{
regexPattern = regex ? Pattern.compile( search, matchCase ? 0 : Pattern.CASE_INSENSITIVE ) : null;
}
catch ( PatternSyntaxException e )
{
return -1;// Invalid regex pattern
}
for ( long filePointer = fromOffset; filePointer < fileLength && filePointer != -1; )
{
file.seek( filePointer );
int readByte = file.readByte();
if ( readByte == LF || readByte == CR )
{
if ( filePointer < fileLength )
{
final String lineText = newString( lineBytes, !forward );
if ( regexPattern != null && regexPattern.matcher( lineText ).find() )
{
return forward ? lineStart : filePointer;
}
else
{
if ( !matchCase && lineText.toUpperCase().contains( searchText ) )
{
return forward ? lineStart : filePointer;
}
else if ( matchCase && lineText.contains( searchText ) )
{
return forward ? lineStart : filePointer;
}
}
lineBytes = new ByteArrayOutputStream();
lineStart = filePointer + 1;
}
}
else
{
lineBytes.write( readByte );
}
if ( forward )
{
filePointer++;
}
else
{
filePointer--;
}
}
if ( lineBytes.size() > 0 )
{
final String lineText = newString( lineBytes, !forward );
if ( regexPattern != null && regexPattern.matcher( lineText ).find() )
{
return lineStart;
}
else
{
if ( !matchCase && lineText.toUpperCase().contains( searchText ) )
{
return 0;
}
else if ( matchCase && lineText.contains( searchText ) )
{
return 0;
}
}
}
return -1;
}
private List<LogLine> readLines( final RandomAccessFile file, final long maxLines, long fromOffset, final ReadDirection direction )
throws IOException
{
final long fileLength = file.length() - 1;
int lineCount = 0;
ByteArrayOutputStream lineBytes = new ByteArrayOutputStream();
long filePointer;
final boolean forward = direction == ReadDirection.FORWARDS;
if ( !forward && fromOffset <= 0 )
{
return Collections.emptyList();
}
if ( forward && fromOffset >= fileLength )
{
return Collections.emptyList();
}
fromOffset = fromOffset < 0 ? 0 : fromOffset;
fromOffset = fromOffset > fileLength ? fileLength : fromOffset;
// skip CR or CRLF before reading backwards
if ( !forward )
{
int readByte = readByte( file, fromOffset );
if ( readByte == CR )
{
fromOffset--;
}
else if ( readByte == LF )
{
fromOffset--;
readByte = readByte( file, fromOffset );
if ( readByte == CR )
{
fromOffset--;
}
}
}
final List<LogLine> lines = new ArrayList<>();
long lineStartOffset = fromOffset;
for ( filePointer = fromOffset; filePointer < fileLength && filePointer != -1; )
{
file.seek( filePointer );
int readByte = file.readByte();
if ( readByte == LF || readByte == CR )
{
if ( filePointer < fileLength )
{
final LogLine logLine;
if ( forward )
{
logLine = new LogLine( newString( lineBytes, false ), lineStartOffset, filePointer );
lineStartOffset = filePointer + 1;
}
else
{
logLine = new LogLine( newString( lineBytes, true ), filePointer + 1, lineStartOffset );
lineStartOffset = filePointer - 1;
}
lines.add( logLine );
lineBytes = new ByteArrayOutputStream();
lineCount = lineCount + 1;
}
}
if ( lineCount >= maxLines )
{
break;
}
if ( readByte != LF && readByte != CR )
{
lineBytes.write( readByte );
}
if ( forward )
{
filePointer++;
}
else
{
filePointer--;
}
}
if ( lineBytes.size() > 0 )
{
final String lastLine = newString( lineBytes, !forward );
final LogLine logLine;
if ( forward )
{
new LogLine( lastLine, lineStartOffset, filePointer );
logLine = new LogLine( lastLine, lineStartOffset, Math.min( filePointer, fileLength ) );
}
else
{
logLine = new LogLine( lastLine, Math.max( filePointer, 0 ), lineStartOffset );
}
lines.add( logLine );
}
if ( direction == ReadDirection.BACKWARDS )
{
Collections.reverse( lines );
}
return lines;
}
private long findNextLineStart( final RandomAccessFile file, final Long from )
throws IOException
{
final long fileLength = file.length() - 1;
long filePointer;
for ( filePointer = from; filePointer < fileLength && filePointer != -1; filePointer++ )
{
file.seek( filePointer );
int readByte = file.readByte();
if ( readByte == LF )
{
filePointer++;
break;
}
if ( readByte == CR )
{
if ( readByte( file, filePointer + 1 ) == LF )
{
filePointer++;
}
filePointer++;
break;
}
}
return filePointer;
}
private int readByte( final RandomAccessFile file, final long position )
{
try
{
file.seek( position );
return file.readByte();
}
catch ( IOException e )
{
return -1;
}
}
private String newString( final ByteArrayOutputStream bytes, final boolean reverse )
{
final byte[] byteArray = bytes.toByteArray();
if ( reverse )
{
reverse( byteArray );
}
return new String( byteArray, StandardCharsets.UTF_8 );
}
private void reverse( final byte[] array )
{
int i = 0;
int j = array.length - 1;
byte tmp;
while ( j > i )
{
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
@Override
public void initialize( final BeanContext context )
{
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.ml;
import com.facebook.presto.common.block.Block;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.DoubleType.DOUBLE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SizeOf.SIZE_OF_INT;
import static io.airlift.slice.SizeOf.SIZE_OF_LONG;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
public final class ModelUtils
{
private static final int VERSION_OFFSET = 0;
private static final int HASH_OFFSET = VERSION_OFFSET + SIZE_OF_INT;
private static final int ALGORITHM_OFFSET = HASH_OFFSET + 32;
private static final int HYPERPARAMETER_LENGTH_OFFSET = ALGORITHM_OFFSET + SIZE_OF_INT;
private static final int HYPERPARAMETERS_OFFSET = HYPERPARAMETER_LENGTH_OFFSET + SIZE_OF_INT;
private static final int CURRENT_FORMAT_VERSION = 1;
// These ids are serialized to disk. Do not change them.
@VisibleForTesting
static final BiMap<Class<? extends Model>, Integer> MODEL_SERIALIZATION_IDS;
static {
ImmutableBiMap.Builder<Class<? extends Model>, Integer> builder = ImmutableBiMap.builder();
builder.put(SvmClassifier.class, 1);
builder.put(SvmRegressor.class, 2);
builder.put(FeatureVectorUnitNormalizer.class, 3);
builder.put(ClassifierFeatureTransformer.class, 4);
builder.put(RegressorFeatureTransformer.class, 5);
builder.put(FeatureUnitNormalizer.class, 6);
builder.put(StringClassifierAdapter.class, 7);
MODEL_SERIALIZATION_IDS = builder.build();
}
private ModelUtils()
{
}
/**
* Serializes the model using the following format
* int: format version
* byte[32]: SHA256 hash of all following data
* int: id of algorithm
* int: length of hyperparameters section
* byte[]: hyperparameters (currently not used)
* long: length of data section
* byte[]: model data
* <p>
* note: all multibyte values are in little endian
*/
public static Slice serialize(Model model)
{
requireNonNull(model, "model is null");
Integer id = MODEL_SERIALIZATION_IDS.get(model.getClass());
requireNonNull(id, "id is null");
int size = HYPERPARAMETERS_OFFSET;
// hyperparameters aren't implemented yet
byte[] hyperparameters = new byte[0];
size += hyperparameters.length;
int dataLengthOffset = size;
size += SIZE_OF_LONG;
int dataOffset = size;
byte[] data = model.getSerializedData();
size += data.length;
Slice slice = Slices.allocate(size);
slice.setInt(VERSION_OFFSET, CURRENT_FORMAT_VERSION);
slice.setInt(ALGORITHM_OFFSET, id);
slice.setInt(HYPERPARAMETER_LENGTH_OFFSET, hyperparameters.length);
slice.setBytes(HYPERPARAMETERS_OFFSET, hyperparameters);
slice.setLong(dataLengthOffset, data.length);
slice.setBytes(dataOffset, data);
byte[] modelHash = Hashing.sha256().hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET)).asBytes();
checkState(modelHash.length == 32, "sha256 hash code expected to be 32 bytes");
slice.setBytes(HASH_OFFSET, modelHash);
return slice;
}
public static HashCode modelHash(Slice slice)
{
return HashCode.fromBytes(slice.getBytes(HASH_OFFSET, 32));
}
public static Model deserialize(byte[] data)
{
return deserialize(Slices.wrappedBuffer(data));
}
public static Model deserialize(Slice slice)
{
int version = slice.getInt(VERSION_OFFSET);
checkArgument(version == CURRENT_FORMAT_VERSION, format("Unsupported version: %d", version));
byte[] modelHashBytes = slice.getBytes(HASH_OFFSET, 32);
HashCode expectedHash = HashCode.fromBytes(modelHashBytes);
HashCode actualHash = Hashing.sha256().hashBytes(slice.getBytes(ALGORITHM_OFFSET, slice.length() - ALGORITHM_OFFSET));
checkArgument(actualHash.equals(expectedHash), "model hash does not match data");
int id = slice.getInt(ALGORITHM_OFFSET);
Class<? extends Model> algorithm = MODEL_SERIALIZATION_IDS.inverse().get(id);
requireNonNull(algorithm, format("Unsupported algorith %d", id));
int hyperparameterLength = slice.getInt(HYPERPARAMETER_LENGTH_OFFSET);
byte[] hyperparameterBytes = slice.getBytes(HYPERPARAMETERS_OFFSET, hyperparameterLength);
int dataLengthOffset = HYPERPARAMETERS_OFFSET + hyperparameterLength;
long dataLength = slice.getLong(dataLengthOffset);
int dataOffset = dataLengthOffset + SIZE_OF_LONG;
byte[] data = slice.getBytes(dataOffset, (int) dataLength);
try {
Method deserialize = algorithm.getMethod("deserialize", byte[].class);
return (Model) deserialize.invoke(null, new Object[] {data});
}
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static byte[] serializeModels(Model... models)
{
List<byte[]> serializedModels = new ArrayList<>();
int size = SIZE_OF_INT + SIZE_OF_INT * models.length;
for (Model model : models) {
byte[] bytes = serialize(model).getBytes();
size += bytes.length;
serializedModels.add(bytes);
}
Slice slice = Slices.allocate(size);
slice.setInt(0, models.length);
for (int i = 0; i < models.length; i++) {
slice.setInt(SIZE_OF_INT * (i + 1), serializedModels.get(i).length);
}
int offset = SIZE_OF_INT + SIZE_OF_INT * models.length;
for (byte[] bytes : serializedModels) {
slice.setBytes(offset, bytes);
offset += bytes.length;
}
return slice.getBytes();
}
public static List<Model> deserializeModels(byte[] bytes)
{
Slice slice = Slices.wrappedBuffer(bytes);
int numModels = slice.getInt(0);
int offset = SIZE_OF_INT + SIZE_OF_INT * numModels;
ImmutableList.Builder<Model> models = ImmutableList.builder();
for (int i = 0; i < numModels; i++) {
int length = slice.getInt(SIZE_OF_INT * (i + 1));
models.add(deserialize(slice.getBytes(offset, length)));
offset += length;
}
return models.build();
}
//TODO: instead of having this function, we should add feature extractors that extend Model and extract features from Strings
public static FeatureVector toFeatures(Block map)
{
Map<Integer, Double> features = new HashMap<>();
if (map != null) {
for (int position = 0; position < map.getPositionCount(); position += 2) {
features.put((int) BIGINT.getLong(map, position), DOUBLE.getDouble(map, position + 1));
}
}
return new FeatureVector(features);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.