lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 3a09881dc11e6c805283b5a5331b1ee7a7867fa6 | 0 | thiagola92/PUC-INF1407,thiagola92/PUC-INF1407,thiagola92/PUC-INF1407 | package pacote;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CalculaServlet")
public class CalculaServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// obter dados
String s0p1 = request.getParameter("operando1");
String s0p2 = request.getParameter("operando2");
String operacao = request.getParameter("operacao");
// processar dados
double operando1 = Double.parseDouble(s0p1);
double operando2 = Double.parseDouble(s0p2);
double resultado = 0;
if(operacao.equals("+")) {
resultado = operando1 + operando2;
} else if(operacao.equals("-")) {
resultado = operando1 - operando2;
} else if(operacao.equals("/")) {
resultado = operando1 / operando2;
} else if(operacao.equals("x")) {
resultado = operando1 * operando2;
} else {
// ERRO!!!
request.setAttribute("tipoErro", "operacao invalida");
request.getRequestDispatcher("../erros/erro.jsp").forward(request, response);
return;
}
// encaminhar resultados para o visual
CalculaBean bean = new CalculaBean();
bean.setOp1(operando1);
bean.setOp2(operando2);
bean.setOperador(operacao);
bean.setResultado(resultado);
request.setAttribute("conta", bean);
request.getRequestDispatcher("calculadora/resultado.jsp").forward(request, response);
}
}
| Aula10/outroExemplo/CalculaServlet.java | package pacote;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CalculaServlet")
public class CalculaServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| Update CalculaServlet.java | Aula10/outroExemplo/CalculaServlet.java | Update CalculaServlet.java | <ide><path>ula10/outroExemplo/CalculaServlet.java
<ide> package pacote;
<ide>
<ide> import java.io.IOException;
<add>
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.annotation.WebServlet;
<ide> import javax.servlet.http.HttpServlet;
<ide> public class CalculaServlet extends HttpServlet {
<ide>
<ide> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
<add> // obter dados
<add> String s0p1 = request.getParameter("operando1");
<add> String s0p2 = request.getParameter("operando2");
<add> String operacao = request.getParameter("operacao");
<add>
<add> // processar dados
<add> double operando1 = Double.parseDouble(s0p1);
<add> double operando2 = Double.parseDouble(s0p2);
<add> double resultado = 0;
<add>
<add> if(operacao.equals("+")) {
<add> resultado = operando1 + operando2;
<add> } else if(operacao.equals("-")) {
<add> resultado = operando1 - operando2;
<add> } else if(operacao.equals("/")) {
<add> resultado = operando1 / operando2;
<add> } else if(operacao.equals("x")) {
<add> resultado = operando1 * operando2;
<add> } else {
<add> // ERRO!!!
<add> request.setAttribute("tipoErro", "operacao invalida");
<add> request.getRequestDispatcher("../erros/erro.jsp").forward(request, response);
<add> return;
<add> }
<add>
<add> // encaminhar resultados para o visual
<add> CalculaBean bean = new CalculaBean();
<add> bean.setOp1(operando1);
<add> bean.setOp2(operando2);
<add> bean.setOperador(operacao);
<add> bean.setResultado(resultado);
<add> request.setAttribute("conta", bean);
<add> request.getRequestDispatcher("calculadora/resultado.jsp").forward(request, response);
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 5b6b5482f78acb9cc0e43a9f64e828c0b915d890 | 0 | serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.model.impl.jdbc;
import org.eclipse.core.runtime.IAdaptable;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.data.DBDDataFormatterProfile;
import org.jkiss.dbeaver.model.data.DBDPreferences;
import org.jkiss.dbeaver.model.data.DBDValueHandler;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCFactory;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCObjectValueHandler;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCConnectionImpl;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCFactoryDefault;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLState;
import org.jkiss.dbeaver.model.struct.DBSDataType;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.net.SocketException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* JDBC data source
*/
public abstract class JDBCDataSource
implements
DBPDataSource,
SQLDataSource,
DBPDataTypeProvider,
DBPErrorAssistant,
DBPRefreshableObject,
DBDPreferences,
DBSObject,
DBSObjectContainer,
DBCQueryTransformProvider,
IAdaptable
{
private static final Log log = Log.getLog(JDBCDataSource.class);
public static final int DISCONNECT_TIMEOUT = 5000;
@NotNull
private final DBPDataSourceContainer container;
@NotNull
protected final JDBCExecutionContext executionContext;
@Nullable
protected JDBCExecutionContext metaContext;
@NotNull
private final List<JDBCExecutionContext> allContexts = new ArrayList<>();
@NotNull
protected volatile DBPDataSourceInfo dataSourceInfo;
protected volatile SQLDialect sqlDialect;
protected final JDBCFactory jdbcFactory;
private int databaseMajorVersion;
private int databaseMinorVersion;
public JDBCDataSource(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSourceContainer container)
throws DBException
{
this.dataSourceInfo = new JDBCDataSourceInfo(container);
this.sqlDialect = BasicSQLDialect.INSTANCE;
this.jdbcFactory = createJdbcFactory();
this.container = container;
this.executionContext = new JDBCExecutionContext(this, "Main");
this.executionContext.connect(monitor, null, null, false);
}
protected Connection openConnection(@NotNull DBRProgressMonitor monitor, @NotNull String purpose)
throws DBCException
{
// It MUST be a JDBC driver
Driver driverInstance;
try {
driverInstance = getDriverInstance(monitor);
} catch (DBException e) {
throw new DBCConnectException("Can't create driver instance", e, this);
}
// Set properties
Properties connectProps = new Properties();
{
// Use properties defined by datasource itself
Map<String,String> internalProps = getInternalConnectionProperties(monitor, purpose);
if (internalProps != null) {
connectProps.putAll(internalProps);
}
}
{
// Use driver properties
final Map<Object, Object> driverProperties = container.getDriver().getConnectionProperties();
for (Map.Entry<Object,Object> prop : driverProperties.entrySet()) {
connectProps.setProperty(CommonUtils.toString(prop.getKey()), CommonUtils.toString(prop.getValue()));
}
}
DBPConnectionConfiguration connectionInfo = container.getActualConnectionConfiguration();
for (Map.Entry<String, String> prop : connectionInfo.getProperties().entrySet()) {
connectProps.setProperty(CommonUtils.toString(prop.getKey()), CommonUtils.toString(prop.getValue()));
}
if (!CommonUtils.isEmpty(connectionInfo.getUserName())) {
connectProps.put(DBConstants.DATA_SOURCE_PROPERTY_USER, getConnectionUserName(connectionInfo));
}
if (!CommonUtils.isEmpty(connectionInfo.getUserPassword())) {
connectProps.put(DBConstants.DATA_SOURCE_PROPERTY_PASSWORD, getConnectionUserPassword(connectionInfo));
}
// Obtain connection
try {
final String url = getConnectionURL(connectionInfo);
if (driverInstance != null) {
try {
if (!driverInstance.acceptsURL(url)) {
// Just write a warning in log. Some drivers are poorly coded and always returns false here.
log.error("Bad URL: " + url);
}
} catch (Throwable e) {
log.debug("Error in " + driverInstance.getClass().getName() + ".acceptsURL() - " + url, e);
}
}
monitor.subTask("Connecting " + purpose);
Connection connection;
if (driverInstance == null) {
connection = DriverManager.getConnection(url, connectProps);
} else {
connection = driverInstance.connect(url, connectProps);
}
if (connection == null) {
throw new DBCException("Null connection returned");
}
// Set read-only flag
if (container.isConnectionReadOnly() && !isConnectionReadOnlyBroken()) {
connection.setReadOnly(true);
}
return connection;
}
catch (SQLException ex) {
throw new DBCConnectException(ex.getMessage(), ex, this);
}
catch (DBCException ex) {
throw ex;
}
catch (Throwable e) {
throw new DBCConnectException("Unexpected driver error occurred while connecting to database", e);
}
}
protected String getConnectionURL(DBPConnectionConfiguration connectionInfo) {
return connectionInfo.getUrl();
}
protected void closeConnection(final Connection connection, String purpose)
{
if (connection != null) {
// Close datasource (in async task)
RuntimeUtils.runTask(new DBRRunnableWithProgress() {
@Override
public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
// If we in transaction - rollback it.
// Any valuable transaction changes should be committed by UI
// so here we do it just in case to avoid error messages on close with open transaction
if (!connection.getAutoCommit()) {
connection.rollback();
}
} catch (Throwable e) {
// Do not write warning because connection maybe broken before the moment of close
log.debug("Error closing transaction", e);
}
try {
connection.close();
}
catch (Throwable ex) {
log.error("Error closing connection", ex);
}
}
}, "Close JDBC connection (" + purpose + ")", DISCONNECT_TIMEOUT);
}
}
/*
@Override
public JDBCSession openSession(DBRProgressMonitor monitor, DBCExecutionPurpose purpose, String taskTitle)
{
if (metaContext != null && (purpose == DBCExecutionPurpose.META || purpose == DBCExecutionPurpose.META_DDL)) {
return createConnection(monitor, this.metaContext, purpose, taskTitle);
}
return createConnection(monitor, executionContext, purpose, taskTitle);
}
*/
@NotNull
@Override
public DBCExecutionContext openIsolatedContext(@NotNull DBRProgressMonitor monitor, @NotNull String purpose) throws DBException
{
JDBCExecutionContext context = new JDBCExecutionContext(this, purpose);
context.connect(monitor, null, null, true);
return context;
}
protected void initializeContextState(@NotNull DBRProgressMonitor monitor, @NotNull JDBCExecutionContext context, boolean setActiveObject) throws DBCException {
}
@NotNull
protected JDBCConnectionImpl createConnection(
@NotNull DBRProgressMonitor monitor,
@NotNull JDBCExecutionContext context,
@NotNull DBCExecutionPurpose purpose,
@NotNull String taskTitle)
{
return new JDBCConnectionImpl(context, monitor, purpose, taskTitle);
}
@NotNull
@Override
public DBPDataSourceContainer getContainer()
{
return container;
}
@NotNull
@Override
public DBPDataSourceInfo getInfo()
{
return dataSourceInfo;
}
@NotNull
@Override
public SQLDialect getSQLDialect() {
return sqlDialect;
}
@NotNull
public JDBCFactory getJdbcFactory() {
return jdbcFactory;
}
@NotNull
@Override
public synchronized JDBCExecutionContext getDefaultContext(boolean meta) {
if (metaContext != null && meta) {
return this.metaContext;
}
return executionContext;
}
@NotNull
@Override
public JDBCExecutionContext[] getAllContexts() {
synchronized (allContexts) {
return allContexts.toArray(new JDBCExecutionContext[allContexts.size()]);
}
}
void addContext(JDBCExecutionContext context) {
synchronized (allContexts) {
allContexts.add(context);
}
}
boolean removeContext(JDBCExecutionContext context) {
synchronized (allContexts) {
return allContexts.remove(context);
}
}
@Override
public void initialize(@NotNull DBRProgressMonitor monitor)
throws DBException
{
if (!container.getDriver().isEmbedded() && container.getPreferenceStore().getBoolean(ModelPreferences.META_SEPARATE_CONNECTION)) {
synchronized (allContexts) {
this.metaContext = new JDBCExecutionContext(this, "Metadata");
this.metaContext.connect(monitor, true, null, false);
}
}
try (JDBCSession session = DBUtils.openMetaSession(monitor, this, ModelMessages.model_jdbc_read_database_meta_data)) {
JDBCDatabaseMetaData metaData = session.getMetaData();
try {
databaseMajorVersion = metaData.getDatabaseMajorVersion();
databaseMinorVersion = metaData.getDatabaseMinorVersion();
} catch (Throwable e) {
log.error("Error determining server version", e);
}
try {
sqlDialect = createSQLDialect(metaData);
} catch (Throwable e) {
log.error("Error creating SQL dialect", e);
}
try {
dataSourceInfo = createDataSourceInfo(metaData);
} catch (Throwable e) {
log.error("Error obtaining database info");
}
} catch (SQLException ex) {
throw new DBException("Error getting JDBC meta data", ex, this);
} finally {
if (sqlDialect == null) {
log.warn("NULL SQL dialect was created");
sqlDialect = BasicSQLDialect.INSTANCE;
}
if (dataSourceInfo == null) {
log.warn("NULL datasource info was created");
dataSourceInfo = new JDBCDataSourceInfo(container);
}
}
}
@Override
public void shutdown(DBRProgressMonitor monitor)
{
// [JDBC] Need sync here because real connection close could take some time
// while UI may invoke callbacks to operate with connection
synchronized (allContexts) {
List<JDBCExecutionContext> ctxCopy = new ArrayList<>(allContexts);
for (JDBCExecutionContext context : ctxCopy) {
monitor.subTask("Close context '" + context.getContextName() + "'");
context.close();
monitor.worked(1);
}
}
}
public boolean isServerVersionAtLeast(int major, int minor) {
if (databaseMajorVersion < major) {
return false;
} else if (databaseMajorVersion == major && databaseMinorVersion < minor) {
return false;
}
return true;
}
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName()
{
return container.getName();
}
@Nullable
@Override
public String getDescription()
{
return container.getDescription();
}
@Override
public DBSObject getParentObject()
{
return container;
}
@Override
public boolean isPersisted()
{
return true;
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
this.dataSourceInfo = new JDBCDataSourceInfo(container);
return this;
}
@Nullable
@Override
public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type)
{
// if (type == DBCQueryTransformType.ORDER_BY) {
//
// } else if (type == DBCQueryTransformType.FILTER) {
//
// }
return null;
}
private static int getValueTypeByTypeName(@NotNull String typeName, int valueType)
{
// [JDBC: SQLite driver uses VARCHAR value type for all LOBs]
if (valueType == Types.OTHER || valueType == Types.VARCHAR) {
if ("BLOB".equalsIgnoreCase(typeName)) {
return Types.BLOB;
} else if ("CLOB".equalsIgnoreCase(typeName)) {
return Types.CLOB;
} else if ("NCLOB".equalsIgnoreCase(typeName)) {
return Types.NCLOB;
}
} else if (valueType == Types.BIT) {
// Workaround for MySQL (and maybe others) when TINYINT(1) == BOOLEAN
if ("TINYINT".equalsIgnoreCase(typeName)) {
return Types.TINYINT;
}
}
return valueType;
}
@NotNull
public DBPDataKind resolveDataKind(@NotNull String typeName, int valueType)
{
return getDataKind(typeName, valueType);
}
@NotNull
public static DBPDataKind getDataKind(@NotNull String typeName, int valueType)
{
switch (getValueTypeByTypeName(typeName, valueType)) {
case Types.BOOLEAN:
return DBPDataKind.BOOLEAN;
case Types.CHAR:
case Types.VARCHAR:
case Types.NVARCHAR:
return DBPDataKind.STRING;
case Types.BIGINT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.INTEGER:
case Types.NUMERIC:
case Types.REAL:
case Types.SMALLINT:
return DBPDataKind.NUMERIC;
case Types.BIT:
case Types.TINYINT:
if (typeName.toLowerCase().contains("bool")) {
// Declared as numeric but actually it's a boolean
return DBPDataKind.BOOLEAN;
}
return DBPDataKind.NUMERIC;
case Types.DATE:
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
return DBPDataKind.DATETIME;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return DBPDataKind.BINARY;
case Types.BLOB:
case Types.CLOB:
case Types.NCLOB:
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
return DBPDataKind.CONTENT;
case Types.SQLXML:
return DBPDataKind.CONTENT;
case Types.STRUCT:
return DBPDataKind.STRUCT;
case Types.ARRAY:
return DBPDataKind.ARRAY;
case Types.ROWID:
return DBPDataKind.ROWID;
case Types.REF:
return DBPDataKind.REFERENCE;
case Types.OTHER:
// TODO: really?
return DBPDataKind.OBJECT;
}
return DBPDataKind.UNKNOWN;
}
@Nullable
@Override
public DBSDataType resolveDataType(@NotNull DBRProgressMonitor monitor, @NotNull String typeFullName) throws DBException
{
return getLocalDataType(typeFullName);
}
@Override
public String getDefaultDataTypeName(@NotNull DBPDataKind dataKind)
{
switch (dataKind) {
case BOOLEAN: return "BOOLEAN";
case NUMERIC: return "NUMERIC";
case STRING: return "VARCHAR";
case DATETIME: return "TIMESTAMP";
case BINARY: return "BLOB";
case CONTENT: return "BLOB";
case STRUCT: return "VARCHAR";
case ARRAY: return "VARCHAR";
case OBJECT: return "VARCHAR";
case REFERENCE: return "VARCHAR";
case ROWID: return "ROWID";
case ANY: return "VARCHAR";
default: return "VARCHAR";
}
}
/////////////////////////////////////////////////
// Overridable functions
protected boolean isConnectionReadOnlyBroken() {
return false;
}
protected String getConnectionUserName(@NotNull DBPConnectionConfiguration connectionInfo)
{
return connectionInfo.getUserName();
}
protected String getConnectionUserPassword(@NotNull DBPConnectionConfiguration connectionInfo)
{
return connectionInfo.getUserPassword();
}
@Nullable
protected Driver getDriverInstance(@NotNull DBRProgressMonitor monitor)
throws DBException
{
return Driver.class.cast(
container.getDriver().getDriverInstance(monitor));
}
/**
* Could be overridden by extenders. May contain any additional connection properties.
* Note: these properties may be overwritten by connection advanced properties.
* @return predefined connection properties
* @param monitor
* @param purpose
*/
@Nullable
protected Map<String, String> getInternalConnectionProperties(DBRProgressMonitor monitor, String purpose)
throws DBCException
{
return null;
}
protected DBPDataSourceInfo createDataSourceInfo(@NotNull JDBCDatabaseMetaData metaData)
{
return new JDBCDataSourceInfo(metaData);
}
protected SQLDialect createSQLDialect(@NotNull JDBCDatabaseMetaData metaData)
{
return new JDBCSQLDialect("JDBC", metaData);
}
@NotNull
protected JDBCFactory createJdbcFactory() {
return new JDBCFactoryDefault();
}
/////////////////////////////////////////////////
// Error assistance
@Override
public ErrorType discoverErrorType(@NotNull DBException error)
{
String sqlState = error.getDatabaseState();
if (SQLState.SQL_08000.getCode().equals(sqlState) ||
SQLState.SQL_08003.getCode().equals(sqlState) ||
SQLState.SQL_08006.getCode().equals(sqlState) ||
SQLState.SQL_08007.getCode().equals(sqlState) ||
SQLState.SQL_08S01.getCode().equals(sqlState))
{
return ErrorType.CONNECTION_LOST;
}
if (GeneralUtils.getRootCause(error) instanceof SocketException) {
return ErrorType.CONNECTION_LOST;
}
if (error instanceof DBCConnectException) {
Throwable rootCause = GeneralUtils.getRootCause(error);
if (rootCause instanceof ClassNotFoundException) {
// Looks like bad driver configuration
return ErrorType.DRIVER_CLASS_MISSING;
}
}
return ErrorType.NORMAL;
}
@Nullable
@Override
public ErrorPosition[] getErrorPosition(@NotNull DBCSession session, @NotNull String query, @NotNull Throwable error) {
return null;
}
@Override
public <T> T getAdapter(Class<T> adapter) {
if (adapter == DBCTransactionManager.class) {
return adapter.cast(executionContext);
}
return null;
}
/////////////////////////////////////////////////
// DBDPreferences
@Override
public DBDDataFormatterProfile getDataFormatterProfile() {
return container.getDataFormatterProfile();
}
@Override
public void setDataFormatterProfile(DBDDataFormatterProfile formatterProfile) {
container.setDataFormatterProfile(formatterProfile);
}
@NotNull
@Override
public DBDValueHandler getDefaultValueHandler() {
return JDBCObjectValueHandler.INSTANCE;
}
}
| plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/JDBCDataSource.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.model.impl.jdbc;
import org.eclipse.core.runtime.IAdaptable;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.connection.DBPConnectionConfiguration;
import org.jkiss.dbeaver.model.data.DBDDataFormatterProfile;
import org.jkiss.dbeaver.model.data.DBDPreferences;
import org.jkiss.dbeaver.model.data.DBDValueHandler;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCFactory;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCObjectValueHandler;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCConnectionImpl;
import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCFactoryDefault;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.sql.SQLState;
import org.jkiss.dbeaver.model.struct.DBSDataType;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* JDBC data source
*/
public abstract class JDBCDataSource
implements
DBPDataSource,
SQLDataSource,
DBPDataTypeProvider,
DBPErrorAssistant,
DBPRefreshableObject,
DBDPreferences,
DBSObject,
DBSObjectContainer,
DBCQueryTransformProvider,
IAdaptable
{
private static final Log log = Log.getLog(JDBCDataSource.class);
public static final int DISCONNECT_TIMEOUT = 5000;
@NotNull
private final DBPDataSourceContainer container;
@NotNull
protected final JDBCExecutionContext executionContext;
@Nullable
protected JDBCExecutionContext metaContext;
@NotNull
private final List<JDBCExecutionContext> allContexts = new ArrayList<>();
@NotNull
protected volatile DBPDataSourceInfo dataSourceInfo;
protected volatile SQLDialect sqlDialect;
protected final JDBCFactory jdbcFactory;
private int databaseMajorVersion;
private int databaseMinorVersion;
public JDBCDataSource(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSourceContainer container)
throws DBException
{
this.dataSourceInfo = new JDBCDataSourceInfo(container);
this.sqlDialect = BasicSQLDialect.INSTANCE;
this.jdbcFactory = createJdbcFactory();
this.container = container;
this.executionContext = new JDBCExecutionContext(this, "Main");
this.executionContext.connect(monitor, null, null, false);
}
protected Connection openConnection(@NotNull DBRProgressMonitor monitor, @NotNull String purpose)
throws DBCException
{
// It MUST be a JDBC driver
Driver driverInstance;
try {
driverInstance = getDriverInstance(monitor);
} catch (DBException e) {
throw new DBCConnectException("Can't create driver instance", e, this);
}
// Set properties
Properties connectProps = new Properties();
{
// Use properties defined by datasource itself
Map<String,String> internalProps = getInternalConnectionProperties(monitor, purpose);
if (internalProps != null) {
connectProps.putAll(internalProps);
}
}
{
// Use driver properties
final Map<Object, Object> driverProperties = container.getDriver().getConnectionProperties();
for (Map.Entry<Object,Object> prop : driverProperties.entrySet()) {
connectProps.setProperty(CommonUtils.toString(prop.getKey()), CommonUtils.toString(prop.getValue()));
}
}
DBPConnectionConfiguration connectionInfo = container.getActualConnectionConfiguration();
for (Map.Entry<String, String> prop : connectionInfo.getProperties().entrySet()) {
connectProps.setProperty(CommonUtils.toString(prop.getKey()), CommonUtils.toString(prop.getValue()));
}
if (!CommonUtils.isEmpty(connectionInfo.getUserName())) {
connectProps.put(DBConstants.DATA_SOURCE_PROPERTY_USER, getConnectionUserName(connectionInfo));
}
if (!CommonUtils.isEmpty(connectionInfo.getUserPassword())) {
connectProps.put(DBConstants.DATA_SOURCE_PROPERTY_PASSWORD, getConnectionUserPassword(connectionInfo));
}
// Obtain connection
try {
final String url = getConnectionURL(connectionInfo);
if (driverInstance != null) {
try {
if (!driverInstance.acceptsURL(url)) {
// Just write a warning in log. Some drivers are poorly coded and always returns false here.
log.error("Bad URL: " + url);
}
} catch (Throwable e) {
log.debug("Error in " + driverInstance.getClass().getName() + ".acceptsURL() - " + url, e);
}
}
monitor.subTask("Connecting " + purpose);
Connection connection;
if (driverInstance == null) {
connection = DriverManager.getConnection(url, connectProps);
} else {
connection = driverInstance.connect(url, connectProps);
}
if (connection == null) {
throw new DBCException("Null connection returned");
}
// Set read-only flag
if (container.isConnectionReadOnly() && !isConnectionReadOnlyBroken()) {
connection.setReadOnly(true);
}
return connection;
}
catch (SQLException ex) {
throw new DBCConnectException(ex.getMessage(), ex, this);
}
catch (DBCException ex) {
throw ex;
}
catch (Throwable e) {
throw new DBCConnectException("Unexpected driver error occurred while connecting to database", e);
}
}
protected String getConnectionURL(DBPConnectionConfiguration connectionInfo) {
return connectionInfo.getUrl();
}
protected void closeConnection(final Connection connection, String purpose)
{
if (connection != null) {
// Close datasource (in async task)
RuntimeUtils.runTask(new DBRRunnableWithProgress() {
@Override
public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
// If we in transaction - rollback it.
// Any valuable transaction changes should be committed by UI
// so here we do it just in case to avoid error messages on close with open transaction
if (!connection.getAutoCommit()) {
connection.rollback();
}
} catch (Throwable e) {
// Do not write warning because connection maybe broken before the moment of close
log.debug("Error closing transaction", e);
}
try {
connection.close();
}
catch (Throwable ex) {
log.error("Error closing connection", ex);
}
}
}, "Close JDBC connection (" + purpose + ")", DISCONNECT_TIMEOUT);
}
}
/*
@Override
public JDBCSession openSession(DBRProgressMonitor monitor, DBCExecutionPurpose purpose, String taskTitle)
{
if (metaContext != null && (purpose == DBCExecutionPurpose.META || purpose == DBCExecutionPurpose.META_DDL)) {
return createConnection(monitor, this.metaContext, purpose, taskTitle);
}
return createConnection(monitor, executionContext, purpose, taskTitle);
}
*/
@NotNull
@Override
public DBCExecutionContext openIsolatedContext(@NotNull DBRProgressMonitor monitor, @NotNull String purpose) throws DBException
{
JDBCExecutionContext context = new JDBCExecutionContext(this, purpose);
context.connect(monitor, null, null, true);
return context;
}
protected void initializeContextState(@NotNull DBRProgressMonitor monitor, @NotNull JDBCExecutionContext context, boolean setActiveObject) throws DBCException {
}
@NotNull
protected JDBCConnectionImpl createConnection(
@NotNull DBRProgressMonitor monitor,
@NotNull JDBCExecutionContext context,
@NotNull DBCExecutionPurpose purpose,
@NotNull String taskTitle)
{
return new JDBCConnectionImpl(context, monitor, purpose, taskTitle);
}
@NotNull
@Override
public DBPDataSourceContainer getContainer()
{
return container;
}
@NotNull
@Override
public DBPDataSourceInfo getInfo()
{
return dataSourceInfo;
}
@NotNull
@Override
public SQLDialect getSQLDialect() {
return sqlDialect;
}
@NotNull
public JDBCFactory getJdbcFactory() {
return jdbcFactory;
}
@NotNull
@Override
public synchronized JDBCExecutionContext getDefaultContext(boolean meta) {
if (metaContext != null && meta) {
return this.metaContext;
}
return executionContext;
}
@NotNull
@Override
public JDBCExecutionContext[] getAllContexts() {
synchronized (allContexts) {
return allContexts.toArray(new JDBCExecutionContext[allContexts.size()]);
}
}
void addContext(JDBCExecutionContext context) {
synchronized (allContexts) {
allContexts.add(context);
}
}
boolean removeContext(JDBCExecutionContext context) {
synchronized (allContexts) {
return allContexts.remove(context);
}
}
@Override
public void initialize(@NotNull DBRProgressMonitor monitor)
throws DBException
{
if (!container.getDriver().isEmbedded() && container.getPreferenceStore().getBoolean(ModelPreferences.META_SEPARATE_CONNECTION)) {
synchronized (allContexts) {
this.metaContext = new JDBCExecutionContext(this, "Metadata");
this.metaContext.connect(monitor, true, null, false);
}
}
try (JDBCSession session = DBUtils.openMetaSession(monitor, this, ModelMessages.model_jdbc_read_database_meta_data)) {
JDBCDatabaseMetaData metaData = session.getMetaData();
try {
databaseMajorVersion = metaData.getDatabaseMajorVersion();
databaseMinorVersion = metaData.getDatabaseMinorVersion();
} catch (Throwable e) {
log.error("Error determining server version", e);
}
try {
sqlDialect = createSQLDialect(metaData);
} catch (Throwable e) {
log.error("Error creating SQL dialect", e);
}
try {
dataSourceInfo = createDataSourceInfo(metaData);
} catch (Throwable e) {
log.error("Error obtaining database info");
}
} catch (SQLException ex) {
throw new DBException("Error getting JDBC meta data", ex, this);
} finally {
if (sqlDialect == null) {
log.warn("NULL SQL dialect was created");
sqlDialect = BasicSQLDialect.INSTANCE;
}
if (dataSourceInfo == null) {
log.warn("NULL datasource info was created");
dataSourceInfo = new JDBCDataSourceInfo(container);
}
}
}
@Override
public void shutdown(DBRProgressMonitor monitor)
{
// [JDBC] Need sync here because real connection close could take some time
// while UI may invoke callbacks to operate with connection
synchronized (allContexts) {
List<JDBCExecutionContext> ctxCopy = new ArrayList<>(allContexts);
for (JDBCExecutionContext context : ctxCopy) {
monitor.subTask("Close context '" + context.getContextName() + "'");
context.close();
monitor.worked(1);
}
}
}
public boolean isServerVersionAtLeast(int major, int minor) {
if (databaseMajorVersion < major) {
return false;
} else if (databaseMajorVersion == major && databaseMinorVersion < minor) {
return false;
}
return true;
}
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName()
{
return container.getName();
}
@Nullable
@Override
public String getDescription()
{
return container.getDescription();
}
@Override
public DBSObject getParentObject()
{
return container;
}
@Override
public boolean isPersisted()
{
return true;
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
this.dataSourceInfo = new JDBCDataSourceInfo(container);
return this;
}
@Nullable
@Override
public DBCQueryTransformer createQueryTransformer(@NotNull DBCQueryTransformType type)
{
// if (type == DBCQueryTransformType.ORDER_BY) {
//
// } else if (type == DBCQueryTransformType.FILTER) {
//
// }
return null;
}
private static int getValueTypeByTypeName(@NotNull String typeName, int valueType)
{
// [JDBC: SQLite driver uses VARCHAR value type for all LOBs]
if (valueType == Types.OTHER || valueType == Types.VARCHAR) {
if ("BLOB".equalsIgnoreCase(typeName)) {
return Types.BLOB;
} else if ("CLOB".equalsIgnoreCase(typeName)) {
return Types.CLOB;
} else if ("NCLOB".equalsIgnoreCase(typeName)) {
return Types.NCLOB;
}
} else if (valueType == Types.BIT) {
// Workaround for MySQL (and maybe others) when TINYINT(1) == BOOLEAN
if ("TINYINT".equalsIgnoreCase(typeName)) {
return Types.TINYINT;
}
}
return valueType;
}
@NotNull
public DBPDataKind resolveDataKind(@NotNull String typeName, int valueType)
{
return getDataKind(typeName, valueType);
}
@NotNull
public static DBPDataKind getDataKind(@NotNull String typeName, int valueType)
{
switch (getValueTypeByTypeName(typeName, valueType)) {
case Types.BOOLEAN:
return DBPDataKind.BOOLEAN;
case Types.CHAR:
case Types.VARCHAR:
case Types.NVARCHAR:
return DBPDataKind.STRING;
case Types.BIGINT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.INTEGER:
case Types.NUMERIC:
case Types.REAL:
case Types.SMALLINT:
return DBPDataKind.NUMERIC;
case Types.BIT:
case Types.TINYINT:
if (typeName.toLowerCase().contains("bool")) {
// Declared as numeric but actually it's a boolean
return DBPDataKind.BOOLEAN;
}
return DBPDataKind.NUMERIC;
case Types.DATE:
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
return DBPDataKind.DATETIME;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return DBPDataKind.BINARY;
case Types.BLOB:
case Types.CLOB:
case Types.NCLOB:
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
return DBPDataKind.CONTENT;
case Types.SQLXML:
return DBPDataKind.CONTENT;
case Types.STRUCT:
return DBPDataKind.STRUCT;
case Types.ARRAY:
return DBPDataKind.ARRAY;
case Types.ROWID:
return DBPDataKind.ROWID;
case Types.REF:
return DBPDataKind.REFERENCE;
case Types.OTHER:
// TODO: really?
return DBPDataKind.OBJECT;
}
return DBPDataKind.UNKNOWN;
}
@Nullable
@Override
public DBSDataType resolveDataType(@NotNull DBRProgressMonitor monitor, @NotNull String typeFullName) throws DBException
{
return getLocalDataType(typeFullName);
}
@Override
public String getDefaultDataTypeName(@NotNull DBPDataKind dataKind)
{
switch (dataKind) {
case BOOLEAN: return "BOOLEAN";
case NUMERIC: return "NUMERIC";
case STRING: return "VARCHAR";
case DATETIME: return "TIMESTAMP";
case BINARY: return "BLOB";
case CONTENT: return "BLOB";
case STRUCT: return "VARCHAR";
case ARRAY: return "VARCHAR";
case OBJECT: return "VARCHAR";
case REFERENCE: return "VARCHAR";
case ROWID: return "ROWID";
case ANY: return "VARCHAR";
default: return "VARCHAR";
}
}
/////////////////////////////////////////////////
// Overridable functions
protected boolean isConnectionReadOnlyBroken() {
return false;
}
protected String getConnectionUserName(@NotNull DBPConnectionConfiguration connectionInfo)
{
return connectionInfo.getUserName();
}
protected String getConnectionUserPassword(@NotNull DBPConnectionConfiguration connectionInfo)
{
return connectionInfo.getUserPassword();
}
@Nullable
protected Driver getDriverInstance(@NotNull DBRProgressMonitor monitor)
throws DBException
{
return Driver.class.cast(
container.getDriver().getDriverInstance(monitor));
}
/**
* Could be overridden by extenders. May contain any additional connection properties.
* Note: these properties may be overwritten by connection advanced properties.
* @return predefined connection properties
* @param monitor
* @param purpose
*/
@Nullable
protected Map<String, String> getInternalConnectionProperties(DBRProgressMonitor monitor, String purpose)
throws DBCException
{
return null;
}
protected DBPDataSourceInfo createDataSourceInfo(@NotNull JDBCDatabaseMetaData metaData)
{
return new JDBCDataSourceInfo(metaData);
}
protected SQLDialect createSQLDialect(@NotNull JDBCDatabaseMetaData metaData)
{
return new JDBCSQLDialect("JDBC", metaData);
}
@NotNull
protected JDBCFactory createJdbcFactory() {
return new JDBCFactoryDefault();
}
/////////////////////////////////////////////////
// Error assistance
@Override
public ErrorType discoverErrorType(@NotNull DBException error)
{
String sqlState = error.getDatabaseState();
if (SQLState.SQL_08000.getCode().equals(sqlState) ||
SQLState.SQL_08003.getCode().equals(sqlState) ||
SQLState.SQL_08006.getCode().equals(sqlState) ||
SQLState.SQL_08007.getCode().equals(sqlState) ||
SQLState.SQL_08S01.getCode().equals(sqlState))
{
return ErrorType.CONNECTION_LOST;
}
if (error instanceof DBCConnectException) {
Throwable rootCause = GeneralUtils.getRootCause(error);
if (rootCause instanceof ClassNotFoundException) {
// Looks like bad driver configuration
return ErrorType.DRIVER_CLASS_MISSING;
}
}
return ErrorType.NORMAL;
}
@Nullable
@Override
public ErrorPosition[] getErrorPosition(@NotNull DBCSession session, @NotNull String query, @NotNull Throwable error) {
return null;
}
@Override
public <T> T getAdapter(Class<T> adapter) {
if (adapter == DBCTransactionManager.class) {
return adapter.cast(executionContext);
}
return null;
}
/////////////////////////////////////////////////
// DBDPreferences
@Override
public DBDDataFormatterProfile getDataFormatterProfile() {
return container.getDataFormatterProfile();
}
@Override
public void setDataFormatterProfile(DBDDataFormatterProfile formatterProfile) {
container.setDataFormatterProfile(formatterProfile);
}
@NotNull
@Override
public DBDValueHandler getDefaultValueHandler() {
return JDBCObjectValueHandler.INSTANCE;
}
}
| #1247 Discover error type by original exception class
Former-commit-id: 0a88b2a1d7b31b188639212a962d29c09523ab3b | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/JDBCDataSource.java | #1247 Discover error type by original exception class | <ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/JDBCDataSource.java
<ide> import org.jkiss.utils.CommonUtils;
<ide>
<ide> import java.lang.reflect.InvocationTargetException;
<add>import java.net.SocketException;
<ide> import java.sql.*;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> {
<ide> return ErrorType.CONNECTION_LOST;
<ide> }
<add> if (GeneralUtils.getRootCause(error) instanceof SocketException) {
<add> return ErrorType.CONNECTION_LOST;
<add> }
<ide> if (error instanceof DBCConnectException) {
<ide> Throwable rootCause = GeneralUtils.getRootCause(error);
<ide> if (rootCause instanceof ClassNotFoundException) { |
|
Java | apache-2.0 | e6c4e2fad1378ec6eef76bc54b71af62f03885ca | 0 | bhecquet/seleniumRobot,bhecquet/seleniumRobot,bhecquet/seleniumRobot | /**
* Orignal work: Copyright 2015 www.seleniumtests.com
* Modified work: Copyright 2016 www.infotel.com
* Copyright 2017-2019 B.Hecquet
*
* 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.seleniumtests.it.driver;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import com.seleniumtests.customexception.ImageSearchException;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.it.driver.support.GenericMultiBrowserTest;
import com.seleniumtests.it.driver.support.pages.DriverTestPage;
import com.seleniumtests.it.driver.support.pages.DriverTestPageWithoutFixedPattern;
import com.seleniumtests.util.helper.WaitHelper;
public class TestPictureElement extends GenericMultiBrowserTest {
public TestPictureElement(WebDriver driver, DriverTestPage testPage) throws Exception {
super(driver, testPage);
}
public TestPictureElement(BrowserType browserType) throws Exception {
super(browserType, "DriverTestPageWithoutFixedPattern");
}
public TestPictureElement() throws Exception {
super(null, "DriverTestPageWithoutFixedPattern");
}
@AfterMethod(groups={"it"}, alwaysRun=true)
public void reset() {
if (driver != null) {
// driver.get(testPageUrl); // reload
try {
DriverTestPageWithoutFixedPattern.logoText.clear();
DriverTestPageWithoutFixedPattern.textElement.clear();
DriverTestPageWithoutFixedPattern.textElement.click(); // issue #408: this click is not necessary but it seems that it "resets" firefox javascript state
} catch (NoSuchElementException e) {
logger.error("Cannot reset");
logger.error(driver.getPageSource());
throw e;
}
}
}
public void testClickOnPicture() {
try {
DriverTestPageWithoutFixedPattern.picture.clickAt(0, -20);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "ff logo");
}
public void testDoubleClickOnPicture() {
try {
DriverTestPageWithoutFixedPattern.picture.doubleClickAt(0, -20);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "double click ff logo");
}
/**
* test correction of issue #131 by clicking on element which does not have a "intoElement" parameter
*/
public void testClickOnGooglePicture() {
try {
DriverTestPageWithoutFixedPattern.googlePicture.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.textElement.getValue(), "image");
}
/**
* test that an action changed actionDuration value
*/
public void testActionDurationIsLogged() {
// be sure action duration has been reset
DriverTestPageWithoutFixedPattern.googlePicture.setActionDuration(0);
try {
DriverTestPageWithoutFixedPattern.googlePicture.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
Assert.assertTrue(DriverTestPageWithoutFixedPattern.googlePicture.getActionDuration() > 0);
}
/**
* test correction of issue #134 by clicking on element defined by a File object
*/
public void testClickOnGooglePictureFromFile() {
try {
DriverTestPageWithoutFixedPattern.googlePictureWithFile.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.textElement.getValue(), "image");
}
public void testSendKeysOnPicture() {
try {
DriverTestPageWithoutFixedPattern.logoText.clear();
DriverTestPageWithoutFixedPattern.picture.sendKeys("hello", 0, 40);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "hello");
}
public void testIsVisible() {
Assert.assertTrue(DriverTestPageWithoutFixedPattern.picture.isElementPresent());
}
public void testIsNotVisible() {
Assert.assertFalse(DriverTestPageWithoutFixedPattern.pictureNotPresent.isElementPresent());
}
}
| core/src/test/java/com/seleniumtests/it/driver/TestPictureElement.java | /**
* Orignal work: Copyright 2015 www.seleniumtests.com
* Modified work: Copyright 2016 www.infotel.com
* Copyright 2017-2019 B.Hecquet
*
* 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.seleniumtests.it.driver;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import com.seleniumtests.customexception.ImageSearchException;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.it.driver.support.GenericMultiBrowserTest;
import com.seleniumtests.it.driver.support.pages.DriverTestPage;
import com.seleniumtests.it.driver.support.pages.DriverTestPageWithoutFixedPattern;
import com.seleniumtests.util.helper.WaitHelper;
public class TestPictureElement extends GenericMultiBrowserTest {
public TestPictureElement(WebDriver driver, DriverTestPage testPage) throws Exception {
super(driver, testPage);
}
public TestPictureElement(BrowserType browserType) throws Exception {
super(browserType, "DriverTestPageWithoutFixedPattern");
}
public TestPictureElement() throws Exception {
super(null, "DriverTestPageWithoutFixedPattern");
}
@AfterMethod(groups={"it"}, alwaysRun=true)
public void reset() {
if (driver != null) {
// driver.get(testPageUrl); // reload
try {
DriverTestPageWithoutFixedPattern.logoText.clear();
DriverTestPageWithoutFixedPattern.textElement.clear();
} catch (NoSuchElementException e) {
logger.error("Cannot reset");
logger.error(driver.getPageSource());
throw e;
}
}
}
public void testClickOnPicture() {
try {
DriverTestPageWithoutFixedPattern.picture.clickAt(0, -20);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "ff logo");
}
public void testDoubleClickOnPicture() {
try {
DriverTestPageWithoutFixedPattern.picture.doubleClickAt(0, -20);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "double click ff logo");
}
/**
* test correction of issue #131 by clicking on element which does not have a "intoElement" parameter
*/
public void testClickOnGooglePicture() {
try {
DriverTestPageWithoutFixedPattern.googlePicture.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.textElement.getValue(), "image");
}
/**
* test that an action changed actionDuration value
*/
public void testActionDurationIsLogged() {
// be sure action duration has been reset
DriverTestPageWithoutFixedPattern.googlePicture.setActionDuration(0);
try {
DriverTestPageWithoutFixedPattern.googlePicture.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
Assert.assertTrue(DriverTestPageWithoutFixedPattern.googlePicture.getActionDuration() > 0);
}
/**
* test correction of issue #134 by clicking on element defined by a File object
*/
public void testClickOnGooglePictureFromFile() {
try {
DriverTestPageWithoutFixedPattern.googlePictureWithFile.click();
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.textElement.getValue(), "image");
}
public void testSendKeysOnPicture() {
try {
DriverTestPageWithoutFixedPattern.logoText.clear();
DriverTestPageWithoutFixedPattern.picture.sendKeys("hello", 0, 40);
} catch (ImageSearchException e) {
throw new SkipException("Image not found, we may be on screenless slave", e);
}
WaitHelper.waitForMilliSeconds(500); // in case of browser slowness
Assert.assertEquals(DriverTestPageWithoutFixedPattern.logoText.getValue(), "hello");
}
public void testIsVisible() {
Assert.assertTrue(DriverTestPageWithoutFixedPattern.picture.isElementPresent());
}
public void testIsNotVisible() {
Assert.assertFalse(DriverTestPageWithoutFixedPattern.pictureNotPresent.isElementPresent());
}
}
| issue #408: try to correct test | core/src/test/java/com/seleniumtests/it/driver/TestPictureElement.java | issue #408: try to correct test | <ide><path>ore/src/test/java/com/seleniumtests/it/driver/TestPictureElement.java
<ide> import org.testng.Assert;
<ide> import org.testng.SkipException;
<ide> import org.testng.annotations.AfterMethod;
<del>import org.testng.annotations.Test;
<ide>
<ide> import com.seleniumtests.customexception.ImageSearchException;
<ide> import com.seleniumtests.driver.BrowserType;
<ide> try {
<ide> DriverTestPageWithoutFixedPattern.logoText.clear();
<ide> DriverTestPageWithoutFixedPattern.textElement.clear();
<add> DriverTestPageWithoutFixedPattern.textElement.click(); // issue #408: this click is not necessary but it seems that it "resets" firefox javascript state
<ide> } catch (NoSuchElementException e) {
<ide> logger.error("Cannot reset");
<ide> logger.error(driver.getPageSource()); |
|
Java | apache-2.0 | c737c2fd23fef4fa3e0e5390b70f956f88baae6b | 0 | ahb0327/intellij-community,da1z/intellij-community,asedunov/intellij-community,retomerz/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,da1z/intellij-community,fitermay/intellij-community,caot/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,kool79/intellij-community,hurricup/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,vladmm/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,signed/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,caot/intellij-community,izonder/intellij-community,kool79/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,allotria/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,izonder/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,samthor/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,da1z/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,amith01994/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,samthor/intellij-community,caot/intellij-community,samthor/intellij-community,da1z/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,asedunov/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,kdwink/intellij-community,fnouama/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,slisson/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,izonder/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,FHannes/intellij-community,semonte/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,amith01994/intellij-community,hurricup/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,clumsy/intellij-community,xfournet/intellij-community,blademainer/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,allotria/intellij-community,fnouama/intellij-community,vladmm/intellij-community,signed/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,samthor/intellij-community,jagguli/intellij-community,signed/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ibinti/intellij-community,asedunov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,caot/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fitermay/intellij-community,fnouama/intellij-community,kdwink/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,xfournet/intellij-community,FHannes/intellij-community,amith01994/intellij-community,xfournet/intellij-community,fitermay/intellij-community,signed/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,asedunov/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,signed/intellij-community,slisson/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,apixandru/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,blademainer/intellij-community,allotria/intellij-community,semonte/intellij-community,caot/intellij-community,ftomassetti/intellij-community,signed/intellij-community,supersven/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,amith01994/intellij-community,da1z/intellij-community,kdwink/intellij-community,samthor/intellij-community,semonte/intellij-community,samthor/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,samthor/intellij-community,apixandru/intellij-community,fitermay/intellij-community,samthor/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,kdwink/intellij-community,FHannes/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,supersven/intellij-community,allotria/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,izonder/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,blademainer/intellij-community,apixandru/intellij-community,supersven/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,kool79/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,slisson/intellij-community,hurricup/intellij-community,slisson/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,jagguli/intellij-community,caot/intellij-community,youdonghai/intellij-community,kool79/intellij-community,youdonghai/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,samthor/intellij-community,signed/intellij-community,amith01994/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,signed/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,izonder/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,FHannes/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,supersven/intellij-community,supersven/intellij-community,retomerz/intellij-community,clumsy/intellij-community,semonte/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,caot/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,kool79/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kool79/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,signed/intellij-community | /*
* Copyright 2000-2012 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: 17.11.2006
* Time: 17:08:11
*/
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.diff.*;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.merge.MergeRequest;
import com.intellij.diff.merge.MergeResult;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.DiffTool;
import com.intellij.openapi.diff.SimpleContent;
import com.intellij.openapi.diff.SimpleDiffRequest;
import com.intellij.openapi.diff.impl.patch.*;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatch;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.WindowWrapper;
import com.intellij.openapi.util.BooleanGetter;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsApplicationSettings;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.CommitContext;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class ApplyPatchAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.patch.ApplyPatchAction");
@Override
public void update(AnActionEvent e) {
Project project = e.getData(CommonDataKeys.PROJECT);
if (e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP)) {
VirtualFile vFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
e.getPresentation().setEnabledAndVisible(project != null && vFile != null && vFile.getFileType() == StdFileTypes.PATCH);
}
else {
e.getPresentation().setVisible(true);
e.getPresentation().setEnabled(project != null);
}
}
public void actionPerformed(AnActionEvent e) {
final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not apply patch now")) return;
FileDocumentManager.getInstance().saveAllDocuments();
if (e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP)) {
VirtualFile vFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
showApplyPatch(project, vFile);
}
else {
final FileChooserDescriptor descriptor = ApplyPatchDifferentiatedDialog.createSelectPatchDescriptor();
final VcsApplicationSettings settings = VcsApplicationSettings.getInstance();
final VirtualFile toSelect = settings.PATCH_STORAGE_LOCATION == null ? null :
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(settings.PATCH_STORAGE_LOCATION));
FileChooser.chooseFile(descriptor, project, toSelect, new Consumer<VirtualFile>() {
@Override
public void consume(VirtualFile file) {
final VirtualFile parent = file.getParent();
if (parent != null) {
settings.PATCH_STORAGE_LOCATION = FileUtil.toSystemDependentName(parent.getPath());
}
showApplyPatch(project, file);
}
});
}
}
private static void showApplyPatch(@NotNull final Project project, @NotNull final VirtualFile file) {
final ApplyPatchDifferentiatedDialog dialog = new ApplyPatchDifferentiatedDialog(
project, new ApplyPatchDefaultExecutor(project),
Collections.<ApplyPatchExecutor>singletonList(new ImportToShelfExecutor(project)), ApplyPatchMode.APPLY, file);
dialog.show();
}
public static void applySkipDirs(final List<FilePatch> patches, final int skipDirs) {
if (skipDirs < 1) {
return;
}
for (FilePatch patch : patches) {
patch.setBeforeName(skipN(patch.getBeforeName(), skipDirs));
patch.setAfterName(skipN(patch.getAfterName(), skipDirs));
}
}
private static String skipN(final String path, final int num) {
final String[] pieces = path.split("/");
final StringBuilder sb = new StringBuilder();
for (int i = num; i < pieces.length; i++) {
final String piece = pieces[i];
sb.append('/').append(piece);
}
return sb.toString();
}
@NotNull
public static ApplyPatchStatus applyOnly(@Nullable final Project project,
@NotNull final ApplyFilePatchBase patch,
@Nullable final ApplyPatchContext context,
@NotNull final VirtualFile file,
@Nullable final CommitContext commitContext,
boolean reverse,
@Nullable String leftPanelTitle,
@Nullable String rightPanelTitle) {
final ApplyFilePatch.Result result = tryApplyPatch(project, patch, context, file, commitContext);
final ApplyPatchStatus status = result.getStatus();
if (ApplyPatchStatus.ALREADY_APPLIED.equals(status) || ApplyPatchStatus.SUCCESS.equals(status)) {
return status;
}
final ApplyPatchForBaseRevisionTexts mergeData = result.getMergeData();
if (mergeData == null) return status;
if (mergeData.getBase() != null) {
return showMergeDialog(project, file, mergeData.getBase(), mergeData.getPatched(), reverse, leftPanelTitle, rightPanelTitle);
}
else {
return showBadDiffDialog(project, file, mergeData, false);
}
}
@NotNull
private static ApplyFilePatch.Result tryApplyPatch(@Nullable final Project project,
@NotNull final ApplyFilePatchBase patch,
@Nullable final ApplyPatchContext context,
@NotNull final VirtualFile file,
@Nullable final CommitContext commitContext) {
final FilePatch patchBase = patch.getPatch();
return ApplicationManager.getApplication().runWriteAction(
new Computable<ApplyFilePatch.Result>() {
@Override
public ApplyFilePatch.Result compute() {
try {
return patch.apply(file, context, project, VcsUtil.getFilePath(file), new Getter<CharSequence>() {
@Override
public CharSequence get() {
final BaseRevisionTextPatchEP baseRevisionTextPatchEP =
Extensions.findExtension(PatchEP.EP_NAME, project, BaseRevisionTextPatchEP.class);
final String path = ObjectUtils.chooseNotNull(patchBase.getBeforeName(), patchBase.getAfterName());
return baseRevisionTextPatchEP.provideContent(path, commitContext);
}
}, commitContext);
}
catch (IOException e) {
LOG.error(e);
return ApplyFilePatch.Result.createThrow(e);
}
}
});
}
@NotNull
private static ApplyPatchStatus showMergeDialog(@Nullable Project project,
@NotNull VirtualFile file,
@Nullable CharSequence content,
@NotNull final String patchedContent,
boolean reverse,
@Nullable String leftPanelTitle,
@Nullable String rightPanelTitle) {
Document document = FileDocumentManager.getInstance().getDocument(file);
if (content == null || document == null) {
return ApplyPatchStatus.FAILURE;
}
List<String> titles = ContainerUtil.list(
leftPanelTitle == null ? VcsBundle.message("patch.apply.conflict.local.version") : leftPanelTitle,
rightPanelTitle == null ? VcsBundle.message("patch.apply.conflict.merged.version") : rightPanelTitle,
VcsBundle.message("patch.apply.conflict.patched.version"));
String windowTitle = VcsBundle.message("patch.apply.conflict.title", file.getPresentableUrl());
final String leftText = document.getText();
List<String> contents = ContainerUtil.list(reverse ? patchedContent : leftText,
content.toString(),
reverse ? leftText : patchedContent);
final Ref<Boolean> successRef = new Ref<Boolean>();
final Consumer<MergeResult> callback = new Consumer<MergeResult>() {
@Override
public void consume(MergeResult result) {
successRef.set(result != MergeResult.CANCEL);
}
};
try {
MergeRequest request = DiffRequestFactory.getInstance()
.createMergeRequest(project, file.getFileType(), document, contents, windowTitle, titles, callback);
DiffManager.getInstance().showMerge(project, request);
return successRef.get() == Boolean.TRUE ? ApplyPatchStatus.SUCCESS : ApplyPatchStatus.FAILURE;
}
catch (InvalidDiffRequestException e) {
LOG.warn(e);
return ApplyPatchStatus.FAILURE;
}
}
@NotNull
private static ApplyPatchStatus showBadDiffDialog(@Nullable Project project,
@NotNull VirtualFile file,
@NotNull final ApplyPatchForBaseRevisionTexts texts,
boolean readonly) {
final Document document = FileDocumentManager.getInstance().getDocument(file);
if (texts.getLocal() == null || document == null) return ApplyPatchStatus.FAILURE;
final CharSequence oldContent = document.getImmutableCharSequence();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
document.setText(texts.getPatched());
}
});
final String fullPath = file.getParent() == null ? file.getPath() : file.getParent().getPath();
final String windowTitle = "Result Of Patch Apply To " + file.getName() + " (" + fullPath + ")";
final List<String> titles = ContainerUtil.list(VcsBundle.message("diff.title.local"), "Patched (with problems)");
final DiffContentFactory contentFactory = DiffContentFactory.getInstance();
final DocumentContent originalContent = contentFactory.create(texts.getLocal().toString(), file.getFileType());
final DiffContent mergedContent = contentFactory.create(project, document);
final List<DiffContent> contents = ContainerUtil.list(originalContent, mergedContent);
final DiffRequest request = new com.intellij.diff.requests.SimpleDiffRequest(windowTitle, contents, titles);
DiffUtil.addNotification(new DiffIsApproximateNotification(), request);
final DiffDialogHints dialogHints = new DiffDialogHints(WindowWrapper.Mode.MODAL);
if (!readonly) {
dialogHints.setCancelAction(new BooleanGetter() {
@Override
public boolean get() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
document.setText(oldContent);
FileDocumentManager.getInstance().saveDocument(document);
}
});
return true;
}
});
dialogHints.setOkAction(new BooleanGetter() {
@Override
public boolean get() {
FileDocumentManager.getInstance().saveDocument(document);
return true;
}
});
}
DiffManager.getInstance().showDiff(project, request, dialogHints);
return ApplyPatchStatus.SUCCESS;
}
@NotNull
public static SimpleDiffRequest createBadDiffRequest(@Nullable final Project project,
@NotNull final VirtualFile file,
@NotNull ApplyPatchForBaseRevisionTexts texts,
boolean readonly) {
final String fullPath = file.getParent() == null ? file.getPath() : file.getParent().getPath();
final String title = "Result Of Patch Apply To " + file.getName() + " (" + fullPath + ")";
final SimpleDiffRequest simpleRequest = new SimpleDiffRequest(project, title);
final DocumentImpl patched = new DocumentImpl(texts.getPatched());
patched.setReadOnly(false);
final com.intellij.openapi.diff.DocumentContent mergedContent =
new com.intellij.openapi.diff.DocumentContent(project, patched, file.getFileType());
mergedContent.getDocument().setReadOnly(readonly);
final SimpleContent originalContent = new SimpleContent(texts.getLocal().toString(), file.getFileType());
simpleRequest.setContents(originalContent, mergedContent);
simpleRequest.setContentTitles(VcsBundle.message("diff.title.local"), "Patched (with problems)");
simpleRequest.addHint(DiffTool.HINT_SHOW_MODAL_DIALOG);
simpleRequest.addHint(DiffTool.HINT_DIFF_IS_APPROXIMATE);
if (!readonly) {
simpleRequest.setOnOkRunnable(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final String resultText = mergedContent.getDocument().getText();
final Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) {
try {
VfsUtil.saveText(file, resultText);
}
catch (IOException e) {
// todo bad: we had already returned success by now
showIOException(project, file.getName(), e);
}
}
else {
document.setText(resultText);
FileDocumentManager.getInstance().saveDocument(document);
}
}
});
}
});
}
return simpleRequest;
}
private static void showIOException(@Nullable Project project, @NotNull String name, @NotNull IOException e) {
Messages.showErrorDialog(project,
VcsBundle.message("patch.apply.error", name, e.getMessage()),
VcsBundle.message("patch.apply.dialog.title"));
}
private static class DiffIsApproximateNotification extends EditorNotificationPanel {
public DiffIsApproximateNotification() {
myLabel.setText("<html>Couldn't find context for patch. Some fragments were applied at the best possible place. <b>Please check carefully.</b></html>");
}
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java | /*
* Copyright 2000-2012 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: 17.11.2006
* Time: 17:08:11
*/
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.diff.DiffRequestFactory;
import com.intellij.diff.InvalidDiffRequestException;
import com.intellij.diff.merge.MergeRequest;
import com.intellij.diff.merge.MergeResult;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.*;
import com.intellij.openapi.diff.impl.patch.*;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatch;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsApplicationSettings;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.CommitContext;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class ApplyPatchAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.patch.ApplyPatchAction");
@Override
public void update(AnActionEvent e) {
Project project = e.getData(CommonDataKeys.PROJECT);
if (e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP)) {
VirtualFile vFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
e.getPresentation().setEnabledAndVisible(project != null && vFile != null && vFile.getFileType() == StdFileTypes.PATCH);
}
else {
e.getPresentation().setVisible(true);
e.getPresentation().setEnabled(project != null);
}
}
public void actionPerformed(AnActionEvent e) {
final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
if (ChangeListManager.getInstance(project).isFreezedWithNotification("Can not apply patch now")) return;
FileDocumentManager.getInstance().saveAllDocuments();
if (e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP)) {
VirtualFile vFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
showApplyPatch(project, vFile);
}
else {
final FileChooserDescriptor descriptor = ApplyPatchDifferentiatedDialog.createSelectPatchDescriptor();
final VcsApplicationSettings settings = VcsApplicationSettings.getInstance();
final VirtualFile toSelect = settings.PATCH_STORAGE_LOCATION == null ? null :
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(settings.PATCH_STORAGE_LOCATION));
FileChooser.chooseFile(descriptor, project, toSelect, new Consumer<VirtualFile>() {
@Override
public void consume(VirtualFile file) {
final VirtualFile parent = file.getParent();
if (parent != null) {
settings.PATCH_STORAGE_LOCATION = FileUtil.toSystemDependentName(parent.getPath());
}
showApplyPatch(project, file);
}
});
}
}
private static void showApplyPatch(@NotNull final Project project, @NotNull final VirtualFile file) {
final ApplyPatchDifferentiatedDialog dialog = new ApplyPatchDifferentiatedDialog(
project, new ApplyPatchDefaultExecutor(project),
Collections.<ApplyPatchExecutor>singletonList(new ImportToShelfExecutor(project)), ApplyPatchMode.APPLY, file);
dialog.show();
}
public static void applySkipDirs(final List<FilePatch> patches, final int skipDirs) {
if (skipDirs < 1) {
return;
}
for (FilePatch patch : patches) {
patch.setBeforeName(skipN(patch.getBeforeName(), skipDirs));
patch.setAfterName(skipN(patch.getAfterName(), skipDirs));
}
}
private static String skipN(final String path, final int num) {
final String[] pieces = path.split("/");
final StringBuilder sb = new StringBuilder();
for (int i = num; i < pieces.length; i++) {
final String piece = pieces[i];
sb.append('/').append(piece);
}
return sb.toString();
}
@NotNull
public static ApplyPatchStatus applyOnly(@Nullable final Project project,
@NotNull final ApplyFilePatchBase patch,
@Nullable final ApplyPatchContext context,
@NotNull final VirtualFile file,
@Nullable final CommitContext commitContext,
boolean reverse,
@Nullable String leftPanelTitle,
@Nullable String rightPanelTitle) {
final ApplyFilePatch.Result result = tryApplyPatch(project, patch, context, file, commitContext);
final ApplyPatchStatus status = result.getStatus();
if (ApplyPatchStatus.ALREADY_APPLIED.equals(status) || ApplyPatchStatus.SUCCESS.equals(status)) {
return status;
}
final ApplyPatchForBaseRevisionTexts mergeData = result.getMergeData();
if (mergeData == null) return status;
if (mergeData.getBase() != null) {
return showMergeDialog(project, file, mergeData.getBase(), mergeData.getPatched(), reverse, leftPanelTitle, rightPanelTitle);
}
else {
return showBadDiffDialog(project, file, mergeData, false);
}
}
@NotNull
private static ApplyFilePatch.Result tryApplyPatch(@Nullable final Project project,
@NotNull final ApplyFilePatchBase patch,
@Nullable final ApplyPatchContext context,
@NotNull final VirtualFile file,
@Nullable final CommitContext commitContext) {
final FilePatch patchBase = patch.getPatch();
return ApplicationManager.getApplication().runWriteAction(
new Computable<ApplyFilePatch.Result>() {
@Override
public ApplyFilePatch.Result compute() {
try {
return patch.apply(file, context, project, VcsUtil.getFilePath(file), new Getter<CharSequence>() {
@Override
public CharSequence get() {
final BaseRevisionTextPatchEP baseRevisionTextPatchEP =
Extensions.findExtension(PatchEP.EP_NAME, project, BaseRevisionTextPatchEP.class);
final String path = ObjectUtils.chooseNotNull(patchBase.getBeforeName(), patchBase.getAfterName());
return baseRevisionTextPatchEP.provideContent(path, commitContext);
}
}, commitContext);
}
catch (IOException e) {
LOG.error(e);
return ApplyFilePatch.Result.createThrow(e);
}
}
});
}
@NotNull
private static ApplyPatchStatus showMergeDialog(@Nullable Project project,
@NotNull VirtualFile file,
@Nullable CharSequence content,
@NotNull final String patchedContent,
boolean reverse,
@Nullable String leftPanelTitle,
@Nullable String rightPanelTitle) {
Document document = FileDocumentManager.getInstance().getDocument(file);
if (content == null || document == null) {
return ApplyPatchStatus.FAILURE;
}
List<String> titles = ContainerUtil.list(
leftPanelTitle == null ? VcsBundle.message("patch.apply.conflict.local.version") : leftPanelTitle,
rightPanelTitle == null ? VcsBundle.message("patch.apply.conflict.merged.version") : rightPanelTitle,
VcsBundle.message("patch.apply.conflict.patched.version"));
String windowTitle = VcsBundle.message("patch.apply.conflict.title", file.getPresentableUrl());
final String leftText = document.getText();
List<String> contents = ContainerUtil.list(reverse ? patchedContent : leftText,
content.toString(),
reverse ? leftText : patchedContent);
final Ref<Boolean> successRef = new Ref<Boolean>();
final Consumer<MergeResult> callback = new Consumer<MergeResult>() {
@Override
public void consume(MergeResult result) {
successRef.set(result != MergeResult.CANCEL);
}
};
try {
MergeRequest request = DiffRequestFactory.getInstance()
.createMergeRequest(project, file.getFileType(), document, contents, windowTitle, titles, callback);
com.intellij.diff.DiffManager.getInstance().showMerge(project, request);
return successRef.get() == Boolean.TRUE ? ApplyPatchStatus.SUCCESS : ApplyPatchStatus.FAILURE;
}
catch (InvalidDiffRequestException e) {
LOG.warn(e);
return ApplyPatchStatus.FAILURE;
}
}
@NotNull
private static ApplyPatchStatus showBadDiffDialog(@Nullable Project project,
@NotNull VirtualFile file,
@NotNull ApplyPatchForBaseRevisionTexts texts,
boolean readonly) {
if (texts.getLocal() == null) return ApplyPatchStatus.FAILURE;
final SimpleDiffRequest simpleRequest = createBadDiffRequest(project, file, texts, readonly);
DiffManager.getInstance().getDiffTool().show(simpleRequest);
return ApplyPatchStatus.SUCCESS;
}
@NotNull
public static SimpleDiffRequest createBadDiffRequest(@Nullable final Project project,
@NotNull final VirtualFile file,
@NotNull ApplyPatchForBaseRevisionTexts texts,
boolean readonly) {
final String fullPath = file.getParent() == null ? file.getPath() : file.getParent().getPath();
final String title = "Result Of Patch Apply To " + file.getName() + " (" + fullPath + ")";
final SimpleDiffRequest simpleRequest = new SimpleDiffRequest(project, title);
final DocumentImpl patched = new DocumentImpl(texts.getPatched());
patched.setReadOnly(false);
final DocumentContent mergedContent = new DocumentContent(project, patched, file.getFileType());
mergedContent.getDocument().setReadOnly(readonly);
final SimpleContent originalContent = new SimpleContent(texts.getLocal().toString(), file.getFileType());
simpleRequest.setContents(originalContent, mergedContent);
simpleRequest.setContentTitles(VcsBundle.message("diff.title.local"), "Patched (with problems)");
simpleRequest.addHint(DiffTool.HINT_SHOW_MODAL_DIALOG);
simpleRequest.addHint(DiffTool.HINT_DIFF_IS_APPROXIMATE);
if (!readonly) {
simpleRequest.setOnOkRunnable(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
final String resultText = mergedContent.getDocument().getText();
final Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) {
try {
VfsUtil.saveText(file, resultText);
}
catch (IOException e) {
// todo bad: we had already returned success by now
showIOException(project, file.getName(), e);
}
}
else {
document.setText(resultText);
FileDocumentManager.getInstance().saveDocument(document);
}
}
});
}
});
}
return simpleRequest;
}
private static void showIOException(@Nullable Project project, @NotNull String name, @NotNull IOException e) {
Messages.showErrorDialog(project,
VcsBundle.message("patch.apply.error", name, e.getMessage()),
VcsBundle.message("patch.apply.dialog.title"));
}
}
| diff: use new API for failed apply patch with unknown base revision
| platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java | diff: use new API for failed apply patch with unknown base revision | <ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java
<ide> */
<ide> package com.intellij.openapi.vcs.changes.patch;
<ide>
<del>import com.intellij.diff.DiffRequestFactory;
<del>import com.intellij.diff.InvalidDiffRequestException;
<add>import com.intellij.diff.*;
<add>import com.intellij.diff.contents.DiffContent;
<add>import com.intellij.diff.contents.DocumentContent;
<ide> import com.intellij.diff.merge.MergeRequest;
<ide> import com.intellij.diff.merge.MergeResult;
<add>import com.intellij.diff.requests.DiffRequest;
<add>import com.intellij.diff.util.DiffUtil;
<ide> import com.intellij.openapi.actionSystem.ActionPlaces;
<ide> import com.intellij.openapi.actionSystem.AnActionEvent;
<ide> import com.intellij.openapi.actionSystem.CommonDataKeys;
<ide> import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.diagnostic.Logger;
<del>import com.intellij.openapi.diff.*;
<add>import com.intellij.openapi.diff.DiffTool;
<add>import com.intellij.openapi.diff.SimpleContent;
<add>import com.intellij.openapi.diff.SimpleDiffRequest;
<ide> import com.intellij.openapi.diff.impl.patch.*;
<ide> import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatch;
<ide> import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
<ide> import com.intellij.openapi.fileChooser.FileChooser;
<ide> import com.intellij.openapi.fileChooser.FileChooserDescriptor;
<ide> import com.intellij.openapi.fileEditor.FileDocumentManager;
<del>import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
<ide> import com.intellij.openapi.fileTypes.StdFileTypes;
<ide> import com.intellij.openapi.project.DumbAwareAction;
<ide> import com.intellij.openapi.project.Project;
<ide> import com.intellij.openapi.ui.Messages;
<add>import com.intellij.openapi.ui.WindowWrapper;
<add>import com.intellij.openapi.util.BooleanGetter;
<ide> import com.intellij.openapi.util.Computable;
<ide> import com.intellij.openapi.util.Getter;
<ide> import com.intellij.openapi.util.Ref;
<ide> import com.intellij.openapi.vfs.LocalFileSystem;
<ide> import com.intellij.openapi.vfs.VfsUtil;
<ide> import com.intellij.openapi.vfs.VirtualFile;
<add>import com.intellij.ui.EditorNotificationPanel;
<ide> import com.intellij.util.Consumer;
<ide> import com.intellij.util.ObjectUtils;
<ide> import com.intellij.util.containers.ContainerUtil;
<ide> MergeRequest request = DiffRequestFactory.getInstance()
<ide> .createMergeRequest(project, file.getFileType(), document, contents, windowTitle, titles, callback);
<ide>
<del> com.intellij.diff.DiffManager.getInstance().showMerge(project, request);
<add> DiffManager.getInstance().showMerge(project, request);
<ide>
<ide> return successRef.get() == Boolean.TRUE ? ApplyPatchStatus.SUCCESS : ApplyPatchStatus.FAILURE;
<ide> }
<ide> @NotNull
<ide> private static ApplyPatchStatus showBadDiffDialog(@Nullable Project project,
<ide> @NotNull VirtualFile file,
<del> @NotNull ApplyPatchForBaseRevisionTexts texts,
<add> @NotNull final ApplyPatchForBaseRevisionTexts texts,
<ide> boolean readonly) {
<del> if (texts.getLocal() == null) return ApplyPatchStatus.FAILURE;
<del>
<del> final SimpleDiffRequest simpleRequest = createBadDiffRequest(project, file, texts, readonly);
<del> DiffManager.getInstance().getDiffTool().show(simpleRequest);
<add> final Document document = FileDocumentManager.getInstance().getDocument(file);
<add> if (texts.getLocal() == null || document == null) return ApplyPatchStatus.FAILURE;
<add>
<add> final CharSequence oldContent = document.getImmutableCharSequence();
<add> ApplicationManager.getApplication().runWriteAction(new Runnable() {
<add> @Override
<add> public void run() {
<add> document.setText(texts.getPatched());
<add> }
<add> });
<add>
<add> final String fullPath = file.getParent() == null ? file.getPath() : file.getParent().getPath();
<add> final String windowTitle = "Result Of Patch Apply To " + file.getName() + " (" + fullPath + ")";
<add> final List<String> titles = ContainerUtil.list(VcsBundle.message("diff.title.local"), "Patched (with problems)");
<add>
<add> final DiffContentFactory contentFactory = DiffContentFactory.getInstance();
<add> final DocumentContent originalContent = contentFactory.create(texts.getLocal().toString(), file.getFileType());
<add> final DiffContent mergedContent = contentFactory.create(project, document);
<add>
<add> final List<DiffContent> contents = ContainerUtil.list(originalContent, mergedContent);
<add>
<add> final DiffRequest request = new com.intellij.diff.requests.SimpleDiffRequest(windowTitle, contents, titles);
<add> DiffUtil.addNotification(new DiffIsApproximateNotification(), request);
<add>
<add> final DiffDialogHints dialogHints = new DiffDialogHints(WindowWrapper.Mode.MODAL);
<add> if (!readonly) {
<add> dialogHints.setCancelAction(new BooleanGetter() {
<add> @Override
<add> public boolean get() {
<add> ApplicationManager.getApplication().runWriteAction(new Runnable() {
<add> @Override
<add> public void run() {
<add> document.setText(oldContent);
<add> FileDocumentManager.getInstance().saveDocument(document);
<add> }
<add> });
<add> return true;
<add> }
<add> });
<add> dialogHints.setOkAction(new BooleanGetter() {
<add> @Override
<add> public boolean get() {
<add> FileDocumentManager.getInstance().saveDocument(document);
<add> return true;
<add> }
<add> });
<add> }
<add>
<add> DiffManager.getInstance().showDiff(project, request, dialogHints);
<ide>
<ide> return ApplyPatchStatus.SUCCESS;
<ide> }
<ide> final DocumentImpl patched = new DocumentImpl(texts.getPatched());
<ide> patched.setReadOnly(false);
<ide>
<del> final DocumentContent mergedContent = new DocumentContent(project, patched, file.getFileType());
<add> final com.intellij.openapi.diff.DocumentContent mergedContent =
<add> new com.intellij.openapi.diff.DocumentContent(project, patched, file.getFileType());
<ide> mergedContent.getDocument().setReadOnly(readonly);
<ide> final SimpleContent originalContent = new SimpleContent(texts.getLocal().toString(), file.getFileType());
<ide>
<ide> VcsBundle.message("patch.apply.error", name, e.getMessage()),
<ide> VcsBundle.message("patch.apply.dialog.title"));
<ide> }
<add>
<add> private static class DiffIsApproximateNotification extends EditorNotificationPanel {
<add> public DiffIsApproximateNotification() {
<add> myLabel.setText("<html>Couldn't find context for patch. Some fragments were applied at the best possible place. <b>Please check carefully.</b></html>");
<add> }
<add> }
<ide> } |
|
JavaScript | mit | e697566cbb2af43f4075d0ab92bc1e5835375ca0 | 0 | kevinclement/SimpleArmory,kevinclement/SimpleArmory,kevinclement/SimpleArmory | var Achievements =
{
"supercats": [
{
"name": "Dungeons & Raids",
"cats": [
{
"name": "Dungeons & Raids",
"zones": [
{
"name": "Dungeons & Raids",
"achs": [
{
"id": "4476",
"icon": "Achievement_Arena_2v2_3",
"side": "",
"obtainable": true
},
{
"id": "4477",
"icon": "Achievement_Arena_3v3_4",
"side": "",
"obtainable": true
},
{
"id": "4478",
"icon": "Achievement_Arena_5v5_3",
"side": "",
"obtainable": true
},
{
"id": "5535",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5536",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5537",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5538",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "6924",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pandaria",
"achs": [
{
"id": "6925",
"icon": "inv_helmet_181v4",
"side": "",
"obtainable": true
},
{
"id": "6926",
"icon": "spell_shadow_shadowembrace",
"side": "",
"obtainable": true
},
{
"id": "6927",
"icon": "inv_helmet_mail_panda_b_01",
"side": "",
"obtainable": true
},
{
"id": "6932",
"icon": "inv_helmet_189",
"side": "",
"obtainable": true
},
{
"id": "8124",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8454",
"icon": "inv_axe_60",
"side": "",
"obtainable": true
}
]
},
{
"name": "Cataclysm",
"achs": [
{
"id": "4844",
"icon": "inv_helm_plate_twilighthammer_c_01",
"side": "",
"obtainable": true
},
{
"id": "5506",
"icon": "achievement_zone_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "4845",
"icon": "inv_helm_plate_pvpdeathknight_c_01",
"side": "",
"obtainable": true
},
{
"id": "4853",
"icon": "inv_helmet_100",
"side": "",
"obtainable": true
},
{
"id": "5828",
"icon": "inv_mace_1h_sulfuron_d_01",
"side": "",
"obtainable": true
},
{
"id": "6169",
"icon": "inv_misc_demonsoul",
"side": "",
"obtainable": true
}
]
},
{
"name": "Wrath of the Lich King",
"achs": [
{
"id": "1288",
"icon": "Spell_Holy_ChampionsBond",
"side": "",
"obtainable": true
},
{
"id": "1289",
"icon": "Ability_Rogue_FeignDeath",
"side": "",
"obtainable": true
},
{
"id": "1658",
"icon": "Spell_Frost_ChillingArmor",
"side": "",
"obtainable": true
},
{
"id": "2136",
"icon": "INV_Helmet_25",
"side": "",
"obtainable": true
},
{
"id": "2137",
"icon": "INV_Helmet_22",
"side": "",
"obtainable": true
},
{
"id": "2138",
"icon": "INV_Helmet_06",
"side": "",
"obtainable": true
},
{
"id": "2957",
"icon": "INV_Helmet_19",
"side": "",
"obtainable": true
},
{
"id": "2958",
"icon": "INV_Helmet_122",
"side": "",
"obtainable": true
},
{
"id": "4602",
"icon": "INV_Helmet_74",
"side": "",
"obtainable": true
},
{
"id": "4603",
"icon": "inv_helmet_151",
"side": "",
"obtainable": true
},
{
"id": "4016",
"icon": "Spell_Nature_ElementalPrecision_2",
"side": "",
"obtainable": true
},
{
"id": "4017",
"icon": "Spell_Nature_ElementalPrecision_2",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Burning Crusade",
"achs": [
{
"id": "1284",
"icon": "Spell_Holy_SummonChampion",
"side": "",
"obtainable": true
},
{
"id": "1287",
"icon": "Ability_Creature_Cursed_02",
"side": "",
"obtainable": true
},
{
"id": "1286",
"icon": "INV_Helmet_90",
"side": "",
"obtainable": true
}
]
},
{
"name": "Classic",
"achs": [
{
"id": "1283",
"icon": "Spell_Holy_ReviveChampion",
"side": "",
"obtainable": true
},
{
"id": "1285",
"icon": "INV_Helmet_74",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria Dungeon",
"zones": [
{
"name": "Gate of the Setting Sun",
"achs": [
{
"id": "6476",
"icon": "ability_rogue_deviouspoisons",
"side": "",
"obtainable": true
},
{
"id": "6479",
"icon": "inv_misc_bomb_04",
"side": "",
"obtainable": true
},
{
"id": "6945",
"icon": "spell_nature_insectswarm",
"side": "",
"obtainable": true
},
{
"id": "6759",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mogu'shan Palace",
"achs": [
{
"id": "6755",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
},
{
"id": "6478",
"icon": "spell_shadow_improvedvampiricembrace",
"side": "",
"obtainable": true
},
{
"id": "6713",
"icon": "inv_misc_gem_emeraldrough_02",
"side": "",
"obtainable": true
},
{
"id": "6736",
"icon": "inv_misc_enggizmos_27",
"side": "",
"obtainable": true
},
{
"id": "6756",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Halls",
"achs": [
{
"id": "6684",
"icon": "achievement_halloween_smiley_01",
"side": "",
"obtainable": true
},
{
"id": "6427",
"icon": "spell_impending_victory",
"side": "",
"obtainable": true
},
{
"id": "6760",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Monastery",
"achs": [
{
"id": "6946",
"icon": "spell_shadow_soulleech_3",
"side": "",
"obtainable": true
},
{
"id": "6928",
"icon": "spell_burningsoul",
"side": "",
"obtainable": true
},
{
"id": "6929",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6761",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scholomance",
"achs": [
{
"id": "6394",
"icon": "trade_archaeology_rustedsteakknife",
"side": "",
"obtainable": true
},
{
"id": "6396",
"icon": "spell_deathknight_bloodboil",
"side": "",
"obtainable": true
},
{
"id": "6531",
"icon": "achievement_character_undead_female",
"side": "",
"obtainable": true
},
{
"id": "6715",
"icon": "inv_potion_97",
"side": "",
"obtainable": true
},
{
"id": "6821",
"icon": "spell_holy_turnundead",
"side": "",
"obtainable": true
},
{
"id": "6762",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan Monastery",
"achs": [
{
"id": "6469",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6471",
"icon": "achievement_shadowpan_hideout_3",
"side": "",
"obtainable": true
},
{
"id": "6472",
"icon": "achievement_shadowpan_hideout_2",
"side": "",
"obtainable": true
},
{
"id": "6477",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "6470",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Siege of Niuzao Temple",
"achs": [
{
"id": "6485",
"icon": "inv_misc_bomb_02",
"side": "",
"obtainable": true
},
{
"id": "6688",
"icon": "spell_nature_shamanrage",
"side": "",
"obtainable": true
},
{
"id": "6822",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "6763",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
}
]
},
{
"name": "Stormstout Brewery",
"achs": [
{
"id": "6457",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6089",
"icon": "achievement_brewery_2",
"side": "",
"obtainable": true
},
{
"id": "6400",
"icon": "achievement_brewery_4",
"side": "",
"obtainable": true
},
{
"id": "6402",
"icon": "achievement_brewery_1",
"side": "",
"obtainable": true
},
{
"id": "6420",
"icon": "achievement_brewery_3",
"side": "",
"obtainable": true
},
{
"id": "6456",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
}
]
},
{
"name": "Temple of the Jade Serpent",
"achs": [
{
"id": "6757",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6460",
"icon": "spell_frost_summonwaterelemental",
"side": "",
"obtainable": true
},
{
"id": "6475",
"icon": "achievement_jadeserpent_1",
"side": "",
"obtainable": true
},
{
"id": "6671",
"icon": "spell_shadow_seedofdestruction",
"side": "",
"obtainable": true
},
{
"id": "6758",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria Raid",
"zones": [
{
"name": "Mogu'shan Vaults",
"achs": [
{
"id": "6458",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "6844",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "6823",
"icon": "ability_hunter_beasttraining",
"side": "",
"obtainable": true
},
{
"id": "6674",
"icon": "thumbsup",
"side": "",
"obtainable": true
},
{
"id": "7056",
"icon": "trade_archaeology_silverscrollcase",
"side": "",
"obtainable": true
},
{
"id": "6687",
"icon": "thumbsup",
"side": "",
"obtainable": true
},
{
"id": "7933",
"icon": "spell_holy_circleofrenewal",
"side": "",
"obtainable": true
},
{
"id": "6686",
"icon": "ability_deathknight_pillaroffrost",
"side": "",
"obtainable": true
},
{
"id": "6455",
"icon": "ability_rogue_shadowstrikes",
"side": "",
"obtainable": true
},
{
"id": "6719",
"icon": "achievement_moguraid_01",
"side": "",
"obtainable": true
},
{
"id": "6720",
"icon": "achievement_moguraid_02",
"side": "",
"obtainable": true
},
{
"id": "6721",
"icon": "achievement_raid_mantidraid05",
"side": "",
"obtainable": true
},
{
"id": "6722",
"icon": "achievement_moguraid_04",
"side": "",
"obtainable": true
},
{
"id": "6723",
"icon": "achievement_moguraid_05",
"side": "",
"obtainable": true
},
{
"id": "6724",
"icon": "achievement_moguraid_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Heart of Fear",
"achs": [
{
"id": "6718",
"icon": "achievement_raid_mantidraid01",
"side": "",
"obtainable": true
},
{
"id": "6845",
"icon": "achievement_raid_mantidraid01",
"side": "",
"obtainable": true
},
{
"id": "6937",
"icon": "inv_misc_archaeology_amburfly",
"side": "",
"obtainable": true
},
{
"id": "6936",
"icon": "trade_archaeology_candlestub",
"side": "",
"obtainable": true
},
{
"id": "6553",
"icon": "inv_misc_ammo_arrow_05",
"side": "",
"obtainable": true
},
{
"id": "6683",
"icon": "spell_brokenheart",
"side": "",
"obtainable": true
},
{
"id": "6518",
"icon": "spell_yorsahj_bloodboil_yellow",
"side": "",
"obtainable": true
},
{
"id": "6922",
"icon": "spell_holy_borrowedtime",
"side": "",
"obtainable": true
},
{
"id": "6725",
"icon": "achievement_raid_mantidraid02",
"side": "",
"obtainable": true
},
{
"id": "6726",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "6727",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "6728",
"icon": "achievement_raid_mantidraid04",
"side": "",
"obtainable": true
},
{
"id": "6729",
"icon": "achievement_raid_mantidraid06",
"side": "",
"obtainable": true
},
{
"id": "6730",
"icon": "achievement_raid_mantidraid07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Terrace of Endless Spring",
"achs": [
{
"id": "6689",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
},
{
"id": "6717",
"icon": "ability_rogue_envelopingshadows",
"side": "",
"obtainable": true
},
{
"id": "6933",
"icon": "trade_herbalism",
"side": "",
"obtainable": true
},
{
"id": "6824",
"icon": "spell_shadow_coneofsilence",
"side": "",
"obtainable": true
},
{
"id": "6825",
"icon": "spell_arcane_mindmastery",
"side": "",
"obtainable": true
},
{
"id": "6731",
"icon": "achievement_raid_terraceofendlessspring01",
"side": "",
"obtainable": true
},
{
"id": "6732",
"icon": "achievement_raid_terraceofendlessspring02",
"side": "",
"obtainable": true
},
{
"id": "6733",
"icon": "achievement_raid_terraceofendlessspring03",
"side": "",
"obtainable": true
},
{
"id": "6734",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
}
]
},
{
"name": "Throne of Thunder",
"achs": [
{
"id": "8069",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8070",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8071",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8072",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8094",
"icon": "ability_vehicle_electrocharge",
"side": "",
"obtainable": true
},
{
"id": "8038",
"icon": "trade_archaeology_dinosaurskeleton",
"side": "",
"obtainable": true
},
{
"id": "8073",
"icon": "inv_pet_magicalcradadbox",
"side": "",
"obtainable": true
},
{
"id": "8077",
"icon": "achievement_boss_tortos",
"side": "",
"obtainable": true
},
{
"id": "8082",
"icon": "inv_misc_head_dragon_01",
"side": "",
"obtainable": true
},
{
"id": "8097",
"icon": "inv_misc_football",
"side": "",
"obtainable": true
},
{
"id": "8098",
"icon": "spell_nature_elementalprecision_1",
"side": "",
"obtainable": true
},
{
"id": "8037",
"icon": "ability_deathknight_roilingblood",
"side": "",
"obtainable": true
},
{
"id": "8081",
"icon": "ability_touchofanimus",
"side": "",
"obtainable": true
},
{
"id": "8087",
"icon": "thumbup",
"side": "",
"obtainable": true
},
{
"id": "8086",
"icon": "spell_holy_pureofheart",
"side": "",
"obtainable": true
},
{
"id": "8090",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "8056",
"icon": "achievement_boss_jinrokhthebreaker",
"side": "",
"obtainable": true
},
{
"id": "8057",
"icon": "achievement_boss_horridon",
"side": "",
"obtainable": true
},
{
"id": "8058",
"icon": "achievement_boss_councilofelders",
"side": "",
"obtainable": true
},
{
"id": "8059",
"icon": "achievement_boss_tortos",
"side": "",
"obtainable": true
},
{
"id": "8060",
"icon": "achievement_boss_megaera",
"side": "",
"obtainable": true
},
{
"id": "8061",
"icon": "achievement_boss_ji-kun",
"side": "",
"obtainable": true
},
{
"id": "8062",
"icon": "achievement_boss_durumu",
"side": "",
"obtainable": true
},
{
"id": "8063",
"icon": "achievement_boss_primordius",
"side": "",
"obtainable": true
},
{
"id": "8065",
"icon": "achievement_boss_iron_qon",
"side": "",
"obtainable": true
},
{
"id": "8066",
"icon": "achievement_boss_mogufemales",
"side": "",
"obtainable": true
},
{
"id": "8067",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8068",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
},
{
"id": "8064",
"icon": "achievement_boss_darkanimus",
"side": "",
"obtainable": true
}
]
},
{
"name": "Siege of Orgrimmar",
"achs": [
{
"id": "8458",
"icon": "achievement_raid_soo_ruined_vale",
"side": "",
"obtainable": true
},
{
"id": "8459",
"icon": "achievement_raid_soo_orgrimmar_outdoors",
"side": "",
"obtainable": true
},
{
"id": "8461",
"icon": "achievement_raid_soo_garrosh_compound_half1",
"side": "",
"obtainable": true
},
{
"id": "8462",
"icon": "achievement_raid_soo_garrosh_compound_half2",
"side": "",
"obtainable": true
},
{
"id": "8536",
"icon": "spell_frost_summonwaterelemental_2",
"side": "",
"obtainable": true
},
{
"id": "8528",
"icon": "ability_fixated_state_red",
"side": "",
"obtainable": true
},
{
"id": "8532",
"icon": "spell_holy_surgeoflight",
"side": "",
"obtainable": true
},
{
"id": "8521",
"icon": "sha_ability_rogue_bloodyeye",
"side": "",
"obtainable": true
},
{
"id": "8530",
"icon": "achievement_bg_3flagcap_nodeaths",
"side": "",
"obtainable": true
},
{
"id": "8520",
"icon": "inv_misc_enggizmos_38",
"side": "",
"obtainable": true
},
{
"id": "8453",
"icon": "ability_paladin_blessedhands",
"side": "",
"obtainable": true
},
{
"id": "8448",
"icon": "achievement_character_tauren_male",
"side": "",
"obtainable": true
},
{
"id": "8538",
"icon": "sha_spell_warlock_demonsoul",
"side": "",
"obtainable": true
},
{
"id": "8529",
"icon": "inv_crate_04",
"side": "",
"obtainable": true
},
{
"id": "8527",
"icon": "inv_misc_shell_04",
"side": "",
"obtainable": true
},
{
"id": "8543",
"icon": "ability_siege_engineer_sockwave_missile",
"side": "",
"obtainable": true
},
{
"id": "8531",
"icon": "achievement_boss_klaxxi_paragons",
"side": "",
"obtainable": true
},
{
"id": "8537",
"icon": "ability_garrosh_siege_engine",
"side": "",
"obtainable": true
},
{
"id": "8679",
"icon": "ability_garrosh_hellscreams_warsong",
"side": "A",
"obtainable": true
},
{
"id": "8680",
"icon": "ability_garrosh_hellscreams_warsong",
"side": "H",
"obtainable": true
},
{
"id": "8463",
"icon": "achievement_boss_immerseus",
"side": "",
"obtainable": true
},
{
"id": "8465",
"icon": "achievement_boss_golden_lotus_council",
"side": "",
"obtainable": true
},
{
"id": "8466",
"icon": "achievement_boss_norushen",
"side": "",
"obtainable": true
},
{
"id": "8467",
"icon": "sha_inv_misc_slime_01",
"side": "",
"obtainable": true
},
{
"id": "8468",
"icon": "achievement_boss_galakras",
"side": "",
"obtainable": true
},
{
"id": "8469",
"icon": "achievement_boss_ironjuggernaut",
"side": "",
"obtainable": true
},
{
"id": "8470",
"icon": "achievement_boss_korkrondarkshaman",
"side": "",
"obtainable": true
},
{
"id": "8471",
"icon": "achievement_boss_general_nazgrim",
"side": "",
"obtainable": true
},
{
"id": "8472",
"icon": "achievement_boss_malkorok",
"side": "",
"obtainable": true
},
{
"id": "8478",
"icon": "achievement_boss_spoils_of_pandaria",
"side": "",
"obtainable": true
},
{
"id": "8479",
"icon": "achievement_boss_thokthebloodthirsty",
"side": "",
"obtainable": true
},
{
"id": "8480",
"icon": "achievement_boss_siegecrafter_blackfuse",
"side": "",
"obtainable": true
},
{
"id": "8481",
"icon": "achievement_boss_klaxxi_paragons",
"side": "",
"obtainable": true
},
{
"id": "8482",
"icon": "achievement_boss_garrosh",
"side": "",
"obtainable": true
}
]
},
{
"name": "Timeless Isle",
"achs": [
{
"id": "8535",
"icon": "inv_pa_celestialmallet",
"side": "",
"obtainable": true
}
]
},
{
"name": "World",
"achs": [
{
"id": "6480",
"icon": "spell_misc_emotionangry",
"side": "",
"obtainable": true
},
{
"id": "6517",
"icon": "spell_fire_meteorstorm",
"side": "",
"obtainable": true
},
{
"id": "8123",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
},
{
"id": "8028",
"icon": "spell_holy_lightsgrace",
"side": "",
"obtainable": true
},
{
"id": "8533",
"icon": "inv_axe_1h_firelandsraid_d_02",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Dungeon Challenges",
"zones": [
{
"name": "Dungeon Challenges",
"achs": [
{
"id": "6920",
"icon": "achievement_guildperk_honorablemention",
"side": "",
"obtainable": true
},
{
"id": "6374",
"icon": "achievement_challengemode_bronze",
"side": "",
"obtainable": true
},
{
"id": "6375",
"icon": "achievement_challengemode_silver",
"side": "",
"obtainable": true
},
{
"id": "6378",
"icon": "achievement_challengemode_gold",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gate of the Setting Sun",
"achs": [
{
"id": "6894",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6905",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6906",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6907",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mogu'shan Palace",
"achs": [
{
"id": "6892",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6899",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6900",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6901",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Halls",
"achs": [
{
"id": "6895",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6908",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6909",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6910",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Monastery",
"achs": [
{
"id": "6896",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6911",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6912",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6913",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scholomance",
"achs": [
{
"id": "6897",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6914",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6915",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6916",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan Monastery",
"achs": [
{
"id": "6893",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6902",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6903",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6904",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Siege of Niuzao Temple",
"achs": [
{
"id": "6898",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6917",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6918",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6919",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
}
]
},
{
"name": "Stormstout Brewery",
"achs": [
{
"id": "6888",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6889",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6890",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6891",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
}
]
},
{
"name": "Temple of the Jade Serpent",
"achs": [
{
"id": "6884",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6885",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6886",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6887",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm Dungeon",
"zones": [
{
"name": "Blackrock Caverns",
"achs": [
{
"id": "4833",
"icon": "achievement_dungeon_blackrockcaverns",
"side": "",
"obtainable": true
},
{
"id": "5281",
"icon": "achievement_dungeon_blackrockcaverns_romogg-bonecrusher",
"side": "",
"obtainable": true
},
{
"id": "5282",
"icon": "achievement_dungeon_blackrockcaverns_corla-herald-of-twilight",
"side": "",
"obtainable": true
},
{
"id": "5283",
"icon": "achievement_dungeon_blackrockcaverns_karshsteelbender",
"side": "",
"obtainable": true
},
{
"id": "5284",
"icon": "achievement_dungeon_blackrockcaverns_ascendantlordobsidius",
"side": "",
"obtainable": true
},
{
"id": "5060",
"icon": "achievement_dungeon_blackrockcaverns",
"side": "",
"obtainable": true
}
]
},
{
"name": "Throne of the Tides",
"achs": [
{
"id": "4839",
"icon": "achievement_dungeon_throne-of-the-tides",
"side": "",
"obtainable": true
},
{
"id": "5285",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "5286",
"icon": "achievement_dungeon_throne-of-the-tides_ozumat",
"side": "",
"obtainable": true
},
{
"id": "5061",
"icon": "achievement_dungeon_throne-of-the-tides",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Stonecore",
"achs": [
{
"id": "4846",
"icon": "achievement_dungeon_deepholm",
"side": "",
"obtainable": true
},
{
"id": "5287",
"icon": "Ability_Warlock_MoltenCore",
"side": "",
"obtainable": true
},
{
"id": "5063",
"icon": "achievement_dungeon_deepholm",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Vortex Pinnacle",
"achs": [
{
"id": "4847",
"icon": "achievement_dungeon_skywall",
"side": "",
"obtainable": true
},
{
"id": "5289",
"icon": "Spell_Frost_WindWalkOn",
"side": "",
"obtainable": true
},
{
"id": "5288",
"icon": "achievement_dungeon_thevortexpinnacle_asaad",
"side": "",
"obtainable": true
},
{
"id": "5064",
"icon": "achievement_dungeon_skywall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Grim Batol",
"achs": [
{
"id": "4840",
"icon": "achievement_dungeon_grimbatol",
"side": "",
"obtainable": true
},
{
"id": "5297",
"icon": "achievement_dungeon_grimbatol_general-umbriss",
"side": "",
"obtainable": true
},
{
"id": "5298",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "",
"obtainable": true
},
{
"id": "5062",
"icon": "achievement_dungeon_grimbatol",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Origination",
"achs": [
{
"id": "4841",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "5293",
"icon": "Spell_Holy_DivineHymn",
"side": "",
"obtainable": true
},
{
"id": "5294",
"icon": "ability_mount_camel_tan",
"side": "",
"obtainable": true
},
{
"id": "5296",
"icon": "INV_Misc_PocketWatch_01",
"side": "",
"obtainable": true
},
{
"id": "5295",
"icon": "achievement_dungeon_halls-of-origination_rajh",
"side": "",
"obtainable": true
},
{
"id": "5065",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lost City of the Tol'vir",
"achs": [
{
"id": "4848",
"icon": "achievement_dungeon_lostcity-of-tolvir",
"side": "",
"obtainable": true
},
{
"id": "5290",
"icon": "INV_Misc_FireDancer_01",
"side": "",
"obtainable": true
},
{
"id": "5291",
"icon": "Ability_Hunter_Pet_Crocolisk",
"side": "",
"obtainable": true
},
{
"id": "5292",
"icon": "Ability_Mage_NetherWindPresence",
"side": "",
"obtainable": true
},
{
"id": "5066",
"icon": "achievement_dungeon_lostcity-of-tolvir",
"side": "",
"obtainable": true
}
]
},
{
"name": "Deadmines",
"achs": [
{
"id": "5366",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
},
{
"id": "5367",
"icon": "inv_misc_food_100_hardcheese",
"side": "",
"obtainable": true
},
{
"id": "5368",
"icon": "INV_Gizmo_GoblingTonkController",
"side": "",
"obtainable": true
},
{
"id": "5369",
"icon": "Spell_DeathKnight_PathOfFrost",
"side": "",
"obtainable": true
},
{
"id": "5370",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "5371",
"icon": "Achievement_Boss_EdwinVancleef",
"side": "",
"obtainable": true
},
{
"id": "5083",
"icon": "INV_Misc_Bandana_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "Hour of Twilight",
"achs": [
{
"id": "6132",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "6119",
"icon": "achievment_raid_houroftwilight",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shadowfang Keep",
"achs": [
{
"id": "5503",
"icon": "Ability_Rogue_StayofExecution",
"side": "",
"obtainable": true
},
{
"id": "5504",
"icon": "Spell_Holy_SealOfBlood",
"side": "",
"obtainable": true
},
{
"id": "5505",
"icon": "INV_Misc_Ammo_Bullet_05",
"side": "",
"obtainable": true
},
{
"id": "5093",
"icon": "inv_helm_robe_dungeonrobe_c_04",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zul'Aman",
"achs": [
{
"id": "5761",
"icon": "Spell_Shaman_Hex",
"side": "",
"obtainable": true
},
{
"id": "5750",
"icon": "Spell_Totem_WardOfDraining",
"side": "",
"obtainable": true
},
{
"id": "5858",
"icon": "inv_misc_bearcubbrown",
"side": "",
"obtainable": true
},
{
"id": "5760",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "5769",
"icon": "achievement_zul_aman_daakara",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zul'Gurub",
"achs": [
{
"id": "5744",
"icon": "INV_Spear_02",
"side": "",
"obtainable": true
},
{
"id": "5743",
"icon": "Ability_Creature_Poison_06",
"side": "",
"obtainable": true
},
{
"id": "5762",
"icon": "ability_mount_fossilizedraptor",
"side": "",
"obtainable": true
},
{
"id": "5765",
"icon": "achievement_rat",
"side": "",
"obtainable": true
},
{
"id": "5759",
"icon": "Ability_Creature_Cursed_05",
"side": "",
"obtainable": true
},
{
"id": "5768",
"icon": "achievement_zulgurub_jindo",
"side": "",
"obtainable": true
}
]
},
{
"name": "End Time",
"achs": [
{
"id": "6130",
"icon": "Achievement_Leader_Sylvanas",
"side": "",
"obtainable": true
},
{
"id": "5995",
"icon": "Ability_UpgradeMoonGlaive",
"side": "",
"obtainable": true
},
{
"id": "6117",
"icon": "achievement_boss_infinitecorruptor",
"side": "",
"obtainable": true
}
]
},
{
"name": "Well of Eternity",
"achs": [
{
"id": "6127",
"icon": "inv_misc_eye_02",
"side": "",
"obtainable": true
},
{
"id": "6070",
"icon": "Spell_Misc_EmotionAngry",
"side": "",
"obtainable": true
},
{
"id": "6118",
"icon": "achievment_boss_wellofeternity",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm Raid",
"zones": [
{
"name": "The Bastion of Twilight",
"achs": [
{
"id": "5300",
"icon": "INV_Misc_Crop_01",
"side": "",
"obtainable": true
},
{
"id": "4852",
"icon": "achievement_dungeon_bastion-of-twilight_valiona-theralion",
"side": "",
"obtainable": true
},
{
"id": "5311",
"icon": "achievement_dungeon_bastion-of-twilight_twilightascendantcouncil",
"side": "",
"obtainable": true
},
{
"id": "5312",
"icon": "spell_shadow_mindflay",
"side": "",
"obtainable": true
},
{
"id": "4850",
"icon": "spell_fire_twilightcano",
"side": "",
"obtainable": true
},
{
"id": "5118",
"icon": "achievement_dungeon_bastion-of-twilight_halfus-wyrmbreaker",
"side": "",
"obtainable": true
},
{
"id": "5117",
"icon": "achievement_dungeon_bastion-of-twilight_valiona-theralion",
"side": "",
"obtainable": true
},
{
"id": "5119",
"icon": "achievement_dungeon_bastion-of-twilight_twilightascendantcouncil",
"side": "",
"obtainable": true
},
{
"id": "5120",
"icon": "achievement_dungeon_bastion-of-twilight_chogall-boss",
"side": "",
"obtainable": true
},
{
"id": "5121",
"icon": "achievement_dungeon_bastion-of-twilight_ladysinestra",
"side": "",
"obtainable": true
},
{
"id": "5313",
"icon": "achievement_dungeon_bastion-of-twilight_ladysinestra",
"side": "",
"obtainable": false
}
]
},
{
"name": "Throne of the Four Winds",
"achs": [
{
"id": "5304",
"icon": "Spell_DeathKnight_FrostFever",
"side": "",
"obtainable": true
},
{
"id": "5305",
"icon": "Spell_Shaman_StaticShock",
"side": "",
"obtainable": true
},
{
"id": "4851",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "5122",
"icon": "Ability_Druid_GaleWinds",
"side": "",
"obtainable": true
},
{
"id": "5123",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
}
]
},
{
"name": "Blackwing Descent",
"achs": [
{
"id": "5306",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "5307",
"icon": "achievement_dungeon_blackwingdescent_darkironcouncil",
"side": "",
"obtainable": true
},
{
"id": "5310",
"icon": "ability_racial_aberration",
"side": "",
"obtainable": true
},
{
"id": "5308",
"icon": "INV_Misc_Bell_01",
"side": "",
"obtainable": true
},
{
"id": "5309",
"icon": "warrior_talent_icon_furyintheblood",
"side": "",
"obtainable": true
},
{
"id": "4849",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4842",
"icon": "Achievement_Boss_Nefarion",
"side": "",
"obtainable": true
},
{
"id": "5094",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "5107",
"icon": "achievement_dungeon_blackwingdescent_darkironcouncil",
"side": "",
"obtainable": true
},
{
"id": "5108",
"icon": "achievement_dungeon_blackwingdescent_raid_maloriak",
"side": "",
"obtainable": true
},
{
"id": "5109",
"icon": "achievement_dungeon_blackwingdescent_raid_atramedes",
"side": "",
"obtainable": true
},
{
"id": "5115",
"icon": "achievement_dungeon_blackwingdescent_raid_chimaron",
"side": "",
"obtainable": true
},
{
"id": "5116",
"icon": "achievement_dungeon_blackwingdescent_raid_nefarian",
"side": "",
"obtainable": true
}
]
},
{
"name": "Firelands",
"achs": [
{
"id": "5829",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5810",
"icon": "misc_arrowright",
"side": "",
"obtainable": true
},
{
"id": "5821",
"icon": "INV_Misc_Head_Nerubian_01",
"side": "",
"obtainable": true
},
{
"id": "5813",
"icon": "spell_magic_polymorphrabbit",
"side": "",
"obtainable": true
},
{
"id": "5830",
"icon": "Spell_Shadow_PainAndSuffering",
"side": "",
"obtainable": true
},
{
"id": "5799",
"icon": "achievement_firelands-raid_fandral-staghelm",
"side": "",
"obtainable": true
},
{
"id": "5855",
"icon": "achievement_firelands-raid_ragnaros",
"side": "",
"obtainable": true
},
{
"id": "5802",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5806",
"icon": "achievement_boss_shannox",
"side": "",
"obtainable": true
},
{
"id": "5808",
"icon": "achievement_boss_lordanthricyst",
"side": "",
"obtainable": true
},
{
"id": "5807",
"icon": "achievement_boss_broodmotheraranae",
"side": "",
"obtainable": true
},
{
"id": "5809",
"icon": "achievement_firelands-raid_alysra",
"side": "",
"obtainable": true
},
{
"id": "5805",
"icon": "achievement_firelandsraid_balorocthegatekeeper",
"side": "",
"obtainable": true
},
{
"id": "5804",
"icon": "achievement_firelands-raid_fandral-staghelm",
"side": "",
"obtainable": true
},
{
"id": "5803",
"icon": "achievement_firelands-raid_ragnaros",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dragon Soul",
"achs": [
{
"id": "6106",
"icon": "Achievement_Reputation_WyrmrestTemple",
"side": "",
"obtainable": true
},
{
"id": "6107",
"icon": "achievment_boss_madnessofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6174",
"icon": "Spell_Nature_MassTeleport",
"side": "",
"obtainable": true
},
{
"id": "6128",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "6129",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "6175",
"icon": "achievement_general_dungeondiplomat",
"side": "",
"obtainable": true
},
{
"id": "6084",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6105",
"icon": "spell_fire_twilightpyroblast",
"side": "",
"obtainable": true
},
{
"id": "6133",
"icon": "achievment_boss_spineofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6177",
"icon": "ability_deathwing_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "6180",
"icon": "inv_dragonchromaticmount",
"side": "",
"obtainable": true
},
{
"id": "6109",
"icon": "achievment_boss_morchok",
"side": "",
"obtainable": true
},
{
"id": "6110",
"icon": "achievment_boss_zonozz",
"side": "",
"obtainable": true
},
{
"id": "6111",
"icon": "achievment_boss_yorsahj",
"side": "",
"obtainable": true
},
{
"id": "6112",
"icon": "achievment_boss_hagara",
"side": "",
"obtainable": true
},
{
"id": "6113",
"icon": "achievment_boss_ultraxion",
"side": "",
"obtainable": true
},
{
"id": "6114",
"icon": "achievment_boss_blackhorn",
"side": "",
"obtainable": true
},
{
"id": "6115",
"icon": "achievment_boss_spineofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6116",
"icon": "achievment_boss_madnessofdeathwing",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lich King Dungeon",
"zones": [
{
"name": "Utgarde Keep",
"achs": [
{
"id": "477",
"icon": "Achievement_Dungeon_UtgardeKeep_Normal",
"side": "",
"obtainable": true
},
{
"id": "1919",
"icon": "Ability_Mage_ColdAsIce",
"side": "",
"obtainable": true
},
{
"id": "489",
"icon": "Achievement_Dungeon_UtgardeKeep_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Nexus",
"achs": [
{
"id": "478",
"icon": "Achievement_Dungeon_Nexus70_Normal",
"side": "",
"obtainable": true
},
{
"id": "2150",
"icon": "Achievement_Dungeon_Nexus70_25man",
"side": "",
"obtainable": true
},
{
"id": "2037",
"icon": "Achievement_Dungeon_Nexus70_25man",
"side": "",
"obtainable": true
},
{
"id": "2036",
"icon": "Ability_Mage_ChilledToTheBone",
"side": "",
"obtainable": true
},
{
"id": "490",
"icon": "Achievement_Dungeon_Nexus70_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Azjol-Nerub",
"achs": [
{
"id": "480",
"icon": "Achievement_Dungeon_AzjolUppercity_Normal",
"side": "",
"obtainable": true
},
{
"id": "1296",
"icon": "Achievement_Dungeon_AzjolUppercity_25man",
"side": "",
"obtainable": true
},
{
"id": "1297",
"icon": "Achievement_Dungeon_AzjolUppercity_10man",
"side": "",
"obtainable": true
},
{
"id": "1860",
"icon": "Achievement_Dungeon_AzjolUppercity",
"side": "",
"obtainable": true
},
{
"id": "491",
"icon": "Achievement_Dungeon_AzjolUppercity_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ahn'kahet: The Old Kingdom",
"achs": [
{
"id": "481",
"icon": "Achievement_Dungeon_AzjolLowercity_Normal",
"side": "",
"obtainable": true
},
{
"id": "2038",
"icon": "INV_Misc_Head_Nerubian_01",
"side": "",
"obtainable": true
},
{
"id": "2056",
"icon": "Achievement_Character_Orc_Female",
"side": "",
"obtainable": true
},
{
"id": "1862",
"icon": "Achievement_Dungeon_AzjolLowercity_25man",
"side": "",
"obtainable": true
},
{
"id": "492",
"icon": "Achievement_Dungeon_AzjolLowercity_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Drak'Tharon Keep",
"achs": [
{
"id": "482",
"icon": "Achievement_Dungeon_Drak'Tharon_Normal",
"side": "",
"obtainable": true
},
{
"id": "2151",
"icon": "Achievement_Dungeon_Drak'Tharon_25man",
"side": "",
"obtainable": true
},
{
"id": "2057",
"icon": "Spell_DeathKnight_ArmyOfTheDead",
"side": "",
"obtainable": true
},
{
"id": "2039",
"icon": "Ability_Hunter_Pet_Devilsaur",
"side": "",
"obtainable": true
},
{
"id": "493",
"icon": "Achievement_Dungeon_Drak'Tharon_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Violet Hold",
"achs": [
{
"id": "483",
"icon": "Achievement_Dungeon_TheVioletHold_Normal",
"side": "",
"obtainable": true
},
{
"id": "2153",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "2041",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "1816",
"icon": "Achievement_Dungeon_TheVioletHold_25man",
"side": "",
"obtainable": true
},
{
"id": "1865",
"icon": "Achievement_Dungeon_TheVioletHold_10man",
"side": "",
"obtainable": true
},
{
"id": "494",
"icon": "Achievement_Dungeon_TheVioletHold_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gundrak",
"achs": [
{
"id": "484",
"icon": "Achievement_Dungeon_Gundrak_Normal",
"side": "",
"obtainable": true
},
{
"id": "2040",
"icon": "INV_Misc_MonsterHorn_04",
"side": "",
"obtainable": true
},
{
"id": "2058",
"icon": "Ability_Hunter_CobraStrikes",
"side": "",
"obtainable": true
},
{
"id": "1864",
"icon": "Achievement_Dungeon_Gundrak_25man",
"side": "",
"obtainable": true
},
{
"id": "2152",
"icon": "Ability_Mount_KotoBrewfest",
"side": "",
"obtainable": true
},
{
"id": "495",
"icon": "Achievement_Dungeon_Gundrak_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Stone",
"achs": [
{
"id": "485",
"icon": "Achievement_Dungeon_Ulduar77_Normal",
"side": "",
"obtainable": true
},
{
"id": "1866",
"icon": "Achievement_Dungeon_Ulduar77_10man",
"side": "",
"obtainable": true
},
{
"id": "2154",
"icon": "Achievement_Character_Dwarf_Male",
"side": "",
"obtainable": true
},
{
"id": "2155",
"icon": "INV_Misc_Slime_01",
"side": "",
"obtainable": true
},
{
"id": "496",
"icon": "Achievement_Dungeon_Ulduar77_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Culling of Stratholme",
"achs": [
{
"id": "479",
"icon": "Achievement_Dungeon_CoTStratholme_Normal",
"side": "",
"obtainable": true
},
{
"id": "1872",
"icon": "Spell_DeathKnight_Explode_Ghoul",
"side": "",
"obtainable": true
},
{
"id": "1817",
"icon": "Achievement_Dungeon_CoTStratholme_25man",
"side": "",
"obtainable": true
},
{
"id": "500",
"icon": "Achievement_Dungeon_CoTStratholme_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Oculus",
"achs": [
{
"id": "487",
"icon": "Achievement_Dungeon_Nexus80_Normal",
"side": "",
"obtainable": true
},
{
"id": "1871",
"icon": "Achievement_Dungeon_Nexus80_10man",
"side": "",
"obtainable": true
},
{
"id": "2046",
"icon": "Ability_Mount_Drake_Bronze",
"side": "",
"obtainable": true
},
{
"id": "2045",
"icon": "Ability_Mount_Drake_Blue",
"side": "",
"obtainable": true
},
{
"id": "2044",
"icon": "Ability_Mount_Drake_Red",
"side": "",
"obtainable": true
},
{
"id": "1868",
"icon": "Achievement_Dungeon_Nexus80_25man",
"side": "",
"obtainable": true
},
{
"id": "498",
"icon": "Achievement_Dungeon_Nexus80_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Lightning",
"achs": [
{
"id": "486",
"icon": "Achievement_Dungeon_Ulduar80_Normal",
"side": "",
"obtainable": true
},
{
"id": "1834",
"icon": "Achievement_Dungeon_Ulduar80_Heroic",
"side": "",
"obtainable": true
},
{
"id": "2042",
"icon": "Spell_Fire_Incinerate",
"side": "",
"obtainable": true
},
{
"id": "1867",
"icon": "Achievement_Dungeon_Ulduar80_25man",
"side": "",
"obtainable": true
},
{
"id": "497",
"icon": "Achievement_Dungeon_Ulduar80_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Utgarde Pinnacle",
"achs": [
{
"id": "488",
"icon": "Achievement_Dungeon_UtgardePinnacle_Normal",
"side": "",
"obtainable": true
},
{
"id": "2043",
"icon": "Spell_Shadow_SummonInfernal",
"side": "",
"obtainable": true
},
{
"id": "1873",
"icon": "Achievement_Dungeon_UtgardePinnacle_10man",
"side": "",
"obtainable": true
},
{
"id": "2156",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_01",
"side": "",
"obtainable": true
},
{
"id": "2157",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_03",
"side": "",
"obtainable": true
},
{
"id": "499",
"icon": "Achievement_Dungeon_UtgardePinnacle_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Trial of the Champion",
"achs": [
{
"id": "3778",
"icon": "INV_Spear_05",
"side": "H",
"obtainable": true
},
{
"id": "4296",
"icon": "INV_Spear_05",
"side": "A",
"obtainable": true
},
{
"id": "3802",
"icon": "INV_Helmet_52",
"side": "",
"obtainable": true
},
{
"id": "3803",
"icon": "Ability_ThunderClap",
"side": "",
"obtainable": true
},
{
"id": "3804",
"icon": "INV_Helmet_23",
"side": "",
"obtainable": true
},
{
"id": "4297",
"icon": "INV_Spear_05",
"side": "H",
"obtainable": true
},
{
"id": "4298",
"icon": "INV_Spear_05",
"side": "A",
"obtainable": true
}
]
},
{
"name": "The Forge of Souls",
"achs": [
{
"id": "4516",
"icon": "achievement_dungeon_icecrown_forgeofsouls",
"side": "",
"obtainable": true
},
{
"id": "4522",
"icon": "achievement_boss_bronjahm",
"side": "",
"obtainable": true
},
{
"id": "4523",
"icon": "achievement_boss_devourerofsouls",
"side": "",
"obtainable": true
},
{
"id": "4519",
"icon": "achievement_dungeon_icecrown_forgeofsouls",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pit of Saron",
"achs": [
{
"id": "4517",
"icon": "achievement_dungeon_icecrown_pitofsaron",
"side": "",
"obtainable": true
},
{
"id": "4524",
"icon": "achievement_boss_forgemaster",
"side": "",
"obtainable": true
},
{
"id": "4525",
"icon": "achievement_boss_scourgelordtyrannus",
"side": "",
"obtainable": true
},
{
"id": "4520",
"icon": "achievement_dungeon_icecrown_pitofsaron",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Reflection",
"achs": [
{
"id": "4518",
"icon": "achievement_dungeon_icecrown_hallsofreflection",
"side": "",
"obtainable": true
},
{
"id": "4526",
"icon": "achievement_boss_lichking",
"side": "",
"obtainable": true
},
{
"id": "4521",
"icon": "achievement_dungeon_icecrown_hallsofreflection",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lich King Raid",
"zones": [
{
"name": "Naxxramas (10 player)",
"achs": [
{
"id": "1858",
"icon": "Achievement_Halloween_Spider_01",
"side": "",
"obtainable": true
},
{
"id": "1997",
"icon": "Spell_Shadow_CurseOfMannoroth",
"side": "",
"obtainable": true
},
{
"id": "562",
"icon": "INV_Trinket_Naxxramas04",
"side": "",
"obtainable": true
},
{
"id": "1996",
"icon": "Ability_Rogue_QuickRecovery",
"side": "",
"obtainable": true
},
{
"id": "2182",
"icon": "INV_Misc_Herb_Ragveil",
"side": "",
"obtainable": true
},
{
"id": "566",
"icon": "INV_Misc_Cauldron_Nature",
"side": "",
"obtainable": true
},
{
"id": "1856",
"icon": "Spell_Shadow_AbominationExplosion",
"side": "",
"obtainable": true
},
{
"id": "2178",
"icon": "Spell_ChargePositive",
"side": "",
"obtainable": true
},
{
"id": "2180",
"icon": "Spell_ChargeNegative",
"side": "",
"obtainable": true
},
{
"id": "564",
"icon": "Ability_Rogue_DeviousPoisons",
"side": "",
"obtainable": true
},
{
"id": "2176",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "568",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "2146",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "572",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "2184",
"icon": "Spell_Deathknight_PlagueStrike",
"side": "",
"obtainable": true
},
{
"id": "574",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "576",
"icon": "Achievement_Dungeon_Naxxramas_Normal",
"side": "",
"obtainable": true
},
{
"id": "578",
"icon": "Spell_Shadow_RaiseDead",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Obsidian Sanctum (10 player)",
"achs": [
{
"id": "1876",
"icon": "Achievement_Dungeon_CoABlackDragonflight",
"side": "",
"obtainable": true
},
{
"id": "2047",
"icon": "Spell_Shaman_LavaFlow",
"side": "",
"obtainable": true
},
{
"id": "624",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Heroic",
"side": "",
"obtainable": true
},
{
"id": "2049",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2050",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2051",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Eye of Eternity (10 player)",
"achs": [
{
"id": "2148",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "622",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
},
{
"id": "1869",
"icon": "Achievement_Dungeon_NexusRaid_Heroic",
"side": "",
"obtainable": true
},
{
"id": "1874",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
}
]
},
{
"name": "Naxxramas (25 player)",
"achs": [
{
"id": "1859",
"icon": "Achievement_Halloween_Spider_01",
"side": "",
"obtainable": true
},
{
"id": "2140",
"icon": "Spell_Shadow_CurseOfMannoroth",
"side": "",
"obtainable": true
},
{
"id": "563",
"icon": "INV_Trinket_Naxxramas04",
"side": "",
"obtainable": true
},
{
"id": "2139",
"icon": "Ability_Rogue_QuickRecovery",
"side": "",
"obtainable": true
},
{
"id": "2183",
"icon": "INV_Misc_Herb_Ragveil",
"side": "",
"obtainable": true
},
{
"id": "567",
"icon": "INV_Misc_Cauldron_Nature",
"side": "",
"obtainable": true
},
{
"id": "1857",
"icon": "Spell_Shadow_PlagueCloud",
"side": "",
"obtainable": true
},
{
"id": "2179",
"icon": "Spell_ChargePositive",
"side": "",
"obtainable": true
},
{
"id": "2181",
"icon": "Spell_ChargeNegative",
"side": "",
"obtainable": true
},
{
"id": "565",
"icon": "Ability_Rogue_DeviousPoisons",
"side": "",
"obtainable": true
},
{
"id": "2177",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "569",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "2147",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "573",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "2185",
"icon": "Spell_Deathknight_PlagueStrike",
"side": "",
"obtainable": true
},
{
"id": "575",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "577",
"icon": "Achievement_Dungeon_Naxxramas_10man",
"side": "",
"obtainable": true
},
{
"id": "579",
"icon": "Spell_Shadow_RaiseDead",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Obsidian Sanctum (25 player)",
"achs": [
{
"id": "625",
"icon": "Achievement_Dungeon_CoABlackDragonflight_10man",
"side": "",
"obtainable": true
},
{
"id": "2048",
"icon": "Spell_Shaman_LavaFlow",
"side": "",
"obtainable": true
},
{
"id": "1877",
"icon": "Achievement_Dungeon_CoABlackDragonflight_25man",
"side": "",
"obtainable": true
},
{
"id": "2052",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2053",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2054",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Eye of Eternity (25 player)",
"achs": [
{
"id": "2149",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "623",
"icon": "Achievement_Dungeon_NexusRaid_10man",
"side": "",
"obtainable": true
},
{
"id": "1870",
"icon": "Achievement_Dungeon_NexusRaid_25man",
"side": "",
"obtainable": true
},
{
"id": "1875",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Secrets of Ulduar (10 player)",
"zones": [
{
"name": "The Siege of Ulduar (10 player)",
"achs": [
{
"id": "2909",
"icon": "Achievement_Boss_TheFlameLeviathan_01",
"side": "",
"obtainable": true
},
{
"id": "3097",
"icon": "ability_vehicle_liquidpyrite_blue",
"side": "",
"obtainable": true
},
{
"id": "2905",
"icon": "INV_Misc_Wrench_02",
"side": "",
"obtainable": true
},
{
"id": "2907",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "2911",
"icon": "INV_Misc_EngGizmos_02",
"side": "",
"obtainable": true
},
{
"id": "2913",
"icon": "INV_Misc_Orb_04",
"side": "",
"obtainable": true
},
{
"id": "2914",
"icon": "INV_Misc_Orb_03",
"side": "",
"obtainable": true
},
{
"id": "2915",
"icon": "INV_Misc_Orb_05",
"side": "",
"obtainable": true
},
{
"id": "3056",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "2925",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "2927",
"icon": "Spell_Fire_Immolation",
"side": "",
"obtainable": true
},
{
"id": "2930",
"icon": "Achievement_Boss_Ignis_01",
"side": "",
"obtainable": true
},
{
"id": "2923",
"icon": "Achievement_Dungeon_UlduarRaid_IronDwarf_01",
"side": "",
"obtainable": true
},
{
"id": "2919",
"icon": "Achievement_Boss_Razorscale",
"side": "",
"obtainable": true
},
{
"id": "2931",
"icon": "INV_Misc_EngGizmos_14",
"side": "",
"obtainable": true
},
{
"id": "3058",
"icon": "INV_ValentinesCardTornLeft",
"side": "",
"obtainable": true
},
{
"id": "2933",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2934",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2937",
"icon": "achievement_boss_xt002deconstructor_01",
"side": "",
"obtainable": true
},
{
"id": "2886",
"icon": "Achievement_Dungeon_UlduarRaid_Archway_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Antechamber of Ulduar (10 player)",
"achs": [
{
"id": "2939",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2940",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2941",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2945",
"icon": "INV_Drink_01",
"side": "",
"obtainable": true
},
{
"id": "2947",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2953",
"icon": "Ability_Warrior_Disarm",
"side": "",
"obtainable": true
},
{
"id": "2955",
"icon": "Spell_Fire_BlueFlameBolt",
"side": "",
"obtainable": true
},
{
"id": "2951",
"icon": "Achievement_Boss_Kologarn_01",
"side": "",
"obtainable": true
},
{
"id": "2959",
"icon": "INV_Elemental_Primal_Earth",
"side": "",
"obtainable": true
},
{
"id": "3076",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "3006",
"icon": "Achievement_Boss_Auriaya_01",
"side": "",
"obtainable": true
},
{
"id": "2888",
"icon": "Achievement_Boss_TribunalofAges",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Keepers of Ulduar (10 player)",
"achs": [
{
"id": "2989",
"icon": "Ability_Mage_MissileBarrage",
"side": "",
"obtainable": true
},
{
"id": "3180",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
},
{
"id": "3138",
"icon": "INV_Gizmo_RocketLauncher",
"side": "",
"obtainable": true
},
{
"id": "2979",
"icon": "Ability_Druid_ForceofNature",
"side": "",
"obtainable": true
},
{
"id": "2980",
"icon": "Ability_Druid_Flourish",
"side": "",
"obtainable": true
},
{
"id": "2982",
"icon": "Achievement_Boss_Freya_01",
"side": "",
"obtainable": true
},
{
"id": "2985",
"icon": "Spell_Nature_NatureTouchDecay",
"side": "",
"obtainable": true
},
{
"id": "3177",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3178",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3179",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "2971",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2973",
"icon": "Achievement_Dungeon_UlduarRaid_IronSentinel_01",
"side": "",
"obtainable": true
},
{
"id": "2975",
"icon": "Spell_Nature_WispSplode",
"side": "",
"obtainable": true
},
{
"id": "2977",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "3176",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "2961",
"icon": "Spell_Frost_FreezingBreath",
"side": "",
"obtainable": true
},
{
"id": "2963",
"icon": "Spell_Frost_ManaRecharge",
"side": "",
"obtainable": true
},
{
"id": "2967",
"icon": "Achievement_Boss_Hodir_01",
"side": "",
"obtainable": true
},
{
"id": "2969",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "3182",
"icon": "INV_Box_04",
"side": "",
"obtainable": true
},
{
"id": "2890",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Descent into Madness (10 player)",
"achs": [
{
"id": "2996",
"icon": "Spell_Shadow_PainSpike",
"side": "",
"obtainable": true
},
{
"id": "3181",
"icon": "Achievement_Boss_GeneralVezax_01",
"side": "",
"obtainable": true
},
{
"id": "3008",
"icon": "Spell_Shadow_MindRot",
"side": "",
"obtainable": true
},
{
"id": "3009",
"icon": "INV_ValentinesCard02",
"side": "",
"obtainable": true
},
{
"id": "3012",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3014",
"icon": "Achievement_Boss_HeraldVolazj",
"side": "",
"obtainable": true
},
{
"id": "3015",
"icon": "Spell_Shadow_Brainwash",
"side": "",
"obtainable": true
},
{
"id": "3157",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3141",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3158",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3159",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "2892",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ulduar (10 player)",
"achs": [
{
"id": "2894",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_01",
"side": "",
"obtainable": true
},
{
"id": "3036",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3003",
"icon": "Spell_Shadow_MindTwisting",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Secrets of Ulduar (25 player)",
"zones": [
{
"name": "The Siege of Ulduar (25 player)",
"achs": [
{
"id": "2910",
"icon": "INV_Misc_MissileSmall_Red",
"side": "",
"obtainable": true
},
{
"id": "3098",
"icon": "ability_vehicle_liquidpyrite_blue",
"side": "",
"obtainable": true
},
{
"id": "2906",
"icon": "INV_Misc_Wrench_02",
"side": "",
"obtainable": true
},
{
"id": "2908",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "2912",
"icon": "INV_Misc_EngGizmos_02",
"side": "",
"obtainable": true
},
{
"id": "2918",
"icon": "INV_Misc_Orb_04",
"side": "",
"obtainable": true
},
{
"id": "2916",
"icon": "INV_Misc_Orb_03",
"side": "",
"obtainable": true
},
{
"id": "2917",
"icon": "INV_Misc_Orb_05",
"side": "",
"obtainable": true
},
{
"id": "3057",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "2926",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "2928",
"icon": "Spell_Fire_Immolation",
"side": "",
"obtainable": true
},
{
"id": "2929",
"icon": "Achievement_Boss_Ignis_01",
"side": "",
"obtainable": true
},
{
"id": "2924",
"icon": "Achievement_Dungeon_UlduarRaid_IronDwarf_01",
"side": "",
"obtainable": true
},
{
"id": "2921",
"icon": "Achievement_Boss_Razorscale",
"side": "",
"obtainable": true
},
{
"id": "2932",
"icon": "INV_Misc_EngGizmos_14",
"side": "",
"obtainable": true
},
{
"id": "3059",
"icon": "INV_ValentinesCardTornLeft",
"side": "",
"obtainable": true
},
{
"id": "2935",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2936",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2938",
"icon": "achievement_boss_xt002deconstructor_01",
"side": "",
"obtainable": true
},
{
"id": "2887",
"icon": "Achievement_Dungeon_UlduarRaid_Archway_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Antechamber of Ulduar (25 player)",
"achs": [
{
"id": "2942",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2943",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2944",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2946",
"icon": "INV_Drink_01",
"side": "",
"obtainable": true
},
{
"id": "2948",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2954",
"icon": "Ability_Warrior_Disarm",
"side": "",
"obtainable": true
},
{
"id": "2956",
"icon": "Spell_Fire_BlueFlameBolt",
"side": "",
"obtainable": true
},
{
"id": "2952",
"icon": "Achievement_Boss_Kologarn_01",
"side": "",
"obtainable": true
},
{
"id": "2960",
"icon": "INV_Elemental_Primal_Earth",
"side": "",
"obtainable": true
},
{
"id": "3077",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "3007",
"icon": "Achievement_Boss_Auriaya_01",
"side": "",
"obtainable": true
},
{
"id": "2889",
"icon": "Achievement_Boss_TribunalofAges",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Keepers of Ulduar (25 player)",
"achs": [
{
"id": "3237",
"icon": "Ability_Mage_MissileBarrage",
"side": "",
"obtainable": true
},
{
"id": "3189",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
},
{
"id": "2995",
"icon": "INV_Gizmo_RocketLauncher",
"side": "",
"obtainable": true
},
{
"id": "3118",
"icon": "Ability_Druid_ForceofNature",
"side": "",
"obtainable": true
},
{
"id": "2981",
"icon": "Ability_Druid_Flourish",
"side": "",
"obtainable": true
},
{
"id": "2983",
"icon": "Achievement_Boss_Freya_01",
"side": "",
"obtainable": true
},
{
"id": "2984",
"icon": "Spell_Nature_NatureTouchDecay",
"side": "",
"obtainable": true
},
{
"id": "3185",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3186",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3187",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "2972",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2974",
"icon": "Achievement_Dungeon_UlduarRaid_IronSentinel_01",
"side": "",
"obtainable": true
},
{
"id": "2976",
"icon": "Spell_Nature_WispSplode",
"side": "",
"obtainable": true
},
{
"id": "2978",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "3183",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "2962",
"icon": "Spell_Frost_FreezingBreath",
"side": "",
"obtainable": true
},
{
"id": "2965",
"icon": "Spell_Frost_ManaRecharge",
"side": "",
"obtainable": true
},
{
"id": "2968",
"icon": "Achievement_Boss_Hodir_01",
"side": "",
"obtainable": true
},
{
"id": "2970",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "3184",
"icon": "INV_Box_04",
"side": "",
"obtainable": true
},
{
"id": "2891",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Descent into Madness (25 player)",
"achs": [
{
"id": "2997",
"icon": "Spell_Shadow_PainSpike",
"side": "",
"obtainable": true
},
{
"id": "3188",
"icon": "Achievement_Boss_GeneralVezax_01",
"side": "",
"obtainable": true
},
{
"id": "3010",
"icon": "Spell_Shadow_MindRot",
"side": "",
"obtainable": true
},
{
"id": "3011",
"icon": "INV_ValentinesCard02",
"side": "",
"obtainable": true
},
{
"id": "3013",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3017",
"icon": "Achievement_Boss_HeraldVolazj",
"side": "",
"obtainable": true
},
{
"id": "3016",
"icon": "Spell_Shadow_Brainwash",
"side": "",
"obtainable": true
},
{
"id": "3161",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3162",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3163",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3164",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "2893",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ulduar (25 player)",
"achs": [
{
"id": "2895",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_01",
"side": "",
"obtainable": true
},
{
"id": "3037",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3002",
"icon": "Spell_Shadow_MindTwisting",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Call of the Crusade",
"zones": [
{
"name": "Trial of the Crusader (10 player)",
"achs": [
{
"id": "3936",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "3797",
"icon": "INV_Ammo_Snowball",
"side": "",
"obtainable": true
},
{
"id": "3996",
"icon": "Spell_Shadow_ShadowMend",
"side": "",
"obtainable": true
},
{
"id": "3798",
"icon": "Achievement_Arena_5v5_3",
"side": "",
"obtainable": true
},
{
"id": "3799",
"icon": "Achievement_Boss_SvalaSorrowgrave",
"side": "",
"obtainable": true
},
{
"id": "3800",
"icon": "Achievement_Boss_Anubarak",
"side": "",
"obtainable": true
},
{
"id": "3917",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3918",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
}
]
},
{
"name": "Trial of the Crusader (25 player)",
"achs": [
{
"id": "3937",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "3813",
"icon": "INV_Ammo_Snowball",
"side": "",
"obtainable": true
},
{
"id": "3997",
"icon": "Spell_Shadow_ShadowMend",
"side": "",
"obtainable": true
},
{
"id": "3815",
"icon": "Achievement_Boss_SvalaSorrowgrave",
"side": "",
"obtainable": true
},
{
"id": "3816",
"icon": "Achievement_Boss_Anubarak",
"side": "",
"obtainable": true
},
{
"id": "3916",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3812",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
}
]
},
{
"name": "Onyxia's Lair (10 player)",
"achs": [
{
"id": "4396",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4403",
"icon": "INV_Misc_Head_Dragon_Black",
"side": "",
"obtainable": true
},
{
"id": "4402",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "4404",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Onyxia's Lair (25 player)",
"achs": [
{
"id": "4397",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4406",
"icon": "INV_Misc_Head_Dragon_Black",
"side": "",
"obtainable": true
},
{
"id": "4405",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "4407",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Fall of the Lich King",
"zones": [
{
"name": "Icecrown Citadel (Normal) (10 player)",
"achs": [
{
"id": "4534",
"icon": "achievement_boss_lordmarrowgar",
"side": "",
"obtainable": true
},
{
"id": "4535",
"icon": "achievement_boss_ladydeathwhisper",
"side": "",
"obtainable": true
},
{
"id": "4536",
"icon": "achievement_dungeon_hordeairship",
"side": "",
"obtainable": true
},
{
"id": "4537",
"icon": "achievement_boss_saurfang",
"side": "",
"obtainable": true
},
{
"id": "4531",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4577",
"icon": "achievement_boss_festergutrotface",
"side": "",
"obtainable": true
},
{
"id": "4538",
"icon": "Spell_Nature_Acid_01",
"side": "",
"obtainable": true
},
{
"id": "4578",
"icon": "achievement_boss_profputricide",
"side": "",
"obtainable": true
},
{
"id": "4528",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4582",
"icon": "achievement_boss_princetaldaram",
"side": "",
"obtainable": true
},
{
"id": "4539",
"icon": "achievement_boss_lanathel",
"side": "",
"obtainable": true
},
{
"id": "4529",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4579",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "4580",
"icon": "achievement_boss_sindragosa",
"side": "",
"obtainable": true
},
{
"id": "4527",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4581",
"icon": "Spell_Shadow_DevouringPlague",
"side": "",
"obtainable": true
},
{
"id": "4601",
"icon": "Spell_DeathKnight_BloodPlague",
"side": "",
"obtainable": true
},
{
"id": "4530",
"icon": "achievement_dungeon_frozenthrone",
"side": "",
"obtainable": true
},
{
"id": "4532",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Heroic) (10 player)",
"achs": [
{
"id": "4628",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4629",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4630",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4631",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4583",
"icon": "achievement_boss_lichking",
"side": "",
"obtainable": true
},
{
"id": "4636",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Ruby Sanctum (10 player)",
"achs": [
{
"id": "4817",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "4818",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Normal) (25 player)",
"achs": [
{
"id": "4610",
"icon": "achievement_boss_lordmarrowgar",
"side": "",
"obtainable": true
},
{
"id": "4611",
"icon": "achievement_boss_ladydeathwhisper",
"side": "",
"obtainable": true
},
{
"id": "4612",
"icon": "achievement_dungeon_hordeairship",
"side": "",
"obtainable": true
},
{
"id": "4613",
"icon": "achievement_boss_saurfang",
"side": "",
"obtainable": true
},
{
"id": "4604",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4615",
"icon": "achievement_boss_festergutrotface",
"side": "",
"obtainable": true
},
{
"id": "4614",
"icon": "Spell_Nature_Acid_01",
"side": "",
"obtainable": true
},
{
"id": "4616",
"icon": "achievement_boss_profputricide",
"side": "",
"obtainable": true
},
{
"id": "4605",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4617",
"icon": "achievement_boss_princetaldaram",
"side": "",
"obtainable": true
},
{
"id": "4618",
"icon": "achievement_boss_lanathel",
"side": "",
"obtainable": true
},
{
"id": "4606",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4619",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "4620",
"icon": "achievement_boss_sindragosa",
"side": "",
"obtainable": true
},
{
"id": "4607",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4622",
"icon": "Spell_Shadow_DevouringPlague",
"side": "",
"obtainable": true
},
{
"id": "4621",
"icon": "Spell_DeathKnight_BloodPlague",
"side": "",
"obtainable": true
},
{
"id": "4597",
"icon": "achievement_dungeon_frozenthrone",
"side": "",
"obtainable": true
},
{
"id": "4608",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Heroic) (25 player)",
"achs": [
{
"id": "4632",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4633",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4634",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4635",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4584",
"icon": "Spell_Holy_Aspiration",
"side": "",
"obtainable": true
},
{
"id": "4637",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Ruby Sanctum (25 player)",
"achs": [
{
"id": "4815",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "4816",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "The Burning Crusade",
"zones": [
{
"name": "Normal Dungeons",
"achs": [
{
"id": "647",
"icon": "Achievement_Boss_OmarTheUnscarred_01",
"side": "",
"obtainable": true
},
{
"id": "648",
"icon": "Achievement_Boss_KelidanTheBreaker",
"side": "",
"obtainable": true
},
{
"id": "649",
"icon": "Achievement_Boss_Quagmirran",
"side": "",
"obtainable": true
},
{
"id": "650",
"icon": "Achievement_Boss_theBlackStalker",
"side": "",
"obtainable": true
},
{
"id": "651",
"icon": "Achievement_Boss_Nexus_Prince_Shaffar",
"side": "",
"obtainable": true
},
{
"id": "666",
"icon": "Achievement_Boss_Exarch_Maladaar",
"side": "",
"obtainable": true
},
{
"id": "652",
"icon": "Achievement_Boss_EpochHunter",
"side": "",
"obtainable": true
},
{
"id": "653",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "654",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "656",
"icon": "Achievement_Boss_Warlord_Kalithresh",
"side": "",
"obtainable": true
},
{
"id": "657",
"icon": "Achievement_Boss_KargathBladefist_01",
"side": "",
"obtainable": true
},
{
"id": "658",
"icon": "Achievement_Boss_PathaleonTheCalculator",
"side": "",
"obtainable": true
},
{
"id": "659",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "655",
"icon": "Achievement_Boss_Aeonus_01",
"side": "",
"obtainable": true
},
{
"id": "660",
"icon": "Achievement_Boss_Harbinger_Skyriss",
"side": "",
"obtainable": true
},
{
"id": "661",
"icon": "Achievement_Boss_Kael'thasSunstrider_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Heroic Dungeons",
"achs": [
{
"id": "667",
"icon": "Achievement_Boss_OmarTheUnscarred_01",
"side": "",
"obtainable": true
},
{
"id": "668",
"icon": "Achievement_Boss_KelidanTheBreaker",
"side": "",
"obtainable": true
},
{
"id": "669",
"icon": "Achievement_Boss_Quagmirran",
"side": "",
"obtainable": true
},
{
"id": "670",
"icon": "Achievement_Boss_theBlackStalker",
"side": "",
"obtainable": true
},
{
"id": "671",
"icon": "Achievement_Boss_Nexus_Prince_Shaffar",
"side": "",
"obtainable": true
},
{
"id": "672",
"icon": "Achievement_Boss_Exarch_Maladaar",
"side": "",
"obtainable": true
},
{
"id": "673",
"icon": "Achievement_Boss_EpochHunter",
"side": "",
"obtainable": true
},
{
"id": "674",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "675",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "677",
"icon": "Achievement_Boss_Warlord_Kalithresh",
"side": "",
"obtainable": true
},
{
"id": "678",
"icon": "Achievement_Boss_KargathBladefist_01",
"side": "",
"obtainable": true
},
{
"id": "679",
"icon": "Achievement_Boss_PathaleonTheCalculator",
"side": "",
"obtainable": true
},
{
"id": "680",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "676",
"icon": "Achievement_Boss_Aeonus_01",
"side": "",
"obtainable": true
},
{
"id": "681",
"icon": "Achievement_Boss_Harbinger_Skyriss",
"side": "",
"obtainable": true
},
{
"id": "682",
"icon": "Achievement_Boss_Kael'thasSunstrider_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Raids",
"achs": [
{
"id": "690",
"icon": "Achievement_Boss_PrinceMalchezaar_02",
"side": "",
"obtainable": true
},
{
"id": "692",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "",
"obtainable": true
},
{
"id": "693",
"icon": "Achievement_Boss_Magtheridon",
"side": "",
"obtainable": true
},
{
"id": "694",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "696",
"icon": "Achievement_Character_Bloodelf_Male",
"side": "",
"obtainable": true
},
{
"id": "695",
"icon": "Achievement_Boss_Archimonde-",
"side": "",
"obtainable": true
},
{
"id": "697",
"icon": "Achievement_Boss_Illidan",
"side": "",
"obtainable": true
},
{
"id": "698",
"icon": "Achievement_Boss_Kiljaedan",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Classic",
"zones": [
{
"name": "Eastern Kingdoms Dungeons",
"achs": [
{
"id": "628",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "631",
"icon": "inv_helm_robe_dungeonrobe_c_04",
"side": "",
"obtainable": true
},
{
"id": "633",
"icon": "INV_Misc_Head_Gnoll_01",
"side": "",
"obtainable": true
},
{
"id": "634",
"icon": "Achievement_Boss_Mekgineer_Thermaplugg-",
"side": "",
"obtainable": true
},
{
"id": "637",
"icon": "INV_Helmet_52",
"side": "",
"obtainable": true
},
{
"id": "7413",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "638",
"icon": "Achievement_Boss_Archaedas",
"side": "",
"obtainable": true
},
{
"id": "645",
"icon": "Spell_Holy_SenseUndead",
"side": "",
"obtainable": true
},
{
"id": "646",
"icon": "Spell_DeathKnight_ArmyOfTheDead",
"side": "",
"obtainable": true
},
{
"id": "641",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "642",
"icon": "Achievement_Boss_EmperorDagranThaurissan",
"side": "",
"obtainable": true
},
{
"id": "643",
"icon": "Achievement_Boss_Overlord_Wyrmthalak",
"side": "",
"obtainable": true
},
{
"id": "1307",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "2188",
"icon": "Ability_Mount_Drake_Red",
"side": "",
"obtainable": true
}
]
},
{
"name": "Kalimdor Dungeons",
"achs": [
{
"id": "629",
"icon": "Spell_Shadow_SummonFelGuard",
"side": "",
"obtainable": true
},
{
"id": "630",
"icon": "Achievement_Boss_Mutanus_the_Devourer",
"side": "",
"obtainable": true
},
{
"id": "632",
"icon": "Achievement_Boss_Bazil_Akumai",
"side": "",
"obtainable": true
},
{
"id": "635",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "",
"obtainable": true
},
{
"id": "640",
"icon": "Achievement_Boss_PrincessTheradras",
"side": "",
"obtainable": true
},
{
"id": "636",
"icon": "Achievement_Boss_Amnennar_the_Coldbringer",
"side": "",
"obtainable": true
},
{
"id": "644",
"icon": "Ability_Warrior_DecisiveStrike",
"side": "",
"obtainable": true
},
{
"id": "639",
"icon": "Achievement_Boss_ChiefUkorzSandscalp",
"side": "",
"obtainable": true
}
]
},
{
"name": "Classic Raids",
"achs": [
{
"id": "685",
"icon": "Achievement_Boss_Nefarion",
"side": "",
"obtainable": true
},
{
"id": "686",
"icon": "Achievement_Boss_Ragnaros",
"side": "",
"obtainable": true
},
{
"id": "689",
"icon": "Achievement_Boss_OssirianTheUnscarred",
"side": "",
"obtainable": true
},
{
"id": "687",
"icon": "Achievement_Boss_CThun",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Player vs. Player",
"cats": [
{
"name": "Player vs. Player",
"zones": [
{
"name": "Conquest Points",
"achs": [
{
"id": "5542",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5541",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5540",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5539",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "8093",
"icon": "achievement_bg_winwsg",
"side": "H",
"obtainable": true
},
{
"id": "8218",
"icon": "achievement_bg_winwsg",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Kills",
"achs": [
{
"id": "238",
"icon": "Achievement_PVP_P_01",
"side": "",
"obtainable": true
},
{
"id": "513",
"icon": "Achievement_PVP_P_02",
"side": "",
"obtainable": true
},
{
"id": "515",
"icon": "Achievement_PVP_P_03",
"side": "",
"obtainable": true
},
{
"id": "516",
"icon": "Achievement_PVP_P_04",
"side": "",
"obtainable": true
},
{
"id": "512",
"icon": "Achievement_PVP_P_06",
"side": "",
"obtainable": true
},
{
"id": "509",
"icon": "Achievement_PVP_P_09",
"side": "",
"obtainable": true
},
{
"id": "239",
"icon": "Achievement_PVP_P_11",
"side": "",
"obtainable": true
},
{
"id": "869",
"icon": "Achievement_PVP_P_14",
"side": "",
"obtainable": true
},
{
"id": "870",
"icon": "Achievement_PVP_P_15",
"side": "",
"obtainable": true
},
{
"id": "5363",
"icon": "achievement_pvp_p_250k",
"side": "",
"obtainable": true
}
]
},
{
"name": "Battlegrounds",
"achs": [
{
"id": "727",
"icon": "Ability_Mount_BlackDireWolf",
"side": "",
"obtainable": true
},
{
"id": "908",
"icon": "Ability_Warrior_Incite",
"side": "A",
"obtainable": true
},
{
"id": "909",
"icon": "Ability_Warrior_Incite",
"side": "H",
"obtainable": true
},
{
"id": "227",
"icon": "Achievement_BG_topDPS",
"side": "",
"obtainable": true
},
{
"id": "229",
"icon": "Spell_Shadow_NetherCloak",
"side": "",
"obtainable": true
},
{
"id": "231",
"icon": "Ability_Warrior_Trauma",
"side": "",
"obtainable": true
},
{
"id": "907",
"icon": "INV_Misc_TabardPVP_03",
"side": "A",
"obtainable": true
},
{
"id": "714",
"icon": "INV_Misc_TabardPVP_04",
"side": "H",
"obtainable": true
},
{
"id": "230",
"icon": "Achievement_PVP_A_15",
"side": "A",
"obtainable": true
},
{
"id": "1175",
"icon": "Achievement_PVP_H_15",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Cities",
"achs": [
{
"id": "604",
"icon": "INV_Trinket_HonorHold",
"side": "A",
"obtainable": true
},
{
"id": "603",
"icon": "INV_Trinket_Thrallmar",
"side": "H",
"obtainable": true
},
{
"id": "388",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "1006",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "613",
"icon": "Achievement_Leader_Lorthemar_Theron-",
"side": "A",
"obtainable": true
},
{
"id": "611",
"icon": "Achievement_Leader_Cairne-Bloodhoof",
"side": "A",
"obtainable": true
},
{
"id": "612",
"icon": "Achievement_Leader_Sylvanas",
"side": "A",
"obtainable": true
},
{
"id": "610",
"icon": "inv_axe_60",
"side": "A",
"obtainable": true
},
{
"id": "618",
"icon": "Achievement_Leader_Prophet_Velen",
"side": "H",
"obtainable": true
},
{
"id": "617",
"icon": "Achievement_Leader_Tyrande_Whisperwind",
"side": "H",
"obtainable": true
},
{
"id": "616",
"icon": "achievement_zone_ironforge",
"side": "H",
"obtainable": true
},
{
"id": "615",
"icon": "Achievement_Leader_King_Varian_Wrynn",
"side": "H",
"obtainable": true
},
{
"id": "614",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "619",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "1157",
"icon": "Ability_DualWieldSpecialization",
"side": "",
"obtainable": true
},
{
"id": "701",
"icon": "INV_Jewelry_TrinketPVP_01",
"side": "A",
"obtainable": true
},
{
"id": "700",
"icon": "INV_Jewelry_TrinketPVP_02",
"side": "H",
"obtainable": true
},
{
"id": "246",
"icon": "Ability_Gouge",
"side": "A",
"obtainable": true
},
{
"id": "1005",
"icon": "Ability_Gouge",
"side": "H",
"obtainable": true
},
{
"id": "245",
"icon": "Ability_CheapShot",
"side": "",
"obtainable": true
},
{
"id": "247",
"icon": "Spell_BrokenHeart",
"side": "",
"obtainable": true
},
{
"id": "389",
"icon": "INV_Misc_ArmorKit_14",
"side": "",
"obtainable": true
},
{
"id": "396",
"icon": "INV_Misc_ArmorKit_04",
"side": "",
"obtainable": true
},
{
"id": "2016",
"icon": "Achievement_Zone_GrizzlyHills_11",
"side": "A",
"obtainable": true
},
{
"id": "2017",
"icon": "Achievement_Zone_GrizzlyHills_11",
"side": "H",
"obtainable": true
},
{
"id": "8052",
"icon": "achievement_pvp_a_15",
"side": "A",
"obtainable": true
},
{
"id": "8055",
"icon": "achievement_pvp_a_15",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Deepwind Gorge",
"zones": [
{
"name": "",
"achs": [
{
"id": "8359",
"icon": "achievement_bg_captureflag_eos",
"side": "",
"obtainable": true
},
{
"id": "8358",
"icon": "ability_warrior_intensifyrage",
"side": "",
"obtainable": true
},
{
"id": "8333",
"icon": "achievement_bg_abshutout",
"side": "",
"obtainable": true
},
{
"id": "8332",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8331",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8360",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8350",
"icon": "achievement_bg_winav_bothmines",
"side": "",
"obtainable": true
},
{
"id": "8351",
"icon": "achievement_bg_tophealer_ab",
"side": "",
"obtainable": true
},
{
"id": "8354",
"icon": "spell_magic_featherfall",
"side": "",
"obtainable": true
},
{
"id": "8355",
"icon": "inv_stone_weightstone_06",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Silvershard Mines",
"zones": [
{
"name": "",
"achs": [
{
"id": "6739",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
},
{
"id": "6883",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
},
{
"id": "7039",
"icon": "inv_misc_gem_diamond_07",
"side": "",
"obtainable": true
},
{
"id": "7049",
"icon": "inv_misc_gem_diamond_07",
"side": "",
"obtainable": true
},
{
"id": "7057",
"icon": "achievement_bg_winav_bothmines",
"side": "",
"obtainable": true
},
{
"id": "7062",
"icon": "inv_pick_02",
"side": "",
"obtainable": true
},
{
"id": "7099",
"icon": "achievement_bg_getxflags_no_die",
"side": "",
"obtainable": true
},
{
"id": "7100",
"icon": "inv_crate_07",
"side": "",
"obtainable": true
},
{
"id": "7102",
"icon": "inv_crate_07",
"side": "",
"obtainable": true
},
{
"id": "7103",
"icon": "ability_racial_packhobgoblin",
"side": "",
"obtainable": true
},
{
"id": "7106",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Temple of Kotmogu",
"zones": [
{
"name": "",
"achs": [
{
"id": "6740",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6882",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6947",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6950",
"icon": "ability_rogue_fleetfooted",
"side": "",
"obtainable": true
},
{
"id": "6970",
"icon": "ability_monk_blackoutkick",
"side": "",
"obtainable": true
},
{
"id": "6971",
"icon": "achievement_bg_abshutout",
"side": "",
"obtainable": true
},
{
"id": "6972",
"icon": "achievement_bg_kill_flag_carrier",
"side": "",
"obtainable": true
},
{
"id": "6973",
"icon": "ability_warrior_intensifyrage",
"side": "",
"obtainable": true
},
{
"id": "6980",
"icon": "ability_wintergrasp_rank1",
"side": "",
"obtainable": true
},
{
"id": "6981",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Warsong Gulch",
"zones": [
{
"name": "",
"achs": [
{
"id": "713",
"icon": "Ability_Racial_ShadowMeld",
"side": "A",
"obtainable": true
},
{
"id": "712",
"icon": "Ability_Warrior_WarCry",
"side": "H",
"obtainable": true
},
{
"id": "1259",
"icon": "Ability_Rogue_Trip",
"side": "",
"obtainable": true
},
{
"id": "199",
"icon": "Achievement_BG_captureflag_WSG",
"side": "",
"obtainable": true
},
{
"id": "202",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "A",
"obtainable": true
},
{
"id": "1502",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "H",
"obtainable": true
},
{
"id": "204",
"icon": "Achievement_BG_3flagcap_nodeaths",
"side": "",
"obtainable": true
},
{
"id": "872",
"icon": "Achievement_BG_returnXflags_def_WSG",
"side": "",
"obtainable": true
},
{
"id": "203",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "A",
"obtainable": true
},
{
"id": "1251",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "H",
"obtainable": true
},
{
"id": "207",
"icon": "Ability_Rogue_SurpriseAttack",
"side": "",
"obtainable": true
},
{
"id": "206",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "A",
"obtainable": true
},
{
"id": "1252",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "H",
"obtainable": true
},
{
"id": "200",
"icon": "Achievement_BG_interruptX_flagcapture_attempts",
"side": "",
"obtainable": true
},
{
"id": "166",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "167",
"icon": "Achievement_BG_win_WSG_X_times",
"side": "",
"obtainable": true
},
{
"id": "201",
"icon": "Achievement_BG_winWSG_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "168",
"icon": "Achievement_BG_winWSG_3-0",
"side": "",
"obtainable": true
},
{
"id": "1172",
"icon": "INV_Misc_Rune_07",
"side": "A",
"obtainable": true
},
{
"id": "1173",
"icon": "INV_Misc_Rune_07",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Arathi Basin",
"zones": [
{
"name": "",
"achs": [
{
"id": "711",
"icon": "Ability_Warrior_RallyingCry",
"side": "A",
"obtainable": true
},
{
"id": "710",
"icon": "Spell_Shadow_PsychicHorrors",
"side": "H",
"obtainable": true
},
{
"id": "583",
"icon": "Ability_Warrior_IntensifyRage",
"side": "",
"obtainable": true
},
{
"id": "584",
"icon": "Ability_Hunter_RapidKilling",
"side": "",
"obtainable": true
},
{
"id": "73",
"icon": "Ability_Warrior_BattleShout",
"side": "",
"obtainable": true
},
{
"id": "1153",
"icon": "Achievement_BG_AB_defendflags",
"side": "",
"obtainable": true
},
{
"id": "158",
"icon": "Achievement_BG_takeXflags_AB",
"side": "",
"obtainable": true
},
{
"id": "157",
"icon": "Ability_Warrior_VictoryRush",
"side": "",
"obtainable": true
},
{
"id": "154",
"icon": "Achievement_BG_winAB",
"side": "",
"obtainable": true
},
{
"id": "155",
"icon": "Achievement_BG_win_AB_X_times",
"side": "",
"obtainable": true
},
{
"id": "159",
"icon": "Achievement_BG_winAB_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "156",
"icon": "Achievement_BG_winAB_5cap",
"side": "",
"obtainable": true
},
{
"id": "161",
"icon": "Achievement_BG_overcome500disadvantage",
"side": "",
"obtainable": true
},
{
"id": "162",
"icon": "Spell_Shadow_ImprovedVampiricEmbrace",
"side": "",
"obtainable": true
},
{
"id": "165",
"icon": "Achievement_BG_ABshutout",
"side": "",
"obtainable": true
},
{
"id": "1169",
"icon": "INV_Jewelry_Amulet_07",
"side": "A",
"obtainable": true
},
{
"id": "1170",
"icon": "INV_Jewelry_Amulet_07",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Alterac Valley",
"zones": [
{
"name": "",
"achs": [
{
"id": "708",
"icon": "INV_Jewelry_FrostwolfTrinket_05",
"side": "H",
"obtainable": true
},
{
"id": "709",
"icon": "INV_Jewelry_StormPikeTrinket_05",
"side": "A",
"obtainable": true
},
{
"id": "706",
"icon": "INV_Jewelry_FrostwolfTrinket_01",
"side": "H",
"obtainable": true
},
{
"id": "707",
"icon": "INV_Jewelry_StormPikeTrinket_01",
"side": "A",
"obtainable": true
},
{
"id": "223",
"icon": "Achievement_BG_kill_on_mount",
"side": "",
"obtainable": true
},
{
"id": "1166",
"icon": "INV_Scroll_10",
"side": "",
"obtainable": true
},
{
"id": "221",
"icon": "Achievement_BG_Xkills_AVgraveyard",
"side": "",
"obtainable": true
},
{
"id": "222",
"icon": "Achievement_BG_DefendXtowers_AV",
"side": "",
"obtainable": true
},
{
"id": "224",
"icon": "Achievement_BG_KillXEnemies_GeneralsRoom",
"side": "H",
"obtainable": true
},
{
"id": "1151",
"icon": "Achievement_BG_KillXEnemies_GeneralsRoom",
"side": "A",
"obtainable": true
},
{
"id": "582",
"icon": "Spell_Holy_Heroism",
"side": "",
"obtainable": true
},
{
"id": "218",
"icon": "Achievement_BG_winAV",
"side": "",
"obtainable": true
},
{
"id": "219",
"icon": "Achievement_BG_win_AV_X_times",
"side": "",
"obtainable": true
},
{
"id": "226",
"icon": "Achievement_BG_winAV_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "225",
"icon": "Achievement_BG_winAV_bothmines",
"side": "A",
"obtainable": true
},
{
"id": "1164",
"icon": "Achievement_BG_winAV_bothmines",
"side": "H",
"obtainable": true
},
{
"id": "873",
"icon": "INV_Jewelry_FrostwolfTrinket_03",
"side": "H",
"obtainable": true
},
{
"id": "220",
"icon": "INV_Jewelry_StormPikeTrinket_03",
"side": "A",
"obtainable": true
},
{
"id": "1167",
"icon": "INV_Jewelry_Necklace_21",
"side": "A",
"obtainable": true
},
{
"id": "1168",
"icon": "INV_Jewelry_Necklace_21",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Eye of the Storm",
"zones": [
{
"name": "",
"achs": [
{
"id": "233",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "1258",
"icon": "Achievement_BG_killingblow_berserker",
"side": "",
"obtainable": true
},
{
"id": "212",
"icon": "Achievement_BG_captureflag_EOS",
"side": "",
"obtainable": true
},
{
"id": "211",
"icon": "Achievement_BG_hld4bases_EOS",
"side": "",
"obtainable": true
},
{
"id": "216",
"icon": "Spell_Arcane_MassDispel",
"side": "",
"obtainable": true
},
{
"id": "213",
"icon": "Achievement_BG_kill_flag_carrierEOS",
"side": "",
"obtainable": true
},
{
"id": "587",
"icon": "Ability_Druid_GaleWinds",
"side": "",
"obtainable": true
},
{
"id": "208",
"icon": "Achievement_BG_winEOS",
"side": "",
"obtainable": true
},
{
"id": "209",
"icon": "Achievement_BG_win_EOS_X_times",
"side": "",
"obtainable": true
},
{
"id": "214",
"icon": "Achievement_BG_winEOS_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "784",
"icon": "INV_BRD_Banner",
"side": "",
"obtainable": true
},
{
"id": "783",
"icon": "INV_BRD_Banner",
"side": "",
"obtainable": true
},
{
"id": "1171",
"icon": "Spell_Nature_EyeOfTheStorm",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Strand of the Ancients",
"zones": [
{
"name": "",
"achs": [
{
"id": "1765",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2193",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "1761",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2190",
"icon": "Ability_Rogue_Dismantle",
"side": "",
"obtainable": true
},
{
"id": "1764",
"icon": "Ability_Hunter_BeastSoothe",
"side": "",
"obtainable": true
},
{
"id": "1766",
"icon": "Ability_Rogue_BloodSplatter",
"side": "",
"obtainable": true
},
{
"id": "2191",
"icon": "Ability_Rogue_Ambush",
"side": "",
"obtainable": true
},
{
"id": "2189",
"icon": "INV_Ammo_Bullet_03",
"side": "",
"obtainable": true
},
{
"id": "1763",
"icon": "INV_Weapon_Rifle_19",
"side": "",
"obtainable": true
},
{
"id": "1757",
"icon": "Ability_Warrior_DefensiveStance",
"side": "A",
"obtainable": true
},
{
"id": "2200",
"icon": "Ability_Warrior_DefensiveStance",
"side": "H",
"obtainable": true
},
{
"id": "1308",
"icon": "Achievement_BG_winSOA",
"side": "",
"obtainable": true
},
{
"id": "1309",
"icon": "Achievement_BG_winSOA",
"side": "",
"obtainable": true
},
{
"id": "1310",
"icon": "Achievement_BG_winSOA_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "1762",
"icon": "Ability_Warrior_Charge",
"side": "A",
"obtainable": true
},
{
"id": "2192",
"icon": "Ability_Warrior_Charge",
"side": "H",
"obtainable": true
},
{
"id": "2194",
"icon": "Achievement_BG_winSOA",
"side": "A",
"obtainable": true
},
{
"id": "2195",
"icon": "Achievement_BG_winSOA",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Isle of Conquest",
"zones": [
{
"name": "",
"achs": [
{
"id": "3848",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "3849",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "3853",
"icon": "INV_Weapon_Shortblade_37",
"side": "",
"obtainable": true
},
{
"id": "3854",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "3852",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "3856",
"icon": "INV_Gizmo_SuperSapperCharge",
"side": "A",
"obtainable": true
},
{
"id": "3850",
"icon": "INV_Misc_MissileSmallCluster_Red",
"side": "",
"obtainable": true
},
{
"id": "4256",
"icon": "INV_Gizmo_SuperSapperCharge",
"side": "H",
"obtainable": true
},
{
"id": "3847",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "3855",
"icon": "Ability_UpgradeMoonGlaive",
"side": "",
"obtainable": true
},
{
"id": "3845",
"icon": "Spell_Holy_Heroism",
"side": "",
"obtainable": true
},
{
"id": "3776",
"icon": "INV_Shield_61",
"side": "",
"obtainable": true
},
{
"id": "3777",
"icon": "Achievement_BG_win_AV_X_times",
"side": "",
"obtainable": true
},
{
"id": "3846",
"icon": "INV_Gizmo_Pipe_03",
"side": "A",
"obtainable": true
},
{
"id": "4176",
"icon": "INV_Gizmo_Pipe_03",
"side": "H",
"obtainable": true
},
{
"id": "3851",
"icon": "INV_Ingot_Cobalt",
"side": "A",
"obtainable": true
},
{
"id": "4177",
"icon": "INV_Ingot_Cobalt",
"side": "H",
"obtainable": true
},
{
"id": "3857",
"icon": "Achievement_BG_winWSG",
"side": "A",
"obtainable": true
},
{
"id": "3957",
"icon": "Achievement_BG_winWSG",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Battle for Gilneas",
"zones": [
{
"name": "",
"achs": [
{
"id": "5262",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "5257",
"icon": "Ability_Hunter_RapidKilling",
"side": "",
"obtainable": true
},
{
"id": "5256",
"icon": "Ability_Warrior_IntensifyRage",
"side": "",
"obtainable": true
},
{
"id": "5249",
"icon": "Achievement_BG_takeXflags_AB",
"side": "",
"obtainable": true
},
{
"id": "5250",
"icon": "Spell_Nature_Tranquility",
"side": "",
"obtainable": true
},
{
"id": "5251",
"icon": "Ability_Warrior_VictoryRush",
"side": "",
"obtainable": true
},
{
"id": "5248",
"icon": "achievement_bg_tophealer_ab",
"side": "",
"obtainable": true
},
{
"id": "5245",
"icon": "achievement_win_gilneas",
"side": "",
"obtainable": true
},
{
"id": "5254",
"icon": "Achievement_BG_winAV_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "5255",
"icon": "Ability_Rogue_KidneyShot",
"side": "",
"obtainable": true
},
{
"id": "5252",
"icon": "Ability_Rogue_StayofExecution",
"side": "",
"obtainable": true
},
{
"id": "5247",
"icon": "Achievement_BG_ABshutout",
"side": "",
"obtainable": true
},
{
"id": "5253",
"icon": "Achievement_BG_3flagcap_nodeaths",
"side": "",
"obtainable": true
},
{
"id": "5246",
"icon": "achievement_win_gilneas",
"side": "",
"obtainable": true
},
{
"id": "5258",
"icon": "achievement_battleground_battleforgilneas",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Twin Peaks",
"zones": [
{
"name": "",
"achs": [
{
"id": "5228",
"icon": "INV_Misc_Head_Dwarf_01",
"side": "H",
"obtainable": true
},
{
"id": "5229",
"icon": "Racial_Orc_BerserkerStrength",
"side": "A",
"obtainable": true
},
{
"id": "5230",
"icon": "Achievement_BG_captureflag_WSG",
"side": "",
"obtainable": true
},
{
"id": "5221",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "A",
"obtainable": true
},
{
"id": "5222",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "H",
"obtainable": true
},
{
"id": "5210",
"icon": "Achievement_BG_captureflag_EOS",
"side": "",
"obtainable": true
},
{
"id": "5219",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "A",
"obtainable": true
},
{
"id": "5220",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "H",
"obtainable": true
},
{
"id": "5227",
"icon": "achievement_cloudnine",
"side": "H",
"obtainable": true
},
{
"id": "5226",
"icon": "achievement_cloudnine",
"side": "A",
"obtainable": true
},
{
"id": "5211",
"icon": "Achievement_BG_interruptX_flagcapture_attempts",
"side": "",
"obtainable": true
},
{
"id": "5214",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "H",
"obtainable": true
},
{
"id": "5213",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "A",
"obtainable": true
},
{
"id": "5208",
"icon": "achievement_bg_tophealer_av",
"side": "",
"obtainable": true
},
{
"id": "5552",
"icon": "achievement_doublejeopardyhorde",
"side": "H",
"obtainable": true
},
{
"id": "5231",
"icon": "achievement_doublejeopardyhorde",
"side": "A",
"obtainable": true
},
{
"id": "5215",
"icon": "Achievement_BG_winWSG_3-0",
"side": "",
"obtainable": true
},
{
"id": "5216",
"icon": "Achievement_BG_winWSG_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "5209",
"icon": "Achievement_BG_win_WSG_X_times",
"side": "",
"obtainable": true
},
{
"id": "5259",
"icon": "Spell_Nature_EarthShock",
"side": "H",
"obtainable": true
},
{
"id": "5223",
"icon": "Spell_Nature_EarthShock",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Wintergrasp",
"zones": [
{
"name": "",
"achs": [
{
"id": "2080",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "1727",
"icon": "Spell_Arcane_TeleportTheramore",
"side": "",
"obtainable": true
},
{
"id": "1737",
"icon": "Spell_Fire_BlueFlameStrike",
"side": "A",
"obtainable": true
},
{
"id": "2476",
"icon": "Spell_Fire_BlueFlameStrike",
"side": "H",
"obtainable": true
},
{
"id": "1751",
"icon": "Achievement_BG_kill_on_mount",
"side": "",
"obtainable": true
},
{
"id": "2776",
"icon": "Spell_Frost_ChillingBlast",
"side": "H",
"obtainable": true
},
{
"id": "1723",
"icon": "Ability_Mount_Gyrocoptor",
"side": "",
"obtainable": true
},
{
"id": "2199",
"icon": "Ability_Mage_ShatterShield",
"side": "",
"obtainable": true
},
{
"id": "1717",
"icon": "Spell_Frost_ChillingBlast",
"side": "",
"obtainable": true
},
{
"id": "1718",
"icon": "Spell_Frost_ChillingBlast",
"side": "",
"obtainable": true
},
{
"id": "1755",
"icon": "Spell_Frost_ManaBurn",
"side": "",
"obtainable": true
},
{
"id": "1752",
"icon": "Spell_Frost_ChillingBlast",
"side": "A",
"obtainable": true
},
{
"id": "1722",
"icon": "INV_Misc_Statue_07",
"side": "",
"obtainable": true
},
{
"id": "3136",
"icon": "INV_Misc_Statue_10",
"side": "",
"obtainable": true
},
{
"id": "3836",
"icon": "Spell_Fire_TotemOfWrath",
"side": "",
"obtainable": true
},
{
"id": "4585",
"icon": "Spell_Frost_FrostBrand",
"side": "",
"obtainable": true
},
{
"id": "1721",
"icon": "INV_Misc_Statue_07",
"side": "",
"obtainable": true
},
{
"id": "3137",
"icon": "INV_Misc_Statue_10",
"side": "",
"obtainable": true
},
{
"id": "3837",
"icon": "Spell_Fire_TotemOfWrath",
"side": "",
"obtainable": true
},
{
"id": "4586",
"icon": "Spell_Frost_FrostBrand",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Tol Barad",
"zones": [
{
"name": "",
"achs": [
{
"id": "5719",
"icon": "achievement_zone_tolbarad",
"side": "H",
"obtainable": true
},
{
"id": "5718",
"icon": "achievement_zone_tolbarad",
"side": "A",
"obtainable": true
},
{
"id": "5415",
"icon": "Spell_Arcane_TeleportTheramore",
"side": "",
"obtainable": true
},
{
"id": "5488",
"icon": "ability_vehicle_siegeengineram",
"side": "",
"obtainable": true
},
{
"id": "5487",
"icon": "ability_vehicle_siegeenginecannon",
"side": "",
"obtainable": true
},
{
"id": "5486",
"icon": "achievement_bg_killingblow_startingrock",
"side": "",
"obtainable": true
},
{
"id": "5412",
"icon": "achievement_zone_tolbarad",
"side": "",
"obtainable": true
},
{
"id": "5417",
"icon": "achievement_zone_tolbarad",
"side": "A",
"obtainable": true
},
{
"id": "5418",
"icon": "achievement_zone_tolbarad",
"side": "H",
"obtainable": true
},
{
"id": "5489",
"icon": "inv_banner_tolbarad_alliance",
"side": "A",
"obtainable": true
},
{
"id": "5490",
"icon": "inv_banner_tolbarad_horde",
"side": "H",
"obtainable": true
},
{
"id": "5416",
"icon": "Achievement_Boss_Magtheridon",
"side": "",
"obtainable": true
},
{
"id": "6045",
"icon": "inv_misc_eye_03",
"side": "",
"obtainable": true
},
{
"id": "6108",
"icon": "achievement_shivan",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Arena",
"zones": [
{
"name": "2v2",
"achs": [
{
"id": "399",
"icon": "Achievement_Arena_2v2_1",
"side": "",
"obtainable": true
},
{
"id": "400",
"icon": "Achievement_Arena_2v2_4",
"side": "",
"obtainable": true
},
{
"id": "401",
"icon": "Achievement_Arena_2v2_5",
"side": "",
"obtainable": true
},
{
"id": "1159",
"icon": "Achievement_Arena_2v2_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "3v3",
"achs": [
{
"id": "402",
"icon": "Achievement_Arena_3v3_1",
"side": "",
"obtainable": true
},
{
"id": "403",
"icon": "Achievement_Arena_3v3_4",
"side": "",
"obtainable": true
},
{
"id": "405",
"icon": "Achievement_Arena_3v3_5",
"side": "",
"obtainable": true
},
{
"id": "1160",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
},
{
"id": "5266",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
},
{
"id": "5267",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "5v5",
"achs": [
{
"id": "406",
"icon": "Achievement_Arena_5v5_1",
"side": "",
"obtainable": true
},
{
"id": "407",
"icon": "Achievement_Arena_5v5_4",
"side": "",
"obtainable": true
},
{
"id": "404",
"icon": "Achievement_Arena_5v5_5",
"side": "",
"obtainable": true
},
{
"id": "1161",
"icon": "Achievement_Arena_5v5_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "397",
"icon": "Achievement_FeatsOfStrength_Gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "398",
"icon": "Achievement_FeatsOfStrength_Gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "875",
"icon": "Achievement_FeatsOfStrength_Gladiator_02",
"side": "",
"obtainable": true
},
{
"id": "876",
"icon": "Achievement_FeatsOfStrength_Gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "2090",
"icon": "Achievement_FeatsOfStrength_Gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "2093",
"icon": "Achievement_FeatsOfStrength_Gladiator_05",
"side": "",
"obtainable": true
},
{
"id": "2092",
"icon": "Achievement_FeatsOfStrength_Gladiator_06",
"side": "",
"obtainable": true
},
{
"id": "2091",
"icon": "Achievement_FeatsOfStrength_Gladiator_07",
"side": "",
"obtainable": true
},
{
"id": "409",
"icon": "Spell_Holy_SurgeOfLight",
"side": "",
"obtainable": true
},
{
"id": "699",
"icon": "Ability_Hunter_Pathfinding",
"side": "",
"obtainable": true
},
{
"id": "408",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "1162",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "1174",
"icon": "Achievement_FeatsOfStrength_Gladiator_08",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Rated Battleground",
"zones": [
{
"name": "Ratings",
"achs": [
{
"id": "5330",
"icon": "Achievement_PVP_A_01",
"side": "A",
"obtainable": true
},
{
"id": "5331",
"icon": "Achievement_PVP_A_02",
"side": "A",
"obtainable": true
},
{
"id": "5332",
"icon": "Achievement_PVP_A_03",
"side": "A",
"obtainable": true
},
{
"id": "5333",
"icon": "Achievement_PVP_A_04",
"side": "A",
"obtainable": true
},
{
"id": "5334",
"icon": "Achievement_PVP_A_05",
"side": "A",
"obtainable": true
},
{
"id": "5335",
"icon": "Achievement_PVP_A_06",
"side": "A",
"obtainable": true
},
{
"id": "5336",
"icon": "Achievement_PVP_A_07",
"side": "A",
"obtainable": true
},
{
"id": "5337",
"icon": "Achievement_PVP_A_08",
"side": "A",
"obtainable": true
},
{
"id": "5359",
"icon": "Achievement_PVP_A_09",
"side": "A",
"obtainable": true
},
{
"id": "5339",
"icon": "Achievement_PVP_A_10",
"side": "A",
"obtainable": true
},
{
"id": "5340",
"icon": "Achievement_PVP_A_11",
"side": "A",
"obtainable": true
},
{
"id": "5341",
"icon": "Achievement_PVP_A_12",
"side": "A",
"obtainable": true
},
{
"id": "5357",
"icon": "Achievement_PVP_A_13",
"side": "A",
"obtainable": true
},
{
"id": "5343",
"icon": "Achievement_PVP_A_14",
"side": "A",
"obtainable": true
},
{
"id": "5344",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "6316",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "6939",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "6942",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "5345",
"icon": "Achievement_PVP_H_01",
"side": "H",
"obtainable": true
},
{
"id": "5346",
"icon": "Achievement_PVP_H_02",
"side": "H",
"obtainable": true
},
{
"id": "5347",
"icon": "Achievement_PVP_H_03",
"side": "H",
"obtainable": true
},
{
"id": "5348",
"icon": "Achievement_PVP_H_04",
"side": "H",
"obtainable": true
},
{
"id": "5349",
"icon": "Achievement_PVP_H_05",
"side": "H",
"obtainable": true
},
{
"id": "5350",
"icon": "Achievement_PVP_H_06",
"side": "H",
"obtainable": true
},
{
"id": "5351",
"icon": "Achievement_PVP_H_07",
"side": "H",
"obtainable": true
},
{
"id": "5352",
"icon": "Achievement_PVP_H_08",
"side": "H",
"obtainable": true
},
{
"id": "5338",
"icon": "Achievement_PVP_H_09",
"side": "H",
"obtainable": true
},
{
"id": "5353",
"icon": "Achievement_PVP_H_10",
"side": "H",
"obtainable": true
},
{
"id": "5354",
"icon": "Achievement_PVP_H_11",
"side": "H",
"obtainable": true
},
{
"id": "5355",
"icon": "Achievement_PVP_H_12",
"side": "H",
"obtainable": true
},
{
"id": "5342",
"icon": "Achievement_PVP_H_13",
"side": "H",
"obtainable": true
},
{
"id": "5356",
"icon": "Achievement_PVP_H_14",
"side": "H",
"obtainable": true
},
{
"id": "5358",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6317",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6940",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6941",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Wins",
"achs": [
{
"id": "5268",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5322",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5327",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5328",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5823",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5329",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5269",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5323",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5324",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5325",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5824",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5326",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "General",
"cats": [
{
"name": "General",
"zones": [
{
"name": "Level",
"achs": [
{
"id": "6",
"icon": "Achievement_Level_10",
"side": "",
"obtainable": true
},
{
"id": "7",
"icon": "Achievement_Level_20",
"side": "",
"obtainable": true
},
{
"id": "8",
"icon": "Achievement_Level_30",
"side": "",
"obtainable": true
},
{
"id": "9",
"icon": "Achievement_Level_40",
"side": "",
"obtainable": true
},
{
"id": "10",
"icon": "Achievement_Level_50",
"side": "",
"obtainable": true
},
{
"id": "11",
"icon": "Achievement_Level_60",
"side": "",
"obtainable": true
},
{
"id": "12",
"icon": "Achievement_Level_70",
"side": "",
"obtainable": true
},
{
"id": "13",
"icon": "Achievement_Level_80",
"side": "",
"obtainable": true
},
{
"id": "4826",
"icon": "achievement_level_85",
"side": "",
"obtainable": true
},
{
"id": "6193",
"icon": "achievement_level_90",
"side": "",
"obtainable": true
},
{
"id": "7382",
"icon": "achievement_arena_2v2_7",
"side": "",
"obtainable": true
},
{
"id": "7383",
"icon": "achievement_guildperk_everybodysfriend",
"side": "",
"obtainable": true
},
{
"id": "7384",
"icon": "achievement_guild_level5",
"side": "",
"obtainable": true
},
{
"id": "7380",
"icon": "achievement_bg_winwsg",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gold",
"achs": [
{
"id": "1176",
"icon": "INV_Misc_Coin_06",
"side": "",
"obtainable": true
},
{
"id": "1177",
"icon": "INV_Misc_Coin_04",
"side": "",
"obtainable": true
},
{
"id": "1178",
"icon": "INV_Misc_Coin_03",
"side": "",
"obtainable": true
},
{
"id": "1180",
"icon": "INV_Misc_Coin_02",
"side": "",
"obtainable": true
},
{
"id": "1181",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "5455",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "5456",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "6753",
"icon": "inv_misc_coin_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mounts",
"achs": [
{
"id": "891",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "889",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "892",
"icon": "Ability_Mount_Wyvern_01",
"side": "",
"obtainable": true
},
{
"id": "890",
"icon": "Ability_Mount_Gryphon_01",
"side": "",
"obtainable": true
},
{
"id": "5180",
"icon": "Ability_Mount_RocketMount",
"side": "",
"obtainable": true
},
{
"id": "2076",
"icon": "Ability_Mount_PolarBear_Brown",
"side": "",
"obtainable": true
},
{
"id": "2077",
"icon": "Ability_Mount_Mammoth_Brown",
"side": "",
"obtainable": true
},
{
"id": "2078",
"icon": "Ability_Mount_Mammoth_Brown",
"side": "",
"obtainable": true
},
{
"id": "2097",
"icon": "INV_Misc_Key_14",
"side": "",
"obtainable": true
},
{
"id": "4888",
"icon": "ability_mount_camel_tan",
"side": "",
"obtainable": true
},
{
"id": "5749",
"icon": "INV_Alchemy_Potion_06",
"side": "",
"obtainable": true
},
{
"id": "7386",
"icon": "ability_mount_travellersyakmount",
"side": "",
"obtainable": true
},
{
"id": "2141",
"icon": "Ability_Mount_RidingElekk",
"side": "",
"obtainable": true
},
{
"id": "2142",
"icon": "Ability_Mount_RidingElekkElite_Green",
"side": "",
"obtainable": true
},
{
"id": "2143",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "2536",
"icon": "Ability_Hunter_Pet_DragonHawk",
"side": "A",
"obtainable": true
},
{
"id": "7860",
"icon": "inv_pandarenserpentmount_green",
"side": "A",
"obtainable": true
},
{
"id": "2537",
"icon": "Ability_Hunter_Pet_DragonHawk",
"side": "H",
"obtainable": true
},
{
"id": "7862",
"icon": "inv_pandarenserpentmount_green",
"side": "H",
"obtainable": true
},
{
"id": "8304",
"icon": "ability_mount_dragonhawkarmorallliance",
"side": "A",
"obtainable": true
},
{
"id": "8302",
"icon": "ability_mount_dragonhawkarmorhorde",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Tabards",
"achs": [
{
"id": "621",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1020",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1021",
"icon": "INV_Chest_Cloth_30",
"side": "",
"obtainable": true
},
{
"id": "5755",
"icon": "INV_Chest_Cloth_30",
"side": "",
"obtainable": true
}
]
},
{
"name": "Books",
"achs": [
{
"id": "1244",
"icon": "INV_Misc_Book_04",
"side": "",
"obtainable": true
},
{
"id": "1956",
"icon": "INV_Misc_Book_11",
"side": "",
"obtainable": true
}
]
},
{
"name": "Items",
"achs": [
{
"id": "558",
"icon": "INV_Misc_Coin_04",
"side": "",
"obtainable": true
},
{
"id": "559",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "557",
"icon": "Spell_Frost_WizardMark",
"side": "",
"obtainable": true
},
{
"id": "556",
"icon": "INV_Enchant_VoidCrystal",
"side": "",
"obtainable": true
},
{
"id": "1165",
"icon": "INV_Misc_Bag_27",
"side": "",
"obtainable": true
},
{
"id": "2084",
"icon": "INV_JEWELRY_RING_73",
"side": "",
"obtainable": true
},
{
"id": "5373",
"icon": "Spell_Frost_WizardMark",
"side": "",
"obtainable": true
},
{
"id": "5372",
"icon": "INV_Enchant_VoidCrystal",
"side": "",
"obtainable": true
},
{
"id": "6348",
"icon": "inv_glove_plate_pvpwarrior_c_01",
"side": "",
"obtainable": true
},
{
"id": "6349",
"icon": "inv_glove_plate_raiddeathknight_j_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Critters",
"achs": [
{
"id": "1254",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "2556",
"icon": "Ability_Hunter_Pet_Spider",
"side": "",
"obtainable": true
},
{
"id": "1206",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "2557",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "5548",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "6350",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
}
]
},
{
"name": "Food",
"achs": [
{
"id": "1833",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "5754",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "1832",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "5753",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "7329",
"icon": "inv_misc_food_115_condorsoup",
"side": "",
"obtainable": true
},
{
"id": "7330",
"icon": "inv_misc_food_115_condorsoup",
"side": "",
"obtainable": true
},
{
"id": "5779",
"icon": "inv_misc_food_150_cookie",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "964",
"icon": "Spell_Shadow_TwistedFaith",
"side": "",
"obtainable": true
},
{
"id": "2716",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "545",
"icon": "INV_Misc_Comb_02",
"side": "",
"obtainable": true
},
{
"id": "546",
"icon": "INV_Box_01",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Professions",
"cats": [
{
"name": "Professions",
"zones": [
{
"name": "",
"achs": [
{
"id": "116",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "731",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "732",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "733",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "734",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "4924",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "6830",
"icon": "inv_misc_note_01",
"side": "",
"obtainable": true
},
{
"id": "730",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "4915",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "6836",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "735",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "4914",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "6835",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "7378",
"icon": "trade_blacksmithing",
"side": "",
"obtainable": true
},
{
"id": "7379",
"icon": "inv_misc_mastersinscription",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Archaeology",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "4857",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4919",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4920",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4921",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4922",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4923",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "6837",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
}
]
},
{
"name": "Counts",
"achs": [
{
"id": "5511",
"icon": "trade_archaeology_tuskarr_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5315",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5469",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5470",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4854",
"icon": "trade_archaeology_aqir_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4855",
"icon": "trade_archaeology_dwarf_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4856",
"icon": "trade_archaeology_highborne_artifactfragment",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lore",
"achs": [
{
"id": "7331",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7332",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7333",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7334",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7335",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7336",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7337",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7612",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8219",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Race",
"achs": [
{
"id": "4859",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "4858",
"icon": "inv_qirajidol_night",
"side": "",
"obtainable": true
},
{
"id": "5301",
"icon": "inv_misc_tabard_tolvir",
"side": "",
"obtainable": true
},
{
"id": "5191",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "5192",
"icon": "inv_helmet_04",
"side": "",
"obtainable": true
},
{
"id": "5193",
"icon": "achievement_boss_cyanigosa",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Pandaren",
"achs": [
{
"id": "7345",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7365",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7343",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7363",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7342",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7362",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7344",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7364",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7339",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7359",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7338",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7358",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7346",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7366",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7347",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7367",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7340",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7360",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7341",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7361",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Mogu",
"achs": [
{
"id": "7349",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7369",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7353",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7373",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7354",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7374",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7348",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7368",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7356",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7376",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7351",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7371",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7350",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7370",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7352",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7372",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7355",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7375",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7357",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7377",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Mantid",
"achs": [
{
"id": "8222",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8223",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8220",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8221",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8227",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8226",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8235",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8234",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8230",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8231",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8232",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8233",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8225",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8224",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8229",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8228",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cooking",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "121",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "122",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "123",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "124",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "125",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "4916",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "7300",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7301",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7302",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7303",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7304",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7305",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7306",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "6365",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
}
]
},
{
"name": "Quests",
"achs": [
{
"id": "906",
"icon": "INV_Misc_Cauldron_Arcane",
"side": "",
"obtainable": true
},
{
"id": "1782",
"icon": "INV_Misc_Food_12",
"side": "A",
"obtainable": true
},
{
"id": "1783",
"icon": "INV_Misc_Food_12",
"side": "H",
"obtainable": true
},
{
"id": "5475",
"icon": "inv_misc_food_42",
"side": "H",
"obtainable": true
},
{
"id": "5844",
"icon": "inv_misc_food_meat_cooked_09",
"side": "H",
"obtainable": true
},
{
"id": "5843",
"icon": "inv_misc_food_pinenut",
"side": "H",
"obtainable": true
},
{
"id": "5474",
"icon": "INV_Misc_Food_19",
"side": "A",
"obtainable": true
},
{
"id": "5841",
"icon": "INV_Cask_04",
"side": "A",
"obtainable": true
},
{
"id": "5842",
"icon": "INV_Misc_Food_63",
"side": "A",
"obtainable": true
},
{
"id": "5846",
"icon": "INV_Misc_Food_DimSum",
"side": "H",
"obtainable": true
},
{
"id": "5845",
"icon": "INV_Misc_Food_DimSum",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Awards",
"achs": [
{
"id": "1998",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "1999",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2000",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2001",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2002",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Recipes",
"achs": [
{
"id": "1795",
"icon": "INV_Misc_Food_66",
"side": "",
"obtainable": true
},
{
"id": "1796",
"icon": "INV_Misc_Food_65",
"side": "",
"obtainable": true
},
{
"id": "1797",
"icon": "INV_Misc_Food_60",
"side": "",
"obtainable": true
},
{
"id": "1798",
"icon": "INV_Misc_Food_13",
"side": "",
"obtainable": true
},
{
"id": "1799",
"icon": "INV_Misc_Food_92_Lobster",
"side": "",
"obtainable": true
},
{
"id": "5471",
"icon": "inv_misc_food_161_fish_89",
"side": "",
"obtainable": true
},
{
"id": "7328",
"icon": "inv_misc_food_161_fish_89",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gourmet",
"achs": [
{
"id": "1800",
"icon": "INV_Misc_Food_84_RoastClefthoof",
"side": "",
"obtainable": true
},
{
"id": "1777",
"icon": "INV_Misc_Food_138_Fish",
"side": "",
"obtainable": true
},
{
"id": "1778",
"icon": "INV_Misc_Food_141_Fish",
"side": "",
"obtainable": true
},
{
"id": "1779",
"icon": "INV_Misc_Food_140_Fish",
"side": "",
"obtainable": true
},
{
"id": "5472",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
},
{
"id": "5473",
"icon": "inv_misc_food_143_fish",
"side": "",
"obtainable": true
},
{
"id": "7326",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
},
{
"id": "7327",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "877",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "1801",
"icon": "INV_Drink_03",
"side": "",
"obtainable": true
},
{
"id": "3296",
"icon": "Achievement_Profession_ChefHat",
"side": "",
"obtainable": true
},
{
"id": "1780",
"icon": "INV_ValentinesChocolate01",
"side": "",
"obtainable": true
},
{
"id": "1781",
"icon": "INV_Misc_Food_88_RavagerNuggets",
"side": "",
"obtainable": true
},
{
"id": "1785",
"icon": "Ability_Hunter_Pet_Boar",
"side": "",
"obtainable": true
},
{
"id": "1563",
"icon": "Achievement_Profession_ChefHat",
"side": "A",
"obtainable": true
},
{
"id": "1784",
"icon": "Achievement_Profession_ChefHat",
"side": "H",
"obtainable": true
},
{
"id": "7325",
"icon": "trade_cooking_2",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "First Aid",
"zones": [
{
"name": "",
"achs": [
{
"id": "131",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "132",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "133",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "134",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "135",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "4918",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "6838",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "137",
"icon": "INV_Misc_Bandage_04",
"side": "",
"obtainable": true
},
{
"id": "5480",
"icon": "inv_emberweavebandage2",
"side": "",
"obtainable": true
},
{
"id": "141",
"icon": "INV_Misc_SurgeonGlove_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Fishing",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "126",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "127",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "128",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "129",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "130",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "4917",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "6839",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
}
]
},
{
"name": "Counts",
"achs": [
{
"id": "1556",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1557",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1558",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1559",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1560",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1561",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
}
]
},
{
"name": "Quests",
"achs": [
{
"id": "905",
"icon": "Achievement_Profession_Fishing_OldManBarlowned",
"side": "",
"obtainable": true
},
{
"id": "3217",
"icon": "INV_Fishingpole_03",
"side": "",
"obtainable": true
},
{
"id": "5477",
"icon": "INV_Fishingpole_03",
"side": "H",
"obtainable": true
},
{
"id": "5849",
"icon": "inv_fishingpole_06",
"side": "H",
"obtainable": true
},
{
"id": "5850",
"icon": "inv_fishingpole_07",
"side": "H",
"obtainable": true
},
{
"id": "5476",
"icon": "INV_Fishingpole_03",
"side": "A",
"obtainable": true
},
{
"id": "5847",
"icon": "INV_Fishingpole_02",
"side": "A",
"obtainable": true
},
{
"id": "5848",
"icon": "inv_fishingpole_06",
"side": "A",
"obtainable": true
},
{
"id": "5851",
"icon": "INV_Helmet_31",
"side": "",
"obtainable": true
},
{
"id": "7614",
"icon": "inv_misc_fish_95",
"side": "",
"obtainable": true
},
{
"id": "7274",
"icon": "inv_helmet_50",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pools",
"achs": [
{
"id": "153",
"icon": "Achievement_Profession_Fishing_JourneymanFisher",
"side": "",
"obtainable": true
},
{
"id": "1243",
"icon": "Achievement_Profession_Fishing_FindFish",
"side": "",
"obtainable": true
},
{
"id": "1257",
"icon": "INV_Crate_05",
"side": "",
"obtainable": true
},
{
"id": "1225",
"icon": "Achievement_Profession_Fishing_OutlandAngler",
"side": "",
"obtainable": true
},
{
"id": "1517",
"icon": "Achievement_Profession_Fishing_NorthrendAngler",
"side": "",
"obtainable": true
},
{
"id": "7611",
"icon": "inv_misc_fish_93",
"side": "",
"obtainable": true
}
]
},
{
"name": "Coins",
"achs": [
{
"id": "2094",
"icon": "INV_Misc_Coin_19",
"side": "",
"obtainable": true
},
{
"id": "2095",
"icon": "INV_Misc_Coin_18",
"side": "",
"obtainable": true
},
{
"id": "1957",
"icon": "INV_Misc_Coin_17",
"side": "",
"obtainable": true
},
{
"id": "2096",
"icon": "INV_Misc_Coin_02",
"side": "",
"obtainable": true
}
]
},
{
"name": "Cities",
"achs": [
{
"id": "150",
"icon": "INV_Helmet_44",
"side": "",
"obtainable": true
},
{
"id": "1837",
"icon": "INV_Misc_Fish_31",
"side": "",
"obtainable": true
},
{
"id": "1836",
"icon": "INV_Misc_Fish_35",
"side": "",
"obtainable": true
},
{
"id": "1958",
"icon": "INV_Misc_MonsterTail_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "World",
"achs": [
{
"id": "5479",
"icon": "inv_misc_fish_61",
"side": "",
"obtainable": true
},
{
"id": "5478",
"icon": "inv_misc_fish_30",
"side": "",
"obtainable": true
},
{
"id": "878",
"icon": "INV_Misc_Fish_35",
"side": "",
"obtainable": true
},
{
"id": "726",
"icon": "INV_Misc_Fish_14",
"side": "",
"obtainable": true
},
{
"id": "3218",
"icon": "inv_misc_fish_turtle_02",
"side": "",
"obtainable": true
},
{
"id": "144",
"icon": "Ability_Creature_Poison_05",
"side": "",
"obtainable": true
},
{
"id": "306",
"icon": "INV_Misc_Fish_06",
"side": "",
"obtainable": true
},
{
"id": "1516",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Quests",
"cats": [
{
"name": "Quests",
"zones": [
{
"name": "Regular Counts",
"achs": [
{
"id": "503",
"icon": "Achievement_Quests_Completed_01",
"side": "",
"obtainable": true
},
{
"id": "504",
"icon": "Achievement_Quests_Completed_02",
"side": "",
"obtainable": true
},
{
"id": "505",
"icon": "Achievement_Quests_Completed_03",
"side": "",
"obtainable": true
},
{
"id": "506",
"icon": "Achievement_Quests_Completed_04",
"side": "",
"obtainable": true
},
{
"id": "507",
"icon": "Achievement_Quests_Completed_05",
"side": "",
"obtainable": true
},
{
"id": "508",
"icon": "Achievement_Quests_Completed_06",
"side": "",
"obtainable": true
},
{
"id": "32",
"icon": "Achievement_Quests_Completed_07",
"side": "",
"obtainable": true
},
{
"id": "978",
"icon": "Achievement_Quests_Completed_08",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily Counts",
"achs": [
{
"id": "973",
"icon": "Achievement_Quests_Completed_Daily_01",
"side": "",
"obtainable": true
},
{
"id": "974",
"icon": "Achievement_Quests_Completed_Daily_02",
"side": "",
"obtainable": true
},
{
"id": "975",
"icon": "Achievement_Quests_Completed_Daily_03",
"side": "",
"obtainable": true
},
{
"id": "976",
"icon": "Achievement_Quests_Completed_Daily_04",
"side": "",
"obtainable": true
},
{
"id": "977",
"icon": "Achievement_Quests_Completed_Daily_05",
"side": "",
"obtainable": true
},
{
"id": "5751",
"icon": "Achievement_Quests_Completed_Daily_05",
"side": "",
"obtainable": true
},
{
"id": "7410",
"icon": "achievement_quests_completed_daily_06",
"side": "",
"obtainable": true
},
{
"id": "7411",
"icon": "achievement_quests_completed_daily_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dungeon Counts",
"achs": [
{
"id": "4956",
"icon": "Achievement_Quests_Completed_05",
"side": "",
"obtainable": true
},
{
"id": "4957",
"icon": "Achievement_Quests_Completed_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Themes",
"achs": [
{
"id": "941",
"icon": "INV_Weapon_Rifle_05",
"side": "",
"obtainable": true
},
{
"id": "1576",
"icon": "INV_Helmet_08",
"side": "",
"obtainable": true
},
{
"id": "4958",
"icon": "Ability_Warrior_BloodFrenzy",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "31",
"icon": "Achievement_Quests_Completed_Daily_x5",
"side": "",
"obtainable": true
},
{
"id": "1182",
"icon": "INV_Misc_Coin_16",
"side": "",
"obtainable": true
},
{
"id": "5752",
"icon": "INV_Misc_Coin_16",
"side": "",
"obtainable": true
},
{
"id": "7520",
"icon": "INV_Misc_Book_07",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "6300",
"icon": "achievement_zone_jadeforest_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6534",
"icon": "achievement_zone_jadeforest_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6301",
"icon": "achievement_zone_valleyoffourwinds_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6535",
"icon": "achievement_zone_krasarangwilds_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6536",
"icon": "achievement_zone_krasarangwilds_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6537",
"icon": "achievement_zone_kunlaisummit_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6538",
"icon": "achievement_zone_kunlaisummit_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6539",
"icon": "achievement_zone_townlongsteppes_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6540",
"icon": "achievement_zone_dreadwastes_loremaster",
"side": "",
"obtainable": true
},
{
"id": "7315",
"icon": "achievement_zone_valeofeternalblossoms_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6541",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "7285",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Klaxxi",
"achs": [
{
"id": "7312",
"icon": "achievement_raid_mantidraid06",
"side": "",
"obtainable": true
},
{
"id": "7313",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "7314",
"icon": "achievement_raid_mantidraid05",
"side": "",
"obtainable": true
},
{
"id": "7316",
"icon": "ability_mount_hordescorpionamber",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Golden Lotus",
"achs": [
{
"id": "7317",
"icon": "achievement_moguraid_04",
"side": "",
"obtainable": true
},
{
"id": "7318",
"icon": "inv_misc_key_15",
"side": "",
"obtainable": true
},
{
"id": "7319",
"icon": "ability_hunter_posthaste",
"side": "",
"obtainable": true
},
{
"id": "7320",
"icon": "ability_toughness",
"side": "",
"obtainable": true
},
{
"id": "7321",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "7322",
"icon": "ability_monk_roll",
"side": "",
"obtainable": true
},
{
"id": "7323",
"icon": "warrior_talent_icon_bloodandthunder",
"side": "",
"obtainable": true
},
{
"id": "7324",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan",
"achs": [
{
"id": "7297",
"icon": "achievement_guildperk_everyones-a-hero_rank2",
"side": "",
"obtainable": true
},
{
"id": "7298",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "7299",
"icon": "achievement_guildperk_everyones-a-hero",
"side": "",
"obtainable": true
},
{
"id": "7307",
"icon": "ability_rogue_masterofsubtlety",
"side": "",
"obtainable": true
},
{
"id": "7308",
"icon": "inv_shield_panstart_a_01",
"side": "",
"obtainable": true
},
{
"id": "7309",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "7310",
"icon": "inv_inscription_trinket_ox",
"side": "",
"obtainable": true
}
]
},
{
"name": "The August Celestials",
"achs": [
{
"id": "7286",
"icon": "ability_monk_summontigerstatue",
"side": "",
"obtainable": true
},
{
"id": "7287",
"icon": "ability_mount_cranemount",
"side": "",
"obtainable": true
},
{
"id": "7288",
"icon": "ability_mount_yakmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Tillers",
"achs": [
{
"id": "7292",
"icon": "inv_misc_herb_01",
"side": "",
"obtainable": true
},
{
"id": "7293",
"icon": "inv_misc_herb_02",
"side": "",
"obtainable": true
},
{
"id": "7294",
"icon": "inv_misc_herb_goldenlotus",
"side": "",
"obtainable": true
},
{
"id": "7295",
"icon": "inv_misc_herb_whiptail",
"side": "",
"obtainable": true
},
{
"id": "7296",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
}
]
},
{
"name": "Order of the Cloud Serpent",
"achs": [
{
"id": "7289",
"icon": "inv_pandarenserpentpet",
"side": "",
"obtainable": true
},
{
"id": "7290",
"icon": "ability_monk_summonserpentstatue",
"side": "",
"obtainable": true
},
{
"id": "7291",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dominance Offensive",
"achs": [
{
"id": "7929",
"icon": "achievement_zone_krasarangwilds",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Operation: Shieldwall",
"achs": [
{
"id": "7928",
"icon": "achievement_zone_krasarangwilds",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "7502",
"icon": "inv_mushanbeastmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "Wrathion",
"achs": [
{
"id": "7533",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "7534",
"icon": "inv_legendary_theblackprince",
"side": "A",
"obtainable": true
},
{
"id": "8008",
"icon": "inv_legendary_theblackprince",
"side": "H",
"obtainable": true
},
{
"id": "7535",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "7536",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "8030",
"icon": "inv_legendary_theblackprince",
"side": "A",
"obtainable": true
},
{
"id": "8031",
"icon": "inv_legendary_theblackprince",
"side": "H",
"obtainable": true
},
{
"id": "8325",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
}
]
},
{
"name": "Isle of Thunder",
"achs": [
{
"id": "8117",
"icon": "achievement_reputation_kirintor",
"side": "",
"obtainable": true
},
{
"id": "8118",
"icon": "ability_druid_empoweredtouch",
"side": "",
"obtainable": true
},
{
"id": "8120",
"icon": "ability_mount_triceratopsmount",
"side": "",
"obtainable": true
},
{
"id": "8112",
"icon": "inv_misc_archaeology_babypterrodax",
"side": "",
"obtainable": true
},
{
"id": "8106",
"icon": "ability_racial_timeismoney",
"side": "",
"obtainable": true
},
{
"id": "8099",
"icon": "spell_nature_callstorm",
"side": "",
"obtainable": true
},
{
"id": "8101",
"icon": "trade_archaeology_chestoftinyglassanimals",
"side": "",
"obtainable": true
},
{
"id": "8119",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "8100",
"icon": "inv_qiraj_jewelglyphed",
"side": "",
"obtainable": true
},
{
"id": "8114",
"icon": "ability_heroicleap",
"side": "",
"obtainable": true
},
{
"id": "8107",
"icon": "inv_pet_cockroach",
"side": "",
"obtainable": true
},
{
"id": "8115",
"icon": "spell_shaman_staticshock",
"side": "",
"obtainable": true
},
{
"id": "8105",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
},
{
"id": "8109",
"icon": "achievement_bg_xkills_avgraveyard",
"side": "",
"obtainable": true
},
{
"id": "8110",
"icon": "inv_polearm_2h_mogu_c_01",
"side": "",
"obtainable": true
},
{
"id": "8111",
"icon": "ability_paladin_beaconoflight",
"side": "",
"obtainable": true
},
{
"id": "8104",
"icon": "archaeology_5_0_mogucoin",
"side": "",
"obtainable": true
},
{
"id": "8108",
"icon": "trade_archaeology_tinydinosaurskeleton",
"side": "",
"obtainable": true
},
{
"id": "8116",
"icon": "ability_deathknight_sanguinfortitude",
"side": "",
"obtainable": true
},
{
"id": "8212",
"icon": "inv_misc_book_06",
"side": "",
"obtainable": true
},
{
"id": "8121",
"icon": "spell_shaman_thunderstorm",
"side": "",
"obtainable": true
}
]
},
{
"name": "Escalation",
"achs": [
{
"id": "8307",
"icon": "inv_hand_1h_trollshaman_c_01",
"side": "H",
"obtainable": true
},
{
"id": "8306",
"icon": "inv_hand_1h_trollshaman_c_01",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4870",
"icon": "achievement_quests_completed_mounthyjal",
"side": "",
"obtainable": true
},
{
"id": "4982",
"icon": "achievement_quests_completed_vashjir",
"side": "H",
"obtainable": true
},
{
"id": "4869",
"icon": "achievement_quests_completed_vashjir",
"side": "A",
"obtainable": true
},
{
"id": "4871",
"icon": "achievement_quests_completed_deepholm",
"side": "",
"obtainable": true
},
{
"id": "4872",
"icon": "achievement_quests_completed_uldum",
"side": "",
"obtainable": true
},
{
"id": "4873",
"icon": "achievement_quests_completed_twilighthighlands",
"side": "A",
"obtainable": true
},
{
"id": "5501",
"icon": "achievement_quests_completed_twilighthighlands",
"side": "H",
"obtainable": true
},
{
"id": "4875",
"icon": "INV_Misc_Book_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "4874",
"icon": "achievement_zone_tolbarad",
"side": "",
"obtainable": true
}
]
},
{
"name": "Hyjal",
"achs": [
{
"id": "5483",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "4959",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "5860",
"icon": "Ability_Hunter_Pet_Vulture",
"side": "",
"obtainable": true
}
]
},
{
"name": "Vashj'ir",
"achs": [
{
"id": "5452",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "5319",
"icon": "inv_misc_fish_51",
"side": "H",
"obtainable": true
},
{
"id": "5318",
"icon": "inv_misc_fish_51",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Deepholm",
"achs": [
{
"id": "5446",
"icon": "inv_mushroom_12",
"side": "",
"obtainable": true
},
{
"id": "5449",
"icon": "Spell_Nature_EarthElemental_Totem",
"side": "",
"obtainable": true
},
{
"id": "5447",
"icon": "achievement_dungeon_the-stonecore_slabhide",
"side": "",
"obtainable": true
},
{
"id": "5445",
"icon": "INV_Mushroom_06",
"side": "",
"obtainable": true
},
{
"id": "5450",
"icon": "INV_Mushroom_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Uldum",
"achs": [
{
"id": "4961",
"icon": "INV_Helmet_50",
"side": "",
"obtainable": true
},
{
"id": "5317",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Twilight Highlands",
"achs": [
{
"id": "4960",
"icon": "INV_Jewelry_Ring_03",
"side": "",
"obtainable": true
},
{
"id": "5481",
"icon": "inv_misc_tabard_wildhammerclan",
"side": "A",
"obtainable": true
},
{
"id": "5451",
"icon": "inv_jewelry_ring_ahnqiraj_05",
"side": "",
"obtainable": true
},
{
"id": "5482",
"icon": "inv_misc_tabard_dragonmawclan",
"side": "H",
"obtainable": true
},
{
"id": "5320",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "A",
"obtainable": true
},
{
"id": "5321",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Molten Front",
"achs": [
{
"id": "5859",
"icon": "Achievement_Character_Nightelf_Female",
"side": "",
"obtainable": true
},
{
"id": "5861",
"icon": "Spell_Fire_Elemental_Totem",
"side": "",
"obtainable": true
},
{
"id": "5862",
"icon": "Ability_Hunter_EagleEye",
"side": "",
"obtainable": true
},
{
"id": "5864",
"icon": "inv_sword_draenei_05",
"side": "",
"obtainable": true
},
{
"id": "5865",
"icon": "INV_Weapon_ShortBlade_10",
"side": "",
"obtainable": true
},
{
"id": "5866",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5867",
"icon": "spell_shaman_improvedfirenova",
"side": "",
"obtainable": true
},
{
"id": "5868",
"icon": "Ability_Tracking",
"side": "",
"obtainable": true
},
{
"id": "5869",
"icon": "ability_hunter_pet_corehound",
"side": "",
"obtainable": true
},
{
"id": "5870",
"icon": "Achievement_Character_Nightelf_Male",
"side": "",
"obtainable": true
},
{
"id": "5871",
"icon": "Spell_Fire_MoltenBlood",
"side": "",
"obtainable": true
},
{
"id": "5872",
"icon": "Ability_Hunter_Pet_Spider",
"side": "",
"obtainable": true
},
{
"id": "5873",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
},
{
"id": "5874",
"icon": "creatureportrait_g_bomb_02",
"side": "",
"obtainable": true
},
{
"id": "5879",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Northrend",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "1358",
"icon": "Achievement_Zone_BoreanTundra_07",
"side": "H",
"obtainable": true
},
{
"id": "33",
"icon": "Achievement_Zone_BoreanTundra_07",
"side": "A",
"obtainable": true
},
{
"id": "34",
"icon": "Achievement_Zone_HowlingFjord_07",
"side": "A",
"obtainable": true
},
{
"id": "1356",
"icon": "Achievement_Zone_HowlingFjord_07",
"side": "H",
"obtainable": true
},
{
"id": "1359",
"icon": "Achievement_Zone_DragonBlight_07",
"side": "H",
"obtainable": true
},
{
"id": "35",
"icon": "Achievement_Zone_DragonBlight_07",
"side": "A",
"obtainable": true
},
{
"id": "1357",
"icon": "Achievement_Zone_GrizzlyHills_07",
"side": "H",
"obtainable": true
},
{
"id": "37",
"icon": "Achievement_Zone_GrizzlyHills_07",
"side": "A",
"obtainable": true
},
{
"id": "39",
"icon": "Achievement_Zone_Sholazar_07",
"side": "",
"obtainable": true
},
{
"id": "36",
"icon": "Achievement_Zone_ZulDrak_07",
"side": "",
"obtainable": true
},
{
"id": "38",
"icon": "Achievement_Zone_StormPeaks_07",
"side": "",
"obtainable": true
},
{
"id": "40",
"icon": "Achievement_Zone_IceCrown_07",
"side": "",
"obtainable": true
},
{
"id": "41",
"icon": "Achievement_Zone_Northrend_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "561",
"icon": "Achievement_Zone_BoreanTundra_11",
"side": "",
"obtainable": true
},
{
"id": "1277",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "938",
"icon": "Ability_Hunter_Pet_Crocolisk",
"side": "",
"obtainable": true
},
{
"id": "1596",
"icon": "Achievement_Zone_ZulDrak_05",
"side": "",
"obtainable": true
},
{
"id": "1428",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "547",
"icon": "Achievement_Zone_IceCrown_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "962",
"icon": "Achievement_Zone_Sholazar_11",
"side": "",
"obtainable": true
},
{
"id": "961",
"icon": "Achievement_Zone_Sholazar_08",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Outland",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "1271",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "H",
"obtainable": true
},
{
"id": "1189",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "A",
"obtainable": true
},
{
"id": "1190",
"icon": "Achievement_Zone_Zangarmarsh",
"side": "",
"obtainable": true
},
{
"id": "1191",
"icon": "Achievement_Zone_Terrokar",
"side": "A",
"obtainable": true
},
{
"id": "1272",
"icon": "Achievement_Zone_Terrokar",
"side": "H",
"obtainable": true
},
{
"id": "1273",
"icon": "Achievement_Zone_Nagrand_01",
"side": "H",
"obtainable": true
},
{
"id": "1192",
"icon": "Achievement_Zone_Nagrand_01",
"side": "A",
"obtainable": true
},
{
"id": "1193",
"icon": "Achievement_Zone_BladesEdgeMtns_01",
"side": "",
"obtainable": true
},
{
"id": "1194",
"icon": "Achievement_Zone_Netherstorm_01",
"side": "",
"obtainable": true
},
{
"id": "1195",
"icon": "Achievement_Zone_Shadowmoon",
"side": "",
"obtainable": true
},
{
"id": "1262",
"icon": "Achievement_Zone_Outland_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "939",
"icon": "Ability_Mount_RidingElekk",
"side": "",
"obtainable": true
},
{
"id": "1275",
"icon": "INV_Misc_Bomb_07",
"side": "",
"obtainable": true
},
{
"id": "1276",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Eastern Kingdoms",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4899",
"icon": "achievement_zone_lochmodan",
"side": "A",
"obtainable": true
},
{
"id": "4894",
"icon": "Achievement_Zone_Silverpine_01",
"side": "H",
"obtainable": true
},
{
"id": "4903",
"icon": "Achievement_Zone_WestFall_01",
"side": "A",
"obtainable": true
},
{
"id": "4908",
"icon": "Achievement_Zone_Ghostlands",
"side": "H",
"obtainable": true
},
{
"id": "4902",
"icon": "Achievement_Zone_RedridgeMountains",
"side": "A",
"obtainable": true
},
{
"id": "4895",
"icon": "Achievement_Zone_HillsbradFoothills",
"side": "H",
"obtainable": true
},
{
"id": "4896",
"icon": "Achievement_Zone_ArathiHighlands_01",
"side": "",
"obtainable": true
},
{
"id": "4906",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4905",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4897",
"icon": "Achievement_Zone_Hinterlands_01",
"side": "",
"obtainable": true
},
{
"id": "4893",
"icon": "Achievement_Zone_WesternPlaguelands_01",
"side": "",
"obtainable": true
},
{
"id": "4892",
"icon": "Achievement_Zone_EasternPlaguelands",
"side": "",
"obtainable": true
},
{
"id": "4900",
"icon": "Achievement_Zone_Badlands_01",
"side": "",
"obtainable": true
},
{
"id": "4910",
"icon": "Achievement_Zone_SearingGorge_01",
"side": "",
"obtainable": true
},
{
"id": "4901",
"icon": "Achievement_Zone_BurningSteppes_01",
"side": "",
"obtainable": true
},
{
"id": "4904",
"icon": "Achievement_Zone_SwampSorrows_01",
"side": "",
"obtainable": true
},
{
"id": "4909",
"icon": "Achievement_Zone_BlastedLands_01",
"side": "",
"obtainable": true
},
{
"id": "1676",
"icon": "Achievement_Zone_EasternKingdoms_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "940",
"icon": "Ability_Mount_WhiteTiger",
"side": "",
"obtainable": true
},
{
"id": "5442",
"icon": "INV_Misc_Crop_02",
"side": "",
"obtainable": true
},
{
"id": "5444",
"icon": "inv_misc_desecrated_plategloves",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Kalimdor",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4927",
"icon": "Achievement_Zone_Azshara_01",
"side": "H",
"obtainable": true
},
{
"id": "4926",
"icon": "Achievement_Zone_BloodmystIsle_01",
"side": "A",
"obtainable": true
},
{
"id": "4928",
"icon": "Achievement_Zone_Darkshore_01",
"side": "A",
"obtainable": true
},
{
"id": "4933",
"icon": "Achievement_Zone_Barrens_01",
"side": "H",
"obtainable": true
},
{
"id": "4925",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "A",
"obtainable": true
},
{
"id": "4976",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "H",
"obtainable": true
},
{
"id": "4936",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "A",
"obtainable": true
},
{
"id": "4980",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "H",
"obtainable": true
},
{
"id": "4937",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "A",
"obtainable": true
},
{
"id": "4981",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "H",
"obtainable": true
},
{
"id": "4930",
"icon": "Achievement_Zone_Desolace",
"side": "",
"obtainable": true
},
{
"id": "4978",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "H",
"obtainable": true
},
{
"id": "4929",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "A",
"obtainable": true
},
{
"id": "4979",
"icon": "Achievement_Zone_Feralas",
"side": "H",
"obtainable": true
},
{
"id": "4932",
"icon": "Achievement_Zone_Feralas",
"side": "A",
"obtainable": true
},
{
"id": "4938",
"icon": "Achievement_Zone_ThousandNeedles_01",
"side": "",
"obtainable": true
},
{
"id": "4931",
"icon": "Achievement_Zone_Felwood",
"side": "",
"obtainable": true
},
{
"id": "4935",
"icon": "Achievement_Zone_Tanaris_01",
"side": "",
"obtainable": true
},
{
"id": "4939",
"icon": "Achievement_Zone_UnGoroCrater_01",
"side": "",
"obtainable": true
},
{
"id": "4940",
"icon": "Achievement_Zone_Winterspring",
"side": "",
"obtainable": true
},
{
"id": "4934",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "1678",
"icon": "Achievement_Zone_Kalimdor_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "5454",
"icon": "Ability_Mount_RocketMount",
"side": "H",
"obtainable": true
},
{
"id": "5448",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5546",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5547",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5453",
"icon": "Achievement_Boss_Illidan",
"side": "A",
"obtainable": true
},
{
"id": "5443",
"icon": "inv_misc_monsterscales_19",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Reputation",
"cats": [
{
"name": "Reputation",
"zones": [
{
"name": "Counts",
"achs": [
{
"id": "522",
"icon": "Achievement_Reputation_01",
"side": "",
"obtainable": true
},
{
"id": "523",
"icon": "Achievement_Reputation_01",
"side": "",
"obtainable": true
},
{
"id": "524",
"icon": "Achievement_Reputation_02",
"side": "",
"obtainable": true
},
{
"id": "521",
"icon": "Achievement_Reputation_03",
"side": "",
"obtainable": true
},
{
"id": "520",
"icon": "Achievement_Reputation_04",
"side": "",
"obtainable": true
},
{
"id": "519",
"icon": "Achievement_Reputation_05",
"side": "",
"obtainable": true
},
{
"id": "518",
"icon": "Achievement_Reputation_06",
"side": "",
"obtainable": true
},
{
"id": "1014",
"icon": "Achievement_Reputation_07",
"side": "",
"obtainable": true
},
{
"id": "1015",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "5374",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "5723",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "6826",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "6742",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "762",
"icon": "Achievement_PVP_H_16",
"side": "H",
"obtainable": true
},
{
"id": "948",
"icon": "Achievement_PVP_A_16",
"side": "A",
"obtainable": true
},
{
"id": "943",
"icon": "INV_Helmet_44",
"side": "H",
"obtainable": true
},
{
"id": "942",
"icon": "INV_Helmet_44",
"side": "A",
"obtainable": true
},
{
"id": "953",
"icon": "Ability_Racial_Ultravision",
"side": "",
"obtainable": true
},
{
"id": "945",
"icon": "Spell_Holy_HolyGuidance",
"side": "",
"obtainable": true
},
{
"id": "5794",
"icon": "inv_epicguildtabard",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "",
"achs": [
{
"id": "6544",
"icon": "achievement_faction_tillers",
"side": "",
"obtainable": true
},
{
"id": "6545",
"icon": "achievement_faction_klaxxi",
"side": "",
"obtainable": true
},
{
"id": "6546",
"icon": "achievement_faction_goldenlotus",
"side": "",
"obtainable": true
},
{
"id": "6547",
"icon": "achievement_faction_anglers",
"side": "",
"obtainable": true
},
{
"id": "6548",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6550",
"icon": "achievement_faction_serpentriders",
"side": "",
"obtainable": true
},
{
"id": "6551",
"icon": "achievement_reputation_01",
"side": "",
"obtainable": true
},
{
"id": "6552",
"icon": "achievement_reputation_03",
"side": "",
"obtainable": true
},
{
"id": "6366",
"icon": "achievement_faction_serpentriders",
"side": "",
"obtainable": true
},
{
"id": "6543",
"icon": "achievement_faction_celestials",
"side": "",
"obtainable": true
},
{
"id": "6827",
"icon": "trade_archaeology_highborne_scroll",
"side": "H",
"obtainable": true
},
{
"id": "6828",
"icon": "trade_archaeology_highborne_scroll",
"side": "A",
"obtainable": true
},
{
"id": "7479",
"icon": "achievement_faction_shadopan",
"side": "",
"obtainable": true
},
{
"id": "8023",
"icon": "achievement_faction_klaxxi",
"side": "",
"obtainable": true
},
{
"id": "8206",
"icon": "achievement_general_hordeslayer",
"side": "H",
"obtainable": true
},
{
"id": "8208",
"icon": "achievement_reputation_kirintor_offensive",
"side": "A",
"obtainable": true
},
{
"id": "8205",
"icon": "achievement_general_allianceslayer",
"side": "A",
"obtainable": true
},
{
"id": "8210",
"icon": "achievement_faction_shadopan",
"side": "",
"obtainable": true
},
{
"id": "8209",
"icon": "achievement_faction_sunreaveronslaught",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "",
"achs": [
{
"id": "4882",
"icon": "inv_misc_tabard_guardiansofhyjal",
"side": "",
"obtainable": true
},
{
"id": "4881",
"icon": "inv_misc_tabard_earthenring",
"side": "",
"obtainable": true
},
{
"id": "4883",
"icon": "inv_misc_tabard_therazane",
"side": "",
"obtainable": true
},
{
"id": "4884",
"icon": "inv_misc_tabard_tolvir",
"side": "",
"obtainable": true
},
{
"id": "4885",
"icon": "inv_misc_tabard_wildhammerclan",
"side": "A",
"obtainable": true
},
{
"id": "4886",
"icon": "inv_misc_tabard_dragonmawclan",
"side": "H",
"obtainable": true
},
{
"id": "5375",
"icon": "inv_misc_tabard_baradinwardens",
"side": "A",
"obtainable": true
},
{
"id": "5376",
"icon": "inv_misc_tabard_hellscream",
"side": "H",
"obtainable": true
},
{
"id": "5827",
"icon": "inv_neck_hyjaldaily_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Wrath of the Lich King",
"zones": [
{
"name": "",
"achs": [
{
"id": "949",
"icon": "Achievement_Reputation_Tuskarr",
"side": "",
"obtainable": true
},
{
"id": "950",
"icon": "Ability_Mount_WhiteDireWolf",
"side": "",
"obtainable": true
},
{
"id": "951",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "952",
"icon": "Spell_Nature_MirrorImage",
"side": "",
"obtainable": true
},
{
"id": "947",
"icon": "INV_Jewelry_Talisman_08",
"side": "",
"obtainable": true
},
{
"id": "1007",
"icon": "Achievement_Reputation_WyrmrestTemple",
"side": "",
"obtainable": true
},
{
"id": "1008",
"icon": "Achievement_Reputation_KirinTor",
"side": "",
"obtainable": true
},
{
"id": "1009",
"icon": "Achievement_Reputation_KnightsoftheEbonBlade",
"side": "",
"obtainable": true
},
{
"id": "1010",
"icon": "Spell_Misc_HellifrePVPCombatMorale",
"side": "",
"obtainable": true
},
{
"id": "1011",
"icon": "Spell_Misc_HellifrePVPThrallmarFavor",
"side": "H",
"obtainable": true
},
{
"id": "1012",
"icon": "Spell_Misc_HellifrePVPHonorHoldFavor",
"side": "A",
"obtainable": true
},
{
"id": "4598",
"icon": "INV_Jewelry_Talisman_08",
"side": "",
"obtainable": true
},
{
"id": "2082",
"icon": "Ability_Mount_Mammoth_White",
"side": "",
"obtainable": true
},
{
"id": "2083",
"icon": "Ability_Mount_Mammoth_White",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "The Burning Crusade",
"zones": [
{
"name": "",
"achs": [
{
"id": "893",
"icon": "Ability_Mount_WarHippogryph",
"side": "",
"obtainable": true
},
{
"id": "894",
"icon": "Ability_Hunter_Pet_NetherRay",
"side": "",
"obtainable": true
},
{
"id": "896",
"icon": "INV_Misc_Apexis_Crystal",
"side": "",
"obtainable": true
},
{
"id": "898",
"icon": "Ability_Mount_NetherdrakePurple",
"side": "",
"obtainable": true
},
{
"id": "1638",
"icon": "Ability_Mount_NetherdrakePurple",
"side": "",
"obtainable": true
},
{
"id": "900",
"icon": "INV_Mushroom_11",
"side": "",
"obtainable": true
},
{
"id": "902",
"icon": "INV_Enchant_ShardPrismaticLarge",
"side": "",
"obtainable": true
},
{
"id": "901",
"icon": "INV_Misc_Foot_Centaur",
"side": "H",
"obtainable": true
},
{
"id": "899",
"icon": "INV_Misc_Foot_Centaur",
"side": "A",
"obtainable": true
},
{
"id": "903",
"icon": "Spell_Arcane_PortalShattrath",
"side": "",
"obtainable": true
},
{
"id": "960",
"icon": "Spell_Holy_MindSooth",
"side": "",
"obtainable": true
},
{
"id": "959",
"icon": "INV_Enchant_DustIllusion",
"side": "",
"obtainable": true
},
{
"id": "958",
"icon": "Achievement_Reputation_AshtongueDeathsworn",
"side": "",
"obtainable": true
},
{
"id": "897",
"icon": "INV_Shield_48",
"side": "",
"obtainable": true
},
{
"id": "764",
"icon": "Spell_Fire_FelFireward",
"side": "A",
"obtainable": true
},
{
"id": "763",
"icon": "Spell_Fire_FelFireward",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Classic",
"zones": [
{
"name": "",
"achs": [
{
"id": "944",
"icon": "Achievement_Reputation_timbermaw",
"side": "",
"obtainable": true
},
{
"id": "946",
"icon": "INV_Jewelry_Talisman_07",
"side": "",
"obtainable": true
},
{
"id": "955",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "956",
"icon": "INV_Misc_Head_Dragon_Bronze",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Exploration",
"cats": [
{
"name": "Exploration",
"zones": [
{
"name": "",
"achs": [
{
"id": "42",
"icon": "Achievement_Zone_EasternKingdoms_01",
"side": "",
"obtainable": true
},
{
"id": "43",
"icon": "Achievement_Zone_Kalimdor_01",
"side": "",
"obtainable": true
},
{
"id": "44",
"icon": "Achievement_Zone_Outland_01",
"side": "",
"obtainable": true
},
{
"id": "45",
"icon": "Achievement_Zone_Northrend_01",
"side": "",
"obtainable": true
},
{
"id": "4868",
"icon": "Spell_Shaman_StormEarthFire",
"side": "",
"obtainable": true
},
{
"id": "6974",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "46",
"icon": "INV_Misc_Map02",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "Area",
"achs": [
{
"id": "6351",
"icon": "achievement_zone_jadeforest",
"side": "",
"obtainable": true
},
{
"id": "6969",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "6975",
"icon": "achievement_zone_krasarangwilds",
"side": "",
"obtainable": true
},
{
"id": "6976",
"icon": "achievement_zone_kunlaisummit",
"side": "",
"obtainable": true
},
{
"id": "6977",
"icon": "achievement_zone_townlongsteppes",
"side": "",
"obtainable": true
},
{
"id": "6978",
"icon": "achievement_zone_dreadwastes",
"side": "",
"obtainable": true
},
{
"id": "6979",
"icon": "achievement_zone_valeofeternalblossoms",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lore",
"achs": [
{
"id": "6716",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6754",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6846",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6847",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6850",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6855",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6856",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6857",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6858",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "7230",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "8049",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "8050",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "8051",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "7381",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
},
{
"id": "7437",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7438",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7439",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7518",
"icon": "ability_mount_pandaranmount",
"side": "",
"obtainable": true
},
{
"id": "7932",
"icon": "ability_rogue_deadliness",
"side": "",
"obtainable": true
},
{
"id": "8103",
"icon": "inv_shield_mogu_c_01",
"side": "",
"obtainable": true
},
{
"id": "8078",
"icon": "inv_misc_archaeology_trollgolem",
"side": "",
"obtainable": true
}
]
},
{
"name": "Treasure",
"achs": [
{
"id": "7281",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7282",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7283",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7284",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7994",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7995",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7996",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7997",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
}
]
},
{
"name": "Timeless Isle",
"achs": [
{
"id": "8726",
"icon": "trade_archaeology_chestoftinyglassanimals",
"side": "",
"obtainable": true
},
{
"id": "8725",
"icon": "inv_misc_coinbag_special",
"side": "",
"obtainable": true
},
{
"id": "8728",
"icon": "inv_misc_bag_16",
"side": "",
"obtainable": true
},
{
"id": "8712",
"icon": "ability_monk_touchofkarma",
"side": "",
"obtainable": true
},
{
"id": "8723",
"icon": "inv_staff_2h_pandarenmonk_c_01",
"side": "",
"obtainable": true
},
{
"id": "8724",
"icon": "ability_monk_tigerslust",
"side": "",
"obtainable": true
},
{
"id": "8730",
"icon": "inv_misc_map09",
"side": "",
"obtainable": true
},
{
"id": "8714",
"icon": "ability_monk_touchofdeath",
"side": "",
"obtainable": true
},
{
"id": "8784",
"icon": "inv_staff_2h_pandarenmonk_c_01",
"side": "",
"obtainable": true
},
{
"id": "8722",
"icon": "monk_ability_cherrymanatea",
"side": "",
"obtainable": true
},
{
"id": "8729",
"icon": "inv_misc_coin_01",
"side": "",
"obtainable": true
},
{
"id": "8727",
"icon": "inv_helmet_66",
"side": "",
"obtainable": true
},
{
"id": "8743",
"icon": "inv_misc_bone_02",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "",
"achs": [
{
"id": "4863",
"icon": "achievement_zone_mount-hyjal",
"side": "",
"obtainable": true
},
{
"id": "4825",
"icon": "achievement_zone_vashjir",
"side": "",
"obtainable": true
},
{
"id": "4864",
"icon": "achievement_zone_deepholm",
"side": "",
"obtainable": true
},
{
"id": "4865",
"icon": "achievement_zone_uldum",
"side": "",
"obtainable": true
},
{
"id": "4866",
"icon": "achievement_zone_twilighthighlands",
"side": "",
"obtainable": true
},
{
"id": "4827",
"icon": "Spell_Fire_Volcano",
"side": "",
"obtainable": true
},
{
"id": "4975",
"icon": "inv_misc_fish_60",
"side": "",
"obtainable": true
},
{
"id": "5518",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Northrend",
"zones": [
{
"name": "",
"achs": [
{
"id": "1264",
"icon": "Achievement_Zone_BoreanTundra_01",
"side": "",
"obtainable": true
},
{
"id": "1268",
"icon": "Achievement_Zone_Sholazar_01",
"side": "",
"obtainable": true
},
{
"id": "1457",
"icon": "Achievement_Zone_CrystalSong_01",
"side": "",
"obtainable": true
},
{
"id": "1265",
"icon": "Achievement_Zone_DragonBlight_01",
"side": "",
"obtainable": true
},
{
"id": "1263",
"icon": "Achievement_Zone_HowlingFjord_01",
"side": "",
"obtainable": true
},
{
"id": "1266",
"icon": "Achievement_Zone_GrizzlyHills_01",
"side": "",
"obtainable": true
},
{
"id": "1267",
"icon": "Achievement_Zone_ZulDrak_03",
"side": "",
"obtainable": true
},
{
"id": "1269",
"icon": "Achievement_Zone_StormPeaks_01",
"side": "",
"obtainable": true
},
{
"id": "1270",
"icon": "Achievement_Zone_IceCrown_01",
"side": "",
"obtainable": true
},
{
"id": "2256",
"icon": "Achievement_Zone_StormPeaks_03",
"side": "",
"obtainable": true
},
{
"id": "2257",
"icon": "Achievement_Zone_DragonBlight_09",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Outland",
"zones": [
{
"name": "",
"achs": [
{
"id": "862",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "",
"obtainable": true
},
{
"id": "863",
"icon": "Achievement_Zone_Zangarmarsh",
"side": "",
"obtainable": true
},
{
"id": "867",
"icon": "Achievement_Zone_Terrokar",
"side": "",
"obtainable": true
},
{
"id": "866",
"icon": "Achievement_Zone_Nagrand_01",
"side": "",
"obtainable": true
},
{
"id": "865",
"icon": "Achievement_Zone_BladesEdgeMtns_01",
"side": "",
"obtainable": true
},
{
"id": "843",
"icon": "Achievement_Zone_Netherstorm_01",
"side": "",
"obtainable": true
},
{
"id": "864",
"icon": "Achievement_Zone_Shadowmoon",
"side": "",
"obtainable": true
},
{
"id": "1311",
"icon": "Spell_Shadow_DeathScream",
"side": "",
"obtainable": true
},
{
"id": "1312",
"icon": "Spell_Shadow_DeathScream",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Eastern Kingdoms",
"zones": [
{
"name": "",
"achs": [
{
"id": "868",
"icon": "Achievement_Zone_IsleOfQuelDanas",
"side": "",
"obtainable": true
},
{
"id": "859",
"icon": "Achievement_Zone_EversongWoods",
"side": "",
"obtainable": true
},
{
"id": "858",
"icon": "Achievement_Zone_Ghostlands",
"side": "",
"obtainable": true
},
{
"id": "771",
"icon": "Achievement_Zone_EasternPlaguelands",
"side": "",
"obtainable": true
},
{
"id": "770",
"icon": "Achievement_Zone_WesternPlaguelands_01",
"side": "",
"obtainable": true
},
{
"id": "768",
"icon": "Achievement_Zone_TirisfalGlades_01",
"side": "",
"obtainable": true
},
{
"id": "769",
"icon": "Achievement_Zone_Silverpine_01",
"side": "",
"obtainable": true
},
{
"id": "772",
"icon": "Achievement_Zone_HillsbradFoothills",
"side": "",
"obtainable": true
},
{
"id": "761",
"icon": "Achievement_Zone_ArathiHighlands_01",
"side": "",
"obtainable": true
},
{
"id": "773",
"icon": "Achievement_Zone_Hinterlands_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "",
"achs": [
{
"id": "841",
"icon": "Achievement_Zone_Wetlands_01",
"side": "",
"obtainable": true
},
{
"id": "627",
"icon": "Achievement_Zone_DunMorogh",
"side": "",
"obtainable": true
},
{
"id": "779",
"icon": "Achievement_Zone_LochModan",
"side": "",
"obtainable": true
},
{
"id": "765",
"icon": "Achievement_Zone_Badlands_01",
"side": "",
"obtainable": true
},
{
"id": "774",
"icon": "Achievement_Zone_SearingGorge_01",
"side": "",
"obtainable": true
},
{
"id": "775",
"icon": "Achievement_Zone_BurningSteppes_01",
"side": "",
"obtainable": true
},
{
"id": "776",
"icon": "Achievement_Zone_ElwynnForest",
"side": "",
"obtainable": true
},
{
"id": "780",
"icon": "Achievement_Zone_RedridgeMountains",
"side": "",
"obtainable": true
},
{
"id": "782",
"icon": "Achievement_Zone_SwampSorrows_01",
"side": "",
"obtainable": true
},
{
"id": "777",
"icon": "Achievement_Zone_DeadwindPass",
"side": "",
"obtainable": true
},
{
"id": "778",
"icon": "Achievement_Zone_Duskwood",
"side": "",
"obtainable": true
},
{
"id": "802",
"icon": "Achievement_Zone_WestFall_01",
"side": "",
"obtainable": true
},
{
"id": "781",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4995",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "766",
"icon": "Achievement_Zone_BlastedLands_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Kalimdor",
"zones": [
{
"name": "",
"achs": [
{
"id": "842",
"icon": "Achievement_Zone_Darnassus",
"side": "",
"obtainable": true
},
{
"id": "861",
"icon": "Achievement_Zone_BloodmystIsle_01",
"side": "",
"obtainable": true
},
{
"id": "860",
"icon": "Achievement_Zone_AzuremystIsle_01",
"side": "",
"obtainable": true
},
{
"id": "844",
"icon": "Achievement_Zone_Darkshore_01",
"side": "",
"obtainable": true
},
{
"id": "855",
"icon": "Spell_Arcane_TeleportMoonglade",
"side": "",
"obtainable": true
},
{
"id": "857",
"icon": "Achievement_Zone_Winterspring",
"side": "",
"obtainable": true
},
{
"id": "853",
"icon": "Achievement_Zone_Felwood",
"side": "",
"obtainable": true
},
{
"id": "845",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "",
"obtainable": true
},
{
"id": "852",
"icon": "Achievement_Zone_Azshara_01",
"side": "",
"obtainable": true
},
{
"id": "728",
"icon": "Achievement_Zone_Durotar",
"side": "",
"obtainable": true
},
{
"id": "847",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "",
"obtainable": true
},
{
"id": "750",
"icon": "Achievement_Zone_Barrens_01",
"side": "",
"obtainable": true
},
{
"id": "4996",
"icon": "Achievement_Zone_Barrens_01",
"side": "",
"obtainable": true
},
{
"id": "848",
"icon": "Achievement_Zone_Desolace",
"side": "",
"obtainable": true
},
{
"id": "849",
"icon": "Achievement_Zone_Feralas",
"side": "",
"obtainable": true
},
{
"id": "736",
"icon": "Achievement_Zone_Mulgore_01",
"side": "",
"obtainable": true
},
{
"id": "850",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "",
"obtainable": true
},
{
"id": "846",
"icon": "Achievement_Zone_ThousandNeedles_01",
"side": "",
"obtainable": true
},
{
"id": "851",
"icon": "Achievement_Zone_Tanaris_01",
"side": "",
"obtainable": true
},
{
"id": "854",
"icon": "Achievement_Zone_UnGoroCrater_01",
"side": "",
"obtainable": true
},
{
"id": "856",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "World Events",
"cats": [
{
"name": "World Events",
"zones": [
{
"name": "",
"achs": [
{
"id": "913",
"icon": "Achievement_WorldEvent_Lunar",
"side": "",
"obtainable": true
},
{
"id": "1693",
"icon": "Achievement_WorldEvent_Valentine",
"side": "",
"obtainable": true
},
{
"id": "2798",
"icon": "INV_Egg_09",
"side": "",
"obtainable": true
},
{
"id": "1793",
"icon": "INV_Misc_Toy_04",
"side": "",
"obtainable": true
},
{
"id": "1039",
"icon": "INV_SummerFest_Symbol_Low",
"side": "H",
"obtainable": true
},
{
"id": "1038",
"icon": "INV_SummerFest_Symbol_High",
"side": "A",
"obtainable": true
},
{
"id": "3457",
"icon": "INV_Helmet_66",
"side": "",
"obtainable": true
},
{
"id": "1656",
"icon": "Achievement_Halloween_Witch_01",
"side": "",
"obtainable": true
},
{
"id": "3456",
"icon": "inv_misc_bone_humanskull_02",
"side": "",
"obtainable": true
},
{
"id": "3478",
"icon": "inv_thanksgiving_turkey",
"side": "",
"obtainable": true
},
{
"id": "1691",
"icon": "Achievement_WorldEvent_Merrymaker",
"side": "",
"obtainable": true
},
{
"id": "2144",
"icon": "Achievement_BG_masterofallBGs",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lunar Festival",
"zones": [
{
"name": "Elders",
"achs": [
{
"id": "915",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "914",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "910",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "912",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "911",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "1396",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "6006",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
}
]
},
{
"name": "Coins",
"achs": [
{
"id": "605",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "606",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "607",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "608",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "609",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "937",
"icon": "Spell_Holy_Aspiration",
"side": "",
"obtainable": true
},
{
"id": "626",
"icon": "INV_Chest_Cloth_59",
"side": "",
"obtainable": true
},
{
"id": "1552",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "1281",
"icon": "INV_Misc_MissileLarge_Red",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Love is in the Air",
"zones": [
{
"name": "",
"achs": [
{
"id": "1698",
"icon": "INV_ValentinesCard02",
"side": "H",
"obtainable": true
},
{
"id": "1697",
"icon": "INV_ValentinesCard02",
"side": "A",
"obtainable": true
},
{
"id": "1700",
"icon": "INV_Ammo_Arrow_02",
"side": "",
"obtainable": true
},
{
"id": "1188",
"icon": "INV_Ammo_Arrow_02",
"side": "",
"obtainable": true
},
{
"id": "1702",
"icon": "INV_ValentinesChocolate02",
"side": "",
"obtainable": true
},
{
"id": "4624",
"icon": "INV_Misc_Head_Undead_01",
"side": "",
"obtainable": true
},
{
"id": "1696",
"icon": "INV_ValentinePinkRocket",
"side": "",
"obtainable": true
},
{
"id": "1703",
"icon": "INV_RoseBouquet01",
"side": "",
"obtainable": true
},
{
"id": "1694",
"icon": "INV_Chest_Cloth_50",
"side": "",
"obtainable": true
},
{
"id": "1699",
"icon": "INV_Misc_Dust_04",
"side": "",
"obtainable": true
},
{
"id": "1695",
"icon": "Spell_BrokenHeart",
"side": "",
"obtainable": true
},
{
"id": "260",
"icon": "inv_jewelry_necklace_43",
"side": "",
"obtainable": true
},
{
"id": "1279",
"icon": "INV_ValentinePerfumeBottle",
"side": "A",
"obtainable": true
},
{
"id": "1280",
"icon": "INV_ValentinePerfumeBottle",
"side": "H",
"obtainable": true
},
{
"id": "1291",
"icon": "INV_Misc_Basket_01",
"side": "",
"obtainable": true
},
{
"id": "1704",
"icon": "INV_Crate_03",
"side": "",
"obtainable": true
},
{
"id": "1701",
"icon": "INV_ValentinesCandy",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Noblegarden",
"zones": [
{
"name": "",
"achs": [
{
"id": "2417",
"icon": "Achievement_Noblegarden_Chocolate_Egg",
"side": "",
"obtainable": true
},
{
"id": "2418",
"icon": "Achievement_Noblegarden_Chocolate_Egg",
"side": "",
"obtainable": true
},
{
"id": "2419",
"icon": "INV_Egg_09",
"side": "A",
"obtainable": true
},
{
"id": "2422",
"icon": "INV_Misc_Flower_02",
"side": "",
"obtainable": true
},
{
"id": "2497",
"icon": "INV_Egg_09",
"side": "H",
"obtainable": true
},
{
"id": "248",
"icon": "INV_Shirt_08",
"side": "",
"obtainable": true
},
{
"id": "2421",
"icon": "INV_Egg_06",
"side": "A",
"obtainable": true
},
{
"id": "2420",
"icon": "INV_Egg_06",
"side": "H",
"obtainable": true
},
{
"id": "2676",
"icon": "INV_Egg_09",
"side": "",
"obtainable": true
},
{
"id": "2436",
"icon": "Spell_Shaman_GiftEarthmother",
"side": "",
"obtainable": true
},
{
"id": "249",
"icon": "INV_Chest_Cloth_04",
"side": "",
"obtainable": true
},
{
"id": "2416",
"icon": "INV_Egg_07",
"side": "",
"obtainable": true
},
{
"id": "2576",
"icon": "Spell_Shadow_SoothingKiss",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Children's Week",
"zones": [
{
"name": "",
"achs": [
{
"id": "1790",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_02",
"side": "",
"obtainable": true
},
{
"id": "1786",
"icon": "Ability_Hunter_BeastCall02",
"side": "",
"obtainable": true
},
{
"id": "1791",
"icon": "INV_Misc_Rune_01",
"side": "",
"obtainable": true
},
{
"id": "1788",
"icon": "INV_Misc_Food_31",
"side": "",
"obtainable": true
},
{
"id": "1789",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "1792",
"icon": "Ability_Hunter_Pet_Turtle",
"side": "",
"obtainable": true
},
{
"id": "275",
"icon": "INV_Misc_Toy_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Midsummer",
"zones": [
{
"name": "Desecrate",
"achs": [
{
"id": "1028",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "1031",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1029",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "1032",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1033",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1030",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6010",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "6007",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6013",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6014",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1037",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1035",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "8042",
"icon": "spell_fire_masterofelements",
"side": "A",
"obtainable": true
},
{
"id": "8043",
"icon": "spell_fire_masterofelements",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Honor",
"achs": [
{
"id": "1022",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1025",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "1026",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "1023",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1024",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1027",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6008",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "6009",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6012",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6011",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1036",
"icon": "Spell_Fire_Fireball",
"side": "H",
"obtainable": true
},
{
"id": "1034",
"icon": "Spell_Fire_Fireball",
"side": "A",
"obtainable": true
},
{
"id": "8044",
"icon": "inv_summerfest_firespirit",
"side": "H",
"obtainable": true
},
{
"id": "8045",
"icon": "inv_summerfest_firespirit",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "272",
"icon": "INV_Torch_Thrown",
"side": "",
"obtainable": true
},
{
"id": "263",
"icon": "Spell_Frost_SummonWaterElemental",
"side": "",
"obtainable": true
},
{
"id": "1145",
"icon": "INV_Helmet_08",
"side": "",
"obtainable": true
},
{
"id": "271",
"icon": "Ability_Mage_FireStarter",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Brewfest",
"zones": [
{
"name": "",
"achs": [
{
"id": "1203",
"icon": "INV_Drink_08",
"side": "H",
"obtainable": true
},
{
"id": "1185",
"icon": "INV_Holiday_BeerfestPretzel01",
"side": "",
"obtainable": true
},
{
"id": "295",
"icon": "INV_Misc_Head_Dwarf_01",
"side": "",
"obtainable": true
},
{
"id": "293",
"icon": "INV_Misc_Beer_01",
"side": "",
"obtainable": true
},
{
"id": "1184",
"icon": "INV_Drink_08",
"side": "A",
"obtainable": true
},
{
"id": "303",
"icon": "INV_Cask_01",
"side": "",
"obtainable": true
},
{
"id": "1936",
"icon": "INV_Drink_13",
"side": "",
"obtainable": true
},
{
"id": "1186",
"icon": "INV_Ore_Mithril_01",
"side": "",
"obtainable": true
},
{
"id": "1260",
"icon": "INV_Cask_02",
"side": "",
"obtainable": true
},
{
"id": "2796",
"icon": "INV_MISC_BEER_02",
"side": "",
"obtainable": true
},
{
"id": "1183",
"icon": "INV_Holiday_BrewfestBuff_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Hallow's End",
"zones": [
{
"name": "Tricks and Treats",
"achs": [
{
"id": "966",
"icon": "INV_Misc_Food_27",
"side": "A",
"obtainable": true
},
{
"id": "967",
"icon": "INV_Misc_Food_27",
"side": "H",
"obtainable": true
},
{
"id": "965",
"icon": "Achievement_Halloween_Candy_01",
"side": "H",
"obtainable": true
},
{
"id": "963",
"icon": "Achievement_Halloween_Candy_01",
"side": "A",
"obtainable": true
},
{
"id": "968",
"icon": "INV_Misc_Food_29",
"side": "H",
"obtainable": true
},
{
"id": "969",
"icon": "INV_Misc_Food_29",
"side": "A",
"obtainable": true
},
{
"id": "971",
"icon": "INV_Misc_Food_28",
"side": "A",
"obtainable": true
},
{
"id": "970",
"icon": "INV_Misc_Food_28",
"side": "H",
"obtainable": true
},
{
"id": "5835",
"icon": "INV_MISC_FOOD_26",
"side": "H",
"obtainable": true
},
{
"id": "5836",
"icon": "INV_MISC_FOOD_26",
"side": "A",
"obtainable": true
},
{
"id": "5837",
"icon": "INV_Misc_Food_25",
"side": "A",
"obtainable": true
},
{
"id": "5838",
"icon": "INV_Misc_Food_25",
"side": "H",
"obtainable": true
},
{
"id": "7601",
"icon": "inv_misc_food_168_ricecake01",
"side": "A",
"obtainable": true
},
{
"id": "7602",
"icon": "inv_misc_food_168_ricecake01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "972",
"icon": "INV_Misc_Food_30",
"side": "",
"obtainable": true
},
{
"id": "288",
"icon": "Spell_Shadow_PlagueCloud",
"side": "",
"obtainable": true
},
{
"id": "1040",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "A",
"obtainable": true
},
{
"id": "1261",
"icon": "Ability_Warrior_Rampage",
"side": "",
"obtainable": true
},
{
"id": "291",
"icon": "INV_Misc_Bag_28_Halloween",
"side": "",
"obtainable": true
},
{
"id": "255",
"icon": "INV_Misc_Food_59",
"side": "",
"obtainable": true
},
{
"id": "1041",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "H",
"obtainable": true
},
{
"id": "292",
"icon": "Achievement_Halloween_Cat_01",
"side": "",
"obtainable": true
},
{
"id": "289",
"icon": "Achievement_Halloween_Bat_01",
"side": "",
"obtainable": true
},
{
"id": "283",
"icon": "Achievement_Halloween_Ghost_01",
"side": "",
"obtainable": true
},
{
"id": "979",
"icon": "INV_Mask_06",
"side": "",
"obtainable": true
},
{
"id": "981",
"icon": "Achievement_Halloween_Smiley_01",
"side": "",
"obtainable": true
},
{
"id": "284",
"icon": "INV_Mask_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pilgrim's Bounty",
"zones": [
{
"name": "",
"achs": [
{
"id": "3558",
"icon": "Spell_Holy_LayOnHands",
"side": "",
"obtainable": true
},
{
"id": "3582",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "3578",
"icon": "Ability_Hunter_SilentHunter",
"side": "",
"obtainable": true
},
{
"id": "3559",
"icon": "INV_Torch_Unlit",
"side": "",
"obtainable": true
},
{
"id": "3597",
"icon": "inv_helmet_65",
"side": "H",
"obtainable": true
},
{
"id": "3596",
"icon": "inv_helmet_65",
"side": "A",
"obtainable": true
},
{
"id": "3577",
"icon": "Achievement_Profession_ChefHat",
"side": "H",
"obtainable": true
},
{
"id": "3576",
"icon": "Achievement_Profession_ChefHat",
"side": "A",
"obtainable": true
},
{
"id": "3556",
"icon": "INV_Misc_Organ_10",
"side": "A",
"obtainable": true
},
{
"id": "3557",
"icon": "INV_Misc_Organ_10",
"side": "H",
"obtainable": true
},
{
"id": "3580",
"icon": "INV_BannerPVP_01",
"side": "A",
"obtainable": true
},
{
"id": "3581",
"icon": "INV_BannerPVP_02",
"side": "H",
"obtainable": true
},
{
"id": "3579",
"icon": "Ability_Warrior_BattleShout",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Winter Veil",
"zones": [
{
"name": "",
"achs": [
{
"id": "273",
"icon": "Achievement_WorldEvent_Reindeer",
"side": "",
"obtainable": true
},
{
"id": "1687",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "1689",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "259",
"icon": "INV_Ammo_Snowball",
"side": "H",
"obtainable": true
},
{
"id": "1255",
"icon": "INV_Ammo_Snowball",
"side": "A",
"obtainable": true
},
{
"id": "252",
"icon": "Achievement_WorldEvent_LittleHelper",
"side": "",
"obtainable": true
},
{
"id": "1688",
"icon": "INV_Misc_Food_62",
"side": "",
"obtainable": true
},
{
"id": "279",
"icon": "INV_Helmet_68",
"side": "",
"obtainable": true
},
{
"id": "1282",
"icon": "Achievement_WorldEvent_XmasOgre",
"side": "",
"obtainable": true
},
{
"id": "1295",
"icon": "INV_Gizmo_GoblingTonkController",
"side": "",
"obtainable": true
},
{
"id": "5854",
"icon": "Spell_Holy_DivineHymn",
"side": "H",
"obtainable": true
},
{
"id": "5853",
"icon": "Spell_Holy_DivineHymn",
"side": "A",
"obtainable": true
},
{
"id": "1690",
"icon": "Spell_Frost_FrostWard",
"side": "",
"obtainable": true
},
{
"id": "4436",
"icon": "INV_Weapon_Rifle_01",
"side": "A",
"obtainable": true
},
{
"id": "4437",
"icon": "INV_Weapon_Rifle_01",
"side": "H",
"obtainable": true
},
{
"id": "1686",
"icon": "INV_Misc_Herb_09",
"side": "A",
"obtainable": true
},
{
"id": "1685",
"icon": "INV_Misc_Herb_09",
"side": "H",
"obtainable": true
},
{
"id": "277",
"icon": "INV_Food_ChristmasFruitCake_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Argent Tournament",
"zones": [
{
"name": "Champion",
"achs": [
{
"id": "2781",
"icon": "inv_misc_tournaments_symbol_human",
"side": "A",
"obtainable": true
},
{
"id": "2780",
"icon": "inv_misc_tournaments_symbol_dwarf",
"side": "A",
"obtainable": true
},
{
"id": "2779",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "2777",
"icon": "inv_misc_tournaments_symbol_nightelf",
"side": "A",
"obtainable": true
},
{
"id": "2778",
"icon": "inv_misc_tournaments_symbol_draenei",
"side": "A",
"obtainable": true
},
{
"id": "2782",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2783",
"icon": "inv_misc_tournaments_symbol_orc",
"side": "H",
"obtainable": true
},
{
"id": "2784",
"icon": "inv_misc_tournaments_symbol_troll",
"side": "H",
"obtainable": true
},
{
"id": "2786",
"icon": "inv_misc_tournaments_symbol_tauren",
"side": "H",
"obtainable": true
},
{
"id": "2787",
"icon": "inv_misc_tournaments_symbol_scourge",
"side": "H",
"obtainable": true
},
{
"id": "2785",
"icon": "inv_misc_tournaments_symbol_bloodelf",
"side": "H",
"obtainable": true
},
{
"id": "2788",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Exalted Champion",
"achs": [
{
"id": "2764",
"icon": "inv_misc_tournaments_symbol_human",
"side": "A",
"obtainable": true
},
{
"id": "2763",
"icon": "inv_misc_tournaments_symbol_dwarf",
"side": "A",
"obtainable": true
},
{
"id": "2762",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "2760",
"icon": "inv_misc_tournaments_symbol_nightelf",
"side": "A",
"obtainable": true
},
{
"id": "2761",
"icon": "inv_misc_tournaments_symbol_draenei",
"side": "A",
"obtainable": true
},
{
"id": "2770",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2817",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2765",
"icon": "inv_misc_tournaments_symbol_orc",
"side": "H",
"obtainable": true
},
{
"id": "2766",
"icon": "inv_misc_tournaments_symbol_troll",
"side": "H",
"obtainable": true
},
{
"id": "2768",
"icon": "inv_misc_tournaments_symbol_tauren",
"side": "H",
"obtainable": true
},
{
"id": "2769",
"icon": "inv_misc_tournaments_symbol_scourge",
"side": "H",
"obtainable": true
},
{
"id": "2767",
"icon": "inv_misc_tournaments_symbol_bloodelf",
"side": "H",
"obtainable": true
},
{
"id": "2771",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
},
{
"id": "2816",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "3677",
"icon": "inv_elemental_primal_nether",
"side": "H",
"obtainable": true
},
{
"id": "2772",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "4596",
"icon": "inv_sword_155",
"side": "",
"obtainable": true
},
{
"id": "3736",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "2836",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "2773",
"icon": "INV_Helmet_44",
"side": "",
"obtainable": true
},
{
"id": "2756",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "2758",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3676",
"icon": "INV_Elemental_Primal_Mana",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Darkmoon Faire",
"zones": [
{
"name": "",
"achs": [
{
"id": "6025",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "6026",
"icon": "INV_Misc_Food_60",
"side": "",
"obtainable": true
},
{
"id": "6022",
"icon": "INV_Ammo_Bullet_01",
"side": "",
"obtainable": true
},
{
"id": "6020",
"icon": "inv_misc_token_darkmoon_01",
"side": "",
"obtainable": true
},
{
"id": "6031",
"icon": "inv_misc_missilesmallcluster_green",
"side": "H",
"obtainable": true
},
{
"id": "6030",
"icon": "inv_misc_missilesmallcluster_green",
"side": "A",
"obtainable": true
},
{
"id": "6032",
"icon": "inv_misc_book_16",
"side": "",
"obtainable": true
},
{
"id": "6019",
"icon": "INV_Misc_Ticket_Darkmoon_01",
"side": "",
"obtainable": true
},
{
"id": "6028",
"icon": "INV_BannerPVP_03",
"side": "",
"obtainable": true
},
{
"id": "6027",
"icon": "INV_Misc_Book_06",
"side": "",
"obtainable": true
},
{
"id": "6029",
"icon": "trade_archaeology_dwarf_runestone",
"side": "",
"obtainable": true
},
{
"id": "6021",
"icon": "Ability_Hunter_MasterMarksman",
"side": "",
"obtainable": true
},
{
"id": "6332",
"icon": "inv_misc_rabbit",
"side": "",
"obtainable": true
},
{
"id": "6023",
"icon": "inv_misc_bone_skull_01",
"side": "",
"obtainable": true
},
{
"id": "6024",
"icon": "Spell_Shadow_Skull",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Brawler's Guild",
"zones": [
{
"name": "",
"achs": [
{
"id": "7947",
"icon": "spell_holy_silence",
"side": "A",
"obtainable": true
},
{
"id": "7948",
"icon": "spell_holy_silence",
"side": "H",
"obtainable": true
},
{
"id": "7937",
"icon": "inv_pants_plate_05",
"side": "A",
"obtainable": true
},
{
"id": "8020",
"icon": "inv_pants_plate_05",
"side": "H",
"obtainable": true
},
{
"id": "7940",
"icon": "inv_misc_bandage_05",
"side": "A",
"obtainable": true
},
{
"id": "7939",
"icon": "inv_misc_bandage_05",
"side": "H",
"obtainable": true
},
{
"id": "7941",
"icon": "spell_holy_fistofjustice",
"side": "A",
"obtainable": true
},
{
"id": "7942",
"icon": "spell_holy_fistofjustice",
"side": "H",
"obtainable": true
},
{
"id": "7946",
"icon": "spell_holy_fistofjustice",
"side": "A",
"obtainable": true
},
{
"id": "8022",
"icon": "spell_holy_fistofjustice",
"side": "H",
"obtainable": true
},
{
"id": "7949",
"icon": "ability_warrior_battleshout",
"side": "A",
"obtainable": true
},
{
"id": "7950",
"icon": "inv_misc_bandage_05",
"side": "H",
"obtainable": true
},
{
"id": "7943",
"icon": "thumbup",
"side": "",
"obtainable": true
},
{
"id": "7944",
"icon": "inv_drink_29_sunkissedwine",
"side": "",
"obtainable": true
},
{
"id": "7945",
"icon": "spell_shaman_spiritwalkersgrace",
"side": "",
"obtainable": true
},
{
"id": "8342",
"icon": "inv_inscription_tarot_volcanocard",
"side": "H",
"obtainable": true
},
{
"id": "8339",
"icon": "inv_inscription_tarot_volcanocard",
"side": "A",
"obtainable": true
},
{
"id": "8340",
"icon": "inv_inscription_tarot_volcanocard",
"side": "A",
"obtainable": true
},
{
"id": "8343",
"icon": "inv_inscription_tarot_volcanocard",
"side": "H",
"obtainable": true
},
{
"id": "8337",
"icon": "warrior_talent_icon_furyintheblood",
"side": "H",
"obtainable": true
},
{
"id": "8335",
"icon": "warrior_talent_icon_furyintheblood",
"side": "A",
"obtainable": true
},
{
"id": "8338",
"icon": "pandarenracial_quiveringpain",
"side": "H",
"obtainable": true
},
{
"id": "8336",
"icon": "pandarenracial_quiveringpain",
"side": "A",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Feats of Strength",
"cats": [
{
"name": "Feats of Strength",
"zones": [
{
"name": "Realm First!",
"achs": [
{
"id": "1416",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "1419",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "1415",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "1420",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "5395",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "1414",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "1417",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "1418",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "1421",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "1423",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "1424",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "1425",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "1422",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "1426",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "1427",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6433",
"icon": "achievement_challengemode_gold",
"side": "",
"obtainable": true
},
{
"id": "457",
"icon": "Achievement_Level_80",
"side": "",
"obtainable": true
},
{
"id": "4999",
"icon": "achievement_level_85",
"side": "",
"obtainable": true
},
{
"id": "6524",
"icon": "achievement_level_90",
"side": "",
"obtainable": true
},
{
"id": "1405",
"icon": "Achievement_Character_Bloodelf_Female",
"side": "",
"obtainable": true
},
{
"id": "1406",
"icon": "Achievement_Character_Draenei_Female",
"side": "",
"obtainable": true
},
{
"id": "1407",
"icon": "Achievement_Character_Dwarf_Male",
"side": "",
"obtainable": true
},
{
"id": "1413",
"icon": "Achievement_Character_Undead_Male",
"side": "",
"obtainable": true
},
{
"id": "1404",
"icon": "Achievement_Character_Gnome_Male",
"side": "",
"obtainable": true
},
{
"id": "1408",
"icon": "Achievement_Character_Human_Female",
"side": "",
"obtainable": true
},
{
"id": "1409",
"icon": "Achievement_Character_Nightelf_Male",
"side": "",
"obtainable": true
},
{
"id": "1410",
"icon": "Achievement_Character_Orc_Male",
"side": "",
"obtainable": true
},
{
"id": "1411",
"icon": "Achievement_Character_Tauren_Female",
"side": "",
"obtainable": true
},
{
"id": "1412",
"icon": "Achievement_Character_Troll_Male",
"side": "",
"obtainable": true
},
{
"id": "461",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "5005",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "6748",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "466",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "5000",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "6743",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "462",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "5004",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "6747",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "460",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "5006",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "6749",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "465",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "5001",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "6744",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "464",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "5002",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "6745",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "458",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "5008",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "6751",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "467",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "4998",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "6523",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "463",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "5003",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "6746",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "459",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "5007",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "6750",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "6752",
"icon": "class_monk",
"side": "",
"obtainable": true
},
{
"id": "1463",
"icon": "Spell_Misc_HellifrePVPCombatMorale",
"side": "",
"obtainable": true
},
{
"id": "1402",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "456",
"icon": "Achievement_Dungeon_CoABlackDragonflight_25man",
"side": "",
"obtainable": true
},
{
"id": "1400",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "3117",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3259",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "4078",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "4576",
"icon": "inv_helmet_96",
"side": "",
"obtainable": true
},
{
"id": "5383",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "6861",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "5386",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "6864",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "5387",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "6865",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "5381",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "6859",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "5396",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "6873",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "5382",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "6860",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "5384",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "6862",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "5385",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "6863",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "5388",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "6866",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "5390",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "6868",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "5391",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "6869",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "5392",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "6870",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "5389",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "6867",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "5393",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "6871",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "5394",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6872",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6829",
"icon": "trade_archaeology_highborne_scroll",
"side": "",
"obtainable": true
}
]
},
{
"name": "PVP",
"achs": [
{
"id": "442",
"icon": "Achievement_PVP_A_01",
"side": "A",
"obtainable": true
},
{
"id": "470",
"icon": "Achievement_PVP_A_02",
"side": "A",
"obtainable": true
},
{
"id": "471",
"icon": "Achievement_PVP_A_03",
"side": "A",
"obtainable": true
},
{
"id": "441",
"icon": "Achievement_PVP_A_04",
"side": "A",
"obtainable": true
},
{
"id": "440",
"icon": "Achievement_PVP_A_05",
"side": "A",
"obtainable": true
},
{
"id": "439",
"icon": "Achievement_PVP_A_06",
"side": "A",
"obtainable": true
},
{
"id": "472",
"icon": "Achievement_PVP_A_07",
"side": "A",
"obtainable": true
},
{
"id": "438",
"icon": "Achievement_PVP_A_08",
"side": "A",
"obtainable": true
},
{
"id": "437",
"icon": "Achievement_PVP_A_09",
"side": "A",
"obtainable": true
},
{
"id": "436",
"icon": "Achievement_PVP_A_10",
"side": "A",
"obtainable": true
},
{
"id": "435",
"icon": "Achievement_PVP_A_11",
"side": "A",
"obtainable": true
},
{
"id": "473",
"icon": "Achievement_PVP_A_12",
"side": "A",
"obtainable": true
},
{
"id": "434",
"icon": "Achievement_PVP_A_13",
"side": "A",
"obtainable": true
},
{
"id": "433",
"icon": "Achievement_PVP_A_14",
"side": "A",
"obtainable": true
},
{
"id": "454",
"icon": "Achievement_PVP_H_01",
"side": "H",
"obtainable": true
},
{
"id": "468",
"icon": "Achievement_PVP_H_02",
"side": "H",
"obtainable": true
},
{
"id": "453",
"icon": "Achievement_PVP_H_03",
"side": "H",
"obtainable": true
},
{
"id": "450",
"icon": "Achievement_PVP_H_04",
"side": "H",
"obtainable": true
},
{
"id": "452",
"icon": "Achievement_PVP_H_05",
"side": "H",
"obtainable": true
},
{
"id": "451",
"icon": "Achievement_PVP_H_06",
"side": "H",
"obtainable": true
},
{
"id": "449",
"icon": "Achievement_PVP_H_07",
"side": "H",
"obtainable": true
},
{
"id": "469",
"icon": "Achievement_PVP_H_08",
"side": "H",
"obtainable": true
},
{
"id": "448",
"icon": "Achievement_PVP_H_09",
"side": "H",
"obtainable": true
},
{
"id": "447",
"icon": "Achievement_PVP_H_10",
"side": "H",
"obtainable": true
},
{
"id": "444",
"icon": "Achievement_PVP_H_11",
"side": "H",
"obtainable": true
},
{
"id": "446",
"icon": "Achievement_PVP_H_12",
"side": "H",
"obtainable": true
},
{
"id": "445",
"icon": "Achievement_PVP_H_13",
"side": "H",
"obtainable": true
},
{
"id": "443",
"icon": "Achievement_PVP_H_14",
"side": "H",
"obtainable": true
},
{
"id": "418",
"icon": "Achievement_FeatsOfStrength_Gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "419",
"icon": "Achievement_FeatsOfStrength_Gladiator_02",
"side": "",
"obtainable": true
},
{
"id": "420",
"icon": "Achievement_FeatsOfStrength_Gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "3336",
"icon": "Achievement_FeatsOfStrength_Gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "3436",
"icon": "Achievement_FeatsOfStrength_Gladiator_05",
"side": "",
"obtainable": true
},
{
"id": "3758",
"icon": "Achievement_FeatsOfStrength_Gladiator_06",
"side": "",
"obtainable": true
},
{
"id": "4599",
"icon": "Achievement_FeatsOfStrength_Gladiator_07",
"side": "",
"obtainable": true
},
{
"id": "6002",
"icon": "achievement_featsofstrength_gladiator_09",
"side": "",
"obtainable": true
},
{
"id": "6124",
"icon": "Achievement_FeatsOfStrength_Gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "6938",
"icon": "achievement_featsofstrength_gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "3618",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "8214",
"icon": "achievement_featsofstrength_gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "8243",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "8244",
"icon": "achievement_pvp_h_h",
"side": "H",
"obtainable": true
},
{
"id": "8392",
"icon": "inv_helmet_plate_pvpwarrior_e_01",
"side": "",
"obtainable": true
},
{
"id": "8391",
"icon": "inv_spear_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mounts",
"achs": [
{
"id": "879",
"icon": "Ability_Mount_MountainRam",
"side": "",
"obtainable": true
},
{
"id": "886",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "887",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "888",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "2316",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "3096",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "3756",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "3757",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "4600",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "6003",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6321",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6322",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6741",
"icon": "ability_mount_drake_twilight",
"side": "",
"obtainable": true
},
{
"id": "424",
"icon": "INV_Misc_QirajiCrystal_02",
"side": "",
"obtainable": true
},
{
"id": "729",
"icon": "Ability_Mount_Undeadhorse",
"side": "",
"obtainable": true
},
{
"id": "880",
"icon": "Ability_Mount_JungleTiger",
"side": "",
"obtainable": true
},
{
"id": "881",
"icon": "Ability_Mount_Raptor",
"side": "",
"obtainable": true
},
{
"id": "882",
"icon": "Ability_Mount_Dreadsteed",
"side": "",
"obtainable": true
},
{
"id": "883",
"icon": "INV-Mount_Raven_54",
"side": "",
"obtainable": true
},
{
"id": "884",
"icon": "Ability_Mount_CockatriceMountElite_Green",
"side": "",
"obtainable": true
},
{
"id": "430",
"icon": "Ability_Druid_ChallangingRoar",
"side": "",
"obtainable": true
},
{
"id": "885",
"icon": "Inv_Misc_SummerFest_BrazierOrange",
"side": "",
"obtainable": true
},
{
"id": "980",
"icon": "INV_Belt_12",
"side": "",
"obtainable": true
},
{
"id": "2081",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "2357",
"icon": "Ability_Mount_Dreadsteed",
"side": "",
"obtainable": true
},
{
"id": "3356",
"icon": "Ability_Mount_PinkTiger",
"side": "A",
"obtainable": true
},
{
"id": "3357",
"icon": "Ability_Hunter_Pet_Raptor",
"side": "H",
"obtainable": true
},
{
"id": "3496",
"icon": "INV_Cask_01",
"side": "",
"obtainable": true
},
{
"id": "4626",
"icon": "INV_Misc_EngGizmos_03",
"side": "",
"obtainable": true
},
{
"id": "4625",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "4627",
"icon": "INV_ValentinePinkRocket",
"side": "",
"obtainable": true
},
{
"id": "5767",
"icon": "ability_mount_camel_gray",
"side": "",
"obtainable": true
},
{
"id": "1436",
"icon": "Ability_Mount_Charger",
"side": "",
"obtainable": true
},
{
"id": "4832",
"icon": "ability_mount_rocketmount2",
"side": "",
"obtainable": true
},
{
"id": "8092",
"icon": "inv_misc_bone_01",
"side": "",
"obtainable": true
},
{
"id": "8213",
"icon": "inv_misc_reforgedarchstone_01",
"side": "",
"obtainable": true
},
{
"id": "8216",
"icon": "inv_pandarenserpentmount_white",
"side": "",
"obtainable": true
},
{
"id": "8345",
"icon": "inv_pegasusmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lost Content",
"achs": [
{
"id": "957",
"icon": "INV_Bijou_Green",
"side": "",
"obtainable": true
},
{
"id": "2496",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "560",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "691",
"icon": "Achievement_Boss_Zuljin",
"side": "",
"obtainable": true
},
{
"id": "688",
"icon": "Achievement_Boss_Hakkar",
"side": "",
"obtainable": true
},
{
"id": "2018",
"icon": "Spell_Arcane_FocusedPower",
"side": "",
"obtainable": true
},
{
"id": "2359",
"icon": "Ability_Druid_FlightForm",
"side": "",
"obtainable": true
},
{
"id": "5533",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "16",
"icon": "Ability_Warrior_SecondWind",
"side": "",
"obtainable": true
},
{
"id": "705",
"icon": "Ability_Warrior_OffensiveStance",
"side": "",
"obtainable": true
},
{
"id": "432",
"icon": "INV_Mace_51",
"side": "",
"obtainable": true
},
{
"id": "431",
"icon": "INV_Mace_25",
"side": "",
"obtainable": true
},
{
"id": "684",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "5788",
"icon": "inv_misc_book_17",
"side": "",
"obtainable": true
},
{
"id": "2358",
"icon": "Ability_Mount_Charger",
"side": "",
"obtainable": true
},
{
"id": "2019",
"icon": "Ability_Paladin_SwiftRetribution",
"side": "",
"obtainable": true
},
{
"id": "3844",
"icon": "Spell_Holy_EmpowerChampion",
"side": "",
"obtainable": true
},
{
"id": "4316",
"icon": "Spell_Holy_EmpowerChampion",
"side": "",
"obtainable": true
},
{
"id": "2187",
"icon": "Spell_Holy_SealOfVengeance",
"side": "",
"obtainable": true
},
{
"id": "2186",
"icon": "Spell_Holy_WeaponMastery",
"side": "",
"obtainable": true
},
{
"id": "3316",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3004",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "2903",
"icon": "Spell_Holy_SealOfVengeance",
"side": "",
"obtainable": true
},
{
"id": "3005",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "2904",
"icon": "Spell_Holy_WeaponMastery",
"side": "",
"obtainable": true
},
{
"id": "3808",
"icon": "INV_Crown_14",
"side": "",
"obtainable": true
},
{
"id": "3809",
"icon": "INV_Crown_15",
"side": "",
"obtainable": true
},
{
"id": "3810",
"icon": "inv_crown_13",
"side": "",
"obtainable": true
},
{
"id": "4080",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "3817",
"icon": "INV_Crown_14",
"side": "",
"obtainable": true
},
{
"id": "3818",
"icon": "INV_Crown_15",
"side": "",
"obtainable": true
},
{
"id": "3819",
"icon": "inv_crown_13",
"side": "",
"obtainable": true
},
{
"id": "4156",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "A",
"obtainable": true
},
{
"id": "4079",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "H",
"obtainable": true
},
{
"id": "7485",
"icon": "achievement_raid_mantidraid07",
"side": "H",
"obtainable": true
},
{
"id": "7486",
"icon": "achievement_raid_mantidraid07",
"side": "H",
"obtainable": true
},
{
"id": "7487",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "H",
"obtainable": true
},
{
"id": "2085",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2086",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2087",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2088",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2089",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "6954",
"icon": "achievement_moguraid_06",
"side": "",
"obtainable": true
},
{
"id": "8246",
"icon": "achievement_raid_mantidraid07",
"side": "",
"obtainable": true
},
{
"id": "8249",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8248",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
},
{
"id": "8089",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
},
{
"id": "8238",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8260",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
}
]
},
{
"name": "Legendary",
"achs": [
{
"id": "428",
"icon": "INV_Sword_39",
"side": "",
"obtainable": true
},
{
"id": "429",
"icon": "INV_Hammer_Unique_Sulfuras",
"side": "",
"obtainable": true
},
{
"id": "425",
"icon": "INV_Staff_Medivh",
"side": "",
"obtainable": true
},
{
"id": "426",
"icon": "INV_Weapon_Glave_01",
"side": "",
"obtainable": true
},
{
"id": "725",
"icon": "INV_WEAPON_BOW_39",
"side": "",
"obtainable": true
},
{
"id": "3142",
"icon": "INV_Mace_99",
"side": "",
"obtainable": true
},
{
"id": "4623",
"icon": "inv_axe_114",
"side": "",
"obtainable": true
},
{
"id": "5839",
"icon": "stave_2h_tarecgosa_e_01stagefinal",
"side": "",
"obtainable": true
},
{
"id": "6181",
"icon": "inv_knife_1h_deathwingraid_e_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector's Edition",
"achs": [
{
"id": "662",
"icon": "INV_DiabloStone",
"side": "",
"obtainable": true
},
{
"id": "663",
"icon": "INV_Belt_05",
"side": "",
"obtainable": true
},
{
"id": "664",
"icon": "Spell_Shadow_SummonFelHunter",
"side": "",
"obtainable": true
},
{
"id": "665",
"icon": "INV_Netherwhelp",
"side": "",
"obtainable": true
},
{
"id": "683",
"icon": "INV_PET_FROSTWYRM",
"side": "",
"obtainable": true
},
{
"id": "4824",
"icon": "inv_sigil_thorim",
"side": "",
"obtainable": true
},
{
"id": "5377",
"icon": "inv_dragonwhelpcataclysm",
"side": "",
"obtainable": true
},
{
"id": "7842",
"icon": "ability_pet_baneling",
"side": "",
"obtainable": true
},
{
"id": "7412",
"icon": "inv_spear_05",
"side": "",
"obtainable": true
},
{
"id": "6848",
"icon": "ability_mount_quilenflyingmount",
"side": "",
"obtainable": true
},
{
"id": "6849",
"icon": "ability_mount_quilenflyingmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "BlizzCon",
"achs": [
{
"id": "411",
"icon": "INV_Egg_03",
"side": "",
"obtainable": true
},
{
"id": "412",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "414",
"icon": "INV_Sword_07",
"side": "",
"obtainable": true
},
{
"id": "415",
"icon": "ability_mount_bigblizzardbear",
"side": "",
"obtainable": true
},
{
"id": "3536",
"icon": "INV_Egg_03",
"side": "",
"obtainable": true
},
{
"id": "5378",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "6185",
"icon": "inv_pet_diablobabymurloc",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "416",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "2079",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1637",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "1636",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "2116",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "2456",
"icon": "Ability_Hunter_Pet_Bat",
"side": "",
"obtainable": true
},
{
"id": "4887",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "4786",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "4790",
"icon": "INV_Misc_Head_Troll_01",
"side": "H",
"obtainable": true
},
{
"id": "7467",
"icon": "spell_arcane_teleporttheramore",
"side": "A",
"obtainable": true
},
{
"id": "7468",
"icon": "spell_arcane_teleporttheramore",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Holidays",
"achs": [
{
"id": "1292",
"icon": "INV_MISC_BEER_02",
"side": "",
"obtainable": true
},
{
"id": "1705",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "1293",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "1706",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "4782",
"icon": "inv_misc_beer_06",
"side": "",
"obtainable": true
},
{
"id": "6059",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "6060",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "6061",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "7852",
"icon": "inv_holiday_christmas_present_01",
"side": "",
"obtainable": true
},
{
"id": "2398",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "4400",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "5512",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "5863",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "6131",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "7853",
"icon": "inv_misc_celebrationcake_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "3636",
"icon": "INV_Misc_Gem_Stone_01",
"side": "",
"obtainable": true
},
{
"id": "3896",
"icon": "INV_Misc_QirajiCrystal_05",
"side": "",
"obtainable": true
},
{
"id": "5364",
"icon": "INV_Misc_Flower_02",
"side": "",
"obtainable": true
},
{
"id": "5365",
"icon": "INV_Mushroom_06",
"side": "",
"obtainable": true
},
{
"id": "1205",
"icon": "Spell_Arcane_TeleportShattrath",
"side": "",
"obtainable": true
},
{
"id": "871",
"icon": "INV_Helmet_66",
"side": "",
"obtainable": true
},
{
"id": "2336",
"icon": "Ability_Mage_BrainFreeze",
"side": "",
"obtainable": true
},
{
"id": "4496",
"icon": "Ability_Warrior_InnerRage",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Scenarios",
"cats": [
{
"name": "Scenarios",
"zones": [
{
"name": "",
"achs": [
{
"id": "7385",
"icon": "inv_misc_archaeology_vrykuldrinkinghorn",
"side": "",
"obtainable": true
},
{
"id": "6874",
"icon": "spell_mage_altertime",
"side": "A",
"obtainable": true
},
{
"id": "7509",
"icon": "spell_mage_altertime",
"side": "H",
"obtainable": true
},
{
"id": "6943",
"icon": "spell_misc_emotionsad",
"side": "",
"obtainable": true
}
]
},
{
"name": "Brewmoon Festival",
"achs": [
{
"id": "6923",
"icon": "inv_drink_05",
"side": "",
"obtainable": true
},
{
"id": "6930",
"icon": "inv_misc_food_68",
"side": "",
"obtainable": true
},
{
"id": "6931",
"icon": "inv_misc_bomb_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "Unga Ingoo",
"achs": [
{
"id": "7231",
"icon": "inv_cask_02",
"side": "",
"obtainable": true
},
{
"id": "7232",
"icon": "achievement_brewery_2",
"side": "",
"obtainable": true
},
{
"id": "7248",
"icon": "ability_hunter_aspectofthemonkey",
"side": "",
"obtainable": true
},
{
"id": "7249",
"icon": "inv_misc_hook_01",
"side": "",
"obtainable": true
},
{
"id": "7239",
"icon": "inv_misc_food_41",
"side": "",
"obtainable": true
}
]
},
{
"name": "Brewing Storm",
"achs": [
{
"id": "7252",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
},
{
"id": "7257",
"icon": "ability_smash",
"side": "",
"obtainable": true
},
{
"id": "7258",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
},
{
"id": "7261",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "8310",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
}
]
},
{
"name": "Greenstone Village",
"achs": [
{
"id": "7265",
"icon": "inv_misc_gem_stone_01",
"side": "",
"obtainable": true
},
{
"id": "7267",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "7266",
"icon": "inv_drink_32_disgustingrotgut",
"side": "",
"obtainable": true
}
]
},
{
"name": "Arena of Annihilation",
"achs": [
{
"id": "7271",
"icon": "achievement_arena_3v3_1",
"side": "",
"obtainable": true
},
{
"id": "7272",
"icon": "ability_monk_summontigerstatue",
"side": "",
"obtainable": true
},
{
"id": "7273",
"icon": "inv_elemental_mote_fire01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Crypt of Forgotten Kings",
"achs": [
{
"id": "7522",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
},
{
"id": "7275",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "7276",
"icon": "ability_rogue_sprint",
"side": "",
"obtainable": true
},
{
"id": "8368",
"icon": "ability_creature_cursed_02",
"side": "",
"obtainable": true
},
{
"id": "8311",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dagger in the Dark",
"achs": [
{
"id": "8009",
"icon": "inv_knife_1h_cataclysm_c_03",
"side": "",
"obtainable": true
},
{
"id": "7984",
"icon": "spell_brokenheart",
"side": "",
"obtainable": true
},
{
"id": "7986",
"icon": "spell_nature_nullward",
"side": "",
"obtainable": true
},
{
"id": "7987",
"icon": "inv_egg_04",
"side": "",
"obtainable": true
}
]
},
{
"name": "A Little Patience",
"achs": [
{
"id": "7988",
"icon": "achievement_character_orc_male",
"side": "A",
"obtainable": true
},
{
"id": "7989",
"icon": "creatureportrait_bubble",
"side": "A",
"obtainable": true
},
{
"id": "7990",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "7991",
"icon": "inv_misc_enggizmos_rocketchicken",
"side": "A",
"obtainable": true
},
{
"id": "7992",
"icon": "achievement_character_nightelf_female",
"side": "A",
"obtainable": true
},
{
"id": "7993",
"icon": "achievement_guild_classypanda",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Assault on Zan'vess",
"achs": [
{
"id": "8016",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "8017",
"icon": "spell_shadow_summonfelhunter",
"side": "",
"obtainable": true
}
]
},
{
"name": "Theramore's Fall",
"achs": [
{
"id": "7523",
"icon": "spell_arcane_teleporttheramore",
"side": "A",
"obtainable": true
},
{
"id": "7524",
"icon": "spell_arcane_teleporttheramore",
"side": "H",
"obtainable": true
},
{
"id": "7526",
"icon": "ability_shaman_stormstrike",
"side": "A",
"obtainable": true
},
{
"id": "7529",
"icon": "ability_shaman_stormstrike",
"side": "H",
"obtainable": true
},
{
"id": "7527",
"icon": "ability_vehicle_demolisherflamecatapult",
"side": "A",
"obtainable": true
},
{
"id": "7530",
"icon": "ability_vehicle_demolisherflamecatapult",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Lion's Landing",
"achs": [
{
"id": "8010",
"icon": "inv_misc_tournaments_tabard_human",
"side": "A",
"obtainable": true
},
{
"id": "8011",
"icon": "achievement_guild_level5",
"side": "A",
"obtainable": true
},
{
"id": "8012",
"icon": "inv_box_01",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Domination Point",
"achs": [
{
"id": "8013",
"icon": "inv_misc_tournaments_tabard_orc",
"side": "H",
"obtainable": true
},
{
"id": "8014",
"icon": "achievement_guild_level5",
"side": "H",
"obtainable": true
},
{
"id": "8015",
"icon": "inv_box_01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Dark Heart of Pandaria",
"achs": [
{
"id": "8319",
"icon": "trade_archaeology_uldumcanopicjar",
"side": "",
"obtainable": true
},
{
"id": "8317",
"icon": "inv_heart_of_the_thunder-king_icon",
"side": "",
"obtainable": true
},
{
"id": "8318",
"icon": "inv_heart_of_the_thunder-king_icon",
"side": "",
"obtainable": true
}
]
},
{
"name": "Blood in the Snow",
"achs": [
{
"id": "8316",
"icon": "achievement_zone_dunmorogh",
"side": "",
"obtainable": true
},
{
"id": "8329",
"icon": "inv_misc_herb_04",
"side": "",
"obtainable": true
},
{
"id": "8330",
"icon": "spell_holy_flashheal",
"side": "",
"obtainable": true
},
{
"id": "8312",
"icon": "inv_shield_zandalari_c_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Secrets of Ragefire",
"achs": [
{
"id": "8327",
"icon": "racial_orc_berserkerstrength",
"side": "",
"obtainable": true
},
{
"id": "8294",
"icon": "racial_orc_berserkerstrength",
"side": "",
"obtainable": true
},
{
"id": "8295",
"icon": "achievement_pvp_h_11",
"side": "",
"obtainable": true
}
]
},
{
"name": "Battle on the High Seas",
"achs": [
{
"id": "8314",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "8315",
"icon": "ability_vehicle_siegeenginecannon",
"side": "H",
"obtainable": true
},
{
"id": "8364",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "8366",
"icon": "ability_vehicle_siegeenginecannon",
"side": "H",
"obtainable": true
},
{
"id": "8347",
"icon": "ability_hunter_snipershot",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Pet Battles",
"cats": [
{
"name": "Pet Battles",
"zones": [
{
"name": "Quest",
"achs": [
{
"id": "7908",
"icon": "petjournalportrait",
"side": "",
"obtainable": true
},
{
"id": "7936",
"icon": "inv_pet_pandarenelemental",
"side": "",
"obtainable": true
},
{
"id": "8080",
"icon": "inv_misc_book_16",
"side": "",
"obtainable": true
}
]
},
{
"name": "Taming",
"achs": [
{
"id": "6601",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "7498",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "7499",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "6602",
"icon": "achievement_zone_kalimdor_01",
"side": "H",
"obtainable": true
},
{
"id": "6603",
"icon": "achievement_zone_easternkingdoms_01",
"side": "A",
"obtainable": true
},
{
"id": "6604",
"icon": "achievement_zone_outland_01",
"side": "",
"obtainable": true
},
{
"id": "6605",
"icon": "achievement_zone_northrend_01",
"side": "",
"obtainable": true
},
{
"id": "7525",
"icon": "achievement_zone_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "6606",
"icon": "inv_pet_achievement_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6607",
"icon": "inv_pet_achievement_defeatpettamer_all",
"side": "",
"obtainable": true
}
]
},
{
"name": "Points",
"achs": [
{
"id": "7482",
"icon": "inv_pet_achievement_earn100achieve",
"side": "",
"obtainable": true
},
{
"id": "7483",
"icon": "inv_pet_achievement_earn200achieve",
"side": "",
"obtainable": true
},
{
"id": "6600",
"icon": "inv_pet_achievement_earn300achieve",
"side": "",
"obtainable": true
},
{
"id": "7521",
"icon": "inv_pet_achievement_earn335achieve",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Collect",
"zones": [
{
"name": "Count",
"achs": [
{
"id": "6554",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6555",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6556",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6557",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7436",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7462",
"icon": "inv_pet_achievement_catchrarepet",
"side": "",
"obtainable": true
},
{
"id": "7463",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7464",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7465",
"icon": "inv_pet_achievement_catchuncommonpet",
"side": "",
"obtainable": true
},
{
"id": "1017",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "15",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "1248",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "1250",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "2516",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5876",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5877",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5875",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "7500",
"icon": "inv_box_petcarrier_01",
"side": "",
"obtainable": true
},
{
"id": "7501",
"icon": "inv_box_petcarrier_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zones",
"achs": [
{
"id": "6612",
"icon": "inv_pet_achievement_defeatwildpettamers_kalimdor",
"side": "",
"obtainable": true
},
{
"id": "6585",
"icon": "inv_pet_achievement_collectallwild_kalimdor",
"side": "",
"obtainable": true
},
{
"id": "6586",
"icon": "inv_pet_achievement_collectallwild_easternkingdoms",
"side": "",
"obtainable": true
},
{
"id": "6613",
"icon": "inv_pet_achievement_defeatwildpettamers_easternkingdom",
"side": "",
"obtainable": true
},
{
"id": "6614",
"icon": "inv_pet_achievement_defeatwildpettamers_outland",
"side": "",
"obtainable": true
},
{
"id": "6587",
"icon": "inv_pet_achievement_collectallwild_outland",
"side": "",
"obtainable": true
},
{
"id": "6615",
"icon": "inv_pet_achievement_defeatwildpettamers_northrend",
"side": "",
"obtainable": true
},
{
"id": "6588",
"icon": "inv_pet_achievement_collectallwild_northrend",
"side": "",
"obtainable": true
},
{
"id": "6616",
"icon": "inv_pet_achievement_defeatwildpettamers_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6589",
"icon": "inv_pet_achievement_collectallwild_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6611",
"icon": "inv_pet_achievement_extra03",
"side": "",
"obtainable": true
},
{
"id": "6590",
"icon": "inv_pet_achievement_collectallwild_cataclysm",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "6608",
"icon": "inv_pet_achievement_captureapetfromeachfamily",
"side": "",
"obtainable": true
},
{
"id": "6571",
"icon": "inv_pet_achievement_captureapetatlessthan5health",
"side": "",
"obtainable": true
},
{
"id": "7934",
"icon": "achievement_boss_ragnaros",
"side": "",
"obtainable": true
},
{
"id": "8293",
"icon": "achievement_boss_prince_malchezaar",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Battle",
"zones": [
{
"name": "Count",
"achs": [
{
"id": "6618",
"icon": "inv_pet_battlepettraining",
"side": "",
"obtainable": true
},
{
"id": "6619",
"icon": "inv_pet_battlepettraining",
"side": "",
"obtainable": true
},
{
"id": "6594",
"icon": "inv_pet_achievement_win10",
"side": "",
"obtainable": true
},
{
"id": "6593",
"icon": "inv_pet_achievement_win50",
"side": "",
"obtainable": true
},
{
"id": "6462",
"icon": "inv_pet_achievement_win250",
"side": "",
"obtainable": true
},
{
"id": "6591",
"icon": "inv_pet_achievement_win1000",
"side": "",
"obtainable": true
},
{
"id": "6592",
"icon": "inv_pet_achievement_win5000",
"side": "",
"obtainable": true
}
]
},
{
"name": "PvP",
"achs": [
{
"id": "6595",
"icon": "inv_pet_achievement_win10pvp",
"side": "",
"obtainable": true
},
{
"id": "6596",
"icon": "inv_pet_achievement_win50pvp",
"side": "",
"obtainable": true
},
{
"id": "6597",
"icon": "inv_pet_achievement_win250pvp",
"side": "",
"obtainable": true
},
{
"id": "6598",
"icon": "inv_pet_achievement_win1000pvp",
"side": "",
"obtainable": true
},
{
"id": "6599",
"icon": "inv_pet_achievement_win5000pvp",
"side": "",
"obtainable": true
},
{
"id": "6620",
"icon": "spell_misc_petheal",
"side": "",
"obtainable": true
},
{
"id": "8300",
"icon": "achievement_featsofstrength_gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "8301",
"icon": "achievement_featsofstrength_gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "8297",
"icon": "achievement_featsofstrength_gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "8298",
"icon": "achievement_featsofstrength_gladiator_02",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zones",
"achs": [
{
"id": "6584",
"icon": "inv_pet_achievement_winpetbattle_stormwind",
"side": "",
"obtainable": true
},
{
"id": "6621",
"icon": "inv_pet_achievement_winpetbattle_orgrimmar",
"side": "",
"obtainable": true
},
{
"id": "6622",
"icon": "inv_pet_achievement_winpetbattle_northrend",
"side": "",
"obtainable": true
},
{
"id": "6558",
"icon": "inv_pet_achievement_catch10petsindifferentzones",
"side": "",
"obtainable": true
},
{
"id": "6559",
"icon": "inv_pet_achievement_catch30petsindifferentzones",
"side": "",
"obtainable": true
},
{
"id": "6560",
"icon": "inv_pet_achievement_catch60petsindifferentzones",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "6851",
"icon": "inv_pet_achievement_captureapetfromeachfamily_battle",
"side": "",
"obtainable": true
},
{
"id": "8348",
"icon": "inv_misc_pocketwatch_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Level",
"zones": [
{
"name": "Raise",
"achs": [
{
"id": "7433",
"icon": "inv_pet_achievement_raiseapetlevel_3",
"side": "",
"obtainable": true
},
{
"id": "6566",
"icon": "inv_pet_achievement_raiseapetlevel_5",
"side": "",
"obtainable": true
},
{
"id": "6567",
"icon": "inv_pet_achievement_raiseapetlevel_10",
"side": "",
"obtainable": true
},
{
"id": "6568",
"icon": "inv_pet_achievement_raiseapetlevel_15",
"side": "",
"obtainable": true
},
{
"id": "6569",
"icon": "inv_pet_achievement_raiseapetlevel_20",
"side": "",
"obtainable": true
},
{
"id": "6570",
"icon": "inv_pet_achievement_raiseapetlevel_25",
"side": "",
"obtainable": true
}
]
},
{
"name": "Count",
"achs": [
{
"id": "6579",
"icon": "inv_pet_achievement_raise15petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6580",
"icon": "inv_pet_achievement_raise30petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6583",
"icon": "inv_pet_achievement_raise75petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6578",
"icon": "inv_pet_achievement_raise15petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6581",
"icon": "inv_pet_achievement_raise30petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6582",
"icon": "inv_pet_achievement_raise75petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6609",
"icon": "inv_pet_achievement_extra01",
"side": "",
"obtainable": true
},
{
"id": "6610",
"icon": "inv_pet_achievement_extra02",
"side": "",
"obtainable": true
}
]
}
]
}
]
}
]
} | achievements.js | var Achievements =
{
"supercats": [
{
"name": "Dungeons & Raids",
"cats": [
{
"name": "Dungeons & Raids",
"zones": [
{
"name": "Dungeons & Raids",
"achs": [
{
"id": "4476",
"icon": "Achievement_Arena_2v2_3",
"side": "",
"obtainable": true
},
{
"id": "4477",
"icon": "Achievement_Arena_3v3_4",
"side": "",
"obtainable": true
},
{
"id": "4478",
"icon": "Achievement_Arena_5v5_3",
"side": "",
"obtainable": true
},
{
"id": "5535",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5536",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5537",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "5538",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
},
{
"id": "6924",
"icon": "pvecurrency-valor",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pandaria",
"achs": [
{
"id": "6925",
"icon": "inv_helmet_181v4",
"side": "",
"obtainable": true
},
{
"id": "6926",
"icon": "spell_shadow_shadowembrace",
"side": "",
"obtainable": true
},
{
"id": "6927",
"icon": "inv_helmet_mail_panda_b_01",
"side": "",
"obtainable": true
},
{
"id": "6932",
"icon": "inv_helmet_189",
"side": "",
"obtainable": true
},
{
"id": "8124",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
}
]
},
{
"name": "Cataclysm",
"achs": [
{
"id": "4844",
"icon": "inv_helm_plate_twilighthammer_c_01",
"side": "",
"obtainable": true
},
{
"id": "5506",
"icon": "achievement_zone_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "4845",
"icon": "inv_helm_plate_pvpdeathknight_c_01",
"side": "",
"obtainable": true
},
{
"id": "4853",
"icon": "inv_helmet_100",
"side": "",
"obtainable": true
},
{
"id": "5828",
"icon": "inv_mace_1h_sulfuron_d_01",
"side": "",
"obtainable": true
},
{
"id": "6169",
"icon": "inv_misc_demonsoul",
"side": "",
"obtainable": true
}
]
},
{
"name": "Wrath of the Lich King",
"achs": [
{
"id": "1288",
"icon": "Spell_Holy_ChampionsBond",
"side": "",
"obtainable": true
},
{
"id": "1289",
"icon": "Ability_Rogue_FeignDeath",
"side": "",
"obtainable": true
},
{
"id": "1658",
"icon": "Spell_Frost_ChillingArmor",
"side": "",
"obtainable": true
},
{
"id": "2136",
"icon": "INV_Helmet_25",
"side": "",
"obtainable": true
},
{
"id": "2137",
"icon": "INV_Helmet_22",
"side": "",
"obtainable": true
},
{
"id": "2138",
"icon": "INV_Helmet_06",
"side": "",
"obtainable": true
},
{
"id": "2957",
"icon": "INV_Helmet_19",
"side": "",
"obtainable": true
},
{
"id": "2958",
"icon": "INV_Helmet_122",
"side": "",
"obtainable": true
},
{
"id": "4602",
"icon": "INV_Helmet_74",
"side": "",
"obtainable": true
},
{
"id": "4603",
"icon": "inv_helmet_151",
"side": "",
"obtainable": true
},
{
"id": "4016",
"icon": "Spell_Nature_ElementalPrecision_2",
"side": "",
"obtainable": true
},
{
"id": "4017",
"icon": "Spell_Nature_ElementalPrecision_2",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Burning Crusade",
"achs": [
{
"id": "1284",
"icon": "Spell_Holy_SummonChampion",
"side": "",
"obtainable": true
},
{
"id": "1287",
"icon": "Ability_Creature_Cursed_02",
"side": "",
"obtainable": true
},
{
"id": "1286",
"icon": "INV_Helmet_90",
"side": "",
"obtainable": true
}
]
},
{
"name": "Classic",
"achs": [
{
"id": "1283",
"icon": "Spell_Holy_ReviveChampion",
"side": "",
"obtainable": true
},
{
"id": "1285",
"icon": "INV_Helmet_74",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria Dungeon",
"zones": [
{
"name": "Gate of the Setting Sun",
"achs": [
{
"id": "6476",
"icon": "ability_rogue_deviouspoisons",
"side": "",
"obtainable": true
},
{
"id": "6479",
"icon": "inv_misc_bomb_04",
"side": "",
"obtainable": true
},
{
"id": "6945",
"icon": "spell_nature_insectswarm",
"side": "",
"obtainable": true
},
{
"id": "6759",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mogu'shan Palace",
"achs": [
{
"id": "6755",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
},
{
"id": "6478",
"icon": "spell_shadow_improvedvampiricembrace",
"side": "",
"obtainable": true
},
{
"id": "6713",
"icon": "inv_misc_gem_emeraldrough_02",
"side": "",
"obtainable": true
},
{
"id": "6736",
"icon": "inv_misc_enggizmos_27",
"side": "",
"obtainable": true
},
{
"id": "6756",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Halls",
"achs": [
{
"id": "6684",
"icon": "achievement_halloween_smiley_01",
"side": "",
"obtainable": true
},
{
"id": "6427",
"icon": "spell_impending_victory",
"side": "",
"obtainable": true
},
{
"id": "6760",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Monastery",
"achs": [
{
"id": "6946",
"icon": "spell_shadow_soulleech_3",
"side": "",
"obtainable": true
},
{
"id": "6928",
"icon": "spell_burningsoul",
"side": "",
"obtainable": true
},
{
"id": "6929",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6761",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scholomance",
"achs": [
{
"id": "6394",
"icon": "trade_archaeology_rustedsteakknife",
"side": "",
"obtainable": true
},
{
"id": "6396",
"icon": "spell_deathknight_bloodboil",
"side": "",
"obtainable": true
},
{
"id": "6531",
"icon": "achievement_character_undead_female",
"side": "",
"obtainable": true
},
{
"id": "6715",
"icon": "inv_potion_97",
"side": "",
"obtainable": true
},
{
"id": "6821",
"icon": "spell_holy_turnundead",
"side": "",
"obtainable": true
},
{
"id": "6762",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan Monastery",
"achs": [
{
"id": "6469",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6471",
"icon": "achievement_shadowpan_hideout_3",
"side": "",
"obtainable": true
},
{
"id": "6472",
"icon": "achievement_shadowpan_hideout_2",
"side": "",
"obtainable": true
},
{
"id": "6477",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "6470",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Siege of Niuzao Temple",
"achs": [
{
"id": "6485",
"icon": "inv_misc_bomb_02",
"side": "",
"obtainable": true
},
{
"id": "6688",
"icon": "spell_nature_shamanrage",
"side": "",
"obtainable": true
},
{
"id": "6822",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "6763",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
}
]
},
{
"name": "Stormstout Brewery",
"achs": [
{
"id": "6457",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6089",
"icon": "achievement_brewery_2",
"side": "",
"obtainable": true
},
{
"id": "6400",
"icon": "achievement_brewery_4",
"side": "",
"obtainable": true
},
{
"id": "6402",
"icon": "achievement_brewery_1",
"side": "",
"obtainable": true
},
{
"id": "6420",
"icon": "achievement_brewery_3",
"side": "",
"obtainable": true
},
{
"id": "6456",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
}
]
},
{
"name": "Temple of the Jade Serpent",
"achs": [
{
"id": "6757",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6460",
"icon": "spell_frost_summonwaterelemental",
"side": "",
"obtainable": true
},
{
"id": "6475",
"icon": "achievement_jadeserpent_1",
"side": "",
"obtainable": true
},
{
"id": "6671",
"icon": "spell_shadow_seedofdestruction",
"side": "",
"obtainable": true
},
{
"id": "6758",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria Raid",
"zones": [
{
"name": "Mogu'shan Vaults",
"achs": [
{
"id": "6458",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "6844",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "6823",
"icon": "ability_hunter_beasttraining",
"side": "",
"obtainable": true
},
{
"id": "6674",
"icon": "thumbsup",
"side": "",
"obtainable": true
},
{
"id": "7056",
"icon": "trade_archaeology_silverscrollcase",
"side": "",
"obtainable": true
},
{
"id": "6687",
"icon": "thumbsup",
"side": "",
"obtainable": true
},
{
"id": "7933",
"icon": "spell_holy_circleofrenewal",
"side": "",
"obtainable": true
},
{
"id": "6686",
"icon": "ability_deathknight_pillaroffrost",
"side": "",
"obtainable": true
},
{
"id": "6455",
"icon": "ability_rogue_shadowstrikes",
"side": "",
"obtainable": true
},
{
"id": "6719",
"icon": "achievement_moguraid_01",
"side": "",
"obtainable": true
},
{
"id": "6720",
"icon": "achievement_moguraid_02",
"side": "",
"obtainable": true
},
{
"id": "6721",
"icon": "achievement_raid_mantidraid05",
"side": "",
"obtainable": true
},
{
"id": "6722",
"icon": "achievement_moguraid_04",
"side": "",
"obtainable": true
},
{
"id": "6723",
"icon": "achievement_moguraid_05",
"side": "",
"obtainable": true
},
{
"id": "6724",
"icon": "achievement_moguraid_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Heart of Fear",
"achs": [
{
"id": "6718",
"icon": "achievement_raid_mantidraid01",
"side": "",
"obtainable": true
},
{
"id": "6845",
"icon": "achievement_raid_mantidraid01",
"side": "",
"obtainable": true
},
{
"id": "6937",
"icon": "inv_misc_archaeology_amburfly",
"side": "",
"obtainable": true
},
{
"id": "6936",
"icon": "trade_archaeology_candlestub",
"side": "",
"obtainable": true
},
{
"id": "6553",
"icon": "inv_misc_ammo_arrow_05",
"side": "",
"obtainable": true
},
{
"id": "6683",
"icon": "spell_brokenheart",
"side": "",
"obtainable": true
},
{
"id": "6518",
"icon": "spell_yorsahj_bloodboil_yellow",
"side": "",
"obtainable": true
},
{
"id": "6922",
"icon": "spell_holy_borrowedtime",
"side": "",
"obtainable": true
},
{
"id": "6725",
"icon": "achievement_raid_mantidraid02",
"side": "",
"obtainable": true
},
{
"id": "6726",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "6727",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "6728",
"icon": "achievement_raid_mantidraid04",
"side": "",
"obtainable": true
},
{
"id": "6729",
"icon": "achievement_raid_mantidraid06",
"side": "",
"obtainable": true
},
{
"id": "6730",
"icon": "achievement_raid_mantidraid07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Terrace of Endless Spring",
"achs": [
{
"id": "6689",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
},
{
"id": "6717",
"icon": "ability_rogue_envelopingshadows",
"side": "",
"obtainable": true
},
{
"id": "6933",
"icon": "trade_herbalism",
"side": "",
"obtainable": true
},
{
"id": "6824",
"icon": "spell_shadow_coneofsilence",
"side": "",
"obtainable": true
},
{
"id": "6825",
"icon": "spell_arcane_mindmastery",
"side": "",
"obtainable": true
},
{
"id": "6731",
"icon": "achievement_raid_terraceofendlessspring01",
"side": "",
"obtainable": true
},
{
"id": "6732",
"icon": "achievement_raid_terraceofendlessspring02",
"side": "",
"obtainable": true
},
{
"id": "6733",
"icon": "achievement_raid_terraceofendlessspring03",
"side": "",
"obtainable": true
},
{
"id": "6734",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
}
]
},
{
"name": "Throne of Thunder",
"achs": [
{
"id": "8069",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8070",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8071",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8072",
"icon": "archaeology_5_0_thunderkinginsignia",
"side": "",
"obtainable": true
},
{
"id": "8094",
"icon": "ability_vehicle_electrocharge",
"side": "",
"obtainable": true
},
{
"id": "8038",
"icon": "trade_archaeology_dinosaurskeleton",
"side": "",
"obtainable": true
},
{
"id": "8073",
"icon": "inv_pet_magicalcradadbox",
"side": "",
"obtainable": true
},
{
"id": "8077",
"icon": "achievement_boss_tortos",
"side": "",
"obtainable": true
},
{
"id": "8082",
"icon": "inv_misc_head_dragon_01",
"side": "",
"obtainable": true
},
{
"id": "8097",
"icon": "inv_misc_football",
"side": "",
"obtainable": true
},
{
"id": "8098",
"icon": "spell_nature_elementalprecision_1",
"side": "",
"obtainable": true
},
{
"id": "8037",
"icon": "ability_deathknight_roilingblood",
"side": "",
"obtainable": true
},
{
"id": "8081",
"icon": "ability_touchofanimus",
"side": "",
"obtainable": true
},
{
"id": "8087",
"icon": "thumbup",
"side": "",
"obtainable": true
},
{
"id": "8086",
"icon": "spell_holy_pureofheart",
"side": "",
"obtainable": true
},
{
"id": "8090",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "8056",
"icon": "achievement_boss_jinrokhthebreaker",
"side": "",
"obtainable": true
},
{
"id": "8057",
"icon": "achievement_boss_horridon",
"side": "",
"obtainable": true
},
{
"id": "8058",
"icon": "achievement_boss_councilofelders",
"side": "",
"obtainable": true
},
{
"id": "8059",
"icon": "achievement_boss_tortos",
"side": "",
"obtainable": true
},
{
"id": "8060",
"icon": "achievement_boss_megaera",
"side": "",
"obtainable": true
},
{
"id": "8061",
"icon": "achievement_boss_ji-kun",
"side": "",
"obtainable": true
},
{
"id": "8062",
"icon": "achievement_boss_durumu",
"side": "",
"obtainable": true
},
{
"id": "8063",
"icon": "achievement_boss_primordius",
"side": "",
"obtainable": true
},
{
"id": "8065",
"icon": "achievement_boss_iron_qon",
"side": "",
"obtainable": true
},
{
"id": "8066",
"icon": "achievement_boss_mogufemales",
"side": "",
"obtainable": true
},
{
"id": "8067",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8068",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
},
{
"id": "8064",
"icon": "achievement_boss_darkanimus",
"side": "",
"obtainable": true
}
]
},
{
"name": "World",
"achs": [
{
"id": "6480",
"icon": "spell_misc_emotionangry",
"side": "",
"obtainable": true
},
{
"id": "6517",
"icon": "spell_fire_meteorstorm",
"side": "",
"obtainable": true
},
{
"id": "8123",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
},
{
"id": "8028",
"icon": "spell_holy_lightsgrace",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Dungeon Challenges",
"zones": [
{
"name": "Dungeon Challenges",
"achs": [
{
"id": "6920",
"icon": "achievement_guildperk_honorablemention",
"side": "",
"obtainable": true
},
{
"id": "6374",
"icon": "achievement_challengemode_bronze",
"side": "",
"obtainable": true
},
{
"id": "6375",
"icon": "achievement_challengemode_silver",
"side": "",
"obtainable": true
},
{
"id": "6378",
"icon": "achievement_challengemode_gold",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gate of the Setting Sun",
"achs": [
{
"id": "6894",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6905",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6906",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6907",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mogu'shan Palace",
"achs": [
{
"id": "6892",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6899",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6900",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "6901",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Halls",
"achs": [
{
"id": "6895",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6908",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6909",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "6910",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scarlet Monastery",
"achs": [
{
"id": "6896",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6911",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6912",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
},
{
"id": "6913",
"icon": "spell_holy_resurrection",
"side": "",
"obtainable": true
}
]
},
{
"name": "Scholomance",
"achs": [
{
"id": "6897",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6914",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6915",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
},
{
"id": "6916",
"icon": "spell_holy_senseundead",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan Monastery",
"achs": [
{
"id": "6893",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6902",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6903",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
},
{
"id": "6904",
"icon": "achievement_shadowpan_hideout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Siege of Niuzao Temple",
"achs": [
{
"id": "6898",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6917",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6918",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
},
{
"id": "6919",
"icon": "achievement_dungeon_siegeofniuzaotemple",
"side": "",
"obtainable": true
}
]
},
{
"name": "Stormstout Brewery",
"achs": [
{
"id": "6888",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6889",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6890",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
},
{
"id": "6891",
"icon": "achievement_brewery",
"side": "",
"obtainable": true
}
]
},
{
"name": "Temple of the Jade Serpent",
"achs": [
{
"id": "6884",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6885",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6886",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
},
{
"id": "6887",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm Dungeon",
"zones": [
{
"name": "Blackrock Caverns",
"achs": [
{
"id": "4833",
"icon": "achievement_dungeon_blackrockcaverns",
"side": "",
"obtainable": true
},
{
"id": "5281",
"icon": "achievement_dungeon_blackrockcaverns_romogg-bonecrusher",
"side": "",
"obtainable": true
},
{
"id": "5282",
"icon": "achievement_dungeon_blackrockcaverns_corla-herald-of-twilight",
"side": "",
"obtainable": true
},
{
"id": "5283",
"icon": "achievement_dungeon_blackrockcaverns_karshsteelbender",
"side": "",
"obtainable": true
},
{
"id": "5284",
"icon": "achievement_dungeon_blackrockcaverns_ascendantlordobsidius",
"side": "",
"obtainable": true
},
{
"id": "5060",
"icon": "achievement_dungeon_blackrockcaverns",
"side": "",
"obtainable": true
}
]
},
{
"name": "Throne of the Tides",
"achs": [
{
"id": "4839",
"icon": "achievement_dungeon_throne-of-the-tides",
"side": "",
"obtainable": true
},
{
"id": "5285",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "5286",
"icon": "achievement_dungeon_throne-of-the-tides_ozumat",
"side": "",
"obtainable": true
},
{
"id": "5061",
"icon": "achievement_dungeon_throne-of-the-tides",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Stonecore",
"achs": [
{
"id": "4846",
"icon": "achievement_dungeon_deepholm",
"side": "",
"obtainable": true
},
{
"id": "5287",
"icon": "Ability_Warlock_MoltenCore",
"side": "",
"obtainable": true
},
{
"id": "5063",
"icon": "achievement_dungeon_deepholm",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Vortex Pinnacle",
"achs": [
{
"id": "4847",
"icon": "achievement_dungeon_skywall",
"side": "",
"obtainable": true
},
{
"id": "5289",
"icon": "Spell_Frost_WindWalkOn",
"side": "",
"obtainable": true
},
{
"id": "5288",
"icon": "achievement_dungeon_thevortexpinnacle_asaad",
"side": "",
"obtainable": true
},
{
"id": "5064",
"icon": "achievement_dungeon_skywall",
"side": "",
"obtainable": true
}
]
},
{
"name": "Grim Batol",
"achs": [
{
"id": "4840",
"icon": "achievement_dungeon_grimbatol",
"side": "",
"obtainable": true
},
{
"id": "5297",
"icon": "achievement_dungeon_grimbatol_general-umbriss",
"side": "",
"obtainable": true
},
{
"id": "5298",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "",
"obtainable": true
},
{
"id": "5062",
"icon": "achievement_dungeon_grimbatol",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Origination",
"achs": [
{
"id": "4841",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
},
{
"id": "5293",
"icon": "Spell_Holy_DivineHymn",
"side": "",
"obtainable": true
},
{
"id": "5294",
"icon": "ability_mount_camel_tan",
"side": "",
"obtainable": true
},
{
"id": "5296",
"icon": "INV_Misc_PocketWatch_01",
"side": "",
"obtainable": true
},
{
"id": "5295",
"icon": "achievement_dungeon_halls-of-origination_rajh",
"side": "",
"obtainable": true
},
{
"id": "5065",
"icon": "achievement_dungeon_halls-of-origination",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lost City of the Tol'vir",
"achs": [
{
"id": "4848",
"icon": "achievement_dungeon_lostcity-of-tolvir",
"side": "",
"obtainable": true
},
{
"id": "5290",
"icon": "INV_Misc_FireDancer_01",
"side": "",
"obtainable": true
},
{
"id": "5291",
"icon": "Ability_Hunter_Pet_Crocolisk",
"side": "",
"obtainable": true
},
{
"id": "5292",
"icon": "Ability_Mage_NetherWindPresence",
"side": "",
"obtainable": true
},
{
"id": "5066",
"icon": "achievement_dungeon_lostcity-of-tolvir",
"side": "",
"obtainable": true
}
]
},
{
"name": "Deadmines",
"achs": [
{
"id": "5366",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
},
{
"id": "5367",
"icon": "inv_misc_food_100_hardcheese",
"side": "",
"obtainable": true
},
{
"id": "5368",
"icon": "INV_Gizmo_GoblingTonkController",
"side": "",
"obtainable": true
},
{
"id": "5369",
"icon": "Spell_DeathKnight_PathOfFrost",
"side": "",
"obtainable": true
},
{
"id": "5370",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "5371",
"icon": "Achievement_Boss_EdwinVancleef",
"side": "",
"obtainable": true
},
{
"id": "5083",
"icon": "INV_Misc_Bandana_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "Hour of Twilight",
"achs": [
{
"id": "6132",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "6119",
"icon": "achievment_raid_houroftwilight",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shadowfang Keep",
"achs": [
{
"id": "5503",
"icon": "Ability_Rogue_StayofExecution",
"side": "",
"obtainable": true
},
{
"id": "5504",
"icon": "Spell_Holy_SealOfBlood",
"side": "",
"obtainable": true
},
{
"id": "5505",
"icon": "INV_Misc_Ammo_Bullet_05",
"side": "",
"obtainable": true
},
{
"id": "5093",
"icon": "inv_helm_robe_dungeonrobe_c_04",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zul'Aman",
"achs": [
{
"id": "5761",
"icon": "Spell_Shaman_Hex",
"side": "",
"obtainable": true
},
{
"id": "5750",
"icon": "Spell_Totem_WardOfDraining",
"side": "",
"obtainable": true
},
{
"id": "5858",
"icon": "inv_misc_bearcubbrown",
"side": "",
"obtainable": true
},
{
"id": "5760",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "5769",
"icon": "achievement_zul_aman_daakara",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zul'Gurub",
"achs": [
{
"id": "5744",
"icon": "INV_Spear_02",
"side": "",
"obtainable": true
},
{
"id": "5743",
"icon": "Ability_Creature_Poison_06",
"side": "",
"obtainable": true
},
{
"id": "5762",
"icon": "ability_mount_fossilizedraptor",
"side": "",
"obtainable": true
},
{
"id": "5765",
"icon": "achievement_rat",
"side": "",
"obtainable": true
},
{
"id": "5759",
"icon": "Ability_Creature_Cursed_05",
"side": "",
"obtainable": true
},
{
"id": "5768",
"icon": "achievement_zulgurub_jindo",
"side": "",
"obtainable": true
}
]
},
{
"name": "End Time",
"achs": [
{
"id": "6130",
"icon": "Achievement_Leader_Sylvanas",
"side": "",
"obtainable": true
},
{
"id": "5995",
"icon": "Ability_UpgradeMoonGlaive",
"side": "",
"obtainable": true
},
{
"id": "6117",
"icon": "achievement_boss_infinitecorruptor",
"side": "",
"obtainable": true
}
]
},
{
"name": "Well of Eternity",
"achs": [
{
"id": "6127",
"icon": "inv_misc_eye_02",
"side": "",
"obtainable": true
},
{
"id": "6070",
"icon": "Spell_Misc_EmotionAngry",
"side": "",
"obtainable": true
},
{
"id": "6118",
"icon": "achievment_boss_wellofeternity",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm Raid",
"zones": [
{
"name": "The Bastion of Twilight",
"achs": [
{
"id": "5300",
"icon": "INV_Misc_Crop_01",
"side": "",
"obtainable": true
},
{
"id": "4852",
"icon": "achievement_dungeon_bastion-of-twilight_valiona-theralion",
"side": "",
"obtainable": true
},
{
"id": "5311",
"icon": "achievement_dungeon_bastion-of-twilight_twilightascendantcouncil",
"side": "",
"obtainable": true
},
{
"id": "5312",
"icon": "spell_shadow_mindflay",
"side": "",
"obtainable": true
},
{
"id": "4850",
"icon": "spell_fire_twilightcano",
"side": "",
"obtainable": true
},
{
"id": "5118",
"icon": "achievement_dungeon_bastion-of-twilight_halfus-wyrmbreaker",
"side": "",
"obtainable": true
},
{
"id": "5117",
"icon": "achievement_dungeon_bastion-of-twilight_valiona-theralion",
"side": "",
"obtainable": true
},
{
"id": "5119",
"icon": "achievement_dungeon_bastion-of-twilight_twilightascendantcouncil",
"side": "",
"obtainable": true
},
{
"id": "5120",
"icon": "achievement_dungeon_bastion-of-twilight_chogall-boss",
"side": "",
"obtainable": true
},
{
"id": "5121",
"icon": "achievement_dungeon_bastion-of-twilight_ladysinestra",
"side": "",
"obtainable": true
},
{
"id": "5313",
"icon": "achievement_dungeon_bastion-of-twilight_ladysinestra",
"side": "",
"obtainable": false
}
]
},
{
"name": "Throne of the Four Winds",
"achs": [
{
"id": "5304",
"icon": "Spell_DeathKnight_FrostFever",
"side": "",
"obtainable": true
},
{
"id": "5305",
"icon": "Spell_Shaman_StaticShock",
"side": "",
"obtainable": true
},
{
"id": "4851",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "5122",
"icon": "Ability_Druid_GaleWinds",
"side": "",
"obtainable": true
},
{
"id": "5123",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
}
]
},
{
"name": "Blackwing Descent",
"achs": [
{
"id": "5306",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "5307",
"icon": "achievement_dungeon_blackwingdescent_darkironcouncil",
"side": "",
"obtainable": true
},
{
"id": "5310",
"icon": "ability_racial_aberration",
"side": "",
"obtainable": true
},
{
"id": "5308",
"icon": "INV_Misc_Bell_01",
"side": "",
"obtainable": true
},
{
"id": "5309",
"icon": "warrior_talent_icon_furyintheblood",
"side": "",
"obtainable": true
},
{
"id": "4849",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4842",
"icon": "Achievement_Boss_Nefarion",
"side": "",
"obtainable": true
},
{
"id": "5094",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "5107",
"icon": "achievement_dungeon_blackwingdescent_darkironcouncil",
"side": "",
"obtainable": true
},
{
"id": "5108",
"icon": "achievement_dungeon_blackwingdescent_raid_maloriak",
"side": "",
"obtainable": true
},
{
"id": "5109",
"icon": "achievement_dungeon_blackwingdescent_raid_atramedes",
"side": "",
"obtainable": true
},
{
"id": "5115",
"icon": "achievement_dungeon_blackwingdescent_raid_chimaron",
"side": "",
"obtainable": true
},
{
"id": "5116",
"icon": "achievement_dungeon_blackwingdescent_raid_nefarian",
"side": "",
"obtainable": true
}
]
},
{
"name": "Firelands",
"achs": [
{
"id": "5829",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5810",
"icon": "misc_arrowright",
"side": "",
"obtainable": true
},
{
"id": "5821",
"icon": "INV_Misc_Head_Nerubian_01",
"side": "",
"obtainable": true
},
{
"id": "5813",
"icon": "spell_magic_polymorphrabbit",
"side": "",
"obtainable": true
},
{
"id": "5830",
"icon": "Spell_Shadow_PainAndSuffering",
"side": "",
"obtainable": true
},
{
"id": "5799",
"icon": "achievement_firelands-raid_fandral-staghelm",
"side": "",
"obtainable": true
},
{
"id": "5855",
"icon": "achievement_firelands-raid_ragnaros",
"side": "",
"obtainable": true
},
{
"id": "5802",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5806",
"icon": "achievement_boss_shannox",
"side": "",
"obtainable": true
},
{
"id": "5808",
"icon": "achievement_boss_lordanthricyst",
"side": "",
"obtainable": true
},
{
"id": "5807",
"icon": "achievement_boss_broodmotheraranae",
"side": "",
"obtainable": true
},
{
"id": "5809",
"icon": "achievement_firelands-raid_alysra",
"side": "",
"obtainable": true
},
{
"id": "5805",
"icon": "achievement_firelandsraid_balorocthegatekeeper",
"side": "",
"obtainable": true
},
{
"id": "5804",
"icon": "achievement_firelands-raid_fandral-staghelm",
"side": "",
"obtainable": true
},
{
"id": "5803",
"icon": "achievement_firelands-raid_ragnaros",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dragon Soul",
"achs": [
{
"id": "6106",
"icon": "Achievement_Reputation_WyrmrestTemple",
"side": "",
"obtainable": true
},
{
"id": "6107",
"icon": "achievment_boss_madnessofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6174",
"icon": "Spell_Nature_MassTeleport",
"side": "",
"obtainable": true
},
{
"id": "6128",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "6129",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "6175",
"icon": "achievement_general_dungeondiplomat",
"side": "",
"obtainable": true
},
{
"id": "6084",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6105",
"icon": "spell_fire_twilightpyroblast",
"side": "",
"obtainable": true
},
{
"id": "6133",
"icon": "achievment_boss_spineofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6177",
"icon": "ability_deathwing_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "6180",
"icon": "inv_dragonchromaticmount",
"side": "",
"obtainable": true
},
{
"id": "6109",
"icon": "achievment_boss_morchok",
"side": "",
"obtainable": true
},
{
"id": "6110",
"icon": "achievment_boss_zonozz",
"side": "",
"obtainable": true
},
{
"id": "6111",
"icon": "achievment_boss_yorsahj",
"side": "",
"obtainable": true
},
{
"id": "6112",
"icon": "achievment_boss_hagara",
"side": "",
"obtainable": true
},
{
"id": "6113",
"icon": "achievment_boss_ultraxion",
"side": "",
"obtainable": true
},
{
"id": "6114",
"icon": "achievment_boss_blackhorn",
"side": "",
"obtainable": true
},
{
"id": "6115",
"icon": "achievment_boss_spineofdeathwing",
"side": "",
"obtainable": true
},
{
"id": "6116",
"icon": "achievment_boss_madnessofdeathwing",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lich King Dungeon",
"zones": [
{
"name": "Utgarde Keep",
"achs": [
{
"id": "477",
"icon": "Achievement_Dungeon_UtgardeKeep_Normal",
"side": "",
"obtainable": true
},
{
"id": "1919",
"icon": "Ability_Mage_ColdAsIce",
"side": "",
"obtainable": true
},
{
"id": "489",
"icon": "Achievement_Dungeon_UtgardeKeep_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Nexus",
"achs": [
{
"id": "478",
"icon": "Achievement_Dungeon_Nexus70_Normal",
"side": "",
"obtainable": true
},
{
"id": "2150",
"icon": "Achievement_Dungeon_Nexus70_25man",
"side": "",
"obtainable": true
},
{
"id": "2037",
"icon": "Achievement_Dungeon_Nexus70_25man",
"side": "",
"obtainable": true
},
{
"id": "2036",
"icon": "Ability_Mage_ChilledToTheBone",
"side": "",
"obtainable": true
},
{
"id": "490",
"icon": "Achievement_Dungeon_Nexus70_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Azjol-Nerub",
"achs": [
{
"id": "480",
"icon": "Achievement_Dungeon_AzjolUppercity_Normal",
"side": "",
"obtainable": true
},
{
"id": "1296",
"icon": "Achievement_Dungeon_AzjolUppercity_25man",
"side": "",
"obtainable": true
},
{
"id": "1297",
"icon": "Achievement_Dungeon_AzjolUppercity_10man",
"side": "",
"obtainable": true
},
{
"id": "1860",
"icon": "Achievement_Dungeon_AzjolUppercity",
"side": "",
"obtainable": true
},
{
"id": "491",
"icon": "Achievement_Dungeon_AzjolUppercity_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ahn'kahet: The Old Kingdom",
"achs": [
{
"id": "481",
"icon": "Achievement_Dungeon_AzjolLowercity_Normal",
"side": "",
"obtainable": true
},
{
"id": "2038",
"icon": "INV_Misc_Head_Nerubian_01",
"side": "",
"obtainable": true
},
{
"id": "2056",
"icon": "Achievement_Character_Orc_Female",
"side": "",
"obtainable": true
},
{
"id": "1862",
"icon": "Achievement_Dungeon_AzjolLowercity_25man",
"side": "",
"obtainable": true
},
{
"id": "492",
"icon": "Achievement_Dungeon_AzjolLowercity_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Drak'Tharon Keep",
"achs": [
{
"id": "482",
"icon": "Achievement_Dungeon_Drak'Tharon_Normal",
"side": "",
"obtainable": true
},
{
"id": "2151",
"icon": "Achievement_Dungeon_Drak'Tharon_25man",
"side": "",
"obtainable": true
},
{
"id": "2057",
"icon": "Spell_DeathKnight_ArmyOfTheDead",
"side": "",
"obtainable": true
},
{
"id": "2039",
"icon": "Ability_Hunter_Pet_Devilsaur",
"side": "",
"obtainable": true
},
{
"id": "493",
"icon": "Achievement_Dungeon_Drak'Tharon_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Violet Hold",
"achs": [
{
"id": "483",
"icon": "Achievement_Dungeon_TheVioletHold_Normal",
"side": "",
"obtainable": true
},
{
"id": "2153",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "2041",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "1816",
"icon": "Achievement_Dungeon_TheVioletHold_25man",
"side": "",
"obtainable": true
},
{
"id": "1865",
"icon": "Achievement_Dungeon_TheVioletHold_10man",
"side": "",
"obtainable": true
},
{
"id": "494",
"icon": "Achievement_Dungeon_TheVioletHold_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gundrak",
"achs": [
{
"id": "484",
"icon": "Achievement_Dungeon_Gundrak_Normal",
"side": "",
"obtainable": true
},
{
"id": "2040",
"icon": "INV_Misc_MonsterHorn_04",
"side": "",
"obtainable": true
},
{
"id": "2058",
"icon": "Ability_Hunter_CobraStrikes",
"side": "",
"obtainable": true
},
{
"id": "1864",
"icon": "Achievement_Dungeon_Gundrak_25man",
"side": "",
"obtainable": true
},
{
"id": "2152",
"icon": "Ability_Mount_KotoBrewfest",
"side": "",
"obtainable": true
},
{
"id": "495",
"icon": "Achievement_Dungeon_Gundrak_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Stone",
"achs": [
{
"id": "485",
"icon": "Achievement_Dungeon_Ulduar77_Normal",
"side": "",
"obtainable": true
},
{
"id": "1866",
"icon": "Achievement_Dungeon_Ulduar77_10man",
"side": "",
"obtainable": true
},
{
"id": "2154",
"icon": "Achievement_Character_Dwarf_Male",
"side": "",
"obtainable": true
},
{
"id": "2155",
"icon": "INV_Misc_Slime_01",
"side": "",
"obtainable": true
},
{
"id": "496",
"icon": "Achievement_Dungeon_Ulduar77_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Culling of Stratholme",
"achs": [
{
"id": "479",
"icon": "Achievement_Dungeon_CoTStratholme_Normal",
"side": "",
"obtainable": true
},
{
"id": "1872",
"icon": "Spell_DeathKnight_Explode_Ghoul",
"side": "",
"obtainable": true
},
{
"id": "1817",
"icon": "Achievement_Dungeon_CoTStratholme_25man",
"side": "",
"obtainable": true
},
{
"id": "500",
"icon": "Achievement_Dungeon_CoTStratholme_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Oculus",
"achs": [
{
"id": "487",
"icon": "Achievement_Dungeon_Nexus80_Normal",
"side": "",
"obtainable": true
},
{
"id": "1871",
"icon": "Achievement_Dungeon_Nexus80_10man",
"side": "",
"obtainable": true
},
{
"id": "2046",
"icon": "Ability_Mount_Drake_Bronze",
"side": "",
"obtainable": true
},
{
"id": "2045",
"icon": "Ability_Mount_Drake_Blue",
"side": "",
"obtainable": true
},
{
"id": "2044",
"icon": "Ability_Mount_Drake_Red",
"side": "",
"obtainable": true
},
{
"id": "1868",
"icon": "Achievement_Dungeon_Nexus80_25man",
"side": "",
"obtainable": true
},
{
"id": "498",
"icon": "Achievement_Dungeon_Nexus80_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Lightning",
"achs": [
{
"id": "486",
"icon": "Achievement_Dungeon_Ulduar80_Normal",
"side": "",
"obtainable": true
},
{
"id": "1834",
"icon": "Achievement_Dungeon_Ulduar80_Heroic",
"side": "",
"obtainable": true
},
{
"id": "2042",
"icon": "Spell_Fire_Incinerate",
"side": "",
"obtainable": true
},
{
"id": "1867",
"icon": "Achievement_Dungeon_Ulduar80_25man",
"side": "",
"obtainable": true
},
{
"id": "497",
"icon": "Achievement_Dungeon_Ulduar80_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Utgarde Pinnacle",
"achs": [
{
"id": "488",
"icon": "Achievement_Dungeon_UtgardePinnacle_Normal",
"side": "",
"obtainable": true
},
{
"id": "2043",
"icon": "Spell_Shadow_SummonInfernal",
"side": "",
"obtainable": true
},
{
"id": "1873",
"icon": "Achievement_Dungeon_UtgardePinnacle_10man",
"side": "",
"obtainable": true
},
{
"id": "2156",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_01",
"side": "",
"obtainable": true
},
{
"id": "2157",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_03",
"side": "",
"obtainable": true
},
{
"id": "499",
"icon": "Achievement_Dungeon_UtgardePinnacle_Heroic",
"side": "",
"obtainable": true
}
]
},
{
"name": "Trial of the Champion",
"achs": [
{
"id": "3778",
"icon": "INV_Spear_05",
"side": "H",
"obtainable": true
},
{
"id": "4296",
"icon": "INV_Spear_05",
"side": "A",
"obtainable": true
},
{
"id": "3802",
"icon": "INV_Helmet_52",
"side": "",
"obtainable": true
},
{
"id": "3803",
"icon": "Ability_ThunderClap",
"side": "",
"obtainable": true
},
{
"id": "3804",
"icon": "INV_Helmet_23",
"side": "",
"obtainable": true
},
{
"id": "4297",
"icon": "INV_Spear_05",
"side": "H",
"obtainable": true
},
{
"id": "4298",
"icon": "INV_Spear_05",
"side": "A",
"obtainable": true
}
]
},
{
"name": "The Forge of Souls",
"achs": [
{
"id": "4516",
"icon": "achievement_dungeon_icecrown_forgeofsouls",
"side": "",
"obtainable": true
},
{
"id": "4522",
"icon": "achievement_boss_bronjahm",
"side": "",
"obtainable": true
},
{
"id": "4523",
"icon": "achievement_boss_devourerofsouls",
"side": "",
"obtainable": true
},
{
"id": "4519",
"icon": "achievement_dungeon_icecrown_forgeofsouls",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pit of Saron",
"achs": [
{
"id": "4517",
"icon": "achievement_dungeon_icecrown_pitofsaron",
"side": "",
"obtainable": true
},
{
"id": "4524",
"icon": "achievement_boss_forgemaster",
"side": "",
"obtainable": true
},
{
"id": "4525",
"icon": "achievement_boss_scourgelordtyrannus",
"side": "",
"obtainable": true
},
{
"id": "4520",
"icon": "achievement_dungeon_icecrown_pitofsaron",
"side": "",
"obtainable": true
}
]
},
{
"name": "Halls of Reflection",
"achs": [
{
"id": "4518",
"icon": "achievement_dungeon_icecrown_hallsofreflection",
"side": "",
"obtainable": true
},
{
"id": "4526",
"icon": "achievement_boss_lichking",
"side": "",
"obtainable": true
},
{
"id": "4521",
"icon": "achievement_dungeon_icecrown_hallsofreflection",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lich King Raid",
"zones": [
{
"name": "Naxxramas (10 player)",
"achs": [
{
"id": "1858",
"icon": "Achievement_Halloween_Spider_01",
"side": "",
"obtainable": true
},
{
"id": "1997",
"icon": "Spell_Shadow_CurseOfMannoroth",
"side": "",
"obtainable": true
},
{
"id": "562",
"icon": "INV_Trinket_Naxxramas04",
"side": "",
"obtainable": true
},
{
"id": "1996",
"icon": "Ability_Rogue_QuickRecovery",
"side": "",
"obtainable": true
},
{
"id": "2182",
"icon": "INV_Misc_Herb_Ragveil",
"side": "",
"obtainable": true
},
{
"id": "566",
"icon": "INV_Misc_Cauldron_Nature",
"side": "",
"obtainable": true
},
{
"id": "1856",
"icon": "Spell_Shadow_AbominationExplosion",
"side": "",
"obtainable": true
},
{
"id": "2178",
"icon": "Spell_ChargePositive",
"side": "",
"obtainable": true
},
{
"id": "2180",
"icon": "Spell_ChargeNegative",
"side": "",
"obtainable": true
},
{
"id": "564",
"icon": "Ability_Rogue_DeviousPoisons",
"side": "",
"obtainable": true
},
{
"id": "2176",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "568",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "2146",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "572",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "2184",
"icon": "Spell_Deathknight_PlagueStrike",
"side": "",
"obtainable": true
},
{
"id": "574",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "576",
"icon": "Achievement_Dungeon_Naxxramas_Normal",
"side": "",
"obtainable": true
},
{
"id": "578",
"icon": "Spell_Shadow_RaiseDead",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Obsidian Sanctum (10 player)",
"achs": [
{
"id": "1876",
"icon": "Achievement_Dungeon_CoABlackDragonflight",
"side": "",
"obtainable": true
},
{
"id": "2047",
"icon": "Spell_Shaman_LavaFlow",
"side": "",
"obtainable": true
},
{
"id": "624",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Heroic",
"side": "",
"obtainable": true
},
{
"id": "2049",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2050",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2051",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Eye of Eternity (10 player)",
"achs": [
{
"id": "2148",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "622",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
},
{
"id": "1869",
"icon": "Achievement_Dungeon_NexusRaid_Heroic",
"side": "",
"obtainable": true
},
{
"id": "1874",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
}
]
},
{
"name": "Naxxramas (25 player)",
"achs": [
{
"id": "1859",
"icon": "Achievement_Halloween_Spider_01",
"side": "",
"obtainable": true
},
{
"id": "2140",
"icon": "Spell_Shadow_CurseOfMannoroth",
"side": "",
"obtainable": true
},
{
"id": "563",
"icon": "INV_Trinket_Naxxramas04",
"side": "",
"obtainable": true
},
{
"id": "2139",
"icon": "Ability_Rogue_QuickRecovery",
"side": "",
"obtainable": true
},
{
"id": "2183",
"icon": "INV_Misc_Herb_Ragveil",
"side": "",
"obtainable": true
},
{
"id": "567",
"icon": "INV_Misc_Cauldron_Nature",
"side": "",
"obtainable": true
},
{
"id": "1857",
"icon": "Spell_Shadow_PlagueCloud",
"side": "",
"obtainable": true
},
{
"id": "2179",
"icon": "Spell_ChargePositive",
"side": "",
"obtainable": true
},
{
"id": "2181",
"icon": "Spell_ChargeNegative",
"side": "",
"obtainable": true
},
{
"id": "565",
"icon": "Ability_Rogue_DeviousPoisons",
"side": "",
"obtainable": true
},
{
"id": "2177",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "569",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "2147",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "573",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "2185",
"icon": "Spell_Deathknight_PlagueStrike",
"side": "",
"obtainable": true
},
{
"id": "575",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "577",
"icon": "Achievement_Dungeon_Naxxramas_10man",
"side": "",
"obtainable": true
},
{
"id": "579",
"icon": "Spell_Shadow_RaiseDead",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Obsidian Sanctum (25 player)",
"achs": [
{
"id": "625",
"icon": "Achievement_Dungeon_CoABlackDragonflight_10man",
"side": "",
"obtainable": true
},
{
"id": "2048",
"icon": "Spell_Shaman_LavaFlow",
"side": "",
"obtainable": true
},
{
"id": "1877",
"icon": "Achievement_Dungeon_CoABlackDragonflight_25man",
"side": "",
"obtainable": true
},
{
"id": "2052",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2053",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
},
{
"id": "2054",
"icon": "Achievement_Dungeon_CoABlackDragonflight_Normal",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Eye of Eternity (25 player)",
"achs": [
{
"id": "2149",
"icon": "INV_Elemental_Mote_Shadow01",
"side": "",
"obtainable": true
},
{
"id": "623",
"icon": "Achievement_Dungeon_NexusRaid_10man",
"side": "",
"obtainable": true
},
{
"id": "1870",
"icon": "Achievement_Dungeon_NexusRaid_25man",
"side": "",
"obtainable": true
},
{
"id": "1875",
"icon": "Achievement_Dungeon_NexusRaid",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Secrets of Ulduar (10 player)",
"zones": [
{
"name": "The Siege of Ulduar (10 player)",
"achs": [
{
"id": "2909",
"icon": "Achievement_Boss_TheFlameLeviathan_01",
"side": "",
"obtainable": true
},
{
"id": "3097",
"icon": "ability_vehicle_liquidpyrite_blue",
"side": "",
"obtainable": true
},
{
"id": "2905",
"icon": "INV_Misc_Wrench_02",
"side": "",
"obtainable": true
},
{
"id": "2907",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "2911",
"icon": "INV_Misc_EngGizmos_02",
"side": "",
"obtainable": true
},
{
"id": "2913",
"icon": "INV_Misc_Orb_04",
"side": "",
"obtainable": true
},
{
"id": "2914",
"icon": "INV_Misc_Orb_03",
"side": "",
"obtainable": true
},
{
"id": "2915",
"icon": "INV_Misc_Orb_05",
"side": "",
"obtainable": true
},
{
"id": "3056",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "2925",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "2927",
"icon": "Spell_Fire_Immolation",
"side": "",
"obtainable": true
},
{
"id": "2930",
"icon": "Achievement_Boss_Ignis_01",
"side": "",
"obtainable": true
},
{
"id": "2923",
"icon": "Achievement_Dungeon_UlduarRaid_IronDwarf_01",
"side": "",
"obtainable": true
},
{
"id": "2919",
"icon": "Achievement_Boss_Razorscale",
"side": "",
"obtainable": true
},
{
"id": "2931",
"icon": "INV_Misc_EngGizmos_14",
"side": "",
"obtainable": true
},
{
"id": "3058",
"icon": "INV_ValentinesCardTornLeft",
"side": "",
"obtainable": true
},
{
"id": "2933",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2934",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2937",
"icon": "achievement_boss_xt002deconstructor_01",
"side": "",
"obtainable": true
},
{
"id": "2886",
"icon": "Achievement_Dungeon_UlduarRaid_Archway_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Antechamber of Ulduar (10 player)",
"achs": [
{
"id": "2939",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2940",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2941",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2945",
"icon": "INV_Drink_01",
"side": "",
"obtainable": true
},
{
"id": "2947",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2953",
"icon": "Ability_Warrior_Disarm",
"side": "",
"obtainable": true
},
{
"id": "2955",
"icon": "Spell_Fire_BlueFlameBolt",
"side": "",
"obtainable": true
},
{
"id": "2951",
"icon": "Achievement_Boss_Kologarn_01",
"side": "",
"obtainable": true
},
{
"id": "2959",
"icon": "INV_Elemental_Primal_Earth",
"side": "",
"obtainable": true
},
{
"id": "3076",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "3006",
"icon": "Achievement_Boss_Auriaya_01",
"side": "",
"obtainable": true
},
{
"id": "2888",
"icon": "Achievement_Boss_TribunalofAges",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Keepers of Ulduar (10 player)",
"achs": [
{
"id": "2989",
"icon": "Ability_Mage_MissileBarrage",
"side": "",
"obtainable": true
},
{
"id": "3180",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
},
{
"id": "3138",
"icon": "INV_Gizmo_RocketLauncher",
"side": "",
"obtainable": true
},
{
"id": "2979",
"icon": "Ability_Druid_ForceofNature",
"side": "",
"obtainable": true
},
{
"id": "2980",
"icon": "Ability_Druid_Flourish",
"side": "",
"obtainable": true
},
{
"id": "2982",
"icon": "Achievement_Boss_Freya_01",
"side": "",
"obtainable": true
},
{
"id": "2985",
"icon": "Spell_Nature_NatureTouchDecay",
"side": "",
"obtainable": true
},
{
"id": "3177",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3178",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3179",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "2971",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2973",
"icon": "Achievement_Dungeon_UlduarRaid_IronSentinel_01",
"side": "",
"obtainable": true
},
{
"id": "2975",
"icon": "Spell_Nature_WispSplode",
"side": "",
"obtainable": true
},
{
"id": "2977",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "3176",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "2961",
"icon": "Spell_Frost_FreezingBreath",
"side": "",
"obtainable": true
},
{
"id": "2963",
"icon": "Spell_Frost_ManaRecharge",
"side": "",
"obtainable": true
},
{
"id": "2967",
"icon": "Achievement_Boss_Hodir_01",
"side": "",
"obtainable": true
},
{
"id": "2969",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "3182",
"icon": "INV_Box_04",
"side": "",
"obtainable": true
},
{
"id": "2890",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Descent into Madness (10 player)",
"achs": [
{
"id": "2996",
"icon": "Spell_Shadow_PainSpike",
"side": "",
"obtainable": true
},
{
"id": "3181",
"icon": "Achievement_Boss_GeneralVezax_01",
"side": "",
"obtainable": true
},
{
"id": "3008",
"icon": "Spell_Shadow_MindRot",
"side": "",
"obtainable": true
},
{
"id": "3009",
"icon": "INV_ValentinesCard02",
"side": "",
"obtainable": true
},
{
"id": "3012",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3014",
"icon": "Achievement_Boss_HeraldVolazj",
"side": "",
"obtainable": true
},
{
"id": "3015",
"icon": "Spell_Shadow_Brainwash",
"side": "",
"obtainable": true
},
{
"id": "3157",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3141",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3158",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3159",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "2892",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ulduar (10 player)",
"achs": [
{
"id": "2894",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_01",
"side": "",
"obtainable": true
},
{
"id": "3036",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3003",
"icon": "Spell_Shadow_MindTwisting",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Secrets of Ulduar (25 player)",
"zones": [
{
"name": "The Siege of Ulduar (25 player)",
"achs": [
{
"id": "2910",
"icon": "INV_Misc_MissileSmall_Red",
"side": "",
"obtainable": true
},
{
"id": "3098",
"icon": "ability_vehicle_liquidpyrite_blue",
"side": "",
"obtainable": true
},
{
"id": "2906",
"icon": "INV_Misc_Wrench_02",
"side": "",
"obtainable": true
},
{
"id": "2908",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "2912",
"icon": "INV_Misc_EngGizmos_02",
"side": "",
"obtainable": true
},
{
"id": "2918",
"icon": "INV_Misc_Orb_04",
"side": "",
"obtainable": true
},
{
"id": "2916",
"icon": "INV_Misc_Orb_03",
"side": "",
"obtainable": true
},
{
"id": "2917",
"icon": "INV_Misc_Orb_05",
"side": "",
"obtainable": true
},
{
"id": "3057",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "2926",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "2928",
"icon": "Spell_Fire_Immolation",
"side": "",
"obtainable": true
},
{
"id": "2929",
"icon": "Achievement_Boss_Ignis_01",
"side": "",
"obtainable": true
},
{
"id": "2924",
"icon": "Achievement_Dungeon_UlduarRaid_IronDwarf_01",
"side": "",
"obtainable": true
},
{
"id": "2921",
"icon": "Achievement_Boss_Razorscale",
"side": "",
"obtainable": true
},
{
"id": "2932",
"icon": "INV_Misc_EngGizmos_14",
"side": "",
"obtainable": true
},
{
"id": "3059",
"icon": "INV_ValentinesCardTornLeft",
"side": "",
"obtainable": true
},
{
"id": "2935",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2936",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2938",
"icon": "achievement_boss_xt002deconstructor_01",
"side": "",
"obtainable": true
},
{
"id": "2887",
"icon": "Achievement_Dungeon_UlduarRaid_Archway_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Antechamber of Ulduar (25 player)",
"achs": [
{
"id": "2942",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2943",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2944",
"icon": "Achievement_Boss_TheIronCouncil_01",
"side": "",
"obtainable": true
},
{
"id": "2946",
"icon": "INV_Drink_01",
"side": "",
"obtainable": true
},
{
"id": "2948",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2954",
"icon": "Ability_Warrior_Disarm",
"side": "",
"obtainable": true
},
{
"id": "2956",
"icon": "Spell_Fire_BlueFlameBolt",
"side": "",
"obtainable": true
},
{
"id": "2952",
"icon": "Achievement_Boss_Kologarn_01",
"side": "",
"obtainable": true
},
{
"id": "2960",
"icon": "INV_Elemental_Primal_Earth",
"side": "",
"obtainable": true
},
{
"id": "3077",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "3007",
"icon": "Achievement_Boss_Auriaya_01",
"side": "",
"obtainable": true
},
{
"id": "2889",
"icon": "Achievement_Boss_TribunalofAges",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Keepers of Ulduar (25 player)",
"achs": [
{
"id": "3237",
"icon": "Ability_Mage_MissileBarrage",
"side": "",
"obtainable": true
},
{
"id": "3189",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
},
{
"id": "2995",
"icon": "INV_Gizmo_RocketLauncher",
"side": "",
"obtainable": true
},
{
"id": "3118",
"icon": "Ability_Druid_ForceofNature",
"side": "",
"obtainable": true
},
{
"id": "2981",
"icon": "Ability_Druid_Flourish",
"side": "",
"obtainable": true
},
{
"id": "2983",
"icon": "Achievement_Boss_Freya_01",
"side": "",
"obtainable": true
},
{
"id": "2984",
"icon": "Spell_Nature_NatureTouchDecay",
"side": "",
"obtainable": true
},
{
"id": "3185",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3186",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "3187",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "2972",
"icon": "Spell_Lightning_LightningBolt01",
"side": "",
"obtainable": true
},
{
"id": "2974",
"icon": "Achievement_Dungeon_UlduarRaid_IronSentinel_01",
"side": "",
"obtainable": true
},
{
"id": "2976",
"icon": "Spell_Nature_WispSplode",
"side": "",
"obtainable": true
},
{
"id": "2978",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "3183",
"icon": "Achievement_Boss_Thorim",
"side": "",
"obtainable": true
},
{
"id": "2962",
"icon": "Spell_Frost_FreezingBreath",
"side": "",
"obtainable": true
},
{
"id": "2965",
"icon": "Spell_Frost_ManaRecharge",
"side": "",
"obtainable": true
},
{
"id": "2968",
"icon": "Achievement_Boss_Hodir_01",
"side": "",
"obtainable": true
},
{
"id": "2970",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "3184",
"icon": "INV_Box_04",
"side": "",
"obtainable": true
},
{
"id": "2891",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Descent into Madness (25 player)",
"achs": [
{
"id": "2997",
"icon": "Spell_Shadow_PainSpike",
"side": "",
"obtainable": true
},
{
"id": "3188",
"icon": "Achievement_Boss_GeneralVezax_01",
"side": "",
"obtainable": true
},
{
"id": "3010",
"icon": "Spell_Shadow_MindRot",
"side": "",
"obtainable": true
},
{
"id": "3011",
"icon": "INV_ValentinesCard02",
"side": "",
"obtainable": true
},
{
"id": "3013",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3017",
"icon": "Achievement_Boss_HeraldVolazj",
"side": "",
"obtainable": true
},
{
"id": "3016",
"icon": "Spell_Shadow_Brainwash",
"side": "",
"obtainable": true
},
{
"id": "3161",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3162",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3163",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "3164",
"icon": "Spell_Shadow_Shadesofdarkness",
"side": "",
"obtainable": true
},
{
"id": "2893",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Ulduar (25 player)",
"achs": [
{
"id": "2895",
"icon": "Achievement_Dungeon_UlduarRaid_Misc_01",
"side": "",
"obtainable": true
},
{
"id": "3037",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3002",
"icon": "Spell_Shadow_MindTwisting",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Call of the Crusade",
"zones": [
{
"name": "Trial of the Crusader (10 player)",
"achs": [
{
"id": "3936",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "3797",
"icon": "INV_Ammo_Snowball",
"side": "",
"obtainable": true
},
{
"id": "3996",
"icon": "Spell_Shadow_ShadowMend",
"side": "",
"obtainable": true
},
{
"id": "3798",
"icon": "Achievement_Arena_5v5_3",
"side": "",
"obtainable": true
},
{
"id": "3799",
"icon": "Achievement_Boss_SvalaSorrowgrave",
"side": "",
"obtainable": true
},
{
"id": "3800",
"icon": "Achievement_Boss_Anubarak",
"side": "",
"obtainable": true
},
{
"id": "3917",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3918",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
}
]
},
{
"name": "Trial of the Crusader (25 player)",
"achs": [
{
"id": "3937",
"icon": "ability_hunter_pet_worm",
"side": "",
"obtainable": true
},
{
"id": "3813",
"icon": "INV_Ammo_Snowball",
"side": "",
"obtainable": true
},
{
"id": "3997",
"icon": "Spell_Shadow_ShadowMend",
"side": "",
"obtainable": true
},
{
"id": "3815",
"icon": "Achievement_Boss_SvalaSorrowgrave",
"side": "",
"obtainable": true
},
{
"id": "3816",
"icon": "Achievement_Boss_Anubarak",
"side": "",
"obtainable": true
},
{
"id": "3916",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3812",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
}
]
},
{
"name": "Onyxia's Lair (10 player)",
"achs": [
{
"id": "4396",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4403",
"icon": "INV_Misc_Head_Dragon_Black",
"side": "",
"obtainable": true
},
{
"id": "4402",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "4404",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
}
]
},
{
"name": "Onyxia's Lair (25 player)",
"achs": [
{
"id": "4397",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "4406",
"icon": "INV_Misc_Head_Dragon_Black",
"side": "",
"obtainable": true
},
{
"id": "4405",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "4407",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Fall of the Lich King",
"zones": [
{
"name": "Icecrown Citadel (Normal) (10 player)",
"achs": [
{
"id": "4534",
"icon": "achievement_boss_lordmarrowgar",
"side": "",
"obtainable": true
},
{
"id": "4535",
"icon": "achievement_boss_ladydeathwhisper",
"side": "",
"obtainable": true
},
{
"id": "4536",
"icon": "achievement_dungeon_hordeairship",
"side": "",
"obtainable": true
},
{
"id": "4537",
"icon": "achievement_boss_saurfang",
"side": "",
"obtainable": true
},
{
"id": "4531",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4577",
"icon": "achievement_boss_festergutrotface",
"side": "",
"obtainable": true
},
{
"id": "4538",
"icon": "Spell_Nature_Acid_01",
"side": "",
"obtainable": true
},
{
"id": "4578",
"icon": "achievement_boss_profputricide",
"side": "",
"obtainable": true
},
{
"id": "4528",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4582",
"icon": "achievement_boss_princetaldaram",
"side": "",
"obtainable": true
},
{
"id": "4539",
"icon": "achievement_boss_lanathel",
"side": "",
"obtainable": true
},
{
"id": "4529",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4579",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "4580",
"icon": "achievement_boss_sindragosa",
"side": "",
"obtainable": true
},
{
"id": "4527",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4581",
"icon": "Spell_Shadow_DevouringPlague",
"side": "",
"obtainable": true
},
{
"id": "4601",
"icon": "Spell_DeathKnight_BloodPlague",
"side": "",
"obtainable": true
},
{
"id": "4530",
"icon": "achievement_dungeon_frozenthrone",
"side": "",
"obtainable": true
},
{
"id": "4532",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Heroic) (10 player)",
"achs": [
{
"id": "4628",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4629",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4630",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4631",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4583",
"icon": "achievement_boss_lichking",
"side": "",
"obtainable": true
},
{
"id": "4636",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Ruby Sanctum (10 player)",
"achs": [
{
"id": "4817",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "4818",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Normal) (25 player)",
"achs": [
{
"id": "4610",
"icon": "achievement_boss_lordmarrowgar",
"side": "",
"obtainable": true
},
{
"id": "4611",
"icon": "achievement_boss_ladydeathwhisper",
"side": "",
"obtainable": true
},
{
"id": "4612",
"icon": "achievement_dungeon_hordeairship",
"side": "",
"obtainable": true
},
{
"id": "4613",
"icon": "achievement_boss_saurfang",
"side": "",
"obtainable": true
},
{
"id": "4604",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4615",
"icon": "achievement_boss_festergutrotface",
"side": "",
"obtainable": true
},
{
"id": "4614",
"icon": "Spell_Nature_Acid_01",
"side": "",
"obtainable": true
},
{
"id": "4616",
"icon": "achievement_boss_profputricide",
"side": "",
"obtainable": true
},
{
"id": "4605",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4617",
"icon": "achievement_boss_princetaldaram",
"side": "",
"obtainable": true
},
{
"id": "4618",
"icon": "achievement_boss_lanathel",
"side": "",
"obtainable": true
},
{
"id": "4606",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4619",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "4620",
"icon": "achievement_boss_sindragosa",
"side": "",
"obtainable": true
},
{
"id": "4607",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4622",
"icon": "Spell_Shadow_DevouringPlague",
"side": "",
"obtainable": true
},
{
"id": "4621",
"icon": "Spell_DeathKnight_BloodPlague",
"side": "",
"obtainable": true
},
{
"id": "4597",
"icon": "achievement_dungeon_frozenthrone",
"side": "",
"obtainable": true
},
{
"id": "4608",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "Icecrown Citadel (Heroic) (25 player)",
"achs": [
{
"id": "4632",
"icon": "achievement_dungeon_icecrown_icecrownentrance",
"side": "",
"obtainable": true
},
{
"id": "4633",
"icon": "achievement_dungeon_plaguewing",
"side": "",
"obtainable": true
},
{
"id": "4634",
"icon": "achievement_dungeon_crimsonhall",
"side": "",
"obtainable": true
},
{
"id": "4635",
"icon": "achievement_dungeon_icecrown_frostwinghalls",
"side": "",
"obtainable": true
},
{
"id": "4584",
"icon": "Spell_Holy_Aspiration",
"side": "",
"obtainable": true
},
{
"id": "4637",
"icon": "achievement_dungeon_icecrown_frostmourne",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Ruby Sanctum (25 player)",
"achs": [
{
"id": "4815",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
},
{
"id": "4816",
"icon": "Spell_Shadow_Twilight",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "The Burning Crusade",
"zones": [
{
"name": "Normal Dungeons",
"achs": [
{
"id": "647",
"icon": "Achievement_Boss_OmarTheUnscarred_01",
"side": "",
"obtainable": true
},
{
"id": "648",
"icon": "Achievement_Boss_KelidanTheBreaker",
"side": "",
"obtainable": true
},
{
"id": "649",
"icon": "Achievement_Boss_Quagmirran",
"side": "",
"obtainable": true
},
{
"id": "650",
"icon": "Achievement_Boss_theBlackStalker",
"side": "",
"obtainable": true
},
{
"id": "651",
"icon": "Achievement_Boss_Nexus_Prince_Shaffar",
"side": "",
"obtainable": true
},
{
"id": "666",
"icon": "Achievement_Boss_Exarch_Maladaar",
"side": "",
"obtainable": true
},
{
"id": "652",
"icon": "Achievement_Boss_EpochHunter",
"side": "",
"obtainable": true
},
{
"id": "653",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "654",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "656",
"icon": "Achievement_Boss_Warlord_Kalithresh",
"side": "",
"obtainable": true
},
{
"id": "657",
"icon": "Achievement_Boss_KargathBladefist_01",
"side": "",
"obtainable": true
},
{
"id": "658",
"icon": "Achievement_Boss_PathaleonTheCalculator",
"side": "",
"obtainable": true
},
{
"id": "659",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "655",
"icon": "Achievement_Boss_Aeonus_01",
"side": "",
"obtainable": true
},
{
"id": "660",
"icon": "Achievement_Boss_Harbinger_Skyriss",
"side": "",
"obtainable": true
},
{
"id": "661",
"icon": "Achievement_Boss_Kael'thasSunstrider_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Heroic Dungeons",
"achs": [
{
"id": "667",
"icon": "Achievement_Boss_OmarTheUnscarred_01",
"side": "",
"obtainable": true
},
{
"id": "668",
"icon": "Achievement_Boss_KelidanTheBreaker",
"side": "",
"obtainable": true
},
{
"id": "669",
"icon": "Achievement_Boss_Quagmirran",
"side": "",
"obtainable": true
},
{
"id": "670",
"icon": "Achievement_Boss_theBlackStalker",
"side": "",
"obtainable": true
},
{
"id": "671",
"icon": "Achievement_Boss_Nexus_Prince_Shaffar",
"side": "",
"obtainable": true
},
{
"id": "672",
"icon": "Achievement_Boss_Exarch_Maladaar",
"side": "",
"obtainable": true
},
{
"id": "673",
"icon": "Achievement_Boss_EpochHunter",
"side": "",
"obtainable": true
},
{
"id": "674",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "675",
"icon": "Achievement_Boss_Murmur",
"side": "",
"obtainable": true
},
{
"id": "677",
"icon": "Achievement_Boss_Warlord_Kalithresh",
"side": "",
"obtainable": true
},
{
"id": "678",
"icon": "Achievement_Boss_KargathBladefist_01",
"side": "",
"obtainable": true
},
{
"id": "679",
"icon": "Achievement_Boss_PathaleonTheCalculator",
"side": "",
"obtainable": true
},
{
"id": "680",
"icon": "Achievement_Boss_WarpSplinter",
"side": "",
"obtainable": true
},
{
"id": "676",
"icon": "Achievement_Boss_Aeonus_01",
"side": "",
"obtainable": true
},
{
"id": "681",
"icon": "Achievement_Boss_Harbinger_Skyriss",
"side": "",
"obtainable": true
},
{
"id": "682",
"icon": "Achievement_Boss_Kael'thasSunstrider_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Raids",
"achs": [
{
"id": "690",
"icon": "Achievement_Boss_PrinceMalchezaar_02",
"side": "",
"obtainable": true
},
{
"id": "692",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "",
"obtainable": true
},
{
"id": "693",
"icon": "Achievement_Boss_Magtheridon",
"side": "",
"obtainable": true
},
{
"id": "694",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "696",
"icon": "Achievement_Character_Bloodelf_Male",
"side": "",
"obtainable": true
},
{
"id": "695",
"icon": "Achievement_Boss_Archimonde-",
"side": "",
"obtainable": true
},
{
"id": "697",
"icon": "Achievement_Boss_Illidan",
"side": "",
"obtainable": true
},
{
"id": "698",
"icon": "Achievement_Boss_Kiljaedan",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Classic",
"zones": [
{
"name": "Eastern Kingdoms Dungeons",
"achs": [
{
"id": "628",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "631",
"icon": "inv_helm_robe_dungeonrobe_c_04",
"side": "",
"obtainable": true
},
{
"id": "633",
"icon": "INV_Misc_Head_Gnoll_01",
"side": "",
"obtainable": true
},
{
"id": "634",
"icon": "Achievement_Boss_Mekgineer_Thermaplugg-",
"side": "",
"obtainable": true
},
{
"id": "637",
"icon": "INV_Helmet_52",
"side": "",
"obtainable": true
},
{
"id": "7413",
"icon": "inv_helmet_52",
"side": "",
"obtainable": true
},
{
"id": "638",
"icon": "Achievement_Boss_Archaedas",
"side": "",
"obtainable": true
},
{
"id": "645",
"icon": "Spell_Holy_SenseUndead",
"side": "",
"obtainable": true
},
{
"id": "646",
"icon": "Spell_DeathKnight_ArmyOfTheDead",
"side": "",
"obtainable": true
},
{
"id": "641",
"icon": "Achievement_Boss_ShadeOfEranikus",
"side": "",
"obtainable": true
},
{
"id": "642",
"icon": "Achievement_Boss_EmperorDagranThaurissan",
"side": "",
"obtainable": true
},
{
"id": "643",
"icon": "Achievement_Boss_Overlord_Wyrmthalak",
"side": "",
"obtainable": true
},
{
"id": "1307",
"icon": "Achievement_Boss_GeneralDrakkisath",
"side": "",
"obtainable": true
},
{
"id": "2188",
"icon": "Ability_Mount_Drake_Red",
"side": "",
"obtainable": true
}
]
},
{
"name": "Kalimdor Dungeons",
"achs": [
{
"id": "629",
"icon": "Spell_Shadow_SummonFelGuard",
"side": "",
"obtainable": true
},
{
"id": "630",
"icon": "Achievement_Boss_Mutanus_the_Devourer",
"side": "",
"obtainable": true
},
{
"id": "632",
"icon": "Achievement_Boss_Bazil_Akumai",
"side": "",
"obtainable": true
},
{
"id": "635",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "",
"obtainable": true
},
{
"id": "640",
"icon": "Achievement_Boss_PrincessTheradras",
"side": "",
"obtainable": true
},
{
"id": "636",
"icon": "Achievement_Boss_Amnennar_the_Coldbringer",
"side": "",
"obtainable": true
},
{
"id": "644",
"icon": "Ability_Warrior_DecisiveStrike",
"side": "",
"obtainable": true
},
{
"id": "639",
"icon": "Achievement_Boss_ChiefUkorzSandscalp",
"side": "",
"obtainable": true
}
]
},
{
"name": "Classic Raids",
"achs": [
{
"id": "685",
"icon": "Achievement_Boss_Nefarion",
"side": "",
"obtainable": true
},
{
"id": "686",
"icon": "Achievement_Boss_Ragnaros",
"side": "",
"obtainable": true
},
{
"id": "689",
"icon": "Achievement_Boss_OssirianTheUnscarred",
"side": "",
"obtainable": true
},
{
"id": "687",
"icon": "Achievement_Boss_CThun",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Player vs. Player",
"cats": [
{
"name": "Player vs. Player",
"zones": [
{
"name": "Conquest Points",
"achs": [
{
"id": "5542",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5541",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5540",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "5539",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "8093",
"icon": "achievement_bg_winwsg",
"side": "H",
"obtainable": true
},
{
"id": "8218",
"icon": "achievement_bg_winwsg",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Kills",
"achs": [
{
"id": "238",
"icon": "Achievement_PVP_P_01",
"side": "",
"obtainable": true
},
{
"id": "513",
"icon": "Achievement_PVP_P_02",
"side": "",
"obtainable": true
},
{
"id": "515",
"icon": "Achievement_PVP_P_03",
"side": "",
"obtainable": true
},
{
"id": "516",
"icon": "Achievement_PVP_P_04",
"side": "",
"obtainable": true
},
{
"id": "512",
"icon": "Achievement_PVP_P_06",
"side": "",
"obtainable": true
},
{
"id": "509",
"icon": "Achievement_PVP_P_09",
"side": "",
"obtainable": true
},
{
"id": "239",
"icon": "Achievement_PVP_P_11",
"side": "",
"obtainable": true
},
{
"id": "869",
"icon": "Achievement_PVP_P_14",
"side": "",
"obtainable": true
},
{
"id": "870",
"icon": "Achievement_PVP_P_15",
"side": "",
"obtainable": true
},
{
"id": "5363",
"icon": "achievement_pvp_p_250k",
"side": "",
"obtainable": true
}
]
},
{
"name": "Battlegrounds",
"achs": [
{
"id": "727",
"icon": "Ability_Mount_BlackDireWolf",
"side": "",
"obtainable": true
},
{
"id": "908",
"icon": "Ability_Warrior_Incite",
"side": "A",
"obtainable": true
},
{
"id": "909",
"icon": "Ability_Warrior_Incite",
"side": "H",
"obtainable": true
},
{
"id": "227",
"icon": "Achievement_BG_topDPS",
"side": "",
"obtainable": true
},
{
"id": "229",
"icon": "Spell_Shadow_NetherCloak",
"side": "",
"obtainable": true
},
{
"id": "231",
"icon": "Ability_Warrior_Trauma",
"side": "",
"obtainable": true
},
{
"id": "907",
"icon": "INV_Misc_TabardPVP_03",
"side": "A",
"obtainable": true
},
{
"id": "714",
"icon": "INV_Misc_TabardPVP_04",
"side": "H",
"obtainable": true
},
{
"id": "230",
"icon": "Achievement_PVP_A_15",
"side": "A",
"obtainable": true
},
{
"id": "1175",
"icon": "Achievement_PVP_H_15",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Cities",
"achs": [
{
"id": "604",
"icon": "INV_Trinket_HonorHold",
"side": "A",
"obtainable": true
},
{
"id": "603",
"icon": "INV_Trinket_Thrallmar",
"side": "H",
"obtainable": true
},
{
"id": "388",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "1006",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "613",
"icon": "Achievement_Leader_Lorthemar_Theron-",
"side": "A",
"obtainable": true
},
{
"id": "611",
"icon": "Achievement_Leader_Cairne-Bloodhoof",
"side": "A",
"obtainable": true
},
{
"id": "612",
"icon": "Achievement_Leader_Sylvanas",
"side": "A",
"obtainable": true
},
{
"id": "610",
"icon": "inv_axe_60",
"side": "A",
"obtainable": true
},
{
"id": "618",
"icon": "Achievement_Leader_Prophet_Velen",
"side": "H",
"obtainable": true
},
{
"id": "617",
"icon": "Achievement_Leader_Tyrande_Whisperwind",
"side": "H",
"obtainable": true
},
{
"id": "616",
"icon": "achievement_zone_ironforge",
"side": "H",
"obtainable": true
},
{
"id": "615",
"icon": "Achievement_Leader_King_Varian_Wrynn",
"side": "H",
"obtainable": true
},
{
"id": "614",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "619",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "1157",
"icon": "Ability_DualWieldSpecialization",
"side": "",
"obtainable": true
},
{
"id": "701",
"icon": "INV_Jewelry_TrinketPVP_01",
"side": "A",
"obtainable": true
},
{
"id": "700",
"icon": "INV_Jewelry_TrinketPVP_02",
"side": "H",
"obtainable": true
},
{
"id": "246",
"icon": "Ability_Gouge",
"side": "A",
"obtainable": true
},
{
"id": "1005",
"icon": "Ability_Gouge",
"side": "H",
"obtainable": true
},
{
"id": "245",
"icon": "Ability_CheapShot",
"side": "",
"obtainable": true
},
{
"id": "247",
"icon": "Spell_BrokenHeart",
"side": "",
"obtainable": true
},
{
"id": "389",
"icon": "INV_Misc_ArmorKit_14",
"side": "",
"obtainable": true
},
{
"id": "396",
"icon": "INV_Misc_ArmorKit_04",
"side": "",
"obtainable": true
},
{
"id": "2016",
"icon": "Achievement_Zone_GrizzlyHills_11",
"side": "A",
"obtainable": true
},
{
"id": "2017",
"icon": "Achievement_Zone_GrizzlyHills_11",
"side": "H",
"obtainable": true
},
{
"id": "8052",
"icon": "achievement_pvp_a_15",
"side": "A",
"obtainable": true
},
{
"id": "8055",
"icon": "achievement_pvp_a_15",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Deepwind Gorge",
"zones": [
{
"name": "",
"achs": [
{
"id": "8359",
"icon": "achievement_bg_captureflag_eos",
"side": "",
"obtainable": true
},
{
"id": "8358",
"icon": "ability_warrior_intensifyrage",
"side": "",
"obtainable": true
},
{
"id": "8333",
"icon": "achievement_bg_abshutout",
"side": "",
"obtainable": true
},
{
"id": "8332",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8331",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8360",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "8350",
"icon": "achievement_bg_winav_bothmines",
"side": "",
"obtainable": true
},
{
"id": "8351",
"icon": "achievement_bg_tophealer_ab",
"side": "",
"obtainable": true
},
{
"id": "8354",
"icon": "spell_magic_featherfall",
"side": "",
"obtainable": true
},
{
"id": "8355",
"icon": "inv_stone_weightstone_06",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Silvershard Mines",
"zones": [
{
"name": "",
"achs": [
{
"id": "6739",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
},
{
"id": "6883",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
},
{
"id": "7039",
"icon": "inv_misc_gem_diamond_07",
"side": "",
"obtainable": true
},
{
"id": "7049",
"icon": "inv_misc_gem_diamond_07",
"side": "",
"obtainable": true
},
{
"id": "7057",
"icon": "achievement_bg_winav_bothmines",
"side": "",
"obtainable": true
},
{
"id": "7062",
"icon": "inv_pick_02",
"side": "",
"obtainable": true
},
{
"id": "7099",
"icon": "achievement_bg_getxflags_no_die",
"side": "",
"obtainable": true
},
{
"id": "7100",
"icon": "inv_crate_07",
"side": "",
"obtainable": true
},
{
"id": "7102",
"icon": "inv_crate_07",
"side": "",
"obtainable": true
},
{
"id": "7103",
"icon": "ability_racial_packhobgoblin",
"side": "",
"obtainable": true
},
{
"id": "7106",
"icon": "achievement_battleground_silvershardmines",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Temple of Kotmogu",
"zones": [
{
"name": "",
"achs": [
{
"id": "6740",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6882",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6947",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
},
{
"id": "6950",
"icon": "ability_rogue_fleetfooted",
"side": "",
"obtainable": true
},
{
"id": "6970",
"icon": "ability_monk_blackoutkick",
"side": "",
"obtainable": true
},
{
"id": "6971",
"icon": "achievement_bg_abshutout",
"side": "",
"obtainable": true
},
{
"id": "6972",
"icon": "achievement_bg_kill_flag_carrier",
"side": "",
"obtainable": true
},
{
"id": "6973",
"icon": "ability_warrior_intensifyrage",
"side": "",
"obtainable": true
},
{
"id": "6980",
"icon": "ability_wintergrasp_rank1",
"side": "",
"obtainable": true
},
{
"id": "6981",
"icon": "achievement_battleground_templeofkotmogu",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Warsong Gulch",
"zones": [
{
"name": "",
"achs": [
{
"id": "713",
"icon": "Ability_Racial_ShadowMeld",
"side": "A",
"obtainable": true
},
{
"id": "712",
"icon": "Ability_Warrior_WarCry",
"side": "H",
"obtainable": true
},
{
"id": "1259",
"icon": "Ability_Rogue_Trip",
"side": "",
"obtainable": true
},
{
"id": "199",
"icon": "Achievement_BG_captureflag_WSG",
"side": "",
"obtainable": true
},
{
"id": "202",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "A",
"obtainable": true
},
{
"id": "1502",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "H",
"obtainable": true
},
{
"id": "204",
"icon": "Achievement_BG_3flagcap_nodeaths",
"side": "",
"obtainable": true
},
{
"id": "872",
"icon": "Achievement_BG_returnXflags_def_WSG",
"side": "",
"obtainable": true
},
{
"id": "203",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "A",
"obtainable": true
},
{
"id": "1251",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "H",
"obtainable": true
},
{
"id": "207",
"icon": "Ability_Rogue_SurpriseAttack",
"side": "",
"obtainable": true
},
{
"id": "206",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "A",
"obtainable": true
},
{
"id": "1252",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "H",
"obtainable": true
},
{
"id": "200",
"icon": "Achievement_BG_interruptX_flagcapture_attempts",
"side": "",
"obtainable": true
},
{
"id": "166",
"icon": "Achievement_BG_winWSG",
"side": "",
"obtainable": true
},
{
"id": "167",
"icon": "Achievement_BG_win_WSG_X_times",
"side": "",
"obtainable": true
},
{
"id": "201",
"icon": "Achievement_BG_winWSG_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "168",
"icon": "Achievement_BG_winWSG_3-0",
"side": "",
"obtainable": true
},
{
"id": "1172",
"icon": "INV_Misc_Rune_07",
"side": "A",
"obtainable": true
},
{
"id": "1173",
"icon": "INV_Misc_Rune_07",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Arathi Basin",
"zones": [
{
"name": "",
"achs": [
{
"id": "711",
"icon": "Ability_Warrior_RallyingCry",
"side": "A",
"obtainable": true
},
{
"id": "710",
"icon": "Spell_Shadow_PsychicHorrors",
"side": "H",
"obtainable": true
},
{
"id": "583",
"icon": "Ability_Warrior_IntensifyRage",
"side": "",
"obtainable": true
},
{
"id": "584",
"icon": "Ability_Hunter_RapidKilling",
"side": "",
"obtainable": true
},
{
"id": "73",
"icon": "Ability_Warrior_BattleShout",
"side": "",
"obtainable": true
},
{
"id": "1153",
"icon": "Achievement_BG_AB_defendflags",
"side": "",
"obtainable": true
},
{
"id": "158",
"icon": "Achievement_BG_takeXflags_AB",
"side": "",
"obtainable": true
},
{
"id": "157",
"icon": "Ability_Warrior_VictoryRush",
"side": "",
"obtainable": true
},
{
"id": "154",
"icon": "Achievement_BG_winAB",
"side": "",
"obtainable": true
},
{
"id": "155",
"icon": "Achievement_BG_win_AB_X_times",
"side": "",
"obtainable": true
},
{
"id": "159",
"icon": "Achievement_BG_winAB_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "156",
"icon": "Achievement_BG_winAB_5cap",
"side": "",
"obtainable": true
},
{
"id": "161",
"icon": "Achievement_BG_overcome500disadvantage",
"side": "",
"obtainable": true
},
{
"id": "162",
"icon": "Spell_Shadow_ImprovedVampiricEmbrace",
"side": "",
"obtainable": true
},
{
"id": "165",
"icon": "Achievement_BG_ABshutout",
"side": "",
"obtainable": true
},
{
"id": "1169",
"icon": "INV_Jewelry_Amulet_07",
"side": "A",
"obtainable": true
},
{
"id": "1170",
"icon": "INV_Jewelry_Amulet_07",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Alterac Valley",
"zones": [
{
"name": "",
"achs": [
{
"id": "708",
"icon": "INV_Jewelry_FrostwolfTrinket_05",
"side": "H",
"obtainable": true
},
{
"id": "709",
"icon": "INV_Jewelry_StormPikeTrinket_05",
"side": "A",
"obtainable": true
},
{
"id": "706",
"icon": "INV_Jewelry_FrostwolfTrinket_01",
"side": "H",
"obtainable": true
},
{
"id": "707",
"icon": "INV_Jewelry_StormPikeTrinket_01",
"side": "A",
"obtainable": true
},
{
"id": "223",
"icon": "Achievement_BG_kill_on_mount",
"side": "",
"obtainable": true
},
{
"id": "1166",
"icon": "INV_Scroll_10",
"side": "",
"obtainable": true
},
{
"id": "221",
"icon": "Achievement_BG_Xkills_AVgraveyard",
"side": "",
"obtainable": true
},
{
"id": "222",
"icon": "Achievement_BG_DefendXtowers_AV",
"side": "",
"obtainable": true
},
{
"id": "224",
"icon": "Achievement_BG_KillXEnemies_GeneralsRoom",
"side": "H",
"obtainable": true
},
{
"id": "1151",
"icon": "Achievement_BG_KillXEnemies_GeneralsRoom",
"side": "A",
"obtainable": true
},
{
"id": "582",
"icon": "Spell_Holy_Heroism",
"side": "",
"obtainable": true
},
{
"id": "218",
"icon": "Achievement_BG_winAV",
"side": "",
"obtainable": true
},
{
"id": "219",
"icon": "Achievement_BG_win_AV_X_times",
"side": "",
"obtainable": true
},
{
"id": "226",
"icon": "Achievement_BG_winAV_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "225",
"icon": "Achievement_BG_winAV_bothmines",
"side": "A",
"obtainable": true
},
{
"id": "1164",
"icon": "Achievement_BG_winAV_bothmines",
"side": "H",
"obtainable": true
},
{
"id": "873",
"icon": "INV_Jewelry_FrostwolfTrinket_03",
"side": "H",
"obtainable": true
},
{
"id": "220",
"icon": "INV_Jewelry_StormPikeTrinket_03",
"side": "A",
"obtainable": true
},
{
"id": "1167",
"icon": "INV_Jewelry_Necklace_21",
"side": "A",
"obtainable": true
},
{
"id": "1168",
"icon": "INV_Jewelry_Necklace_21",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Eye of the Storm",
"zones": [
{
"name": "",
"achs": [
{
"id": "233",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "1258",
"icon": "Achievement_BG_killingblow_berserker",
"side": "",
"obtainable": true
},
{
"id": "212",
"icon": "Achievement_BG_captureflag_EOS",
"side": "",
"obtainable": true
},
{
"id": "211",
"icon": "Achievement_BG_hld4bases_EOS",
"side": "",
"obtainable": true
},
{
"id": "216",
"icon": "Spell_Arcane_MassDispel",
"side": "",
"obtainable": true
},
{
"id": "213",
"icon": "Achievement_BG_kill_flag_carrierEOS",
"side": "",
"obtainable": true
},
{
"id": "587",
"icon": "Ability_Druid_GaleWinds",
"side": "",
"obtainable": true
},
{
"id": "208",
"icon": "Achievement_BG_winEOS",
"side": "",
"obtainable": true
},
{
"id": "209",
"icon": "Achievement_BG_win_EOS_X_times",
"side": "",
"obtainable": true
},
{
"id": "214",
"icon": "Achievement_BG_winEOS_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "784",
"icon": "INV_BRD_Banner",
"side": "",
"obtainable": true
},
{
"id": "783",
"icon": "INV_BRD_Banner",
"side": "",
"obtainable": true
},
{
"id": "1171",
"icon": "Spell_Nature_EyeOfTheStorm",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Strand of the Ancients",
"zones": [
{
"name": "",
"achs": [
{
"id": "1765",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "2193",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "1761",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "2190",
"icon": "Ability_Rogue_Dismantle",
"side": "",
"obtainable": true
},
{
"id": "1764",
"icon": "Ability_Hunter_BeastSoothe",
"side": "",
"obtainable": true
},
{
"id": "1766",
"icon": "Ability_Rogue_BloodSplatter",
"side": "",
"obtainable": true
},
{
"id": "2191",
"icon": "Ability_Rogue_Ambush",
"side": "",
"obtainable": true
},
{
"id": "2189",
"icon": "INV_Ammo_Bullet_03",
"side": "",
"obtainable": true
},
{
"id": "1763",
"icon": "INV_Weapon_Rifle_19",
"side": "",
"obtainable": true
},
{
"id": "1757",
"icon": "Ability_Warrior_DefensiveStance",
"side": "A",
"obtainable": true
},
{
"id": "2200",
"icon": "Ability_Warrior_DefensiveStance",
"side": "H",
"obtainable": true
},
{
"id": "1308",
"icon": "Achievement_BG_winSOA",
"side": "",
"obtainable": true
},
{
"id": "1309",
"icon": "Achievement_BG_winSOA",
"side": "",
"obtainable": true
},
{
"id": "1310",
"icon": "Achievement_BG_winSOA_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "1762",
"icon": "Ability_Warrior_Charge",
"side": "A",
"obtainable": true
},
{
"id": "2192",
"icon": "Ability_Warrior_Charge",
"side": "H",
"obtainable": true
},
{
"id": "2194",
"icon": "Achievement_BG_winSOA",
"side": "A",
"obtainable": true
},
{
"id": "2195",
"icon": "Achievement_BG_winSOA",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Isle of Conquest",
"zones": [
{
"name": "",
"achs": [
{
"id": "3848",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
},
{
"id": "3849",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "3853",
"icon": "INV_Weapon_Shortblade_37",
"side": "",
"obtainable": true
},
{
"id": "3854",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "3852",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "3856",
"icon": "INV_Gizmo_SuperSapperCharge",
"side": "A",
"obtainable": true
},
{
"id": "3850",
"icon": "INV_Misc_MissileSmallCluster_Red",
"side": "",
"obtainable": true
},
{
"id": "4256",
"icon": "INV_Gizmo_SuperSapperCharge",
"side": "H",
"obtainable": true
},
{
"id": "3847",
"icon": "INV_Gizmo_02",
"side": "",
"obtainable": true
},
{
"id": "3855",
"icon": "Ability_UpgradeMoonGlaive",
"side": "",
"obtainable": true
},
{
"id": "3845",
"icon": "Spell_Holy_Heroism",
"side": "",
"obtainable": true
},
{
"id": "3776",
"icon": "INV_Shield_61",
"side": "",
"obtainable": true
},
{
"id": "3777",
"icon": "Achievement_BG_win_AV_X_times",
"side": "",
"obtainable": true
},
{
"id": "3846",
"icon": "INV_Gizmo_Pipe_03",
"side": "A",
"obtainable": true
},
{
"id": "4176",
"icon": "INV_Gizmo_Pipe_03",
"side": "H",
"obtainable": true
},
{
"id": "3851",
"icon": "INV_Ingot_Cobalt",
"side": "A",
"obtainable": true
},
{
"id": "4177",
"icon": "INV_Ingot_Cobalt",
"side": "H",
"obtainable": true
},
{
"id": "3857",
"icon": "Achievement_BG_winWSG",
"side": "A",
"obtainable": true
},
{
"id": "3957",
"icon": "Achievement_BG_winWSG",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Battle for Gilneas",
"zones": [
{
"name": "",
"achs": [
{
"id": "5262",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "5257",
"icon": "Ability_Hunter_RapidKilling",
"side": "",
"obtainable": true
},
{
"id": "5256",
"icon": "Ability_Warrior_IntensifyRage",
"side": "",
"obtainable": true
},
{
"id": "5249",
"icon": "Achievement_BG_takeXflags_AB",
"side": "",
"obtainable": true
},
{
"id": "5250",
"icon": "Spell_Nature_Tranquility",
"side": "",
"obtainable": true
},
{
"id": "5251",
"icon": "Ability_Warrior_VictoryRush",
"side": "",
"obtainable": true
},
{
"id": "5248",
"icon": "achievement_bg_tophealer_ab",
"side": "",
"obtainable": true
},
{
"id": "5245",
"icon": "achievement_win_gilneas",
"side": "",
"obtainable": true
},
{
"id": "5254",
"icon": "Achievement_BG_winAV_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "5255",
"icon": "Ability_Rogue_KidneyShot",
"side": "",
"obtainable": true
},
{
"id": "5252",
"icon": "Ability_Rogue_StayofExecution",
"side": "",
"obtainable": true
},
{
"id": "5247",
"icon": "Achievement_BG_ABshutout",
"side": "",
"obtainable": true
},
{
"id": "5253",
"icon": "Achievement_BG_3flagcap_nodeaths",
"side": "",
"obtainable": true
},
{
"id": "5246",
"icon": "achievement_win_gilneas",
"side": "",
"obtainable": true
},
{
"id": "5258",
"icon": "achievement_battleground_battleforgilneas",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Twin Peaks",
"zones": [
{
"name": "",
"achs": [
{
"id": "5228",
"icon": "INV_Misc_Head_Dwarf_01",
"side": "H",
"obtainable": true
},
{
"id": "5229",
"icon": "Racial_Orc_BerserkerStrength",
"side": "A",
"obtainable": true
},
{
"id": "5230",
"icon": "Achievement_BG_captureflag_WSG",
"side": "",
"obtainable": true
},
{
"id": "5221",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "A",
"obtainable": true
},
{
"id": "5222",
"icon": "Achievement_BG_grab_cap_flagunderXseconds",
"side": "H",
"obtainable": true
},
{
"id": "5210",
"icon": "Achievement_BG_captureflag_EOS",
"side": "",
"obtainable": true
},
{
"id": "5219",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "A",
"obtainable": true
},
{
"id": "5220",
"icon": "Achievement_BG_KillFlagCarriers_grabFlag_CapIt",
"side": "H",
"obtainable": true
},
{
"id": "5227",
"icon": "achievement_cloudnine",
"side": "H",
"obtainable": true
},
{
"id": "5226",
"icon": "achievement_cloudnine",
"side": "A",
"obtainable": true
},
{
"id": "5211",
"icon": "Achievement_BG_interruptX_flagcapture_attempts",
"side": "",
"obtainable": true
},
{
"id": "5214",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "H",
"obtainable": true
},
{
"id": "5213",
"icon": "Achievement_BG_kill_flag_carrierWSG",
"side": "A",
"obtainable": true
},
{
"id": "5208",
"icon": "achievement_bg_tophealer_av",
"side": "",
"obtainable": true
},
{
"id": "5552",
"icon": "achievement_doublejeopardyhorde",
"side": "H",
"obtainable": true
},
{
"id": "5231",
"icon": "achievement_doublejeopardyhorde",
"side": "A",
"obtainable": true
},
{
"id": "5215",
"icon": "Achievement_BG_winWSG_3-0",
"side": "",
"obtainable": true
},
{
"id": "5216",
"icon": "Achievement_BG_winWSG_underXminutes",
"side": "",
"obtainable": true
},
{
"id": "5209",
"icon": "Achievement_BG_win_WSG_X_times",
"side": "",
"obtainable": true
},
{
"id": "5259",
"icon": "Spell_Nature_EarthShock",
"side": "H",
"obtainable": true
},
{
"id": "5223",
"icon": "Spell_Nature_EarthShock",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Wintergrasp",
"zones": [
{
"name": "",
"achs": [
{
"id": "2080",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "1727",
"icon": "Spell_Arcane_TeleportTheramore",
"side": "",
"obtainable": true
},
{
"id": "1737",
"icon": "Spell_Fire_BlueFlameStrike",
"side": "A",
"obtainable": true
},
{
"id": "2476",
"icon": "Spell_Fire_BlueFlameStrike",
"side": "H",
"obtainable": true
},
{
"id": "1751",
"icon": "Achievement_BG_kill_on_mount",
"side": "",
"obtainable": true
},
{
"id": "2776",
"icon": "Spell_Frost_ChillingBlast",
"side": "H",
"obtainable": true
},
{
"id": "1723",
"icon": "Ability_Mount_Gyrocoptor",
"side": "",
"obtainable": true
},
{
"id": "2199",
"icon": "Ability_Mage_ShatterShield",
"side": "",
"obtainable": true
},
{
"id": "1717",
"icon": "Spell_Frost_ChillingBlast",
"side": "",
"obtainable": true
},
{
"id": "1718",
"icon": "Spell_Frost_ChillingBlast",
"side": "",
"obtainable": true
},
{
"id": "1755",
"icon": "Spell_Frost_ManaBurn",
"side": "",
"obtainable": true
},
{
"id": "1752",
"icon": "Spell_Frost_ChillingBlast",
"side": "A",
"obtainable": true
},
{
"id": "1722",
"icon": "INV_Misc_Statue_07",
"side": "",
"obtainable": true
},
{
"id": "3136",
"icon": "INV_Misc_Statue_10",
"side": "",
"obtainable": true
},
{
"id": "3836",
"icon": "Spell_Fire_TotemOfWrath",
"side": "",
"obtainable": true
},
{
"id": "4585",
"icon": "Spell_Frost_FrostBrand",
"side": "",
"obtainable": true
},
{
"id": "1721",
"icon": "INV_Misc_Statue_07",
"side": "",
"obtainable": true
},
{
"id": "3137",
"icon": "INV_Misc_Statue_10",
"side": "",
"obtainable": true
},
{
"id": "3837",
"icon": "Spell_Fire_TotemOfWrath",
"side": "",
"obtainable": true
},
{
"id": "4586",
"icon": "Spell_Frost_FrostBrand",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Tol Barad",
"zones": [
{
"name": "",
"achs": [
{
"id": "5719",
"icon": "achievement_zone_tolbarad",
"side": "H",
"obtainable": true
},
{
"id": "5718",
"icon": "achievement_zone_tolbarad",
"side": "A",
"obtainable": true
},
{
"id": "5415",
"icon": "Spell_Arcane_TeleportTheramore",
"side": "",
"obtainable": true
},
{
"id": "5488",
"icon": "ability_vehicle_siegeengineram",
"side": "",
"obtainable": true
},
{
"id": "5487",
"icon": "ability_vehicle_siegeenginecannon",
"side": "",
"obtainable": true
},
{
"id": "5486",
"icon": "achievement_bg_killingblow_startingrock",
"side": "",
"obtainable": true
},
{
"id": "5412",
"icon": "achievement_zone_tolbarad",
"side": "",
"obtainable": true
},
{
"id": "5417",
"icon": "achievement_zone_tolbarad",
"side": "A",
"obtainable": true
},
{
"id": "5418",
"icon": "achievement_zone_tolbarad",
"side": "H",
"obtainable": true
},
{
"id": "5489",
"icon": "inv_banner_tolbarad_alliance",
"side": "A",
"obtainable": true
},
{
"id": "5490",
"icon": "inv_banner_tolbarad_horde",
"side": "H",
"obtainable": true
},
{
"id": "5416",
"icon": "Achievement_Boss_Magtheridon",
"side": "",
"obtainable": true
},
{
"id": "6045",
"icon": "inv_misc_eye_03",
"side": "",
"obtainable": true
},
{
"id": "6108",
"icon": "achievement_shivan",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Arena",
"zones": [
{
"name": "2v2",
"achs": [
{
"id": "399",
"icon": "Achievement_Arena_2v2_1",
"side": "",
"obtainable": true
},
{
"id": "400",
"icon": "Achievement_Arena_2v2_4",
"side": "",
"obtainable": true
},
{
"id": "401",
"icon": "Achievement_Arena_2v2_5",
"side": "",
"obtainable": true
},
{
"id": "1159",
"icon": "Achievement_Arena_2v2_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "3v3",
"achs": [
{
"id": "402",
"icon": "Achievement_Arena_3v3_1",
"side": "",
"obtainable": true
},
{
"id": "403",
"icon": "Achievement_Arena_3v3_4",
"side": "",
"obtainable": true
},
{
"id": "405",
"icon": "Achievement_Arena_3v3_5",
"side": "",
"obtainable": true
},
{
"id": "1160",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
},
{
"id": "5266",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
},
{
"id": "5267",
"icon": "Achievement_Arena_3v3_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "5v5",
"achs": [
{
"id": "406",
"icon": "Achievement_Arena_5v5_1",
"side": "",
"obtainable": true
},
{
"id": "407",
"icon": "Achievement_Arena_5v5_4",
"side": "",
"obtainable": true
},
{
"id": "404",
"icon": "Achievement_Arena_5v5_5",
"side": "",
"obtainable": true
},
{
"id": "1161",
"icon": "Achievement_Arena_5v5_7",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "397",
"icon": "Achievement_FeatsOfStrength_Gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "398",
"icon": "Achievement_FeatsOfStrength_Gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "875",
"icon": "Achievement_FeatsOfStrength_Gladiator_02",
"side": "",
"obtainable": true
},
{
"id": "876",
"icon": "Achievement_FeatsOfStrength_Gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "2090",
"icon": "Achievement_FeatsOfStrength_Gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "2093",
"icon": "Achievement_FeatsOfStrength_Gladiator_05",
"side": "",
"obtainable": true
},
{
"id": "2092",
"icon": "Achievement_FeatsOfStrength_Gladiator_06",
"side": "",
"obtainable": true
},
{
"id": "2091",
"icon": "Achievement_FeatsOfStrength_Gladiator_07",
"side": "",
"obtainable": true
},
{
"id": "409",
"icon": "Spell_Holy_SurgeOfLight",
"side": "",
"obtainable": true
},
{
"id": "699",
"icon": "Ability_Hunter_Pathfinding",
"side": "",
"obtainable": true
},
{
"id": "408",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "1162",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
},
{
"id": "1174",
"icon": "Achievement_FeatsOfStrength_Gladiator_08",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Rated Battleground",
"zones": [
{
"name": "Ratings",
"achs": [
{
"id": "5330",
"icon": "Achievement_PVP_A_01",
"side": "A",
"obtainable": true
},
{
"id": "5331",
"icon": "Achievement_PVP_A_02",
"side": "A",
"obtainable": true
},
{
"id": "5332",
"icon": "Achievement_PVP_A_03",
"side": "A",
"obtainable": true
},
{
"id": "5333",
"icon": "Achievement_PVP_A_04",
"side": "A",
"obtainable": true
},
{
"id": "5334",
"icon": "Achievement_PVP_A_05",
"side": "A",
"obtainable": true
},
{
"id": "5335",
"icon": "Achievement_PVP_A_06",
"side": "A",
"obtainable": true
},
{
"id": "5336",
"icon": "Achievement_PVP_A_07",
"side": "A",
"obtainable": true
},
{
"id": "5337",
"icon": "Achievement_PVP_A_08",
"side": "A",
"obtainable": true
},
{
"id": "5359",
"icon": "Achievement_PVP_A_09",
"side": "A",
"obtainable": true
},
{
"id": "5339",
"icon": "Achievement_PVP_A_10",
"side": "A",
"obtainable": true
},
{
"id": "5340",
"icon": "Achievement_PVP_A_11",
"side": "A",
"obtainable": true
},
{
"id": "5341",
"icon": "Achievement_PVP_A_12",
"side": "A",
"obtainable": true
},
{
"id": "5357",
"icon": "Achievement_PVP_A_13",
"side": "A",
"obtainable": true
},
{
"id": "5343",
"icon": "Achievement_PVP_A_14",
"side": "A",
"obtainable": true
},
{
"id": "5344",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "6316",
"icon": "Achievement_PVP_A_A",
"side": "A",
"obtainable": true
},
{
"id": "6939",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "6942",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "5345",
"icon": "Achievement_PVP_H_01",
"side": "H",
"obtainable": true
},
{
"id": "5346",
"icon": "Achievement_PVP_H_02",
"side": "H",
"obtainable": true
},
{
"id": "5347",
"icon": "Achievement_PVP_H_03",
"side": "H",
"obtainable": true
},
{
"id": "5348",
"icon": "Achievement_PVP_H_04",
"side": "H",
"obtainable": true
},
{
"id": "5349",
"icon": "Achievement_PVP_H_05",
"side": "H",
"obtainable": true
},
{
"id": "5350",
"icon": "Achievement_PVP_H_06",
"side": "H",
"obtainable": true
},
{
"id": "5351",
"icon": "Achievement_PVP_H_07",
"side": "H",
"obtainable": true
},
{
"id": "5352",
"icon": "Achievement_PVP_H_08",
"side": "H",
"obtainable": true
},
{
"id": "5338",
"icon": "Achievement_PVP_H_09",
"side": "H",
"obtainable": true
},
{
"id": "5353",
"icon": "Achievement_PVP_H_10",
"side": "H",
"obtainable": true
},
{
"id": "5354",
"icon": "Achievement_PVP_H_11",
"side": "H",
"obtainable": true
},
{
"id": "5355",
"icon": "Achievement_PVP_H_12",
"side": "H",
"obtainable": true
},
{
"id": "5342",
"icon": "Achievement_PVP_H_13",
"side": "H",
"obtainable": true
},
{
"id": "5356",
"icon": "Achievement_PVP_H_14",
"side": "H",
"obtainable": true
},
{
"id": "5358",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6317",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6940",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
},
{
"id": "6941",
"icon": "Achievement_PVP_H_H",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Wins",
"achs": [
{
"id": "5268",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5322",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5327",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5328",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5823",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5329",
"icon": "INV_BannerPVP_02",
"side": "A",
"obtainable": true
},
{
"id": "5269",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5323",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5324",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5325",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5824",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
},
{
"id": "5326",
"icon": "INV_BannerPVP_01",
"side": "H",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "General",
"cats": [
{
"name": "General",
"zones": [
{
"name": "Level",
"achs": [
{
"id": "6",
"icon": "Achievement_Level_10",
"side": "",
"obtainable": true
},
{
"id": "7",
"icon": "Achievement_Level_20",
"side": "",
"obtainable": true
},
{
"id": "8",
"icon": "Achievement_Level_30",
"side": "",
"obtainable": true
},
{
"id": "9",
"icon": "Achievement_Level_40",
"side": "",
"obtainable": true
},
{
"id": "10",
"icon": "Achievement_Level_50",
"side": "",
"obtainable": true
},
{
"id": "11",
"icon": "Achievement_Level_60",
"side": "",
"obtainable": true
},
{
"id": "12",
"icon": "Achievement_Level_70",
"side": "",
"obtainable": true
},
{
"id": "13",
"icon": "Achievement_Level_80",
"side": "",
"obtainable": true
},
{
"id": "4826",
"icon": "achievement_level_85",
"side": "",
"obtainable": true
},
{
"id": "6193",
"icon": "achievement_level_90",
"side": "",
"obtainable": true
},
{
"id": "7382",
"icon": "achievement_arena_2v2_7",
"side": "",
"obtainable": true
},
{
"id": "7383",
"icon": "achievement_guildperk_everybodysfriend",
"side": "",
"obtainable": true
},
{
"id": "7384",
"icon": "achievement_guild_level5",
"side": "",
"obtainable": true
},
{
"id": "7380",
"icon": "achievement_bg_winwsg",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gold",
"achs": [
{
"id": "1176",
"icon": "INV_Misc_Coin_06",
"side": "",
"obtainable": true
},
{
"id": "1177",
"icon": "INV_Misc_Coin_04",
"side": "",
"obtainable": true
},
{
"id": "1178",
"icon": "INV_Misc_Coin_03",
"side": "",
"obtainable": true
},
{
"id": "1180",
"icon": "INV_Misc_Coin_02",
"side": "",
"obtainable": true
},
{
"id": "1181",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "5455",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "5456",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "6753",
"icon": "inv_misc_coin_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mounts",
"achs": [
{
"id": "891",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "889",
"icon": "Ability_Mount_BlackPanther",
"side": "",
"obtainable": true
},
{
"id": "892",
"icon": "Ability_Mount_Wyvern_01",
"side": "",
"obtainable": true
},
{
"id": "890",
"icon": "Ability_Mount_Gryphon_01",
"side": "",
"obtainable": true
},
{
"id": "5180",
"icon": "Ability_Mount_RocketMount",
"side": "",
"obtainable": true
},
{
"id": "2076",
"icon": "Ability_Mount_PolarBear_Brown",
"side": "",
"obtainable": true
},
{
"id": "2077",
"icon": "Ability_Mount_Mammoth_Brown",
"side": "",
"obtainable": true
},
{
"id": "2078",
"icon": "Ability_Mount_Mammoth_Brown",
"side": "",
"obtainable": true
},
{
"id": "2097",
"icon": "INV_Misc_Key_14",
"side": "",
"obtainable": true
},
{
"id": "4888",
"icon": "ability_mount_camel_tan",
"side": "",
"obtainable": true
},
{
"id": "5749",
"icon": "INV_Alchemy_Potion_06",
"side": "",
"obtainable": true
},
{
"id": "7386",
"icon": "ability_mount_travellersyakmount",
"side": "",
"obtainable": true
},
{
"id": "2141",
"icon": "Ability_Mount_RidingElekk",
"side": "",
"obtainable": true
},
{
"id": "2142",
"icon": "Ability_Mount_RidingElekkElite_Green",
"side": "",
"obtainable": true
},
{
"id": "2143",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "2536",
"icon": "Ability_Hunter_Pet_DragonHawk",
"side": "A",
"obtainable": true
},
{
"id": "7860",
"icon": "inv_pandarenserpentmount_green",
"side": "A",
"obtainable": true
},
{
"id": "2537",
"icon": "Ability_Hunter_Pet_DragonHawk",
"side": "H",
"obtainable": true
},
{
"id": "7862",
"icon": "inv_pandarenserpentmount_green",
"side": "H",
"obtainable": true
},
{
"id": "8304",
"icon": "ability_mount_dragonhawkarmorallliance",
"side": "A",
"obtainable": true
},
{
"id": "8302",
"icon": "ability_mount_dragonhawkarmorhorde",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Tabards",
"achs": [
{
"id": "621",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1020",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1021",
"icon": "INV_Chest_Cloth_30",
"side": "",
"obtainable": true
},
{
"id": "5755",
"icon": "INV_Chest_Cloth_30",
"side": "",
"obtainable": true
}
]
},
{
"name": "Books",
"achs": [
{
"id": "1244",
"icon": "INV_Misc_Book_04",
"side": "",
"obtainable": true
},
{
"id": "1956",
"icon": "INV_Misc_Book_11",
"side": "",
"obtainable": true
}
]
},
{
"name": "Items",
"achs": [
{
"id": "558",
"icon": "INV_Misc_Coin_04",
"side": "",
"obtainable": true
},
{
"id": "559",
"icon": "INV_Misc_Coin_01",
"side": "",
"obtainable": true
},
{
"id": "557",
"icon": "Spell_Frost_WizardMark",
"side": "",
"obtainable": true
},
{
"id": "556",
"icon": "INV_Enchant_VoidCrystal",
"side": "",
"obtainable": true
},
{
"id": "1165",
"icon": "INV_Misc_Bag_27",
"side": "",
"obtainable": true
},
{
"id": "2084",
"icon": "INV_JEWELRY_RING_73",
"side": "",
"obtainable": true
},
{
"id": "5373",
"icon": "Spell_Frost_WizardMark",
"side": "",
"obtainable": true
},
{
"id": "5372",
"icon": "INV_Enchant_VoidCrystal",
"side": "",
"obtainable": true
},
{
"id": "6348",
"icon": "inv_glove_plate_pvpwarrior_c_01",
"side": "",
"obtainable": true
},
{
"id": "6349",
"icon": "inv_glove_plate_raiddeathknight_j_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Critters",
"achs": [
{
"id": "1254",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "2556",
"icon": "Ability_Hunter_Pet_Spider",
"side": "",
"obtainable": true
},
{
"id": "1206",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "2557",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "5548",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
},
{
"id": "6350",
"icon": "INV_Jewelcrafting_CrimsonHare",
"side": "",
"obtainable": true
}
]
},
{
"name": "Food",
"achs": [
{
"id": "1833",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "5754",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "1832",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "5753",
"icon": "INV_Misc_Food_115_CondorSoup",
"side": "",
"obtainable": true
},
{
"id": "7329",
"icon": "inv_misc_food_115_condorsoup",
"side": "",
"obtainable": true
},
{
"id": "7330",
"icon": "inv_misc_food_115_condorsoup",
"side": "",
"obtainable": true
},
{
"id": "5779",
"icon": "inv_misc_food_150_cookie",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "964",
"icon": "Spell_Shadow_TwistedFaith",
"side": "",
"obtainable": true
},
{
"id": "2716",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "545",
"icon": "INV_Misc_Comb_02",
"side": "",
"obtainable": true
},
{
"id": "546",
"icon": "INV_Box_01",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Professions",
"cats": [
{
"name": "Professions",
"zones": [
{
"name": "",
"achs": [
{
"id": "116",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "731",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "732",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "733",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "734",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "4924",
"icon": "INV_Misc_Note_01",
"side": "",
"obtainable": true
},
{
"id": "6830",
"icon": "inv_misc_note_01",
"side": "",
"obtainable": true
},
{
"id": "730",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "4915",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "6836",
"icon": "INV_Misc_Note_02",
"side": "",
"obtainable": true
},
{
"id": "735",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "4914",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "6835",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "7378",
"icon": "trade_blacksmithing",
"side": "",
"obtainable": true
},
{
"id": "7379",
"icon": "inv_misc_mastersinscription",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Archaeology",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "4857",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4919",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4920",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4921",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4922",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "4923",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "6837",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
}
]
},
{
"name": "Counts",
"achs": [
{
"id": "5511",
"icon": "trade_archaeology_tuskarr_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5315",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5469",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "5470",
"icon": "trade_archaeology_nerubian_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4854",
"icon": "trade_archaeology_aqir_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4855",
"icon": "trade_archaeology_dwarf_artifactfragment",
"side": "",
"obtainable": true
},
{
"id": "4856",
"icon": "trade_archaeology_highborne_artifactfragment",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lore",
"achs": [
{
"id": "7331",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7332",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7333",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7334",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7335",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7336",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7337",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7612",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8219",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Race",
"achs": [
{
"id": "4859",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "4858",
"icon": "inv_qirajidol_night",
"side": "",
"obtainable": true
},
{
"id": "5301",
"icon": "inv_misc_tabard_tolvir",
"side": "",
"obtainable": true
},
{
"id": "5191",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "5192",
"icon": "inv_helmet_04",
"side": "",
"obtainable": true
},
{
"id": "5193",
"icon": "achievement_boss_cyanigosa",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Pandaren",
"achs": [
{
"id": "7345",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7365",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7343",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7363",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7342",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7362",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7344",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7364",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7339",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7359",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7338",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7358",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7346",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7366",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7347",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7367",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7340",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7360",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7341",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7361",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Mogu",
"achs": [
{
"id": "7349",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7369",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7353",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7373",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7354",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7374",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7348",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7368",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7356",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7376",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7351",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7371",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7350",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7370",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7352",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7372",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7355",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7375",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7357",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "7377",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector: Mantid",
"achs": [
{
"id": "8222",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8223",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8220",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8221",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8227",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8226",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8235",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8234",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8230",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8231",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8232",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8233",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8225",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8224",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8229",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
},
{
"id": "8228",
"icon": "achievement_zone_ironforge",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cooking",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "121",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "122",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "123",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "124",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "125",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "4916",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "7300",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7301",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7302",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7303",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7304",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7305",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "7306",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
},
{
"id": "6365",
"icon": "inv_misc_food_15",
"side": "",
"obtainable": true
}
]
},
{
"name": "Quests",
"achs": [
{
"id": "906",
"icon": "INV_Misc_Cauldron_Arcane",
"side": "",
"obtainable": true
},
{
"id": "1782",
"icon": "INV_Misc_Food_12",
"side": "A",
"obtainable": true
},
{
"id": "1783",
"icon": "INV_Misc_Food_12",
"side": "H",
"obtainable": true
},
{
"id": "5475",
"icon": "inv_misc_food_42",
"side": "H",
"obtainable": true
},
{
"id": "5844",
"icon": "inv_misc_food_meat_cooked_09",
"side": "H",
"obtainable": true
},
{
"id": "5843",
"icon": "inv_misc_food_pinenut",
"side": "H",
"obtainable": true
},
{
"id": "5474",
"icon": "INV_Misc_Food_19",
"side": "A",
"obtainable": true
},
{
"id": "5841",
"icon": "INV_Cask_04",
"side": "A",
"obtainable": true
},
{
"id": "5842",
"icon": "INV_Misc_Food_63",
"side": "A",
"obtainable": true
},
{
"id": "5846",
"icon": "INV_Misc_Food_DimSum",
"side": "H",
"obtainable": true
},
{
"id": "5845",
"icon": "INV_Misc_Food_DimSum",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Awards",
"achs": [
{
"id": "1998",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "1999",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2000",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2001",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
},
{
"id": "2002",
"icon": "INV_Misc_Ribbon_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Recipes",
"achs": [
{
"id": "1795",
"icon": "INV_Misc_Food_66",
"side": "",
"obtainable": true
},
{
"id": "1796",
"icon": "INV_Misc_Food_65",
"side": "",
"obtainable": true
},
{
"id": "1797",
"icon": "INV_Misc_Food_60",
"side": "",
"obtainable": true
},
{
"id": "1798",
"icon": "INV_Misc_Food_13",
"side": "",
"obtainable": true
},
{
"id": "1799",
"icon": "INV_Misc_Food_92_Lobster",
"side": "",
"obtainable": true
},
{
"id": "5471",
"icon": "inv_misc_food_161_fish_89",
"side": "",
"obtainable": true
},
{
"id": "7328",
"icon": "inv_misc_food_161_fish_89",
"side": "",
"obtainable": true
}
]
},
{
"name": "Gourmet",
"achs": [
{
"id": "1800",
"icon": "INV_Misc_Food_84_RoastClefthoof",
"side": "",
"obtainable": true
},
{
"id": "1777",
"icon": "INV_Misc_Food_138_Fish",
"side": "",
"obtainable": true
},
{
"id": "1778",
"icon": "INV_Misc_Food_141_Fish",
"side": "",
"obtainable": true
},
{
"id": "1779",
"icon": "INV_Misc_Food_140_Fish",
"side": "",
"obtainable": true
},
{
"id": "5472",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
},
{
"id": "5473",
"icon": "inv_misc_food_143_fish",
"side": "",
"obtainable": true
},
{
"id": "7326",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
},
{
"id": "7327",
"icon": "inv_misc_food_142_fish",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "877",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "1801",
"icon": "INV_Drink_03",
"side": "",
"obtainable": true
},
{
"id": "3296",
"icon": "Achievement_Profession_ChefHat",
"side": "",
"obtainable": true
},
{
"id": "1780",
"icon": "INV_ValentinesChocolate01",
"side": "",
"obtainable": true
},
{
"id": "1781",
"icon": "INV_Misc_Food_88_RavagerNuggets",
"side": "",
"obtainable": true
},
{
"id": "1785",
"icon": "Ability_Hunter_Pet_Boar",
"side": "",
"obtainable": true
},
{
"id": "1563",
"icon": "Achievement_Profession_ChefHat",
"side": "A",
"obtainable": true
},
{
"id": "1784",
"icon": "Achievement_Profession_ChefHat",
"side": "H",
"obtainable": true
},
{
"id": "7325",
"icon": "trade_cooking_2",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "First Aid",
"zones": [
{
"name": "",
"achs": [
{
"id": "131",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "132",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "133",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "134",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "135",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "4918",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "6838",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "137",
"icon": "INV_Misc_Bandage_04",
"side": "",
"obtainable": true
},
{
"id": "5480",
"icon": "inv_emberweavebandage2",
"side": "",
"obtainable": true
},
{
"id": "141",
"icon": "INV_Misc_SurgeonGlove_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Fishing",
"zones": [
{
"name": "Skill",
"achs": [
{
"id": "126",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "127",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "128",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "129",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "130",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "4917",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "6839",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
}
]
},
{
"name": "Counts",
"achs": [
{
"id": "1556",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1557",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1558",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1559",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1560",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
},
{
"id": "1561",
"icon": "INV_Misc_Fish_50",
"side": "",
"obtainable": true
}
]
},
{
"name": "Quests",
"achs": [
{
"id": "905",
"icon": "Achievement_Profession_Fishing_OldManBarlowned",
"side": "",
"obtainable": true
},
{
"id": "3217",
"icon": "INV_Fishingpole_03",
"side": "",
"obtainable": true
},
{
"id": "5477",
"icon": "INV_Fishingpole_03",
"side": "H",
"obtainable": true
},
{
"id": "5849",
"icon": "inv_fishingpole_06",
"side": "H",
"obtainable": true
},
{
"id": "5850",
"icon": "inv_fishingpole_07",
"side": "H",
"obtainable": true
},
{
"id": "5476",
"icon": "INV_Fishingpole_03",
"side": "A",
"obtainable": true
},
{
"id": "5847",
"icon": "INV_Fishingpole_02",
"side": "A",
"obtainable": true
},
{
"id": "5848",
"icon": "inv_fishingpole_06",
"side": "A",
"obtainable": true
},
{
"id": "5851",
"icon": "INV_Helmet_31",
"side": "",
"obtainable": true
},
{
"id": "7614",
"icon": "inv_misc_fish_95",
"side": "",
"obtainable": true
},
{
"id": "7274",
"icon": "inv_helmet_50",
"side": "",
"obtainable": true
}
]
},
{
"name": "Pools",
"achs": [
{
"id": "153",
"icon": "Achievement_Profession_Fishing_JourneymanFisher",
"side": "",
"obtainable": true
},
{
"id": "1243",
"icon": "Achievement_Profession_Fishing_FindFish",
"side": "",
"obtainable": true
},
{
"id": "1257",
"icon": "INV_Crate_05",
"side": "",
"obtainable": true
},
{
"id": "1225",
"icon": "Achievement_Profession_Fishing_OutlandAngler",
"side": "",
"obtainable": true
},
{
"id": "1517",
"icon": "Achievement_Profession_Fishing_NorthrendAngler",
"side": "",
"obtainable": true
},
{
"id": "7611",
"icon": "inv_misc_fish_93",
"side": "",
"obtainable": true
}
]
},
{
"name": "Coins",
"achs": [
{
"id": "2094",
"icon": "INV_Misc_Coin_19",
"side": "",
"obtainable": true
},
{
"id": "2095",
"icon": "INV_Misc_Coin_18",
"side": "",
"obtainable": true
},
{
"id": "1957",
"icon": "INV_Misc_Coin_17",
"side": "",
"obtainable": true
},
{
"id": "2096",
"icon": "INV_Misc_Coin_02",
"side": "",
"obtainable": true
}
]
},
{
"name": "Cities",
"achs": [
{
"id": "150",
"icon": "INV_Helmet_44",
"side": "",
"obtainable": true
},
{
"id": "1837",
"icon": "INV_Misc_Fish_31",
"side": "",
"obtainable": true
},
{
"id": "1836",
"icon": "INV_Misc_Fish_35",
"side": "",
"obtainable": true
},
{
"id": "1958",
"icon": "INV_Misc_MonsterTail_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "World",
"achs": [
{
"id": "5479",
"icon": "inv_misc_fish_61",
"side": "",
"obtainable": true
},
{
"id": "5478",
"icon": "inv_misc_fish_30",
"side": "",
"obtainable": true
},
{
"id": "878",
"icon": "INV_Misc_Fish_35",
"side": "",
"obtainable": true
},
{
"id": "726",
"icon": "INV_Misc_Fish_14",
"side": "",
"obtainable": true
},
{
"id": "3218",
"icon": "inv_misc_fish_turtle_02",
"side": "",
"obtainable": true
},
{
"id": "144",
"icon": "Ability_Creature_Poison_05",
"side": "",
"obtainable": true
},
{
"id": "306",
"icon": "INV_Misc_Fish_06",
"side": "",
"obtainable": true
},
{
"id": "1516",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Quests",
"cats": [
{
"name": "Quests",
"zones": [
{
"name": "Regular Counts",
"achs": [
{
"id": "503",
"icon": "Achievement_Quests_Completed_01",
"side": "",
"obtainable": true
},
{
"id": "504",
"icon": "Achievement_Quests_Completed_02",
"side": "",
"obtainable": true
},
{
"id": "505",
"icon": "Achievement_Quests_Completed_03",
"side": "",
"obtainable": true
},
{
"id": "506",
"icon": "Achievement_Quests_Completed_04",
"side": "",
"obtainable": true
},
{
"id": "507",
"icon": "Achievement_Quests_Completed_05",
"side": "",
"obtainable": true
},
{
"id": "508",
"icon": "Achievement_Quests_Completed_06",
"side": "",
"obtainable": true
},
{
"id": "32",
"icon": "Achievement_Quests_Completed_07",
"side": "",
"obtainable": true
},
{
"id": "978",
"icon": "Achievement_Quests_Completed_08",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily Counts",
"achs": [
{
"id": "973",
"icon": "Achievement_Quests_Completed_Daily_01",
"side": "",
"obtainable": true
},
{
"id": "974",
"icon": "Achievement_Quests_Completed_Daily_02",
"side": "",
"obtainable": true
},
{
"id": "975",
"icon": "Achievement_Quests_Completed_Daily_03",
"side": "",
"obtainable": true
},
{
"id": "976",
"icon": "Achievement_Quests_Completed_Daily_04",
"side": "",
"obtainable": true
},
{
"id": "977",
"icon": "Achievement_Quests_Completed_Daily_05",
"side": "",
"obtainable": true
},
{
"id": "5751",
"icon": "Achievement_Quests_Completed_Daily_05",
"side": "",
"obtainable": true
},
{
"id": "7410",
"icon": "achievement_quests_completed_daily_06",
"side": "",
"obtainable": true
},
{
"id": "7411",
"icon": "achievement_quests_completed_daily_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dungeon Counts",
"achs": [
{
"id": "4956",
"icon": "Achievement_Quests_Completed_05",
"side": "",
"obtainable": true
},
{
"id": "4957",
"icon": "Achievement_Quests_Completed_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Themes",
"achs": [
{
"id": "941",
"icon": "INV_Weapon_Rifle_05",
"side": "",
"obtainable": true
},
{
"id": "1576",
"icon": "INV_Helmet_08",
"side": "",
"obtainable": true
},
{
"id": "4958",
"icon": "Ability_Warrior_BloodFrenzy",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "31",
"icon": "Achievement_Quests_Completed_Daily_x5",
"side": "",
"obtainable": true
},
{
"id": "1182",
"icon": "INV_Misc_Coin_16",
"side": "",
"obtainable": true
},
{
"id": "5752",
"icon": "INV_Misc_Coin_16",
"side": "",
"obtainable": true
},
{
"id": "7520",
"icon": "INV_Misc_Book_07",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "6300",
"icon": "achievement_zone_jadeforest_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6534",
"icon": "achievement_zone_jadeforest_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6301",
"icon": "achievement_zone_valleyoffourwinds_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6535",
"icon": "achievement_zone_krasarangwilds_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6536",
"icon": "achievement_zone_krasarangwilds_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6537",
"icon": "achievement_zone_kunlaisummit_loremaster",
"side": "A",
"obtainable": true
},
{
"id": "6538",
"icon": "achievement_zone_kunlaisummit_loremaster",
"side": "H",
"obtainable": true
},
{
"id": "6539",
"icon": "achievement_zone_townlongsteppes_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6540",
"icon": "achievement_zone_dreadwastes_loremaster",
"side": "",
"obtainable": true
},
{
"id": "7315",
"icon": "achievement_zone_valeofeternalblossoms_loremaster",
"side": "",
"obtainable": true
},
{
"id": "6541",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "7285",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Klaxxi",
"achs": [
{
"id": "7312",
"icon": "achievement_raid_mantidraid06",
"side": "",
"obtainable": true
},
{
"id": "7313",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "7314",
"icon": "achievement_raid_mantidraid05",
"side": "",
"obtainable": true
},
{
"id": "7316",
"icon": "ability_mount_hordescorpionamber",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Golden Lotus",
"achs": [
{
"id": "7317",
"icon": "achievement_moguraid_04",
"side": "",
"obtainable": true
},
{
"id": "7318",
"icon": "inv_misc_key_15",
"side": "",
"obtainable": true
},
{
"id": "7319",
"icon": "ability_hunter_posthaste",
"side": "",
"obtainable": true
},
{
"id": "7320",
"icon": "ability_toughness",
"side": "",
"obtainable": true
},
{
"id": "7321",
"icon": "achievement_greatwall",
"side": "",
"obtainable": true
},
{
"id": "7322",
"icon": "ability_monk_roll",
"side": "",
"obtainable": true
},
{
"id": "7323",
"icon": "warrior_talent_icon_bloodandthunder",
"side": "",
"obtainable": true
},
{
"id": "7324",
"icon": "achievement_dungeon_mogupalace",
"side": "",
"obtainable": true
}
]
},
{
"name": "Shado-Pan",
"achs": [
{
"id": "7297",
"icon": "achievement_guildperk_everyones-a-hero_rank2",
"side": "",
"obtainable": true
},
{
"id": "7298",
"icon": "achievement_shadowpan_hideout_1",
"side": "",
"obtainable": true
},
{
"id": "7299",
"icon": "achievement_guildperk_everyones-a-hero",
"side": "",
"obtainable": true
},
{
"id": "7307",
"icon": "ability_rogue_masterofsubtlety",
"side": "",
"obtainable": true
},
{
"id": "7308",
"icon": "inv_shield_panstart_a_01",
"side": "",
"obtainable": true
},
{
"id": "7309",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "7310",
"icon": "inv_inscription_trinket_ox",
"side": "",
"obtainable": true
}
]
},
{
"name": "The August Celestials",
"achs": [
{
"id": "7286",
"icon": "ability_monk_summontigerstatue",
"side": "",
"obtainable": true
},
{
"id": "7287",
"icon": "ability_mount_cranemount",
"side": "",
"obtainable": true
},
{
"id": "7288",
"icon": "ability_mount_yakmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "The Tillers",
"achs": [
{
"id": "7292",
"icon": "inv_misc_herb_01",
"side": "",
"obtainable": true
},
{
"id": "7293",
"icon": "inv_misc_herb_02",
"side": "",
"obtainable": true
},
{
"id": "7294",
"icon": "inv_misc_herb_goldenlotus",
"side": "",
"obtainable": true
},
{
"id": "7295",
"icon": "inv_misc_herb_whiptail",
"side": "",
"obtainable": true
},
{
"id": "7296",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
}
]
},
{
"name": "Order of the Cloud Serpent",
"achs": [
{
"id": "7289",
"icon": "inv_pandarenserpentpet",
"side": "",
"obtainable": true
},
{
"id": "7290",
"icon": "ability_monk_summonserpentstatue",
"side": "",
"obtainable": true
},
{
"id": "7291",
"icon": "achievement_jadeserpent",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dominance Offensive",
"achs": [
{
"id": "7929",
"icon": "achievement_zone_krasarangwilds",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Operation: Shieldwall",
"achs": [
{
"id": "7928",
"icon": "achievement_zone_krasarangwilds",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "7502",
"icon": "inv_mushanbeastmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "Wrathion",
"achs": [
{
"id": "7533",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "7534",
"icon": "inv_legendary_theblackprince",
"side": "A",
"obtainable": true
},
{
"id": "8008",
"icon": "inv_legendary_theblackprince",
"side": "H",
"obtainable": true
},
{
"id": "7535",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "7536",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
},
{
"id": "8030",
"icon": "inv_legendary_theblackprince",
"side": "A",
"obtainable": true
},
{
"id": "8031",
"icon": "inv_legendary_theblackprince",
"side": "H",
"obtainable": true
},
{
"id": "8325",
"icon": "inv_legendary_theblackprince",
"side": "",
"obtainable": true
}
]
},
{
"name": "Isle of Thunder",
"achs": [
{
"id": "8117",
"icon": "achievement_reputation_kirintor",
"side": "",
"obtainable": true
},
{
"id": "8118",
"icon": "ability_druid_empoweredtouch",
"side": "",
"obtainable": true
},
{
"id": "8120",
"icon": "ability_mount_triceratopsmount",
"side": "",
"obtainable": true
},
{
"id": "8112",
"icon": "inv_misc_archaeology_babypterrodax",
"side": "",
"obtainable": true
},
{
"id": "8106",
"icon": "ability_racial_timeismoney",
"side": "",
"obtainable": true
},
{
"id": "8099",
"icon": "spell_nature_callstorm",
"side": "",
"obtainable": true
},
{
"id": "8101",
"icon": "trade_archaeology_chestoftinyglassanimals",
"side": "",
"obtainable": true
},
{
"id": "8119",
"icon": "achievement_doublerainbow",
"side": "",
"obtainable": true
},
{
"id": "8100",
"icon": "inv_qiraj_jewelglyphed",
"side": "",
"obtainable": true
},
{
"id": "8114",
"icon": "ability_heroicleap",
"side": "",
"obtainable": true
},
{
"id": "8107",
"icon": "inv_pet_cockroach",
"side": "",
"obtainable": true
},
{
"id": "8115",
"icon": "spell_shaman_staticshock",
"side": "",
"obtainable": true
},
{
"id": "8105",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
},
{
"id": "8109",
"icon": "achievement_bg_xkills_avgraveyard",
"side": "",
"obtainable": true
},
{
"id": "8110",
"icon": "inv_polearm_2h_mogu_c_01",
"side": "",
"obtainable": true
},
{
"id": "8111",
"icon": "ability_paladin_beaconoflight",
"side": "",
"obtainable": true
},
{
"id": "8104",
"icon": "archaeology_5_0_mogucoin",
"side": "",
"obtainable": true
},
{
"id": "8108",
"icon": "trade_archaeology_tinydinosaurskeleton",
"side": "",
"obtainable": true
},
{
"id": "8116",
"icon": "ability_deathknight_sanguinfortitude",
"side": "",
"obtainable": true
},
{
"id": "8212",
"icon": "inv_misc_book_06",
"side": "",
"obtainable": true
},
{
"id": "8121",
"icon": "spell_shaman_thunderstorm",
"side": "",
"obtainable": true
}
]
},
{
"name": "Escalation",
"achs": [
{
"id": "8307",
"icon": "inv_hand_1h_trollshaman_c_01",
"side": "H",
"obtainable": true
},
{
"id": "8306",
"icon": "inv_hand_1h_trollshaman_c_01",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4870",
"icon": "achievement_quests_completed_mounthyjal",
"side": "",
"obtainable": true
},
{
"id": "4982",
"icon": "achievement_quests_completed_vashjir",
"side": "H",
"obtainable": true
},
{
"id": "4869",
"icon": "achievement_quests_completed_vashjir",
"side": "A",
"obtainable": true
},
{
"id": "4871",
"icon": "achievement_quests_completed_deepholm",
"side": "",
"obtainable": true
},
{
"id": "4872",
"icon": "achievement_quests_completed_uldum",
"side": "",
"obtainable": true
},
{
"id": "4873",
"icon": "achievement_quests_completed_twilighthighlands",
"side": "A",
"obtainable": true
},
{
"id": "5501",
"icon": "achievement_quests_completed_twilighthighlands",
"side": "H",
"obtainable": true
},
{
"id": "4875",
"icon": "INV_Misc_Book_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "4874",
"icon": "achievement_zone_tolbarad",
"side": "",
"obtainable": true
}
]
},
{
"name": "Hyjal",
"achs": [
{
"id": "5483",
"icon": "ability_vehicle_launchplayer",
"side": "",
"obtainable": true
},
{
"id": "4959",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "5860",
"icon": "Ability_Hunter_Pet_Vulture",
"side": "",
"obtainable": true
}
]
},
{
"name": "Vashj'ir",
"achs": [
{
"id": "5452",
"icon": "Achievement_Boss_LadyVashj",
"side": "",
"obtainable": true
},
{
"id": "5319",
"icon": "inv_misc_fish_51",
"side": "H",
"obtainable": true
},
{
"id": "5318",
"icon": "inv_misc_fish_51",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Deepholm",
"achs": [
{
"id": "5446",
"icon": "inv_mushroom_12",
"side": "",
"obtainable": true
},
{
"id": "5449",
"icon": "Spell_Nature_EarthElemental_Totem",
"side": "",
"obtainable": true
},
{
"id": "5447",
"icon": "achievement_dungeon_the-stonecore_slabhide",
"side": "",
"obtainable": true
},
{
"id": "5445",
"icon": "INV_Mushroom_06",
"side": "",
"obtainable": true
},
{
"id": "5450",
"icon": "INV_Mushroom_07",
"side": "",
"obtainable": true
}
]
},
{
"name": "Uldum",
"achs": [
{
"id": "4961",
"icon": "INV_Helmet_50",
"side": "",
"obtainable": true
},
{
"id": "5317",
"icon": "INV_Misc_Bomb_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Twilight Highlands",
"achs": [
{
"id": "4960",
"icon": "INV_Jewelry_Ring_03",
"side": "",
"obtainable": true
},
{
"id": "5481",
"icon": "inv_misc_tabard_wildhammerclan",
"side": "A",
"obtainable": true
},
{
"id": "5451",
"icon": "inv_jewelry_ring_ahnqiraj_05",
"side": "",
"obtainable": true
},
{
"id": "5482",
"icon": "inv_misc_tabard_dragonmawclan",
"side": "H",
"obtainable": true
},
{
"id": "5320",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "A",
"obtainable": true
},
{
"id": "5321",
"icon": "Achievement_Boss_GruulTheDragonkiller",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Molten Front",
"achs": [
{
"id": "5859",
"icon": "Achievement_Character_Nightelf_Female",
"side": "",
"obtainable": true
},
{
"id": "5861",
"icon": "Spell_Fire_Elemental_Totem",
"side": "",
"obtainable": true
},
{
"id": "5862",
"icon": "Ability_Hunter_EagleEye",
"side": "",
"obtainable": true
},
{
"id": "5864",
"icon": "inv_sword_draenei_05",
"side": "",
"obtainable": true
},
{
"id": "5865",
"icon": "INV_Weapon_ShortBlade_10",
"side": "",
"obtainable": true
},
{
"id": "5866",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
},
{
"id": "5867",
"icon": "spell_shaman_improvedfirenova",
"side": "",
"obtainable": true
},
{
"id": "5868",
"icon": "Ability_Tracking",
"side": "",
"obtainable": true
},
{
"id": "5869",
"icon": "ability_hunter_pet_corehound",
"side": "",
"obtainable": true
},
{
"id": "5870",
"icon": "Achievement_Character_Nightelf_Male",
"side": "",
"obtainable": true
},
{
"id": "5871",
"icon": "Spell_Fire_MoltenBlood",
"side": "",
"obtainable": true
},
{
"id": "5872",
"icon": "Ability_Hunter_Pet_Spider",
"side": "",
"obtainable": true
},
{
"id": "5873",
"icon": "Spell_Fire_Burnout",
"side": "",
"obtainable": true
},
{
"id": "5874",
"icon": "creatureportrait_g_bomb_02",
"side": "",
"obtainable": true
},
{
"id": "5879",
"icon": "achievement_zone_firelands",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Northrend",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "1358",
"icon": "Achievement_Zone_BoreanTundra_07",
"side": "H",
"obtainable": true
},
{
"id": "33",
"icon": "Achievement_Zone_BoreanTundra_07",
"side": "A",
"obtainable": true
},
{
"id": "34",
"icon": "Achievement_Zone_HowlingFjord_07",
"side": "A",
"obtainable": true
},
{
"id": "1356",
"icon": "Achievement_Zone_HowlingFjord_07",
"side": "H",
"obtainable": true
},
{
"id": "1359",
"icon": "Achievement_Zone_DragonBlight_07",
"side": "H",
"obtainable": true
},
{
"id": "35",
"icon": "Achievement_Zone_DragonBlight_07",
"side": "A",
"obtainable": true
},
{
"id": "1357",
"icon": "Achievement_Zone_GrizzlyHills_07",
"side": "H",
"obtainable": true
},
{
"id": "37",
"icon": "Achievement_Zone_GrizzlyHills_07",
"side": "A",
"obtainable": true
},
{
"id": "39",
"icon": "Achievement_Zone_Sholazar_07",
"side": "",
"obtainable": true
},
{
"id": "36",
"icon": "Achievement_Zone_ZulDrak_07",
"side": "",
"obtainable": true
},
{
"id": "38",
"icon": "Achievement_Zone_StormPeaks_07",
"side": "",
"obtainable": true
},
{
"id": "40",
"icon": "Achievement_Zone_IceCrown_07",
"side": "",
"obtainable": true
},
{
"id": "41",
"icon": "Achievement_Zone_Northrend_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "561",
"icon": "Achievement_Zone_BoreanTundra_11",
"side": "",
"obtainable": true
},
{
"id": "1277",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "938",
"icon": "Ability_Hunter_Pet_Crocolisk",
"side": "",
"obtainable": true
},
{
"id": "1596",
"icon": "Achievement_Zone_ZulDrak_05",
"side": "",
"obtainable": true
},
{
"id": "1428",
"icon": "INV_Misc_Bomb_02",
"side": "",
"obtainable": true
},
{
"id": "547",
"icon": "Achievement_Zone_IceCrown_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "Daily",
"achs": [
{
"id": "962",
"icon": "Achievement_Zone_Sholazar_11",
"side": "",
"obtainable": true
},
{
"id": "961",
"icon": "Achievement_Zone_Sholazar_08",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Outland",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "1271",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "H",
"obtainable": true
},
{
"id": "1189",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "A",
"obtainable": true
},
{
"id": "1190",
"icon": "Achievement_Zone_Zangarmarsh",
"side": "",
"obtainable": true
},
{
"id": "1191",
"icon": "Achievement_Zone_Terrokar",
"side": "A",
"obtainable": true
},
{
"id": "1272",
"icon": "Achievement_Zone_Terrokar",
"side": "H",
"obtainable": true
},
{
"id": "1273",
"icon": "Achievement_Zone_Nagrand_01",
"side": "H",
"obtainable": true
},
{
"id": "1192",
"icon": "Achievement_Zone_Nagrand_01",
"side": "A",
"obtainable": true
},
{
"id": "1193",
"icon": "Achievement_Zone_BladesEdgeMtns_01",
"side": "",
"obtainable": true
},
{
"id": "1194",
"icon": "Achievement_Zone_Netherstorm_01",
"side": "",
"obtainable": true
},
{
"id": "1195",
"icon": "Achievement_Zone_Shadowmoon",
"side": "",
"obtainable": true
},
{
"id": "1262",
"icon": "Achievement_Zone_Outland_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "939",
"icon": "Ability_Mount_RidingElekk",
"side": "",
"obtainable": true
},
{
"id": "1275",
"icon": "INV_Misc_Bomb_07",
"side": "",
"obtainable": true
},
{
"id": "1276",
"icon": "INV_Misc_Bomb_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Eastern Kingdoms",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4899",
"icon": "achievement_zone_lochmodan",
"side": "A",
"obtainable": true
},
{
"id": "4894",
"icon": "Achievement_Zone_Silverpine_01",
"side": "H",
"obtainable": true
},
{
"id": "4903",
"icon": "Achievement_Zone_WestFall_01",
"side": "A",
"obtainable": true
},
{
"id": "4908",
"icon": "Achievement_Zone_Ghostlands",
"side": "H",
"obtainable": true
},
{
"id": "4902",
"icon": "Achievement_Zone_RedridgeMountains",
"side": "A",
"obtainable": true
},
{
"id": "4895",
"icon": "Achievement_Zone_HillsbradFoothills",
"side": "H",
"obtainable": true
},
{
"id": "4896",
"icon": "Achievement_Zone_ArathiHighlands_01",
"side": "",
"obtainable": true
},
{
"id": "4906",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4905",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4897",
"icon": "Achievement_Zone_Hinterlands_01",
"side": "",
"obtainable": true
},
{
"id": "4893",
"icon": "Achievement_Zone_WesternPlaguelands_01",
"side": "",
"obtainable": true
},
{
"id": "4892",
"icon": "Achievement_Zone_EasternPlaguelands",
"side": "",
"obtainable": true
},
{
"id": "4900",
"icon": "Achievement_Zone_Badlands_01",
"side": "",
"obtainable": true
},
{
"id": "4910",
"icon": "Achievement_Zone_SearingGorge_01",
"side": "",
"obtainable": true
},
{
"id": "4901",
"icon": "Achievement_Zone_BurningSteppes_01",
"side": "",
"obtainable": true
},
{
"id": "4904",
"icon": "Achievement_Zone_SwampSorrows_01",
"side": "",
"obtainable": true
},
{
"id": "4909",
"icon": "Achievement_Zone_BlastedLands_01",
"side": "",
"obtainable": true
},
{
"id": "1676",
"icon": "Achievement_Zone_EasternKingdoms_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "940",
"icon": "Ability_Mount_WhiteTiger",
"side": "",
"obtainable": true
},
{
"id": "5442",
"icon": "INV_Misc_Crop_02",
"side": "",
"obtainable": true
},
{
"id": "5444",
"icon": "inv_misc_desecrated_plategloves",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Kalimdor",
"zones": [
{
"name": "Zones",
"achs": [
{
"id": "4927",
"icon": "Achievement_Zone_Azshara_01",
"side": "H",
"obtainable": true
},
{
"id": "4926",
"icon": "Achievement_Zone_BloodmystIsle_01",
"side": "A",
"obtainable": true
},
{
"id": "4928",
"icon": "Achievement_Zone_Darkshore_01",
"side": "A",
"obtainable": true
},
{
"id": "4933",
"icon": "Achievement_Zone_Barrens_01",
"side": "H",
"obtainable": true
},
{
"id": "4925",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "A",
"obtainable": true
},
{
"id": "4976",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "H",
"obtainable": true
},
{
"id": "4936",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "A",
"obtainable": true
},
{
"id": "4980",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "H",
"obtainable": true
},
{
"id": "4937",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "A",
"obtainable": true
},
{
"id": "4981",
"icon": "Achievement_Boss_CharlgaRazorflank",
"side": "H",
"obtainable": true
},
{
"id": "4930",
"icon": "Achievement_Zone_Desolace",
"side": "",
"obtainable": true
},
{
"id": "4978",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "H",
"obtainable": true
},
{
"id": "4929",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "A",
"obtainable": true
},
{
"id": "4979",
"icon": "Achievement_Zone_Feralas",
"side": "H",
"obtainable": true
},
{
"id": "4932",
"icon": "Achievement_Zone_Feralas",
"side": "A",
"obtainable": true
},
{
"id": "4938",
"icon": "Achievement_Zone_ThousandNeedles_01",
"side": "",
"obtainable": true
},
{
"id": "4931",
"icon": "Achievement_Zone_Felwood",
"side": "",
"obtainable": true
},
{
"id": "4935",
"icon": "Achievement_Zone_Tanaris_01",
"side": "",
"obtainable": true
},
{
"id": "4939",
"icon": "Achievement_Zone_UnGoroCrater_01",
"side": "",
"obtainable": true
},
{
"id": "4940",
"icon": "Achievement_Zone_Winterspring",
"side": "",
"obtainable": true
},
{
"id": "4934",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "1678",
"icon": "Achievement_Zone_Kalimdor_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "5454",
"icon": "Ability_Mount_RocketMount",
"side": "H",
"obtainable": true
},
{
"id": "5448",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5546",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5547",
"icon": "Ability_Mage_PotentSpirit",
"side": "",
"obtainable": true
},
{
"id": "5453",
"icon": "Achievement_Boss_Illidan",
"side": "A",
"obtainable": true
},
{
"id": "5443",
"icon": "inv_misc_monsterscales_19",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Reputation",
"cats": [
{
"name": "Reputation",
"zones": [
{
"name": "Counts",
"achs": [
{
"id": "522",
"icon": "Achievement_Reputation_01",
"side": "",
"obtainable": true
},
{
"id": "523",
"icon": "Achievement_Reputation_01",
"side": "",
"obtainable": true
},
{
"id": "524",
"icon": "Achievement_Reputation_02",
"side": "",
"obtainable": true
},
{
"id": "521",
"icon": "Achievement_Reputation_03",
"side": "",
"obtainable": true
},
{
"id": "520",
"icon": "Achievement_Reputation_04",
"side": "",
"obtainable": true
},
{
"id": "519",
"icon": "Achievement_Reputation_05",
"side": "",
"obtainable": true
},
{
"id": "518",
"icon": "Achievement_Reputation_06",
"side": "",
"obtainable": true
},
{
"id": "1014",
"icon": "Achievement_Reputation_07",
"side": "",
"obtainable": true
},
{
"id": "1015",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "5374",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "5723",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "6826",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
},
{
"id": "6742",
"icon": "Achievement_Reputation_08",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "762",
"icon": "Achievement_PVP_H_16",
"side": "H",
"obtainable": true
},
{
"id": "948",
"icon": "Achievement_PVP_A_16",
"side": "A",
"obtainable": true
},
{
"id": "943",
"icon": "INV_Helmet_44",
"side": "H",
"obtainable": true
},
{
"id": "942",
"icon": "INV_Helmet_44",
"side": "A",
"obtainable": true
},
{
"id": "953",
"icon": "Ability_Racial_Ultravision",
"side": "",
"obtainable": true
},
{
"id": "945",
"icon": "Spell_Holy_HolyGuidance",
"side": "",
"obtainable": true
},
{
"id": "5794",
"icon": "inv_epicguildtabard",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "",
"achs": [
{
"id": "6544",
"icon": "achievement_faction_tillers",
"side": "",
"obtainable": true
},
{
"id": "6545",
"icon": "achievement_faction_klaxxi",
"side": "",
"obtainable": true
},
{
"id": "6546",
"icon": "achievement_faction_goldenlotus",
"side": "",
"obtainable": true
},
{
"id": "6547",
"icon": "achievement_faction_anglers",
"side": "",
"obtainable": true
},
{
"id": "6548",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6550",
"icon": "achievement_faction_serpentriders",
"side": "",
"obtainable": true
},
{
"id": "6551",
"icon": "achievement_reputation_01",
"side": "",
"obtainable": true
},
{
"id": "6552",
"icon": "achievement_reputation_03",
"side": "",
"obtainable": true
},
{
"id": "6366",
"icon": "achievement_faction_serpentriders",
"side": "",
"obtainable": true
},
{
"id": "6543",
"icon": "achievement_faction_celestials",
"side": "",
"obtainable": true
},
{
"id": "6827",
"icon": "trade_archaeology_highborne_scroll",
"side": "H",
"obtainable": true
},
{
"id": "6828",
"icon": "trade_archaeology_highborne_scroll",
"side": "A",
"obtainable": true
},
{
"id": "7479",
"icon": "achievement_faction_shadopan",
"side": "",
"obtainable": true
},
{
"id": "8023",
"icon": "achievement_faction_klaxxi",
"side": "",
"obtainable": true
},
{
"id": "8206",
"icon": "achievement_general_hordeslayer",
"side": "H",
"obtainable": true
},
{
"id": "8208",
"icon": "achievement_reputation_kirintor_offensive",
"side": "A",
"obtainable": true
},
{
"id": "8205",
"icon": "achievement_general_allianceslayer",
"side": "A",
"obtainable": true
},
{
"id": "8210",
"icon": "achievement_faction_shadopan",
"side": "",
"obtainable": true
},
{
"id": "8209",
"icon": "achievement_faction_sunreaveronslaught",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "",
"achs": [
{
"id": "4882",
"icon": "inv_misc_tabard_guardiansofhyjal",
"side": "",
"obtainable": true
},
{
"id": "4881",
"icon": "inv_misc_tabard_earthenring",
"side": "",
"obtainable": true
},
{
"id": "4883",
"icon": "inv_misc_tabard_therazane",
"side": "",
"obtainable": true
},
{
"id": "4884",
"icon": "inv_misc_tabard_tolvir",
"side": "",
"obtainable": true
},
{
"id": "4885",
"icon": "inv_misc_tabard_wildhammerclan",
"side": "A",
"obtainable": true
},
{
"id": "4886",
"icon": "inv_misc_tabard_dragonmawclan",
"side": "H",
"obtainable": true
},
{
"id": "5375",
"icon": "inv_misc_tabard_baradinwardens",
"side": "A",
"obtainable": true
},
{
"id": "5376",
"icon": "inv_misc_tabard_hellscream",
"side": "H",
"obtainable": true
},
{
"id": "5827",
"icon": "inv_neck_hyjaldaily_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Wrath of the Lich King",
"zones": [
{
"name": "",
"achs": [
{
"id": "949",
"icon": "Achievement_Reputation_Tuskarr",
"side": "",
"obtainable": true
},
{
"id": "950",
"icon": "Ability_Mount_WhiteDireWolf",
"side": "",
"obtainable": true
},
{
"id": "951",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "952",
"icon": "Spell_Nature_MirrorImage",
"side": "",
"obtainable": true
},
{
"id": "947",
"icon": "INV_Jewelry_Talisman_08",
"side": "",
"obtainable": true
},
{
"id": "1007",
"icon": "Achievement_Reputation_WyrmrestTemple",
"side": "",
"obtainable": true
},
{
"id": "1008",
"icon": "Achievement_Reputation_KirinTor",
"side": "",
"obtainable": true
},
{
"id": "1009",
"icon": "Achievement_Reputation_KnightsoftheEbonBlade",
"side": "",
"obtainable": true
},
{
"id": "1010",
"icon": "Spell_Misc_HellifrePVPCombatMorale",
"side": "",
"obtainable": true
},
{
"id": "1011",
"icon": "Spell_Misc_HellifrePVPThrallmarFavor",
"side": "H",
"obtainable": true
},
{
"id": "1012",
"icon": "Spell_Misc_HellifrePVPHonorHoldFavor",
"side": "A",
"obtainable": true
},
{
"id": "4598",
"icon": "INV_Jewelry_Talisman_08",
"side": "",
"obtainable": true
},
{
"id": "2082",
"icon": "Ability_Mount_Mammoth_White",
"side": "",
"obtainable": true
},
{
"id": "2083",
"icon": "Ability_Mount_Mammoth_White",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "The Burning Crusade",
"zones": [
{
"name": "",
"achs": [
{
"id": "893",
"icon": "Ability_Mount_WarHippogryph",
"side": "",
"obtainable": true
},
{
"id": "894",
"icon": "Ability_Hunter_Pet_NetherRay",
"side": "",
"obtainable": true
},
{
"id": "896",
"icon": "INV_Misc_Apexis_Crystal",
"side": "",
"obtainable": true
},
{
"id": "898",
"icon": "Ability_Mount_NetherdrakePurple",
"side": "",
"obtainable": true
},
{
"id": "1638",
"icon": "Ability_Mount_NetherdrakePurple",
"side": "",
"obtainable": true
},
{
"id": "900",
"icon": "INV_Mushroom_11",
"side": "",
"obtainable": true
},
{
"id": "902",
"icon": "INV_Enchant_ShardPrismaticLarge",
"side": "",
"obtainable": true
},
{
"id": "901",
"icon": "INV_Misc_Foot_Centaur",
"side": "H",
"obtainable": true
},
{
"id": "899",
"icon": "INV_Misc_Foot_Centaur",
"side": "A",
"obtainable": true
},
{
"id": "903",
"icon": "Spell_Arcane_PortalShattrath",
"side": "",
"obtainable": true
},
{
"id": "960",
"icon": "Spell_Holy_MindSooth",
"side": "",
"obtainable": true
},
{
"id": "959",
"icon": "INV_Enchant_DustIllusion",
"side": "",
"obtainable": true
},
{
"id": "958",
"icon": "Achievement_Reputation_AshtongueDeathsworn",
"side": "",
"obtainable": true
},
{
"id": "897",
"icon": "INV_Shield_48",
"side": "",
"obtainable": true
},
{
"id": "764",
"icon": "Spell_Fire_FelFireward",
"side": "A",
"obtainable": true
},
{
"id": "763",
"icon": "Spell_Fire_FelFireward",
"side": "H",
"obtainable": true
}
]
}
]
},
{
"name": "Classic",
"zones": [
{
"name": "",
"achs": [
{
"id": "944",
"icon": "Achievement_Reputation_timbermaw",
"side": "",
"obtainable": true
},
{
"id": "946",
"icon": "INV_Jewelry_Talisman_07",
"side": "",
"obtainable": true
},
{
"id": "955",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "956",
"icon": "INV_Misc_Head_Dragon_Bronze",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Exploration",
"cats": [
{
"name": "Exploration",
"zones": [
{
"name": "",
"achs": [
{
"id": "42",
"icon": "Achievement_Zone_EasternKingdoms_01",
"side": "",
"obtainable": true
},
{
"id": "43",
"icon": "Achievement_Zone_Kalimdor_01",
"side": "",
"obtainable": true
},
{
"id": "44",
"icon": "Achievement_Zone_Outland_01",
"side": "",
"obtainable": true
},
{
"id": "45",
"icon": "Achievement_Zone_Northrend_01",
"side": "",
"obtainable": true
},
{
"id": "4868",
"icon": "Spell_Shaman_StormEarthFire",
"side": "",
"obtainable": true
},
{
"id": "6974",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "46",
"icon": "INV_Misc_Map02",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pandaria",
"zones": [
{
"name": "Area",
"achs": [
{
"id": "6351",
"icon": "achievement_zone_jadeforest",
"side": "",
"obtainable": true
},
{
"id": "6969",
"icon": "achievement_zone_valleyoffourwinds",
"side": "",
"obtainable": true
},
{
"id": "6975",
"icon": "achievement_zone_krasarangwilds",
"side": "",
"obtainable": true
},
{
"id": "6976",
"icon": "achievement_zone_kunlaisummit",
"side": "",
"obtainable": true
},
{
"id": "6977",
"icon": "achievement_zone_townlongsteppes",
"side": "",
"obtainable": true
},
{
"id": "6978",
"icon": "achievement_zone_dreadwastes",
"side": "",
"obtainable": true
},
{
"id": "6979",
"icon": "achievement_zone_valeofeternalblossoms",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lore",
"achs": [
{
"id": "6716",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6754",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6846",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6847",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6850",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6855",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6856",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6857",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "6858",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "7230",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "8049",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "8050",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
},
{
"id": "8051",
"icon": "achievement_faction_lorewalkers",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "7381",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
},
{
"id": "7437",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7438",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7439",
"icon": "expansionicon_mistsofpandaria",
"side": "",
"obtainable": true
},
{
"id": "7518",
"icon": "ability_mount_pandaranmount",
"side": "",
"obtainable": true
},
{
"id": "7932",
"icon": "ability_rogue_deadliness",
"side": "",
"obtainable": true
},
{
"id": "8103",
"icon": "inv_shield_mogu_c_01",
"side": "",
"obtainable": true
},
{
"id": "8078",
"icon": "inv_misc_archaeology_trollgolem",
"side": "",
"obtainable": true
}
]
},
{
"name": "Treasure",
"achs": [
{
"id": "7281",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7282",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7283",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7284",
"icon": "inv_misc_ornatebox",
"side": "",
"obtainable": true
},
{
"id": "7994",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7995",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7996",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
},
{
"id": "7997",
"icon": "racial_dwarf_findtreasure",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Cataclysm",
"zones": [
{
"name": "",
"achs": [
{
"id": "4863",
"icon": "achievement_zone_mount-hyjal",
"side": "",
"obtainable": true
},
{
"id": "4825",
"icon": "achievement_zone_vashjir",
"side": "",
"obtainable": true
},
{
"id": "4864",
"icon": "achievement_zone_deepholm",
"side": "",
"obtainable": true
},
{
"id": "4865",
"icon": "achievement_zone_uldum",
"side": "",
"obtainable": true
},
{
"id": "4866",
"icon": "achievement_zone_twilighthighlands",
"side": "",
"obtainable": true
},
{
"id": "4827",
"icon": "Spell_Fire_Volcano",
"side": "",
"obtainable": true
},
{
"id": "4975",
"icon": "inv_misc_fish_60",
"side": "",
"obtainable": true
},
{
"id": "5518",
"icon": "Spell_Fire_Fire",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Northrend",
"zones": [
{
"name": "",
"achs": [
{
"id": "1264",
"icon": "Achievement_Zone_BoreanTundra_01",
"side": "",
"obtainable": true
},
{
"id": "1268",
"icon": "Achievement_Zone_Sholazar_01",
"side": "",
"obtainable": true
},
{
"id": "1457",
"icon": "Achievement_Zone_CrystalSong_01",
"side": "",
"obtainable": true
},
{
"id": "1265",
"icon": "Achievement_Zone_DragonBlight_01",
"side": "",
"obtainable": true
},
{
"id": "1263",
"icon": "Achievement_Zone_HowlingFjord_01",
"side": "",
"obtainable": true
},
{
"id": "1266",
"icon": "Achievement_Zone_GrizzlyHills_01",
"side": "",
"obtainable": true
},
{
"id": "1267",
"icon": "Achievement_Zone_ZulDrak_03",
"side": "",
"obtainable": true
},
{
"id": "1269",
"icon": "Achievement_Zone_StormPeaks_01",
"side": "",
"obtainable": true
},
{
"id": "1270",
"icon": "Achievement_Zone_IceCrown_01",
"side": "",
"obtainable": true
},
{
"id": "2256",
"icon": "Achievement_Zone_StormPeaks_03",
"side": "",
"obtainable": true
},
{
"id": "2257",
"icon": "Achievement_Zone_DragonBlight_09",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Outland",
"zones": [
{
"name": "",
"achs": [
{
"id": "862",
"icon": "Achievement_Zone_HellfirePeninsula_01",
"side": "",
"obtainable": true
},
{
"id": "863",
"icon": "Achievement_Zone_Zangarmarsh",
"side": "",
"obtainable": true
},
{
"id": "867",
"icon": "Achievement_Zone_Terrokar",
"side": "",
"obtainable": true
},
{
"id": "866",
"icon": "Achievement_Zone_Nagrand_01",
"side": "",
"obtainable": true
},
{
"id": "865",
"icon": "Achievement_Zone_BladesEdgeMtns_01",
"side": "",
"obtainable": true
},
{
"id": "843",
"icon": "Achievement_Zone_Netherstorm_01",
"side": "",
"obtainable": true
},
{
"id": "864",
"icon": "Achievement_Zone_Shadowmoon",
"side": "",
"obtainable": true
},
{
"id": "1311",
"icon": "Spell_Shadow_DeathScream",
"side": "",
"obtainable": true
},
{
"id": "1312",
"icon": "Spell_Shadow_DeathScream",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Eastern Kingdoms",
"zones": [
{
"name": "",
"achs": [
{
"id": "868",
"icon": "Achievement_Zone_IsleOfQuelDanas",
"side": "",
"obtainable": true
},
{
"id": "859",
"icon": "Achievement_Zone_EversongWoods",
"side": "",
"obtainable": true
},
{
"id": "858",
"icon": "Achievement_Zone_Ghostlands",
"side": "",
"obtainable": true
},
{
"id": "771",
"icon": "Achievement_Zone_EasternPlaguelands",
"side": "",
"obtainable": true
},
{
"id": "770",
"icon": "Achievement_Zone_WesternPlaguelands_01",
"side": "",
"obtainable": true
},
{
"id": "768",
"icon": "Achievement_Zone_TirisfalGlades_01",
"side": "",
"obtainable": true
},
{
"id": "769",
"icon": "Achievement_Zone_Silverpine_01",
"side": "",
"obtainable": true
},
{
"id": "772",
"icon": "Achievement_Zone_HillsbradFoothills",
"side": "",
"obtainable": true
},
{
"id": "761",
"icon": "Achievement_Zone_ArathiHighlands_01",
"side": "",
"obtainable": true
},
{
"id": "773",
"icon": "Achievement_Zone_Hinterlands_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "",
"achs": [
{
"id": "841",
"icon": "Achievement_Zone_Wetlands_01",
"side": "",
"obtainable": true
},
{
"id": "627",
"icon": "Achievement_Zone_DunMorogh",
"side": "",
"obtainable": true
},
{
"id": "779",
"icon": "Achievement_Zone_LochModan",
"side": "",
"obtainable": true
},
{
"id": "765",
"icon": "Achievement_Zone_Badlands_01",
"side": "",
"obtainable": true
},
{
"id": "774",
"icon": "Achievement_Zone_SearingGorge_01",
"side": "",
"obtainable": true
},
{
"id": "775",
"icon": "Achievement_Zone_BurningSteppes_01",
"side": "",
"obtainable": true
},
{
"id": "776",
"icon": "Achievement_Zone_ElwynnForest",
"side": "",
"obtainable": true
},
{
"id": "780",
"icon": "Achievement_Zone_RedridgeMountains",
"side": "",
"obtainable": true
},
{
"id": "782",
"icon": "Achievement_Zone_SwampSorrows_01",
"side": "",
"obtainable": true
},
{
"id": "777",
"icon": "Achievement_Zone_DeadwindPass",
"side": "",
"obtainable": true
},
{
"id": "778",
"icon": "Achievement_Zone_Duskwood",
"side": "",
"obtainable": true
},
{
"id": "802",
"icon": "Achievement_Zone_WestFall_01",
"side": "",
"obtainable": true
},
{
"id": "781",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "4995",
"icon": "Achievement_Zone_Stranglethorn_01",
"side": "",
"obtainable": true
},
{
"id": "766",
"icon": "Achievement_Zone_BlastedLands_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Kalimdor",
"zones": [
{
"name": "",
"achs": [
{
"id": "842",
"icon": "Achievement_Zone_Darnassus",
"side": "",
"obtainable": true
},
{
"id": "861",
"icon": "Achievement_Zone_BloodmystIsle_01",
"side": "",
"obtainable": true
},
{
"id": "860",
"icon": "Achievement_Zone_AzuremystIsle_01",
"side": "",
"obtainable": true
},
{
"id": "844",
"icon": "Achievement_Zone_Darkshore_01",
"side": "",
"obtainable": true
},
{
"id": "855",
"icon": "Spell_Arcane_TeleportMoonglade",
"side": "",
"obtainable": true
},
{
"id": "857",
"icon": "Achievement_Zone_Winterspring",
"side": "",
"obtainable": true
},
{
"id": "853",
"icon": "Achievement_Zone_Felwood",
"side": "",
"obtainable": true
},
{
"id": "845",
"icon": "Achievement_Zone_Ashenvale_01",
"side": "",
"obtainable": true
},
{
"id": "852",
"icon": "Achievement_Zone_Azshara_01",
"side": "",
"obtainable": true
},
{
"id": "728",
"icon": "Achievement_Zone_Durotar",
"side": "",
"obtainable": true
},
{
"id": "847",
"icon": "Achievement_Zone_Stonetalon_01",
"side": "",
"obtainable": true
},
{
"id": "750",
"icon": "Achievement_Zone_Barrens_01",
"side": "",
"obtainable": true
},
{
"id": "4996",
"icon": "Achievement_Zone_Barrens_01",
"side": "",
"obtainable": true
},
{
"id": "848",
"icon": "Achievement_Zone_Desolace",
"side": "",
"obtainable": true
},
{
"id": "849",
"icon": "Achievement_Zone_Feralas",
"side": "",
"obtainable": true
},
{
"id": "736",
"icon": "Achievement_Zone_Mulgore_01",
"side": "",
"obtainable": true
},
{
"id": "850",
"icon": "Achievement_Zone_DustwallowMarsh",
"side": "",
"obtainable": true
},
{
"id": "846",
"icon": "Achievement_Zone_ThousandNeedles_01",
"side": "",
"obtainable": true
},
{
"id": "851",
"icon": "Achievement_Zone_Tanaris_01",
"side": "",
"obtainable": true
},
{
"id": "854",
"icon": "Achievement_Zone_UnGoroCrater_01",
"side": "",
"obtainable": true
},
{
"id": "856",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "World Events",
"cats": [
{
"name": "World Events",
"zones": [
{
"name": "",
"achs": [
{
"id": "913",
"icon": "Achievement_WorldEvent_Lunar",
"side": "",
"obtainable": true
},
{
"id": "1693",
"icon": "Achievement_WorldEvent_Valentine",
"side": "",
"obtainable": true
},
{
"id": "2798",
"icon": "INV_Egg_09",
"side": "",
"obtainable": true
},
{
"id": "1793",
"icon": "INV_Misc_Toy_04",
"side": "",
"obtainable": true
},
{
"id": "1039",
"icon": "INV_SummerFest_Symbol_Low",
"side": "H",
"obtainable": true
},
{
"id": "1038",
"icon": "INV_SummerFest_Symbol_High",
"side": "A",
"obtainable": true
},
{
"id": "3457",
"icon": "INV_Helmet_66",
"side": "",
"obtainable": true
},
{
"id": "1656",
"icon": "Achievement_Halloween_Witch_01",
"side": "",
"obtainable": true
},
{
"id": "3456",
"icon": "inv_misc_bone_humanskull_02",
"side": "",
"obtainable": true
},
{
"id": "3478",
"icon": "inv_thanksgiving_turkey",
"side": "",
"obtainable": true
},
{
"id": "1691",
"icon": "Achievement_WorldEvent_Merrymaker",
"side": "",
"obtainable": true
},
{
"id": "2144",
"icon": "Achievement_BG_masterofallBGs",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Lunar Festival",
"zones": [
{
"name": "Elders",
"achs": [
{
"id": "915",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "914",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "910",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "912",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "911",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "1396",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
},
{
"id": "6006",
"icon": "Spell_Holy_SymbolOfHope",
"side": "",
"obtainable": true
}
]
},
{
"name": "Coins",
"achs": [
{
"id": "605",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "606",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "607",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "608",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
},
{
"id": "609",
"icon": "INV_Misc_ElvenCoins",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "937",
"icon": "Spell_Holy_Aspiration",
"side": "",
"obtainable": true
},
{
"id": "626",
"icon": "INV_Chest_Cloth_59",
"side": "",
"obtainable": true
},
{
"id": "1552",
"icon": "INV_Misc_Bomb_05",
"side": "",
"obtainable": true
},
{
"id": "1281",
"icon": "INV_Misc_MissileLarge_Red",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Love is in the Air",
"zones": [
{
"name": "",
"achs": [
{
"id": "1698",
"icon": "INV_ValentinesCard02",
"side": "H",
"obtainable": true
},
{
"id": "1697",
"icon": "INV_ValentinesCard02",
"side": "A",
"obtainable": true
},
{
"id": "1700",
"icon": "INV_Ammo_Arrow_02",
"side": "",
"obtainable": true
},
{
"id": "1188",
"icon": "INV_Ammo_Arrow_02",
"side": "",
"obtainable": true
},
{
"id": "1702",
"icon": "INV_ValentinesChocolate02",
"side": "",
"obtainable": true
},
{
"id": "4624",
"icon": "INV_Misc_Head_Undead_01",
"side": "",
"obtainable": true
},
{
"id": "1696",
"icon": "INV_ValentinePinkRocket",
"side": "",
"obtainable": true
},
{
"id": "1703",
"icon": "INV_RoseBouquet01",
"side": "",
"obtainable": true
},
{
"id": "1694",
"icon": "INV_Chest_Cloth_50",
"side": "",
"obtainable": true
},
{
"id": "1699",
"icon": "INV_Misc_Dust_04",
"side": "",
"obtainable": true
},
{
"id": "1695",
"icon": "Spell_BrokenHeart",
"side": "",
"obtainable": true
},
{
"id": "260",
"icon": "inv_jewelry_necklace_43",
"side": "",
"obtainable": true
},
{
"id": "1279",
"icon": "INV_ValentinePerfumeBottle",
"side": "A",
"obtainable": true
},
{
"id": "1280",
"icon": "INV_ValentinePerfumeBottle",
"side": "H",
"obtainable": true
},
{
"id": "1291",
"icon": "INV_Misc_Basket_01",
"side": "",
"obtainable": true
},
{
"id": "1704",
"icon": "INV_Crate_03",
"side": "",
"obtainable": true
},
{
"id": "1701",
"icon": "INV_ValentinesCandy",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Noblegarden",
"zones": [
{
"name": "",
"achs": [
{
"id": "2417",
"icon": "Achievement_Noblegarden_Chocolate_Egg",
"side": "",
"obtainable": true
},
{
"id": "2418",
"icon": "Achievement_Noblegarden_Chocolate_Egg",
"side": "",
"obtainable": true
},
{
"id": "2419",
"icon": "INV_Egg_09",
"side": "A",
"obtainable": true
},
{
"id": "2422",
"icon": "INV_Misc_Flower_02",
"side": "",
"obtainable": true
},
{
"id": "2497",
"icon": "INV_Egg_09",
"side": "H",
"obtainable": true
},
{
"id": "248",
"icon": "INV_Shirt_08",
"side": "",
"obtainable": true
},
{
"id": "2421",
"icon": "INV_Egg_06",
"side": "A",
"obtainable": true
},
{
"id": "2420",
"icon": "INV_Egg_06",
"side": "H",
"obtainable": true
},
{
"id": "2676",
"icon": "INV_Egg_09",
"side": "",
"obtainable": true
},
{
"id": "2436",
"icon": "Spell_Shaman_GiftEarthmother",
"side": "",
"obtainable": true
},
{
"id": "249",
"icon": "INV_Chest_Cloth_04",
"side": "",
"obtainable": true
},
{
"id": "2416",
"icon": "INV_Egg_07",
"side": "",
"obtainable": true
},
{
"id": "2576",
"icon": "Spell_Shadow_SoothingKiss",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Children's Week",
"zones": [
{
"name": "",
"achs": [
{
"id": "1790",
"icon": "ACHIEVEMENT_BOSS_KINGYMIRON_02",
"side": "",
"obtainable": true
},
{
"id": "1786",
"icon": "Ability_Hunter_BeastCall02",
"side": "",
"obtainable": true
},
{
"id": "1791",
"icon": "INV_Misc_Rune_01",
"side": "",
"obtainable": true
},
{
"id": "1788",
"icon": "INV_Misc_Food_31",
"side": "",
"obtainable": true
},
{
"id": "1789",
"icon": "Ability_Repair",
"side": "",
"obtainable": true
},
{
"id": "1792",
"icon": "Ability_Hunter_Pet_Turtle",
"side": "",
"obtainable": true
},
{
"id": "275",
"icon": "INV_Misc_Toy_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Midsummer",
"zones": [
{
"name": "Desecrate",
"achs": [
{
"id": "1028",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "1031",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1029",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "1032",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1033",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1030",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6010",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "6007",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6013",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "6014",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1037",
"icon": "Spell_Fire_MasterOfElements",
"side": "H",
"obtainable": true
},
{
"id": "1035",
"icon": "Spell_Fire_MasterOfElements",
"side": "A",
"obtainable": true
},
{
"id": "8042",
"icon": "spell_fire_masterofelements",
"side": "A",
"obtainable": true
},
{
"id": "8043",
"icon": "spell_fire_masterofelements",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Honor",
"achs": [
{
"id": "1022",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1025",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "1026",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "1023",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1024",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1027",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6008",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "6009",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6012",
"icon": "INV_SummerFest_FireSpirit",
"side": "H",
"obtainable": true
},
{
"id": "6011",
"icon": "INV_SummerFest_FireSpirit",
"side": "A",
"obtainable": true
},
{
"id": "1036",
"icon": "Spell_Fire_Fireball",
"side": "H",
"obtainable": true
},
{
"id": "1034",
"icon": "Spell_Fire_Fireball",
"side": "A",
"obtainable": true
},
{
"id": "8044",
"icon": "inv_summerfest_firespirit",
"side": "H",
"obtainable": true
},
{
"id": "8045",
"icon": "inv_summerfest_firespirit",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "272",
"icon": "INV_Torch_Thrown",
"side": "",
"obtainable": true
},
{
"id": "263",
"icon": "Spell_Frost_SummonWaterElemental",
"side": "",
"obtainable": true
},
{
"id": "1145",
"icon": "INV_Helmet_08",
"side": "",
"obtainable": true
},
{
"id": "271",
"icon": "Ability_Mage_FireStarter",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Brewfest",
"zones": [
{
"name": "",
"achs": [
{
"id": "1203",
"icon": "INV_Drink_08",
"side": "H",
"obtainable": true
},
{
"id": "1185",
"icon": "INV_Holiday_BeerfestPretzel01",
"side": "",
"obtainable": true
},
{
"id": "295",
"icon": "INV_Misc_Head_Dwarf_01",
"side": "",
"obtainable": true
},
{
"id": "293",
"icon": "INV_Misc_Beer_01",
"side": "",
"obtainable": true
},
{
"id": "1184",
"icon": "INV_Drink_08",
"side": "A",
"obtainable": true
},
{
"id": "303",
"icon": "INV_Cask_01",
"side": "",
"obtainable": true
},
{
"id": "1936",
"icon": "INV_Drink_13",
"side": "",
"obtainable": true
},
{
"id": "1186",
"icon": "INV_Ore_Mithril_01",
"side": "",
"obtainable": true
},
{
"id": "1260",
"icon": "INV_Cask_02",
"side": "",
"obtainable": true
},
{
"id": "2796",
"icon": "INV_MISC_BEER_02",
"side": "",
"obtainable": true
},
{
"id": "1183",
"icon": "INV_Holiday_BrewfestBuff_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Hallow's End",
"zones": [
{
"name": "Tricks and Treats",
"achs": [
{
"id": "966",
"icon": "INV_Misc_Food_27",
"side": "A",
"obtainable": true
},
{
"id": "967",
"icon": "INV_Misc_Food_27",
"side": "H",
"obtainable": true
},
{
"id": "965",
"icon": "Achievement_Halloween_Candy_01",
"side": "H",
"obtainable": true
},
{
"id": "963",
"icon": "Achievement_Halloween_Candy_01",
"side": "A",
"obtainable": true
},
{
"id": "968",
"icon": "INV_Misc_Food_29",
"side": "H",
"obtainable": true
},
{
"id": "969",
"icon": "INV_Misc_Food_29",
"side": "A",
"obtainable": true
},
{
"id": "971",
"icon": "INV_Misc_Food_28",
"side": "A",
"obtainable": true
},
{
"id": "970",
"icon": "INV_Misc_Food_28",
"side": "H",
"obtainable": true
},
{
"id": "5835",
"icon": "INV_MISC_FOOD_26",
"side": "H",
"obtainable": true
},
{
"id": "5836",
"icon": "INV_MISC_FOOD_26",
"side": "A",
"obtainable": true
},
{
"id": "5837",
"icon": "INV_Misc_Food_25",
"side": "A",
"obtainable": true
},
{
"id": "5838",
"icon": "INV_Misc_Food_25",
"side": "H",
"obtainable": true
},
{
"id": "7601",
"icon": "inv_misc_food_168_ricecake01",
"side": "A",
"obtainable": true
},
{
"id": "7602",
"icon": "inv_misc_food_168_ricecake01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "972",
"icon": "INV_Misc_Food_30",
"side": "",
"obtainable": true
},
{
"id": "288",
"icon": "Spell_Shadow_PlagueCloud",
"side": "",
"obtainable": true
},
{
"id": "1040",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "A",
"obtainable": true
},
{
"id": "1261",
"icon": "Ability_Warrior_Rampage",
"side": "",
"obtainable": true
},
{
"id": "291",
"icon": "INV_Misc_Bag_28_Halloween",
"side": "",
"obtainable": true
},
{
"id": "255",
"icon": "INV_Misc_Food_59",
"side": "",
"obtainable": true
},
{
"id": "1041",
"icon": "Achievement_Halloween_RottenEgg_01",
"side": "H",
"obtainable": true
},
{
"id": "292",
"icon": "Achievement_Halloween_Cat_01",
"side": "",
"obtainable": true
},
{
"id": "289",
"icon": "Achievement_Halloween_Bat_01",
"side": "",
"obtainable": true
},
{
"id": "283",
"icon": "Achievement_Halloween_Ghost_01",
"side": "",
"obtainable": true
},
{
"id": "979",
"icon": "INV_Mask_06",
"side": "",
"obtainable": true
},
{
"id": "981",
"icon": "Achievement_Halloween_Smiley_01",
"side": "",
"obtainable": true
},
{
"id": "284",
"icon": "INV_Mask_04",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Pilgrim's Bounty",
"zones": [
{
"name": "",
"achs": [
{
"id": "3558",
"icon": "Spell_Holy_LayOnHands",
"side": "",
"obtainable": true
},
{
"id": "3582",
"icon": "Achievement_Boss_TalonKingIkiss",
"side": "",
"obtainable": true
},
{
"id": "3578",
"icon": "Ability_Hunter_SilentHunter",
"side": "",
"obtainable": true
},
{
"id": "3559",
"icon": "INV_Torch_Unlit",
"side": "",
"obtainable": true
},
{
"id": "3597",
"icon": "inv_helmet_65",
"side": "H",
"obtainable": true
},
{
"id": "3596",
"icon": "inv_helmet_65",
"side": "A",
"obtainable": true
},
{
"id": "3577",
"icon": "Achievement_Profession_ChefHat",
"side": "H",
"obtainable": true
},
{
"id": "3576",
"icon": "Achievement_Profession_ChefHat",
"side": "A",
"obtainable": true
},
{
"id": "3556",
"icon": "INV_Misc_Organ_10",
"side": "A",
"obtainable": true
},
{
"id": "3557",
"icon": "INV_Misc_Organ_10",
"side": "H",
"obtainable": true
},
{
"id": "3580",
"icon": "INV_BannerPVP_01",
"side": "A",
"obtainable": true
},
{
"id": "3581",
"icon": "INV_BannerPVP_02",
"side": "H",
"obtainable": true
},
{
"id": "3579",
"icon": "Ability_Warrior_BattleShout",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Winter Veil",
"zones": [
{
"name": "",
"achs": [
{
"id": "273",
"icon": "Achievement_WorldEvent_Reindeer",
"side": "",
"obtainable": true
},
{
"id": "1687",
"icon": "Spell_Frost_FrostShock",
"side": "",
"obtainable": true
},
{
"id": "1689",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "259",
"icon": "INV_Ammo_Snowball",
"side": "H",
"obtainable": true
},
{
"id": "1255",
"icon": "INV_Ammo_Snowball",
"side": "A",
"obtainable": true
},
{
"id": "252",
"icon": "Achievement_WorldEvent_LittleHelper",
"side": "",
"obtainable": true
},
{
"id": "1688",
"icon": "INV_Misc_Food_62",
"side": "",
"obtainable": true
},
{
"id": "279",
"icon": "INV_Helmet_68",
"side": "",
"obtainable": true
},
{
"id": "1282",
"icon": "Achievement_WorldEvent_XmasOgre",
"side": "",
"obtainable": true
},
{
"id": "1295",
"icon": "INV_Gizmo_GoblingTonkController",
"side": "",
"obtainable": true
},
{
"id": "5854",
"icon": "Spell_Holy_DivineHymn",
"side": "H",
"obtainable": true
},
{
"id": "5853",
"icon": "Spell_Holy_DivineHymn",
"side": "A",
"obtainable": true
},
{
"id": "1690",
"icon": "Spell_Frost_FrostWard",
"side": "",
"obtainable": true
},
{
"id": "4436",
"icon": "INV_Weapon_Rifle_01",
"side": "A",
"obtainable": true
},
{
"id": "4437",
"icon": "INV_Weapon_Rifle_01",
"side": "H",
"obtainable": true
},
{
"id": "1686",
"icon": "INV_Misc_Herb_09",
"side": "A",
"obtainable": true
},
{
"id": "1685",
"icon": "INV_Misc_Herb_09",
"side": "H",
"obtainable": true
},
{
"id": "277",
"icon": "INV_Food_ChristmasFruitCake_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Argent Tournament",
"zones": [
{
"name": "Champion",
"achs": [
{
"id": "2781",
"icon": "inv_misc_tournaments_symbol_human",
"side": "A",
"obtainable": true
},
{
"id": "2780",
"icon": "inv_misc_tournaments_symbol_dwarf",
"side": "A",
"obtainable": true
},
{
"id": "2779",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "2777",
"icon": "inv_misc_tournaments_symbol_nightelf",
"side": "A",
"obtainable": true
},
{
"id": "2778",
"icon": "inv_misc_tournaments_symbol_draenei",
"side": "A",
"obtainable": true
},
{
"id": "2782",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2783",
"icon": "inv_misc_tournaments_symbol_orc",
"side": "H",
"obtainable": true
},
{
"id": "2784",
"icon": "inv_misc_tournaments_symbol_troll",
"side": "H",
"obtainable": true
},
{
"id": "2786",
"icon": "inv_misc_tournaments_symbol_tauren",
"side": "H",
"obtainable": true
},
{
"id": "2787",
"icon": "inv_misc_tournaments_symbol_scourge",
"side": "H",
"obtainable": true
},
{
"id": "2785",
"icon": "inv_misc_tournaments_symbol_bloodelf",
"side": "H",
"obtainable": true
},
{
"id": "2788",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Exalted Champion",
"achs": [
{
"id": "2764",
"icon": "inv_misc_tournaments_symbol_human",
"side": "A",
"obtainable": true
},
{
"id": "2763",
"icon": "inv_misc_tournaments_symbol_dwarf",
"side": "A",
"obtainable": true
},
{
"id": "2762",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "2760",
"icon": "inv_misc_tournaments_symbol_nightelf",
"side": "A",
"obtainable": true
},
{
"id": "2761",
"icon": "inv_misc_tournaments_symbol_draenei",
"side": "A",
"obtainable": true
},
{
"id": "2770",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2817",
"icon": "inv_misc_tournaments_banner_human",
"side": "A",
"obtainable": true
},
{
"id": "2765",
"icon": "inv_misc_tournaments_symbol_orc",
"side": "H",
"obtainable": true
},
{
"id": "2766",
"icon": "inv_misc_tournaments_symbol_troll",
"side": "H",
"obtainable": true
},
{
"id": "2768",
"icon": "inv_misc_tournaments_symbol_tauren",
"side": "H",
"obtainable": true
},
{
"id": "2769",
"icon": "inv_misc_tournaments_symbol_scourge",
"side": "H",
"obtainable": true
},
{
"id": "2767",
"icon": "inv_misc_tournaments_symbol_bloodelf",
"side": "H",
"obtainable": true
},
{
"id": "2771",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
},
{
"id": "2816",
"icon": "inv_misc_tournaments_banner_orc",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "3677",
"icon": "inv_elemental_primal_nether",
"side": "H",
"obtainable": true
},
{
"id": "2772",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "4596",
"icon": "inv_sword_155",
"side": "",
"obtainable": true
},
{
"id": "3736",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "2836",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "2773",
"icon": "INV_Helmet_44",
"side": "",
"obtainable": true
},
{
"id": "2756",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "2758",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "",
"obtainable": true
},
{
"id": "3676",
"icon": "INV_Elemental_Primal_Mana",
"side": "A",
"obtainable": true
}
]
}
]
},
{
"name": "Darkmoon Faire",
"zones": [
{
"name": "",
"achs": [
{
"id": "6025",
"icon": "Ability_Mount_RidingHorse",
"side": "",
"obtainable": true
},
{
"id": "6026",
"icon": "INV_Misc_Food_60",
"side": "",
"obtainable": true
},
{
"id": "6022",
"icon": "INV_Ammo_Bullet_01",
"side": "",
"obtainable": true
},
{
"id": "6020",
"icon": "inv_misc_token_darkmoon_01",
"side": "",
"obtainable": true
},
{
"id": "6031",
"icon": "inv_misc_missilesmallcluster_green",
"side": "H",
"obtainable": true
},
{
"id": "6030",
"icon": "inv_misc_missilesmallcluster_green",
"side": "A",
"obtainable": true
},
{
"id": "6032",
"icon": "inv_misc_book_16",
"side": "",
"obtainable": true
},
{
"id": "6019",
"icon": "INV_Misc_Ticket_Darkmoon_01",
"side": "",
"obtainable": true
},
{
"id": "6028",
"icon": "INV_BannerPVP_03",
"side": "",
"obtainable": true
},
{
"id": "6027",
"icon": "INV_Misc_Book_06",
"side": "",
"obtainable": true
},
{
"id": "6029",
"icon": "trade_archaeology_dwarf_runestone",
"side": "",
"obtainable": true
},
{
"id": "6021",
"icon": "Ability_Hunter_MasterMarksman",
"side": "",
"obtainable": true
},
{
"id": "6332",
"icon": "inv_misc_rabbit",
"side": "",
"obtainable": true
},
{
"id": "6023",
"icon": "inv_misc_bone_skull_01",
"side": "",
"obtainable": true
},
{
"id": "6024",
"icon": "Spell_Shadow_Skull",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Brawler's Guild",
"zones": [
{
"name": "",
"achs": [
{
"id": "7947",
"icon": "spell_holy_silence",
"side": "A",
"obtainable": true
},
{
"id": "7948",
"icon": "spell_holy_silence",
"side": "H",
"obtainable": true
},
{
"id": "7937",
"icon": "inv_pants_plate_05",
"side": "A",
"obtainable": true
},
{
"id": "8020",
"icon": "inv_pants_plate_05",
"side": "H",
"obtainable": true
},
{
"id": "7940",
"icon": "inv_misc_bandage_05",
"side": "A",
"obtainable": true
},
{
"id": "7939",
"icon": "inv_misc_bandage_05",
"side": "H",
"obtainable": true
},
{
"id": "7941",
"icon": "spell_holy_fistofjustice",
"side": "A",
"obtainable": true
},
{
"id": "7942",
"icon": "spell_holy_fistofjustice",
"side": "H",
"obtainable": true
},
{
"id": "7946",
"icon": "spell_holy_fistofjustice",
"side": "A",
"obtainable": true
},
{
"id": "8022",
"icon": "spell_holy_fistofjustice",
"side": "H",
"obtainable": true
},
{
"id": "7949",
"icon": "ability_warrior_battleshout",
"side": "A",
"obtainable": true
},
{
"id": "7950",
"icon": "inv_misc_bandage_05",
"side": "H",
"obtainable": true
},
{
"id": "7943",
"icon": "thumbup",
"side": "",
"obtainable": true
},
{
"id": "7944",
"icon": "inv_drink_29_sunkissedwine",
"side": "",
"obtainable": true
},
{
"id": "7945",
"icon": "spell_shaman_spiritwalkersgrace",
"side": "",
"obtainable": true
},
{
"id": "8342",
"icon": "inv_inscription_tarot_volcanocard",
"side": "H",
"obtainable": true
},
{
"id": "8339",
"icon": "inv_inscription_tarot_volcanocard",
"side": "A",
"obtainable": true
},
{
"id": "8340",
"icon": "inv_inscription_tarot_volcanocard",
"side": "A",
"obtainable": true
},
{
"id": "8343",
"icon": "inv_inscription_tarot_volcanocard",
"side": "H",
"obtainable": true
},
{
"id": "8337",
"icon": "warrior_talent_icon_furyintheblood",
"side": "H",
"obtainable": true
},
{
"id": "8335",
"icon": "warrior_talent_icon_furyintheblood",
"side": "A",
"obtainable": true
},
{
"id": "8338",
"icon": "pandarenracial_quiveringpain",
"side": "H",
"obtainable": true
},
{
"id": "8336",
"icon": "pandarenracial_quiveringpain",
"side": "A",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Feats of Strength",
"cats": [
{
"name": "Feats of Strength",
"zones": [
{
"name": "Realm First!",
"achs": [
{
"id": "1416",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "1419",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "1415",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "1420",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "5395",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "1414",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "1417",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "1418",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "1421",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "1423",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "1424",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "1425",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "1422",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "1426",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "1427",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6433",
"icon": "achievement_challengemode_gold",
"side": "",
"obtainable": true
},
{
"id": "457",
"icon": "Achievement_Level_80",
"side": "",
"obtainable": true
},
{
"id": "4999",
"icon": "achievement_level_85",
"side": "",
"obtainable": true
},
{
"id": "6524",
"icon": "achievement_level_90",
"side": "",
"obtainable": true
},
{
"id": "1405",
"icon": "Achievement_Character_Bloodelf_Female",
"side": "",
"obtainable": true
},
{
"id": "1406",
"icon": "Achievement_Character_Draenei_Female",
"side": "",
"obtainable": true
},
{
"id": "1407",
"icon": "Achievement_Character_Dwarf_Male",
"side": "",
"obtainable": true
},
{
"id": "1413",
"icon": "Achievement_Character_Undead_Male",
"side": "",
"obtainable": true
},
{
"id": "1404",
"icon": "Achievement_Character_Gnome_Male",
"side": "",
"obtainable": true
},
{
"id": "1408",
"icon": "Achievement_Character_Human_Female",
"side": "",
"obtainable": true
},
{
"id": "1409",
"icon": "Achievement_Character_Nightelf_Male",
"side": "",
"obtainable": true
},
{
"id": "1410",
"icon": "Achievement_Character_Orc_Male",
"side": "",
"obtainable": true
},
{
"id": "1411",
"icon": "Achievement_Character_Tauren_Female",
"side": "",
"obtainable": true
},
{
"id": "1412",
"icon": "Achievement_Character_Troll_Male",
"side": "",
"obtainable": true
},
{
"id": "461",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "5005",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "6748",
"icon": "Spell_Deathknight_ClassIcon",
"side": "",
"obtainable": true
},
{
"id": "466",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "5000",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "6743",
"icon": "Ability_Druid_Maul",
"side": "",
"obtainable": true
},
{
"id": "462",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "5004",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "6747",
"icon": "INV_Weapon_Bow_07",
"side": "",
"obtainable": true
},
{
"id": "460",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "5006",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "6749",
"icon": "INV_Staff_13",
"side": "",
"obtainable": true
},
{
"id": "465",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "5001",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "6744",
"icon": "Ability_ThunderBolt",
"side": "",
"obtainable": true
},
{
"id": "464",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "5002",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "6745",
"icon": "INV_Staff_30",
"side": "",
"obtainable": true
},
{
"id": "458",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "5008",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "6751",
"icon": "INV_ThrowingKnife_04",
"side": "",
"obtainable": true
},
{
"id": "467",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "4998",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "6523",
"icon": "Spell_Nature_BloodLust",
"side": "",
"obtainable": true
},
{
"id": "463",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "5003",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "6746",
"icon": "Spell_Nature_Drowsy",
"side": "",
"obtainable": true
},
{
"id": "459",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "5007",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "6750",
"icon": "INV_Sword_27",
"side": "",
"obtainable": true
},
{
"id": "6752",
"icon": "class_monk",
"side": "",
"obtainable": true
},
{
"id": "1463",
"icon": "Spell_Misc_HellifrePVPCombatMorale",
"side": "",
"obtainable": true
},
{
"id": "1402",
"icon": "INV_Trinket_Naxxramas06",
"side": "",
"obtainable": true
},
{
"id": "456",
"icon": "Achievement_Dungeon_CoABlackDragonflight_25man",
"side": "",
"obtainable": true
},
{
"id": "1400",
"icon": "INV_Misc_Head_Dragon_Blue",
"side": "",
"obtainable": true
},
{
"id": "3117",
"icon": "Achievement_Boss_YoggSaron_01",
"side": "",
"obtainable": true
},
{
"id": "3259",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "4078",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "4576",
"icon": "inv_helmet_96",
"side": "",
"obtainable": true
},
{
"id": "5383",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "6861",
"icon": "INV_Misc_Food_15",
"side": "",
"obtainable": true
},
{
"id": "5386",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "6864",
"icon": "Spell_Holy_SealOfSacrifice",
"side": "",
"obtainable": true
},
{
"id": "5387",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "6865",
"icon": "Trade_Fishing",
"side": "",
"obtainable": true
},
{
"id": "5381",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "6859",
"icon": "Trade_Alchemy",
"side": "",
"obtainable": true
},
{
"id": "5396",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "6873",
"icon": "trade_archaeology",
"side": "",
"obtainable": true
},
{
"id": "5382",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "6860",
"icon": "Trade_BlackSmithing",
"side": "",
"obtainable": true
},
{
"id": "5384",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "6862",
"icon": "Trade_Engraving",
"side": "",
"obtainable": true
},
{
"id": "5385",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "6863",
"icon": "Trade_Engineering",
"side": "",
"obtainable": true
},
{
"id": "5388",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "6866",
"icon": "Trade_Herbalism",
"side": "",
"obtainable": true
},
{
"id": "5390",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "6868",
"icon": "INV_Misc_Gem_01",
"side": "",
"obtainable": true
},
{
"id": "5391",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "6869",
"icon": "Trade_LeatherWorking",
"side": "",
"obtainable": true
},
{
"id": "5392",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "6870",
"icon": "Trade_Mining",
"side": "",
"obtainable": true
},
{
"id": "5389",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "6867",
"icon": "INV_Feather_05",
"side": "",
"obtainable": true
},
{
"id": "5393",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "6871",
"icon": "INV_Misc_Pelt_Wolf_01",
"side": "",
"obtainable": true
},
{
"id": "5394",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6872",
"icon": "Trade_Tailoring",
"side": "",
"obtainable": true
},
{
"id": "6829",
"icon": "trade_archaeology_highborne_scroll",
"side": "",
"obtainable": true
}
]
},
{
"name": "PVP",
"achs": [
{
"id": "442",
"icon": "Achievement_PVP_A_01",
"side": "A",
"obtainable": true
},
{
"id": "470",
"icon": "Achievement_PVP_A_02",
"side": "A",
"obtainable": true
},
{
"id": "471",
"icon": "Achievement_PVP_A_03",
"side": "A",
"obtainable": true
},
{
"id": "441",
"icon": "Achievement_PVP_A_04",
"side": "A",
"obtainable": true
},
{
"id": "440",
"icon": "Achievement_PVP_A_05",
"side": "A",
"obtainable": true
},
{
"id": "439",
"icon": "Achievement_PVP_A_06",
"side": "A",
"obtainable": true
},
{
"id": "472",
"icon": "Achievement_PVP_A_07",
"side": "A",
"obtainable": true
},
{
"id": "438",
"icon": "Achievement_PVP_A_08",
"side": "A",
"obtainable": true
},
{
"id": "437",
"icon": "Achievement_PVP_A_09",
"side": "A",
"obtainable": true
},
{
"id": "436",
"icon": "Achievement_PVP_A_10",
"side": "A",
"obtainable": true
},
{
"id": "435",
"icon": "Achievement_PVP_A_11",
"side": "A",
"obtainable": true
},
{
"id": "473",
"icon": "Achievement_PVP_A_12",
"side": "A",
"obtainable": true
},
{
"id": "434",
"icon": "Achievement_PVP_A_13",
"side": "A",
"obtainable": true
},
{
"id": "433",
"icon": "Achievement_PVP_A_14",
"side": "A",
"obtainable": true
},
{
"id": "454",
"icon": "Achievement_PVP_H_01",
"side": "H",
"obtainable": true
},
{
"id": "468",
"icon": "Achievement_PVP_H_02",
"side": "H",
"obtainable": true
},
{
"id": "453",
"icon": "Achievement_PVP_H_03",
"side": "H",
"obtainable": true
},
{
"id": "450",
"icon": "Achievement_PVP_H_04",
"side": "H",
"obtainable": true
},
{
"id": "452",
"icon": "Achievement_PVP_H_05",
"side": "H",
"obtainable": true
},
{
"id": "451",
"icon": "Achievement_PVP_H_06",
"side": "H",
"obtainable": true
},
{
"id": "449",
"icon": "Achievement_PVP_H_07",
"side": "H",
"obtainable": true
},
{
"id": "469",
"icon": "Achievement_PVP_H_08",
"side": "H",
"obtainable": true
},
{
"id": "448",
"icon": "Achievement_PVP_H_09",
"side": "H",
"obtainable": true
},
{
"id": "447",
"icon": "Achievement_PVP_H_10",
"side": "H",
"obtainable": true
},
{
"id": "444",
"icon": "Achievement_PVP_H_11",
"side": "H",
"obtainable": true
},
{
"id": "446",
"icon": "Achievement_PVP_H_12",
"side": "H",
"obtainable": true
},
{
"id": "445",
"icon": "Achievement_PVP_H_13",
"side": "H",
"obtainable": true
},
{
"id": "443",
"icon": "Achievement_PVP_H_14",
"side": "H",
"obtainable": true
},
{
"id": "418",
"icon": "Achievement_FeatsOfStrength_Gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "419",
"icon": "Achievement_FeatsOfStrength_Gladiator_02",
"side": "",
"obtainable": true
},
{
"id": "420",
"icon": "Achievement_FeatsOfStrength_Gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "3336",
"icon": "Achievement_FeatsOfStrength_Gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "3436",
"icon": "Achievement_FeatsOfStrength_Gladiator_05",
"side": "",
"obtainable": true
},
{
"id": "3758",
"icon": "Achievement_FeatsOfStrength_Gladiator_06",
"side": "",
"obtainable": true
},
{
"id": "4599",
"icon": "Achievement_FeatsOfStrength_Gladiator_07",
"side": "",
"obtainable": true
},
{
"id": "6002",
"icon": "achievement_featsofstrength_gladiator_09",
"side": "",
"obtainable": true
},
{
"id": "6124",
"icon": "Achievement_FeatsOfStrength_Gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "6938",
"icon": "achievement_featsofstrength_gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "3618",
"icon": "INV_Spear_05",
"side": "",
"obtainable": true
},
{
"id": "8214",
"icon": "achievement_featsofstrength_gladiator_10",
"side": "",
"obtainable": true
},
{
"id": "8243",
"icon": "achievement_pvp_a_a",
"side": "A",
"obtainable": true
},
{
"id": "8244",
"icon": "achievement_pvp_h_h",
"side": "H",
"obtainable": true
},
{
"id": "8392",
"icon": "inv_helmet_plate_pvpwarrior_e_01",
"side": "",
"obtainable": true
},
{
"id": "8391",
"icon": "inv_spear_06",
"side": "",
"obtainable": true
}
]
},
{
"name": "Mounts",
"achs": [
{
"id": "879",
"icon": "Ability_Mount_MountainRam",
"side": "",
"obtainable": true
},
{
"id": "886",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "887",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "888",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "2316",
"icon": "Ability_Mount_NetherDrakeElite",
"side": "",
"obtainable": true
},
{
"id": "3096",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "3756",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "3757",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "4600",
"icon": "ability_mount_redfrostwyrm_01",
"side": "",
"obtainable": true
},
{
"id": "6003",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6321",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6322",
"icon": "Ability_Mount_Drake_Twilight",
"side": "",
"obtainable": true
},
{
"id": "6741",
"icon": "ability_mount_drake_twilight",
"side": "",
"obtainable": true
},
{
"id": "424",
"icon": "INV_Misc_QirajiCrystal_02",
"side": "",
"obtainable": true
},
{
"id": "729",
"icon": "Ability_Mount_Undeadhorse",
"side": "",
"obtainable": true
},
{
"id": "880",
"icon": "Ability_Mount_JungleTiger",
"side": "",
"obtainable": true
},
{
"id": "881",
"icon": "Ability_Mount_Raptor",
"side": "",
"obtainable": true
},
{
"id": "882",
"icon": "Ability_Mount_Dreadsteed",
"side": "",
"obtainable": true
},
{
"id": "883",
"icon": "INV-Mount_Raven_54",
"side": "",
"obtainable": true
},
{
"id": "884",
"icon": "Ability_Mount_CockatriceMountElite_Green",
"side": "",
"obtainable": true
},
{
"id": "430",
"icon": "Ability_Druid_ChallangingRoar",
"side": "",
"obtainable": true
},
{
"id": "885",
"icon": "Inv_Misc_SummerFest_BrazierOrange",
"side": "",
"obtainable": true
},
{
"id": "980",
"icon": "INV_Belt_12",
"side": "",
"obtainable": true
},
{
"id": "2081",
"icon": "Ability_Mount_Mammoth_Black",
"side": "",
"obtainable": true
},
{
"id": "2357",
"icon": "Ability_Mount_Dreadsteed",
"side": "",
"obtainable": true
},
{
"id": "3356",
"icon": "Ability_Mount_PinkTiger",
"side": "A",
"obtainable": true
},
{
"id": "3357",
"icon": "Ability_Hunter_Pet_Raptor",
"side": "H",
"obtainable": true
},
{
"id": "3496",
"icon": "INV_Cask_01",
"side": "",
"obtainable": true
},
{
"id": "4626",
"icon": "INV_Misc_EngGizmos_03",
"side": "",
"obtainable": true
},
{
"id": "4625",
"icon": "Spell_DeathKnight_SummonDeathCharger",
"side": "",
"obtainable": true
},
{
"id": "4627",
"icon": "INV_ValentinePinkRocket",
"side": "",
"obtainable": true
},
{
"id": "5767",
"icon": "ability_mount_camel_gray",
"side": "",
"obtainable": true
},
{
"id": "1436",
"icon": "Ability_Mount_Charger",
"side": "",
"obtainable": true
},
{
"id": "4832",
"icon": "ability_mount_rocketmount2",
"side": "",
"obtainable": true
},
{
"id": "8092",
"icon": "inv_misc_bone_01",
"side": "",
"obtainable": true
},
{
"id": "8213",
"icon": "inv_misc_reforgedarchstone_01",
"side": "",
"obtainable": true
},
{
"id": "8216",
"icon": "inv_pandarenserpentmount_white",
"side": "",
"obtainable": true
},
{
"id": "8345",
"icon": "inv_pegasusmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "Lost Content",
"achs": [
{
"id": "957",
"icon": "INV_Bijou_Green",
"side": "",
"obtainable": true
},
{
"id": "2496",
"icon": "Spell_Frost_SummonWaterElemental_2",
"side": "",
"obtainable": true
},
{
"id": "560",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "691",
"icon": "Achievement_Boss_Zuljin",
"side": "",
"obtainable": true
},
{
"id": "688",
"icon": "Achievement_Boss_Hakkar",
"side": "",
"obtainable": true
},
{
"id": "2018",
"icon": "Spell_Arcane_FocusedPower",
"side": "",
"obtainable": true
},
{
"id": "2359",
"icon": "Ability_Druid_FlightForm",
"side": "",
"obtainable": true
},
{
"id": "5533",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "16",
"icon": "Ability_Warrior_SecondWind",
"side": "",
"obtainable": true
},
{
"id": "705",
"icon": "Ability_Warrior_OffensiveStance",
"side": "",
"obtainable": true
},
{
"id": "432",
"icon": "INV_Mace_51",
"side": "",
"obtainable": true
},
{
"id": "431",
"icon": "INV_Mace_25",
"side": "",
"obtainable": true
},
{
"id": "684",
"icon": "Achievement_Boss_Onyxia",
"side": "",
"obtainable": true
},
{
"id": "5788",
"icon": "inv_misc_book_17",
"side": "",
"obtainable": true
},
{
"id": "2358",
"icon": "Ability_Mount_Charger",
"side": "",
"obtainable": true
},
{
"id": "2019",
"icon": "Ability_Paladin_SwiftRetribution",
"side": "",
"obtainable": true
},
{
"id": "3844",
"icon": "Spell_Holy_EmpowerChampion",
"side": "",
"obtainable": true
},
{
"id": "4316",
"icon": "Spell_Holy_EmpowerChampion",
"side": "",
"obtainable": true
},
{
"id": "2187",
"icon": "Spell_Holy_SealOfVengeance",
"side": "",
"obtainable": true
},
{
"id": "2186",
"icon": "Spell_Holy_WeaponMastery",
"side": "",
"obtainable": true
},
{
"id": "3316",
"icon": "Achievement_Boss_Algalon_01",
"side": "",
"obtainable": true
},
{
"id": "3004",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "2903",
"icon": "Spell_Holy_SealOfVengeance",
"side": "",
"obtainable": true
},
{
"id": "3005",
"icon": "Spell_Misc_EmotionSad",
"side": "",
"obtainable": true
},
{
"id": "2904",
"icon": "Spell_Holy_WeaponMastery",
"side": "",
"obtainable": true
},
{
"id": "3808",
"icon": "INV_Crown_14",
"side": "",
"obtainable": true
},
{
"id": "3809",
"icon": "INV_Crown_15",
"side": "",
"obtainable": true
},
{
"id": "3810",
"icon": "inv_crown_13",
"side": "",
"obtainable": true
},
{
"id": "4080",
"icon": "achievement_reputation_argentcrusader",
"side": "",
"obtainable": true
},
{
"id": "3817",
"icon": "INV_Crown_14",
"side": "",
"obtainable": true
},
{
"id": "3818",
"icon": "INV_Crown_15",
"side": "",
"obtainable": true
},
{
"id": "3819",
"icon": "inv_crown_13",
"side": "",
"obtainable": true
},
{
"id": "4156",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "A",
"obtainable": true
},
{
"id": "4079",
"icon": "Achievement_Reputation_ArgentChampion",
"side": "H",
"obtainable": true
},
{
"id": "7485",
"icon": "achievement_raid_mantidraid07",
"side": "H",
"obtainable": true
},
{
"id": "7486",
"icon": "achievement_raid_mantidraid07",
"side": "H",
"obtainable": true
},
{
"id": "7487",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "H",
"obtainable": true
},
{
"id": "2085",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2086",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2087",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2088",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "2089",
"icon": "INV_Misc_Platnumdisks",
"side": "",
"obtainable": true
},
{
"id": "6954",
"icon": "achievement_moguraid_06",
"side": "",
"obtainable": true
},
{
"id": "8246",
"icon": "achievement_raid_mantidraid07",
"side": "",
"obtainable": true
},
{
"id": "8249",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8248",
"icon": "achievement_raid_terraceofendlessspring04",
"side": "",
"obtainable": true
},
{
"id": "8089",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
},
{
"id": "8238",
"icon": "achievement_boss_leishen",
"side": "",
"obtainable": true
},
{
"id": "8260",
"icon": "achievement_boss_ra_den",
"side": "",
"obtainable": true
}
]
},
{
"name": "Legendary",
"achs": [
{
"id": "428",
"icon": "INV_Sword_39",
"side": "",
"obtainable": true
},
{
"id": "429",
"icon": "INV_Hammer_Unique_Sulfuras",
"side": "",
"obtainable": true
},
{
"id": "425",
"icon": "INV_Staff_Medivh",
"side": "",
"obtainable": true
},
{
"id": "426",
"icon": "INV_Weapon_Glave_01",
"side": "",
"obtainable": true
},
{
"id": "725",
"icon": "INV_WEAPON_BOW_39",
"side": "",
"obtainable": true
},
{
"id": "3142",
"icon": "INV_Mace_99",
"side": "",
"obtainable": true
},
{
"id": "4623",
"icon": "inv_axe_114",
"side": "",
"obtainable": true
},
{
"id": "5839",
"icon": "stave_2h_tarecgosa_e_01stagefinal",
"side": "",
"obtainable": true
},
{
"id": "6181",
"icon": "inv_knife_1h_deathwingraid_e_03",
"side": "",
"obtainable": true
}
]
},
{
"name": "Collector's Edition",
"achs": [
{
"id": "662",
"icon": "INV_DiabloStone",
"side": "",
"obtainable": true
},
{
"id": "663",
"icon": "INV_Belt_05",
"side": "",
"obtainable": true
},
{
"id": "664",
"icon": "Spell_Shadow_SummonFelHunter",
"side": "",
"obtainable": true
},
{
"id": "665",
"icon": "INV_Netherwhelp",
"side": "",
"obtainable": true
},
{
"id": "683",
"icon": "INV_PET_FROSTWYRM",
"side": "",
"obtainable": true
},
{
"id": "4824",
"icon": "inv_sigil_thorim",
"side": "",
"obtainable": true
},
{
"id": "5377",
"icon": "inv_dragonwhelpcataclysm",
"side": "",
"obtainable": true
},
{
"id": "7842",
"icon": "ability_pet_baneling",
"side": "",
"obtainable": true
},
{
"id": "7412",
"icon": "inv_spear_05",
"side": "",
"obtainable": true
},
{
"id": "6848",
"icon": "ability_mount_quilenflyingmount",
"side": "",
"obtainable": true
},
{
"id": "6849",
"icon": "ability_mount_quilenflyingmount",
"side": "",
"obtainable": true
}
]
},
{
"name": "BlizzCon",
"achs": [
{
"id": "411",
"icon": "INV_Egg_03",
"side": "",
"obtainable": true
},
{
"id": "412",
"icon": "INV_Misc_Head_Murloc_01",
"side": "",
"obtainable": true
},
{
"id": "414",
"icon": "INV_Sword_07",
"side": "",
"obtainable": true
},
{
"id": "415",
"icon": "ability_mount_bigblizzardbear",
"side": "",
"obtainable": true
},
{
"id": "3536",
"icon": "INV_Egg_03",
"side": "",
"obtainable": true
},
{
"id": "5378",
"icon": "INV_Misc_ShadowEgg",
"side": "",
"obtainable": true
},
{
"id": "6185",
"icon": "inv_pet_diablobabymurloc",
"side": "",
"obtainable": true
}
]
},
{
"name": "Events",
"achs": [
{
"id": "416",
"icon": "Achievement_Zone_Silithus_01",
"side": "",
"obtainable": true
},
{
"id": "2079",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "1637",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "1636",
"icon": "Achievement_General",
"side": "",
"obtainable": true
},
{
"id": "2116",
"icon": "INV_Shirt_GuildTabard_01",
"side": "",
"obtainable": true
},
{
"id": "2456",
"icon": "Ability_Hunter_Pet_Bat",
"side": "",
"obtainable": true
},
{
"id": "4887",
"icon": "INV_Enchant_VoidSphere",
"side": "",
"obtainable": true
},
{
"id": "4786",
"icon": "inv_misc_tournaments_symbol_gnome",
"side": "A",
"obtainable": true
},
{
"id": "4790",
"icon": "INV_Misc_Head_Troll_01",
"side": "H",
"obtainable": true
},
{
"id": "7467",
"icon": "spell_arcane_teleporttheramore",
"side": "A",
"obtainable": true
},
{
"id": "7468",
"icon": "spell_arcane_teleporttheramore",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Holidays",
"achs": [
{
"id": "1292",
"icon": "INV_MISC_BEER_02",
"side": "",
"obtainable": true
},
{
"id": "1705",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "1293",
"icon": "INV_Misc_Beer_04",
"side": "",
"obtainable": true
},
{
"id": "1706",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "4782",
"icon": "inv_misc_beer_06",
"side": "",
"obtainable": true
},
{
"id": "6059",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "6060",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "6061",
"icon": "INV_Holiday_Christmas_Present_01",
"side": "",
"obtainable": true
},
{
"id": "7852",
"icon": "inv_holiday_christmas_present_01",
"side": "",
"obtainable": true
},
{
"id": "2398",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "4400",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "5512",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "5863",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "6131",
"icon": "INV_Misc_CelebrationCake_01",
"side": "",
"obtainable": true
},
{
"id": "7853",
"icon": "inv_misc_celebrationcake_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "3636",
"icon": "INV_Misc_Gem_Stone_01",
"side": "",
"obtainable": true
},
{
"id": "3896",
"icon": "INV_Misc_QirajiCrystal_05",
"side": "",
"obtainable": true
},
{
"id": "5364",
"icon": "INV_Misc_Flower_02",
"side": "",
"obtainable": true
},
{
"id": "5365",
"icon": "INV_Mushroom_06",
"side": "",
"obtainable": true
},
{
"id": "1205",
"icon": "Spell_Arcane_TeleportShattrath",
"side": "",
"obtainable": true
},
{
"id": "871",
"icon": "INV_Helmet_66",
"side": "",
"obtainable": true
},
{
"id": "2336",
"icon": "Ability_Mage_BrainFreeze",
"side": "",
"obtainable": true
},
{
"id": "4496",
"icon": "Ability_Warrior_InnerRage",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Scenarios",
"cats": [
{
"name": "Scenarios",
"zones": [
{
"name": "",
"achs": [
{
"id": "7385",
"icon": "inv_misc_archaeology_vrykuldrinkinghorn",
"side": "",
"obtainable": true
},
{
"id": "6874",
"icon": "spell_mage_altertime",
"side": "A",
"obtainable": true
},
{
"id": "7509",
"icon": "spell_mage_altertime",
"side": "H",
"obtainable": true
},
{
"id": "6943",
"icon": "spell_misc_emotionsad",
"side": "",
"obtainable": true
}
]
},
{
"name": "Brewmoon Festival",
"achs": [
{
"id": "6923",
"icon": "inv_drink_05",
"side": "",
"obtainable": true
},
{
"id": "6930",
"icon": "inv_misc_food_68",
"side": "",
"obtainable": true
},
{
"id": "6931",
"icon": "inv_misc_bomb_05",
"side": "",
"obtainable": true
}
]
},
{
"name": "Unga Ingoo",
"achs": [
{
"id": "7231",
"icon": "inv_cask_02",
"side": "",
"obtainable": true
},
{
"id": "7232",
"icon": "achievement_brewery_2",
"side": "",
"obtainable": true
},
{
"id": "7248",
"icon": "ability_hunter_aspectofthemonkey",
"side": "",
"obtainable": true
},
{
"id": "7249",
"icon": "inv_misc_hook_01",
"side": "",
"obtainable": true
},
{
"id": "7239",
"icon": "inv_misc_food_41",
"side": "",
"obtainable": true
}
]
},
{
"name": "Brewing Storm",
"achs": [
{
"id": "7252",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
},
{
"id": "7257",
"icon": "ability_smash",
"side": "",
"obtainable": true
},
{
"id": "7258",
"icon": "pandarenracial_innerpeace",
"side": "",
"obtainable": true
},
{
"id": "7261",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "8310",
"icon": "ability_hunter_pet_devilsaur",
"side": "",
"obtainable": true
}
]
},
{
"name": "Greenstone Village",
"achs": [
{
"id": "7265",
"icon": "inv_misc_gem_stone_01",
"side": "",
"obtainable": true
},
{
"id": "7267",
"icon": "inv_cask_03",
"side": "",
"obtainable": true
},
{
"id": "7266",
"icon": "inv_drink_32_disgustingrotgut",
"side": "",
"obtainable": true
}
]
},
{
"name": "Arena of Annihilation",
"achs": [
{
"id": "7271",
"icon": "achievement_arena_3v3_1",
"side": "",
"obtainable": true
},
{
"id": "7272",
"icon": "ability_monk_summontigerstatue",
"side": "",
"obtainable": true
},
{
"id": "7273",
"icon": "inv_elemental_mote_fire01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Crypt of Forgotten Kings",
"achs": [
{
"id": "7522",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
},
{
"id": "7275",
"icon": "spell_nature_lightningoverload",
"side": "",
"obtainable": true
},
{
"id": "7276",
"icon": "ability_rogue_sprint",
"side": "",
"obtainable": true
},
{
"id": "8368",
"icon": "ability_creature_cursed_02",
"side": "",
"obtainable": true
},
{
"id": "8311",
"icon": "archaeology_5_0_keystone_mogu",
"side": "",
"obtainable": true
}
]
},
{
"name": "Dagger in the Dark",
"achs": [
{
"id": "8009",
"icon": "inv_knife_1h_cataclysm_c_03",
"side": "",
"obtainable": true
},
{
"id": "7984",
"icon": "spell_brokenheart",
"side": "",
"obtainable": true
},
{
"id": "7986",
"icon": "spell_nature_nullward",
"side": "",
"obtainable": true
},
{
"id": "7987",
"icon": "inv_egg_04",
"side": "",
"obtainable": true
}
]
},
{
"name": "A Little Patience",
"achs": [
{
"id": "7988",
"icon": "achievement_character_orc_male",
"side": "A",
"obtainable": true
},
{
"id": "7989",
"icon": "creatureportrait_bubble",
"side": "A",
"obtainable": true
},
{
"id": "7990",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "7991",
"icon": "inv_misc_enggizmos_rocketchicken",
"side": "A",
"obtainable": true
},
{
"id": "7992",
"icon": "achievement_character_nightelf_female",
"side": "A",
"obtainable": true
},
{
"id": "7993",
"icon": "achievement_guild_classypanda",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Assault on Zan'vess",
"achs": [
{
"id": "8016",
"icon": "achievement_raid_mantidraid03",
"side": "",
"obtainable": true
},
{
"id": "8017",
"icon": "spell_shadow_summonfelhunter",
"side": "",
"obtainable": true
}
]
},
{
"name": "Theramore's Fall",
"achs": [
{
"id": "7523",
"icon": "spell_arcane_teleporttheramore",
"side": "A",
"obtainable": true
},
{
"id": "7524",
"icon": "spell_arcane_teleporttheramore",
"side": "H",
"obtainable": true
},
{
"id": "7526",
"icon": "ability_shaman_stormstrike",
"side": "A",
"obtainable": true
},
{
"id": "7529",
"icon": "ability_shaman_stormstrike",
"side": "H",
"obtainable": true
},
{
"id": "7527",
"icon": "ability_vehicle_demolisherflamecatapult",
"side": "A",
"obtainable": true
},
{
"id": "7530",
"icon": "ability_vehicle_demolisherflamecatapult",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Lion's Landing",
"achs": [
{
"id": "8010",
"icon": "inv_misc_tournaments_tabard_human",
"side": "A",
"obtainable": true
},
{
"id": "8011",
"icon": "achievement_guild_level5",
"side": "A",
"obtainable": true
},
{
"id": "8012",
"icon": "inv_box_01",
"side": "A",
"obtainable": true
}
]
},
{
"name": "Domination Point",
"achs": [
{
"id": "8013",
"icon": "inv_misc_tournaments_tabard_orc",
"side": "H",
"obtainable": true
},
{
"id": "8014",
"icon": "achievement_guild_level5",
"side": "H",
"obtainable": true
},
{
"id": "8015",
"icon": "inv_box_01",
"side": "H",
"obtainable": true
}
]
},
{
"name": "Dark Heart of Pandaria",
"achs": [
{
"id": "8319",
"icon": "trade_archaeology_uldumcanopicjar",
"side": "",
"obtainable": true
},
{
"id": "8317",
"icon": "inv_heart_of_the_thunder-king_icon",
"side": "",
"obtainable": true
},
{
"id": "8318",
"icon": "inv_heart_of_the_thunder-king_icon",
"side": "",
"obtainable": true
}
]
},
{
"name": "Blood in the Snow",
"achs": [
{
"id": "8316",
"icon": "achievement_zone_dunmorogh",
"side": "",
"obtainable": true
},
{
"id": "8329",
"icon": "inv_misc_herb_04",
"side": "",
"obtainable": true
},
{
"id": "8330",
"icon": "spell_holy_flashheal",
"side": "",
"obtainable": true
},
{
"id": "8312",
"icon": "inv_shield_zandalari_c_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Secrets of Ragefire",
"achs": [
{
"id": "8327",
"icon": "racial_orc_berserkerstrength",
"side": "",
"obtainable": true
},
{
"id": "8294",
"icon": "racial_orc_berserkerstrength",
"side": "",
"obtainable": true
},
{
"id": "8295",
"icon": "achievement_pvp_h_11",
"side": "",
"obtainable": true
}
]
},
{
"name": "Battle on the High Seas",
"achs": [
{
"id": "8314",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "8315",
"icon": "ability_vehicle_siegeenginecannon",
"side": "H",
"obtainable": true
},
{
"id": "8364",
"icon": "ability_vehicle_siegeenginecannon",
"side": "A",
"obtainable": true
},
{
"id": "8366",
"icon": "ability_vehicle_siegeenginecannon",
"side": "H",
"obtainable": true
},
{
"id": "8347",
"icon": "ability_hunter_snipershot",
"side": "",
"obtainable": true
}
]
}
]
}
]
},
{
"name": "Pet Battles",
"cats": [
{
"name": "Pet Battles",
"zones": [
{
"name": "Quest",
"achs": [
{
"id": "7908",
"icon": "petjournalportrait",
"side": "",
"obtainable": true
},
{
"id": "7936",
"icon": "inv_pet_pandarenelemental",
"side": "",
"obtainable": true
},
{
"id": "8080",
"icon": "inv_misc_book_16",
"side": "",
"obtainable": true
}
]
},
{
"name": "Taming",
"achs": [
{
"id": "6601",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "7498",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "7499",
"icon": "inv_pet_achievement_defeatpettamer",
"side": "",
"obtainable": true
},
{
"id": "6602",
"icon": "achievement_zone_kalimdor_01",
"side": "H",
"obtainable": true
},
{
"id": "6603",
"icon": "achievement_zone_easternkingdoms_01",
"side": "A",
"obtainable": true
},
{
"id": "6604",
"icon": "achievement_zone_outland_01",
"side": "",
"obtainable": true
},
{
"id": "6605",
"icon": "achievement_zone_northrend_01",
"side": "",
"obtainable": true
},
{
"id": "7525",
"icon": "achievement_zone_cataclysm",
"side": "",
"obtainable": true
},
{
"id": "6606",
"icon": "inv_pet_achievement_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6607",
"icon": "inv_pet_achievement_defeatpettamer_all",
"side": "",
"obtainable": true
}
]
},
{
"name": "Points",
"achs": [
{
"id": "7482",
"icon": "inv_pet_achievement_earn100achieve",
"side": "",
"obtainable": true
},
{
"id": "7483",
"icon": "inv_pet_achievement_earn200achieve",
"side": "",
"obtainable": true
},
{
"id": "6600",
"icon": "inv_pet_achievement_earn300achieve",
"side": "",
"obtainable": true
},
{
"id": "7521",
"icon": "inv_pet_achievement_earn335achieve",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Collect",
"zones": [
{
"name": "Count",
"achs": [
{
"id": "6554",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6555",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6556",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "6557",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7436",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7462",
"icon": "inv_pet_achievement_catchrarepet",
"side": "",
"obtainable": true
},
{
"id": "7463",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7464",
"icon": "inv_pet_achievement_captureawildpet",
"side": "",
"obtainable": true
},
{
"id": "7465",
"icon": "inv_pet_achievement_catchuncommonpet",
"side": "",
"obtainable": true
},
{
"id": "1017",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "15",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "1248",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "1250",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "2516",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5876",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5877",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "5875",
"icon": "INV_Box_PetCarrier_01",
"side": "",
"obtainable": true
},
{
"id": "7500",
"icon": "inv_box_petcarrier_01",
"side": "",
"obtainable": true
},
{
"id": "7501",
"icon": "inv_box_petcarrier_01",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zones",
"achs": [
{
"id": "6612",
"icon": "inv_pet_achievement_defeatwildpettamers_kalimdor",
"side": "",
"obtainable": true
},
{
"id": "6585",
"icon": "inv_pet_achievement_collectallwild_kalimdor",
"side": "",
"obtainable": true
},
{
"id": "6586",
"icon": "inv_pet_achievement_collectallwild_easternkingdoms",
"side": "",
"obtainable": true
},
{
"id": "6613",
"icon": "inv_pet_achievement_defeatwildpettamers_easternkingdom",
"side": "",
"obtainable": true
},
{
"id": "6614",
"icon": "inv_pet_achievement_defeatwildpettamers_outland",
"side": "",
"obtainable": true
},
{
"id": "6587",
"icon": "inv_pet_achievement_collectallwild_outland",
"side": "",
"obtainable": true
},
{
"id": "6615",
"icon": "inv_pet_achievement_defeatwildpettamers_northrend",
"side": "",
"obtainable": true
},
{
"id": "6588",
"icon": "inv_pet_achievement_collectallwild_northrend",
"side": "",
"obtainable": true
},
{
"id": "6616",
"icon": "inv_pet_achievement_defeatwildpettamers_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6589",
"icon": "inv_pet_achievement_collectallwild_pandaria",
"side": "",
"obtainable": true
},
{
"id": "6611",
"icon": "inv_pet_achievement_extra03",
"side": "",
"obtainable": true
},
{
"id": "6590",
"icon": "inv_pet_achievement_collectallwild_cataclysm",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "6608",
"icon": "inv_pet_achievement_captureapetfromeachfamily",
"side": "",
"obtainable": true
},
{
"id": "6571",
"icon": "inv_pet_achievement_captureapetatlessthan5health",
"side": "",
"obtainable": true
},
{
"id": "7934",
"icon": "achievement_boss_ragnaros",
"side": "",
"obtainable": true
},
{
"id": "8293",
"icon": "achievement_boss_prince_malchezaar",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Battle",
"zones": [
{
"name": "Count",
"achs": [
{
"id": "6618",
"icon": "inv_pet_battlepettraining",
"side": "",
"obtainable": true
},
{
"id": "6619",
"icon": "inv_pet_battlepettraining",
"side": "",
"obtainable": true
},
{
"id": "6594",
"icon": "inv_pet_achievement_win10",
"side": "",
"obtainable": true
},
{
"id": "6593",
"icon": "inv_pet_achievement_win50",
"side": "",
"obtainable": true
},
{
"id": "6462",
"icon": "inv_pet_achievement_win250",
"side": "",
"obtainable": true
},
{
"id": "6591",
"icon": "inv_pet_achievement_win1000",
"side": "",
"obtainable": true
},
{
"id": "6592",
"icon": "inv_pet_achievement_win5000",
"side": "",
"obtainable": true
}
]
},
{
"name": "PvP",
"achs": [
{
"id": "6595",
"icon": "inv_pet_achievement_win10pvp",
"side": "",
"obtainable": true
},
{
"id": "6596",
"icon": "inv_pet_achievement_win50pvp",
"side": "",
"obtainable": true
},
{
"id": "6597",
"icon": "inv_pet_achievement_win250pvp",
"side": "",
"obtainable": true
},
{
"id": "6598",
"icon": "inv_pet_achievement_win1000pvp",
"side": "",
"obtainable": true
},
{
"id": "6599",
"icon": "inv_pet_achievement_win5000pvp",
"side": "",
"obtainable": true
},
{
"id": "6620",
"icon": "spell_misc_petheal",
"side": "",
"obtainable": true
},
{
"id": "8300",
"icon": "achievement_featsofstrength_gladiator_03",
"side": "",
"obtainable": true
},
{
"id": "8301",
"icon": "achievement_featsofstrength_gladiator_04",
"side": "",
"obtainable": true
},
{
"id": "8297",
"icon": "achievement_featsofstrength_gladiator_01",
"side": "",
"obtainable": true
},
{
"id": "8298",
"icon": "achievement_featsofstrength_gladiator_02",
"side": "",
"obtainable": true
}
]
},
{
"name": "Zones",
"achs": [
{
"id": "6584",
"icon": "inv_pet_achievement_winpetbattle_stormwind",
"side": "",
"obtainable": true
},
{
"id": "6621",
"icon": "inv_pet_achievement_winpetbattle_orgrimmar",
"side": "",
"obtainable": true
},
{
"id": "6622",
"icon": "inv_pet_achievement_winpetbattle_northrend",
"side": "",
"obtainable": true
},
{
"id": "6558",
"icon": "inv_pet_achievement_catch10petsindifferentzones",
"side": "",
"obtainable": true
},
{
"id": "6559",
"icon": "inv_pet_achievement_catch30petsindifferentzones",
"side": "",
"obtainable": true
},
{
"id": "6560",
"icon": "inv_pet_achievement_catch60petsindifferentzones",
"side": "",
"obtainable": true
}
]
},
{
"name": "Other",
"achs": [
{
"id": "6851",
"icon": "inv_pet_achievement_captureapetfromeachfamily_battle",
"side": "",
"obtainable": true
},
{
"id": "8348",
"icon": "inv_misc_pocketwatch_01",
"side": "",
"obtainable": true
}
]
}
]
},
{
"name": "Level",
"zones": [
{
"name": "Raise",
"achs": [
{
"id": "7433",
"icon": "inv_pet_achievement_raiseapetlevel_3",
"side": "",
"obtainable": true
},
{
"id": "6566",
"icon": "inv_pet_achievement_raiseapetlevel_5",
"side": "",
"obtainable": true
},
{
"id": "6567",
"icon": "inv_pet_achievement_raiseapetlevel_10",
"side": "",
"obtainable": true
},
{
"id": "6568",
"icon": "inv_pet_achievement_raiseapetlevel_15",
"side": "",
"obtainable": true
},
{
"id": "6569",
"icon": "inv_pet_achievement_raiseapetlevel_20",
"side": "",
"obtainable": true
},
{
"id": "6570",
"icon": "inv_pet_achievement_raiseapetlevel_25",
"side": "",
"obtainable": true
}
]
},
{
"name": "Count",
"achs": [
{
"id": "6579",
"icon": "inv_pet_achievement_raise15petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6580",
"icon": "inv_pet_achievement_raise30petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6583",
"icon": "inv_pet_achievement_raise75petstolevel25",
"side": "",
"obtainable": true
},
{
"id": "6578",
"icon": "inv_pet_achievement_raise15petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6581",
"icon": "inv_pet_achievement_raise30petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6582",
"icon": "inv_pet_achievement_raise75petstolevel10",
"side": "",
"obtainable": true
},
{
"id": "6609",
"icon": "inv_pet_achievement_extra01",
"side": "",
"obtainable": true
},
{
"id": "6610",
"icon": "inv_pet_achievement_extra02",
"side": "",
"obtainable": true
}
]
}
]
}
]
}
]
} | Exploration & Dungeons
| achievements.js | Exploration & Dungeons | <ide><path>chievements.js
<ide> "icon": "archaeology_5_0_thunderkinginsignia",
<ide> "side": "",
<ide> "obtainable": true
<add> },
<add> {
<add> "id": "8454",
<add> "icon": "inv_axe_60",
<add> "side": "",
<add> "obtainable": true
<ide> }
<ide> ]
<ide> },
<ide> ]
<ide> },
<ide> {
<add> "name": "Siege of Orgrimmar",
<add> "achs": [
<add> {
<add> "id": "8458",
<add> "icon": "achievement_raid_soo_ruined_vale",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8459",
<add> "icon": "achievement_raid_soo_orgrimmar_outdoors",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8461",
<add> "icon": "achievement_raid_soo_garrosh_compound_half1",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8462",
<add> "icon": "achievement_raid_soo_garrosh_compound_half2",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8536",
<add> "icon": "spell_frost_summonwaterelemental_2",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8528",
<add> "icon": "ability_fixated_state_red",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8532",
<add> "icon": "spell_holy_surgeoflight",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8521",
<add> "icon": "sha_ability_rogue_bloodyeye",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8530",
<add> "icon": "achievement_bg_3flagcap_nodeaths",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8520",
<add> "icon": "inv_misc_enggizmos_38",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8453",
<add> "icon": "ability_paladin_blessedhands",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8448",
<add> "icon": "achievement_character_tauren_male",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8538",
<add> "icon": "sha_spell_warlock_demonsoul",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8529",
<add> "icon": "inv_crate_04",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8527",
<add> "icon": "inv_misc_shell_04",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8543",
<add> "icon": "ability_siege_engineer_sockwave_missile",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8531",
<add> "icon": "achievement_boss_klaxxi_paragons",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8537",
<add> "icon": "ability_garrosh_siege_engine",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8679",
<add> "icon": "ability_garrosh_hellscreams_warsong",
<add> "side": "A",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8680",
<add> "icon": "ability_garrosh_hellscreams_warsong",
<add> "side": "H",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8463",
<add> "icon": "achievement_boss_immerseus",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8465",
<add> "icon": "achievement_boss_golden_lotus_council",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8466",
<add> "icon": "achievement_boss_norushen",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8467",
<add> "icon": "sha_inv_misc_slime_01",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8468",
<add> "icon": "achievement_boss_galakras",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8469",
<add> "icon": "achievement_boss_ironjuggernaut",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8470",
<add> "icon": "achievement_boss_korkrondarkshaman",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8471",
<add> "icon": "achievement_boss_general_nazgrim",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8472",
<add> "icon": "achievement_boss_malkorok",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8478",
<add> "icon": "achievement_boss_spoils_of_pandaria",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8479",
<add> "icon": "achievement_boss_thokthebloodthirsty",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8480",
<add> "icon": "achievement_boss_siegecrafter_blackfuse",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8481",
<add> "icon": "achievement_boss_klaxxi_paragons",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8482",
<add> "icon": "achievement_boss_garrosh",
<add> "side": "",
<add> "obtainable": true
<add> }
<add> ]
<add> },
<add> {
<add> "name": "Timeless Isle",
<add> "achs": [
<add> {
<add> "id": "8535",
<add> "icon": "inv_pa_celestialmallet",
<add> "side": "",
<add> "obtainable": true
<add> }
<add> ]
<add> },
<add> {
<ide> "name": "World",
<ide> "achs": [
<ide> {
<ide> {
<ide> "id": "8028",
<ide> "icon": "spell_holy_lightsgrace",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8533",
<add> "icon": "inv_axe_1h_firelandsraid_d_02",
<ide> "side": "",
<ide> "obtainable": true
<ide> }
<ide> "obtainable": true
<ide> }
<ide> ]
<add> },
<add> {
<add> "name": "Timeless Isle",
<add> "achs": [
<add> {
<add> "id": "8726",
<add> "icon": "trade_archaeology_chestoftinyglassanimals",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8725",
<add> "icon": "inv_misc_coinbag_special",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8728",
<add> "icon": "inv_misc_bag_16",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8712",
<add> "icon": "ability_monk_touchofkarma",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8723",
<add> "icon": "inv_staff_2h_pandarenmonk_c_01",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8724",
<add> "icon": "ability_monk_tigerslust",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8730",
<add> "icon": "inv_misc_map09",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8714",
<add> "icon": "ability_monk_touchofdeath",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8784",
<add> "icon": "inv_staff_2h_pandarenmonk_c_01",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8722",
<add> "icon": "monk_ability_cherrymanatea",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8729",
<add> "icon": "inv_misc_coin_01",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8727",
<add> "icon": "inv_helmet_66",
<add> "side": "",
<add> "obtainable": true
<add> },
<add> {
<add> "id": "8743",
<add> "icon": "inv_misc_bone_02",
<add> "side": "",
<add> "obtainable": true
<add> }
<add> ]
<ide> }
<ide> ]
<ide> }, |
|
Java | apache-2.0 | 3226823708070a3a78b6bc6eb800539f5da5c499 | 0 | semonte/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,allotria/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,amith01994/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,slisson/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,samthor/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,retomerz/intellij-community,xfournet/intellij-community,dslomov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,slisson/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,semonte/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,clumsy/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,fitermay/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,samthor/intellij-community,da1z/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,blademainer/intellij-community,jagguli/intellij-community,caot/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,signed/intellij-community,hurricup/intellij-community,caot/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,fitermay/intellij-community,robovm/robovm-studio,caot/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,jagguli/intellij-community,caot/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ibinti/intellij-community,adedayo/intellij-community,robovm/robovm-studio,hurricup/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,fnouama/intellij-community,allotria/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,petteyg/intellij-community,kool79/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,holmes/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,signed/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,kool79/intellij-community,caot/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ibinti/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,supersven/intellij-community,amith01994/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fitermay/intellij-community,hurricup/intellij-community,semonte/intellij-community,adedayo/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,signed/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,samthor/intellij-community,clumsy/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,diorcety/intellij-community,samthor/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,slisson/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,semonte/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,kool79/intellij-community,asedunov/intellij-community,signed/intellij-community,izonder/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,retomerz/intellij-community,fitermay/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,signed/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,samthor/intellij-community,Lekanich/intellij-community,caot/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,apixandru/intellij-community,retomerz/intellij-community,samthor/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,ryano144/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,asedunov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,semonte/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ryano144/intellij-community,holmes/intellij-community,xfournet/intellij-community,da1z/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,semonte/intellij-community,kdwink/intellij-community,signed/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,caot/intellij-community,vladmm/intellij-community,allotria/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,fnouama/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ryano144/intellij-community,samthor/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,signed/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,FHannes/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,petteyg/intellij-community,amith01994/intellij-community,da1z/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,caot/intellij-community,holmes/intellij-community,signed/intellij-community,signed/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,dslomov/intellij-community,apixandru/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,signed/intellij-community,asedunov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,da1z/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,supersven/intellij-community,diorcety/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,da1z/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,da1z/intellij-community,blademainer/intellij-community,petteyg/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,kool79/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,asedunov/intellij-community,slisson/intellij-community,samthor/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,xfournet/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,hurricup/intellij-community,fnouama/intellij-community,signed/intellij-community,izonder/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,caot/intellij-community,slisson/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,semonte/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,samthor/intellij-community,kdwink/intellij-community,asedunov/intellij-community,izonder/intellij-community,vladmm/intellij-community,izonder/intellij-community,slisson/intellij-community,mglukhikh/intellij-community | /*
* Copyright 2000-2009 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.fileEditor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
public abstract class FileEditorManager {
public static final Key<Boolean> USE_CURRENT_WINDOW = Key.create("OpenFile.searchForOpen");
public static FileEditorManager getInstance(Project project) {
return project.getComponent(FileEditorManager.class);
}
/**
* @param file file to open. Parameter cannot be null. File should be valid.
*
* @return array of opened editors
*/
@NotNull
public abstract FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor);
/**
* Opens a file
*
*
* @param file file to open
* @param focusEditor <code>true</code> if need to focus
* @return array of opened editors
*/
@NotNull
public FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor, boolean searchForOpen) {
throw new UnsupportedOperationException("Not implemented");
}
/**
* Closes all editors opened for the file.
*
* @param file file to be closed. Cannot be null.
*/
public abstract void closeFile(@NotNull VirtualFile file);
/**
* Works as {@link #openFile(VirtualFile, boolean)} but forces opening of text editor.
* This method ignores {@link FileEditorPolicy#HIDE_DEFAULT_EDITOR} policy.
*
* @return opened text editor. The method returns <code>null</code> in case if text editor wasn't opened.
*/
@Nullable
public abstract Editor openTextEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor);
/**
* @return currently selected text editor. The method returns <code>null</code> in case
* there is no selected editor at all or selected editor is not a text one.
*/
@Nullable
public abstract Editor getSelectedTextEditor();
/**
* @return <code>true</code> if <code>file</code> is opened, <code>false</code> otherwise
*/
public abstract boolean isFileOpen(@NotNull VirtualFile file);
/**
* @return all opened files. Order of files in the array corresponds to the order of editor tabs.
*/
@NotNull
public abstract VirtualFile[] getOpenFiles();
/**
* @return files currently selected. The method returns empty array if there are no selected files.
* If more than one file is selected (split), the file with most recent focused editor is returned first.
*/
@NotNull
public abstract VirtualFile[] getSelectedFiles();
/**
* @return editors currently selected. The method returns empty array if no editors are open.
*/
@NotNull
public abstract FileEditor[] getSelectedEditors();
/**
* @param file cannot be null
*
* @return editor which is currently selected in the currently selected file.
* The method returns <code>null</code> if <code>file</code> is not opened.
*/
@Nullable
public abstract FileEditor getSelectedEditor(@NotNull VirtualFile file);
/**
* @param file cannot be null
*
* @return current editors for the specified <code>file</code>
*/
@NotNull
public abstract FileEditor[] getEditors(@NotNull VirtualFile file);
/**
* @param file cannot be null
*
* @return all editors for the specified <code>file</code>
*/
@NotNull
public abstract FileEditor[] getAllEditors(@NotNull VirtualFile file);
/**
* @return all open editors
*/
@NotNull
public abstract FileEditor[] getAllEditors();
/**
* @deprecated use addTopComponent
*/
public abstract void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent);
/**
* @deprecated use removeTopComponent
*/
public abstract void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent);
public abstract void addTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void removeTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void addBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void removeBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
/**
* Adds specified <code>listener</code>
* @param listener listener to be added
* @deprecated Use MessageBus instead: see {@link FileEditorManagerListener#FILE_EDITOR_MANAGER}
*/
public abstract void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener);
/**
* @deprecated Use {@link FileEditorManagerListener#FILE_EDITOR_MANAGER} instead
*/
public abstract void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener, @NotNull Disposable parentDisposable);
/**
* Removes specified <code>listener</code>
*
* @param listener listener to be removed
* @deprecated Use {@link FileEditorManagerListener#FILE_EDITOR_MANAGER} instead
*/
public abstract void removeFileEditorManagerListener(@NotNull FileEditorManagerListener listener);
@NotNull
public abstract List<FileEditor> openEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor);
/**
* Returns the project with which the file editor manager is associated.
*
* @return the project instance.
* @since 5.0.1
*/
@NotNull
public abstract Project getProject();
public abstract void registerExtraEditorDataProvider(@NotNull EditorDataProvider provider, Disposable parentDisposable);
/**
* Selects a specified file editor tab for the specified editor.
* @param file a file to switch the file editor tab for. The function does nothing if the file is not currently open in the editor.
* @param fileEditorProviderId the ID of the file editor to open; matches the return value of
* {@link com.intellij.openapi.fileEditor.FileEditorProvider#getEditorTypeId()}
*/
public abstract void setSelectedEditor(@NotNull VirtualFile file, String fileEditorProviderId);
}
| platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java | /*
* Copyright 2000-2009 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.fileEditor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.List;
public abstract class FileEditorManager {
public static final Key<Boolean> USE_CURRENT_WINDOW = Key.create("OpenFile.searchForOpen");
public static FileEditorManager getInstance(Project project) {
return project.getComponent(FileEditorManager.class);
}
/**
* @param file file to open. Parameter cannot be null. File should be valid.
*
* @return array of opened editors
*/
@NotNull
public abstract FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor);
/**
* Opens a file
*
*
* @param file file to open
* @param focusEditor <code>true</code> if need to focus
* @return array of opened editors
*/
@NotNull
public FileEditor[] openFile(@NotNull VirtualFile file, boolean focusEditor, boolean searchForOpen) {
throw new UnsupportedOperationException("Not implemented");
}
/**
* Closes all editors opened for the file.
*
* @param file file to be closed. Cannot be null.
*/
public abstract void closeFile(@NotNull VirtualFile file);
/**
* Works as {@link #openFile(VirtualFile, boolean)} but forces opening of text editor.
* This method ignores {@link FileEditorPolicy#HIDE_DEFAULT_EDITOR} policy.
*
* @return opened text editor. The method returns <code>null</code> in case if text editor wasn't opened.
*/
@Nullable
public abstract Editor openTextEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor);
/**
* @return currently selected text editor. The method returns <code>null</code> in case
* there is no selected editor at all or selected editor is not a text one.
*/
@Nullable
public abstract Editor getSelectedTextEditor();
/**
* @return <code>true</code> if <code>file</code> is opened, <code>false</code> otherwise
*/
public abstract boolean isFileOpen(@NotNull VirtualFile file);
/**
* @return all opened files. Order of files in the array corresponds to the order of editor tabs.
*/
@NotNull
public abstract VirtualFile[] getOpenFiles();
/**
* @return files currently selected. The method returns empty array if there are no selected files.
* If more than one file is selected (split), the file with most recent focused editor is returned first.
*/
@NotNull
public abstract VirtualFile[] getSelectedFiles();
/**
* @return editors currently selected. The method returns empty array if no editors are open.
*/
@NotNull
public abstract FileEditor[] getSelectedEditors();
/**
* @param file cannot be null
*
* @return editor which is currently selected in the currently selected file.
* The method returns <code>null</code> if <code>file</code> is not opened.
*/
@Nullable
public abstract FileEditor getSelectedEditor(@NotNull VirtualFile file);
/**
* @param file cannot be null
*
* @return current editors for the specified <code>file</code>
*/
@NotNull
public abstract FileEditor[] getEditors(@NotNull VirtualFile file);
/**
* @param file cannot be null
*
* @return all editors for the specified <code>file</code>
*/
@NotNull
public abstract FileEditor[] getAllEditors(@NotNull VirtualFile file);
/**
* @return all open editors
*/
@NotNull
public abstract FileEditor[] getAllEditors();
/**
* @deprecated use addTopComponent
*/
public abstract void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent);
/**
* @deprecated use removeTopComponent
*/
public abstract void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent);
public abstract void addTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void removeTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void addBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
public abstract void removeBottomComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
/**
* Adds specified <code>listener</code>
* @param listener listener to be added
* @deprecated Use MessageBus instead: see {@link FileEditorManagerListener#FILE_EDITOR_MANAGER}
*/
public abstract void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener);
/**
* @deprecated Use {@link FileEditorManagerListener#FILE_EDITOR_MANAGER} instead
*/
public abstract void addFileEditorManagerListener(@NotNull FileEditorManagerListener listener, @NotNull Disposable parentDisposable);
/**
* Removes specified <code>listener</code>
*
* @param listener listener to be removed
* @deprecated Use {@link FileEditorManagerListener#FILE_EDITOR_MANAGER} instead
*/
public abstract void removeFileEditorManagerListener(@NotNull FileEditorManagerListener listener);
@NotNull
public abstract List<FileEditor> openEditor(@NotNull OpenFileDescriptor descriptor, boolean focusEditor);
/**
* Returns the project with which the file editor manager is associated.
*
* @return the project instance.
* @since 5.0.1
*/
@NotNull
public abstract Project getProject();
public abstract void registerExtraEditorDataProvider(@NotNull EditorDataProvider provider, Disposable parentDisposable);
/**
* Selects a specified file editor tab for the specified editor.
* @param file a file to switch the file editor tab for. The function does nothing if the file is not currently open in the editor.
* @param fileEditorProviderId the ID of the file editor to open; matches the return value of
* {@link com.intellij.openapi.fileEditor.FileEditorProvider#getEditorTypeId()}
*/
public abstract void setSelectedEditor(@NotNull VirtualFile file, String fileEditorProviderId);
}
| spelling
| platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java | spelling | <ide><path>latform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorManager.java
<ide> /**
<ide> * @deprecated use addTopComponent
<ide> */
<del> public abstract void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent);
<add> public abstract void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent);
<ide> /**
<ide> * @deprecated use removeTopComponent
<ide> */
<del> public abstract void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent);
<add> public abstract void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent);
<ide>
<ide> public abstract void addTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component);
<ide> public abstract void removeTopComponent(@NotNull final FileEditor editor, @NotNull final JComponent component); |
|
Java | apache-2.0 | error: pathspec 'src/test/java/net/openhft/chronicle/map/ListenersTest.java' did not match any file(s) known to git
| 788d8282b1a33ed80050ddecae9ae51af5903c06 | 1 | OpenHFT/Chronicle-Map | package net.openhft.chronicle.map;
import net.openhft.chronicle.hash.Value;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ListenersTest {
static class CountingEntryOperations<K, V> implements MapEntryOperations<K, V, Void> {
AtomicInteger removeCount = new AtomicInteger();
AtomicInteger insertCount = new AtomicInteger();
AtomicInteger replaceValueCount = new AtomicInteger();
@Override
public Void remove(@NotNull MapEntry<K, V> entry) {
removeCount.incrementAndGet();
return MapEntryOperations.super.remove(entry);
}
@Override
public Void replaceValue(@NotNull MapEntry<K, V> entry, Value<V, ?> newValue) {
replaceValueCount.incrementAndGet();
return MapEntryOperations.super.replaceValue(entry, newValue);
}
@Override
public Void insert(@NotNull MapAbsentEntry<K, V> absentEntry, Value<V, ?> value) {
insertCount.incrementAndGet();
return MapEntryOperations.super.insert(absentEntry, value);
}
}
@Test
public void testRemove() {
CountingEntryOperations<Integer, Integer> removeCounting =
new CountingEntryOperations<>();
ChronicleMap<Integer, Integer> map =
ChronicleMapBuilder.of(Integer.class, Integer.class)
.entries(100)
.entryOperations(removeCounting)
.create();
map.put(1, 1);
map.remove(1); // removeCount 1
map.put(1, 1);
assertFalse(map.remove(1, 2));
map.remove(1, 1); // removeCount 2
map.put(1, 1);
map.merge(1, 1, (v1, v2) -> null); // removeCount 3
map.put(1, 1);
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
it.next();
it.remove(); // removeCount 4
assertEquals(4, removeCounting.removeCount.get());
}
@Test
public void testPut() {
CountingEntryOperations<Integer, Integer> putCounting =
new CountingEntryOperations<>();
ChronicleMap<Integer, Integer> map =
ChronicleMapBuilder.of(Integer.class, Integer.class)
.entries(100)
.entryOperations(putCounting)
.create();
map.put(1, 1); // insert 1
map.put(1, 2); // replaceValue 1
map.compute(1, (k, v) -> 2); // replaceValue 2
map.entrySet().iterator().next().setValue(1); // replaceValue 3
map.compute(2, (k, v) -> 1); // insert 2
assertEquals(3, putCounting.replaceValueCount.get());
assertEquals(2, putCounting.insertCount.get());
}
}
| src/test/java/net/openhft/chronicle/map/ListenersTest.java | Add Listeners test
| src/test/java/net/openhft/chronicle/map/ListenersTest.java | Add Listeners test | <ide><path>rc/test/java/net/openhft/chronicle/map/ListenersTest.java
<add>package net.openhft.chronicle.map;
<add>
<add>import net.openhft.chronicle.hash.Value;
<add>import org.jetbrains.annotations.NotNull;
<add>import org.junit.Test;
<add>
<add>import java.util.Iterator;
<add>import java.util.Map;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>
<add>public class ListenersTest {
<add>
<add> static class CountingEntryOperations<K, V> implements MapEntryOperations<K, V, Void> {
<add> AtomicInteger removeCount = new AtomicInteger();
<add> AtomicInteger insertCount = new AtomicInteger();
<add> AtomicInteger replaceValueCount = new AtomicInteger();
<add> @Override
<add> public Void remove(@NotNull MapEntry<K, V> entry) {
<add> removeCount.incrementAndGet();
<add> return MapEntryOperations.super.remove(entry);
<add> }
<add> @Override
<add> public Void replaceValue(@NotNull MapEntry<K, V> entry, Value<V, ?> newValue) {
<add> replaceValueCount.incrementAndGet();
<add> return MapEntryOperations.super.replaceValue(entry, newValue);
<add> }
<add>
<add> @Override
<add> public Void insert(@NotNull MapAbsentEntry<K, V> absentEntry, Value<V, ?> value) {
<add> insertCount.incrementAndGet();
<add> return MapEntryOperations.super.insert(absentEntry, value);
<add> }
<add> }
<add>
<add> @Test
<add> public void testRemove() {
<add> CountingEntryOperations<Integer, Integer> removeCounting =
<add> new CountingEntryOperations<>();
<add> ChronicleMap<Integer, Integer> map =
<add> ChronicleMapBuilder.of(Integer.class, Integer.class)
<add> .entries(100)
<add> .entryOperations(removeCounting)
<add> .create();
<add>
<add> map.put(1, 1);
<add> map.remove(1); // removeCount 1
<add>
<add> map.put(1, 1);
<add> assertFalse(map.remove(1, 2));
<add> map.remove(1, 1); // removeCount 2
<add>
<add> map.put(1, 1);
<add> map.merge(1, 1, (v1, v2) -> null); // removeCount 3
<add>
<add> map.put(1, 1);
<add> Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
<add> it.next();
<add> it.remove(); // removeCount 4
<add>
<add> assertEquals(4, removeCounting.removeCount.get());
<add> }
<add>
<add> @Test
<add> public void testPut() {
<add> CountingEntryOperations<Integer, Integer> putCounting =
<add> new CountingEntryOperations<>();
<add> ChronicleMap<Integer, Integer> map =
<add> ChronicleMapBuilder.of(Integer.class, Integer.class)
<add> .entries(100)
<add> .entryOperations(putCounting)
<add> .create();
<add>
<add> map.put(1, 1); // insert 1
<add>
<add> map.put(1, 2); // replaceValue 1
<add> map.compute(1, (k, v) -> 2); // replaceValue 2
<add>
<add> map.entrySet().iterator().next().setValue(1); // replaceValue 3
<add>
<add> map.compute(2, (k, v) -> 1); // insert 2
<add>
<add> assertEquals(3, putCounting.replaceValueCount.get());
<add> assertEquals(2, putCounting.insertCount.get());
<add> }
<add>} |
|
JavaScript | mit | 200a3195fda28766cde37a6810e3428db5e6bcda | 0 | blockstack/opendig,blockstack/blockstack-cli,blockstack/blockstack-cli | import { exec } from 'child_process'
import test from 'tape'
import { transactions, config, network, hexStringToECPair, hash160 } from '../../../lib'
function pExec(cmd) {
return new Promise(
(resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err)
} else {
resolve(stdout, stderr)
}
})
})
}
function initializeBlockstackCore() {
return pExec('docker pull quay.io/blockstack/integrationtests:develop')
.then(() => {
console.log('Pulled latest docker image')
return pExec(`docker stop test-bsk-core ;
docker rm test-bsk-core ;
rm -rf /tmp/.blockstack_int_test`)
.catch(() => true)
})
.then(() => pExec('docker run --name test-bsk-core -dt -p 16268:16268 -p 18332:18332 ' +
'-e BLOCKSTACK_TEST_CLIENT_RPC_PORT=16268 ' +
'-e BLOCKSTACK_TEST_CLIENT_BIND=0.0.0.0 ' +
'-e BLOCKSTACK_TEST_BITCOIND_ALLOWIP=172.17.0.0/16 ' +
'quay.io/blockstack/integrationtests:develop ' +
'blockstack-test-scenario --interactive 2 ' +
'blockstack_integration_tests.scenarios.portal_test_env'))
.then(() => {
console.log('Started regtest container, waiting until initialized')
return pExec('docker logs -f test-bsk-core | grep -q \'Test finished\'')
})
}
function shutdownBlockstackCore() {
return pExec('docker stop test-bsk-core')
}
export function runIntegrationTests() {
test('registerName', (t) => {
t.plan(8)
config.network = network.defaults.LOCAL_REGTEST
const myNet = config.network
const nsPay = '6e50431b955fe73f079469b24f06480aee44e4519282686433195b3c4b5336ef01'
const nsReveal = 'c244642ce0b4eb68da8e098facfcad889e3063c36a68b7951fb4c085de49df1b'
const nsRevealAddress = hexStringToECPair(nsPay).getAddress()
const dest = '19238846ac60fa62f8f8bb8898b03df79bc6112600181f36061835ad8934086001'
const destAddress = hexStringToECPair(dest).getAddress()
const btcDest = '897f1b92041b798580f96b8be379053f6276f04eb7590a9042a62059d46d6fc301'
const btcDestAddress = hexStringToECPair(btcDest).getAddress()
const payer = 'bb68eda988e768132bc6c7ca73a87fb9b0918e9a38d3618b74099be25f7cab7d01'
const secondOwner = '54164693e3803223f7fa9a004997bfbf1475f5c44f65593fa45c6783086dafec01'
const transferDestination = hexStringToECPair(secondOwner).getAddress()
const renewalDestination = 'myPgwEX2ddQxPPqWBRkXNqL3TwuWbY29DJ'
const zfTest = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
const zfTest2 = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
const renewalZF = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`
const importZF = '$ORIGIN import.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
initializeBlockstackCore()
.then(() => {
console.log('Blockstack Core initialized.')
console.log('Preorder namespace "hello"')
return transactions.makeNamespacePreorder('hello', nsRevealAddress, nsPay)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_PREORDER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
const ns = transactions.BlockstackNamespace('test')
ns.setVersion(1)
ns.setLifetime(52595)
ns.setCoeff(4)
ns.setBase(4)
ns.setBuckets([6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
ns.setNonalphaDiscount(10)
ns.setNoVowelDiscount(10)
console.log('Reveal namespace "hello"')
return transactions.makeNamespaceReveal(ns, nsRevealAddress, nsPay)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_REVEAL broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
console.log('NAME_IMPORT import.hello')
const zfHash = hash160(Buffer.from(importZF)).toString()
return transactions.makeNameImport(
'import.hello', renewalDestination, zfHash, nsReveal)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAME_IMPORT broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(importZF))
.then(() => fetch(`${myNet.broadcastAPIUrl}/v1/names/import.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
`import.hello should be owned by ${renewalDestination}`)
t.equal(nameInfo.zonefile, importZF, 'zonefile should be properly set for import.hello')
})
.then(() => {
console.log('Launch namespace "hello"')
return transactions.makeNamespaceReady('hello', nsReveal)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_READY broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
console.log('Namespace initialized. Preordering aaron.hello')
return transactions.makePreorder('aaron.hello', destAddress, payer)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('PREORDER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => transactions.makeRegister('aaron.hello', destAddress, payer, zfTest))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('REGISTER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(zfTest))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(myNet.coerceAddress(nameInfo.address), destAddress,
`aaron.hello should be owned by ${destAddress}`)
t.equal(nameInfo.zonefile, zfTest, 'zonefile should be properly set')
})
.then(() => transactions.makeUpdate('aaron.hello', dest, payer, zfTest2))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('UPDATE broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(zfTest2))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(nameInfo.zonefile, zfTest2, 'zonefile should be updated')
})
.then(() => transactions.makeTransfer('aaron.hello', transferDestination, dest, payer))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('TRANSFER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(myNet.coerceAddress(nameInfo.address), transferDestination,
`aaron.hello should be owned by ${transferDestination}`)
})
.then(() => transactions.makeRenewal('aaron.hello', renewalDestination,
secondOwner, payer, renewalZF))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('RENEWAL broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(renewalZF))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
`aaron.hello should be owned by ${renewalDestination}`)
})
.then(() => transactions.makeRevoke('aaron.hello', secondOwner))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('REVOKE broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(nameInfo.status, 'revoked', 'Name should be revoked')
})
.then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('broadcasted SPEND, waiting 10 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.getUTXOs(btcDestAddress))
.then((utxos) => {
t.equal(utxos.length, 1, `Destination address ${btcDestAddress} should have 1 UTXO`)
const satoshis = utxos.reduce((agg, utxo) => agg + utxo.value, 0)
console.log(`${btcDestAddress} has ${satoshis} satoshis`)
})
.then(() => shutdownBlockstackCore())
})
}
| tests/operationsTests/src/operationsTests.js | import { exec } from 'child_process'
import test from 'tape'
import { transactions, config, network, hexStringToECPair } from '../../../lib'
function pExec(cmd) {
return new Promise(
(resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) {
reject(err)
} else {
resolve(stdout, stderr)
}
})
})
}
function initializeBlockstackCore() {
return pExec('docker pull quay.io/blockstack/integrationtests:develop')
.then(() => {
console.log('Pulled latest docker image')
return pExec(`docker stop test-bsk-core ;
docker rm test-bsk-core ;
rm -rf /tmp/.blockstack_int_test`)
.catch(() => true)
})
.then(() => pExec('docker run --name test-bsk-core -dt -p 16268:16268 -p 18332:18332 ' +
'-e BLOCKSTACK_TEST_CLIENT_RPC_PORT=16268 ' +
'-e BLOCKSTACK_TEST_CLIENT_BIND=0.0.0.0 ' +
'-e BLOCKSTACK_TEST_BITCOIND_ALLOWIP=172.17.0.0/16 ' +
'quay.io/blockstack/integrationtests:develop ' +
'blockstack-test-scenario --interactive 2 ' +
'blockstack_integration_tests.scenarios.portal_test_env'))
.then(() => {
console.log('Started regtest container, waiting until initialized')
return pExec('docker logs -f test-bsk-core | grep -q \'Test finished\'')
})
}
function shutdownBlockstackCore() {
return pExec('docker stop test-bsk-core')
}
export function runIntegrationTests() {
test('registerName', (t) => {
t.plan(7)
config.network = network.defaults.LOCAL_REGTEST
const myNet = config.network
const nsPay = '6e50431b955fe73f079469b24f06480aee44e4519282686433195b3c4b5336ef01'
const nsReveal = 'c244642ce0b4eb68da8e098facfcad889e3063c36a68b7951fb4c085de49df1b'
const nsRevealAddress = hexStringToECPair(nsPay).getAddress()
const dest = '19238846ac60fa62f8f8bb8898b03df79bc6112600181f36061835ad8934086001'
const destAddress = hexStringToECPair(dest).getAddress()
const btcDest = '897f1b92041b798580f96b8be379053f6276f04eb7590a9042a62059d46d6fc301'
const btcDestAddress = hexStringToECPair(btcDest).getAddress()
const payer = 'bb68eda988e768132bc6c7ca73a87fb9b0918e9a38d3618b74099be25f7cab7d01'
const secondOwner = '54164693e3803223f7fa9a004997bfbf1475f5c44f65593fa45c6783086dafec01'
const transferDestination = hexStringToECPair(secondOwner).getAddress()
const renewalDestination = 'myPgwEX2ddQxPPqWBRkXNqL3TwuWbY29DJ'
const zfTest = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
const zfTest2 = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
const renewalZF = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
`"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`
initializeBlockstackCore()
.then(() => {
console.log('Blockstack Core initialized.')
console.log('Preorder namespace "hello"')
return transactions.makeNamespacePreorder('hello', nsRevealAddress, nsPay)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_PREORDER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
const ns = transactions.BlockstackNamespace('test')
ns.setVersion(1)
ns.setLifetime(52595)
ns.setCoeff(4)
ns.setBase(4)
ns.setBuckets([6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
ns.setNonalphaDiscount(10)
ns.setNoVowelDiscount(10)
console.log('Reveal namespace "hello"')
return transactions.makeNamespaceReveal(ns, nsRevealAddress, nsPay)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_REVEAL broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
console.log('Launch namespace "hello"')
return transactions.makeNamespaceReady('hello', nsReveal)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('NAMESPACE_READY broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => {
console.log('Namespace initialized. Preordering aaron.hello')
return transactions.makePreorder('aaron.hello', destAddress, payer)
})
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('PREORDER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => transactions.makeRegister('aaron.hello', destAddress, payer, zfTest))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('REGISTER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(zfTest))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(myNet.coerceAddress(nameInfo.address), destAddress,
`aaron.hello should be owned by ${destAddress}`)
t.equal(nameInfo.zonefile, zfTest, 'zonefile should be properly set')
})
.then(() => transactions.makeUpdate('aaron.hello', dest, payer, zfTest2))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('UPDATE broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(zfTest2))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(nameInfo.zonefile, zfTest2, 'zonefile should be updated')
})
.then(() => transactions.makeTransfer('aaron.hello', transferDestination, dest, payer))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('TRANSFER broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(myNet.coerceAddress(nameInfo.address), transferDestination,
`aaron.hello should be owned by ${transferDestination}`)
})
.then(() => transactions.makeRenewal('aaron.hello', renewalDestination,
secondOwner, payer, renewalZF))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('RENEWAL broadcasted, waiting 30 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.broadcastZoneFile(renewalZF))
.then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
.then(resp => resp.json())
.then(nameInfo => {
t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
`aaron.hello should be owned by ${renewalDestination}`)
})
.then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
.then(rawtx => myNet.broadcastTransaction(rawtx))
.then(() => {
console.log('broadcasted SPEND, waiting 10 seconds.')
return new Promise((resolve) => setTimeout(resolve, 30000))
})
.then(() => myNet.getUTXOs(btcDestAddress))
.then((utxos) => {
t.equal(utxos.length, 1, `Destination address ${btcDestAddress} should have 1 UTXO`)
const satoshis = utxos.reduce((agg, utxo) => agg + utxo.value, 0)
console.log(`${btcDestAddress} has ${satoshis} satoshis`)
})
.then(() => shutdownBlockstackCore())
})
}
| expand integration test to include revoke, name_import, and announce
| tests/operationsTests/src/operationsTests.js | expand integration test to include revoke, name_import, and announce | <ide><path>ests/operationsTests/src/operationsTests.js
<ide> import { exec } from 'child_process'
<ide> import test from 'tape'
<ide>
<del>import { transactions, config, network, hexStringToECPair } from '../../../lib'
<add>import { transactions, config, network, hexStringToECPair, hash160 } from '../../../lib'
<ide>
<ide> function pExec(cmd) {
<ide> return new Promise(
<ide>
<ide> export function runIntegrationTests() {
<ide> test('registerName', (t) => {
<del> t.plan(7)
<add> t.plan(8)
<ide>
<ide> config.network = network.defaults.LOCAL_REGTEST
<ide> const myNet = config.network
<ide> `"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
<ide> const renewalZF = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
<ide> `"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`
<add> const importZF = '$ORIGIN import.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
<add> `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
<ide>
<ide> initializeBlockstackCore()
<ide> .then(() => {
<ide> return new Promise((resolve) => setTimeout(resolve, 30000))
<ide> })
<ide> .then(() => {
<add> console.log('NAME_IMPORT import.hello')
<add> const zfHash = hash160(Buffer.from(importZF)).toString()
<add> return transactions.makeNameImport(
<add> 'import.hello', renewalDestination, zfHash, nsReveal)
<add> })
<add> .then(rawtx => myNet.broadcastTransaction(rawtx))
<add> .then(() => {
<add> console.log('NAME_IMPORT broadcasted, waiting 30 seconds.')
<add> return new Promise((resolve) => setTimeout(resolve, 30000))
<add> })
<add> .then(() => myNet.broadcastZoneFile(importZF))
<add> .then(() => fetch(`${myNet.broadcastAPIUrl}/v1/names/import.hello`))
<add> .then(resp => resp.json())
<add> .then(nameInfo => {
<add> t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
<add> `import.hello should be owned by ${renewalDestination}`)
<add> t.equal(nameInfo.zonefile, importZF, 'zonefile should be properly set for import.hello')
<add> })
<add> .then(() => {
<ide> console.log('Launch namespace "hello"')
<ide> return transactions.makeNamespaceReady('hello', nsReveal)
<ide> })
<ide> t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
<ide> t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
<ide> `aaron.hello should be owned by ${renewalDestination}`)
<add> })
<add> .then(() => transactions.makeRevoke('aaron.hello', secondOwner))
<add> .then(rawtx => myNet.broadcastTransaction(rawtx))
<add> .then(() => {
<add> console.log('REVOKE broadcasted, waiting 30 seconds.')
<add> return new Promise((resolve) => setTimeout(resolve, 30000))
<add> })
<add> .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
<add> .then(resp => resp.json())
<add> .then(nameInfo => {
<add> t.equal(nameInfo.status, 'revoked', 'Name should be revoked')
<ide> })
<ide> .then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
<ide> .then(rawtx => myNet.broadcastTransaction(rawtx)) |
|
Java | mit | 48403143100da1dd2d1a32ffa5b618bb26288236 | 0 | jbosboom/streamjit,jbosboom/streamjit | package edu.mit.streamjit.util.json;
import static com.google.common.base.Preconditions.*;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.ServiceLoader;
import javax.json.Json;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonStructure;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
/**
*
* @author Jeffrey Bosboom <[email protected]>
* @since 3/25/2013
*/
public final class Jsonifiers {
private static final ServiceLoader<JsonifierFactory> FACTORY_LOADER = ServiceLoader.load(JsonifierFactory.class);
private Jsonifiers() {}
/**
* Serializes the given Object to JSON.
*
* This method returns JsonValue; to get a JSON string, call the returned
* value's toString() method.
* @param obj an object
* @return a JsonValue representing the serialized form of the object
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static JsonValue toJson(Object obj) {
if (obj == null)
return JsonValue.NULL;
//This is checked dynamically via obj.getClass(). Not sure what
//generics I need to make this work.
Jsonifier jsonifier = findJsonifierByClass(obj.getClass());
return jsonifier.toJson(obj);
}
/**
* Deserializes the given well-formed JSON string into an object of the given class. If
* the object is of a subtype of the given class, an instance of that
* subtype will be created, rather than an instance of the given class.
*
* Note that well-formed JSON strings are always arrays or objects at their
* top level; this method will not deserialize the number 3 to an Integer,
* for example.
* @param <T> the type of the given class
* @param str a well-formed JSON string
* @param klass the class of the value being deserialized (must not be null)
* @return a deserialized Java object
* @throws NullPointerException if either str or klass is null
* @throws JsonSerializationException if a deserialization error occurs
*/
public static <T> T fromJson(String str, Class<T> klass) {
checkNotNull(str);
checkNotNull(klass);
JsonStructure struct;
try {
struct = Json.createReader(new StringReader(str)).read();
} catch (JsonException ex) {
throw new JsonSerializationException(ex);
}
return fromJson(struct, klass);
}
/**
* Deserializes the given JSON value into an object of the given class. If
* the object is of a subtype of the given class, an instance of that
* subtype will be created, rather than an instance of the given class.
* @param <T> the type of the given class
* @param value the JSON value to deserialized (must not be null, but may
* be a JSON null (JsonValue.NULL) object)
* @param klass the class of the value being deserialized (must not be null)
* @return a deserialized Java object
* @throws NullPointerException if either value or klass is null
* @throws JsonSerializationException if a deserialization error occurs
*/
public static <T> T fromJson(JsonValue value, Class<T> klass) {
checkNotNull(value); //checks for Java null, not JSON null
checkNotNull(klass);
if (value.getValueType() == JsonValue.ValueType.NULL)
//Surprisingly, int.class.cast(null) does not throw, instead
//returning null, which is probably not what the caller expects
//(if the caller tries to unbox immediately, it'll receive a
//NullPointerException for the implicit call to intValue().) So we
//check explicitly.
if (klass.isPrimitive())
throw new JsonSerializationException("deserializing null as "+klass.getSimpleName());
else
return klass.cast(null);
Class<?> trueClass = klass;
if (value instanceof JsonObject)
trueClass = objectClass((JsonObject)value);
Jsonifier<?> jsonifier = findJsonifierByClass(trueClass);
Object obj = jsonifier.fromJson(value);
return klass.cast(obj);
}
/**
* Parses the given JSON string, then prettyprints it. This is a purely
* syntactic transformation; no serialization or deserialization is done.
* @param json a well-formed JSON string
* @return a pretty-printed JSON string
*/
public static String prettyprint(String json) {
return prettyprint(Json.createReader(new StringReader(json)).read());
}
/**
* Prettyprints the given JSON structure. (All well-formed JSON strings
* have an array or object at their top level.)
* @param value a JSON structure
* @return a pretty-printed JSON string
*/
public static String prettyprint(JsonStructure value) {
StringWriter string = new StringWriter();
JsonWriterFactory writerFactory = Json.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, null));
try (JsonWriter writer = writerFactory.createWriter(string)) {
writer.write(value);
}
return string.toString();
}
/**
* Extracts the class of a JSON object (the value of the "class" key), or
* throws JsonSerializationException if unsuccessful. Used during
* deserialization.
* @param obj a JSON object
* @return the class of the JSON object
* @throws JsonSerializationException if the "class" key is not present, or
* if the value is not a string or does not name a Java class
*/
private static Class<?> objectClass(JsonObject obj) {
if (!(obj.get("class") instanceof JsonString))
throw new JsonSerializationException("class not present or not a string", obj);
String className = obj.getString("class");
Class<?> klass;
try {
klass = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new JsonSerializationException("bad class: "+className, ex, obj);
}
return klass;
}
private static <T> Jsonifier<T> findJsonifierByClass(Class<T> klass) {
for (JsonifierFactory f : FACTORY_LOADER) {
Jsonifier<T> jsonifier = f.getJsonifier(klass);
if (jsonifier != null)
return jsonifier;
}
throw new JsonSerializationException("no Jsonifier for "+klass);
}
/**
* Checks if the given value is a JSON object representing a Java object of
* the given class. If it is, the JSON object is returned; if not, a
* JsonSerializationException is thrown.
*
* This method is provided for the benefit of Jsonifier implementations;
* users of the JSON library have no need to call this method.
*
* Jsonifiers can call this method to test if the object they are
* deserializing is an instance of the exact class they expect.
* @param value a JSON value
* @param klass a class
* @return the JSON object if it represents a Java object of the given class
* @throws JsonSerializationException if the JSON value is not a JSON object
* or represents a Java object of a different class
* @see #checkClassAssignable(javax.json.JsonValue, java.lang.Class)
*/
public static JsonObject checkClassEqual(JsonValue value, Class<?> klass) {
if (!(value instanceof JsonObject))
throw new JsonSerializationException("value not an object", value);
JsonObject obj = (JsonObject)value;
if (!objectClass(obj).equals(klass))
throw new JsonSerializationException("class not "+klass.getName(), value);
return obj;
}
/**
* Checks if the given value is a JSON object representing a Java object assignable to
* the given class. If it is, the JSON object is returned; if not, a
* JsonSerializationException is thrown.
*
* This method is provided for the benefit of Jsonifier implementations;
* users of the JSON library have no need to call this method.
*
* Jsonifiers can call this method to test if the object they are
* deserializing is an instance or subtype of the class they expect.
* @param value a JSON value
* @param klass a class
* @return the JSON object if it represents a Java object assignable to the given class
* @throws JsonSerializationException if the JSON value is not a JSON object
* or represents a Java object of a different class
* @see #checkClassEqual(javax.json.JsonValue, java.lang.Class)
*/
public static JsonObject checkClassAssignable(JsonValue value, Class<?> klass) {
if (!(value instanceof JsonObject))
throw new JsonSerializationException("value not an object", value);
JsonObject obj = (JsonObject)value;
if (!klass.isAssignableFrom(objectClass(obj)))
throw new JsonSerializationException("class not "+klass.getName(), value);
return obj;
}
public static boolean notHeapPolluted(Iterable<?> iterable, Class<?> klass) {
for (Object o : iterable)
if (!klass.isAssignableFrom(o.getClass()))
return false; //heap-polluted
return true;
}
public static boolean notHeapPolluted(Map<?, ?> map, Class<?> keyClass, Class<?> valueClass) {
return notHeapPolluted(map.keySet(), keyClass) && notHeapPolluted(map.values(), valueClass);
}
}
| src/edu/mit/streamjit/util/json/Jsonifiers.java | package edu.mit.streamjit.util.json;
import static com.google.common.base.Preconditions.*;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.ServiceLoader;
import javax.json.Json;
import javax.json.JsonException;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonStructure;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
/**
*
* @author Jeffrey Bosboom <[email protected]>
* @since 3/25/2013
*/
public final class Jsonifiers {
private static final ServiceLoader<JsonifierFactory> FACTORY_LOADER = ServiceLoader.load(JsonifierFactory.class);
private Jsonifiers() {}
/**
* Serializes the given Object to JSON.
*
* This method returns JsonValue; to get a JSON string, call the returned
* value's toString() method.
* @param obj an object
* @return a JsonValue representing the serialized form of the object
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static JsonValue toJson(Object obj) {
if (obj == null)
return JsonValue.NULL;
//This is checked dynamically via obj.getClass(). Not sure what
//generics I need to make this work.
Jsonifier jsonifier = findJsonifierByClass(obj.getClass());
return jsonifier.toJson(obj);
}
/**
* Deserializes the given well-formed JSON string into an object of the given class. If
* the object is of a subtype of the given class, an instance of that
* subtype will be created, rather than an instance of the given class.
*
* Note that well-formed JSON strings are always arrays or objects at their
* top level; this method will not deserialize the number 3 to an Integer,
* for example.
* @param <T> the type of the given class
* @param str a well-formed JSON string
* @param klass the class of the value being deserialized (must not be null)
* @return a deserialized Java object
* @throws NullPointerException if either str or klass is null
* @throws JsonSerializationException if a deserialization error occurs
*/
public static <T> T fromJson(String str, Class<T> klass) {
checkNotNull(str);
checkNotNull(klass);
JsonStructure struct;
try {
struct = Json.createReader(new StringReader(str)).read();
} catch (JsonException ex) {
throw new JsonSerializationException(ex);
}
return fromJson(struct, klass);
}
/**
* Deserializes the given JSON value into an object of the given class. If
* the object is of a subtype of the given class, an instance of that
* subtype will be created, rather than an instance of the given class.
* @param <T> the type of the given class
* @param value the JSON value to deserialized (must not be null, but may
* be a JSON null (JsonValue.NULL) object)
* @param klass the class of the value being deserialized (must not be null)
* @return a deserialized Java object
* @throws NullPointerException if either value or klass is null
* @throws JsonSerializationException if a deserialization error occurs
*/
public static <T> T fromJson(JsonValue value, Class<T> klass) {
checkNotNull(value); //checks for Java null, not JSON null
checkNotNull(klass);
if (value.getValueType() == JsonValue.ValueType.NULL)
//Surprisingly, int.class.cast(null) does not throw, instead
//returning null, which is probably not what the caller expects
//(if the caller tries to unbox immediately, it'll receive a
//NullPointerException for the implicit call to intValue().) So we
//check explicitly.
if (klass.isPrimitive())
throw new JsonSerializationException("deserializing null as "+klass.getSimpleName());
else
return klass.cast(null);
Class<?> trueClass = klass;
if (value instanceof JsonObject)
trueClass = objectClass((JsonObject)value);
Jsonifier<?> jsonifier = findJsonifierByClass(trueClass);
Object obj = jsonifier.fromJson(value);
return klass.cast(obj);
}
/**
* Parses the given JSON string, then prettyprints it. This is a purely
* syntactic transformation; no serialization or deserialization is done.
* @param json a well-formed JSON string
* @return a pretty-printed JSON string
*/
public static String prettyprint(String json) {
return prettyprint(Json.createReader(new StringReader(json)).read());
}
/**
* Prettyprints the given JSON structure. (All well-formed JSON strings
* have an array or object at their top level.)
* @param value a JSON structure
* @return a pretty-printed JSON string
*/
public static String prettyprint(JsonStructure value) {
StringWriter string = new StringWriter();
JsonWriterFactory writerFactory = Json.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, null));
try (JsonWriter writer = writerFactory.createWriter(string)) {
writer.write(value);
}
return string.toString();
}
/**
* Extracts the class of a JSON object (the value of the "class" key), or
* throws JsonSerializationException if unsuccessful. Used during
* deserialization.
* @param obj a JSON object
* @return the class of the JSON object
* @throws JsonSerializationException if the "class" key is not present, or
* if the value is not a string or does not name a Java class
*/
private static Class<?> objectClass(JsonObject obj) {
if (!(obj.get("class") instanceof JsonString))
throw new JsonSerializationException("class not present or not a string", obj);
String className = obj.getString("class");
Class<?> klass;
try {
klass = Class.forName(className);
} catch (ClassNotFoundException ex) {
throw new JsonSerializationException("bad class: "+className, ex, obj);
}
return klass;
}
private static <T> Jsonifier<T> findJsonifierByClass(Class<T> klass) {
for (JsonifierFactory f : FACTORY_LOADER) {
Jsonifier<T> jsonifier = f.getJsonifier(klass);
if (jsonifier != null)
return jsonifier;
}
throw new JsonSerializationException("no Jsonifier for "+klass);
}
public static JsonObject checkClassEqual(JsonValue value, Class<?> klass) {
if (!(value instanceof JsonObject))
throw new JsonSerializationException("value not an object", value);
JsonObject obj = (JsonObject)value;
if (!objectClass(obj).equals(klass))
throw new JsonSerializationException("class not "+klass.getName(), value);
return obj;
}
public static JsonObject checkClassAssignable(JsonValue value, Class<?> klass) {
if (!(value instanceof JsonObject))
throw new JsonSerializationException("value not an object", value);
JsonObject obj = (JsonObject)value;
if (!klass.isAssignableFrom(objectClass(obj)))
throw new JsonSerializationException("class not "+klass.getName(), value);
return obj;
}
public static boolean notHeapPolluted(Iterable<?> iterable, Class<?> klass) {
for (Object o : iterable)
if (!klass.isAssignableFrom(o.getClass()))
return false; //heap-polluted
return true;
}
public static boolean notHeapPolluted(Map<?, ?> map, Class<?> keyClass, Class<?> valueClass) {
return notHeapPolluted(map.keySet(), keyClass) && notHeapPolluted(map.values(), valueClass);
}
}
| More Jsonifiers comments
| src/edu/mit/streamjit/util/json/Jsonifiers.java | More Jsonifiers comments | <ide><path>rc/edu/mit/streamjit/util/json/Jsonifiers.java
<ide> throw new JsonSerializationException("no Jsonifier for "+klass);
<ide> }
<ide>
<add> /**
<add> * Checks if the given value is a JSON object representing a Java object of
<add> * the given class. If it is, the JSON object is returned; if not, a
<add> * JsonSerializationException is thrown.
<add> *
<add> * This method is provided for the benefit of Jsonifier implementations;
<add> * users of the JSON library have no need to call this method.
<add> *
<add> * Jsonifiers can call this method to test if the object they are
<add> * deserializing is an instance of the exact class they expect.
<add> * @param value a JSON value
<add> * @param klass a class
<add> * @return the JSON object if it represents a Java object of the given class
<add> * @throws JsonSerializationException if the JSON value is not a JSON object
<add> * or represents a Java object of a different class
<add> * @see #checkClassAssignable(javax.json.JsonValue, java.lang.Class)
<add> */
<ide> public static JsonObject checkClassEqual(JsonValue value, Class<?> klass) {
<ide> if (!(value instanceof JsonObject))
<ide> throw new JsonSerializationException("value not an object", value);
<ide> return obj;
<ide> }
<ide>
<add> /**
<add> * Checks if the given value is a JSON object representing a Java object assignable to
<add> * the given class. If it is, the JSON object is returned; if not, a
<add> * JsonSerializationException is thrown.
<add> *
<add> * This method is provided for the benefit of Jsonifier implementations;
<add> * users of the JSON library have no need to call this method.
<add> *
<add> * Jsonifiers can call this method to test if the object they are
<add> * deserializing is an instance or subtype of the class they expect.
<add> * @param value a JSON value
<add> * @param klass a class
<add> * @return the JSON object if it represents a Java object assignable to the given class
<add> * @throws JsonSerializationException if the JSON value is not a JSON object
<add> * or represents a Java object of a different class
<add> * @see #checkClassEqual(javax.json.JsonValue, java.lang.Class)
<add> */
<ide> public static JsonObject checkClassAssignable(JsonValue value, Class<?> klass) {
<ide> if (!(value instanceof JsonObject))
<ide> throw new JsonSerializationException("value not an object", value); |
|
Java | apache-2.0 | 3f9f5984a2bb65e8ecf0e970ec9fb58cd66c74b7 | 0 | apache/empire-db,apache/empire-db,apache/empire-db,apache/empire-db | /*
* 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.empire.db;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.expr.compare.DBCompareColExpr;
import org.apache.empire.db.expr.compare.DBCompareExpr;
import org.apache.empire.db.expr.join.DBColumnJoinExpr;
import org.apache.empire.db.expr.join.DBCompareJoinExpr;
import org.apache.empire.db.expr.join.DBCrossJoinExpr;
import org.apache.empire.db.expr.join.DBJoinExpr;
import org.apache.empire.db.expr.order.DBOrderByExpr;
import org.apache.empire.db.expr.set.DBSetExpr;
import org.apache.empire.dbms.DBSqlPhrase;
import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.ItemNotFoundException;
import org.apache.empire.exceptions.ObjectNotValidException;
import org.apache.empire.exceptions.UnspecifiedErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This abstract class handles the creation of the SQL-Commands.
* There are methods to create SQL-Commands, like update, insert,
* delete and select.
*/
public abstract class DBCommand extends DBCommandExpr
implements Cloneable
{
// *Deprecated* private static final long serialVersionUID = 1L;
// Logger
protected static final Logger log = LoggerFactory.getLogger(DBCommand.class);
// Distinct Select
protected boolean selectDistinct = false;
// Lists
protected List<DBColumnExpr> select = null;
protected List<DBSetExpr> set = null;
protected List<DBJoinExpr> joins = null;
protected List<DBCompareExpr> where = null;
protected List<DBCompareExpr> having = null;
protected List<DBColumnExpr> groupBy = null;
// Parameters for prepared Statements generation
protected boolean autoPrepareStmt = false;
protected List<DBCmdParam> cmdParams = null;
private int paramUsageCount = 0;
/**
* Constructs a new DBCommand object and set the specified DBDatabase object.
*
* @param db the current database object
*/
protected DBCommand(boolean autoPrepareStmt)
{
this.autoPrepareStmt = autoPrepareStmt;
}
/**
* Custom serialization for transient database.
*
private void writeObject(ObjectOutputStream strm) throws IOException
{ // Database
strm.writeObject(db.getIdentifier());
// write the rest
strm.defaultWriteObject();
}
private void readObject(ObjectInputStream strm) throws IOException, ClassNotFoundException
{
String dbid = String.valueOf(strm.readObject());
// find database
DBDatabase dbo = DBDatabase.findByIdentifier(dbid);
if (dbo==null)
throw new ItemNotFoundException(dbid);
// set final field
ClassUtils.setPrivateFieldValue(DBCommand.class, this, "db", dbo);
// read the rest
strm.defaultReadObject();
}
*/
/**
* internally used to reset the command param usage count.
* Note: Only one thread my generate an SQL statement
*/
protected void resetParamUsage()
{
paramUsageCount = 0;
if (cmdParams==null)
return;
// clear subquery params
for (int i=cmdParams.size()-1; i>=0 ;i--)
if (cmdParams.get(i).getCmd()!=this)
cmdParams.remove(i);
}
/**
* internally used to remove unused Command Params from list
* Note: Only one thread my generate an SQL statement
*/
protected void completeParamUsage()
{
if (cmdParams==null)
return;
// check whether all params have been used
if (paramUsageCount < cmdParams.size())
{ // Remove unused parameters
log.warn("DBCommand has {} unused Command params", cmdParams.size()-paramUsageCount);
for (int i=cmdParams.size()-1; i>=paramUsageCount; i--)
cmdParams.remove(i);
}
}
/**
* internally used to reorder the command params to match their order of occurance
*/
protected void notifyParamUsage(DBCmdParam param)
{
int index = cmdParams.indexOf(param);
if (index < paramUsageCount)
{ // Error: parameter probably used twice in statement!
throw new UnspecifiedErrorException("A parameter may only be used once in a command.");
}
if (index > paramUsageCount)
{ // Correct parameter order
cmdParams.remove(index);
cmdParams.add(paramUsageCount, param);
}
paramUsageCount++;
}
/**
* internally used to remove the command param used in a constraint
*/
private void removeCommandParam(DBCompareColExpr cmp)
{
if (cmdParams!=null && (cmp.getValue() instanceof DBCmdParam))
cmdParams.remove(cmp.getValue());
}
/**
* internally used to remove all command params used in a list of constraints
*/
private void removeAllCommandParams(List<DBCompareExpr> list)
{
if (cmdParams == null)
return;
for(DBCompareExpr cmp : list)
{ // Check whether it is a compare column expr.
if (!(cmp instanceof DBCompareColExpr))
continue;
// Check the value is a DBCommandParam
removeCommandParam((DBCompareColExpr)cmp);
}
}
/**
* Creates a clone of this class.
*/
@Override
public DBCommand clone()
{
try
{
DBCommand clone = (DBCommand)super.clone();
// Clone lists
if (select!=null)
clone.select = new ArrayList<DBColumnExpr>(select);
if (set!=null)
clone.set = new ArrayList<DBSetExpr>(set);
if (joins!=null)
clone.joins = new ArrayList<DBJoinExpr>(joins);
if (where!=null)
clone.where = new ArrayList<DBCompareExpr>(where);
if (groupBy!=null)
clone.groupBy = new ArrayList<DBColumnExpr>(groupBy);
if (having!=null)
clone.having = new ArrayList<DBCompareExpr>(having);
if (cmdParams!=null && !cmdParams.isEmpty())
{ // clone params
clone.paramUsageCount = 0;
clone.cmdParams = new ArrayList<DBCmdParam>(cmdParams.size());
// clone set
for (int i=0; (clone.set!=null && i<clone.set.size()); i++)
clone.set.set(i, clone.set.get(i).copy(clone));
// clone where and having
for (int i=0; (clone.where!=null && i<clone.where.size()); i++)
clone.where.set(i, clone.where.get(i).copy(clone));
for (int i=0; (clone.having!=null && i<clone.having.size()); i++)
clone.having.set(i, clone.having.get(i).copy(clone));
}
// done
return clone;
} catch (CloneNotSupportedException e) {
log.error("Cloning DBCommand object failed!", e);
throw new InternalException(e);
}
}
@SuppressWarnings("unchecked")
@Override
public final DBDatabase getDatabase()
{
if (hasSelectExpr())
return this.select.get(0).getDatabase();
if (hasSetExpr())
return this.set.get(0).getDatabase();
// two more chances (should we?)
if (where!=null && !where.isEmpty())
return where.get(0).getDatabase();
if (orderBy!=null && !orderBy.isEmpty())
return orderBy.get(0).getDatabase();
// not valid yet
throw new ObjectNotValidException(this);
}
/**
* Returns true if the this command has either Select or Set expressions
*/
@Override
public boolean isValid()
{
return hasSelectExpr() || hasSetExpr();
}
/**
* Sets whether or not the select statement should contain
* the distinct directive .
* @return itself (this)
*/
public DBCommand selectDistinct()
{
this.selectDistinct = true;
return this;
}
/**
* Returns whether or not the select statement will be distinct or not.
*
* @return true if the select will contain the distinct directive or false otherwise.
*/
public boolean isSelectDistinct()
{
return selectDistinct;
}
/**
* returns whether or not the command has any select expression
* @return true if the command has any select expression of false otherwise
*/
@Override
public boolean hasSelectExpr()
{
return (select!=null && !select.isEmpty());
}
/**
* returns whether or not the command has a specific select expression
* @return true if the command contains the given select expression of false otherwise
*/
@Override
public boolean hasSelectExpr(DBColumnExpr expr)
{
return (select!=null ? (select.indexOf(expr)>=0) : false);
}
/**
* Adds a DBColumnExpr object to the Select collection
*
* @param expr the DBColumnExpr object
* @return itself (this)
*/
public DBCommand select(DBColumnExpr expr)
{ // Select this column
if (select == null)
select = new ArrayList<DBColumnExpr>();
if (expr != null && select.contains(expr) == false)
select.add(expr);
return this;
}
/**
* Adds a list of columns to the select phrase of an sql statement.
*
* @param exprs an vararg of DBColumnExpr's to select
* @return itself (this)
*/
public final DBCommand select(DBColumnExpr... exprs)
{
for (DBColumnExpr expr : exprs)
{
select(expr);
}
return this;
}
/**
* Adds a collection of columns to the select phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand select(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr expr : columns)
{
select(expr);
}
return this;
}
/**
* Adds a list of columns with their qualified name to the select phrase of an sql statement.
*
* @param exprs one or more columns to select
* @return itself (this)
*/
public DBCommand selectQualified(DBColumnExpr... columns)
{
for (DBColumnExpr col : columns)
{
select(col.qualified());
}
return this;
}
/**
* Adds a collection of columns to the select phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand selectQualified(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr col : columns)
{
select(col.qualified());
}
return this;
}
/**
* Returns an array of all select expressions
*
* @return an array of all DBColumnExpr objects or <code>null</code> if there is nothing to select
*/
@Override
public DBColumnExpr[] getSelectExprList()
{
int count = (select != null) ? select.size() : 0;
if (count < 1)
return null;
// The List
DBColumnExpr[] exprList = new DBColumnExpr[count];
for (int i = 0; i < count; i++)
exprList[i] = select.get(i);
// The expression List
return exprList;
}
/**
* Returns all select expressions as unmodifiable list
* @return the list of DBColumnExpr used for select
*/
@Override
public List<DBColumnExpr> getSelectExpressions()
{
return (this.select!=null ? Collections.unmodifiableList(this.select) : null);
}
/**
* replaces a select expression with another or removes a select expression
* In order to remove the expression, set the replWith parameter to null
* If the replace expression is not found, an ItemNotFoundException is thrown
* @param replExpr
* @param replWith
*/
public void replaceSelect(DBColumnExpr replExpr, DBColumnExpr replWith)
{
int idx = (select != null ? select.indexOf(replExpr) : -1);
if (idx < 0)
throw new ItemNotFoundException(replExpr);
// replace now
if (replWith!=null)
select.set(idx, replWith);
else
select.remove(idx);
}
/**
* removes one or more expressions from the Select expression list
* @param exprs the expression(s) to be removed
*/
public void removeSelect(DBColumnExpr... exprs)
{
if (select==null)
return;
for (int i=0; i<exprs.length; i++)
{
int idx = select.indexOf(exprs[i]);
if (idx>=0)
select.remove(idx);
}
}
/**
* Checks whether or not there are any aggregate functions in the Select
* @return true if at least on of the selected expressions is an aggregate
*/
public boolean hasAggegation()
{
for (DBColumnExpr expr : this.select)
{
if (expr.isAggregate())
return true;
}
return false;
}
/**
* Adds a single set expressions to this command
* Use column.to(...) to create a set expression
*
* @param expr the DBSetExpr object(s)
* @return itself (this)
*/
public DBCommand set(DBSetExpr expr)
{
// add to list
if (set == null)
set = new ArrayList<DBSetExpr>();
for (int i = 0; i < set.size(); i++)
{
DBSetExpr chk = set.get(i);
if (chk.column.equals(expr.column))
{ // Overwrite existing value
if (useCmdParam(expr.column, expr.value))
{ // Use parameter value
if (chk.value instanceof DBCmdParam)
{ // reuse the old paramter
((DBCmdParam)chk.value).setValue(expr.value);
expr.value = chk.value;
chk.value = null;
}
else
{ // create new one
expr.value = addParam(expr.column.getDataType(), expr.value);
}
}
else
{ // remove from parameter list (if necessary)
if (cmdParams!=null && (chk.value instanceof DBCmdParam))
cmdParams.remove(chk.value);
}
// replace now
set.set(i, expr);
return this;
}
}
// Replace with parameter
if (useCmdParam(expr.column, expr.value))
expr.value = addParam(expr.column.getDataType(), expr.value);
// new Value!
set.add(expr);
return this;
}
/**
* Adds a list of set expressions to this command
* Use column.to(...) to create a set expression
*
* @param expr the DBSetExpr object(s)
* @return itself (this)
*/
public final DBCommand set(DBSetExpr... exprs)
{
for (int i=0; i<exprs.length; i++)
set(exprs[i]);
return this;
}
/**
* Returns whether or not the command has group by set
*/
public boolean hasSetExpr()
{
return (this.set!=null ? !this.set.isEmpty() : false);
}
/**
* Checks whether a column is in the list of set expressions
* @param column
* @return <code>true</code> if there is a set expression
*/
protected boolean hasSetExprOn(DBColumn column)
{
if (set==null)
return false;
Iterator<DBSetExpr> i = set.iterator();
while (i.hasNext())
{
DBSetExpr chk = i.next();
if (chk.column.equals(column))
return true;
}
return false;
}
/**
* Returns all set expressions as unmodifiable list
* @return the list of DBSetExpr used for set
*/
public List<DBSetExpr> getSetExpressions()
{
return (this.set!=null ? Collections.unmodifiableList(this.set) : null);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The command parameter returned may be used to alter the value.
*
* @param type the data type of the parameter
* @param value the initial parameter value
*
* @return the command parameter object
*/
public DBCmdParam addParam(DataType type, Object value)
{
if (cmdParams==null)
cmdParams= new ArrayList<DBCmdParam>();
// Create and add the parameter to the parameter list
DBCmdParam param = new DBCmdParam(this, type, value);
cmdParams.add(param);
// done
return param;
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @param colExpr the column expression for which to create the parameter
* @param value the initial parameter value
*
* @return the command parameter object
*/
public final DBCmdParam addParam(DBColumnExpr colExpr, Object value)
{
return addParam(colExpr.getDataType(), value);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @return the command parameter object
*/
public final DBCmdParam addParam(Object value)
{
return addParam(DataType.UNKNOWN, value);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @return the command parameter object
*/
public final DBCmdParam addParam()
{
return addParam(DataType.UNKNOWN, null);
}
/**
* Adds a join to the list of join expressions.
*
* @param join the join expression
* @return itself (this)
*/
public DBCommand join(DBJoinExpr join)
{
// check tables
if (join.getLeftTable().equals(join.getRightTable()))
throw new InvalidArgumentException("left|right", join.getLeftTable());
// create list
if (joins == null)
joins = new ArrayList<DBJoinExpr>();
// Create a new join
for (int i = 0; i < joins.size(); i++)
{ // Check whether join exists
DBJoinExpr item = joins.get(i);
if (item.equals(join))
return this;
}
joins.add(join);
return this;
}
/**
* Adds an inner join based on two columns to the list of join expressions.
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand join(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.INNER, addlConstraints);
}
/**
* Adds a left join based on two columns to the list of join expressions.
* Added for convenience
* Same as join(left, right, DBJoinType.LEFT);
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand joinLeft(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.LEFT, addlConstraints);
}
/**
* Adds a right join based on two columns to the list of join expressions.
* Added for convenience
* Same as join(left, right, DBJoinType.RIGHT);
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand joinRight(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.RIGHT, addlConstraints);
}
/**
* Adds a join based on two columns to the list of join expressions.
*
* Migration hint from 2.x -> replace ").where(" with just ","
*
* @param left the left join value
* @param right the right join
* @param joinType type of join ({@link DBJoinType#INNER}, {@link DBJoinType#LEFT}, {@link DBJoinType#RIGHT})
* @return itself (this)
*/
public final DBCommand join(DBColumnExpr left, DBColumn right, DBJoinType joinType, DBCompareExpr... addlConstraints)
{
if (left==null || right==null || left.getSourceColumn()==null)
throw new InvalidArgumentException("left|right", left);
if (left.getSourceColumn().getRowSet()==right.getRowSet())
throw new InvalidArgumentException("rowset", left.getSourceColumn().getRowSet().getName()+"|"+right.getRowSet().getName());
// create the expression
DBColumnJoinExpr join = new DBColumnJoinExpr(left, right, joinType);
// additional constraints
DBCompareExpr where = null;
for (int i=0; i<addlConstraints.length; i++)
{
DBCompareExpr cmpExpr = addlConstraints[i];
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
// Chain with previouss
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
if (where!=null)
join.where(where);
// done
join(join);
return this;
}
/**
* Multi-Column version of column based join expression
* @param left the columsn on the left
* @param right the columns on the right
* @param joinType the joinType
* @param addlConstraints addlConstraints
* @return itself (this)
*/
public final DBCommand join(DBColumn[] left, DBColumn[] right, DBJoinType joinType, DBCompareExpr... addlConstraints)
{
// check params
if (left==null || right==null || left.length==0 || left.length!=right.length)
throw new InvalidArgumentException("left|right", left);
if (left[0].getRowSet()==right[0].getRowSet())
throw new InvalidArgumentException("rowset", left[0].getSourceColumn().getRowSet().getName()+"|"+right[0].getRowSet().getName());
/*
* TODO: Find a better solution / Make DBColumnJoinExpr multi-column
*/
DBColumnJoinExpr join = new DBColumnJoinExpr(left[0], right[0], joinType);
// compare the columns except the first
DBCompareExpr where = null;
for (int i=1; i<left.length; i++)
{ // add to where list
DBCompareExpr cmpExpr = right[i].is(left[i]);
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
// additional constraints
for (int i=0; i<addlConstraints.length; i++)
{
DBCompareExpr cmpExpr = addlConstraints[i];
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
if (where!=null)
join.where(where);
// done
join(join);
return this;
}
/**
* Adds a cross join for two tables or views
* @param left the left RowSet
* @param right the right RowSet
* @return itself (this)
*/
public final DBCommand join(DBRowSet left, DBRowSet right)
{
DBCrossJoinExpr join = new DBCrossJoinExpr(left, right);
join(join);
// done
return this;
}
/**
* Adds a join based on a compare expression to the command.
*
* @param rowset table or view to join
* @param cmp the compare expression with wich to join the table
* @param joinType type of join ({@link DBJoinType#INNER}, {@link DBJoinType#LEFT}, {@link DBJoinType#RIGHT})
* @return itself (this)
*/
public final DBCommand join(DBRowSet rowset, DBCompareExpr cmp, DBJoinType joinType)
{
DBCompareJoinExpr join = new DBCompareJoinExpr(rowset, cmp, joinType);
join(join);
return this;
}
/**
* Adds an inner join based on a compare expression to the command.
*
* @param rowset table of view which to join
* @param cmp the compare expression with wich to join the table
* @return itself (this)
*/
public final DBCommand join(DBRowSet rowset, DBCompareExpr cmp)
{
return join(rowset, cmp, DBJoinType.INNER);
}
/**
* Adds a list of join expressions to the command.
*
* @param joinExprList list of join expressions
*/
public void addJoins(List<DBJoinExpr> joinExprList)
{
if (joins == null)
{
joins = new ArrayList<DBJoinExpr>();
}
this.joins.addAll(joinExprList);
}
/**
* Returns true if the command has a join on the given table or false otherwise.
*
* @param rowset rowset table or view to join
*
* @return true if the command has a join on the given table or false otherwise
*/
public boolean hasJoinOn(DBRowSet rowset)
{
if (joins==null)
return false;
// Examine all joins
for (DBJoinExpr join : joins)
{
if (join.isJoinOn(rowset))
return true;
}
// not found
return false;
}
/**
* Returns true if the command has a constraint on the given table or false otherwise.
*
* @param rowset rowset table or view to join
*
* @return true if the command has a join on the given table or false otherwise
*/
public boolean hasConstraintOn(DBRowSet rowset)
{
if (where==null && having==null)
return false;
// Examine all constraints
int i = 0;
Set<DBColumn> columns = new HashSet<DBColumn>();
for (i = 0; where != null && i < where.size(); i++)
((DBExpr) where.get(i)).addReferencedColumns(columns);
/*
for (i = 0; groupBy != null && i < groupBy.size(); i++)
((DBExpr) groupBy.get(i)).addReferencedColumns(columns);
*/
for (i = 0; having != null && i < having.size(); i++)
((DBExpr) having.get(i)).addReferencedColumns(columns);
// now we have all columns
Iterator<DBColumn> iterator = columns.iterator();
while (iterator.hasNext())
{ // get the table
DBColumn col = iterator.next();
DBRowSet table = col.getRowSet();
if (table.equals(rowset))
return true;
}
// not found
return false;
}
/**
* Returns true if the command has a join on the given column or false otherwise.
*
* @param column the column to test
*
* @return true if the command has a join on the given column or false otherwise
*/
public boolean hasJoinOn(DBColumn column)
{
if (joins==null)
return false;
// Examine all joins
for (DBJoinExpr join : joins)
{
if (join.isJoinOn(column))
return true;
}
// not found
return false;
}
/**
* removes all joins to a given table or view
*
* @param rowset the table or view for which to remove all joins
*
* @return true if any joins have been removed or false otherwise
*/
public boolean removeJoinsOn(DBRowSet rowset)
{
if (joins==null)
return false;
// Examine all joins
int size = joins.size();
for (int i=size-1; i>=0; i--)
{
if (joins.get(i).isJoinOn(rowset))
joins.remove(i);
}
return (size!=joins.size());
}
/**
* removes all joins to a given column
*
* @param column the column for which to remove all joins
*
* @return true if any joins have been removed or false otherwise
*/
public boolean removeJoinsOn(DBColumn column)
{
if (joins==null)
return false;
// Examine all joins
int size = joins.size();
for (int i=size-1; i>=0; i--)
{
if (joins.get(i).isJoinOn(column))
joins.remove(i);
}
return (size!=joins.size());
}
/**
* Adds a constraint to the where phrase of the sql statement
* If another restriction already exists for the same column it will be replaced.
*
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public DBCommand where(DBCompareExpr expr)
{
if (where == null)
where = new ArrayList<DBCompareExpr>();
setConstraint(where, expr);
return this;
}
/**
* Adds a list of constraints to the where phrase of the sql statement
* If another restriction already exists for the same column it will be replaced.
*
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public final DBCommand where(DBCompareExpr... exprs)
{
for (int i=0; i<exprs.length; i++)
where(exprs[i]);
return this;
}
/**
* Returns true if the command has constraints or false if not.
*
* @return true if constraints have been set on the command
*/
public boolean hasWhereConstraints()
{
return (where!=null && where.size()>0);
}
/**
* Returns a copy of the defined where clauses.
*
* @return vector of where clauses
*/
public List<DBCompareExpr> getWhereConstraints()
{
return (this.where!=null ? Collections.unmodifiableList(this.where) : null);
}
/**
* removes a constraint on a particular column from the where clause
* @param col the column expression for which to remove the constraint
*/
public void removeWhereConstraintOn(DBColumnExpr col)
{
if (where == null)
return;
removeConstraintOn(where, col);
}
/**
* Returns a copy of the defined joins.
*
* @return the list of joins
*/
public List<DBJoinExpr> getJoins()
{
return (this.joins!=null ? Collections.unmodifiableList(this.joins) : null);
}
/**
* Adds a list of constraints to the command.
* @param constraints list of constraints
*/
public void addWhereConstraints(List<DBCompareExpr> constraints)
{
// allocate
if (where == null)
where = new ArrayList<DBCompareExpr>();
// add
this.where.addAll(constraints);
}
/**
* adds a constraint to the having clause.
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public DBCommand having(DBCompareExpr expr)
{
if (having == null)
having = new ArrayList<DBCompareExpr>();
setConstraint(having, expr);
return this;
}
/**
* Returns true if the command has having-constraints or false if not.
*
* @return true if constraints have been set on the command
*/
public boolean hasHavingConstraints()
{
return (having!=null && having.size()>0);
}
/**
* Returns a copy of the defined having clauses.
*
* @return list of having constraints
*/
public List<DBCompareExpr> getHavingConstraints()
{
return (this.having!=null ? Collections.unmodifiableList(this.having) : null);
}
/**
* removes a constraint on a particular column from the having clause
* @param col the column expression for which to remove the constraint
*/
public void removeHavingConstraintOn(DBColumnExpr col)
{
if (having == null)
return;
removeConstraintOn(having, col);
}
/**
* Returns whether or not the command has group by set
*/
public boolean hasGroupBy()
{
return (this.groupBy!=null ? !this.groupBy.isEmpty() : false);
}
/**
* Returns a copy of the defined where clauses.
*
* @return vector of where clauses
*/
public List<DBColumnExpr> getGroupBy()
{
return (this.groupBy!=null ? Collections.unmodifiableList(this.groupBy) : null);
}
/**
* Adds a list of columns to the group by phrase of an sql statement.
*
* @param exprs vararg of columns by which to group the rows
* @return itself (this)
*/
public DBCommand groupBy(DBColumnExpr...exprs)
{
if (groupBy == null)
groupBy = new ArrayList<DBColumnExpr>();
// Add all
for(DBColumnExpr expr : exprs)
{
if (expr.isAggregate()==false && groupBy.contains(expr)==false)
groupBy.add(expr);
}
return this;
}
/**
* Adds a collection of columns to the group by phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand groupBy(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr expr : columns)
{
groupBy(expr);
}
return this;
}
/**
* Clears the select distinct option.
*/
public void clearSelectDistinct()
{
this.selectDistinct = false;
}
/**
* Clears the list of selected columns.
*/
public void clearSelect()
{
select = null;
}
/**
* Clears the list of set expressions.
*/
public void clearSet()
{
if (set!=null && cmdParams!=null)
{ // remove params
for (DBSetExpr set : this.set)
{ // remove all
Object value = set.getValue();
if (value instanceof DBCmdParam)
cmdParams.remove(value);
}
}
set = null;
}
/**
* Clears the list of join expressions.
*/
public void clearJoin()
{
joins = null;
}
/**
* Clears the list of where constraints.
*/
public void clearWhere()
{
removeAllCommandParams(where);
where = null;
}
/**
* Clears the list of having constraints.
*/
public void clearHaving()
{
removeAllCommandParams(having);
having = null;
}
/**
* Clears the list of group by constraints.
*/
public void clearGroupBy()
{
groupBy = null;
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBOrderByExpr... exprs)
{
return (DBCommand)super.orderBy(exprs);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBColumnExpr... exprs)
{
return (DBCommand)super.orderBy(exprs);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBColumnExpr expr, boolean desc)
{
return (DBCommand)super.orderBy(expr, desc);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand limitRows(int limitRows)
{
return (DBCommand)super.limitRows(limitRows);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand skipRows(int skipRows)
{
return (DBCommand)super.skipRows(skipRows);
}
/**
* Clears the entire command object.
*/
public void clear()
{
cmdParams = null;
clearSelectDistinct();
clearSelect();
clearSet();
clearJoin();
clearWhere();
clearHaving();
clearGroupBy();
clearOrderBy();
clearLimit();
resetParamUsage();
}
/**
* returns true if prepared statements are enabled for this command
*/
protected boolean isPreparedStatementsEnabled()
{
return this.autoPrepareStmt;
}
/**
* returns true if a cmdParam should be used for the given column or false otherwise
*/
protected boolean useCmdParam(DBColumnExpr col, Object value)
{
// Cannot wrap DBExpr or DBSystemDate
if (value==null || value instanceof DBExpr || value instanceof DBDatabase.DBSystemDate)
return false;
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
return true;
// Only use a command param if column is of type BLOB or CLOB
DataType dt = col.getDataType();
return ( dt==DataType.BLOB || dt==DataType.CLOB );
}
/**
* adds a constraint to the 'where' or 'having' collections
* @param list the 'where' or 'having' list
* @param expr the DBCompareExpr object
*/
protected void setConstraint(List<DBCompareExpr> list, DBCompareExpr expr)
{
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
expr.prepareCommand(this);
}
// adds a comparison to the where or having list
for (int i = 0; i < list.size(); i++)
{ // check expression
DBCompareExpr other = list.get(i);
if (expr.isMutuallyExclusive(other)==false)
continue;
// Check if we replace a DBCommandParam
if (other instanceof DBCompareColExpr)
removeCommandParam((DBCompareColExpr)other);
// columns match
list.set(i, expr);
return;
}
// add expression
list.add(expr);
}
/**
* removes a constraint on a particular column to the 'where' or 'having' collections
* @param list the 'where' or 'having' list
* @param col the column expression for which to remove the constraint
*/
protected void removeConstraintOn(List<DBCompareExpr> list, DBColumnExpr col)
{
if (list == null)
return;
for(DBCompareExpr cmp : list)
{ // Check whether it is a compare column expr.
if (!(cmp instanceof DBCompareColExpr))
continue;
// Compare columns
DBColumnExpr c = ((DBCompareColExpr)cmp).getColumn();
DBColumn udc = c.getUpdateColumn();
if (c.equals(col) || (udc!=null && udc.equals(col.getUpdateColumn())))
{ // Check if we replace a DBCommandParam
removeCommandParam((DBCompareColExpr)cmp);
// remove the constraint
list.remove(cmp);
return;
}
}
}
/**
* Gets a list of all tables referenced by the query.
*
* @return list of all rowsets (tables or views) used by the query
*/
protected List<DBRowSet> getRowSetList()
{
// Check all tables
int i = 0;
Set<DBColumn> columns = new HashSet<DBColumn>();
for (i = 0; select != null && i < select.size(); i++)
((DBExpr) select.get(i)).addReferencedColumns(columns);
for (i = 0; joins != null && i < joins.size(); i++)
((DBExpr) joins.get(i)).addReferencedColumns(columns);
for (i = 0; where != null && i < where.size(); i++)
((DBExpr) where.get(i)).addReferencedColumns(columns);
for (i = 0; groupBy != null && i < groupBy.size(); i++)
((DBExpr) groupBy.get(i)).addReferencedColumns(columns);
for (i = 0; having != null && i < having.size(); i++)
((DBExpr) having.get(i)).addReferencedColumns(columns);
for (i = 0; orderBy != null && i < orderBy.size(); i++)
((DBExpr) orderBy.get(i)).addReferencedColumns(columns);
// now we have all columns
List<DBRowSet> tables = new ArrayList<DBRowSet>();
Iterator<DBColumn> iterator = columns.iterator();
while (iterator.hasNext())
{ // get the table
DBColumn col = iterator.next();
DBRowSet table = col.getRowSet();
if (table == cmdQuery)
{ // Recursion
log.error("Recursive Column Selection in Command!");
continue;
}
if (tables.contains(table) == false && table != null)
{ // Add table
tables.add(table);
}
}
return tables;
}
/**
* Adds Columns
*/
@Override
public void addReferencedColumns(Set<DBColumn> list)
{
// nothing to do!
return;
}
/**
* Returns an array of parameter values for a prepared statement.
* To ensure that all values are in the order of their occurrence, getSelect() should be called first.
* @return an array of parameter values for a prepared statement
*/
@Override
public Object[] getParamValues()
{
if (cmdParams==null || cmdParams.size()==0)
return null;
// Check whether all parameters have been used
if (paramUsageCount>0 && paramUsageCount!=cmdParams.size())
log.warn("DBCommand parameter count ("+String.valueOf(cmdParams.size())
+ ") does not match parameter use count ("+String.valueOf(paramUsageCount)+")");
// Create result array
Object[] values = new Object[cmdParams.size()];
for (int i=0; i<values.length; i++)
values[i]=cmdParams.get(i).getValue();
// values
return values;
}
/**
* Creates a select SQL-Statement
*
* @return a select SQL-Statement
*/
@Override
public void getSelect(StringBuilder buf)
{
resetParamUsage();
if (select == null)
throw new ObjectNotValidException(this); // invalid!
// Prepares statement
addSelect(buf);
// From clause
addFrom(buf);
// Add Where
addWhere(buf);
// Add Grouping
addGrouping(buf);
// Add Order
addOrder(buf);
// done
completeParamUsage();
}
/**
* Creates an insert SQL-Statement
*
* @return an insert SQL-Statement
*/
// get Insert
public String getInsert()
{
resetParamUsage();
if (set==null || set.get(0)==null)
return null;
StringBuilder buf = new StringBuilder("INSERT INTO ");
// addTableExpr(buf, CTX_NAME);
DBRowSet table = set.get(0).getTable();
table.addSQL(buf, CTX_FULLNAME);
// Set Expressions
buf.append("( ");
// Set Expressions
ArrayList<DBCompareColExpr> compexpr = null;
if (where!=null && !where.isEmpty())
{ // Convert ColumnExpression List to Column List
compexpr = new ArrayList<DBCompareColExpr>(where.size());
for (DBCompareExpr expr : where)
{ if (expr instanceof DBCompareColExpr)
{ DBColumn column = ((DBCompareColExpr)expr).getColumn().getUpdateColumn();
if (column!=null && hasSetExprOn(column)==false)
compexpr.add((DBCompareColExpr)expr);
}
}
// Add Column Names from where clause
if (compexpr.size()>0)
{
// add List
addListExpr(buf, compexpr, CTX_NAME, ", ");
// add separator
if (set != null)
buf.append(", ");
}
else
{ // No columns to set
compexpr = null;
}
}
if (set != null)
addListExpr(buf, set, CTX_NAME, ", ");
// Values
buf.append(") VALUES ( ");
if (compexpr != null)
addListExpr(buf, compexpr, CTX_VALUE, ", ");
if (compexpr != null && set != null)
buf.append(", ");
if (set != null)
addListExpr(buf, set, CTX_VALUE, ", ");
// End
buf.append(")");
// done
completeParamUsage();
return buf.toString();
}
/**
* Creates an update SQL-Statement
*
* @return an update SQL-Statement
*/
public String getUpdate()
{
resetParamUsage();
if (set == null)
return null;
StringBuilder buf = new StringBuilder("UPDATE ");
DBRowSet table = set.get(0).getTable();
if (joins!=null && !joins.isEmpty())
{ // Join Update
buf.append( table.getAlias() );
long context = CTX_DEFAULT;
// Set Expressions
buf.append("\r\nSET ");
addListExpr(buf, set, context, ", ");
// From clause
addFrom(buf);
// Add Where
addWhere(buf, context);
}
else
{ // Simple Statement
table.addSQL(buf, CTX_FULLNAME);
long context = CTX_NAME | CTX_VALUE;
// Set Expressions
buf.append("\r\nSET ");
addListExpr(buf, set, context, ", ");
// Add Where
addWhere(buf, context);
}
// done
completeParamUsage();
return buf.toString();
}
/**
* Creates a delete SQL-Statement
*
* @param table the table object
*
* @return a delete SQL-Statement
*/
public String getDelete(DBTable table)
{
resetParamUsage();
StringBuilder buf = new StringBuilder("DELETE ");
// joins or simple
if (joins!=null && !joins.isEmpty())
{ // delete with joins
table.addSQL(buf, CTX_FULLNAME);
// From clause
addFrom(buf);
// Add Where
addWhere(buf, CTX_DEFAULT);
}
else
{ // Simple Statement
buf.append("FROM ");
table.addSQL(buf, CTX_FULLNAME);
// where
addWhere(buf, CTX_NAME|CTX_VALUE);
}
// done
completeParamUsage();
return buf.toString();
}
// ------- Select Statement Parts -------
protected void addSelect(StringBuilder buf)
{
// Prepares statement
buf.append("SELECT ");
if (selectDistinct)
buf.append("DISTINCT ");
// Add Select Expressions
addListExpr(buf, select, CTX_ALL, ", ");
}
protected void addFrom(StringBuilder buf)
{
int originalLength = buf.length();
buf.append("\r\nFROM ");
// Join
boolean sep = false;
List<DBRowSet> tables = getRowSetList();
if (joins!=null && joins.size()>0)
{ // Join
List<DBRowSet> joinTables = new ArrayList<DBRowSet>();
for (int i=0; i<joins.size(); i++)
{ // append join
long context;
DBJoinExpr join = joins.get(i);
if (i<1)
{ // Add Join Tables
joinTables.add(join.getLeftTable());
joinTables.add(join.getRightTable());
// Remove from List
tables.remove(join.getLeftTable());
tables.remove(join.getRightTable());
// Context
context = CTX_NAME|CTX_VALUE;
}
else
{ // Extend the join
if ( joinTables.contains(join.getRightTable()))
join.reverse();
// Add Right Table
joinTables.add(join.getRightTable());
tables .remove(join.getRightTable());
// Context
context = CTX_VALUE;
buf.append( "\t" );
}
join.addSQL(buf, context);
// Merge subquery params
Object[] subQueryParams = join.getSubqueryParams();
if (subQueryParams!=null)
mergeSubqueryParams(subQueryParams);
// add CRLF
if( i!=joins.size()-1 )
buf.append("\r\n");
}
sep = true;
}
for (int i=0; i<tables.size(); i++)
{
if (sep) buf.append(", ");
DBRowSet t = tables.get(i);
t.addSQL(buf, CTX_DEFAULT|CTX_ALIAS);
// check for query
if (t instanceof DBQuery)
{ // Merge subquery params
mergeSubqueryParams(((DBQuery)t).getCommandExpr().getParamValues());
}
sep = true;
}
if (sep==false)
{ // add pseudo table or omitt from
String pseudoTable = getDatabase().getDbms().getSQLPhrase(DBSqlPhrase.SQL_PSEUDO_TABLE);
if (StringUtils.isNotEmpty(pseudoTable))
{ // add pseudo table
buf.append(pseudoTable);
}
else
{ // remove from
buf.setLength(originalLength);
}
}
}
protected void mergeSubqueryParams(Object[] subQueryParams)
{
if (subQueryParams==null || subQueryParams.length==0)
return;
// Subquery has parameters
if (cmdParams==null)
cmdParams= new ArrayList<DBCmdParam>(subQueryParams.length);
for (int p=0; p<subQueryParams.length; p++)
cmdParams.add(paramUsageCount++, new DBCmdParam(null, DataType.UNKNOWN, subQueryParams[p]));
}
protected void addWhere(StringBuilder buf, long context)
{
if (where!=null && !where.isEmpty())
{
buf.append("\r\nWHERE ");
// add where expression
addListExpr(buf, where, context, " AND ");
}
}
protected final void addWhere(StringBuilder buf)
{
addWhere(buf, CTX_DEFAULT);
}
protected void addGrouping(StringBuilder buf)
{
if (groupBy!=null && !groupBy.isEmpty())
{ // Having
buf.append("\r\nGROUP BY ");
addListExpr(buf, groupBy, CTX_DEFAULT, ", ");
}
if (having!=null && !having.isEmpty())
{ // Having
buf.append("\r\nHAVING ");
addListExpr(buf, having, CTX_DEFAULT, " AND ");
}
}
protected void addOrder(StringBuilder buf)
{
if (orderBy!=null && !orderBy.isEmpty())
{ // order By
buf.append("\r\nORDER BY ");
addListExpr(buf, orderBy, CTX_DEFAULT, ", ");
}
}
} | empire-db/src/main/java/org/apache/empire/db/DBCommand.java | /*
* 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.empire.db;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.data.DataType;
import org.apache.empire.db.expr.compare.DBCompareColExpr;
import org.apache.empire.db.expr.compare.DBCompareExpr;
import org.apache.empire.db.expr.join.DBColumnJoinExpr;
import org.apache.empire.db.expr.join.DBCompareJoinExpr;
import org.apache.empire.db.expr.join.DBCrossJoinExpr;
import org.apache.empire.db.expr.join.DBJoinExpr;
import org.apache.empire.db.expr.order.DBOrderByExpr;
import org.apache.empire.db.expr.set.DBSetExpr;
import org.apache.empire.dbms.DBSqlPhrase;
import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.exceptions.ItemNotFoundException;
import org.apache.empire.exceptions.ObjectNotValidException;
import org.apache.empire.exceptions.UnspecifiedErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This abstract class handles the creation of the SQL-Commands.
* There are methods to create SQL-Commands, like update, insert,
* delete and select.
*/
public abstract class DBCommand extends DBCommandExpr
implements Cloneable
{
// *Deprecated* private static final long serialVersionUID = 1L;
// Logger
protected static final Logger log = LoggerFactory.getLogger(DBCommand.class);
// Distinct Select
protected boolean selectDistinct = false;
// Lists
protected List<DBColumnExpr> select = null;
protected List<DBSetExpr> set = null;
protected List<DBJoinExpr> joins = null;
protected List<DBCompareExpr> where = null;
protected List<DBCompareExpr> having = null;
protected List<DBColumnExpr> groupBy = null;
// Parameters for prepared Statements generation
protected boolean autoPrepareStmt = false;
protected List<DBCmdParam> cmdParams = null;
private int paramUsageCount = 0;
/**
* Constructs a new DBCommand object and set the specified DBDatabase object.
*
* @param db the current database object
*/
protected DBCommand(boolean autoPrepareStmt)
{
this.autoPrepareStmt = autoPrepareStmt;
}
/**
* Custom serialization for transient database.
*
private void writeObject(ObjectOutputStream strm) throws IOException
{ // Database
strm.writeObject(db.getIdentifier());
// write the rest
strm.defaultWriteObject();
}
private void readObject(ObjectInputStream strm) throws IOException, ClassNotFoundException
{
String dbid = String.valueOf(strm.readObject());
// find database
DBDatabase dbo = DBDatabase.findByIdentifier(dbid);
if (dbo==null)
throw new ItemNotFoundException(dbid);
// set final field
ClassUtils.setPrivateFieldValue(DBCommand.class, this, "db", dbo);
// read the rest
strm.defaultReadObject();
}
*/
/**
* internally used to reset the command param usage count.
* Note: Only one thread my generate an SQL statement
*/
protected void resetParamUsage()
{
paramUsageCount = 0;
if (cmdParams==null)
return;
// clear subquery params
for (int i=cmdParams.size()-1; i>=0 ;i--)
if (cmdParams.get(i).getCmd()!=this)
cmdParams.remove(i);
}
/**
* internally used to remove unused Command Params from list
* Note: Only one thread my generate an SQL statement
*/
protected void completeParamUsage()
{
if (cmdParams==null)
return;
// check whether all params have been used
if (paramUsageCount < cmdParams.size())
{ // Remove unused parameters
log.warn("DBCommand has {} unused Command params", cmdParams.size()-paramUsageCount);
for (int i=cmdParams.size()-1; i>=paramUsageCount; i--)
cmdParams.remove(i);
}
}
/**
* internally used to reorder the command params to match their order of occurance
*/
protected void notifyParamUsage(DBCmdParam param)
{
int index = cmdParams.indexOf(param);
if (index < paramUsageCount)
{ // Error: parameter probably used twice in statement!
throw new UnspecifiedErrorException("A parameter may only be used once in a command.");
}
if (index > paramUsageCount)
{ // Correct parameter order
cmdParams.remove(index);
cmdParams.add(paramUsageCount, param);
}
paramUsageCount++;
}
/**
* internally used to remove the command param used in a constraint
*/
private void removeCommandParam(DBCompareColExpr cmp)
{
if (cmdParams!=null && (cmp.getValue() instanceof DBCmdParam))
cmdParams.remove(cmp.getValue());
}
/**
* internally used to remove all command params used in a list of constraints
*/
private void removeAllCommandParams(List<DBCompareExpr> list)
{
if (cmdParams == null)
return;
for(DBCompareExpr cmp : list)
{ // Check whether it is a compare column expr.
if (!(cmp instanceof DBCompareColExpr))
continue;
// Check the value is a DBCommandParam
removeCommandParam((DBCompareColExpr)cmp);
}
}
/**
* Creates a clone of this class.
*/
@Override
public DBCommand clone()
{
try
{
DBCommand clone = (DBCommand)super.clone();
// Clone lists
if (select!=null)
clone.select = new ArrayList<DBColumnExpr>(select);
if (set!=null)
clone.set = new ArrayList<DBSetExpr>(set);
if (joins!=null)
clone.joins = new ArrayList<DBJoinExpr>(joins);
if (where!=null)
clone.where = new ArrayList<DBCompareExpr>(where);
if (groupBy!=null)
clone.groupBy = new ArrayList<DBColumnExpr>(groupBy);
if (having!=null)
clone.having = new ArrayList<DBCompareExpr>(having);
if (cmdParams!=null && !cmdParams.isEmpty())
{ // clone params
clone.paramUsageCount = 0;
clone.cmdParams = new ArrayList<DBCmdParam>(cmdParams.size());
// clone set
for (int i=0; (clone.set!=null && i<clone.set.size()); i++)
clone.set.set(i, clone.set.get(i).copy(clone));
// clone where and having
for (int i=0; (clone.where!=null && i<clone.where.size()); i++)
clone.where.set(i, clone.where.get(i).copy(clone));
for (int i=0; (clone.having!=null && i<clone.having.size()); i++)
clone.having.set(i, clone.having.get(i).copy(clone));
}
// done
return clone;
} catch (CloneNotSupportedException e) {
log.error("Cloning DBCommand object failed!", e);
throw new InternalException(e);
}
}
@SuppressWarnings("unchecked")
@Override
public final DBDatabase getDatabase()
{
if (hasSelectExpr())
return this.select.get(0).getDatabase();
if (hasSetExpr())
return this.set.get(0).getDatabase();
// two more chances (should we?)
if (where!=null && !where.isEmpty())
return where.get(0).getDatabase();
if (orderBy!=null && !orderBy.isEmpty())
return orderBy.get(0).getDatabase();
// not valid yet
throw new ObjectNotValidException(this);
}
/**
* Returns true if the this command has either Select or Set expressions
*/
@Override
public boolean isValid()
{
return hasSelectExpr() || hasSetExpr();
}
/**
* Sets whether or not the select statement should contain
* the distinct directive .
* @return itself (this)
*/
public DBCommand selectDistinct()
{
this.selectDistinct = true;
return this;
}
/**
* Returns whether or not the select statement will be distinct or not.
*
* @return true if the select will contain the distinct directive or false otherwise.
*/
public boolean isSelectDistinct()
{
return selectDistinct;
}
/**
* returns whether or not the command has any select expression
* @return true if the command has any select expression of false otherwise
*/
@Override
public boolean hasSelectExpr()
{
return (select!=null && !select.isEmpty());
}
/**
* returns whether or not the command has a specific select expression
* @return true if the command contains the given select expression of false otherwise
*/
@Override
public boolean hasSelectExpr(DBColumnExpr expr)
{
return (select!=null ? (select.indexOf(expr)>=0) : false);
}
/**
* Adds a DBColumnExpr object to the Select collection
*
* @param expr the DBColumnExpr object
* @return itself (this)
*/
public DBCommand select(DBColumnExpr expr)
{ // Select this column
if (select == null)
select = new ArrayList<DBColumnExpr>();
if (expr != null && select.contains(expr) == false)
select.add(expr);
return this;
}
/**
* Adds a list of columns to the select phrase of an sql statement.
*
* @param exprs an vararg of DBColumnExpr's to select
* @return itself (this)
*/
public final DBCommand select(DBColumnExpr... exprs)
{
for (DBColumnExpr expr : exprs)
{
select(expr);
}
return this;
}
/**
* Adds a collection of columns to the select phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand select(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr expr : columns)
{
select(expr);
}
return this;
}
/**
* Adds a list of columns with their qualified name to the select phrase of an sql statement.
*
* @param exprs one or more columns to select
* @return itself (this)
*/
public DBCommand selectQualified(DBColumnExpr... columns)
{
for (DBColumnExpr col : columns)
{
select(col.qualified());
}
return this;
}
/**
* Adds a collection of columns to the select phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand selectQualified(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr col : columns)
{
select(col.qualified());
}
return this;
}
/**
* Returns an array of all select expressions
*
* @return an array of all DBColumnExpr objects or <code>null</code> if there is nothing to select
*/
@Override
public DBColumnExpr[] getSelectExprList()
{
int count = (select != null) ? select.size() : 0;
if (count < 1)
return null;
// The List
DBColumnExpr[] exprList = new DBColumnExpr[count];
for (int i = 0; i < count; i++)
exprList[i] = select.get(i);
// The expression List
return exprList;
}
/**
* Returns all select expressions as unmodifiable list
* @return the list of DBColumnExpr used for select
*/
@Override
public List<DBColumnExpr> getSelectExpressions()
{
return (this.select!=null ? Collections.unmodifiableList(this.select) : null);
}
/**
* replaces a select expression with another or removes a select expression
* In order to remove the expression, set the replWith parameter to null
* If the replace expression is not found, an ItemNotFoundException is thrown
* @param replExpr
* @param replWith
*/
public void replaceSelect(DBColumnExpr replExpr, DBColumnExpr replWith)
{
int idx = (select != null ? select.indexOf(replExpr) : -1);
if (idx < 0)
throw new ItemNotFoundException(replExpr);
// replace now
if (replWith!=null)
select.set(idx, replWith);
else
select.remove(idx);
}
/**
* removes one or more expressions from the Select expression list
* @param exprs the expression(s) to be removed
*/
public void removeSelect(DBColumnExpr... exprs)
{
if (select==null)
return;
for (int i=0; i<exprs.length; i++)
{
int idx = select.indexOf(exprs[i]);
if (idx>=0)
select.remove(idx);
}
}
/**
* Checks whether or not there are any aggregate functions in the Select
* @return true if at least on of the selected expressions is an aggregate
*/
public boolean hasAggegation()
{
for (DBColumnExpr expr : this.select)
{
if (expr.isAggregate())
return true;
}
return false;
}
/**
* Adds a single set expressions to this command
* Use column.to(...) to create a set expression
*
* @param expr the DBSetExpr object(s)
* @return itself (this)
*/
public DBCommand set(DBSetExpr expr)
{
// add to list
if (set == null)
set = new ArrayList<DBSetExpr>();
for (int i = 0; i < set.size(); i++)
{
DBSetExpr chk = set.get(i);
if (chk.column.equals(expr.column))
{ // Overwrite existing value
if (useCmdParam(expr.column, expr.value))
{ // Use parameter value
if (chk.value instanceof DBCmdParam)
{ // reuse the old paramter
((DBCmdParam)chk.value).setValue(expr.value);
expr.value = chk.value;
chk.value = null;
}
else
{ // create new one
expr.value = addParam(expr.column.getDataType(), expr.value);
}
}
else
{ // remove from parameter list (if necessary)
if (cmdParams!=null && (chk.value instanceof DBCmdParam))
cmdParams.remove(chk.value);
}
// replace now
set.set(i, expr);
return this;
}
}
// Replace with parameter
if (useCmdParam(expr.column, expr.value))
expr.value = addParam(expr.column.getDataType(), expr.value);
// new Value!
set.add(expr);
return this;
}
/**
* Adds a list of set expressions to this command
* Use column.to(...) to create a set expression
*
* @param expr the DBSetExpr object(s)
* @return itself (this)
*/
public final DBCommand set(DBSetExpr... exprs)
{
for (int i=0; i<exprs.length; i++)
set(exprs[i]);
return this;
}
/**
* Returns whether or not the command has group by set
*/
public boolean hasSetExpr()
{
return (this.set!=null ? !this.set.isEmpty() : false);
}
/**
* Checks whether a column is in the list of set expressions
* @param column
* @return <code>true</code> if there is a set expression
*/
protected boolean hasSetExprOn(DBColumn column)
{
if (set==null)
return false;
Iterator<DBSetExpr> i = set.iterator();
while (i.hasNext())
{
DBSetExpr chk = i.next();
if (chk.column.equals(column))
return true;
}
return false;
}
/**
* Returns all set expressions as unmodifiable list
* @return the list of DBSetExpr used for set
*/
public List<DBSetExpr> getSetExpressions()
{
return (this.set!=null ? Collections.unmodifiableList(this.set) : null);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The command parameter returned may be used to alter the value.
*
* @param type the data type of the parameter
* @param value the initial parameter value
*
* @return the command parameter object
*/
public DBCmdParam addParam(DataType type, Object value)
{
if (cmdParams==null)
cmdParams= new ArrayList<DBCmdParam>();
// Create and add the parameter to the parameter list
DBCmdParam param = new DBCmdParam(this, type, value);
cmdParams.add(param);
// done
return param;
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @param colExpr the column expression for which to create the parameter
* @param value the initial parameter value
*
* @return the command parameter object
*/
public final DBCmdParam addParam(DBColumnExpr colExpr, Object value)
{
return addParam(colExpr.getDataType(), value);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @return the command parameter object
*/
public final DBCmdParam addParam(Object value)
{
return addParam(DataType.UNKNOWN, value);
}
/**
* Adds an command parameter which will be used in a prepared statement.
* The initial value of the command parameter is null but can be modified using the setValue method.
*
* @return the command parameter object
*/
public final DBCmdParam addParam()
{
return addParam(DataType.UNKNOWN, null);
}
/**
* Adds a join to the list of join expressions.
*
* @param join the join expression
* @return itself (this)
*/
public DBCommand join(DBJoinExpr join)
{
// check tables
if (join.getLeftTable().equals(join.getRightTable()))
throw new InvalidArgumentException("left|right", join.getLeftTable());
// create list
if (joins == null)
joins = new ArrayList<DBJoinExpr>();
// Create a new join
for (int i = 0; i < joins.size(); i++)
{ // Check whether join exists
DBJoinExpr item = joins.get(i);
if (item.equals(join))
return this;
}
joins.add(join);
return this;
}
/**
* Adds an inner join based on two columns to the list of join expressions.
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand join(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.INNER, addlConstraints);
}
/**
* Adds a left join based on two columns to the list of join expressions.
* Added for convenience
* Same as join(left, right, DBJoinType.LEFT);
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand joinLeft(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.LEFT, addlConstraints);
}
/**
* Adds a right join based on two columns to the list of join expressions.
* Added for convenience
* Same as join(left, right, DBJoinType.RIGHT);
*
* @param left the left join value
* @param right the right join
* @return itself (this)
*/
public final DBCommand joinRight(DBColumnExpr left, DBColumn right, DBCompareExpr... addlConstraints)
{
return join(left, right, DBJoinType.RIGHT, addlConstraints);
}
/**
* Adds a join based on two columns to the list of join expressions.
*
* Migration hint from 2.x -> replace ").where(" with just ","
*
* @param left the left join value
* @param right the right join
* @param joinType type of join ({@link DBJoinType#INNER}, {@link DBJoinType#LEFT}, {@link DBJoinType#RIGHT})
* @return itself (this)
*/
public final DBCommand join(DBColumnExpr left, DBColumn right, DBJoinType joinType, DBCompareExpr... addlConstraints)
{
if (left==null || right==null || left.getSourceColumn()==null)
throw new InvalidArgumentException("left|right", left);
if (left.getSourceColumn().getRowSet()==right.getRowSet())
throw new InvalidArgumentException("rowset", left.getSourceColumn().getRowSet().getName()+"|"+right.getRowSet().getName());
// create the expression
DBColumnJoinExpr join = new DBColumnJoinExpr(left, right, joinType);
// additional constraints
DBCompareExpr where = null;
for (int i=0; i<addlConstraints.length; i++)
{
DBCompareExpr cmpExpr = addlConstraints[i];
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
// Chain with previouss
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
if (where!=null)
join.where(where);
// done
join(join);
return this;
}
/**
* Multi-Column version of column based join expression
* @param left the columsn on the left
* @param right the columns on the right
* @param joinType the joinType
* @param addlConstraints addlConstraints
* @return itself (this)
*/
public final DBCommand join(DBColumn[] left, DBColumn[] right, DBJoinType joinType, DBCompareExpr... addlConstraints)
{
// check params
if (left==null || right==null || left.length==0 || left.length!=right.length)
throw new InvalidArgumentException("left|right", left);
if (left[0].getRowSet()==right[0].getRowSet())
throw new InvalidArgumentException("rowset", left[0].getSourceColumn().getRowSet().getName()+"|"+right[0].getRowSet().getName());
/*
* TODO: Find a better solution / Make DBColumnJoinExpr multi-column
*/
DBColumnJoinExpr join = new DBColumnJoinExpr(left[0], right[0], joinType);
// compare the columns except the first
DBCompareExpr where = null;
for (int i=1; i<left.length; i++)
{ // add to where list
DBCompareExpr cmpExpr = right[i].is(left[i]);
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
// additional constraints
for (int i=0; i<addlConstraints.length; i++)
{
DBCompareExpr cmpExpr = addlConstraints[i];
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
cmpExpr.prepareCommand(this);
}
where = (where!=null ? where.and(cmpExpr) : cmpExpr);
}
if (where!=null)
join.where(where);
// done
join(join);
return this;
}
/**
* Adds a cross join for two tables or views
* @param left the left RowSet
* @param right the right RowSet
* @return itself (this)
*/
public final DBCommand join(DBRowSet left, DBRowSet right)
{
DBCrossJoinExpr join = new DBCrossJoinExpr(left, right);
join(join);
// done
return this;
}
/**
* Adds a join based on a compare expression to the command.
*
* @param rowset table or view to join
* @param cmp the compare expression with wich to join the table
* @param joinType type of join ({@link DBJoinType#INNER}, {@link DBJoinType#LEFT}, {@link DBJoinType#RIGHT})
* @return itself (this)
*/
public final DBCommand join(DBRowSet rowset, DBCompareExpr cmp, DBJoinType joinType)
{
DBCompareJoinExpr join = new DBCompareJoinExpr(rowset, cmp, joinType);
join(join);
return this;
}
/**
* Adds an inner join based on a compare expression to the command.
*
* @param rowset table of view which to join
* @param cmp the compare expression with wich to join the table
* @return itself (this)
*/
public final DBCommand join(DBRowSet rowset, DBCompareExpr cmp)
{
return join(rowset, cmp, DBJoinType.INNER);
}
/**
* Adds a list of join expressions to the command.
*
* @param joinExprList list of join expressions
*/
public void addJoins(List<DBJoinExpr> joinExprList)
{
if (joins == null)
{
joins = new ArrayList<DBJoinExpr>();
}
this.joins.addAll(joinExprList);
}
/**
* Returns true if the command has a join on the given table or false otherwise.
*
* @param rowset rowset table or view to join
*
* @return true if the command has a join on the given table or false otherwise
*/
public boolean hasJoinOn(DBRowSet rowset)
{
if (joins==null)
return false;
// Examine all joins
for (DBJoinExpr join : joins)
{
if (join.isJoinOn(rowset))
return true;
}
// not found
return false;
}
/**
* Returns true if the command has a constraint on the given table or false otherwise.
*
* @param rowset rowset table or view to join
*
* @return true if the command has a join on the given table or false otherwise
*/
public boolean hasConstraintOn(DBRowSet rowset)
{
if (where==null && having==null)
return false;
// Examine all constraints
int i = 0;
Set<DBColumn> columns = new HashSet<DBColumn>();
for (i = 0; where != null && i < where.size(); i++)
((DBExpr) where.get(i)).addReferencedColumns(columns);
/*
for (i = 0; groupBy != null && i < groupBy.size(); i++)
((DBExpr) groupBy.get(i)).addReferencedColumns(columns);
*/
for (i = 0; having != null && i < having.size(); i++)
((DBExpr) having.get(i)).addReferencedColumns(columns);
// now we have all columns
Iterator<DBColumn> iterator = columns.iterator();
while (iterator.hasNext())
{ // get the table
DBColumn col = iterator.next();
DBRowSet table = col.getRowSet();
if (table.equals(rowset))
return true;
}
// not found
return false;
}
/**
* Returns true if the command has a join on the given column or false otherwise.
*
* @param column the column to test
*
* @return true if the command has a join on the given column or false otherwise
*/
public boolean hasJoinOn(DBColumn column)
{
if (joins==null)
return false;
// Examine all joins
for (DBJoinExpr join : joins)
{
if (join.isJoinOn(column))
return true;
}
// not found
return false;
}
/**
* removes all joins to a given table or view
*
* @param rowset the table or view for which to remove all joins
*
* @return true if any joins have been removed or false otherwise
*/
public boolean removeJoinsOn(DBRowSet rowset)
{
if (joins==null)
return false;
// Examine all joins
int size = joins.size();
for (int i=size-1; i>=0; i--)
{
if (joins.get(i).isJoinOn(rowset))
joins.remove(i);
}
return (size!=joins.size());
}
/**
* removes all joins to a given column
*
* @param column the column for which to remove all joins
*
* @return true if any joins have been removed or false otherwise
*/
public boolean removeJoinsOn(DBColumn column)
{
if (joins==null)
return false;
// Examine all joins
int size = joins.size();
for (int i=size-1; i>=0; i--)
{
if (joins.get(i).isJoinOn(column))
joins.remove(i);
}
return (size!=joins.size());
}
/**
* Adds a constraint to the where phrase of the sql statement
* If another restriction already exists for the same column it will be replaced.
*
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public DBCommand where(DBCompareExpr expr)
{
if (where == null)
where = new ArrayList<DBCompareExpr>();
setConstraint(where, expr);
return this;
}
/**
* Adds a list of constraints to the where phrase of the sql statement
* If another restriction already exists for the same column it will be replaced.
*
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public final DBCommand where(DBCompareExpr... exprs)
{
for (int i=0; i<exprs.length; i++)
where(exprs[i]);
return this;
}
/**
* Returns true if the command has constraints or false if not.
*
* @return true if constraints have been set on the command
*/
public boolean hasWhereConstraints()
{
return (where!=null && where.size()>0);
}
/**
* Returns a copy of the defined where clauses.
*
* @return vector of where clauses
*/
public List<DBCompareExpr> getWhereConstraints()
{
return (this.where!=null ? Collections.unmodifiableList(this.where) : null);
}
/**
* removes a constraint on a particular column from the where clause
* @param col the column expression for which to remove the constraint
*/
public void removeWhereConstraintOn(DBColumnExpr col)
{
if (where == null)
return;
removeConstraintOn(where, col);
}
/**
* Returns a copy of the defined joins.
*
* @return the list of joins
*/
public List<DBJoinExpr> getJoins()
{
return (this.joins!=null ? Collections.unmodifiableList(this.joins) : null);
}
/**
* Adds a list of constraints to the command.
* @param constraints list of constraints
*/
public void addWhereConstraints(List<DBCompareExpr> constraints)
{
// allocate
if (where == null)
where = new ArrayList<DBCompareExpr>();
// add
this.where.addAll(constraints);
}
/**
* adds a constraint to the having clause.
* @param expr the DBCompareExpr object
* @return itself (this)
*/
public DBCommand having(DBCompareExpr expr)
{
if (having == null)
having = new ArrayList<DBCompareExpr>();
setConstraint(having, expr);
return this;
}
/**
* Returns true if the command has having-constraints or false if not.
*
* @return true if constraints have been set on the command
*/
public boolean hasHavingConstraints()
{
return (having!=null && having.size()>0);
}
/**
* Returns a copy of the defined having clauses.
*
* @return list of having constraints
*/
public List<DBCompareExpr> getHavingConstraints()
{
return (this.having!=null ? Collections.unmodifiableList(this.having) : null);
}
/**
* removes a constraint on a particular column from the having clause
* @param col the column expression for which to remove the constraint
*/
public void removeHavingConstraintOn(DBColumnExpr col)
{
if (having == null)
return;
removeConstraintOn(having, col);
}
/**
* Returns whether or not the command has group by set
*/
public boolean hasGroupBy()
{
return (this.groupBy!=null ? !this.groupBy.isEmpty() : false);
}
/**
* Returns a copy of the defined where clauses.
*
* @return vector of where clauses
*/
public List<DBColumnExpr> getGroupBy()
{
return (this.groupBy!=null ? Collections.unmodifiableList(this.groupBy) : null);
}
/**
* Adds a list of columns to the group by phrase of an sql statement.
*
* @param exprs vararg of columns by which to group the rows
* @return itself (this)
*/
public DBCommand groupBy(DBColumnExpr...exprs)
{
if (groupBy == null)
groupBy = new ArrayList<DBColumnExpr>();
// Add all
for(DBColumnExpr expr : exprs)
{
if (expr.isAggregate()==false && groupBy.contains(expr)==false)
groupBy.add(expr);
}
return this;
}
/**
* Adds a collection of columns to the group by phrase of an sql statement.
*
* @param columns the column expressions to add
* @return itself (this)
*/
public final DBCommand groupBy(Collection<? extends DBColumnExpr> columns)
{
for (DBColumnExpr expr : columns)
{
groupBy(expr);
}
return this;
}
/**
* Clears the select distinct option.
*/
public void clearSelectDistinct()
{
this.selectDistinct = false;
}
/**
* Clears the list of selected columns.
*/
public void clearSelect()
{
select = null;
}
/**
* Clears the list of set expressions.
*/
public void clearSet()
{
if (set!=null && cmdParams!=null)
{ // remove params
for (DBSetExpr set : this.set)
{ // remove all
Object value = set.getValue();
if (value instanceof DBCmdParam)
cmdParams.remove(value);
}
}
set = null;
}
/**
* Clears the list of join expressions.
*/
public void clearJoin()
{
joins = null;
}
/**
* Clears the list of where constraints.
*/
public void clearWhere()
{
removeAllCommandParams(where);
where = null;
}
/**
* Clears the list of having constraints.
*/
public void clearHaving()
{
removeAllCommandParams(having);
having = null;
}
/**
* Clears the list of group by constraints.
*/
public void clearGroupBy()
{
groupBy = null;
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBOrderByExpr... exprs)
{
return (DBCommand)super.orderBy(exprs);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBColumnExpr... exprs)
{
return (DBCommand)super.orderBy(exprs);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand orderBy(DBColumnExpr expr, boolean desc)
{
return (DBCommand)super.orderBy(expr, desc);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand limitRows(int limitRows)
{
return (DBCommand)super.limitRows(limitRows);
}
/**
* Overridden to change return type from DBCommandExpr to DBCommand
*/
@Override
public DBCommand skipRows(int skipRows)
{
return (DBCommand)super.skipRows(skipRows);
}
/**
* Clears the entire command object.
*/
public void clear()
{
cmdParams = null;
clearSelectDistinct();
clearSelect();
clearSet();
clearJoin();
clearWhere();
clearHaving();
clearGroupBy();
clearOrderBy();
clearLimit();
resetParamUsage();
}
/**
* returns true if prepared statements are enabled for this command
*/
protected boolean isPreparedStatementsEnabled()
{
return this.autoPrepareStmt;
}
/**
* returns true if a cmdParam should be used for the given column or false otherwise
*/
protected boolean useCmdParam(DBColumnExpr col, Object value)
{
// Cannot wrap DBExpr or DBSystemDate
if (value==null || value instanceof DBExpr || value instanceof DBDatabase.DBSystemDate)
return false;
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
return true;
// Only use a command param if column is of type BLOB or CLOB
DataType dt = col.getDataType();
return ( dt==DataType.BLOB || dt==DataType.CLOB );
}
/**
* adds a constraint to the 'where' or 'having' collections
* @param list the 'where' or 'having' list
* @param expr the DBCompareExpr object
*/
protected void setConstraint(List<DBCompareExpr> list, DBCompareExpr expr)
{
// Check if prepared statements are enabled
if (isPreparedStatementsEnabled())
{ // use command params
expr.prepareCommand(this);
}
// adds a comparison to the where or having list
for (int i = 0; i < list.size(); i++)
{ // check expression
DBCompareExpr other = list.get(i);
if (expr.isMutuallyExclusive(other)==false)
continue;
// Check if we replace a DBCommandParam
if (other instanceof DBCompareColExpr)
removeCommandParam((DBCompareColExpr)other);
// columns match
list.set(i, expr);
return;
}
// add expression
list.add(expr);
}
/**
* removes a constraint on a particular column to the 'where' or 'having' collections
* @param list the 'where' or 'having' list
* @param col the column expression for which to remove the constraint
*/
protected void removeConstraintOn(List<DBCompareExpr> list, DBColumnExpr col)
{
if (list == null)
return;
for(DBCompareExpr cmp : list)
{ // Check whether it is a compare column expr.
if (!(cmp instanceof DBCompareColExpr))
continue;
// Compare columns
DBColumnExpr c = ((DBCompareColExpr)cmp).getColumn();
DBColumn udc = c.getUpdateColumn();
if (c.equals(col) || (udc!=null && udc.equals(col.getUpdateColumn())))
{ // Check if we replace a DBCommandParam
removeCommandParam((DBCompareColExpr)cmp);
// remove the constraint
list.remove(cmp);
return;
}
}
}
/**
* Gets a list of all tables referenced by the query.
*
* @return list of all rowsets (tables or views) used by the query
*/
protected List<DBRowSet> getRowSetList()
{
// Check all tables
int i = 0;
Set<DBColumn> columns = new HashSet<DBColumn>();
for (i = 0; select != null && i < select.size(); i++)
((DBExpr) select.get(i)).addReferencedColumns(columns);
for (i = 0; joins != null && i < joins.size(); i++)
((DBExpr) joins.get(i)).addReferencedColumns(columns);
for (i = 0; where != null && i < where.size(); i++)
((DBExpr) where.get(i)).addReferencedColumns(columns);
for (i = 0; groupBy != null && i < groupBy.size(); i++)
((DBExpr) groupBy.get(i)).addReferencedColumns(columns);
for (i = 0; having != null && i < having.size(); i++)
((DBExpr) having.get(i)).addReferencedColumns(columns);
for (i = 0; orderBy != null && i < orderBy.size(); i++)
((DBExpr) orderBy.get(i)).addReferencedColumns(columns);
// now we have all columns
List<DBRowSet> tables = new ArrayList<DBRowSet>();
Iterator<DBColumn> iterator = columns.iterator();
while (iterator.hasNext())
{ // get the table
DBColumn col = iterator.next();
DBRowSet table = col.getRowSet();
if (table == cmdQuery)
{ // Recursion
log.error("Recursive Column Selection in Command!");
continue;
}
if (tables.contains(table) == false && table != null)
{ // Add table
tables.add(table);
}
}
return tables;
}
/**
* Adds Columns
*/
@Override
public void addReferencedColumns(Set<DBColumn> list)
{
// nothing to do!
return;
}
/**
* Returns an array of parameter values for a prepared statement.
* To ensure that all values are in the order of their occurrence, getSelect() should be called first.
* @return an array of parameter values for a prepared statement
*/
@Override
public Object[] getParamValues()
{
if (cmdParams==null || cmdParams.size()==0)
return null;
// Check whether all parameters have been used
if (paramUsageCount>0 && paramUsageCount!=cmdParams.size())
log.warn("DBCommand parameter count ("+String.valueOf(cmdParams.size())
+ ") does not match parameter use count ("+String.valueOf(paramUsageCount)+")");
// Create result array
Object[] values = new Object[cmdParams.size()];
for (int i=0; i<values.length; i++)
values[i]=cmdParams.get(i).getValue();
// values
return values;
}
/**
* Creates a select SQL-Statement
*
* @return a select SQL-Statement
*/
@Override
public void getSelect(StringBuilder buf)
{
resetParamUsage();
if (select == null)
throw new ObjectNotValidException(this); // invalid!
// Prepares statement
addSelect(buf);
// From clause
addFrom(buf);
// Add Where
addWhere(buf);
// Add Grouping
addGrouping(buf);
// Add Order
addOrder(buf);
// done
completeParamUsage();
}
/**
* Creates an insert SQL-Statement
*
* @return an insert SQL-Statement
*/
// get Insert
public String getInsert()
{
resetParamUsage();
if (set==null || set.get(0)==null)
return null;
StringBuilder buf = new StringBuilder("INSERT INTO ");
// addTableExpr(buf, CTX_NAME);
DBRowSet table = set.get(0).getTable();
table.addSQL(buf, CTX_FULLNAME);
// Set Expressions
buf.append("( ");
// Set Expressions
ArrayList<DBCompareColExpr> compexpr = null;
if (where!=null && !where.isEmpty())
{ // Convert ColumnExpression List to Column List
compexpr = new ArrayList<DBCompareColExpr>(where.size());
for (DBCompareExpr expr : where)
{ if (expr instanceof DBCompareColExpr)
{ DBColumn column = ((DBCompareColExpr)expr).getColumn().getUpdateColumn();
if (column!=null && hasSetExprOn(column)==false)
compexpr.add((DBCompareColExpr)expr);
}
}
// Add Column Names from where clause
if (compexpr.size()>0)
{
// add List
addListExpr(buf, compexpr, CTX_NAME, ", ");
// add separator
if (set != null)
buf.append(", ");
}
else
{ // No columns to set
compexpr = null;
}
}
if (set != null)
addListExpr(buf, set, CTX_NAME, ", ");
// Values
buf.append(") VALUES ( ");
if (compexpr != null)
addListExpr(buf, compexpr, CTX_VALUE, ", ");
if (compexpr != null && set != null)
buf.append(", ");
if (set != null)
addListExpr(buf, set, CTX_VALUE, ", ");
// End
buf.append(")");
// done
completeParamUsage();
return buf.toString();
}
/**
* Creates an update SQL-Statement
*
* @return an update SQL-Statement
*/
public String getUpdate()
{
resetParamUsage();
if (set == null)
return null;
StringBuilder buf = new StringBuilder("UPDATE ");
DBRowSet table = set.get(0).getTable();
if (joins!=null && !joins.isEmpty())
{ // Join Update
buf.append( table.getAlias() );
long context = CTX_DEFAULT;
// Set Expressions
buf.append("\r\nSET ");
addListExpr(buf, set, context, ", ");
// From clause
addFrom(buf);
// Add Where
addWhere(buf, context);
}
else
{ // Simple Statement
table.addSQL(buf, CTX_FULLNAME);
long context = CTX_NAME | CTX_VALUE;
// Set Expressions
buf.append("\r\nSET ");
addListExpr(buf, set, context, ", ");
// Add Where
addWhere(buf, context);
}
// done
completeParamUsage();
return buf.toString();
}
/**
* Creates a delete SQL-Statement
*
* @param table the table object
*
* @return a delete SQL-Statement
*/
public String getDelete(DBTable table)
{
resetParamUsage();
StringBuilder buf = new StringBuilder("DELETE ");
// joins or simple
if (joins!=null && !joins.isEmpty())
{ // delete with joins
table.addSQL(buf, CTX_FULLNAME);
// From clause
addFrom(buf);
// Add Where
addWhere(buf, CTX_DEFAULT);
}
else
{ // Simple Statement
buf.append("FROM ");
table.addSQL(buf, CTX_FULLNAME);
// where
addWhere(buf, CTX_NAME|CTX_VALUE);
}
// done
completeParamUsage();
return buf.toString();
}
// ------- Select Statement Parts -------
protected void addSelect(StringBuilder buf)
{
// Prepares statement
buf.append("SELECT ");
if (selectDistinct)
buf.append("DISTINCT ");
// Add Select Expressions
addListExpr(buf, select, CTX_ALL, ", ");
}
protected void addFrom(StringBuilder buf)
{
int originalLength = buf.length();
buf.append("\r\nFROM ");
// Join
boolean sep = false;
List<DBRowSet> tables = getRowSetList();
if (joins!=null && joins.size()>0)
{ // Join
List<DBRowSet> joinTables = new ArrayList<DBRowSet>();
for (int i=0; i<joins.size(); i++)
{ // append join
long context;
DBJoinExpr join = joins.get(i);
if (i<1)
{ // Add Join Tables
joinTables.add(join.getLeftTable());
joinTables.add(join.getRightTable());
// Remove from List
tables.remove(join.getLeftTable());
tables.remove(join.getRightTable());
// Context
context = CTX_NAME|CTX_VALUE;
}
else
{ // Extend the join
if ( joinTables.contains(join.getRightTable()))
join.reverse();
// Add Right Table
joinTables.add(join.getRightTable());
tables .remove(join.getRightTable());
// Context
context = CTX_VALUE;
buf.append( "\t" );
}
join.addSQL(buf, context);
// Merge subquery params
Object[] qryParams = join.getSubqueryParams();
if (qryParams!=null && qryParams.length>0)
{ // Subquery has parameters
if (cmdParams==null)
cmdParams= new ArrayList<DBCmdParam>(qryParams.length);
for (int p=0; p<qryParams.length; p++)
cmdParams.add(paramUsageCount++, new DBCmdParam(null, DataType.UNKNOWN, qryParams[p]));
}
// add CRLF
if( i!=joins.size()-1 )
buf.append("\r\n");
}
sep = true;
}
for (int i=0; i<tables.size(); i++)
{
if (sep) buf.append(", ");
DBRowSet t = tables.get(i);
t.addSQL(buf, CTX_DEFAULT|CTX_ALIAS);
sep = true;
}
if (sep==false)
{ // add pseudo table or omitt from
String pseudoTable = getDatabase().getDbms().getSQLPhrase(DBSqlPhrase.SQL_PSEUDO_TABLE);
if (StringUtils.isNotEmpty(pseudoTable))
{ // add pseudo table
buf.append(pseudoTable);
}
else
{ // remove from
buf.setLength(originalLength);
}
}
}
protected void addWhere(StringBuilder buf, long context)
{
if (where!=null && !where.isEmpty())
{
buf.append("\r\nWHERE ");
// add where expression
addListExpr(buf, where, context, " AND ");
}
}
protected final void addWhere(StringBuilder buf)
{
addWhere(buf, CTX_DEFAULT);
}
protected void addGrouping(StringBuilder buf)
{
if (groupBy!=null && !groupBy.isEmpty())
{ // Having
buf.append("\r\nGROUP BY ");
addListExpr(buf, groupBy, CTX_DEFAULT, ", ");
}
if (having!=null && !having.isEmpty())
{ // Having
buf.append("\r\nHAVING ");
addListExpr(buf, having, CTX_DEFAULT, " AND ");
}
}
protected void addOrder(StringBuilder buf)
{
if (orderBy!=null && !orderBy.isEmpty())
{ // order By
buf.append("\r\nORDER BY ");
addListExpr(buf, orderBy, CTX_DEFAULT, ", ");
}
}
} | EMPIREDB-362 Bugfix DBCommand mergeSubqueryParams
| empire-db/src/main/java/org/apache/empire/db/DBCommand.java | EMPIREDB-362 Bugfix DBCommand mergeSubqueryParams | <ide><path>mpire-db/src/main/java/org/apache/empire/db/DBCommand.java
<ide> }
<ide> join.addSQL(buf, context);
<ide> // Merge subquery params
<del> Object[] qryParams = join.getSubqueryParams();
<del> if (qryParams!=null && qryParams.length>0)
<del> { // Subquery has parameters
<del> if (cmdParams==null)
<del> cmdParams= new ArrayList<DBCmdParam>(qryParams.length);
<del> for (int p=0; p<qryParams.length; p++)
<del> cmdParams.add(paramUsageCount++, new DBCmdParam(null, DataType.UNKNOWN, qryParams[p]));
<del> }
<add> Object[] subQueryParams = join.getSubqueryParams();
<add> if (subQueryParams!=null)
<add> mergeSubqueryParams(subQueryParams);
<ide> // add CRLF
<ide> if( i!=joins.size()-1 )
<ide> buf.append("\r\n");
<ide> if (sep) buf.append(", ");
<ide> DBRowSet t = tables.get(i);
<ide> t.addSQL(buf, CTX_DEFAULT|CTX_ALIAS);
<add> // check for query
<add> if (t instanceof DBQuery)
<add> { // Merge subquery params
<add> mergeSubqueryParams(((DBQuery)t).getCommandExpr().getParamValues());
<add> }
<ide> sep = true;
<ide> }
<ide> if (sep==false)
<ide> }
<ide> }
<ide> }
<add>
<add> protected void mergeSubqueryParams(Object[] subQueryParams)
<add> {
<add> if (subQueryParams==null || subQueryParams.length==0)
<add> return;
<add> // Subquery has parameters
<add> if (cmdParams==null)
<add> cmdParams= new ArrayList<DBCmdParam>(subQueryParams.length);
<add> for (int p=0; p<subQueryParams.length; p++)
<add> cmdParams.add(paramUsageCount++, new DBCmdParam(null, DataType.UNKNOWN, subQueryParams[p]));
<add> }
<ide>
<ide> protected void addWhere(StringBuilder buf, long context)
<ide> { |
|
Java | apache-2.0 | 11027ae8e6efe052f05fa4e32501bb16e1491edd | 0 | consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo,consulo/consulo | /*
* Copyright 2000-2012 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.project.impl;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.notification.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathMacros;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.ComponentConfig;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.ServiceDescriptor;
import com.intellij.openapi.components.TrackingPathMacroSubstitutor;
import com.intellij.openapi.components.impl.ProjectPathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.impl.ExtensionAreaId;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.AsyncResult;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.FrameTitleBuilder;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.util.TimedReference;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import consulo.application.AccessRule;
import consulo.components.impl.PlatformComponentManagerImpl;
import consulo.components.impl.stores.*;
import consulo.container.plugin.PluginDescriptor;
import consulo.injecting.InjectingContainerBuilder;
import consulo.ui.RequiredUIAccess;
import consulo.ui.UIAccess;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
public class ProjectImpl extends PlatformComponentManagerImpl implements ProjectEx {
private static final Logger LOG = Logger.getInstance(ProjectImpl.class);
private static final ExtensionPointName<ServiceDescriptor> PROJECT_SERVICES = ExtensionPointName.create("com.intellij.projectService");
public static final String NAME_FILE = ".name";
private final ProjectManager myManager;
private MyProjectManagerListener myProjectManagerListener;
private final AtomicBoolean mySavingInProgress = new AtomicBoolean(false);
public boolean myOptimiseTestLoadSpeed;
private String myName;
public static Key<Long> CREATION_TIME = Key.create("ProjectImpl.CREATION_TIME");
public static final Key<String> CREATION_TRACE = Key.create("ProjectImpl.CREATION_TRACE");
private final List<ProjectComponent> myProjectComponents = new CopyOnWriteArrayList<>();
protected ProjectImpl(@Nonnull ProjectManager manager, @Nonnull String dirPath, boolean isOptimiseTestLoadSpeed, String projectName, boolean noUIThread) {
super(ApplicationManager.getApplication(), "Project " + (projectName == null ? dirPath : projectName), ExtensionAreaId.PROJECT);
putUserData(CREATION_TIME, System.nanoTime());
if (ApplicationManager.getApplication().isUnitTestMode()) {
putUserData(CREATION_TRACE, DebugUtil.currentStackTrace());
}
if (!isDefault()) {
if (noUIThread) {
getStateStore().setProjectFilePathNoUI(dirPath);
}
else {
getStateStore().setProjectFilePath(dirPath);
}
}
myOptimiseTestLoadSpeed = isOptimiseTestLoadSpeed;
myManager = manager;
myName = projectName;
}
@Nullable
@Override
protected ExtensionPointName<ServiceDescriptor> getServiceExtensionPointName() {
return PROJECT_SERVICES;
}
@Nonnull
@Override
protected List<ComponentConfig> getComponentConfigs(PluginDescriptor ideaPluginDescriptor) {
return ideaPluginDescriptor.getProjectComponents();
}
@Override
public void setProjectName(@Nonnull String projectName) {
String name = getName();
if (!projectName.equals(name)) {
myName = projectName;
StartupManager.getInstance(this).runWhenProjectIsInitialized(new DumbAwareRunnable() {
@Override
public void run() {
if (isDisposed()) return;
JFrame frame = WindowManager.getInstance().getFrame(ProjectImpl.this);
String title = FrameTitleBuilder.getInstance().getProjectTitle(ProjectImpl.this);
if (frame != null && title != null) {
frame.setTitle(title);
}
}
});
}
}
@Override
protected void bootstrapInjectingContainer(@Nonnull InjectingContainerBuilder builder) {
super.bootstrapInjectingContainer(builder);
builder.bind(Project.class).to(this);
builder.bind(ProjectEx.class).to(this);
builder.bind(ProjectPathMacroManager.class).to(ProjectPathMacroManager.class).forceSingleton();
final Class<? extends IProjectStore> storeClass = isDefault() ? DefaultProjectStoreImpl.class : ProjectStoreImpl.class;
builder.bind(IProjectStore.class).to(storeClass).forceSingleton();
}
@Nonnull
@Override
public IProjectStore getStateStore() {
return getComponent(IProjectStore.class);
}
@Override
protected void notifyAboutInitialization(float percentOfLoad, Object component) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText2(getComponentName(component));
}
if (component instanceof ProjectComponent) {
myProjectComponents.add((ProjectComponent)component);
}
}
@Override
public boolean isOpen() {
return ProjectManagerEx.getInstanceEx().isProjectOpened(this);
}
@Override
public boolean isInitialized() {
return isOpen() && !isDisposed() && StartupManagerEx.getInstanceEx(this).startupActivityPassed();
}
@Override
@Nonnull
public String getProjectFilePath() {
return getStateStore().getProjectFilePath();
}
@Override
public VirtualFile getProjectFile() {
return getStateStore().getProjectFile();
}
@Override
public VirtualFile getBaseDir() {
return getStateStore().getProjectBaseDir();
}
@Override
public String getBasePath() {
return getStateStore().getProjectBasePath();
}
@Nonnull
@Override
public String getName() {
if(myName == null) {
myName = getStateStore().getProjectName();
}
return myName;
}
@NonNls
@Override
public String getPresentableUrl() {
return getStateStore().getPresentableUrl();
}
@Nonnull
@NonNls
@Override
public String getLocationHash() {
String str = getPresentableUrl();
if (str == null) str = getName();
final String prefix = !isDefault() ? "" : getName();
return prefix + Integer.toHexString(str.hashCode());
}
@Override
@Nullable
public VirtualFile getWorkspaceFile() {
return getStateStore().getWorkspaceFile();
}
@Override
public boolean isOptimiseTestLoadSpeed() {
return myOptimiseTestLoadSpeed;
}
@Override
public void setOptimiseTestLoadSpeed(final boolean optimiseTestLoadSpeed) {
myOptimiseTestLoadSpeed = optimiseTestLoadSpeed;
}
@Override
public void initNotLazyServices() {
long start = System.currentTimeMillis();
// ProfilingUtil.startCPUProfiling();
super.initNotLazyServices();
// ProfilingUtil.captureCPUSnapshot();
long time = System.currentTimeMillis() - start;
LOG.info(getNotLazyServicesCount() + " project components initialized in " + time + " ms");
getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).projectComponentsInitialized(this);
myProjectManagerListener = new MyProjectManagerListener();
myManager.addProjectManagerListener(this, myProjectManagerListener);
}
@Override
public void save() {
if (ApplicationManagerEx.getApplicationEx().isDoNotSave()) {
// no need to save
return;
}
if (!mySavingInProgress.compareAndSet(false, true)) {
return;
}
HeavyProcessLatch.INSTANCE.prioritizeUiActivity();
try {
if (!isDefault()) {
String projectBasePath = getStateStore().getProjectBasePath();
if (projectBasePath != null) {
File projectDir = new File(projectBasePath);
File nameFile = new File(projectDir, DIRECTORY_STORE_FOLDER + "/" + NAME_FILE);
if (!projectDir.getName().equals(getName())) {
try {
FileUtil.writeToFile(nameFile, getName());
}
catch (IOException e) {
LOG.error("Unable to store project name", e);
}
}
else {
FileUtil.delete(nameFile);
}
}
}
StoreUtil.save(getStateStore(), this);
}
finally {
mySavingInProgress.set(false);
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectSaved.TOPIC).saved(this);
}
}
@Nonnull
@Override
public AsyncResult<Void> saveAsync(@Nonnull UIAccess uiAccess) {
return AccessRule.writeAsync(() -> saveAsyncImpl(uiAccess));
}
private void saveAsyncImpl(@Nonnull UIAccess uiAccess) {
if (ApplicationManagerEx.getApplicationEx().isDoNotSave()) {
// no need to save
return;
}
if (!mySavingInProgress.compareAndSet(false, true)) {
return;
}
//HeavyProcessLatch.INSTANCE.prioritizeUiActivity();
try {
if (!isDefault()) {
String projectBasePath = getStateStore().getProjectBasePath();
if (projectBasePath != null) {
File projectDir = new File(projectBasePath);
File nameFile = new File(projectDir, DIRECTORY_STORE_FOLDER + "/" + NAME_FILE);
if (!projectDir.getName().equals(getName())) {
try {
FileUtil.writeToFile(nameFile, getName());
}
catch (IOException e) {
LOG.error("Unable to store project name", e);
}
}
else {
FileUtil.delete(nameFile);
}
}
}
StoreUtil.saveAsync(getStateStore(), uiAccess, this);
}
finally {
mySavingInProgress.set(false);
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectSaved.TOPIC).saved(this);
}
}
@RequiredUIAccess
@Override
public void dispose() {
Application application = Application.get();
assert application.isWriteAccessAllowed(); // dispose must be under write action
// can call dispose only via com.intellij.ide.impl.ProjectUtil.closeAndDispose()
LOG.assertTrue(application.isUnitTestMode() || !ProjectManagerEx.getInstanceEx().isProjectOpened(this));
LOG.assertTrue(!isDisposed());
if (myProjectManagerListener != null) {
myManager.removeProjectManagerListener(this, myProjectManagerListener);
}
myProjectManagerListener = null;
if (!application.isDisposed()) {
application.getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).afterProjectClosed(this);
}
super.dispose();
TimedReference.disposeTimed();
}
private void projectOpened() {
for (ProjectComponent component : myProjectComponents) {
try {
component.projectOpened();
}
catch (Throwable e) {
LOG.error(component.toString(), e);
}
}
}
private void projectClosed() {
List<ProjectComponent> components = new ArrayList<>(myProjectComponents);
Collections.reverse(components);
for (ProjectComponent component : components) {
try {
component.projectClosed();
}
catch (Throwable e) {
LOG.error(e);
}
}
}
private class MyProjectManagerListener extends ProjectManagerAdapter {
@Override
public void projectOpened(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
LOG.assertTrue(project == ProjectImpl.this);
ProjectImpl.this.projectOpened();
}
@Override
public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
LOG.assertTrue(project == ProjectImpl.this);
ProjectImpl.this.projectClosed();
}
}
@Override
public boolean isDefault() {
return false;
}
@Override
public void checkUnknownMacros(final boolean showDialog) {
final IProjectStore stateStore = getStateStore();
final TrackingPathMacroSubstitutor[] substitutors = stateStore.getSubstitutors();
final Set<String> unknownMacros = new HashSet<>();
for (final TrackingPathMacroSubstitutor substitutor : substitutors) {
unknownMacros.addAll(substitutor.getUnknownMacros(null));
}
if (!unknownMacros.isEmpty()) {
if (!showDialog || ProjectMacrosUtil.checkMacros(this, new HashSet<>(unknownMacros))) {
final PathMacros pathMacros = PathMacros.getInstance();
final Set<String> macros2invalidate = new HashSet<>(unknownMacros);
for (Iterator it = macros2invalidate.iterator(); it.hasNext(); ) {
final String macro = (String)it.next();
final String value = pathMacros.getValue(macro);
if ((value == null || value.trim().isEmpty()) && !pathMacros.isIgnoredMacroName(macro)) {
it.remove();
}
}
if (!macros2invalidate.isEmpty()) {
final Set<String> components = new HashSet<>();
for (TrackingPathMacroSubstitutor substitutor : substitutors) {
components.addAll(substitutor.getComponents(macros2invalidate));
}
for (final TrackingPathMacroSubstitutor substitutor : substitutors) {
substitutor.invalidateUnknownMacros(macros2invalidate);
}
final UnknownMacroNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnknownMacroNotification.class, this);
for (final UnknownMacroNotification notification : notifications) {
if (macros2invalidate.containsAll(notification.getMacros())) notification.expire();
}
ApplicationManager.getApplication().runWriteAction(() -> stateStore.reinitComponents(components, true));
}
}
}
}
@NonNls
@Override
public String toString() {
return "Project" +
(isDisposed() ? " (Disposed" + (temporarilyDisposed ? " temporarily" : "") + ")" : isDefault() ? "" : " '" + getPresentableUrl() + "'") +
(isDefault() ? " (Default)" : "") +
" " +
myName;
}
public static void dropUnableToSaveProjectNotification(@Nonnull final Project project, Collection<File> readOnlyFiles) {
final UnableToSaveProjectNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification.class, project);
if (notifications.length == 0) {
Notifications.Bus.notify(new UnableToSaveProjectNotification(project, readOnlyFiles), project);
}
}
public static class UnableToSaveProjectNotification extends Notification {
private Project myProject;
private final List<String> myFileNames;
private UnableToSaveProjectNotification(@Nonnull final Project project, final Collection<File> readOnlyFiles) {
super("Project Settings", "Could not save project!", buildMessage(), NotificationType.ERROR, new NotificationListener() {
@Override
public void hyperlinkUpdate(@Nonnull Notification notification, @Nonnull HyperlinkEvent event) {
final UnableToSaveProjectNotification unableToSaveProjectNotification = (UnableToSaveProjectNotification)notification;
final Project _project = unableToSaveProjectNotification.getProject();
notification.expire();
if (_project != null && !_project.isDisposed()) {
_project.save();
}
}
});
myProject = project;
myFileNames = ContainerUtil.map(readOnlyFiles, File::getPath);
}
public List<String> getFileNames() {
return myFileNames;
}
private static String buildMessage() {
final StringBuilder sb = new StringBuilder("<p>Unable to save project files. Please ensure project files are writable and you have permissions to modify them.");
return sb.append(" <a href=\"\">Try to save project again</a>.</p>").toString();
}
public Project getProject() {
return myProject;
}
@Override
public void expire() {
myProject = null;
super.expire();
}
}
}
| modules/base/platform-impl/src/main/java/com/intellij/openapi/project/impl/ProjectImpl.java | /*
* Copyright 2000-2012 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.project.impl;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.notification.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathMacros;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.components.ComponentConfig;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.components.ServiceDescriptor;
import com.intellij.openapi.components.TrackingPathMacroSubstitutor;
import com.intellij.openapi.components.impl.ProjectPathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.impl.ExtensionAreaId;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.AsyncResult;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.impl.FrameTitleBuilder;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.util.TimedReference;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import consulo.application.AccessRule;
import consulo.components.impl.PlatformComponentManagerImpl;
import consulo.components.impl.stores.*;
import consulo.container.plugin.PluginDescriptor;
import consulo.injecting.InjectingContainerBuilder;
import consulo.ui.RequiredUIAccess;
import consulo.ui.UIAccess;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
public class ProjectImpl extends PlatformComponentManagerImpl implements ProjectEx {
private static final Logger LOG = Logger.getInstance(ProjectImpl.class);
private static final ExtensionPointName<ServiceDescriptor> PROJECT_SERVICES = ExtensionPointName.create("com.intellij.projectService");
public static final String NAME_FILE = ".name";
private ProjectManager myManager;
private MyProjectManagerListener myProjectManagerListener;
private final AtomicBoolean mySavingInProgress = new AtomicBoolean(false);
public boolean myOptimiseTestLoadSpeed;
@NonNls
public static final String TEMPLATE_PROJECT_NAME = "Default (Template) Project";
private String myName;
public static Key<Long> CREATION_TIME = Key.create("ProjectImpl.CREATION_TIME");
public static final Key<String> CREATION_TRACE = Key.create("ProjectImpl.CREATION_TRACE");
private final List<ProjectComponent> myProjectComponents = new CopyOnWriteArrayList<>();
protected ProjectImpl(@Nonnull ProjectManager manager, @Nonnull String dirPath, boolean isOptimiseTestLoadSpeed, String projectName, boolean noUIThread) {
super(ApplicationManager.getApplication(), "Project " + (projectName == null ? dirPath : projectName), ExtensionAreaId.PROJECT);
putUserData(CREATION_TIME, System.nanoTime());
if (ApplicationManager.getApplication().isUnitTestMode()) {
putUserData(CREATION_TRACE, DebugUtil.currentStackTrace());
}
if (!isDefault()) {
if (noUIThread) {
getStateStore().setProjectFilePathNoUI(dirPath);
}
else {
getStateStore().setProjectFilePath(dirPath);
}
}
myOptimiseTestLoadSpeed = isOptimiseTestLoadSpeed;
myManager = manager;
myName = isDefault() ? TEMPLATE_PROJECT_NAME : projectName == null ? getStateStore().getProjectName() : projectName;
}
@Nullable
@Override
protected ExtensionPointName<ServiceDescriptor> getServiceExtensionPointName() {
return PROJECT_SERVICES;
}
@Nonnull
@Override
protected List<ComponentConfig> getComponentConfigs(PluginDescriptor ideaPluginDescriptor) {
return ideaPluginDescriptor.getProjectComponents();
}
@Override
public void setProjectName(@Nonnull String projectName) {
if (!projectName.equals(myName)) {
myName = projectName;
StartupManager.getInstance(this).runWhenProjectIsInitialized(new DumbAwareRunnable() {
@Override
public void run() {
if (isDisposed()) return;
JFrame frame = WindowManager.getInstance().getFrame(ProjectImpl.this);
String title = FrameTitleBuilder.getInstance().getProjectTitle(ProjectImpl.this);
if (frame != null && title != null) {
frame.setTitle(title);
}
}
});
}
}
@Override
protected void bootstrapInjectingContainer(@Nonnull InjectingContainerBuilder builder) {
super.bootstrapInjectingContainer(builder);
builder.bind(Project.class).to(this);
builder.bind(ProjectEx.class).to(this);
builder.bind(ProjectPathMacroManager.class).to(ProjectPathMacroManager.class).forceSingleton();
final Class<? extends IProjectStore> storeClass = isDefault() ? DefaultProjectStoreImpl.class : ProjectStoreImpl.class;
builder.bind(IProjectStore.class).to(storeClass).forceSingleton();
}
@Nonnull
@Override
public IProjectStore getStateStore() {
return getComponent(IProjectStore.class);
}
@Override
protected void notifyAboutInitialization(float percentOfLoad, Object component) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText2(getComponentName(component));
}
if (component instanceof ProjectComponent) {
myProjectComponents.add((ProjectComponent)component);
}
}
@Override
public boolean isOpen() {
return ProjectManagerEx.getInstanceEx().isProjectOpened(this);
}
@Override
public boolean isInitialized() {
return isOpen() && !isDisposed() && StartupManagerEx.getInstanceEx(this).startupActivityPassed();
}
@Override
@Nonnull
public String getProjectFilePath() {
return getStateStore().getProjectFilePath();
}
@Override
public VirtualFile getProjectFile() {
return getStateStore().getProjectFile();
}
@Override
public VirtualFile getBaseDir() {
return getStateStore().getProjectBaseDir();
}
@Override
public String getBasePath() {
return getStateStore().getProjectBasePath();
}
@Nonnull
@Override
public String getName() {
return myName;
}
@NonNls
@Override
public String getPresentableUrl() {
if (myName == null) return null; // not yet initialized
return getStateStore().getPresentableUrl();
}
@Nonnull
@NonNls
@Override
public String getLocationHash() {
String str = getPresentableUrl();
if (str == null) str = getName();
final String prefix = !isDefault() ? "" : getName();
return prefix + Integer.toHexString(str.hashCode());
}
@Override
@Nullable
public VirtualFile getWorkspaceFile() {
return getStateStore().getWorkspaceFile();
}
@Override
public boolean isOptimiseTestLoadSpeed() {
return myOptimiseTestLoadSpeed;
}
@Override
public void setOptimiseTestLoadSpeed(final boolean optimiseTestLoadSpeed) {
myOptimiseTestLoadSpeed = optimiseTestLoadSpeed;
}
@Override
public void initNotLazyServices() {
long start = System.currentTimeMillis();
// ProfilingUtil.startCPUProfiling();
super.initNotLazyServices();
// ProfilingUtil.captureCPUSnapshot();
long time = System.currentTimeMillis() - start;
LOG.info(getNotLazyServicesCount() + " project components initialized in " + time + " ms");
getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).projectComponentsInitialized(this);
myProjectManagerListener = new MyProjectManagerListener();
myManager.addProjectManagerListener(this, myProjectManagerListener);
}
@Override
public void save() {
if (ApplicationManagerEx.getApplicationEx().isDoNotSave()) {
// no need to save
return;
}
if (!mySavingInProgress.compareAndSet(false, true)) {
return;
}
HeavyProcessLatch.INSTANCE.prioritizeUiActivity();
try {
if (!isDefault()) {
String projectBasePath = getStateStore().getProjectBasePath();
if (projectBasePath != null) {
File projectDir = new File(projectBasePath);
File nameFile = new File(projectDir, DIRECTORY_STORE_FOLDER + "/" + NAME_FILE);
if (!projectDir.getName().equals(getName())) {
try {
FileUtil.writeToFile(nameFile, getName());
}
catch (IOException e) {
LOG.error("Unable to store project name", e);
}
}
else {
FileUtil.delete(nameFile);
}
}
}
StoreUtil.save(getStateStore(), this);
}
finally {
mySavingInProgress.set(false);
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectSaved.TOPIC).saved(this);
}
}
@Nonnull
@Override
public AsyncResult<Void> saveAsync(@Nonnull UIAccess uiAccess) {
return AccessRule.writeAsync(() -> saveAsyncImpl(uiAccess));
}
private void saveAsyncImpl(@Nonnull UIAccess uiAccess) {
if (ApplicationManagerEx.getApplicationEx().isDoNotSave()) {
// no need to save
return;
}
if (!mySavingInProgress.compareAndSet(false, true)) {
return;
}
//HeavyProcessLatch.INSTANCE.prioritizeUiActivity();
try {
if (!isDefault()) {
String projectBasePath = getStateStore().getProjectBasePath();
if (projectBasePath != null) {
File projectDir = new File(projectBasePath);
File nameFile = new File(projectDir, DIRECTORY_STORE_FOLDER + "/" + NAME_FILE);
if (!projectDir.getName().equals(getName())) {
try {
FileUtil.writeToFile(nameFile, getName());
}
catch (IOException e) {
LOG.error("Unable to store project name", e);
}
}
else {
FileUtil.delete(nameFile);
}
}
}
StoreUtil.saveAsync(getStateStore(), uiAccess, this);
}
finally {
mySavingInProgress.set(false);
ApplicationManager.getApplication().getMessageBus().syncPublisher(ProjectSaved.TOPIC).saved(this);
}
}
@RequiredUIAccess
@Override
public void dispose() {
Application application = Application.get();
assert application.isWriteAccessAllowed(); // dispose must be under write action
// can call dispose only via com.intellij.ide.impl.ProjectUtil.closeAndDispose()
LOG.assertTrue(application.isUnitTestMode() || !ProjectManagerEx.getInstanceEx().isProjectOpened(this));
LOG.assertTrue(!isDisposed());
if (myProjectManagerListener != null) {
myManager.removeProjectManagerListener(this, myProjectManagerListener);
}
myManager = null;
myName = null;
myProjectManagerListener = null;
if (!application.isDisposed()) {
application.getMessageBus().syncPublisher(ProjectLifecycleListener.TOPIC).afterProjectClosed(this);
}
super.dispose();
TimedReference.disposeTimed();
}
private void projectOpened() {
for (ProjectComponent component : myProjectComponents) {
try {
component.projectOpened();
}
catch (Throwable e) {
LOG.error(component.toString(), e);
}
}
}
private void projectClosed() {
List<ProjectComponent> components = new ArrayList<>(myProjectComponents);
Collections.reverse(components);
for (ProjectComponent component : components) {
try {
component.projectClosed();
}
catch (Throwable e) {
LOG.error(e);
}
}
}
private class MyProjectManagerListener extends ProjectManagerAdapter {
@Override
public void projectOpened(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
LOG.assertTrue(project == ProjectImpl.this);
ProjectImpl.this.projectOpened();
}
@Override
public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
LOG.assertTrue(project == ProjectImpl.this);
ProjectImpl.this.projectClosed();
}
}
@Override
public boolean isDefault() {
return false;
}
@Override
public void checkUnknownMacros(final boolean showDialog) {
final IProjectStore stateStore = getStateStore();
final TrackingPathMacroSubstitutor[] substitutors = stateStore.getSubstitutors();
final Set<String> unknownMacros = new HashSet<>();
for (final TrackingPathMacroSubstitutor substitutor : substitutors) {
unknownMacros.addAll(substitutor.getUnknownMacros(null));
}
if (!unknownMacros.isEmpty()) {
if (!showDialog || ProjectMacrosUtil.checkMacros(this, new HashSet<>(unknownMacros))) {
final PathMacros pathMacros = PathMacros.getInstance();
final Set<String> macros2invalidate = new HashSet<>(unknownMacros);
for (Iterator it = macros2invalidate.iterator(); it.hasNext(); ) {
final String macro = (String)it.next();
final String value = pathMacros.getValue(macro);
if ((value == null || value.trim().isEmpty()) && !pathMacros.isIgnoredMacroName(macro)) {
it.remove();
}
}
if (!macros2invalidate.isEmpty()) {
final Set<String> components = new HashSet<>();
for (TrackingPathMacroSubstitutor substitutor : substitutors) {
components.addAll(substitutor.getComponents(macros2invalidate));
}
for (final TrackingPathMacroSubstitutor substitutor : substitutors) {
substitutor.invalidateUnknownMacros(macros2invalidate);
}
final UnknownMacroNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnknownMacroNotification.class, this);
for (final UnknownMacroNotification notification : notifications) {
if (macros2invalidate.containsAll(notification.getMacros())) notification.expire();
}
ApplicationManager.getApplication().runWriteAction(() -> stateStore.reinitComponents(components, true));
}
}
}
}
@NonNls
@Override
public String toString() {
return "Project" +
(isDisposed() ? " (Disposed" + (temporarilyDisposed ? " temporarily" : "") + ")" : isDefault() ? "" : " '" + getPresentableUrl() + "'") +
(isDefault() ? " (Default)" : "") +
" " +
myName;
}
public static void dropUnableToSaveProjectNotification(@Nonnull final Project project, Collection<File> readOnlyFiles) {
final UnableToSaveProjectNotification[] notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification.class, project);
if (notifications.length == 0) {
Notifications.Bus.notify(new UnableToSaveProjectNotification(project, readOnlyFiles), project);
}
}
public static class UnableToSaveProjectNotification extends Notification {
private Project myProject;
private final List<String> myFileNames;
private UnableToSaveProjectNotification(@Nonnull final Project project, final Collection<File> readOnlyFiles) {
super("Project Settings", "Could not save project!", buildMessage(), NotificationType.ERROR, new NotificationListener() {
@Override
public void hyperlinkUpdate(@Nonnull Notification notification, @Nonnull HyperlinkEvent event) {
final UnableToSaveProjectNotification unableToSaveProjectNotification = (UnableToSaveProjectNotification)notification;
final Project _project = unableToSaveProjectNotification.getProject();
notification.expire();
if (_project != null && !_project.isDisposed()) {
_project.save();
}
}
});
myProject = project;
myFileNames = ContainerUtil.map(readOnlyFiles, File::getPath);
}
public List<String> getFileNames() {
return myFileNames;
}
private static String buildMessage() {
final StringBuilder sb = new StringBuilder("<p>Unable to save project files. Please ensure project files are writable and you have permissions to modify them.");
return sb.append(" <a href=\"\">Try to save project again</a>.</p>").toString();
}
public Project getProject() {
return myProject;
}
@Override
public void expire() {
myProject = null;
super.expire();
}
}
}
| project name must be always not null - fix assertion
| modules/base/platform-impl/src/main/java/com/intellij/openapi/project/impl/ProjectImpl.java | project name must be always not null - fix assertion | <ide><path>odules/base/platform-impl/src/main/java/com/intellij/openapi/project/impl/ProjectImpl.java
<ide>
<ide> public static final String NAME_FILE = ".name";
<ide>
<del> private ProjectManager myManager;
<add> private final ProjectManager myManager;
<ide>
<ide> private MyProjectManagerListener myProjectManagerListener;
<ide>
<ide> private final AtomicBoolean mySavingInProgress = new AtomicBoolean(false);
<ide>
<ide> public boolean myOptimiseTestLoadSpeed;
<del> @NonNls
<del> public static final String TEMPLATE_PROJECT_NAME = "Default (Template) Project";
<ide>
<ide> private String myName;
<ide>
<ide>
<ide> myManager = manager;
<ide>
<del> myName = isDefault() ? TEMPLATE_PROJECT_NAME : projectName == null ? getStateStore().getProjectName() : projectName;
<add> myName = projectName;
<ide> }
<ide>
<ide> @Nullable
<ide>
<ide> @Override
<ide> public void setProjectName(@Nonnull String projectName) {
<del> if (!projectName.equals(myName)) {
<add> String name = getName();
<add>
<add> if (!projectName.equals(name)) {
<ide> myName = projectName;
<ide> StartupManager.getInstance(this).runWhenProjectIsInitialized(new DumbAwareRunnable() {
<ide> @Override
<ide> @Nonnull
<ide> @Override
<ide> public String getName() {
<add> if(myName == null) {
<add> myName = getStateStore().getProjectName();
<add> }
<ide> return myName;
<ide> }
<ide>
<ide> @NonNls
<ide> @Override
<ide> public String getPresentableUrl() {
<del> if (myName == null) return null; // not yet initialized
<ide> return getStateStore().getPresentableUrl();
<ide> }
<ide>
<ide> myManager.removeProjectManagerListener(this, myProjectManagerListener);
<ide> }
<ide>
<del> myManager = null;
<del> myName = null;
<ide> myProjectManagerListener = null;
<ide>
<ide> if (!application.isDisposed()) { |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/innoq/qmqp/testserver/QMQPTestServer.java' did not match any file(s) known to git
| 9e623b7f6293cc082c1f3b18081f852ac301b0db | 1 | innoq/QMQP-Java | /*
Copyright (C) 2012 innoQ Deutschland GmbH
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.innoq.qmqp.testserver;
import com.innoq.qmqp.codec.RequestCodec;
import com.innoq.qmqp.codec.ResponseCodec;
import com.innoq.qmqp.protocol.QMQPException;
import com.innoq.qmqp.protocol.Request;
import com.innoq.qmqp.protocol.Response;
import com.innoq.qmqp.protocol.ReturnCode;
import com.innoq.qmqp.util.IOUtil;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Rudimentary QMQP-Server not suitable for any sort of production use
* in any way.
*/
public class QMQPTestServer {
/**
* Callback invoked by the server for each request.
*/
public static interface TestRequestHandler {
public Response handle(Request r) throws QMQPException;
}
private final int port;
private ServerSocket server;
/**
* Initializes but doesn't start the server to listen on the given port.
*/
public QMQPTestServer(int port) {
this.port = port;
}
/**
* Starts the server, handles a single request and then shuts down
* the server again.
*/
public void handleOneRequest(TestRequestHandler handler) {
Socket client = null;
InputStream in = null;
OutputStream out = null;
try {
server = new ServerSocket(port);
client = server.accept();
if (handler == null) {
throw new QMQPException("missing handler");
}
in = client.getInputStream();
out = client.getOutputStream();
RequestCodec req = new RequestCodec();
ResponseCodec res = new ResponseCodec();
try {
out.write(res.toNetwork(handler
.handle(req
.fromNetwork(IOUtil
.readFully(in)))));
} catch (QMQPException q) {
out.write(res.toNetwork(new Response(ReturnCode.PERM_FAIL,
q.getMessage())));
}
} catch (IOException ex) {
throw new QMQPException("exception in server", ex);
} finally {
IOUtil.close(in, true);
IOUtil.close(out, true);
IOUtil.close(client, true);
stop();
}
}
/**
* Shuts down the server if it is running, swallows any exception.
*/
public void stop() {
IOUtil.close(server, true);
server = null;
}
} | src/test/java/com/innoq/qmqp/testserver/QMQPTestServer.java | rudimentary - and untested - test server
| src/test/java/com/innoq/qmqp/testserver/QMQPTestServer.java | rudimentary - and untested - test server | <ide><path>rc/test/java/com/innoq/qmqp/testserver/QMQPTestServer.java
<add>/*
<add> Copyright (C) 2012 innoQ Deutschland GmbH
<add>
<add> Licensed under the Apache License, Version 2.0 (the "License");
<add> you may not use this file except in compliance with the License.
<add> You may obtain a copy of the License at
<add>
<add> http://www.apache.org/licenses/LICENSE-2.0
<add>
<add> Unless required by applicable law or agreed to in writing, software
<add> distributed under the License is distributed on an "AS IS" BASIS,
<add> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> See the License for the specific language governing permissions and
<add> limitations under the License.
<add>*/
<add>
<add>package com.innoq.qmqp.testserver;
<add>
<add>import com.innoq.qmqp.codec.RequestCodec;
<add>import com.innoq.qmqp.codec.ResponseCodec;
<add>import com.innoq.qmqp.protocol.QMQPException;
<add>import com.innoq.qmqp.protocol.Request;
<add>import com.innoq.qmqp.protocol.Response;
<add>import com.innoq.qmqp.protocol.ReturnCode;
<add>import com.innoq.qmqp.util.IOUtil;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.io.OutputStream;
<add>import java.net.ServerSocket;
<add>import java.net.Socket;
<add>
<add>/**
<add> * Rudimentary QMQP-Server not suitable for any sort of production use
<add> * in any way.
<add> */
<add>public class QMQPTestServer {
<add>
<add> /**
<add> * Callback invoked by the server for each request.
<add> */
<add> public static interface TestRequestHandler {
<add> public Response handle(Request r) throws QMQPException;
<add> }
<add>
<add> private final int port;
<add> private ServerSocket server;
<add>
<add> /**
<add> * Initializes but doesn't start the server to listen on the given port.
<add> */
<add> public QMQPTestServer(int port) {
<add> this.port = port;
<add> }
<add>
<add> /**
<add> * Starts the server, handles a single request and then shuts down
<add> * the server again.
<add> */
<add> public void handleOneRequest(TestRequestHandler handler) {
<add> Socket client = null;
<add> InputStream in = null;
<add> OutputStream out = null;
<add> try {
<add> server = new ServerSocket(port);
<add> client = server.accept();
<add> if (handler == null) {
<add> throw new QMQPException("missing handler");
<add> }
<add> in = client.getInputStream();
<add> out = client.getOutputStream();
<add> RequestCodec req = new RequestCodec();
<add> ResponseCodec res = new ResponseCodec();
<add> try {
<add> out.write(res.toNetwork(handler
<add> .handle(req
<add> .fromNetwork(IOUtil
<add> .readFully(in)))));
<add> } catch (QMQPException q) {
<add> out.write(res.toNetwork(new Response(ReturnCode.PERM_FAIL,
<add> q.getMessage())));
<add> }
<add> } catch (IOException ex) {
<add> throw new QMQPException("exception in server", ex);
<add> } finally {
<add> IOUtil.close(in, true);
<add> IOUtil.close(out, true);
<add> IOUtil.close(client, true);
<add> stop();
<add> }
<add> }
<add>
<add> /**
<add> * Shuts down the server if it is running, swallows any exception.
<add> */
<add> public void stop() {
<add> IOUtil.close(server, true);
<add> server = null;
<add> }
<add>
<add>} |
|
Java | mit | fd5d28e89c4c7e91323e59f31d1b11b0910c9f81 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.application.workflow.actions;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.resource.ApplicationEvent;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.transactional.SectionStatusService;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.form.resource.SectionResource;
import org.innovateuk.ifs.form.transactional.SectionService;
import org.springframework.statemachine.StateContext;
import org.springframework.stereotype.Component;
import static org.innovateuk.ifs.form.resource.SectionType.TERMS_AND_CONDITIONS;
/**
* Auto mark-as-complete terms and conditions for EOI competitions
*/
@Component
public class AutoCompleteSectionsAction extends BaseApplicationAction {
private final SectionService sectionService;
private final SectionStatusService sectionStatusService;
public AutoCompleteSectionsAction(SectionService sectionService, SectionStatusService sectionStatusService) {
this.sectionService = sectionService;
this.sectionStatusService = sectionStatusService;
}
@Override
protected void doExecute(final Application application,
final StateContext<ApplicationState, ApplicationEvent> context) {
Competition competition = application.getCompetition();
if (competition.getCompetitionType().isExpressionOfInterest()) {
long termsSectionId = sectionService.getSectionsByCompetitionIdAndType(competition.getId(), TERMS_AND_CONDITIONS)
.getSuccess()
.stream()
.findFirst()
.map(SectionResource::getId)
.get();
completeTermsAndConditions(application, termsSectionId);
}
}
private void completeTermsAndConditions(Application application, long termsSectionId) {
sectionStatusService.markSectionAsComplete(termsSectionId, application.getId(), application.getLeadApplicantProcessRole().getId());
}
} | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/workflow/actions/AutoCompleteSectionsAction.java | package org.innovateuk.ifs.application.workflow.actions;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.resource.ApplicationEvent;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.transactional.SectionStatusService;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.form.resource.SectionResource;
import org.innovateuk.ifs.form.transactional.SectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateContext;
import org.springframework.stereotype.Component;
import static org.innovateuk.ifs.form.resource.SectionType.TERMS_AND_CONDITIONS;
/**
* Auto mark-as-complete terms and conditions for EOI competitions
*/
@Component
public class AutoCompleteSectionsAction extends BaseApplicationAction {
@Autowired
private SectionService sectionService;
@Autowired
private SectionStatusService sectionStatusService;
@Override
protected void doExecute(final Application application,
final StateContext<ApplicationState, ApplicationEvent> context) {
Competition competition = application.getCompetition();
if (competition.getCompetitionType().isExpressionOfInterest()) {
long termsSectionId = sectionService.getSectionsByCompetitionIdAndType(competition.getId(), TERMS_AND_CONDITIONS)
.getSuccess()
.stream()
.findFirst()
.map(SectionResource::getId)
.get();
completeTermsAndConditions(application, termsSectionId);
}
}
private void completeTermsAndConditions(Application application, long termsSectionId) {
sectionStatusService.markSectionAsComplete(termsSectionId, application.getId(), application.getLeadApplicantProcessRole().getId());
}
} | IFS-5989 - Moves field injection to constructor on AutoCompleteSectionsAction
| ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/workflow/actions/AutoCompleteSectionsAction.java | IFS-5989 - Moves field injection to constructor on AutoCompleteSectionsAction | <ide><path>fs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/workflow/actions/AutoCompleteSectionsAction.java
<ide> import org.innovateuk.ifs.competition.domain.Competition;
<ide> import org.innovateuk.ifs.form.resource.SectionResource;
<ide> import org.innovateuk.ifs.form.transactional.SectionService;
<del>import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.statemachine.StateContext;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> @Component
<ide> public class AutoCompleteSectionsAction extends BaseApplicationAction {
<ide>
<del> @Autowired
<del> private SectionService sectionService;
<add> private final SectionService sectionService;
<add> private final SectionStatusService sectionStatusService;
<ide>
<del> @Autowired
<del> private SectionStatusService sectionStatusService;
<add> public AutoCompleteSectionsAction(SectionService sectionService, SectionStatusService sectionStatusService) {
<add> this.sectionService = sectionService;
<add> this.sectionStatusService = sectionStatusService;
<add> }
<ide>
<ide> @Override
<ide> protected void doExecute(final Application application,
<ide> }
<ide> }
<ide>
<del>
<ide> private void completeTermsAndConditions(Application application, long termsSectionId) {
<ide> sectionStatusService.markSectionAsComplete(termsSectionId, application.getId(), application.getLeadApplicantProcessRole().getId());
<ide> } |
|
Java | mit | dd3349bd27d92bd1c04e020844548b3ebd0bfb7c | 0 | Banno/Sentry-Android | package com.joshdholtz.sentry;
import android.Manifest.permission;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.WindowManager;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.EnglishReasonPhraseCatalog;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Sentry {
private static final String TAG = "Sentry";
private final static String sentryVersion = "7";
private static final int MAX_QUEUE_LENGTH = 50;
private static final int MAX_BREADCRUMBS = 10;
public static boolean debug = false;
private Context context;
private String baseUrl;
private String publicKey;
private String secretKey;
private String projectId;
private AppInfo appInfo = AppInfo.Empty;
private boolean verifySsl;
private SentryEventCaptureListener captureListener;
private JSONObject contexts = new JSONObject();
private Executor executor;
private LinkedList<Breadcrumb> breadcrumbs = new LinkedList<>();
public enum SentryEventLevel {
FATAL("fatal"),
ERROR("error"),
WARNING("warning"),
INFO("info"),
DEBUG("debug");
private final String value;
SentryEventLevel(String value) {
this.value = value;
}
}
private Sentry() {
}
private static void log(String text) {
if (debug) {
Log.d(TAG, text);
}
}
private static Sentry getInstance() {
return LazyHolder.instance;
}
private static class LazyHolder {
private static final Sentry instance = new Sentry();
}
public static void init(Context context, String dsn) {
Pair<String, String> publicKeySecretKey = getPublicKeySecretKeyPair(dsn);
Uri uri = Uri.parse(dsn);
String port = "";
if (uri.getPort() >= 0) {
port = ":" + uri.getPort();
}
init(context,
uri.getScheme() + "://" + uri.getHost() + port,
publicKeySecretKey.first,
publicKeySecretKey.second,
getProjectId(Uri.parse(dsn)));
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId) {
init(context, baseUrl, publicKey, secretKey, projectId, true);
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId,
boolean verifySsl) {
init(context, baseUrl, publicKey, secretKey, projectId, verifySsl, true);
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId,
boolean verifySsl,
boolean setupUncaughtExceptionHandler) {
final Sentry sentry = Sentry.getInstance();
sentry.context = context.getApplicationContext();
sentry.baseUrl = baseUrl;
sentry.publicKey = publicKey;
sentry.secretKey = secretKey;
sentry.projectId = projectId;
sentry.appInfo = AppInfo.Read(sentry.context);
sentry.verifySsl = verifySsl;
sentry.contexts = readContexts(sentry.context, sentry.appInfo);
sentry.executor = fixedQueueDiscardingExecutor(MAX_QUEUE_LENGTH);
if (setupUncaughtExceptionHandler) {
sentry.setupUncaughtExceptionHandler();
}
}
private static Executor fixedQueueDiscardingExecutor(int queueSize) {
// Name our threads so that it is easy for app developers to see who is creating threads.
final ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicLong count = new AtomicLong();
@Override
public Thread newThread(Runnable runnable) {
final Thread thread = new Thread(runnable);
thread.setName(String.format(Locale.US, "Sentry HTTP Thread %d", count.incrementAndGet()));
return thread;
}
};
return new ThreadPoolExecutor(
0, 1, // Keep 0 threads alive. Max pool size is 1.
60, TimeUnit.SECONDS, // Kill unused threads after this length.
new ArrayBlockingQueue<Runnable>(queueSize),
threadFactory, new ThreadPoolExecutor.DiscardPolicy()); // Discard exceptions
}
private static boolean getVerifySsl(String dsn) {
List<NameValuePair> params = getAllGetParams(dsn);
for (NameValuePair param : params) {
if (param.getName().equals("verify_ssl"))
return Integer.parseInt(param.getValue()) != 0;
}
return false;
}
private static List<NameValuePair> getAllGetParams(String dsn) {
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(dsn), HTTP.UTF_8);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return params;
}
private void setupUncaughtExceptionHandler() {
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if (currentHandler != null) {
log("current handler class=" + currentHandler.getClass().getName());
}
// don't register again if already registered
if (!(currentHandler instanceof SentryUncaughtExceptionHandler)) {
// Register default exceptions handler
Thread.setDefaultUncaughtExceptionHandler(
new SentryUncaughtExceptionHandler(currentHandler, InternalStorage.getInstance()));
}
sendAllCachedCapturedEvents();
}
private static String createXSentryAuthHeader() {
StringBuilder header = new StringBuilder();
header.append("Sentry ")
.append(String.format("sentry_version=%s,", sentryVersion))
.append(String.format("sentry_client=sentry-android/%s,", BuildConfig.SENTRY_ANDROID_VERSION))
.append(String.format("sentry_timestamp=%s,", System.currentTimeMillis()))
.append(String.format("sentry_key=%s,", Sentry.getInstance().publicKey))
.append(String.format("sentry_secret=%s", Sentry.getInstance().secretKey));
return header.toString();
}
private static Pair<String, String> getPublicKeySecretKeyPair(String dsn) {
Uri uri = Uri.parse(dsn);
Log.d("Sentry", "URI - " + uri);
String authority = uri.getAuthority().replace("@" + uri.getHost(), "");
String[] authorityParts = authority.split(":");
String publicKey = authorityParts[0];
String secretKey = authorityParts[1];
return Pair.create(publicKey, secretKey);
}
private static String getProjectId(Uri dsn) {
String path = dsn.getPath();
String projectId = path.substring(path.lastIndexOf("/") + 1);
return projectId;
}
public static void sendAllCachedCapturedEvents() {
List<SentryEventRequest> unsentRequests = InternalStorage.getInstance().getUnsentRequests();
log("Sending up " + unsentRequests.size() + " cached response(s)");
for (SentryEventRequest request : unsentRequests) {
Sentry.doCaptureEventPost(request);
}
}
/**
* @param captureListener the captureListener to set
*/
public static void setCaptureListener(SentryEventCaptureListener captureListener) {
Sentry.getInstance().captureListener = captureListener;
}
public static void captureMessage(String message) {
Sentry.captureMessage(message, SentryEventLevel.INFO);
}
public static void captureMessage(String message, SentryEventLevel level) {
Sentry.captureEvent(new SentryEventBuilder()
.setMessage(message)
.setLevel(level)
);
}
public static void captureException(Throwable t) {
Sentry.captureException(t, t.getMessage(), SentryEventLevel.ERROR);
}
public static void captureException(Throwable t, String message) {
Sentry.captureException(t, message, SentryEventLevel.ERROR);
}
public static void captureException(Throwable t, SentryEventLevel level) {
captureException(t, t.getMessage(), level);
}
public static void captureException(Throwable t, String message, SentryEventLevel level) {
String culprit = getCause(t, t.getMessage());
Sentry.captureEvent(new SentryEventBuilder()
.setMessage(message)
.setCulprit(culprit)
.setLevel(level)
.setException(t)
);
}
private static String getCause(Throwable t, String culprit) {
final String packageName = Sentry.getInstance().appInfo.name;
for (StackTraceElement stackTrace : t.getStackTrace()) {
if (stackTrace.toString().contains(packageName)) {
return stackTrace.toString();
}
}
return culprit;
}
public static void captureEvent(SentryEventBuilder builder) {
final Sentry sentry = Sentry.getInstance();
final SentryEventRequest request;
builder.event.put("contexts", sentry.contexts);
builder.setRelease(Integer.toString(sentry.appInfo.versionCode));
builder.event.put("breadcrumbs", Sentry.getInstance().currentBreadcrumbs());
if (sentry.captureListener != null) {
builder = sentry.captureListener.beforeCapture(builder);
if (builder == null) {
Log.e(Sentry.TAG, "SentryEventBuilder in captureEvent is null");
return;
}
request = new SentryEventRequest(builder);
} else {
request = new SentryEventRequest(builder);
}
log("Request - " + request.getRequestData());
doCaptureEventPost(request);
}
private boolean shouldAttemptPost() {
PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(permission.ACCESS_NETWORK_STATE, context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
return false;
}
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private static class ExSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
ExSSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
private static HttpClient getHttpsClient(HttpClient client) {
try {
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
SSLSocketFactory sslSocketFactory = new ExSSLSocketFactory(sslContext);
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager clientConnectionManager = client.getConnectionManager();
SchemeRegistry schemeRegistry = clientConnectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
return new DefaultHttpClient(clientConnectionManager, client.getParams());
} catch (Exception ex) {
return null;
}
}
private static void doCaptureEventPost(final SentryEventRequest request) {
final Sentry sentry = Sentry.getInstance();
if (!sentry.shouldAttemptPost()) {
InternalStorage.getInstance().addRequest(request);
return;
}
sentry.executor.execute(new Runnable() {
@Override
public void run() {
HttpClient httpClient;
if (Sentry.getInstance().verifySsl) {
log("Using http client");
httpClient = new DefaultHttpClient();
} else {
log("Using https client");
httpClient = getHttpsClient(new DefaultHttpClient());
}
HttpPost httpPost = new HttpPost(sentry.baseUrl
+ "/api/"
+ sentry.projectId
+ "/store/");
int TIMEOUT_MILLISEC = 10000; // = 20 seconds
HttpParams httpParams = httpPost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8);
boolean success = false;
try {
httpPost.setHeader("X-Sentry-Auth", createXSentryAuthHeader());
httpPost.setHeader("User-Agent", "sentry-android/" + BuildConfig.SENTRY_ANDROID_VERSION);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(request.getRequestData(), HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
int status = httpResponse.getStatusLine().getStatusCode();
byte[] byteResp = null;
// Gets the input stream and unpackages the response into a command
if (httpResponse.getEntity() != null) {
try {
InputStream in = httpResponse.getEntity().getContent();
byteResp = this.readBytes(in);
} catch (IOException e) {
e.printStackTrace();
}
}
String stringResponse = null;
Charset charsetInput = Charset.forName("UTF-8");
CharsetDecoder decoder = charsetInput.newDecoder();
CharBuffer cbuf = null;
try {
cbuf = decoder.decode(ByteBuffer.wrap(byteResp));
stringResponse = cbuf.toString();
} catch (CharacterCodingException e) {
e.printStackTrace();
}
success = (status == 200);
log("SendEvent - " + status + " " + stringResponse);
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
InternalStorage.getInstance().removeBuilder(request);
} else {
InternalStorage.getInstance().addRequest(request);
}
}
private byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
});
}
private static class SentryUncaughtExceptionHandler implements UncaughtExceptionHandler {
private final InternalStorage storage;
private final UncaughtExceptionHandler defaultExceptionHandler;
// constructor
public SentryUncaughtExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler, InternalStorage storage) {
defaultExceptionHandler = pDefaultExceptionHandler;
this.storage = storage;
}
@Override
public void uncaughtException(Thread thread, Throwable e) {
final Sentry sentry = Sentry.getInstance();
// Here you should have a more robust, permanent record of problems
SentryEventBuilder builder = new SentryEventBuilder(e, SentryEventLevel.FATAL);
builder.setRelease(Integer.toString(sentry.appInfo.versionCode));
if (sentry.captureListener != null) {
builder = sentry.captureListener.beforeCapture(builder);
}
if (builder != null) {
builder.event.put("contexts", sentry.contexts);
storage.addRequest(new SentryEventRequest(builder));
} else {
Log.e(Sentry.TAG, "SentryEventBuilder in uncaughtException is null");
}
//call original handler
defaultExceptionHandler.uncaughtException(thread, e);
}
}
private static class InternalStorage {
private final static String FILE_NAME = "unsent_requests";
private final List<SentryEventRequest> unsentRequests;
private static InternalStorage getInstance() {
return LazyHolder.instance;
}
private static class LazyHolder {
private static final InternalStorage instance = new InternalStorage();
}
private InternalStorage() {
Context context = Sentry.getInstance().context;
try {
File unsetRequestsFile = new File(context.getFilesDir(), FILE_NAME);
if (!unsetRequestsFile.exists()) {
writeObject(context, new ArrayList<Sentry.SentryEventRequest>());
}
} catch (Exception e) {
Log.e(TAG, "Error initializing storage", e);
}
this.unsentRequests = this.readObject(context);
}
/**
* @return the unsentRequests
*/
public List<SentryEventRequest> getUnsentRequests() {
final List<SentryEventRequest> copy = new ArrayList<>();
synchronized (this) {
copy.addAll(unsentRequests);
}
return copy;
}
public void addRequest(SentryEventRequest request) {
synchronized (this) {
log("Adding request - " + request.uuid);
if (!this.unsentRequests.contains(request)) {
this.unsentRequests.add(request);
this.writeObject(Sentry.getInstance().context, this.unsentRequests);
}
}
}
public void removeBuilder(SentryEventRequest request) {
synchronized (this) {
log("Removing request - " + request.uuid);
this.unsentRequests.remove(request);
this.writeObject(Sentry.getInstance().context, this.unsentRequests);
}
}
private void writeObject(Context context, List<SentryEventRequest> requests) {
try {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(requests);
oos.close();
fos.close();
} catch (IOException e) {
Log.e(TAG, "Error saving to storage", e);
}
}
private List<SentryEventRequest> readObject(Context context) {
try {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis);
List<SentryEventRequest> requests = (ArrayList<SentryEventRequest>) ois.readObject();
ois.close();
fis.close();
return requests;
} catch (IOException | ClassNotFoundException e) {
Log.e(TAG, "Error loading from storage", e);
}
return new ArrayList<>();
}
}
public interface SentryEventCaptureListener {
SentryEventBuilder beforeCapture(SentryEventBuilder builder);
}
private final static class Breadcrumb {
enum Type {
Default("default"),
HTTP("http"),
Navigation("navigation");
private final String value;
Type(String value) {
this.value = value;
}
}
final long timestamp;
final Type type;
final String message;
final String category;
final SentryEventLevel level;
final Map<String, String> data = new HashMap<>();
Breadcrumb(long timestamp, Type type, String message, String category, SentryEventLevel level) {
this.timestamp = timestamp;
this.type = type;
this.message = message;
this.category = category;
this.level = level;
}
}
private void pushBreadcrumb(Breadcrumb b) {
while (breadcrumbs.size() >= MAX_BREADCRUMBS) {
breadcrumbs.removeFirst();
}
breadcrumbs.add(b);
}
/**
* Record a breadcrumb to log a navigation from `from` to `to`.
* @param category A category to label the event under. This generally is similar to a logger
* name, and will let you more easily understand the area an event took place, such as auth.
* @param from A string representing the original application state / location.
* @param to A string representing the new application state / location.
*
* @see com.joshdholtz.sentry.Sentry#addHttpBreadcrumb(String, String, int)
*/
public static void addNavigationBreadcrumb(String category, String from, String to) {
final Breadcrumb b = new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.Navigation,
"",
category,
SentryEventLevel.INFO);
b.data.put("from", from);
b.data.put("to", to);
getInstance().pushBreadcrumb(b);
}
/**
* Record a HTTP request breadcrumb. This represents an HTTP request transmitted from your
* application. This could be an AJAX request from a web application, or a server-to-server HTTP
* request to an API service provider, etc.
*
* @param url The request URL.
* @param method The HTTP request method.
* @param statusCode The HTTP status code of the response.
*
* @see com.joshdholtz.sentry.Sentry#addHttpBreadcrumb(String, String, int)
*/
public static void addHttpBreadcrumb(String url, String method, int statusCode) {
final String reason = EnglishReasonPhraseCatalog.INSTANCE.getReason(statusCode, Locale.US);
final Breadcrumb b = new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.HTTP,
"",
String.format("http.%s", method.toLowerCase()),
SentryEventLevel.INFO);
b.data.put("url", url);
b.data.put("method", method);
b.data.put("status_code", Integer.toString(statusCode));
b.data.put("reason", reason);
getInstance().pushBreadcrumb(b);
}
/**
* Sentry supports a concept called Breadcrumbs, which is a trail of events which happened prior
* to an issue. Often times these events are very similar to traditional logs, but also have the
* ability to record more rich structured data.
*
* @param category A category to label the event under. This generally is similar to a logger
* name, and will let you more easily understand the area an event took place,
* such as auth.
*
* @param message A string describing the event. The most common vector, often used as a drop-in
* for a traditional log message.
*
* See https://docs.sentry.io/hosted/learn/breadcrumbs/
*
*/
public static void addBreadcrumb(String category, String message) {
getInstance().pushBreadcrumb(new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.Default,
message,
category,
SentryEventLevel.INFO));
}
private JSONArray currentBreadcrumbs() {
final JSONArray crumbs = new JSONArray();
for (Breadcrumb breadcrumb : breadcrumbs) {
final JSONObject json = new JSONObject();
try {
json.put("timestamp", breadcrumb.timestamp);
json.put("type", breadcrumb.type.value);
json.put("message", breadcrumb.message);
json.put("category", breadcrumb.category);
json.put("level", breadcrumb.level.value);
json.put("data", new JSONObject(breadcrumb.data));
} catch (JSONException jse) {
Log.e(TAG, "Error serializing breadcrumbs", jse);
}
crumbs.put(json);
}
return crumbs;
}
public static class SentryEventRequest implements Serializable {
private final String requestData;
private final UUID uuid;
public SentryEventRequest(SentryEventBuilder builder) {
this.requestData = new JSONObject(builder.event).toString();
this.uuid = UUID.randomUUID();
}
/**
* @return the requestData
*/
public String getRequestData() {
return requestData;
}
/**
* @return the uuid
*/
public UUID getUuid() {
return uuid;
}
@Override
public boolean equals(Object other) {
SentryEventRequest otherRequest = (SentryEventRequest) other;
if (this.uuid != null && otherRequest.uuid != null) {
return uuid.equals(otherRequest.uuid);
}
return false;
}
}
/**
* The Sentry server assumes the time is in UTC.
* The timestamp should be in ISO 8601 format, without a timezone.
*/
private static DateFormat iso8601() {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format;
}
public static class SentryEventBuilder implements Serializable {
private static final long serialVersionUID = -8589756678369463988L;
// Match packages names that start with some well-known internal class-paths:
// java.*
// android.*
// com.android.*
// com.google.android.*
// dalvik.system.*
static final String isInternalPackage = "^(java|android|com\\.android|com\\.google\\.android|dalvik\\.system)\\..*";
private final static DateFormat timestampFormat = iso8601();
private final Map<String, Object> event;
public JSONObject toJSON() {
return new JSONObject(event);
}
public SentryEventBuilder() {
event = new HashMap<>();
event.put("event_id", UUID.randomUUID().toString().replace("-", ""));
event.put("platform", "java");
this.setTimestamp(System.currentTimeMillis());
}
public SentryEventBuilder(Throwable t, SentryEventLevel level) {
this();
String culprit = getCause(t, t.getMessage());
this.setMessage(t.getMessage())
.setCulprit(culprit)
.setLevel(level)
.setException(t);
}
/**
* "message": "SyntaxError: Wattttt!"
*
* @param message Message
* @return SentryEventBuilder
*/
public SentryEventBuilder setMessage(String message) {
event.put("message", message);
return this;
}
/**
* "timestamp": "2011-05-02T17:41:36"
*
* @param timestamp Timestamp
* @return SentryEventBuilder
*/
public SentryEventBuilder setTimestamp(long timestamp) {
event.put("timestamp", timestampFormat.format(new Date(timestamp)));
return this;
}
/**
* "level": "warning"
*
* @param level Level
* @return SentryEventBuilder
*/
public SentryEventBuilder setLevel(SentryEventLevel level) {
event.put("level", level.value);
return this;
}
/**
* "logger": "my.logger.name"
*
* @param logger Logger
* @return SentryEventBuilder
*/
public SentryEventBuilder setLogger(String logger) {
event.put("logger", logger);
return this;
}
/**
* "culprit": "my.module.function_name"
*
* @param culprit Culprit
* @return SentryEventBuilder
*/
public SentryEventBuilder setCulprit(String culprit) {
event.put("culprit", culprit);
return this;
}
/**
* @param user User
* @return SentryEventBuilder
*/
public SentryEventBuilder setUser(Map<String, String> user) {
setUser(new JSONObject(user));
return this;
}
public SentryEventBuilder setUser(JSONObject user) {
event.put("user", user);
return this;
}
public JSONObject getUser() {
if (!event.containsKey("user")) {
setTags(new HashMap<String, String>());
}
return (JSONObject) event.get("user");
}
/**
* @param tags Tags
* @return SentryEventBuilder
*/
public SentryEventBuilder setTags(Map<String, String> tags) {
setTags(new JSONObject(tags));
return this;
}
public SentryEventBuilder setTags(JSONObject tags) {
event.put("tags", tags);
return this;
}
public SentryEventBuilder addTag(String key, String value) {
try {
getTags().put(key, value);
} catch (JSONException e) {
Log.e(Sentry.TAG, "Error adding tag in SentryEventBuilder");
}
return this;
}
public JSONObject getTags() {
if (!event.containsKey("tags")) {
setTags(new HashMap<String, String>());
}
return (JSONObject) event.get("tags");
}
/**
* @param serverName Server name
* @return SentryEventBuilder
*/
public SentryEventBuilder setServerName(String serverName) {
event.put("server_name", serverName);
return this;
}
/**
* @param release Release
* @return SentryEventBuilder
*/
public SentryEventBuilder setRelease(String release) {
event.put("release", release);
return this;
}
/**
* @param name Name
* @param version Version
* @return SentryEventBuilder
*/
public SentryEventBuilder addModule(String name, String version) {
JSONArray modules;
if (!event.containsKey("modules")) {
modules = new JSONArray();
event.put("modules", modules);
} else {
modules = (JSONArray) event.get("modules");
}
if (name != null && version != null) {
String[] module = {name, version};
modules.put(new JSONArray(Arrays.asList(module)));
}
return this;
}
/**
* @param extra Extra
* @return SentryEventBuilder
*/
public SentryEventBuilder setExtra(Map<String, String> extra) {
setExtra(new JSONObject(extra));
return this;
}
public SentryEventBuilder setExtra(JSONObject extra) {
event.put("extra", extra);
return this;
}
public SentryEventBuilder addExtra(String key, String value) {
try {
getExtra().put(key, value);
} catch (JSONException e) {
Log.e(Sentry.TAG, "Error adding extra in SentryEventBuilder");
}
return this;
}
public JSONObject getExtra() {
if (!event.containsKey("extra")) {
setExtra(new HashMap<String, String>());
}
return (JSONObject) event.get("extra");
}
/**
* @param t Throwable
* @return SentryEventBuilder
*/
public SentryEventBuilder setException(Throwable t) {
JSONArray values = new JSONArray();
while (t != null) {
JSONObject exception = new JSONObject();
try {
exception.put("type", t.getClass().getSimpleName());
exception.put("value", t.getMessage());
exception.put("module", t.getClass().getPackage().getName());
exception.put("stacktrace", getStackTrace(t.getStackTrace()));
values.put(exception);
} catch (JSONException e) {
Log.e(TAG, "Failed to build sentry report for " + t, e);
}
t = t.getCause();
}
JSONObject exceptionReport = new JSONObject();
try {
exceptionReport.put("values", values);
event.put("exception", exceptionReport);
} catch (JSONException e) {
Log.e(TAG, "Unable to attach exception to event " + values, e);
}
return this;
}
private static JSONObject getStackTrace(StackTraceElement[] stackFrames) {
JSONObject stacktrace = new JSONObject();
try {
JSONArray frameList = new JSONArray();
// Java stack frames are in the opposite order from what the Sentry client API expects.
// > The zeroth element of the array (assuming the array's length is non-zero)
// > represents the top of the stack, which is the last method invocation in the
// > sequence.
// See:
// https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace()
// https://docs.sentry.io/clientdev/interfaces/#failure-interfaces
//
// This code uses array indices rather a foreach construct since there is no built-in
// reverse iterator in the Java standard library. To use a foreach loop would require
// calling Collections.reverse which would require copying the array to a list.
for (int i = stackFrames.length - 1; i >= 0; i--) {
frameList.put(frameJson(stackFrames[i]));
}
stacktrace.put("frames", frameList);
} catch (JSONException e) {
Log.e(TAG, "Error serializing stack frames", e);
}
return stacktrace;
}
/**
* Add a stack trace to the event.
* A stack trace for the current thread can be obtained by using
* `Thread.currentThread().getStackTrace()`.
*
* @param stackTrace StackTraceElement[]
* @return SentryEventBuilder
*
* @see Thread#currentThread()
* @see Thread#getStackTrace()
*/
public SentryEventBuilder setStackTrace(StackTraceElement[] stackTrace) {
this.event.put("stacktrace", getStackTrace(stackTrace));
return this;
}
// Convert a StackTraceElement to a sentry.interfaces.stacktrace.Stacktrace JSON object.
static JSONObject frameJson(StackTraceElement ste) throws JSONException {
final JSONObject frame = new JSONObject();
final String method = ste.getMethodName();
if (Present(method)) {
frame.put("function", method);
}
final String fileName = ste.getFileName();
if (Present(fileName)) {
frame.put("filename", fileName);
}
int lineno = ste.getLineNumber();
if (!ste.isNativeMethod() && lineno >= 0) {
frame.put("lineno", lineno);
}
String className = ste.getClassName();
frame.put("module", className);
// Take out some of the system packages to improve the exception folding on the sentry server
frame.put("in_app", !className.matches(isInternalPackage));
return frame;
}
}
/**
* Store a tuple of package version information captured from PackageInfo
*
* @see PackageInfo
*/
private final static class AppInfo {
final static AppInfo Empty = new AppInfo("", "", 0);
final String name;
final String versionName;
final int versionCode;
AppInfo(String name, String versionName, int versionCode) {
this.name = name;
this.versionName = versionName;
this.versionCode = versionCode;
}
static AppInfo Read(final Context context) {
try {
final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return new AppInfo(info.packageName, info.versionName, info.versionCode);
} catch (Exception e) {
Log.e(TAG, "Error reading package context", e);
return Empty;
}
}
}
private static JSONObject readContexts(Context context, AppInfo appInfo) {
final JSONObject contexts = new JSONObject();
try {
contexts.put("os", osContext());
contexts.put("device", deviceContext(context));
contexts.put("package", packageContext(appInfo));
} catch (JSONException e) {
Log.e(TAG, "Failed to build device contexts", e);
}
return contexts;
}
/**
* Read the device and build into a map.
* <p>
* Not implemented:
* - battery_level
* If the device has a battery this can be an integer defining the battery level (in
* the range 0-100). (Android requires registration of an intent to query the battery).
* - name
* The name of the device. This is typically a hostname.
* <p>
* See https://docs.getsentry.com/hosted/clientdev/interfaces/#context-types
*/
private static JSONObject deviceContext(Context context) {
final JSONObject device = new JSONObject();
try {
// The family of the device. This is normally the common part of model names across
// generations. For instance iPhone would be a reasonable family, so would be Samsung Galaxy.
device.put("family", Build.BRAND);
// The model name. This for instance can be Samsung Galaxy S3.
device.put("model", Build.PRODUCT);
// An internal hardware revision to identify the device exactly.
device.put("model_id", Build.MODEL);
final String architecture = System.getProperty("os.arch");
if (Present(architecture)) {
device.put("arch", architecture);
}
final int orient = context.getResources().getConfiguration().orientation;
device.put("orientation", orient == Configuration.ORIENTATION_LANDSCAPE ?
"landscape" : "portrait");
// Read screen resolution in the format "800x600"
// Normalised to have wider side first.
final Object windowManager = context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null && windowManager instanceof WindowManager) {
final DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) windowManager).getDefaultDisplay().getMetrics(metrics);
device.put("screen_resolution",
String.format("%sx%s",
Math.max(metrics.widthPixels, metrics.heightPixels),
Math.min(metrics.widthPixels, metrics.heightPixels)));
}
} catch (Exception e) {
Log.e(TAG, "Error reading device context", e);
}
return device;
}
private static JSONObject osContext() {
final JSONObject os = new JSONObject();
try {
os.put("type", "os");
os.put("name", "Android");
os.put("version", Build.VERSION.RELEASE);
if (Build.VERSION.SDK_INT < 4) {
os.put("build", Build.VERSION.SDK);
} else {
os.put("build", Integer.toString(Build.VERSION.SDK_INT));
}
final String kernelVersion = System.getProperty("os.version");
if (Present(kernelVersion)) {
os.put("kernel_version", kernelVersion);
}
} catch (Exception e) {
Log.e(TAG, "Error reading OS context", e);
}
return os;
}
/**
* Read the package data into map to be sent as an event context item.
* This is not a built-in context type.
*/
private static JSONObject packageContext(AppInfo appInfo) {
final JSONObject pack = new JSONObject();
try {
pack.put("type", "package");
pack.put("name", appInfo.name);
pack.put("version_name", appInfo.versionName);
pack.put("version_code", Integer.toString(appInfo.versionCode));
} catch (JSONException e) {
Log.e(TAG, "Error reading package context", e);
}
return pack;
}
/**
* Take the idea of `present?` from ActiveSupport.
*/
private static boolean Present(String s) {
return s != null && s.length() > 0;
}
}
| sentry-android/src/main/java/com/joshdholtz/sentry/Sentry.java | package com.joshdholtz.sentry;
import android.Manifest.permission;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.WindowManager;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.EnglishReasonPhraseCatalog;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Sentry {
private static final String TAG = "Sentry";
private final static String sentryVersion = "7";
private static final int MAX_QUEUE_LENGTH = 50;
private static final int MAX_BREADCRUMBS = 10;
public static boolean debug = false;
private Context context;
private String baseUrl;
private String publicKey;
private String secretKey;
private String projectId;
private AppInfo appInfo = AppInfo.Empty;
private boolean verifySsl;
private SentryEventCaptureListener captureListener;
private JSONObject contexts = new JSONObject();
private Executor executor;
private LinkedList<Breadcrumb> breadcrumbs = new LinkedList<>();
public enum SentryEventLevel {
FATAL("fatal"),
ERROR("error"),
WARNING("warning"),
INFO("info"),
DEBUG("debug");
private final String value;
SentryEventLevel(String value) {
this.value = value;
}
}
private Sentry() {
}
private static void log(String text) {
if (debug) {
Log.d(TAG, text);
}
}
private static Sentry getInstance() {
return LazyHolder.instance;
}
private static class LazyHolder {
private static final Sentry instance = new Sentry();
}
public static void init(Context context, String dsn) {
Pair<String, String> publicKeySecretKey = getPublicKeySecretKeyPair(dsn);
Uri uri = Uri.parse(dsn);
String port = "";
if (uri.getPort() >= 0) {
port = ":" + uri.getPort();
}
init(context,
uri.getScheme() + "://" + uri.getHost() + port,
publicKeySecretKey.first,
publicKeySecretKey.second,
getProjectId(Uri.parse(dsn)));
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId) {
init(context, baseUrl, publicKey, secretKey, projectId, true);
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId,
boolean verifySsl) {
init(context, baseUrl, publicKey, secretKey, projectId, verifySsl, true);
}
public static void init(Context context,
String baseUrl,
String publicKey,
String secretKey,
String projectId,
boolean verifySsl,
boolean setupUncaughtExceptionHandler) {
final Sentry sentry = Sentry.getInstance();
sentry.context = context.getApplicationContext();
sentry.baseUrl = baseUrl;
sentry.publicKey = publicKey;
sentry.secretKey = secretKey;
sentry.projectId = projectId;
sentry.appInfo = AppInfo.Read(sentry.context);
sentry.verifySsl = verifySsl;
sentry.contexts = readContexts(sentry.context, sentry.appInfo);
sentry.executor = fixedQueueDiscardingExecutor(MAX_QUEUE_LENGTH);
if (setupUncaughtExceptionHandler) {
sentry.setupUncaughtExceptionHandler();
}
}
private static Executor fixedQueueDiscardingExecutor(int queueSize) {
// Name our threads so that it is easy for app developers to see who is creating threads.
final ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicLong count = new AtomicLong();
@Override
public Thread newThread(Runnable runnable) {
final Thread thread = new Thread(runnable);
thread.setName(String.format(Locale.US, "Sentry HTTP Thread %d", count.incrementAndGet()));
return thread;
}
};
return new ThreadPoolExecutor(
0, 1, // Keep 0 threads alive. Max pool size is 1.
60, TimeUnit.SECONDS, // Kill unused threads after this length.
new ArrayBlockingQueue<Runnable>(queueSize),
threadFactory, new ThreadPoolExecutor.DiscardPolicy()); // Discard exceptions
}
private static boolean getVerifySsl(String dsn) {
List<NameValuePair> params = getAllGetParams(dsn);
for (NameValuePair param : params) {
if (param.getName().equals("verify_ssl"))
return Integer.parseInt(param.getValue()) != 0;
}
return false;
}
private static List<NameValuePair> getAllGetParams(String dsn) {
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(dsn), HTTP.UTF_8);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return params;
}
private void setupUncaughtExceptionHandler() {
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if (currentHandler != null) {
log("current handler class=" + currentHandler.getClass().getName());
}
// don't register again if already registered
if (!(currentHandler instanceof SentryUncaughtExceptionHandler)) {
// Register default exceptions handler
Thread.setDefaultUncaughtExceptionHandler(
new SentryUncaughtExceptionHandler(currentHandler, InternalStorage.getInstance()));
}
sendAllCachedCapturedEvents();
}
private static String createXSentryAuthHeader() {
StringBuilder header = new StringBuilder();
header.append("Sentry ")
.append(String.format("sentry_version=%s,", sentryVersion))
.append(String.format("sentry_client=sentry-android/%s,", BuildConfig.SENTRY_ANDROID_VERSION))
.append(String.format("sentry_timestamp=%s,", System.currentTimeMillis()))
.append(String.format("sentry_key=%s,", Sentry.getInstance().publicKey))
.append(String.format("sentry_secret=%s", Sentry.getInstance().secretKey));
return header.toString();
}
private static Pair<String, String> getPublicKeySecretKeyPair(String dsn) {
Uri uri = Uri.parse(dsn);
Log.d("Sentry", "URI - " + uri);
String authority = uri.getAuthority().replace("@" + uri.getHost(), "");
String[] authorityParts = authority.split(":");
String publicKey = authorityParts[0];
String secretKey = authorityParts[1];
return Pair.create(publicKey, secretKey);
}
private static String getProjectId(Uri dsn) {
String path = dsn.getPath();
String projectId = path.substring(path.lastIndexOf("/") + 1);
return projectId;
}
public static void sendAllCachedCapturedEvents() {
List<SentryEventRequest> unsentRequests = InternalStorage.getInstance().getUnsentRequests();
log("Sending up " + unsentRequests.size() + " cached response(s)");
for (SentryEventRequest request : unsentRequests) {
Sentry.doCaptureEventPost(request);
}
}
/**
* @param captureListener the captureListener to set
*/
public static void setCaptureListener(SentryEventCaptureListener captureListener) {
Sentry.getInstance().captureListener = captureListener;
}
public static void captureMessage(String message) {
Sentry.captureMessage(message, SentryEventLevel.INFO);
}
public static void captureMessage(String message, SentryEventLevel level) {
Sentry.captureEvent(new SentryEventBuilder()
.setMessage(message)
.setLevel(level)
);
}
public static void captureException(Throwable t) {
Sentry.captureException(t, t.getMessage(), SentryEventLevel.ERROR);
}
public static void captureException(Throwable t, String message) {
Sentry.captureException(t, message, SentryEventLevel.ERROR);
}
public static void captureException(Throwable t, SentryEventLevel level) {
captureException(t, t.getMessage(), level);
}
public static void captureException(Throwable t, String message, SentryEventLevel level) {
String culprit = getCause(t, t.getMessage());
Sentry.captureEvent(new SentryEventBuilder()
.setMessage(message)
.setCulprit(culprit)
.setLevel(level)
.setException(t)
);
}
private static String getCause(Throwable t, String culprit) {
final String packageName = Sentry.getInstance().appInfo.name;
for (StackTraceElement stackTrace : t.getStackTrace()) {
if (stackTrace.toString().contains(packageName)) {
return stackTrace.toString();
}
}
return culprit;
}
public static void captureEvent(SentryEventBuilder builder) {
final Sentry sentry = Sentry.getInstance();
final SentryEventRequest request;
builder.event.put("contexts", sentry.contexts);
builder.setRelease(Integer.toString(sentry.appInfo.versionCode));
builder.event.put("breadcrumbs", Sentry.getInstance().currentBreadcrumbs());
if (sentry.captureListener != null) {
builder = sentry.captureListener.beforeCapture(builder);
if (builder == null) {
Log.e(Sentry.TAG, "SentryEventBuilder in captureEvent is null");
return;
}
request = new SentryEventRequest(builder);
} else {
request = new SentryEventRequest(builder);
}
log("Request - " + request.getRequestData());
doCaptureEventPost(request);
}
private boolean shouldAttemptPost() {
PackageManager pm = context.getPackageManager();
int hasPerm = pm.checkPermission(permission.ACCESS_NETWORK_STATE, context.getPackageName());
if (hasPerm != PackageManager.PERMISSION_GRANTED) {
return false;
}
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private static class ExSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
ExSSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
private static HttpClient getHttpsClient(HttpClient client) {
try {
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
SSLSocketFactory sslSocketFactory = new ExSSLSocketFactory(sslContext);
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager clientConnectionManager = client.getConnectionManager();
SchemeRegistry schemeRegistry = clientConnectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
return new DefaultHttpClient(clientConnectionManager, client.getParams());
} catch (Exception ex) {
return null;
}
}
private static void doCaptureEventPost(final SentryEventRequest request) {
final Sentry sentry = Sentry.getInstance();
if (!sentry.shouldAttemptPost()) {
InternalStorage.getInstance().addRequest(request);
return;
}
sentry.executor.execute(new Runnable() {
@Override
public void run() {
HttpClient httpClient;
if (Sentry.getInstance().verifySsl) {
log("Using http client");
httpClient = new DefaultHttpClient();
} else {
log("Using https client");
httpClient = getHttpsClient(new DefaultHttpClient());
}
HttpPost httpPost = new HttpPost(sentry.baseUrl
+ "/api/"
+ sentry.projectId
+ "/store/");
int TIMEOUT_MILLISEC = 10000; // = 20 seconds
HttpParams httpParams = httpPost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParams, HTTP.UTF_8);
boolean success = false;
try {
httpPost.setHeader("X-Sentry-Auth", createXSentryAuthHeader());
httpPost.setHeader("User-Agent", "sentry-android/" + BuildConfig.SENTRY_ANDROID_VERSION);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(request.getRequestData(), HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
int status = httpResponse.getStatusLine().getStatusCode();
byte[] byteResp = null;
// Gets the input stream and unpackages the response into a command
if (httpResponse.getEntity() != null) {
try {
InputStream in = httpResponse.getEntity().getContent();
byteResp = this.readBytes(in);
} catch (IOException e) {
e.printStackTrace();
}
}
String stringResponse = null;
Charset charsetInput = Charset.forName("UTF-8");
CharsetDecoder decoder = charsetInput.newDecoder();
CharBuffer cbuf = null;
try {
cbuf = decoder.decode(ByteBuffer.wrap(byteResp));
stringResponse = cbuf.toString();
} catch (CharacterCodingException e) {
e.printStackTrace();
}
success = (status == 200);
log("SendEvent - " + status + " " + stringResponse);
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
InternalStorage.getInstance().removeBuilder(request);
} else {
InternalStorage.getInstance().addRequest(request);
}
}
private byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
});
}
private static class SentryUncaughtExceptionHandler implements UncaughtExceptionHandler {
private final InternalStorage storage;
private final UncaughtExceptionHandler defaultExceptionHandler;
// constructor
public SentryUncaughtExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler, InternalStorage storage) {
defaultExceptionHandler = pDefaultExceptionHandler;
this.storage = storage;
}
@Override
public void uncaughtException(Thread thread, Throwable e) {
final Sentry sentry = Sentry.getInstance();
// Here you should have a more robust, permanent record of problems
SentryEventBuilder builder = new SentryEventBuilder(e, SentryEventLevel.FATAL);
builder.setRelease(Integer.toString(sentry.appInfo.versionCode));
if (sentry.captureListener != null) {
builder = sentry.captureListener.beforeCapture(builder);
}
if (builder != null) {
builder.event.put("contexts", sentry.contexts);
storage.addRequest(new SentryEventRequest(builder));
} else {
Log.e(Sentry.TAG, "SentryEventBuilder in uncaughtException is null");
}
//call original handler
defaultExceptionHandler.uncaughtException(thread, e);
}
}
private static class InternalStorage {
private final static String FILE_NAME = "unsent_requests";
private final List<SentryEventRequest> unsentRequests;
private static InternalStorage getInstance() {
return LazyHolder.instance;
}
private static class LazyHolder {
private static final InternalStorage instance = new InternalStorage();
}
private InternalStorage() {
Context context = Sentry.getInstance().context;
try {
File unsetRequestsFile = new File(context.getFilesDir(), FILE_NAME);
if (!unsetRequestsFile.exists()) {
writeObject(context, new ArrayList<Sentry.SentryEventRequest>());
}
} catch (Exception e) {
Log.e(TAG, "Error initializing storage", e);
}
this.unsentRequests = this.readObject(context);
}
/**
* @return the unsentRequests
*/
public List<SentryEventRequest> getUnsentRequests() {
final List<SentryEventRequest> copy = new ArrayList<>();
synchronized (this) {
copy.addAll(unsentRequests);
}
return copy;
}
public void addRequest(SentryEventRequest request) {
synchronized (this) {
log("Adding request - " + request.uuid);
if (!this.unsentRequests.contains(request)) {
this.unsentRequests.add(request);
this.writeObject(Sentry.getInstance().context, this.unsentRequests);
}
}
}
public void removeBuilder(SentryEventRequest request) {
synchronized (this) {
log("Removing request - " + request.uuid);
this.unsentRequests.remove(request);
this.writeObject(Sentry.getInstance().context, this.unsentRequests);
}
}
private void writeObject(Context context, List<SentryEventRequest> requests) {
try {
FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(requests);
oos.close();
fos.close();
} catch (IOException e) {
Log.e(TAG, "Error saving to storage", e);
}
}
private List<SentryEventRequest> readObject(Context context) {
try {
FileInputStream fis = context.openFileInput(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis);
List<SentryEventRequest> requests = (ArrayList<SentryEventRequest>) ois.readObject();
ois.close();
fis.close();
return requests;
} catch (IOException | ClassNotFoundException e) {
Log.e(TAG, "Error loading from storage", e);
}
return new ArrayList<>();
}
}
public interface SentryEventCaptureListener {
SentryEventBuilder beforeCapture(SentryEventBuilder builder);
}
private final static class Breadcrumb {
enum Type {
Default("default"),
HTTP("http"),
Navigation("navigation");
private final String value;
Type(String value) {
this.value = value;
}
}
final long timestamp;
final Type type;
final String message;
final String category;
final SentryEventLevel level;
final Map<String, String> data = new HashMap<>();
Breadcrumb(long timestamp, Type type, String message, String category, SentryEventLevel level) {
this.timestamp = timestamp;
this.type = type;
this.message = message;
this.category = category;
this.level = level;
}
}
private void pushBreadcrumb(Breadcrumb b) {
while (breadcrumbs.size() >= MAX_BREADCRUMBS) {
breadcrumbs.removeFirst();
}
breadcrumbs.add(b);
}
/**
* Record a breadcrumb to log a navigation from `from` to `to`.
* @param category A category to label the event under. This generally is similar to a logger
* name, and will let you more easily understand the area an event took place, such as auth.
* @param from A string representing the original application state / location.
* @param to A string representing the new application state / location.
*
* @see com.joshdholtz.sentry.Sentry#addHttpBreadcrumb(String, String, int)
*/
public static void addNavigationBreadcrumb(String category, String from, String to) {
final Breadcrumb b = new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.Navigation,
"",
category,
SentryEventLevel.INFO);
b.data.put("from", from);
b.data.put("to", to);
getInstance().pushBreadcrumb(b);
}
/**
* Record a HTTP request breadcrumb. This represents an HTTP request transmitted from your
* application. This could be an AJAX request from a web application, or a server-to-server HTTP
* request to an API service provider, etc.
*
* @param url The request URL.
* @param method The HTTP request method.
* @param statusCode The HTTP status code of the response.
*
* @see com.joshdholtz.sentry.Sentry#addHttpBreadcrumb(String, String, int)
*/
public static void addHttpBreadcrumb(String url, String method, int statusCode) {
final String reason = EnglishReasonPhraseCatalog.INSTANCE.getReason(statusCode, Locale.US);
final Breadcrumb b = new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.HTTP,
"",
String.format("http.%s", method.toLowerCase()),
SentryEventLevel.INFO);
b.data.put("url", url);
b.data.put("method", method);
b.data.put("status_code", Integer.toString(statusCode));
b.data.put("reason", reason);
getInstance().pushBreadcrumb(b);
}
/**
* Sentry supports a concept called Breadcrumbs, which is a trail of events which happened prior
* to an issue. Often times these events are very similar to traditional logs, but also have the
* ability to record more rich structured data.
*
* @param category A category to label the event under. This generally is similar to a logger
* name, and will let you more easily understand the area an event took place,
* such as auth.
*
* @param message A string describing the event. The most common vector, often used as a drop-in
* for a traditional log message.
*
* See https://docs.sentry.io/hosted/learn/breadcrumbs/
*
*/
public static void addBreadcrumb(String category, String message) {
getInstance().pushBreadcrumb(new Breadcrumb(
System.currentTimeMillis() / 1000,
Breadcrumb.Type.Default,
message,
category,
SentryEventLevel.INFO));
}
private JSONArray currentBreadcrumbs() {
final JSONArray crumbs = new JSONArray();
for (Breadcrumb breadcrumb : breadcrumbs) {
final JSONObject json = new JSONObject();
try {
json.put("timestamp", breadcrumb.timestamp);
json.put("type", breadcrumb.type.value);
json.put("message", breadcrumb.message);
json.put("category", breadcrumb.category);
json.put("level", breadcrumb.level.value);
json.put("data", new JSONObject(breadcrumb.data));
} catch (JSONException jse) {
Log.e(TAG, "Error serializing breadcrumbs", jse);
}
crumbs.put(json);
}
return crumbs;
}
public static class SentryEventRequest implements Serializable {
private final String requestData;
private final UUID uuid;
public SentryEventRequest(SentryEventBuilder builder) {
this.requestData = new JSONObject(builder.event).toString();
this.uuid = UUID.randomUUID();
}
/**
* @return the requestData
*/
public String getRequestData() {
return requestData;
}
/**
* @return the uuid
*/
public UUID getUuid() {
return uuid;
}
@Override
public boolean equals(Object other) {
SentryEventRequest otherRequest = (SentryEventRequest) other;
if (this.uuid != null && otherRequest.uuid != null) {
return uuid.equals(otherRequest.uuid);
}
return false;
}
}
/**
* The Sentry server assumes the time is in UTC.
* The timestamp should be in ISO 8601 format, without a timezone.
*/
private static DateFormat iso8601() {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format;
}
public static class SentryEventBuilder implements Serializable {
private static final long serialVersionUID = -8589756678369463988L;
// Match packages names that start with some well-known internal class-paths:
// java.*
// android.*
// com.android.*
// com.google.android.*
// dalvik.system.*
static final String isInternalPackage = "^(java|android|com\\.android|com\\.google\\.android|dalvik\\.system)\\..*";
private final static DateFormat timestampFormat = iso8601();
private final Map<String, Object> event;
public JSONObject toJSON() {
return new JSONObject(event);
}
public SentryEventBuilder() {
event = new HashMap<>();
event.put("event_id", UUID.randomUUID().toString().replace("-", ""));
event.put("platform", "java");
this.setTimestamp(System.currentTimeMillis());
}
public SentryEventBuilder(Throwable t, SentryEventLevel level) {
this();
String culprit = getCause(t, t.getMessage());
this.setMessage(t.getMessage())
.setCulprit(culprit)
.setLevel(level)
.setException(t);
}
/**
* "message": "SyntaxError: Wattttt!"
*
* @param message Message
* @return SentryEventBuilder
*/
public SentryEventBuilder setMessage(String message) {
event.put("message", message);
return this;
}
/**
* "timestamp": "2011-05-02T17:41:36"
*
* @param timestamp Timestamp
* @return SentryEventBuilder
*/
public SentryEventBuilder setTimestamp(long timestamp) {
event.put("timestamp", timestampFormat.format(new Date(timestamp)));
return this;
}
/**
* "level": "warning"
*
* @param level Level
* @return SentryEventBuilder
*/
public SentryEventBuilder setLevel(SentryEventLevel level) {
event.put("level", level.value);
return this;
}
/**
* "logger": "my.logger.name"
*
* @param logger Logger
* @return SentryEventBuilder
*/
public SentryEventBuilder setLogger(String logger) {
event.put("logger", logger);
return this;
}
/**
* "culprit": "my.module.function_name"
*
* @param culprit Culprit
* @return SentryEventBuilder
*/
public SentryEventBuilder setCulprit(String culprit) {
event.put("culprit", culprit);
return this;
}
/**
* @param user User
* @return SentryEventBuilder
*/
public SentryEventBuilder setUser(Map<String, String> user) {
setUser(new JSONObject(user));
return this;
}
public SentryEventBuilder setUser(JSONObject user) {
event.put("user", user);
return this;
}
public JSONObject getUser() {
if (!event.containsKey("user")) {
setTags(new HashMap<String, String>());
}
return (JSONObject) event.get("user");
}
/**
* @param tags Tags
* @return SentryEventBuilder
*/
public SentryEventBuilder setTags(Map<String, String> tags) {
setTags(new JSONObject(tags));
return this;
}
public SentryEventBuilder setTags(JSONObject tags) {
event.put("tags", tags);
return this;
}
public SentryEventBuilder addTag(String key, String value) {
try {
getTags().put(key, value);
} catch (JSONException e) {
Log.e(Sentry.TAG, "Error adding tag in SentryEventBuilder");
}
return this;
}
public JSONObject getTags() {
if (!event.containsKey("tags")) {
setTags(new HashMap<String, String>());
}
return (JSONObject) event.get("tags");
}
/**
* @param serverName Server name
* @return SentryEventBuilder
*/
public SentryEventBuilder setServerName(String serverName) {
event.put("server_name", serverName);
return this;
}
/**
* @param release Release
* @return SentryEventBuilder
*/
public SentryEventBuilder setRelease(String release) {
event.put("release", release);
return this;
}
/**
* @param name Name
* @param version Version
* @return SentryEventBuilder
*/
public SentryEventBuilder addModule(String name, String version) {
JSONArray modules;
if (!event.containsKey("modules")) {
modules = new JSONArray();
event.put("modules", modules);
} else {
modules = (JSONArray) event.get("modules");
}
if (name != null && version != null) {
String[] module = {name, version};
modules.put(new JSONArray(Arrays.asList(module)));
}
return this;
}
/**
* @param extra Extra
* @return SentryEventBuilder
*/
public SentryEventBuilder setExtra(Map<String, String> extra) {
setExtra(new JSONObject(extra));
return this;
}
public SentryEventBuilder setExtra(JSONObject extra) {
event.put("extra", extra);
return this;
}
public SentryEventBuilder addExtra(String key, String value) {
try {
getExtra().put(key, value);
} catch (JSONException e) {
Log.e(Sentry.TAG, "Error adding extra in SentryEventBuilder");
}
return this;
}
public JSONObject getExtra() {
if (!event.containsKey("extra")) {
setExtra(new HashMap<String, String>());
}
return (JSONObject) event.get("extra");
}
/**
* @param t Throwable
* @return SentryEventBuilder
*/
public SentryEventBuilder setException(Throwable t) {
JSONArray values = new JSONArray();
while (t != null) {
JSONObject exception = new JSONObject();
try {
exception.put("type", t.getClass().getSimpleName());
exception.put("value", t.getMessage());
exception.put("module", t.getClass().getPackage().getName());
exception.put("stacktrace", getStackTrace(t.getStackTrace()));
values.put(exception);
} catch (JSONException e) {
Log.e(TAG, "Failed to build sentry report for " + t, e);
}
t = t.getCause();
}
JSONObject exceptionReport = new JSONObject();
try {
exceptionReport.put("values", values);
event.put("exception", exceptionReport);
} catch (JSONException e) {
Log.e(TAG, "Unable to attach exception to event " + values, e);
}
return this;
}
private static JSONObject getStackTrace(StackTraceElement[] stackFrames) {
JSONObject stacktrace = new JSONObject();
try {
JSONArray frameList = new JSONArray();
// Java stack frames are in the opposite order from what the Sentry client API expects.
// > The zeroth element of the array (assuming the array's length is non-zero)
// > represents the top of the stack, which is the last method invocation in the
// > sequence.
// See:
// https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getStackTrace()
// https://docs.sentry.io/clientdev/interfaces/#failure-interfaces
//
// This code uses array indices rather a foreach construct since there is no built-in
// reverse iterator in the Java standard library. To use a foreach loop would require
// calling Collections.reverse which would require copying the array to a list.
for (int i = stackFrames.length - 1; i >= 0; i--) {
frameList.put(frameJson(stackFrames[i]));
}
stacktrace.put("frames", frameList);
} catch (JSONException e) {
Log.e(TAG, "Error serializing stack frames", e);
}
return stacktrace;
}
/**
* Add a stack trace to the event.
* A stack trace for the current thread can be obtained by using
* `Thread.currentThread().getStackTrace()`.
*
* @see Thread#currentThread()
* @see Thread#getStackTrace()
*/
public SentryEventBuilder setStackTrace(StackTraceElement[] stackTrace) {
this.event.put("stacktrace", getStackTrace(stackTrace));
return this;
}
// Convert a StackTraceElement to a sentry.interfaces.stacktrace.Stacktrace JSON object.
static JSONObject frameJson(StackTraceElement ste) throws JSONException {
final JSONObject frame = new JSONObject();
final String method = ste.getMethodName();
if (Present(method)) {
frame.put("function", method);
}
final String fileName = ste.getFileName();
if (Present(fileName)) {
frame.put("filename", fileName);
}
int lineno = ste.getLineNumber();
if (!ste.isNativeMethod() && lineno >= 0) {
frame.put("lineno", lineno);
}
String className = ste.getClassName();
frame.put("module", className);
// Take out some of the system packages to improve the exception folding on the sentry server
frame.put("in_app", !className.matches(isInternalPackage));
return frame;
}
}
/**
* Store a tuple of package version information captured from PackageInfo
*
* @see PackageInfo
*/
private final static class AppInfo {
final static AppInfo Empty = new AppInfo("", "", 0);
final String name;
final String versionName;
final int versionCode;
AppInfo(String name, String versionName, int versionCode) {
this.name = name;
this.versionName = versionName;
this.versionCode = versionCode;
}
static AppInfo Read(final Context context) {
try {
final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return new AppInfo(info.packageName, info.versionName, info.versionCode);
} catch (Exception e) {
Log.e(TAG, "Error reading package context", e);
return Empty;
}
}
}
private static JSONObject readContexts(Context context, AppInfo appInfo) {
final JSONObject contexts = new JSONObject();
try {
contexts.put("os", osContext());
contexts.put("device", deviceContext(context));
contexts.put("package", packageContext(appInfo));
} catch (JSONException e) {
Log.e(TAG, "Failed to build device contexts", e);
}
return contexts;
}
/**
* Read the device and build into a map.
* <p>
* Not implemented:
* - battery_level
* If the device has a battery this can be an integer defining the battery level (in
* the range 0-100). (Android requires registration of an intent to query the battery).
* - name
* The name of the device. This is typically a hostname.
* <p>
* See https://docs.getsentry.com/hosted/clientdev/interfaces/#context-types
*/
private static JSONObject deviceContext(Context context) {
final JSONObject device = new JSONObject();
try {
// The family of the device. This is normally the common part of model names across
// generations. For instance iPhone would be a reasonable family, so would be Samsung Galaxy.
device.put("family", Build.BRAND);
// The model name. This for instance can be Samsung Galaxy S3.
device.put("model", Build.PRODUCT);
// An internal hardware revision to identify the device exactly.
device.put("model_id", Build.MODEL);
final String architecture = System.getProperty("os.arch");
if (Present(architecture)) {
device.put("arch", architecture);
}
final int orient = context.getResources().getConfiguration().orientation;
device.put("orientation", orient == Configuration.ORIENTATION_LANDSCAPE ?
"landscape" : "portrait");
// Read screen resolution in the format "800x600"
// Normalised to have wider side first.
final Object windowManager = context.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null && windowManager instanceof WindowManager) {
final DisplayMetrics metrics = new DisplayMetrics();
((WindowManager) windowManager).getDefaultDisplay().getMetrics(metrics);
device.put("screen_resolution",
String.format("%sx%s",
Math.max(metrics.widthPixels, metrics.heightPixels),
Math.min(metrics.widthPixels, metrics.heightPixels)));
}
} catch (Exception e) {
Log.e(TAG, "Error reading device context", e);
}
return device;
}
private static JSONObject osContext() {
final JSONObject os = new JSONObject();
try {
os.put("type", "os");
os.put("name", "Android");
os.put("version", Build.VERSION.RELEASE);
if (Build.VERSION.SDK_INT < 4) {
os.put("build", Build.VERSION.SDK);
} else {
os.put("build", Integer.toString(Build.VERSION.SDK_INT));
}
final String kernelVersion = System.getProperty("os.version");
if (Present(kernelVersion)) {
os.put("kernel_version", kernelVersion);
}
} catch (Exception e) {
Log.e(TAG, "Error reading OS context", e);
}
return os;
}
/**
* Read the package data into map to be sent as an event context item.
* This is not a built-in context type.
*/
private static JSONObject packageContext(AppInfo appInfo) {
final JSONObject pack = new JSONObject();
try {
pack.put("type", "package");
pack.put("name", appInfo.name);
pack.put("version_name", appInfo.versionName);
pack.put("version_code", Integer.toString(appInfo.versionCode));
} catch (JSONException e) {
Log.e(TAG, "Error reading package context", e);
}
return pack;
}
/**
* Take the idea of `present?` from ActiveSupport.
*/
private static boolean Present(String s) {
return s != null && s.length() > 0;
}
}
| Fix docs
| sentry-android/src/main/java/com/joshdholtz/sentry/Sentry.java | Fix docs | <ide><path>entry-android/src/main/java/com/joshdholtz/sentry/Sentry.java
<ide> * A stack trace for the current thread can be obtained by using
<ide> * `Thread.currentThread().getStackTrace()`.
<ide> *
<add> * @param stackTrace StackTraceElement[]
<add> * @return SentryEventBuilder
<add> *
<ide> * @see Thread#currentThread()
<ide> * @see Thread#getStackTrace()
<ide> */ |
|
Java | agpl-3.0 | 5d701b7d5f58c4c0d4b8f2c16a2677e6197387a8 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | cb8c660c-2e61-11e5-9284-b827eb9e62be | hello.java | cb86fb0e-2e61-11e5-9284-b827eb9e62be | cb8c660c-2e61-11e5-9284-b827eb9e62be | hello.java | cb8c660c-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>cb86fb0e-2e61-11e5-9284-b827eb9e62be
<add>cb8c660c-2e61-11e5-9284-b827eb9e62be |
|
Java | mit | 47a9ec3bda298d68c1a034ee1253ad64305227b0 | 0 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicLib | package com.elmakers.mine.bukkit.spell;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.elmakers.mine.bukkit.api.event.CastEvent;
import com.elmakers.mine.bukkit.api.event.PreCastEvent;
import com.elmakers.mine.bukkit.api.spell.MageSpell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.TargetType;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.spell.SpellCategory;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.effect.EffectPlayer;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.Messages;
public abstract class BaseSpell implements MageSpell, Cloneable {
protected static final double VIEW_HEIGHT = 1.65;
protected static final double LOOK_THRESHOLD_RADIANS = 0.8;
// TODO: Config-drive
protected static final int MIN_Y = 1;
protected static final int MAX_Y = 255;
protected static final int MAX_NETHER_Y = 120;
// TODO: Configurable default? this does look cool, though.
protected final static Material DEFAULT_EFFECT_MATERIAL = Material.STATIONARY_WATER;
public final static String[] EXAMPLE_VECTOR_COMPONENTS = {"-1", "-0.5", "0", "0.5", "1", "~-1", "~-0.5", "~0", "~0.5", "*1", "*-1", "*-0.5", "*0.5", "*1"};
public final static String[] EXAMPLE_SIZES = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "12", "16", "32", "64"};
public final static String[] EXAMPLE_BOOLEANS = {"true", "false"};
public final static String[] EXAMPLE_DURATIONS = {"500", "1000", "2000", "5000", "10000", "60000", "120000"};
public final static String[] EXAMPLE_PERCENTAGES = {"0", "0.1", "0.25", "0.5", "0.75", "1"};
public final static String[] OTHER_PARAMETERS = {
"transparent", "target", "target_type", "range", "duration", "player"
};
public final static String[] WORLD_PARAMETERS = {
"pworld", "tworld", "otworld", "t2world"
};
protected final static Set<String> worldParameterMap = new HashSet<String>(Arrays.asList(WORLD_PARAMETERS));
public final static String[] VECTOR_PARAMETERS = {
"px", "py", "pz", "pdx", "pdy", "pdz", "tx", "ty", "tz", "otx", "oty", "otz", "t2x", "t2y", "t2z",
"otdx", "otdy", "otdz"
};
protected final static Set<String> vectorParameterMap = new HashSet<String>(Arrays.asList(VECTOR_PARAMETERS));
public final static String[] BOOLEAN_PARAMETERS = {
"allow_max_range", "prevent_passthrough", "passthrough", "bypass_build", "bypass_pvp", "target_npc"
};
protected final static Set<String> booleanParameterMap = new HashSet<String>(Arrays.asList(BOOLEAN_PARAMETERS));
public final static String[] PERCENTAGE_PARAMETERS = {
"fizzle_chance", "backfire_chance", "cooldown_reduction"
};
protected final static Set<String> percentageParameterMap = new HashSet<String>(Arrays.asList(PERCENTAGE_PARAMETERS));
public final static String[] COMMON_PARAMETERS = (String[])
ArrayUtils.addAll(
ArrayUtils.addAll(
ArrayUtils.addAll(
ArrayUtils.addAll(VECTOR_PARAMETERS, BOOLEAN_PARAMETERS),
OTHER_PARAMETERS
),
WORLD_PARAMETERS
),
PERCENTAGE_PARAMETERS
);
/*
* protected members that are helpful to use
*/
protected MageController controller;
protected Mage mage;
protected Location location;
/*
* Variant properties
*/
private SpellKey spellKey;
private String name;
private String alias;
private String description;
private String extendedDescription;
private String levelDescription;
private String upgradeDescription;
private String usage;
private long worth;
private Color color;
private String particle;
private SpellCategory category;
private BaseSpell template;
private MageSpell upgrade;
private long requiredUpgradeCasts;
private String requiredUpgradePath;
private MaterialAndData icon = new MaterialAndData(Material.AIR);
private String iconURL = null;
private List<CastingCost> costs = null;
private List<CastingCost> activeCosts = null;
protected boolean pvpRestricted = false;
protected boolean bypassPvpRestriction = false;
protected boolean bypassConfusion = false;
protected boolean bypassPermissions = false;
protected boolean castOnNoTarget = false;
protected boolean bypassDeactivate = false;
protected boolean quiet = false;
protected boolean loud = false;
private boolean backfired = false;
private boolean hidden = false;
protected ConfigurationSection parameters = null;
protected ConfigurationSection configuration = null;
protected static Random random = new Random();
protected Set<UUID> targetMessagesSent = new HashSet<UUID>();
/*
* private data
*/
private float cooldownReduction = 0;
private float costReduction = 0;
private int cooldown = 0;
private int duration = 0;
private long lastCast = 0;
private long castCount = 0;
private boolean isActive = false;
private Map<String, Collection<EffectPlayer>> effects = new HashMap<String, Collection<EffectPlayer>>();
private float fizzleChance = 0.0f;
private float backfireChance = 0.0f;
private long lastMessageSent = 0;
private Set<Material> preventPassThroughMaterials = null;
private Set<Material> passthroughMaterials = null;
private Collection<EffectPlayer> currentEffects = null;
public boolean allowPassThrough(Material mat)
{
if (mage != null && mage.isSuperPowered()) {
return true;
}
if (passthroughMaterials != null && passthroughMaterials.contains(mat)) {
return true;
}
return preventPassThroughMaterials == null || !preventPassThroughMaterials.contains(mat);
}
/*
* Ground / location search and test functions
*/
public boolean isOkToStandIn(Material mat)
{
return passthroughMaterials.contains(mat);
}
public boolean isWater(Material mat)
{
return (mat == Material.WATER || mat == Material.STATIONARY_WATER);
}
public boolean isOkToStandOn(Material mat)
{
return (mat != Material.AIR && mat != Material.LAVA && mat != Material.STATIONARY_LAVA);
}
public boolean isSafeLocation(Block block)
{
if (!block.getChunk().isLoaded()) {
block.getChunk().load(true);
return false;
}
if (block.getY() > MAX_Y) {
return false;
}
Block blockOneUp = block.getRelative(BlockFace.UP);
Block blockOneDown = block.getRelative(BlockFace.DOWN);
Player player = mage.getPlayer();
return (
(isOkToStandOn(blockOneDown.getType()) || (player != null && player.isFlying()))
&& isOkToStandIn(blockOneUp.getType())
&& isOkToStandIn(block.getType())
);
}
public boolean isSafeLocation(Location loc)
{
return isSafeLocation(loc.getBlock());
}
public Location tryFindPlaceToStand(Location targetLoc)
{
return tryFindPlaceToStand(targetLoc, MAX_Y, MAX_Y);
}
public Location tryFindPlaceToStand(Location targetLoc, int maxDownDelta, int maxUpDelta)
{
Location location = findPlaceToStand(targetLoc, maxDownDelta, maxUpDelta);
return location == null ? targetLoc : location;
}
public Location findPlaceToStand(Location targetLoc, int maxDownDelta, int maxUpDelta)
{
if (!targetLoc.getBlock().getChunk().isLoaded()) return null;
int minY = MIN_Y;
int maxY = targetLoc.getWorld().getEnvironment() == Environment.NETHER ? MAX_NETHER_Y : MAX_Y;
int targetY = targetLoc.getBlockY();
if (targetY >= minY && targetY <= maxY && isSafeLocation(targetLoc)) return targetLoc;
Location location = null;
if (targetY < minY) {
location = targetLoc.clone();
location.setY(minY);
location = findPlaceToStand(location, true, maxUpDelta);
} else if (targetY > maxY) {
location = targetLoc.clone();
location.setY(maxY);
location = findPlaceToStand(location, false, maxDownDelta);
} else {
// First look down just a little bit
int testMinY = Math.min(maxDownDelta, 4);
location = findPlaceToStand(targetLoc, false, testMinY);
// Then look up
if (location == null) {
location = findPlaceToStand(targetLoc, true, maxUpDelta);
}
// Then look allll the way down.
if (location == null) {
location = findPlaceToStand(targetLoc, false, maxDownDelta);
}
}
return location;
}
public Location findPlaceToStand(Location target, boolean goUp)
{
return findPlaceToStand(target, goUp, MAX_Y);
}
public Location findPlaceToStand(Location target, boolean goUp, int maxDelta)
{
int direction = goUp ? 1 : -1;
// search for a spot to stand
Location targetLocation = target.clone();
int yDelta = 0;
int minY = MIN_Y;
int maxY = targetLocation.getWorld().getEnvironment() == Environment.NETHER ? MAX_NETHER_Y : MAX_Y;
while (minY <= targetLocation.getY() && targetLocation.getY() <= maxY && yDelta < maxDelta)
{
Block block = targetLocation.getBlock();
if
(
isSafeLocation(block)
&& !(goUp && isUnderwater() && isWater(block.getType())) // rise to surface of water
)
{
// spot found - return location
return targetLocation;
}
if (!allowPassThrough(block.getType())) {
return null;
}
yDelta++;
targetLocation.setY(targetLocation.getY() + direction);
}
// no spot found
return null;
}
/**
* Get the block the player is standing on.
*
* @return The Block the player is standing on
*/
public Block getPlayerBlock()
{
Location location = getLocation();
if (location == null) return null;
return location.getBlock().getRelative(BlockFace.DOWN);
}
/**
* Get the direction the player is facing as a BlockFace.
*
* @return a BlockFace representing the direction the player is facing
*/
public BlockFace getPlayerFacing()
{
return getFacing(getLocation());
}
public static BlockFace getFacing(Location location)
{
float playerRot = location.getYaw();
while (playerRot < 0)
playerRot += 360;
while (playerRot > 360)
playerRot -= 360;
BlockFace direction = BlockFace.NORTH;
if (playerRot <= 45 || playerRot > 315)
{
direction = BlockFace.SOUTH;
}
else if (playerRot > 45 && playerRot <= 135)
{
direction = BlockFace.WEST;
}
else if (playerRot > 135 && playerRot <= 225)
{
direction = BlockFace.NORTH;
}
else if (playerRot > 225 && playerRot <= 315)
{
direction = BlockFace.EAST;
}
return direction;
}
/*
* Functions to send text to player- use these to respect "quiet" and "silent" modes.
*/
/**
* Send a message to a player when a spell is cast.
*
* @param message The message to send
*/
public void castMessage(String message)
{
if (!quiet && canSendMessage() && message != null && message.length() > 0)
{
mage.castMessage(message);
lastMessageSent = System.currentTimeMillis();
}
}
/**
* Send a message to a player.
*
* Use this to send messages to the player that are important.
*
* @param message The message to send
*/
public void sendMessage(String message)
{
if (!quiet && message != null && message.length() > 0)
{
mage.sendMessage(message);
lastMessageSent = System.currentTimeMillis();
}
}
public Location getLocation()
{
if (location != null) return location.clone();
if (mage != null) {
return mage.getLocation();
}
return null;
}
public Location getEyeLocation()
{
Location location = getLocation();
if (location == null) return null;
location.setY(location.getY() + 1.5);
return location;
}
public Vector getDirection()
{
if (location == null) {
return mage.getDirection();
}
return location.getDirection();
}
public boolean isLookingUp()
{
Vector direction = getDirection();
if (direction == null) return false;
return direction.getY() > LOOK_THRESHOLD_RADIANS;
}
public boolean isLookingDown()
{
Vector direction = getDirection();
if (direction == null) return false;
return direction.getY() < -LOOK_THRESHOLD_RADIANS;
}
public World getWorld()
{
Location location = getLocation();
if (location != null) return location.getWorld();
return null;
}
/**
* Check to see if the player is underwater
*
* @return true if the player is underwater
*/
public boolean isUnderwater()
{
Block playerBlock = getPlayerBlock();
if (playerBlock == null) return false;
playerBlock = playerBlock.getRelative(BlockFace.UP);
return (playerBlock.getType() == Material.WATER || playerBlock.getType() == Material.STATIONARY_WATER);
}
protected String getBlockSkin(Material blockType) {
String skinName = null;
switch (blockType) {
case CACTUS:
skinName = "MHF_Cactus";
break;
case CHEST:
skinName = "MHF_Chest";
break;
case MELON_BLOCK:
skinName = "MHF_Melon";
break;
case TNT:
if (random.nextDouble() > 0.5) {
skinName = "MHF_TNT";
} else {
skinName = "MHF_TNT2";
}
break;
case LOG:
skinName = "MHF_OakLog";
break;
case PUMPKIN:
skinName = "MHF_Pumpkin";
break;
default:
// TODO .. ?
/*
* Blocks:
Bonus:
MHF_ArrowUp
MHF_ArrowDown
MHF_ArrowLeft
MHF_ArrowRight
MHF_Exclamation
MHF_Question
*/
}
return skinName;
}
protected String getMobSkin(EntityType mobType)
{
String mobSkin = null;
switch (mobType) {
case BLAZE:
mobSkin = "MHF_Blaze";
break;
case CAVE_SPIDER:
mobSkin = "MHF_CaveSpider";
break;
case CHICKEN:
mobSkin = "MHF_Chicken";
break;
case COW:
mobSkin = "MHF_Cow";
break;
case ENDERMAN:
mobSkin = "MHF_Enderman";
break;
case GHAST:
mobSkin = "MHF_Ghast";
break;
case IRON_GOLEM:
mobSkin = "MHF_Golem";
break;
case MAGMA_CUBE:
mobSkin = "MHF_LavaSlime";
break;
case MUSHROOM_COW:
mobSkin = "MHF_MushroomCow";
break;
case OCELOT:
mobSkin = "MHF_Ocelot";
break;
case PIG:
mobSkin = "MHF_Pig";
break;
case PIG_ZOMBIE:
mobSkin = "MHF_PigZombie";
break;
case SHEEP:
mobSkin = "MHF_Sheep";
break;
case SLIME:
mobSkin = "MHF_Slime";
break;
case SPIDER:
mobSkin = "MHF_Spider";
break;
case SQUID:
mobSkin = "MHF_Squid";
break;
case VILLAGER:
mobSkin = "MHF_Villager";
default:
// TODO: Find skins for SKELETON, CREEPER and ZOMBIE .. ?
}
return mobSkin;
}
public static Collection<PotionEffect> getPotionEffects(ConfigurationSection parameters)
{
return getPotionEffects(parameters, null);
}
public static Collection<PotionEffect> getPotionEffects(ConfigurationSection parameters, Integer duration)
{
List<PotionEffect> effects = new ArrayList<PotionEffect>();
PotionEffectType[] effectTypes = PotionEffectType.values();
for (PotionEffectType effectType : effectTypes) {
// Why is there a null entry in this list? Maybe a 1.7 bug?
if (effectType == null) continue;
String parameterName = "effect_" + effectType.getName().toLowerCase();
if (parameters.contains(parameterName)) {
String value = parameters.getString(parameterName);
int ticks = 10;
int power = 1;
try {
if (value.contains(",")) {
String[] pieces = value.split(",");
ticks = (int)Float.parseFloat(pieces[0]);
power = (int)Float.parseFloat(pieces[1]);
} else {
power = (int)Float.parseFloat(value);
if (duration != null) {
ticks = duration / 50;
}
}
} catch (Exception ex) {
Bukkit.getLogger().warning("Error parsing potion effect for " + effectType + ": " + value);
}
PotionEffect effect = new PotionEffect(effectType, ticks, power, true);
effects.add(effect);
}
}
return effects;
}
public boolean isInCircle(int x, int z, int R)
{
return ((x * x) + (z * z) - (R * R)) <= 0;
}
private boolean canSendMessage()
{
if (lastMessageSent == 0) return true;
int throttle = controller.getMessageThrottle();
long now = System.currentTimeMillis();
return (lastMessageSent < now - throttle);
}
protected Location getEffectLocation()
{
return getEyeLocation();
}
public FireworkEffect getFireworkEffect() {
return getFireworkEffect(null, null, null, null, null);
}
public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType) {
return getFireworkEffect(color1, color2, fireworkType, null, null);
}
public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType, Boolean flicker, Boolean trail) {
Color wandColor = mage == null ? null : mage.getEffectColor();
if (wandColor != null) {
color1 = wandColor;
color2 = wandColor.mixColors(color1, Color.WHITE);
} else {
if (color1 == null) {
color1 = Color.fromRGB(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
if (color2 == null) {
color2 = Color.fromRGB(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
}
if (fireworkType == null) {
fireworkType = org.bukkit.FireworkEffect.Type.values()[random.nextInt(org.bukkit.FireworkEffect.Type.values().length)];
}
if (flicker == null) {
flicker = random.nextBoolean();
}
if (trail == null) {
trail = random.nextBoolean();
}
return FireworkEffect.builder().flicker(flicker).withColor(color1).withFade(color2).with(fireworkType).trail(trail).build();
}
public boolean hasBrushOverride()
{
return false;
}
@Override
public boolean usesBrush()
{
return false;
}
@Override
public boolean isUndoable()
{
return false;
}
public void checkActiveCosts() {
if (activeCosts == null) return;
for (CastingCost cost : activeCosts)
{
if (!cost.has(this))
{
deactivate();
return;
}
cost.use(this);
}
}
public void checkActiveDuration() {
if (duration > 0 && lastCast < System.currentTimeMillis() - duration) {
deactivate();
}
}
protected List<CastingCost> parseCosts(ConfigurationSection node) {
if (node == null) {
return null;
}
List<CastingCost> castingCosts = new ArrayList<CastingCost>();
Set<String> costKeys = node.getKeys(false);
for (String key : costKeys)
{
castingCosts.add(new CastingCost(key, node.getInt(key, 1)));
}
return castingCosts;
}
@SuppressWarnings("unchecked")
protected void loadTemplate(ConfigurationSection node)
{
// Get localizations
String baseKey = spellKey.getBaseKey();
// Message defaults come from the messages.yml file
name = controller.getMessages().get("spells." + baseKey + ".name", baseKey);
description = controller.getMessages().get("spells." + baseKey + ".description", "");
extendedDescription = controller.getMessages().get("spells." + baseKey + ".extended_description", "");
usage = controller.getMessages().get("spells." + baseKey + ".usage", "");
// Upgrade path information
// The actual upgrade spell will be set externally.
requiredUpgradePath = node.getString("upgrade_required_path");
requiredUpgradeCasts = node.getLong("upgrade_required_casts");
// Can be overridden by the base spell, or the variant spell
levelDescription = controller.getMessages().get("spells." + baseKey + ".level_description", levelDescription);
upgradeDescription = controller.getMessages().get("spells." + baseKey + ".upgrade_description", upgradeDescription);
// Spell level variants can override
if (spellKey.isVariant()) {
String variantKey = spellKey.getKey();
name = controller.getMessages().get("spells." + variantKey + ".name", name);
description = controller.getMessages().get("spells." + variantKey + ".description", description);
extendedDescription = controller.getMessages().get("spells." + variantKey + ".extended_description", extendedDescription);
usage = controller.getMessages().get("spells." + variantKey + ".usage", usage);
// Level description defaults to pre-formatted text
levelDescription = controller.getMessages().get("spell.level_description", levelDescription);
// Any spell may have a level description, including base spells if chosen.
// Base spells must specify their own level in each spell config though,
// they don't get an auto-generated one.
levelDescription = controller.getMessages().get("spells." + variantKey + ".level_description", levelDescription);
upgradeDescription = controller.getMessages().get("spells." + variantKey + ".upgrade_description", upgradeDescription);
}
// Individual spell configuration overrides all
name = node.getString("name", name);
alias = node.getString("alias", "");
extendedDescription = node.getString("extended_description", extendedDescription);
description = node.getString("description", description);
levelDescription = node.getString("level_description", levelDescription);
// Parameterize level description
if (levelDescription != null && !levelDescription.isEmpty()) {
levelDescription = levelDescription.replace("$level", Integer.toString(spellKey.getLevel()));
}
// Load basic properties
icon = ConfigurationUtils.getMaterialAndData(node, "icon", icon);
iconURL = node.getString("icon_url");
color = ConfigurationUtils.getColor(node, "color", null);
worth = node.getLong("worth", worth);
category = controller.getCategory(node.getString("category"));
parameters = node.getConfigurationSection("parameters");
costs = parseCosts(node.getConfigurationSection("costs"));
activeCosts = parseCosts(node.getConfigurationSection("active_costs"));
pvpRestricted = node.getBoolean("pvp_restricted", pvpRestricted);
castOnNoTarget = node.getBoolean("cast_on_no_target", castOnNoTarget);
hidden = node.getBoolean("hidden", false);
// Preload some parameters
ConfigurationSection parameters = node.getConfigurationSection("parameters");
if (parameters != null) {
cooldown = parameters.getInt("cooldown", cooldown);
cooldown = parameters.getInt("cool", cooldown);
bypassPvpRestriction = parameters.getBoolean("bypass_pvp", bypassPvpRestriction);
bypassPvpRestriction = parameters.getBoolean("bp", bypassPvpRestriction);
bypassPermissions = parameters.getBoolean("bypass_permissions", bypassPermissions);
duration = parameters.getInt("duration", duration);
}
effects.clear();
if (node.contains("effects")) {
ConfigurationSection effectsNode = node.getConfigurationSection("effects");
Collection<String> effectKeys = effectsNode.getKeys(false);
for (String effectKey : effectKeys) {
if (effectsNode.isString(effectKey)) {
String referenceKey = effectsNode.getString(effectKey);
if (effects.containsKey(referenceKey)) {
effects.put(effectKey, new ArrayList(effects.get(referenceKey)));
}
}
else
{
effects.put(effectKey, EffectPlayer.loadEffects(controller.getPlugin(), effectsNode, effectKey));
}
}
}
}
protected void preCast()
{
}
protected void reset()
{
Location mageLocation = mage != null ? mage.getLocation() : null;
// Kind of a hack, but assume the default location has no direction.
if (this.location != null && mageLocation != null) {
this.location.setPitch(mageLocation.getPitch());
this.location.setYaw(mageLocation.getYaw());
}
backfired = false;
cancelEffects();
}
public boolean cast(String[] extraParameters, Location defaultLocation)
{
this.reset();
targetMessagesSent.clear();
// Allow other plugins to cancel this cast
PreCastEvent preCast = new PreCastEvent(mage, this);
Bukkit.getPluginManager().callEvent(preCast);
if (preCast.isCancelled()) {
processResult(SpellResult.CANCELLED);
return false;
}
if (this.parameters == null) {
this.parameters = new MemoryConfiguration();
}
this.location = defaultLocation;
final ConfigurationSection parameters = new MemoryConfiguration();
ConfigurationUtils.addConfigurations(parameters, this.parameters);
ConfigurationUtils.addParameters(extraParameters, parameters);
processParameters(parameters);
// Don't allow casting if the player is confused
bypassConfusion = parameters.getBoolean("bypass_confusion", bypassConfusion);
LivingEntity livingEntity = mage.getLivingEntity();
if (livingEntity != null && !bypassConfusion && !mage.isSuperPowered() && livingEntity.hasPotionEffect(PotionEffectType.CONFUSION)) {
processResult(SpellResult.CURSED);
return false;
}
// Don't perform permission check until after processing parameters, in case of overrides
if (!canCast(getLocation())) {
processResult(SpellResult.INSUFFICIENT_PERMISSION);
return false;
}
this.preCast();
// PVP override settings
bypassPvpRestriction = parameters.getBoolean("bypass_pvp", false);
bypassPvpRestriction = parameters.getBoolean("bp", bypassPvpRestriction);
bypassPermissions = parameters.getBoolean("bypass_permissions", bypassPermissions);
// Check cooldowns
cooldown = parameters.getInt("cooldown", cooldown);
cooldown = parameters.getInt("cool", cooldown);
// Color override
color = ConfigurationUtils.getColor(parameters, "color", color);
particle = parameters.getString("particle", null);
long cooldownRemaining = getRemainingCooldown() / 1000;
String timeDescription = "";
if (cooldownRemaining > 0) {
if (cooldownRemaining > 60 * 60 ) {
long hours = cooldownRemaining / (60 * 60);
if (hours == 1) {
timeDescription = controller.getMessages().get("cooldown.wait_hour");
} else {
timeDescription = controller.getMessages().get("cooldown.wait_hours").replace("$hours", ((Long) hours).toString());
}
} else if (cooldownRemaining > 60) {
long minutes = cooldownRemaining / 60;
if (minutes == 1) {
timeDescription = controller.getMessages().get("cooldown.wait_minute");
} else {
timeDescription = controller.getMessages().get("cooldown.wait_minutes").replace("$minutes", ((Long) minutes).toString());
}
} else if (cooldownRemaining > 1) {
timeDescription = controller.getMessages().get("cooldown.wait_seconds").replace("$seconds", ((Long)cooldownRemaining).toString());
} else {
timeDescription = controller.getMessages().get("cooldown.wait_moment");
}
sendMessage(getMessage("cooldown").replace("$time", timeDescription));
processResult(SpellResult.COOLDOWN);
return false;
}
com.elmakers.mine.bukkit.api.spell.CastingCost required = getRequiredCost();
if (required != null) {
String baseMessage = getMessage("insufficient_resources");
String costDescription = required.getDescription(controller.getMessages(), mage);
sendMessage(baseMessage.replace("$cost", costDescription));
processResult(SpellResult.INSUFFICIENT_RESOURCES);
return false;
}
return finalizeCast(parameters);
}
public boolean canCast(Location location) {
if (!hasCastPermission(mage.getCommandSender())) return false;
Boolean regionPermission = controller.getRegionCastPermission(mage.getPlayer(), this, location);
if (regionPermission != null && regionPermission == true) return true;
if (regionPermission != null && regionPermission == false) return false;
if (requiresBuildPermission() && !hasBuildPermission(location.getBlock())) return false;
return !pvpRestricted || bypassPvpRestriction || mage.isPVPAllowed(location);
}
public boolean requiresBuildPermission() {
return false;
}
public boolean hasBuildPermission(Block block) {
// Cast permissions bypass
Boolean castPermission = controller.getRegionCastPermission(mage.getPlayer(), this, block.getLocation());
if (castPermission != null && castPermission == true) return true;
if (castPermission != null && castPermission == false) return false;
return mage.hasBuildPermission(block);
}
protected void onBackfire() {
}
protected void backfire() {
if (!backfired) {
onBackfire();
}
backfired = true;
}
protected boolean finalizeCast(ConfigurationSection parameters) {
SpellResult result = null;
// Global parameters
controller.disablePhysics(parameters.getInt("disable_physics", 0));
if (!mage.isSuperPowered()) {
if (backfireChance > 0 && random.nextDouble() < backfireChance) {
backfire();
} else if (fizzleChance > 0 && random.nextDouble() < fizzleChance) {
result = SpellResult.FIZZLE;
}
}
if (result == null) {
result = onCast(parameters);
}
if (backfired) {
result = SpellResult.BACKFIRE;
}
processResult(result);
boolean success = result.isSuccess();
boolean requiresCost = success || (castOnNoTarget && result == SpellResult.NO_TARGET);
boolean free = !requiresCost && result.isFree();
if (!free) {
lastCast = System.currentTimeMillis();
if (costs != null && !mage.isCostFree()) {
for (CastingCost cost : costs)
{
cost.use(this);
}
}
}
if (success) {
castCount++;
if (template != null) {
template.castCount++;
}
}
return success;
}
public String getMessage(String messageKey) {
return getMessage(messageKey, "");
}
public String getMessage(String messageKey, String def) {
String message = controller.getMessages().get("spells.default." + messageKey, def);
message = controller.getMessages().get("spells." + spellKey.getBaseKey() + "." + messageKey, message);
if (spellKey.isVariant()) {
message = controller.getMessages().get("spells." + spellKey.getKey() + "." + messageKey, message);
}
if (message == null) message = "";
// Escape some common parameters
String playerName = mage.getName();
message = message.replace("$player", playerName);
String materialName = getDisplayMaterialName();
// TODO: Localize "None", provide static getter
materialName = materialName == null ? "None" : materialName;
message = message.replace("$material", materialName);
return message;
}
protected String getDisplayMaterialName()
{
return "None";
}
protected void processResult(SpellResult result) {
// Notify other plugins of this spell cast
CastEvent castEvent = new CastEvent(mage, this, result);
Bukkit.getPluginManager().callEvent(castEvent);
if (mage != null) {
mage.onCast(this, result);
}
// Show messaging
String resultName = result.name().toLowerCase();
if (result.isSuccess()) {
String message = null;
if (result != SpellResult.CAST) {
message = getMessage("cast");
}
if (result.isAlternate() && result != SpellResult.ALTERNATE) {
message = getMessage("alternate", message);
}
message = getMessage(resultName, message);
LivingEntity sourceEntity = mage.getLivingEntity();
Entity targetEntity = getTargetEntity();
if (targetEntity == sourceEntity) {
message = getMessage("cast_self", message);
} else if (targetEntity instanceof Player) {
message = getMessage("cast_player", message);
} else if (targetEntity instanceof LivingEntity) {
message = getMessage("cast_livingentity", message);
} else if (targetEntity instanceof Entity) {
message = getMessage("cast_entity", message);
}
if (loud) {
sendMessage(message);
} else {
castMessage(message);
}
messageTargets("cast_player_message");
} else
// Special cases where messaging is handled elsewhere
if (result != SpellResult.INSUFFICIENT_RESOURCES && result != SpellResult.COOLDOWN)
{
String message = null;
if (result.isFailure() && result != SpellResult.FAIL) {
message = getMessage("fail");
}
sendMessage(getMessage(resultName, message));
}
// Play effects
playEffects(resultName);
}
public void messageTargets(String messageKey)
{
LivingEntity sourceEntity = mage == null ? null : mage.getLivingEntity();
String playerMessage = getMessage(messageKey);
if (!mage.isStealth() && playerMessage.length() > 0)
{
Collection<Entity> targets = getTargetEntities();
for (Entity target : targets)
{
UUID targetUUID = target.getUniqueId();
if (target instanceof Player && target != sourceEntity && !targetMessagesSent.contains(targetUUID))
{
targetMessagesSent.add(targetUUID);
playerMessage = playerMessage.replace("$spell", getName());
Mage targetMage = controller.getMage(target);
targetMage.sendMessage(playerMessage);
}
}
}
}
public void playEffects(String effectName, float scale) {
playEffects(effectName, scale, getEffectLocation(), mage.getEntity(), getTargetLocation(), getTargetEntity());
}
public void playEffects(String effectName)
{
playEffects(effectName, 1);
}
@Override
public void playEffects(String effectName, float scale, Location source, Entity sourceEntity, Location targetLocation, Entity targetEntity)
{
if (effects.containsKey(effectName) && source != null)
{
cancelEffects();
currentEffects = effects.get(effectName);
Collection<Entity> targeted = getTargetEntities();
for (EffectPlayer player : currentEffects)
{
// Set scale
player.setScale(scale);
// Set material and color
player.setMaterial(getEffectMaterial());
player.setColor(mage.getEffectColor());
String overrideParticle = particle != null ? particle : mage.getEffectParticleName();
player.setParticleOverride(overrideParticle);
if (player.shouldPlayAtAllTargets())
{
player.start(source, sourceEntity, targeted);
}
else
{
player.start(source, sourceEntity, targetLocation, targetEntity);
}
}
}
}
@Override
public void target() {
}
@Override
public Location getTargetLocation() {
return null;
}
@Override
public boolean canTarget(Entity entity) {
return true;
}
@Override
public Entity getTargetEntity() {
return null;
}
public Collection<Entity> getTargetEntities() {
return null;
}
public com.elmakers.mine.bukkit.api.block.MaterialAndData getEffectMaterial()
{
return new MaterialAndData(DEFAULT_EFFECT_MATERIAL);
}
protected void processParameters(ConfigurationSection parameters) {
fizzleChance = (float)parameters.getDouble("fizzle_chance", fizzleChance);
backfireChance = (float)parameters.getDouble("backfire_chance", backfireChance);
Location defaultLocation = location == null ? mage.getLocation() : location;
Location locationOverride = ConfigurationUtils.overrideLocation(parameters, "p", defaultLocation, controller.canCreateWorlds());
if (locationOverride != null) {
location = locationOverride;
}
costReduction = (float)parameters.getDouble("cost_reduction", 0);
cooldownReduction = (float)parameters.getDouble("cooldown_reduction", 0);
if (parameters.contains("prevent_passthrough")) {
preventPassThroughMaterials = controller.getMaterialSet(parameters.getString("prevent_passthrough"));
} else {
preventPassThroughMaterials = controller.getMaterialSet("indestructible");
}
if (parameters.contains("passthrough")) {
passthroughMaterials = controller.getMaterialSet(parameters.getString("passthrough"));
} else {
passthroughMaterials = controller.getMaterialSet("passthrough");
}
bypassDeactivate = parameters.getBoolean("bypass_deactivate", false);
quiet = parameters.getBoolean("quiet", false);
loud = parameters.getBoolean("loud", false);
}
public String getPermissionNode()
{
return "Magic.cast." + spellKey.getBaseKey();
}
/**
* Called when a material selection spell is cancelled mid-selection.
*/
public boolean onCancel()
{
return false;
}
/**
* Listener method, called on player quit for registered spells.
*
* @param event The player who just quit
*/
public void onPlayerQuit(PlayerQuitEvent event)
{
}
/**
* Listener method, called on player move for registered spells.
*
* @param event The original entity death event
*/
public void onPlayerDeath(EntityDeathEvent event)
{
}
public void onPlayerDamage(EntityDamageEvent event)
{
}
/**
* Used internally to initialize the Spell, do not call.
*
* @param instance The spells instance
*/
public void initialize(MageController instance)
{
this.controller = instance;
}
@Override
public long getCastCount()
{
return castCount;
}
@Override
public void setCastCount(long count) {
castCount = count;
}
public void onActivate() {
}
public void onDeactivate() {
}
/**
* Called on player data load.
*/
public void onLoad(ConfigurationSection node)
{
}
/**
* Called on player data save.
*
* @param node The configuration node to load data from.
*/
public void onSave(ConfigurationSection node)
{
}
//
// Cloneable implementation
//
@Override
public Object clone()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException ex)
{
return null;
}
}
//
// CostReducer Implementation
//
@Override
public float getCostReduction()
{
return costReduction + mage.getCostReduction();
}
//
// Public API Implementation
//
@Override
public com.elmakers.mine.bukkit.api.spell.Spell createSpell()
{
BaseSpell spell = null;
try {
spell = (BaseSpell) this.getClass().newInstance();
spell.initialize(controller);
spell.loadTemplate(spellKey.getKey(), configuration);
spell.template = this;
} catch (Exception ex) {
controller.getLogger().log(Level.WARNING, "Error creating spell", ex);
}
return spell;
}
@Override
public boolean cast()
{
return cast(null, null);
}
@Override
public boolean cast(String[] extraParameters)
{
return cast(extraParameters, null);
}
@Override
public final String getKey()
{
return spellKey.getKey();
}
@Override
public final String getName()
{
return name;
}
@Override
public final String getAlias()
{
return alias;
}
@Override
public final com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon()
{
return icon;
}
@Override
public boolean hasIcon() {
return icon != null && icon.getMaterial() != Material.AIR;
}
@Override
public final String getDescription()
{
return description;
}
@Override
public final String getExtendedDescription()
{
return extendedDescription;
}
@Override
public final String getLevelDescription()
{
return levelDescription;
}
@Override
public final SpellKey getSpellKey()
{
return spellKey;
}
@Override
public final String getUsage()
{
return usage;
}
@Override
public final long getWorth()
{
return worth;
}
@Override
public final SpellCategory getCategory()
{
return category;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.effect.EffectPlayer> getEffects(SpellResult result) {
return getEffects(result.name().toLowerCase());
}
@Override
public Collection<com.elmakers.mine.bukkit.api.effect.EffectPlayer> getEffects(String key) {
Collection<EffectPlayer> effectList = effects.get(key);
if (effectList == null) {
return new ArrayList<com.elmakers.mine.bukkit.api.effect.EffectPlayer>();
}
return new ArrayList<com.elmakers.mine.bukkit.api.effect.EffectPlayer>(effectList);
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.CastingCost> getCosts() {
if (costs == null) return null;
List<com.elmakers.mine.bukkit.api.spell.CastingCost> copy = new ArrayList<com.elmakers.mine.bukkit.api.spell.CastingCost>();
copy.addAll(costs);
return copy;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.CastingCost> getActiveCosts() {
if (activeCosts == null) return null;
List<com.elmakers.mine.bukkit.api.spell.CastingCost> copy = new ArrayList<com.elmakers.mine.bukkit.api.spell.CastingCost>();
copy.addAll(activeCosts);
return copy;
}
@Override
public void getParameters(Collection<String> parameters)
{
parameters.addAll(Arrays.asList(COMMON_PARAMETERS));
}
@Override
public void getParameterOptions(Collection<String> examples, String parameterKey)
{
if (parameterKey.equals("duration")) {
examples.addAll(Arrays.asList(EXAMPLE_DURATIONS));
} else if (parameterKey.equals("range")) {
examples.addAll(Arrays.asList(EXAMPLE_SIZES));
} else if (parameterKey.equals("transparent")) {
examples.addAll(controller.getMaterialSets());
} else if (parameterKey.equals("player")) {
examples.addAll(controller.getPlayerNames());
} else if (parameterKey.equals("target")) {
TargetType[] targetTypes = TargetType.values();
for (TargetType targetType : targetTypes) {
examples.add(targetType.name().toLowerCase());
}
} else if (parameterKey.equals("target")) {
TargetType[] targetTypes = TargetType.values();
for (TargetType targetType : targetTypes) {
examples.add(targetType.name().toLowerCase());
}
} else if (parameterKey.equals("target_type")) {
EntityType[] entityTypes = EntityType.values();
for (EntityType entityType : entityTypes) {
examples.add(entityType.name().toLowerCase());
}
} else if (booleanParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_BOOLEANS));
} else if (vectorParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_VECTOR_COMPONENTS));
} else if (worldParameterMap.contains(parameterKey)) {
List<World> worlds = Bukkit.getWorlds();
for (World world : worlds) {
examples.add(world.getName());
}
} else if (percentageParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_PERCENTAGES));
}
}
@Override
public String getCooldownDescription() {
if (cooldown > 0) {
int cooldownInSeconds = cooldown / 1000;
if (cooldownInSeconds > 60 * 60 ) {
int hours = cooldownInSeconds / (60 * 60);
if (hours == 1) {
return controller.getMessages().get("cooldown.description_hour");
}
return controller.getMessages().get("cooldown.description_hours").replace("$hours", ((Integer)hours).toString());
} else if (cooldownInSeconds > 60) {
int minutes = cooldownInSeconds / 60;
if (minutes == 1) {
return controller.getMessages().get("cooldown.description_minute");
}
return controller.getMessages().get("cooldown.description_minutes").replace("$minutes", ((Integer)minutes).toString());
} else if (cooldownInSeconds > 1) {
return controller.getMessages().get("cooldown.description_seconds").replace("$seconds", ((Integer)cooldownInSeconds).toString());
} else {
return controller.getMessages().get("cooldown.description_moment");
}
}
return null;
}
@Override
public long getCooldown()
{
return cooldown;
}
@Override
public CastingCost getRequiredCost() {
if (!mage.isCostFree())
{
if (costs != null && !isActive)
{
for (CastingCost cost : costs)
{
if (!cost.has(this))
{
return cost;
}
}
}
}
return null;
}
@Override
public long getRemainingCooldown() {
long currentTime = System.currentTimeMillis();
if (!mage.isCooldownFree()) {
double cooldownReduction = mage.getCooldownReduction() + this.cooldownReduction;
if (cooldownReduction < 1 && !isActive && cooldown > 0) {
int reducedCooldown = (int)Math.ceil((1.0f - cooldownReduction) * cooldown);
if (lastCast != 0 && lastCast > currentTime - reducedCooldown)
{
return lastCast - (currentTime - reducedCooldown);
}
}
}
return 0;
}
@Override
public long getDuration()
{
return duration;
}
@Override
public void setMage(Mage mage)
{
this.mage = mage;
}
@Override
public boolean cancel()
{
boolean cancelled = onCancel();
if (cancelled) {
sendMessage(getMessage("cancel"));
}
return cancelled;
}
@Override
public void reactivate() {
isActive = true;
onActivate();
}
@Override
public void activate() {
if (!isActive) {
mage.activateSpell(this);
}
}
@Override
public boolean deactivate() {
return deactivate(false, false);
}
@Override
public boolean deactivate(boolean force, boolean quiet) {
if (!force && bypassDeactivate) {
return false;
}
if (isActive) {
isActive = false;
onDeactivate();
mage.deactivateSpell(this);
if (!quiet) {
sendMessage(getMessage("deactivate"));
}
cancelEffects();
}
return true;
}
public void cancelEffects() {
if (currentEffects != null) {
for (EffectPlayer player : currentEffects) {
player.cancel();
}
currentEffects = null;
}
}
@Override
public Mage getMage() {
return mage;
}
@Override
public void load(ConfigurationSection node) {
try {
castCount = node.getLong("cast_count", 0);
lastCast = node.getLong("last_cast", 0);
if (category != null && template == null) {
category.addCasts(castCount, lastCast);
}
isActive = node.getBoolean("active", false);
onLoad(node);
} catch (Exception ex) {
controller.getPlugin().getLogger().warning("Failed to load data for spell " + name + ": " + ex.getMessage());
}
}
@Override
public void save(ConfigurationSection node) {
try {
node.set("cast_count", castCount);
node.set("last_cast", lastCast);
node.set("active", isActive);
onSave(node);
} catch (Exception ex) {
controller.getPlugin().getLogger().warning("Failed to save data for spell " + name);
ex.printStackTrace();
}
}
@Override
public void loadTemplate(String key, ConfigurationSection node)
{
spellKey = new SpellKey(key);
this.configuration = node;
this.loadTemplate(node);
}
@Override
public void tick()
{
checkActiveDuration();
checkActiveCosts();
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public int compareTo(com.elmakers.mine.bukkit.api.spell.SpellTemplate other)
{
return name.compareTo(other.getName());
}
@Override
public boolean hasCastPermission(CommandSender sender)
{
if (sender == null || bypassPermissions) return true;
return controller.hasCastPermission(sender, this);
}
@Override
public Color getColor()
{
if (color != null) return color;
if (category != null) return category.getColor();
return null;
}
@Override
public boolean isHidden()
{
return hidden;
}
//
// Spell abstract interface
//
/**
* Called when this spell is cast.
*
* This is where you do your work!
*
* If parameters were passed to this spell, either via a variant or the command line,
* they will be passed in here.
*
* @param parameters Any parameters that were passed to this spell
* @return true if the spell worked, false if it failed
*/
public abstract SpellResult onCast(ConfigurationSection parameters);
@Override
public MageController getController() {
return controller;
}
@Override
public String getIconURL() {
return iconURL;
}
@Override
public String getRequiredUpgradePath() {
return requiredUpgradePath;
}
@Override
public long getRequiredUpgradeCasts() {
return requiredUpgradeCasts;
}
@Override
public String getUpgradeDescription() {
return upgradeDescription == null ? "" : upgradeDescription;
}
@Override
public MageSpell getUpgrade() {
return upgrade;
}
@Override
public void setUpgrade(MageSpell upgrade) {
this.upgrade = upgrade;
}
}
| src/main/java/com/elmakers/mine/bukkit/spell/BaseSpell.java | package com.elmakers.mine.bukkit.spell;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.elmakers.mine.bukkit.api.event.CastEvent;
import com.elmakers.mine.bukkit.api.event.PreCastEvent;
import com.elmakers.mine.bukkit.api.spell.MageSpell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.TargetType;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.spell.SpellCategory;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.effect.EffectPlayer;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.Messages;
public abstract class BaseSpell implements MageSpell, Cloneable {
protected static final double VIEW_HEIGHT = 1.65;
protected static final double LOOK_THRESHOLD_RADIANS = 0.8;
// TODO: Config-drive
protected static final int MIN_Y = 1;
protected static final int MAX_Y = 255;
protected static final int MAX_NETHER_Y = 120;
// TODO: Configurable default? this does look cool, though.
protected final static Material DEFAULT_EFFECT_MATERIAL = Material.STATIONARY_WATER;
public final static String[] EXAMPLE_VECTOR_COMPONENTS = {"-1", "-0.5", "0", "0.5", "1", "~-1", "~-0.5", "~0", "~0.5", "*1", "*-1", "*-0.5", "*0.5", "*1"};
public final static String[] EXAMPLE_SIZES = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "12", "16", "32", "64"};
public final static String[] EXAMPLE_BOOLEANS = {"true", "false"};
public final static String[] EXAMPLE_DURATIONS = {"500", "1000", "2000", "5000", "10000", "60000", "120000"};
public final static String[] EXAMPLE_PERCENTAGES = {"0", "0.1", "0.25", "0.5", "0.75", "1"};
public final static String[] OTHER_PARAMETERS = {
"transparent", "target", "target_type", "range", "duration", "player"
};
public final static String[] WORLD_PARAMETERS = {
"pworld", "tworld", "otworld", "t2world"
};
protected final static Set<String> worldParameterMap = new HashSet<String>(Arrays.asList(WORLD_PARAMETERS));
public final static String[] VECTOR_PARAMETERS = {
"px", "py", "pz", "pdx", "pdy", "pdz", "tx", "ty", "tz", "otx", "oty", "otz", "t2x", "t2y", "t2z",
"otdx", "otdy", "otdz"
};
protected final static Set<String> vectorParameterMap = new HashSet<String>(Arrays.asList(VECTOR_PARAMETERS));
public final static String[] BOOLEAN_PARAMETERS = {
"allow_max_range", "prevent_passthrough", "passthrough", "bypass_build", "bypass_pvp", "target_npc"
};
protected final static Set<String> booleanParameterMap = new HashSet<String>(Arrays.asList(BOOLEAN_PARAMETERS));
public final static String[] PERCENTAGE_PARAMETERS = {
"fizzle_chance", "backfire_chance", "cooldown_reduction"
};
protected final static Set<String> percentageParameterMap = new HashSet<String>(Arrays.asList(PERCENTAGE_PARAMETERS));
public final static String[] COMMON_PARAMETERS = (String[])
ArrayUtils.addAll(
ArrayUtils.addAll(
ArrayUtils.addAll(
ArrayUtils.addAll(VECTOR_PARAMETERS, BOOLEAN_PARAMETERS),
OTHER_PARAMETERS
),
WORLD_PARAMETERS
),
PERCENTAGE_PARAMETERS
);
/*
* protected members that are helpful to use
*/
protected MageController controller;
protected Mage mage;
protected Location location;
/*
* Variant properties
*/
private SpellKey spellKey;
private String name;
private String alias;
private String description;
private String extendedDescription;
private String levelDescription;
private String upgradeDescription;
private String usage;
private long worth;
private Color color;
private String particle;
private SpellCategory category;
private BaseSpell template;
private MageSpell upgrade;
private long requiredUpgradeCasts;
private String requiredUpgradePath;
private MaterialAndData icon = new MaterialAndData(Material.AIR);
private String iconURL = null;
private List<CastingCost> costs = null;
private List<CastingCost> activeCosts = null;
protected boolean pvpRestricted = false;
protected boolean bypassPvpRestriction = false;
protected boolean bypassConfusion = false;
protected boolean bypassPermissions = false;
protected boolean castOnNoTarget = false;
protected boolean bypassDeactivate = false;
protected boolean quiet = false;
protected boolean loud = false;
private boolean backfired = false;
private boolean hidden = false;
protected ConfigurationSection parameters = null;
protected ConfigurationSection configuration = null;
protected static Random random = new Random();
protected Set<UUID> targetMessagesSent = new HashSet<UUID>();
/*
* private data
*/
private float cooldownReduction = 0;
private float costReduction = 0;
private int cooldown = 0;
private int duration = 0;
private long lastCast = 0;
private long castCount = 0;
private boolean isActive = false;
private Map<String, Collection<EffectPlayer>> effects = new HashMap<String, Collection<EffectPlayer>>();
private float fizzleChance = 0.0f;
private float backfireChance = 0.0f;
private long lastMessageSent = 0;
private Set<Material> preventPassThroughMaterials = null;
private Set<Material> passthroughMaterials = null;
private Collection<EffectPlayer> currentEffects = null;
public boolean allowPassThrough(Material mat)
{
if (mage != null && mage.isSuperPowered()) {
return true;
}
if (passthroughMaterials != null && passthroughMaterials.contains(mat)) {
return true;
}
return preventPassThroughMaterials == null || !preventPassThroughMaterials.contains(mat);
}
/*
* Ground / location search and test functions
*/
public boolean isOkToStandIn(Material mat)
{
return passthroughMaterials.contains(mat);
}
public boolean isWater(Material mat)
{
return (mat == Material.WATER || mat == Material.STATIONARY_WATER);
}
public boolean isOkToStandOn(Material mat)
{
return (mat != Material.AIR && mat != Material.LAVA && mat != Material.STATIONARY_LAVA);
}
public boolean isSafeLocation(Block block)
{
if (!block.getChunk().isLoaded()) {
block.getChunk().load(true);
return false;
}
if (block.getY() > MAX_Y) {
return false;
}
Block blockOneUp = block.getRelative(BlockFace.UP);
Block blockOneDown = block.getRelative(BlockFace.DOWN);
Player player = mage.getPlayer();
return (
(isOkToStandOn(blockOneDown.getType()) || (player != null && player.isFlying()))
&& isOkToStandIn(blockOneUp.getType())
&& isOkToStandIn(block.getType())
);
}
public boolean isSafeLocation(Location loc)
{
return isSafeLocation(loc.getBlock());
}
public Location tryFindPlaceToStand(Location targetLoc)
{
return tryFindPlaceToStand(targetLoc, MAX_Y, MAX_Y);
}
public Location tryFindPlaceToStand(Location targetLoc, int maxDownDelta, int maxUpDelta)
{
Location location = findPlaceToStand(targetLoc, maxDownDelta, maxUpDelta);
return location == null ? targetLoc : location;
}
public Location findPlaceToStand(Location targetLoc, int maxDownDelta, int maxUpDelta)
{
if (!targetLoc.getBlock().getChunk().isLoaded()) return null;
int minY = MIN_Y;
int maxY = targetLoc.getWorld().getEnvironment() == Environment.NETHER ? MAX_NETHER_Y : MAX_Y;
int targetY = targetLoc.getBlockY();
if (targetY >= minY && targetY <= maxY && isSafeLocation(targetLoc)) return targetLoc;
Location location = null;
if (targetY < minY) {
location = targetLoc.clone();
location.setY(minY);
location = findPlaceToStand(location, true, maxUpDelta);
} else if (targetY > maxY) {
location = targetLoc.clone();
location.setY(maxY);
location = findPlaceToStand(location, false, maxDownDelta);
} else {
// First look down just a little bit
int testMinY = Math.min(maxDownDelta, 4);
location = findPlaceToStand(targetLoc, false, testMinY);
// Then look up
if (location == null) {
location = findPlaceToStand(targetLoc, true, maxUpDelta);
}
// Then look allll the way down.
if (location == null) {
location = findPlaceToStand(targetLoc, false, maxDownDelta);
}
}
return location;
}
public Location findPlaceToStand(Location target, boolean goUp)
{
return findPlaceToStand(target, goUp, MAX_Y);
}
public Location findPlaceToStand(Location target, boolean goUp, int maxDelta)
{
int direction = goUp ? 1 : -1;
// search for a spot to stand
Location targetLocation = target.clone();
int yDelta = 0;
int minY = MIN_Y;
int maxY = targetLocation.getWorld().getEnvironment() == Environment.NETHER ? MAX_NETHER_Y : MAX_Y;
while (minY <= targetLocation.getY() && targetLocation.getY() <= maxY && yDelta < maxDelta)
{
Block block = targetLocation.getBlock();
if
(
isSafeLocation(block)
&& !(goUp && isUnderwater() && isWater(block.getType())) // rise to surface of water
)
{
// spot found - return location
return targetLocation;
}
if (!allowPassThrough(block.getType())) {
return null;
}
yDelta++;
targetLocation.setY(targetLocation.getY() + direction);
}
// no spot found
return null;
}
/**
* Get the block the player is standing on.
*
* @return The Block the player is standing on
*/
public Block getPlayerBlock()
{
Location location = getLocation();
if (location == null) return null;
return location.getBlock().getRelative(BlockFace.DOWN);
}
/**
* Get the direction the player is facing as a BlockFace.
*
* @return a BlockFace representing the direction the player is facing
*/
public BlockFace getPlayerFacing()
{
return getFacing(getLocation());
}
public static BlockFace getFacing(Location location)
{
float playerRot = location.getYaw();
while (playerRot < 0)
playerRot += 360;
while (playerRot > 360)
playerRot -= 360;
BlockFace direction = BlockFace.NORTH;
if (playerRot <= 45 || playerRot > 315)
{
direction = BlockFace.SOUTH;
}
else if (playerRot > 45 && playerRot <= 135)
{
direction = BlockFace.WEST;
}
else if (playerRot > 135 && playerRot <= 225)
{
direction = BlockFace.NORTH;
}
else if (playerRot > 225 && playerRot <= 315)
{
direction = BlockFace.EAST;
}
return direction;
}
/*
* Functions to send text to player- use these to respect "quiet" and "silent" modes.
*/
/**
* Send a message to a player when a spell is cast.
*
* @param message The message to send
*/
public void castMessage(String message)
{
if (!quiet && canSendMessage() && message != null && message.length() > 0)
{
mage.castMessage(message);
lastMessageSent = System.currentTimeMillis();
}
}
/**
* Send a message to a player.
*
* Use this to send messages to the player that are important.
*
* @param message The message to send
*/
public void sendMessage(String message)
{
if (!quiet && message != null && message.length() > 0)
{
mage.sendMessage(message);
lastMessageSent = System.currentTimeMillis();
}
}
public Location getLocation()
{
if (location != null) return location.clone();
if (mage != null) {
return mage.getLocation();
}
return null;
}
public Location getEyeLocation()
{
Location location = getLocation();
if (location == null) return null;
location.setY(location.getY() + 1.5);
return location;
}
public Vector getDirection()
{
if (location == null) {
return mage.getDirection();
}
return location.getDirection();
}
public boolean isLookingUp()
{
Vector direction = getDirection();
if (direction == null) return false;
return direction.getY() > LOOK_THRESHOLD_RADIANS;
}
public boolean isLookingDown()
{
Vector direction = getDirection();
if (direction == null) return false;
return direction.getY() < -LOOK_THRESHOLD_RADIANS;
}
public World getWorld()
{
Location location = getLocation();
if (location != null) return location.getWorld();
return null;
}
/**
* Check to see if the player is underwater
*
* @return true if the player is underwater
*/
public boolean isUnderwater()
{
Block playerBlock = getPlayerBlock();
if (playerBlock == null) return false;
playerBlock = playerBlock.getRelative(BlockFace.UP);
return (playerBlock.getType() == Material.WATER || playerBlock.getType() == Material.STATIONARY_WATER);
}
protected String getBlockSkin(Material blockType) {
String skinName = null;
switch (blockType) {
case CACTUS:
skinName = "MHF_Cactus";
break;
case CHEST:
skinName = "MHF_Chest";
break;
case MELON_BLOCK:
skinName = "MHF_Melon";
break;
case TNT:
if (random.nextDouble() > 0.5) {
skinName = "MHF_TNT";
} else {
skinName = "MHF_TNT2";
}
break;
case LOG:
skinName = "MHF_OakLog";
break;
case PUMPKIN:
skinName = "MHF_Pumpkin";
break;
default:
// TODO .. ?
/*
* Blocks:
Bonus:
MHF_ArrowUp
MHF_ArrowDown
MHF_ArrowLeft
MHF_ArrowRight
MHF_Exclamation
MHF_Question
*/
}
return skinName;
}
protected String getMobSkin(EntityType mobType)
{
String mobSkin = null;
switch (mobType) {
case BLAZE:
mobSkin = "MHF_Blaze";
break;
case CAVE_SPIDER:
mobSkin = "MHF_CaveSpider";
break;
case CHICKEN:
mobSkin = "MHF_Chicken";
break;
case COW:
mobSkin = "MHF_Cow";
break;
case ENDERMAN:
mobSkin = "MHF_Enderman";
break;
case GHAST:
mobSkin = "MHF_Ghast";
break;
case IRON_GOLEM:
mobSkin = "MHF_Golem";
break;
case MAGMA_CUBE:
mobSkin = "MHF_LavaSlime";
break;
case MUSHROOM_COW:
mobSkin = "MHF_MushroomCow";
break;
case OCELOT:
mobSkin = "MHF_Ocelot";
break;
case PIG:
mobSkin = "MHF_Pig";
break;
case PIG_ZOMBIE:
mobSkin = "MHF_PigZombie";
break;
case SHEEP:
mobSkin = "MHF_Sheep";
break;
case SLIME:
mobSkin = "MHF_Slime";
break;
case SPIDER:
mobSkin = "MHF_Spider";
break;
case SQUID:
mobSkin = "MHF_Squid";
break;
case VILLAGER:
mobSkin = "MHF_Villager";
default:
// TODO: Find skins for SKELETON, CREEPER and ZOMBIE .. ?
}
return mobSkin;
}
public static Collection<PotionEffect> getPotionEffects(ConfigurationSection parameters)
{
return getPotionEffects(parameters, null);
}
public static Collection<PotionEffect> getPotionEffects(ConfigurationSection parameters, Integer duration)
{
List<PotionEffect> effects = new ArrayList<PotionEffect>();
PotionEffectType[] effectTypes = PotionEffectType.values();
for (PotionEffectType effectType : effectTypes) {
// Why is there a null entry in this list? Maybe a 1.7 bug?
if (effectType == null) continue;
String parameterName = "effect_" + effectType.getName().toLowerCase();
if (parameters.contains(parameterName)) {
String value = parameters.getString(parameterName);
int ticks = 10;
int power = 1;
try {
if (value.contains(",")) {
String[] pieces = value.split(",");
ticks = (int)Float.parseFloat(pieces[0]);
power = (int)Float.parseFloat(pieces[1]);
} else {
power = (int)Float.parseFloat(value);
if (duration != null) {
ticks = duration / 50;
}
}
} catch (Exception ex) {
Bukkit.getLogger().warning("Error parsing potion effect for " + effectType + ": " + value);
}
PotionEffect effect = new PotionEffect(effectType, ticks, power, true);
effects.add(effect);
}
}
return effects;
}
public boolean isInCircle(int x, int z, int R)
{
return ((x * x) + (z * z) - (R * R)) <= 0;
}
private boolean canSendMessage()
{
if (lastMessageSent == 0) return true;
int throttle = controller.getMessageThrottle();
long now = System.currentTimeMillis();
return (lastMessageSent < now - throttle);
}
protected Location getEffectLocation()
{
return getEyeLocation();
}
public FireworkEffect getFireworkEffect() {
return getFireworkEffect(null, null, null, null, null);
}
public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType) {
return getFireworkEffect(color1, color2, fireworkType, null, null);
}
public FireworkEffect getFireworkEffect(Color color1, Color color2, org.bukkit.FireworkEffect.Type fireworkType, Boolean flicker, Boolean trail) {
Color wandColor = mage == null ? null : mage.getEffectColor();
if (wandColor != null) {
color1 = wandColor;
color2 = wandColor.mixColors(color1, Color.WHITE);
} else {
if (color1 == null) {
color1 = Color.fromRGB(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
if (color2 == null) {
color2 = Color.fromRGB(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
}
if (fireworkType == null) {
fireworkType = org.bukkit.FireworkEffect.Type.values()[random.nextInt(org.bukkit.FireworkEffect.Type.values().length)];
}
if (flicker == null) {
flicker = random.nextBoolean();
}
if (trail == null) {
trail = random.nextBoolean();
}
return FireworkEffect.builder().flicker(flicker).withColor(color1).withFade(color2).with(fireworkType).trail(trail).build();
}
public boolean hasBrushOverride()
{
return false;
}
@Override
public boolean usesBrush()
{
return false;
}
@Override
public boolean isUndoable()
{
return false;
}
public void checkActiveCosts() {
if (activeCosts == null) return;
for (CastingCost cost : activeCosts)
{
if (!cost.has(this))
{
deactivate();
return;
}
cost.use(this);
}
}
public void checkActiveDuration() {
if (duration > 0 && lastCast < System.currentTimeMillis() - duration) {
deactivate();
}
}
protected List<CastingCost> parseCosts(ConfigurationSection node) {
if (node == null) {
return null;
}
List<CastingCost> castingCosts = new ArrayList<CastingCost>();
Set<String> costKeys = node.getKeys(false);
for (String key : costKeys)
{
castingCosts.add(new CastingCost(key, node.getInt(key, 1)));
}
return castingCosts;
}
@SuppressWarnings("unchecked")
protected void loadTemplate(ConfigurationSection node)
{
// Get localizations
String baseKey = spellKey.getBaseKey();
// Message defaults come from the messages.yml file
name = controller.getMessages().get("spells." + baseKey + ".name", baseKey);
description = controller.getMessages().get("spells." + baseKey + ".description", "");
extendedDescription = controller.getMessages().get("spells." + baseKey + ".extended_description", "");
usage = controller.getMessages().get("spells." + baseKey + ".usage", "");
// Upgrade path information
// The actual upgrade spell will be set externally.
requiredUpgradePath = node.getString("upgrade_required_path");
requiredUpgradeCasts = node.getLong("upgrade_required_casts");
// Can be overridden by the base spell, or the variant spell
levelDescription = controller.getMessages().get("spells." + baseKey + ".level_description", levelDescription);
upgradeDescription = controller.getMessages().get("spells." + baseKey + ".upgrade_description", levelDescription);
// Spell level variants can override
if (spellKey.isVariant()) {
String variantKey = spellKey.getKey();
name = controller.getMessages().get("spells." + variantKey + ".name", name);
description = controller.getMessages().get("spells." + variantKey + ".description", description);
extendedDescription = controller.getMessages().get("spells." + variantKey + ".extended_description", extendedDescription);
usage = controller.getMessages().get("spells." + variantKey + ".usage", usage);
// Level description defaults to pre-formatted text
levelDescription = controller.getMessages().get("spell.level_description", levelDescription);
// Any spell may have a level description, including base spells if chosen.
// Base spells must specify their own level in each spell config though,
// they don't get an auto-generated one.
levelDescription = controller.getMessages().get("spells." + variantKey + ".level_description", levelDescription);
upgradeDescription = controller.getMessages().get("spells." + variantKey + ".upgrade_description", upgradeDescription);
}
// Individual spell configuration overrides all
name = node.getString("name", name);
alias = node.getString("alias", "");
extendedDescription = node.getString("extended_description", extendedDescription);
description = node.getString("description", description);
levelDescription = node.getString("level_description", levelDescription);
// Parameterize level description
if (levelDescription != null && !levelDescription.isEmpty()) {
levelDescription = levelDescription.replace("$level", Integer.toString(spellKey.getLevel()));
}
// Load basic properties
icon = ConfigurationUtils.getMaterialAndData(node, "icon", icon);
iconURL = node.getString("icon_url");
color = ConfigurationUtils.getColor(node, "color", null);
worth = node.getLong("worth", worth);
category = controller.getCategory(node.getString("category"));
parameters = node.getConfigurationSection("parameters");
costs = parseCosts(node.getConfigurationSection("costs"));
activeCosts = parseCosts(node.getConfigurationSection("active_costs"));
pvpRestricted = node.getBoolean("pvp_restricted", pvpRestricted);
castOnNoTarget = node.getBoolean("cast_on_no_target", castOnNoTarget);
hidden = node.getBoolean("hidden", false);
// Preload some parameters
ConfigurationSection parameters = node.getConfigurationSection("parameters");
if (parameters != null) {
cooldown = parameters.getInt("cooldown", cooldown);
cooldown = parameters.getInt("cool", cooldown);
bypassPvpRestriction = parameters.getBoolean("bypass_pvp", bypassPvpRestriction);
bypassPvpRestriction = parameters.getBoolean("bp", bypassPvpRestriction);
bypassPermissions = parameters.getBoolean("bypass_permissions", bypassPermissions);
duration = parameters.getInt("duration", duration);
}
effects.clear();
if (node.contains("effects")) {
ConfigurationSection effectsNode = node.getConfigurationSection("effects");
Collection<String> effectKeys = effectsNode.getKeys(false);
for (String effectKey : effectKeys) {
if (effectsNode.isString(effectKey)) {
String referenceKey = effectsNode.getString(effectKey);
if (effects.containsKey(referenceKey)) {
effects.put(effectKey, new ArrayList(effects.get(referenceKey)));
}
}
else
{
effects.put(effectKey, EffectPlayer.loadEffects(controller.getPlugin(), effectsNode, effectKey));
}
}
}
}
protected void preCast()
{
}
protected void reset()
{
Location mageLocation = mage != null ? mage.getLocation() : null;
// Kind of a hack, but assume the default location has no direction.
if (this.location != null && mageLocation != null) {
this.location.setPitch(mageLocation.getPitch());
this.location.setYaw(mageLocation.getYaw());
}
backfired = false;
cancelEffects();
}
public boolean cast(String[] extraParameters, Location defaultLocation)
{
this.reset();
targetMessagesSent.clear();
// Allow other plugins to cancel this cast
PreCastEvent preCast = new PreCastEvent(mage, this);
Bukkit.getPluginManager().callEvent(preCast);
if (preCast.isCancelled()) {
processResult(SpellResult.CANCELLED);
return false;
}
if (this.parameters == null) {
this.parameters = new MemoryConfiguration();
}
this.location = defaultLocation;
final ConfigurationSection parameters = new MemoryConfiguration();
ConfigurationUtils.addConfigurations(parameters, this.parameters);
ConfigurationUtils.addParameters(extraParameters, parameters);
processParameters(parameters);
// Don't allow casting if the player is confused
bypassConfusion = parameters.getBoolean("bypass_confusion", bypassConfusion);
LivingEntity livingEntity = mage.getLivingEntity();
if (livingEntity != null && !bypassConfusion && !mage.isSuperPowered() && livingEntity.hasPotionEffect(PotionEffectType.CONFUSION)) {
processResult(SpellResult.CURSED);
return false;
}
// Don't perform permission check until after processing parameters, in case of overrides
if (!canCast(getLocation())) {
processResult(SpellResult.INSUFFICIENT_PERMISSION);
return false;
}
this.preCast();
// PVP override settings
bypassPvpRestriction = parameters.getBoolean("bypass_pvp", false);
bypassPvpRestriction = parameters.getBoolean("bp", bypassPvpRestriction);
bypassPermissions = parameters.getBoolean("bypass_permissions", bypassPermissions);
// Check cooldowns
cooldown = parameters.getInt("cooldown", cooldown);
cooldown = parameters.getInt("cool", cooldown);
// Color override
color = ConfigurationUtils.getColor(parameters, "color", color);
particle = parameters.getString("particle", null);
long cooldownRemaining = getRemainingCooldown() / 1000;
String timeDescription = "";
if (cooldownRemaining > 0) {
if (cooldownRemaining > 60 * 60 ) {
long hours = cooldownRemaining / (60 * 60);
if (hours == 1) {
timeDescription = controller.getMessages().get("cooldown.wait_hour");
} else {
timeDescription = controller.getMessages().get("cooldown.wait_hours").replace("$hours", ((Long) hours).toString());
}
} else if (cooldownRemaining > 60) {
long minutes = cooldownRemaining / 60;
if (minutes == 1) {
timeDescription = controller.getMessages().get("cooldown.wait_minute");
} else {
timeDescription = controller.getMessages().get("cooldown.wait_minutes").replace("$minutes", ((Long) minutes).toString());
}
} else if (cooldownRemaining > 1) {
timeDescription = controller.getMessages().get("cooldown.wait_seconds").replace("$seconds", ((Long)cooldownRemaining).toString());
} else {
timeDescription = controller.getMessages().get("cooldown.wait_moment");
}
sendMessage(getMessage("cooldown").replace("$time", timeDescription));
processResult(SpellResult.COOLDOWN);
return false;
}
com.elmakers.mine.bukkit.api.spell.CastingCost required = getRequiredCost();
if (required != null) {
String baseMessage = getMessage("insufficient_resources");
String costDescription = required.getDescription(controller.getMessages(), mage);
sendMessage(baseMessage.replace("$cost", costDescription));
processResult(SpellResult.INSUFFICIENT_RESOURCES);
return false;
}
return finalizeCast(parameters);
}
public boolean canCast(Location location) {
if (!hasCastPermission(mage.getCommandSender())) return false;
Boolean regionPermission = controller.getRegionCastPermission(mage.getPlayer(), this, location);
if (regionPermission != null && regionPermission == true) return true;
if (regionPermission != null && regionPermission == false) return false;
if (requiresBuildPermission() && !hasBuildPermission(location.getBlock())) return false;
return !pvpRestricted || bypassPvpRestriction || mage.isPVPAllowed(location);
}
public boolean requiresBuildPermission() {
return false;
}
public boolean hasBuildPermission(Block block) {
// Cast permissions bypass
Boolean castPermission = controller.getRegionCastPermission(mage.getPlayer(), this, block.getLocation());
if (castPermission != null && castPermission == true) return true;
if (castPermission != null && castPermission == false) return false;
return mage.hasBuildPermission(block);
}
protected void onBackfire() {
}
protected void backfire() {
if (!backfired) {
onBackfire();
}
backfired = true;
}
protected boolean finalizeCast(ConfigurationSection parameters) {
SpellResult result = null;
// Global parameters
controller.disablePhysics(parameters.getInt("disable_physics", 0));
if (!mage.isSuperPowered()) {
if (backfireChance > 0 && random.nextDouble() < backfireChance) {
backfire();
} else if (fizzleChance > 0 && random.nextDouble() < fizzleChance) {
result = SpellResult.FIZZLE;
}
}
if (result == null) {
result = onCast(parameters);
}
if (backfired) {
result = SpellResult.BACKFIRE;
}
processResult(result);
boolean success = result.isSuccess();
boolean requiresCost = success || (castOnNoTarget && result == SpellResult.NO_TARGET);
boolean free = !requiresCost && result.isFree();
if (!free) {
lastCast = System.currentTimeMillis();
if (costs != null && !mage.isCostFree()) {
for (CastingCost cost : costs)
{
cost.use(this);
}
}
}
if (success) {
castCount++;
if (template != null) {
template.castCount++;
}
}
return success;
}
public String getMessage(String messageKey) {
return getMessage(messageKey, "");
}
public String getMessage(String messageKey, String def) {
String message = controller.getMessages().get("spells.default." + messageKey, def);
message = controller.getMessages().get("spells." + spellKey.getBaseKey() + "." + messageKey, message);
if (spellKey.isVariant()) {
message = controller.getMessages().get("spells." + spellKey.getKey() + "." + messageKey, message);
}
if (message == null) message = "";
// Escape some common parameters
String playerName = mage.getName();
message = message.replace("$player", playerName);
String materialName = getDisplayMaterialName();
// TODO: Localize "None", provide static getter
materialName = materialName == null ? "None" : materialName;
message = message.replace("$material", materialName);
return message;
}
protected String getDisplayMaterialName()
{
return "None";
}
protected void processResult(SpellResult result) {
// Notify other plugins of this spell cast
CastEvent castEvent = new CastEvent(mage, this, result);
Bukkit.getPluginManager().callEvent(castEvent);
if (mage != null) {
mage.onCast(this, result);
}
// Show messaging
String resultName = result.name().toLowerCase();
if (result.isSuccess()) {
String message = null;
if (result != SpellResult.CAST) {
message = getMessage("cast");
}
if (result.isAlternate() && result != SpellResult.ALTERNATE) {
message = getMessage("alternate", message);
}
message = getMessage(resultName, message);
LivingEntity sourceEntity = mage.getLivingEntity();
Entity targetEntity = getTargetEntity();
if (targetEntity == sourceEntity) {
message = getMessage("cast_self", message);
} else if (targetEntity instanceof Player) {
message = getMessage("cast_player", message);
} else if (targetEntity instanceof LivingEntity) {
message = getMessage("cast_livingentity", message);
} else if (targetEntity instanceof Entity) {
message = getMessage("cast_entity", message);
}
if (loud) {
sendMessage(message);
} else {
castMessage(message);
}
messageTargets("cast_player_message");
} else
// Special cases where messaging is handled elsewhere
if (result != SpellResult.INSUFFICIENT_RESOURCES && result != SpellResult.COOLDOWN)
{
String message = null;
if (result.isFailure() && result != SpellResult.FAIL) {
message = getMessage("fail");
}
sendMessage(getMessage(resultName, message));
}
// Play effects
playEffects(resultName);
}
public void messageTargets(String messageKey)
{
LivingEntity sourceEntity = mage == null ? null : mage.getLivingEntity();
String playerMessage = getMessage(messageKey);
if (!mage.isStealth() && playerMessage.length() > 0)
{
Collection<Entity> targets = getTargetEntities();
for (Entity target : targets)
{
UUID targetUUID = target.getUniqueId();
if (target instanceof Player && target != sourceEntity && !targetMessagesSent.contains(targetUUID))
{
targetMessagesSent.add(targetUUID);
playerMessage = playerMessage.replace("$spell", getName());
Mage targetMage = controller.getMage(target);
targetMage.sendMessage(playerMessage);
}
}
}
}
public void playEffects(String effectName, float scale) {
playEffects(effectName, scale, getEffectLocation(), mage.getEntity(), getTargetLocation(), getTargetEntity());
}
public void playEffects(String effectName)
{
playEffects(effectName, 1);
}
@Override
public void playEffects(String effectName, float scale, Location source, Entity sourceEntity, Location targetLocation, Entity targetEntity)
{
if (effects.containsKey(effectName) && source != null)
{
cancelEffects();
currentEffects = effects.get(effectName);
Collection<Entity> targeted = getTargetEntities();
for (EffectPlayer player : currentEffects)
{
// Set scale
player.setScale(scale);
// Set material and color
player.setMaterial(getEffectMaterial());
player.setColor(mage.getEffectColor());
String overrideParticle = particle != null ? particle : mage.getEffectParticleName();
player.setParticleOverride(overrideParticle);
if (player.shouldPlayAtAllTargets())
{
player.start(source, sourceEntity, targeted);
}
else
{
player.start(source, sourceEntity, targetLocation, targetEntity);
}
}
}
}
@Override
public void target() {
}
@Override
public Location getTargetLocation() {
return null;
}
@Override
public boolean canTarget(Entity entity) {
return true;
}
@Override
public Entity getTargetEntity() {
return null;
}
public Collection<Entity> getTargetEntities() {
return null;
}
public com.elmakers.mine.bukkit.api.block.MaterialAndData getEffectMaterial()
{
return new MaterialAndData(DEFAULT_EFFECT_MATERIAL);
}
protected void processParameters(ConfigurationSection parameters) {
fizzleChance = (float)parameters.getDouble("fizzle_chance", fizzleChance);
backfireChance = (float)parameters.getDouble("backfire_chance", backfireChance);
Location defaultLocation = location == null ? mage.getLocation() : location;
Location locationOverride = ConfigurationUtils.overrideLocation(parameters, "p", defaultLocation, controller.canCreateWorlds());
if (locationOverride != null) {
location = locationOverride;
}
costReduction = (float)parameters.getDouble("cost_reduction", 0);
cooldownReduction = (float)parameters.getDouble("cooldown_reduction", 0);
if (parameters.contains("prevent_passthrough")) {
preventPassThroughMaterials = controller.getMaterialSet(parameters.getString("prevent_passthrough"));
} else {
preventPassThroughMaterials = controller.getMaterialSet("indestructible");
}
if (parameters.contains("passthrough")) {
passthroughMaterials = controller.getMaterialSet(parameters.getString("passthrough"));
} else {
passthroughMaterials = controller.getMaterialSet("passthrough");
}
bypassDeactivate = parameters.getBoolean("bypass_deactivate", false);
quiet = parameters.getBoolean("quiet", false);
loud = parameters.getBoolean("loud", false);
}
public String getPermissionNode()
{
return "Magic.cast." + spellKey.getBaseKey();
}
/**
* Called when a material selection spell is cancelled mid-selection.
*/
public boolean onCancel()
{
return false;
}
/**
* Listener method, called on player quit for registered spells.
*
* @param event The player who just quit
*/
public void onPlayerQuit(PlayerQuitEvent event)
{
}
/**
* Listener method, called on player move for registered spells.
*
* @param event The original entity death event
*/
public void onPlayerDeath(EntityDeathEvent event)
{
}
public void onPlayerDamage(EntityDamageEvent event)
{
}
/**
* Used internally to initialize the Spell, do not call.
*
* @param instance The spells instance
*/
public void initialize(MageController instance)
{
this.controller = instance;
}
@Override
public long getCastCount()
{
return castCount;
}
@Override
public void setCastCount(long count) {
castCount = count;
}
public void onActivate() {
}
public void onDeactivate() {
}
/**
* Called on player data load.
*/
public void onLoad(ConfigurationSection node)
{
}
/**
* Called on player data save.
*
* @param node The configuration node to load data from.
*/
public void onSave(ConfigurationSection node)
{
}
//
// Cloneable implementation
//
@Override
public Object clone()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException ex)
{
return null;
}
}
//
// CostReducer Implementation
//
@Override
public float getCostReduction()
{
return costReduction + mage.getCostReduction();
}
//
// Public API Implementation
//
@Override
public com.elmakers.mine.bukkit.api.spell.Spell createSpell()
{
BaseSpell spell = null;
try {
spell = (BaseSpell) this.getClass().newInstance();
spell.initialize(controller);
spell.loadTemplate(spellKey.getKey(), configuration);
spell.template = this;
} catch (Exception ex) {
controller.getLogger().log(Level.WARNING, "Error creating spell", ex);
}
return spell;
}
@Override
public boolean cast()
{
return cast(null, null);
}
@Override
public boolean cast(String[] extraParameters)
{
return cast(extraParameters, null);
}
@Override
public final String getKey()
{
return spellKey.getKey();
}
@Override
public final String getName()
{
return name;
}
@Override
public final String getAlias()
{
return alias;
}
@Override
public final com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon()
{
return icon;
}
@Override
public boolean hasIcon() {
return icon != null && icon.getMaterial() != Material.AIR;
}
@Override
public final String getDescription()
{
return description;
}
@Override
public final String getExtendedDescription()
{
return extendedDescription;
}
@Override
public final String getLevelDescription()
{
return levelDescription;
}
@Override
public final SpellKey getSpellKey()
{
return spellKey;
}
@Override
public final String getUsage()
{
return usage;
}
@Override
public final long getWorth()
{
return worth;
}
@Override
public final SpellCategory getCategory()
{
return category;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.effect.EffectPlayer> getEffects(SpellResult result) {
return getEffects(result.name().toLowerCase());
}
@Override
public Collection<com.elmakers.mine.bukkit.api.effect.EffectPlayer> getEffects(String key) {
Collection<EffectPlayer> effectList = effects.get(key);
if (effectList == null) {
return new ArrayList<com.elmakers.mine.bukkit.api.effect.EffectPlayer>();
}
return new ArrayList<com.elmakers.mine.bukkit.api.effect.EffectPlayer>(effectList);
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.CastingCost> getCosts() {
if (costs == null) return null;
List<com.elmakers.mine.bukkit.api.spell.CastingCost> copy = new ArrayList<com.elmakers.mine.bukkit.api.spell.CastingCost>();
copy.addAll(costs);
return copy;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.CastingCost> getActiveCosts() {
if (activeCosts == null) return null;
List<com.elmakers.mine.bukkit.api.spell.CastingCost> copy = new ArrayList<com.elmakers.mine.bukkit.api.spell.CastingCost>();
copy.addAll(activeCosts);
return copy;
}
@Override
public void getParameters(Collection<String> parameters)
{
parameters.addAll(Arrays.asList(COMMON_PARAMETERS));
}
@Override
public void getParameterOptions(Collection<String> examples, String parameterKey)
{
if (parameterKey.equals("duration")) {
examples.addAll(Arrays.asList(EXAMPLE_DURATIONS));
} else if (parameterKey.equals("range")) {
examples.addAll(Arrays.asList(EXAMPLE_SIZES));
} else if (parameterKey.equals("transparent")) {
examples.addAll(controller.getMaterialSets());
} else if (parameterKey.equals("player")) {
examples.addAll(controller.getPlayerNames());
} else if (parameterKey.equals("target")) {
TargetType[] targetTypes = TargetType.values();
for (TargetType targetType : targetTypes) {
examples.add(targetType.name().toLowerCase());
}
} else if (parameterKey.equals("target")) {
TargetType[] targetTypes = TargetType.values();
for (TargetType targetType : targetTypes) {
examples.add(targetType.name().toLowerCase());
}
} else if (parameterKey.equals("target_type")) {
EntityType[] entityTypes = EntityType.values();
for (EntityType entityType : entityTypes) {
examples.add(entityType.name().toLowerCase());
}
} else if (booleanParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_BOOLEANS));
} else if (vectorParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_VECTOR_COMPONENTS));
} else if (worldParameterMap.contains(parameterKey)) {
List<World> worlds = Bukkit.getWorlds();
for (World world : worlds) {
examples.add(world.getName());
}
} else if (percentageParameterMap.contains(parameterKey)) {
examples.addAll(Arrays.asList(EXAMPLE_PERCENTAGES));
}
}
@Override
public String getCooldownDescription() {
if (cooldown > 0) {
int cooldownInSeconds = cooldown / 1000;
if (cooldownInSeconds > 60 * 60 ) {
int hours = cooldownInSeconds / (60 * 60);
if (hours == 1) {
return controller.getMessages().get("cooldown.description_hour");
}
return controller.getMessages().get("cooldown.description_hours").replace("$hours", ((Integer)hours).toString());
} else if (cooldownInSeconds > 60) {
int minutes = cooldownInSeconds / 60;
if (minutes == 1) {
return controller.getMessages().get("cooldown.description_minute");
}
return controller.getMessages().get("cooldown.description_minutes").replace("$minutes", ((Integer)minutes).toString());
} else if (cooldownInSeconds > 1) {
return controller.getMessages().get("cooldown.description_seconds").replace("$seconds", ((Integer)cooldownInSeconds).toString());
} else {
return controller.getMessages().get("cooldown.description_moment");
}
}
return null;
}
@Override
public long getCooldown()
{
return cooldown;
}
@Override
public CastingCost getRequiredCost() {
if (!mage.isCostFree())
{
if (costs != null && !isActive)
{
for (CastingCost cost : costs)
{
if (!cost.has(this))
{
return cost;
}
}
}
}
return null;
}
@Override
public long getRemainingCooldown() {
long currentTime = System.currentTimeMillis();
if (!mage.isCooldownFree()) {
double cooldownReduction = mage.getCooldownReduction() + this.cooldownReduction;
if (cooldownReduction < 1 && !isActive && cooldown > 0) {
int reducedCooldown = (int)Math.ceil((1.0f - cooldownReduction) * cooldown);
if (lastCast != 0 && lastCast > currentTime - reducedCooldown)
{
return lastCast - (currentTime - reducedCooldown);
}
}
}
return 0;
}
@Override
public long getDuration()
{
return duration;
}
@Override
public void setMage(Mage mage)
{
this.mage = mage;
}
@Override
public boolean cancel()
{
boolean cancelled = onCancel();
if (cancelled) {
sendMessage(getMessage("cancel"));
}
return cancelled;
}
@Override
public void reactivate() {
isActive = true;
onActivate();
}
@Override
public void activate() {
if (!isActive) {
mage.activateSpell(this);
}
}
@Override
public boolean deactivate() {
return deactivate(false, false);
}
@Override
public boolean deactivate(boolean force, boolean quiet) {
if (!force && bypassDeactivate) {
return false;
}
if (isActive) {
isActive = false;
onDeactivate();
mage.deactivateSpell(this);
if (!quiet) {
sendMessage(getMessage("deactivate"));
}
cancelEffects();
}
return true;
}
public void cancelEffects() {
if (currentEffects != null) {
for (EffectPlayer player : currentEffects) {
player.cancel();
}
currentEffects = null;
}
}
@Override
public Mage getMage() {
return mage;
}
@Override
public void load(ConfigurationSection node) {
try {
castCount = node.getLong("cast_count", 0);
lastCast = node.getLong("last_cast", 0);
if (category != null && template == null) {
category.addCasts(castCount, lastCast);
}
isActive = node.getBoolean("active", false);
onLoad(node);
} catch (Exception ex) {
controller.getPlugin().getLogger().warning("Failed to load data for spell " + name + ": " + ex.getMessage());
}
}
@Override
public void save(ConfigurationSection node) {
try {
node.set("cast_count", castCount);
node.set("last_cast", lastCast);
node.set("active", isActive);
onSave(node);
} catch (Exception ex) {
controller.getPlugin().getLogger().warning("Failed to save data for spell " + name);
ex.printStackTrace();
}
}
@Override
public void loadTemplate(String key, ConfigurationSection node)
{
spellKey = new SpellKey(key);
this.configuration = node;
this.loadTemplate(node);
}
@Override
public void tick()
{
checkActiveDuration();
checkActiveCosts();
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public int compareTo(com.elmakers.mine.bukkit.api.spell.SpellTemplate other)
{
return name.compareTo(other.getName());
}
@Override
public boolean hasCastPermission(CommandSender sender)
{
if (sender == null || bypassPermissions) return true;
return controller.hasCastPermission(sender, this);
}
@Override
public Color getColor()
{
if (color != null) return color;
if (category != null) return category.getColor();
return null;
}
@Override
public boolean isHidden()
{
return hidden;
}
//
// Spell abstract interface
//
/**
* Called when this spell is cast.
*
* This is where you do your work!
*
* If parameters were passed to this spell, either via a variant or the command line,
* they will be passed in here.
*
* @param parameters Any parameters that were passed to this spell
* @return true if the spell worked, false if it failed
*/
public abstract SpellResult onCast(ConfigurationSection parameters);
@Override
public MageController getController() {
return controller;
}
@Override
public String getIconURL() {
return iconURL;
}
@Override
public String getRequiredUpgradePath() {
return requiredUpgradePath;
}
@Override
public long getRequiredUpgradeCasts() {
return requiredUpgradeCasts;
}
@Override
public String getUpgradeDescription() {
return upgradeDescription == null ? "" : upgradeDescription;
}
@Override
public MageSpell getUpgrade() {
return upgrade;
}
@Override
public void setUpgrade(MageSpell upgrade) {
this.upgrade = upgrade;
}
}
| Fix empty upgrade descriptions return the level name
| src/main/java/com/elmakers/mine/bukkit/spell/BaseSpell.java | Fix empty upgrade descriptions return the level name | <ide><path>rc/main/java/com/elmakers/mine/bukkit/spell/BaseSpell.java
<ide>
<ide> // Can be overridden by the base spell, or the variant spell
<ide> levelDescription = controller.getMessages().get("spells." + baseKey + ".level_description", levelDescription);
<del> upgradeDescription = controller.getMessages().get("spells." + baseKey + ".upgrade_description", levelDescription);
<add> upgradeDescription = controller.getMessages().get("spells." + baseKey + ".upgrade_description", upgradeDescription);
<ide>
<ide> // Spell level variants can override
<ide> if (spellKey.isVariant()) { |
|
Java | mit | 60877132bb8a25b356769579d04c56a26e866585 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
/**
* https://leetcode.com/problems/champagne-tower/
*/
public class Problem799 {
public double champagneTower(int poured, int query_row, int query_glass) {
double[][] glasses = new double[100][100];
int row = 0;
glasses[row] = new double[]{poured};
while (row < glasses.length) {
int colIdx = 0;
boolean overflow = false;
for (int col = 0; col < glasses[row].length; col++) {
double val = glasses[row][col];
if (val == 0) {
break;
}
if (val > 1) {
glasses[row][col] = 1;
double half = (val - 1) / 2;
glasses[row + 1][colIdx++] += half;
glasses[row + 1][colIdx] += half;
overflow = true;
}
}
if (!overflow) {
break;
}
row++;
}
return glasses[query_row][query_glass];
}
public static void main(String[] args) {
Problem799 prob = new Problem799();
// System.out.println(prob.champagneTower(1, 1, 1)); // 0.0
// System.out.println(prob.champagneTower(2, 1, 1)); // 0.5
// System.out.println(prob.champagneTower(3, 0, 0)); // 1.0
// System.out.println(prob.champagneTower(3, 1, 1)); // 1.0
// System.out.println(prob.champagneTower(3, 2, 0)); // 0.0
// System.out.println(prob.champagneTower(3, 2, 1)); // 0.0
// System.out.println(prob.champagneTower(4, 2, 0)); // 0.25
// System.out.println(prob.champagneTower(4, 1, 0)); // 1.0
// System.out.println(prob.champagneTower(4, 1, 1)); // 1.0
// System.out.println(prob.champagneTower(4, 2, 1)); // 0.5
System.out.println(prob.champagneTower(6, 3, 0)); // 0.0
}
}
| src/main/java/leetcode/Problem799.java | package leetcode;
/**
* https://leetcode.com/problems/champagne-tower/
*/
public class Problem799 {
public double champagneTower(int poured, int query_row, int query_glass) {
double[][] glasses = new double[100][100];
int row = 0;
glasses[row] = new double[]{poured};
while (row < glasses.length) {
int colIdx = 0;
boolean overflow = false;
for (int col = 0; col < glasses[row].length; col++) {
double val = glasses[row][col];
if (val == 0) {
break;
}
if (val > 1) {
glasses[row][col] = 1;
double half = (val - 1) / 2;
glasses[row + 1][colIdx++] += half;
glasses[row + 1][colIdx++] += half;
overflow = true;
}
}
if (!overflow) {
break;
}
row++;
}
return glasses[query_row][query_glass];
}
public static void main(String[] args) {
Problem799 prob = new Problem799();
// System.out.println(prob.champagneTower(1, 1, 1)); // 0.0
// System.out.println(prob.champagneTower(2, 1, 1)); // 0.5
// System.out.println(prob.champagneTower(3, 0, 0)); // 1.0
// System.out.println(prob.champagneTower(3, 1, 1)); // 1.0
// System.out.println(prob.champagneTower(3, 2, 0)); // 0.0
// System.out.println(prob.champagneTower(3, 2, 1)); // 0.0
// System.out.println(prob.champagneTower(4, 2, 0)); // 0.25
// System.out.println(prob.champagneTower(4, 1, 0)); // 1.0
// System.out.println(prob.champagneTower(4, 1, 1)); // 1.0
System.out.println(prob.champagneTower(4, 2, 1)); // 0.5
}
}
| Update problem 799
| src/main/java/leetcode/Problem799.java | Update problem 799 | <ide><path>rc/main/java/leetcode/Problem799.java
<ide> glasses[row][col] = 1;
<ide> double half = (val - 1) / 2;
<ide> glasses[row + 1][colIdx++] += half;
<del> glasses[row + 1][colIdx++] += half;
<add> glasses[row + 1][colIdx] += half;
<ide> overflow = true;
<ide> }
<ide> }
<ide> // System.out.println(prob.champagneTower(4, 2, 0)); // 0.25
<ide> // System.out.println(prob.champagneTower(4, 1, 0)); // 1.0
<ide> // System.out.println(prob.champagneTower(4, 1, 1)); // 1.0
<del> System.out.println(prob.champagneTower(4, 2, 1)); // 0.5
<add>// System.out.println(prob.champagneTower(4, 2, 1)); // 0.5
<add> System.out.println(prob.champagneTower(6, 3, 0)); // 0.0
<ide> }
<ide> } |
|
Java | mit | 90c0e7360bb9a7bac4e4127b815ebfd7813a2774 | 0 | DemigodsRPG/Demigods3 | package com.censoredsoftware.demigods.listener;
import com.censoredsoftware.demigods.Demigods;
import com.censoredsoftware.demigods.battle.Battle;
import com.censoredsoftware.demigods.battle.Participant;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.util.Vector;
public class BattleListener implements Listener
{
@EventHandler(priority = EventPriority.HIGHEST)
public static void onDamageBy(EntityDamageByEntityEvent event)
{
if(event.isCancelled()) return;
if(Demigods.isDisabledWorld(event.getEntity().getLocation())) return;
Entity damager = event.getDamager();
if(damager instanceof Projectile) damager = ((Projectile) damager).getShooter();
if(!Battle.Util.canParticipate(event.getEntity()) || !Battle.Util.canParticipate(damager)) return;
// Define participants
Participant damageeParticipant = Battle.Util.defineParticipant(event.getEntity());
Participant damagerParticipant = Battle.Util.defineParticipant(damager);
if(damageeParticipant.equals(damagerParticipant)) return;
// Calculate midpoint location
Location midpoint = damagerParticipant.getCurrentLocation().toVector().getMidpoint(event.getEntity().getLocation().toVector()).toLocation(damagerParticipant.getCurrentLocation().getWorld());
if(Battle.Util.isInBattle(damageeParticipant) || Battle.Util.isInBattle(damagerParticipant))
{
// Add to existing battle
Battle battle = Battle.Util.isInBattle(damageeParticipant) ? Battle.Util.getBattle(damageeParticipant) : Battle.Util.getBattle(damagerParticipant);
// Add participants from this event
battle.addParticipant(damageeParticipant);
battle.addParticipant(damagerParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
return;
}
if(!Battle.Util.existsNear(midpoint) && !Battle.Util.existsInRadius(midpoint))
{
// Create new battle
Battle battle = Battle.Util.create(damagerParticipant, damageeParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
// Debug
Demigods.message.broadcast(ChatColor.YELLOW + "Battle started involving " + damagerParticipant.getRelatedCharacter().getName() + " and " + damageeParticipant.getRelatedCharacter().getName() + "!");
}
else
{
// Add to existing battle
Battle battle = Battle.Util.getNear(midpoint) != null ? Battle.Util.getNear(midpoint) : Battle.Util.getInRadius(midpoint);
// Add participants from this event
battle.addParticipant(damageeParticipant);
battle.addParticipant(damagerParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onDamage(EntityDamageEvent event)
{
if(Demigods.isDisabledWorld(event.getEntity().getLocation())) return;
if(event instanceof EntityDamageByEntityEvent || !Battle.Util.canParticipate(event.getEntity())) return;
Participant participant = Battle.Util.defineParticipant(event.getEntity());
// Battle death
if(Battle.Util.isInBattle(participant) && event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(participant, Battle.Util.getBattle(participant));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleMove(PlayerMoveEvent event)
{
if(Demigods.isDisabledWorld(event.getPlayer().getLocation())) return;
if(!Battle.Util.canParticipate(event.getPlayer())) return;
Participant participant = Battle.Util.defineParticipant(event.getPlayer());
if(Battle.Util.isInBattle(participant))
{
Battle battle = Battle.Util.getBattle(participant);
if(event.getTo().distance(battle.getStartLocation()) > battle.getRange())
{
event.getPlayer().getVelocity();
Vector vector = battle.getStartLocation().toVector();
Vector victor = event.getPlayer().getLocation().toVector().add(vector).multiply(1.3D);
event.getPlayer().setVelocity(victor);
};
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleMove(PlayerTeleportEvent event)
{
if(Demigods.isDisabledWorld(event.getPlayer().getLocation())) return;
if(!Battle.Util.canParticipate(event.getPlayer())) return;
Participant participant = Battle.Util.defineParticipant(event.getPlayer());
if(Battle.Util.isInBattle(participant))
{
Battle battle = Battle.Util.getBattle(participant);
if(!event.getTo().getWorld().equals(battle.getStartLocation().getWorld())) return;
if(event.getTo().distance(battle.getStartLocation()) > battle.getRange()) event.setCancelled(true);
}
}
}
| src/main/java/com/censoredsoftware/demigods/listener/BattleListener.java | package com.censoredsoftware.demigods.listener;
import com.censoredsoftware.demigods.Demigods;
import com.censoredsoftware.demigods.battle.Battle;
import com.censoredsoftware.demigods.battle.Participant;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
public class BattleListener implements Listener
{
@EventHandler(priority = EventPriority.HIGHEST)
public static void onDamageBy(EntityDamageByEntityEvent event)
{
if(event.isCancelled()) return;
if(Demigods.isDisabledWorld(event.getEntity().getLocation())) return;
Entity damager = event.getDamager();
if(damager instanceof Projectile) damager = ((Projectile) damager).getShooter();
if(!Battle.Util.canParticipate(event.getEntity()) || !Battle.Util.canParticipate(damager)) return;
// Define participants
Participant damageeParticipant = Battle.Util.defineParticipant(event.getEntity());
Participant damagerParticipant = Battle.Util.defineParticipant(damager);
if(damageeParticipant.equals(damagerParticipant)) return;
// Calculate midpoint location
Location midpoint = damagerParticipant.getCurrentLocation().toVector().getMidpoint(event.getEntity().getLocation().toVector()).toLocation(damagerParticipant.getCurrentLocation().getWorld());
if(Battle.Util.isInBattle(damageeParticipant) || Battle.Util.isInBattle(damagerParticipant))
{
// Add to existing battle
Battle battle = Battle.Util.isInBattle(damageeParticipant) ? Battle.Util.getBattle(damageeParticipant) : Battle.Util.getBattle(damagerParticipant);
// Add participants from this event
battle.addParticipant(damageeParticipant);
battle.addParticipant(damagerParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
return;
}
if(!Battle.Util.existsNear(midpoint) && !Battle.Util.existsInRadius(midpoint))
{
// Create new battle
Battle battle = Battle.Util.create(damagerParticipant, damageeParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
// Debug
Demigods.message.broadcast(ChatColor.YELLOW + "Battle started involving " + damagerParticipant.getRelatedCharacter().getName() + " and " + damageeParticipant.getRelatedCharacter().getName() + "!");
}
else
{
// Add to existing battle
Battle battle = Battle.Util.getNear(midpoint) != null ? Battle.Util.getNear(midpoint) : Battle.Util.getInRadius(midpoint);
// Add participants from this event
battle.addParticipant(damageeParticipant);
battle.addParticipant(damagerParticipant);
// Battle death
if(event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(damagerParticipant, damageeParticipant, battle);
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onDamage(EntityDamageEvent event)
{
if(Demigods.isDisabledWorld(event.getEntity().getLocation())) return;
if(event instanceof EntityDamageByEntityEvent || !Battle.Util.canParticipate(event.getEntity())) return;
Participant participant = Battle.Util.defineParticipant(event.getEntity());
// Battle death
if(Battle.Util.isInBattle(participant) && event.getDamage() >= ((LivingEntity) event.getEntity()).getHealth())
{
event.setCancelled(true);
Battle.Util.battleDeath(participant, Battle.Util.getBattle(participant));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleMove(PlayerMoveEvent event)
{
if(Demigods.isDisabledWorld(event.getPlayer().getLocation())) return;
if(!Battle.Util.canParticipate(event.getPlayer())) return;
Participant participant = Battle.Util.defineParticipant(event.getPlayer());
if(Battle.Util.isInBattle(participant))
{
Battle battle = Battle.Util.getBattle(participant);
if(event.getTo().distance(battle.getStartLocation()) > battle.getRange()) event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleMove(PlayerTeleportEvent event)
{
if(Demigods.isDisabledWorld(event.getPlayer().getLocation())) return;
if(!Battle.Util.canParticipate(event.getPlayer())) return;
Participant participant = Battle.Util.defineParticipant(event.getPlayer());
if(Battle.Util.isInBattle(participant))
{
Battle battle = Battle.Util.getBattle(participant);
if(!event.getTo().getWorld().equals(battle.getStartLocation().getWorld())) return;
if(event.getTo().distance(battle.getStartLocation()) > battle.getRange()) event.setCancelled(true);
}
}
}
| Try to shove them back in.
| src/main/java/com/censoredsoftware/demigods/listener/BattleListener.java | Try to shove them back in. | <ide><path>rc/main/java/com/censoredsoftware/demigods/listener/BattleListener.java
<ide> import org.bukkit.event.entity.EntityDamageEvent;
<ide> import org.bukkit.event.player.PlayerMoveEvent;
<ide> import org.bukkit.event.player.PlayerTeleportEvent;
<add>import org.bukkit.util.Vector;
<ide>
<ide> public class BattleListener implements Listener
<ide> {
<ide> if(Battle.Util.isInBattle(participant))
<ide> {
<ide> Battle battle = Battle.Util.getBattle(participant);
<del> if(event.getTo().distance(battle.getStartLocation()) > battle.getRange()) event.setCancelled(true);
<add> if(event.getTo().distance(battle.getStartLocation()) > battle.getRange())
<add> {
<add> event.getPlayer().getVelocity();
<add> Vector vector = battle.getStartLocation().toVector();
<add> Vector victor = event.getPlayer().getLocation().toVector().add(vector).multiply(1.3D);
<add> event.getPlayer().setVelocity(victor);
<add> };
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 0b5f4484630558840d431115fcfdd69221689eda | 0 | CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web | 'use strict';
angular.module('confRegistrationWebApp')
.directive('block', function () {
return {
templateUrl: 'views/blockDirective.html',
restrict: 'E',
controller: function ($scope, $location, AnswerCache, RegistrationCache, uuid) {
$scope.wizard = $location.path().indexOf('wizard') !== -1;
RegistrationCache.getCurrent($scope.conference.id).then(function (currentRegistration) {
var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id });
if (answerForThisBlock.length > 0) {
$scope.answer = answerForThisBlock[0];
}
if (angular.isUndefined($scope.answer)) {
$scope.answer = {
id : uuid(),
registrationId : currentRegistration.id,
blockId : $scope.block.id,
value : {}
};
currentRegistration.answers.push($scope.answer);
}
});
AnswerCache.syncBlock($scope, 'answer');
}
};
});
| app/scripts/directives/block.js | 'use strict';
angular.module('confRegistrationWebApp')
.directive('block', function () {
return {
templateUrl: 'views/blockDirective.html',
restrict: 'E',
controller: function ($scope, AnswerCache, RegistrationCache, uuid) {
$scope.wizard = $location.path().indexOf('wizard') !== -1;
RegistrationCache.getCurrent($scope.conference.id).then(function (currentRegistration) {
var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id });
if (answerForThisBlock.length > 0) {
$scope.answer = answerForThisBlock[0];
}
if (angular.isUndefined($scope.answer)) {
$scope.answer = {
id : uuid(),
registrationId : currentRegistration.id,
blockId : $scope.block.id,
value : {}
};
currentRegistration.answers.push($scope.answer);
}
});
AnswerCache.syncBlock($scope, 'answer');
}
};
});
| Added $location argument
| app/scripts/directives/block.js | Added $location argument | <ide><path>pp/scripts/directives/block.js
<ide> return {
<ide> templateUrl: 'views/blockDirective.html',
<ide> restrict: 'E',
<del> controller: function ($scope, AnswerCache, RegistrationCache, uuid) {
<add> controller: function ($scope, $location, AnswerCache, RegistrationCache, uuid) {
<ide> $scope.wizard = $location.path().indexOf('wizard') !== -1;
<ide> RegistrationCache.getCurrent($scope.conference.id).then(function (currentRegistration) {
<ide> var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id }); |
|
Java | apache-2.0 | 287603d36c304913929d69a96d8d66a8a0450e32 | 0 | visallo/vertexium,visallo/vertexium,v5analytics/vertexium | package org.vertexium.test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.junit.*;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.vertexium.*;
import org.vertexium.event.*;
import org.vertexium.mutation.ElementMutation;
import org.vertexium.mutation.ExistingElementMutation;
import org.vertexium.property.PropertyValue;
import org.vertexium.property.StreamingPropertyValue;
import org.vertexium.query.*;
import org.vertexium.search.DefaultSearchIndex;
import org.vertexium.search.IndexHint;
import org.vertexium.test.util.LargeStringInputStream;
import org.vertexium.type.*;
import org.vertexium.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import static org.vertexium.test.util.VertexiumAssert.*;
import static org.vertexium.util.IterableUtils.count;
import static org.vertexium.util.IterableUtils.toList;
import static org.vertexium.util.StreamUtils.stream;
@RunWith(JUnit4.class)
public abstract class GraphTestBase {
private static final VertexiumLogger LOGGER = VertexiumLoggerFactory.getLogger(GraphTestBase.class);
public static final String VISIBILITY_A_STRING = "a";
public static final String VISIBILITY_B_STRING = "b";
public static final String VISIBILITY_C_STRING = "c";
public static final String VISIBILITY_MIXED_CASE_STRING = "MIXED_CASE_a";
public static final Visibility VISIBILITY_A = new Visibility(VISIBILITY_A_STRING);
public static final Visibility VISIBILITY_A_AND_B = new Visibility("a&b");
public static final Visibility VISIBILITY_B = new Visibility("b");
public static final Visibility VISIBILITY_MIXED_CASE_a = new Visibility("((MIXED_CASE_a))|b");
public static final Visibility VISIBILITY_EMPTY = new Visibility("");
public final Authorizations AUTHORIZATIONS_A;
public final Authorizations AUTHORIZATIONS_B;
public final Authorizations AUTHORIZATIONS_C;
public final Authorizations AUTHORIZATIONS_MIXED_CASE_a_AND_B;
public final Authorizations AUTHORIZATIONS_A_AND_B;
public final Authorizations AUTHORIZATIONS_EMPTY;
public final Authorizations AUTHORIZATIONS_BAD;
public final Authorizations AUTHORIZATIONS_ALL;
public static final int LARGE_PROPERTY_VALUE_SIZE = 1024 * 1024 + 1;
protected Graph graph;
protected abstract Graph createGraph() throws Exception;
public Graph getGraph() {
return graph;
}
public GraphTestBase() {
AUTHORIZATIONS_A = createAuthorizations("a");
AUTHORIZATIONS_B = createAuthorizations("b");
AUTHORIZATIONS_C = createAuthorizations("c");
AUTHORIZATIONS_A_AND_B = createAuthorizations("a", "b");
AUTHORIZATIONS_MIXED_CASE_a_AND_B = createAuthorizations("MIXED_CASE_a", "b");
AUTHORIZATIONS_EMPTY = createAuthorizations();
AUTHORIZATIONS_BAD = createAuthorizations("bad");
AUTHORIZATIONS_ALL = createAuthorizations("a", "b", "c", "MIXED_CASE_a");
}
protected abstract Authorizations createAuthorizations(String... auths);
@Before
public void before() throws Exception {
graph = createGraph();
clearGraphEvents();
graph.addGraphEventListener(new GraphEventListener() {
@Override
public void onGraphEvent(GraphEvent graphEvent) {
addGraphEvent(graphEvent);
}
});
}
@After
public void after() throws Exception {
if (graph != null) {
graph.shutdown();
graph = null;
}
}
// Need this to given occasional output so Travis doesn't fail the build for no output
@Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
System.out.println("Starting test: " + description.getMethodName());
}
};
@Test
public void testAddVertexWithId() {
Vertex vertexAdded = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(vertexAdded);
assertEquals("v1", vertexAdded.getId());
graph.flush();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_A, v.getVisibility());
v = graph.getVertex("", AUTHORIZATIONS_A);
assertNull(v);
v = graph.getVertex(null, AUTHORIZATIONS_A);
assertNull(v);
assertEvents(
new AddVertexEvent(graph, vertexAdded)
);
}
@Test
public void testAddVertexWithoutId() {
Vertex vertexAdded = graph.addVertex(VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(vertexAdded);
String vertexId = vertexAdded.getId();
assertNotNull(vertexId);
graph.flush();
Vertex v = graph.getVertex(vertexId, AUTHORIZATIONS_A);
assertNotNull(v);
assertNotNull(vertexId);
assertEvents(
new AddVertexEvent(graph, vertexAdded)
);
}
@Test
public void testGetSingleVertexWithSameRowPrefix() {
graph.addVertex("prefix", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
graph.addVertex("prefixA", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex v = graph.getVertex("prefix", AUTHORIZATIONS_EMPTY);
assertEquals("prefix", v.getId());
v = graph.getVertex("prefixA", AUTHORIZATIONS_EMPTY);
assertEquals("prefixA", v.getId());
}
@Test
public void testStreamingPropertyValueReadAsString() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("spv", StreamingPropertyValue.create("Hello World"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertEquals("Hello World", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString());
assertEquals("Wor", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString(6, 3));
assertEquals("", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString("Hello World".length(), 1));
assertEquals("Hello World", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString(0, 100));
}
@SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
@Test
public void testAddStreamingPropertyValue() throws IOException, InterruptedException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class, 6);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()),
String.class, expectedLargeValue.length()
);
String largePropertyName = "propLarge/\\*!@#$%^&*()[]{}|";
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Object> propSmallValues = v1.getPropertyValues("propSmall");
Assert.assertEquals(1, count(propSmallValues));
Object propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
StreamingPropertyValue value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
Iterable<Object> propLargeValues = v1.getPropertyValues(largePropertyName);
Assert.assertEquals(1, count(propLargeValues));
Object propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
propSmallValues = v1.getPropertyValues("propSmall");
Assert.assertEquals(1, count(propSmallValues));
propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
propLargeValues = v1.getPropertyValues(largePropertyName);
Assert.assertEquals(1, count(propLargeValues));
propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
}
@Test
public void testAddVertexPropertyWithMetadata() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("metadata1", "metadata1Value", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
if (v instanceof HasTimestamp) {
assertTrue("timestamp should be more than 0", v.getTimestamp() > 0);
}
Assert.assertEquals(1, count(v.getProperties("prop1")));
Property prop1 = v.getProperties("prop1").iterator().next();
if (prop1 instanceof HasTimestamp) {
assertTrue("timestamp should be more than 0", prop1.getTimestamp() > 0);
}
prop1Metadata = prop1.getMetadata();
assertNotNull(prop1Metadata);
assertEquals(1, prop1Metadata.entrySet().size());
assertEquals("metadata1Value", prop1Metadata.getEntry("metadata1", VISIBILITY_A).getValue());
prop1Metadata.add("metadata2", "metadata2Value", VISIBILITY_A);
v.prepareMutation()
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(2, prop1Metadata.entrySet().size());
assertEquals("metadata1Value", prop1Metadata.getEntry("metadata1", VISIBILITY_A).getValue());
assertEquals("metadata2Value", prop1Metadata.getEntry("metadata2", VISIBILITY_A).getValue());
// make sure that when we update the value the metadata is not carried over
prop1Metadata = new Metadata();
v.setProperty("prop1", "value2", prop1Metadata, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
assertEquals("value2", prop1.getValue());
prop1Metadata = prop1.getMetadata();
assertEquals(0, prop1Metadata.entrySet().size());
}
@Test
public void testAddVertexWithProperties() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(vertexAdded.getProperties("prop1")));
assertEquals("value1", vertexAdded.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(vertexAdded.getProperties("prop2")));
assertEquals("value2", vertexAdded.getPropertyValues("prop2").iterator().next());
graph.flush();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
assertEvents(
new AddVertexEvent(graph, vertexAdded),
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop1")),
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop2"))
);
clearGraphEvents();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v.prepareMutation()
.addPropertyValue("key1", "prop1Mutation", "value1Mutation", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(v.getProperties("prop1Mutation")));
assertEquals("value1Mutation", v.getPropertyValues("prop1Mutation").iterator().next());
assertEvents(
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop1Mutation"))
);
}
@Test
public void testNullPropertyValue() {
try {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", null, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
throw new VertexiumException("expected null check");
} catch (NullPointerException ex) {
assertTrue(ex.getMessage().contains("prop1"));
}
}
@Test
public void testConcurrentModificationOfProperties() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
int i = 0;
for (Property p : v.getProperties()) {
assertNotNull(p.toString());
if (i == 0) {
v.setProperty("prop3", "value3", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
}
i++;
}
}
@Test
public void testAddVertexWithPropertiesWithTwoDifferentVisibilities() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1a", VISIBILITY_A)
.setProperty("prop1", "value1b", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties("prop1")));
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1a", v.getPropertyValue("prop1"));
v = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1b", v.getPropertyValue("prop1"));
}
@Test
public void testMultivaluedProperties() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.addPropertyValue("propid3a", "prop3", "value3a", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("value1a", v.getPropertyValues("prop1").iterator().next());
assertEquals("value2a", v.getPropertyValues("prop2").iterator().next());
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
Assert.assertEquals(3, count(v.getProperties()));
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getPropertyValues("prop1")));
assertEquals("value1b", v.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(v.getPropertyValues("prop2")));
assertEquals("value2b", v.getPropertyValues("prop2").iterator().next());
Assert.assertEquals(1, count(v.getPropertyValues("prop3")));
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
Assert.assertEquals(3, count(v.getProperties()));
v.addPropertyValue("propid1b", "prop1", "value1a-new", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
org.vertexium.test.util.IterableUtils.assertContains("value1b", v.getPropertyValues("prop1"));
org.vertexium.test.util.IterableUtils.assertContains("value1a-new", v.getPropertyValues("prop1"));
Assert.assertEquals(4, count(v.getProperties()));
}
@Test
public void testMultivaluedPropertyOrder() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("a", "prop", "a", VISIBILITY_A)
.addPropertyValue("aa", "prop", "aa", VISIBILITY_A)
.addPropertyValue("b", "prop", "b", VISIBILITY_A)
.addPropertyValue("0", "prop", "0", VISIBILITY_A)
.addPropertyValue("A", "prop", "A", VISIBILITY_A)
.addPropertyValue("Z", "prop", "Z", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("0", v1.getPropertyValue("prop", 0));
assertEquals("A", v1.getPropertyValue("prop", 1));
assertEquals("Z", v1.getPropertyValue("prop", 2));
assertEquals("a", v1.getPropertyValue("prop", 3));
assertEquals("aa", v1.getPropertyValue("prop", 4));
assertEquals("b", v1.getPropertyValue("prop", 5));
}
@Test
public void testDeleteProperty() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
clearGraphEvents();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Property prop1_propid1a = v.getProperty("propid1a", "prop1");
Property prop1_propid1b = v.getProperty("propid1b", "prop1");
v.deleteProperties("prop1", AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(v.getProperties()));
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop2", "value2a").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1a").vertices()));
assertEvents(
new DeletePropertyEvent(graph, v, prop1_propid1a),
new DeletePropertyEvent(graph, v, prop1_propid1b)
);
clearGraphEvents();
Property prop2_propid2a = v.getProperty("propid2a", "prop2");
v.deleteProperty("propid2a", "prop2", AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, v, prop2_propid2a)
);
}
@Test
public void testDeletePropertyWithMutation() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "edge1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
clearGraphEvents();
// delete multiple properties
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Property prop1_propid1a = v1.getProperty("propid1a", "prop1");
Property prop1_propid1b = v1.getProperty("propid1b", "prop1");
v1.prepareMutation()
.deleteProperties("prop1")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(v1.getProperties()));
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getProperties()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop2", "value2a").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1a").vertices()));
assertEvents(
new DeletePropertyEvent(graph, v1, prop1_propid1a),
new DeletePropertyEvent(graph, v1, prop1_propid1b)
);
clearGraphEvents();
// delete property with key and name
Property prop2_propid2a = v1.getProperty("propid2a", "prop2");
v1.prepareMutation()
.deleteProperties("propid2a", "prop2")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(v1.getProperties()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, v1, prop2_propid2a)
);
clearGraphEvents();
// delete property from edge
Edge e1 = graph.getEdge("e1", FetchHint.ALL, AUTHORIZATIONS_A);
Property edgeProperty = e1.getProperty("key1", "prop1");
e1.prepareMutation()
.deleteProperties("key1", "prop1")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(e1.getProperties()));
e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(e1.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, e1, edgeProperty)
);
}
@Test
public void testDeleteElement() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
graph.deleteVertex(v.getId(), AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v);
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
}
@Test
public void testDeleteVertex() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A)));
}
@Test
public void testSoftDeleteVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
Vertex v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(1, v2.getEdgeCount(Direction.BOTH, AUTHORIZATIONS_A));
graph.softDeleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(0, v2.getEdgeCount(Direction.BOTH, AUTHORIZATIONS_A));
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(4, count(graph.getVertices(AUTHORIZATIONS_A)));
assertResultsCount(3, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.softDeleteVertex("v3", AUTHORIZATIONS_A);
graph.flush();
assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
assertResultsCount(2, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testGetSoftDeletedElementWithFetchHintsAndTimestamp() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
long beforeDeleteTime = IncreasingTime.currentTimeMillis();
graph.softDeleteEdge(e1, AUTHORIZATIONS_A);
graph.softDeleteVertex(v1, AUTHORIZATIONS_A);
graph.flush();
assertNull(graph.getEdge(e1.getId(), AUTHORIZATIONS_A));
assertNull(graph.getEdge(e1.getId(), graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
assertNull(graph.getEdge(e1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A));
assertNotNull(graph.getEdge(e1.getId(), graph.getDefaultFetchHints(), beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getEdge(e1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getVertex(v1.getId(), graph.getDefaultFetchHints(), beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getVertex(v1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, beforeDeleteTime, AUTHORIZATIONS_A));
}
@Test
public void testSoftDeleteEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.addVertex("v3", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.addEdge("e1", v1, v2, "label1", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.addEdge("e2", v1, v3, "label1", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
graph.softDeleteEdge(e1, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v1.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v1.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A_AND_B);
assertEquals(0, count(v2.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v2 = graph.getVertex("v2", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(0, count(v2.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v3.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v3 = graph.getVertex("v3", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v3.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testSoftDeleteProperty() throws InterruptedException {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A).softDeleteProperties("name1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A).softDeleteProperties("name1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testSoftDeletePropertyThroughMutation() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.softDeleteProperties("name1")
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.softDeleteProperties("name1")
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testSoftDeletePropertyOnEdgeNotIndexed() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
ElementBuilder<Edge> elementBuilder = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_B)
.setProperty("prop1", "value1", VISIBILITY_B);
elementBuilder.setIndexHint(IndexHint.DO_NOT_INDEX);
Edge e1 = elementBuilder.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
ExistingElementMutation<Edge> m = e1.prepareMutation();
m.softDeleteProperty("prop1", VISIBILITY_B);
m.setIndexHint(IndexHint.DO_NOT_INDEX);
m.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
assertEquals(0, IterableUtils.count(e1.getProperties()));
}
@Test
public void testSoftDeletePropertyWithVisibility() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("value1", v1.getPropertyValues("name1"));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).softDeleteProperty("key1", "name1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getPropertyValues("key1", "name1")));
org.vertexium.test.util.IterableUtils.assertContains("value2", graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getPropertyValues("name1"));
}
@Test
public void testSoftDeletePropertyThroughMutationWithVisibility() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("value1", v1.getPropertyValues("name1"));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B)
.prepareMutation()
.softDeleteProperty("key1", "name1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
assertEquals(1, count(v1.getPropertyValues("key1", "name1")));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
}
@Test
public void testSoftDeletePropertyOnAHiddenVertex() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
v1.softDeleteProperty("key1", "name1", AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
assertNull(v1.getProperty("key1", "name1", VISIBILITY_EMPTY));
}
@Test
public void testMarkHiddenWithVisibilityChange() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
List<Property> properties = IterableUtils.toList(v1.getProperties());
assertEquals(2, count(properties));
boolean foundJoeProp = false;
boolean foundJosephProp = false;
for (Property property : properties) {
if (property.getName().equals("firstName")) {
if (property.getKey().equals("key1") && property.getValue().equals("Joe")) {
foundJoeProp = true;
assertTrue("should be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A));
} else if (property.getKey().equals("key1") && property.getValue().equals("Joseph")) {
if (property.getVisibility().equals(VISIBILITY_B)) {
foundJosephProp = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Joseph property value not found", foundJosephProp);
assertTrue("Joe property value not found", foundJoeProp);
}
@Test
public void testSoftDeleteWithVisibilityChanges() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1.softDeleteProperty("key1", "firstName", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1.markPropertyVisible("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Property> properties = IterableUtils.toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
Property property = properties.iterator().next();
assertEquals(VISIBILITY_A, property.getVisibility());
assertEquals("Joseph", property.getValue());
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v2.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v2.getPropertyValues("firstName"));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A_AND_B);
v2.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v2.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v2.softDeleteProperty("key1", "firstName", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v2.markPropertyVisible("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v2.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
properties = IterableUtils.toList(graph.getVertex("v2", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
property = properties.iterator().next();
assertEquals(VISIBILITY_A, property.getVisibility());
assertEquals("Joe", property.getValue());
}
@Test
public void testMarkPropertyVisible() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
long t = IncreasingTime.currentTimeMillis();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, t, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
t += 10;
List<Property> properties = IterableUtils.toList(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
long beforeMarkPropertyVisibleTimestamp = t;
t += 10;
v1.markPropertyVisible("key1", "firstName", VISIBILITY_A, t, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
t += 10;
properties = IterableUtils.toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
graph.flush();
v1 = graph.getVertex("v1", graph.getDefaultFetchHints(), beforeMarkPropertyVisibleTimestamp, AUTHORIZATIONS_A_AND_B);
assertNotNull("could not find v1 before timestamp " + beforeMarkPropertyVisibleTimestamp + " current time " + t, v1);
properties = IterableUtils.toList(v1.getProperties());
assertEquals(0, count(properties));
}
@Test
public void testAddVertexWithVisibility() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_ALL);
graph.flush();
Iterable<Vertex> cVertices = graph.getVertices(AUTHORIZATIONS_C);
Assert.assertEquals(0, count(cVertices));
Iterable<Vertex> aVertices = graph.getVertices(AUTHORIZATIONS_A);
assertEquals("v1", IterableUtils.single(aVertices).getId());
Iterable<Vertex> bVertices = graph.getVertices(AUTHORIZATIONS_B);
assertEquals("v2", IterableUtils.single(bVertices).getId());
Iterable<Vertex> allVertices = graph.getVertices(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(allVertices));
}
@Test
public void testAddMultipleVertices() {
List<ElementBuilder<Vertex>> elements = new ArrayList<>();
elements.add(graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "v1", VISIBILITY_A));
elements.add(graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "v2", VISIBILITY_A));
Iterable<Vertex> vertices = graph.addVertices(elements, AUTHORIZATIONS_A_AND_B);
assertVertexIds(vertices, "v1", "v2");
graph.flush();
if (graph instanceof GraphWithSearchIndex) {
((GraphWithSearchIndex) graph).getSearchIndex().addElements(graph, vertices, AUTHORIZATIONS_A_AND_B);
assertVertexIds(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "v1").vertices(), "v1");
assertVertexIds(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "v2").vertices(), "v2");
}
}
@Test
public void testGetVerticesWithIds() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v1b", VISIBILITY_A)
.setProperty("prop1", "v1b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("prop1", "v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> ids = new ArrayList<>();
ids.add("v2");
ids.add("v1");
Iterable<Vertex> vertices = graph.getVertices(ids, AUTHORIZATIONS_A);
boolean foundV1 = false, foundV2 = false;
for (Vertex v : vertices) {
if (v.getId().equals("v1")) {
assertEquals("v1", v.getPropertyValue("prop1"));
foundV1 = true;
} else if (v.getId().equals("v2")) {
assertEquals("v2", v.getPropertyValue("prop1"));
foundV2 = true;
} else {
assertTrue("Unexpected vertex id: " + v.getId(), false);
}
}
assertTrue("v1 not found", foundV1);
assertTrue("v2 not found", foundV2);
List<Vertex> verticesInOrder = graph.getVerticesInOrder(ids, AUTHORIZATIONS_A);
assertEquals(2, verticesInOrder.size());
assertEquals("v2", verticesInOrder.get(0).getId());
assertEquals("v1", verticesInOrder.get(1).getId());
}
@Test
public void testGetVerticesWithPrefix() {
graph.addVertex("a", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("aa", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("az", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("b", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Vertex> vertices = sortById(toList(graph.getVerticesWithPrefix("a", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices, "a", "aa", "az");
vertices = sortById(toList(graph.getVerticesWithPrefix("b", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices, "b");
vertices = sortById(toList(graph.getVerticesWithPrefix("c", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices);
}
@Test
public void testGetVerticesInRange() {
graph.addVertex("a", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("aa", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("az", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("b", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Vertex> vertices = toList(graph.getVerticesInRange(new Range(null, "a"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices);
vertices = toList(graph.getVerticesInRange(new Range(null, "b"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az");
vertices = toList(graph.getVerticesInRange(new Range(null, "bb"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az", "b");
vertices = toList(graph.getVerticesInRange(new Range(null, null), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az", "b");
}
@Test
public void testGetEdgesInRange() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("a", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("aa", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("az", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("b", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Edge> edges = toList(graph.getEdgesInRange(new Range(null, "a"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{});
edges = toList(graph.getEdgesInRange(new Range(null, "b"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az"});
edges = toList(graph.getEdgesInRange(new Range(null, "bb"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az", "b"});
edges = toList(graph.getEdgesInRange(new Range(null, null), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az", "b"});
}
@Test
public void testGetEdgesWithIds() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1a", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "", VISIBILITY_A)
.setProperty("prop1", "e2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", v2, v3, "", VISIBILITY_A)
.setProperty("prop1", "e3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> ids = new ArrayList<>();
ids.add("e1");
ids.add("e2");
Iterable<Edge> edges = graph.getEdges(ids, AUTHORIZATIONS_A);
boolean foundE1 = false, foundE2 = false;
for (Edge e : edges) {
if (e.getId().equals("e1")) {
assertEquals("e1", e.getPropertyValue("prop1"));
foundE1 = true;
} else if (e.getId().equals("e2")) {
assertEquals("e2", e.getPropertyValue("prop1"));
foundE2 = true;
} else {
assertTrue("Unexpected vertex id: " + e.getId(), false);
}
}
assertTrue("e1 not found", foundE1);
assertTrue("e2 not found", foundE2);
}
@Test
public void testMarkVertexAndPropertiesHidden() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("k2", "age", 30, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_ALL);
for (Property property : v1.getProperties()) {
v1.markPropertyHidden(property, VISIBILITY_A, AUTHORIZATIONS_ALL);
}
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull("v1 was found", v1);
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_ALL);
assertNotNull("could not find v1", v1);
assertEquals(2, count(v1.getProperties()));
assertEquals(25, v1.getPropertyValue("k1", "age"));
assertEquals(30, v1.getPropertyValue("k2", "age"));
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_ALL);
graph.markVertexVisible(v1, VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1AfterVisible = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull("could not find v1", v1AfterVisible);
assertEquals(0, count(v1AfterVisible.getProperties()));
for (Property property : v1.getProperties()) {
v1.markPropertyVisible(property, VISIBILITY_A, AUTHORIZATIONS_ALL);
}
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull("could not find v1", v1);
assertEquals(2, count(v1.getProperties()));
assertEquals(25, v1.getPropertyValue("k1", "age"));
assertEquals(30, v1.getPropertyValue("k2", "age"));
}
@Test
public void testMarkVertexHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("v1tov2", v1, v2, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
List<String> vertexIdList = new ArrayList<>();
vertexIdList.add("v1");
vertexIdList.add("v2");
vertexIdList.add("bad"); // add "bad" to the end of the list to test ordering of results
Map<String, Boolean> verticesExist = graph.doVerticesExist(vertexIdList, AUTHORIZATIONS_A);
assertEquals(3, vertexIdList.size());
assertTrue("v1 exist", verticesExist.get("v1"));
assertTrue("v2 exist", verticesExist.get("v2"));
assertFalse("bad exist", verticesExist.get("bad"));
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertTrue("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexHidden(v1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertFalse("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
assertNull("found v1 but shouldn't have", graph.getVertex("v1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
Vertex v1Hidden = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
assertNotNull("did not find v1 but should have", v1Hidden);
assertTrue("v1 should be hidden", v1Hidden.isHidden(AUTHORIZATIONS_A));
graph.markVertexVisible(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexVisible(v1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertTrue("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
}
@Test
public void testMarkEdgeHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("v1tov2", v1, v2, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("v2tov3", v2, v3, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
List<String> edgeIdList = new ArrayList<>();
edgeIdList.add("v1tov2");
edgeIdList.add("v2tov3");
edgeIdList.add("bad");
Map<String, Boolean> edgesExist = graph.doEdgesExist(edgeIdList, AUTHORIZATIONS_A);
assertEquals(3, edgeIdList.size());
assertTrue("v1tov2 exist", edgesExist.get("v1tov2"));
assertTrue("v2tov3 exist", edgesExist.get("v2tov3"));
assertFalse("bad exist", edgesExist.get("bad"));
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertTrue("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
graph.markEdgeHidden(e1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertFalse("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdgeInfos(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdgeInfos(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A)));
assertNull("found e1 but shouldn't have", graph.getEdge("v1tov2", graph.getDefaultFetchHints(), AUTHORIZATIONS_A_AND_B));
Edge e1Hidden = graph.getEdge("v1tov2", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertNotNull("did not find e1 but should have", e1Hidden);
assertTrue("e1 should be hidden", e1Hidden.isHidden(AUTHORIZATIONS_A_AND_B));
graph.markEdgeVisible(e1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertTrue("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testMarkPropertyHidden() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_B)
.addPropertyValue("key2", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Assert.assertEquals(3, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1")));
v1.markPropertyHidden("key1", "prop1", VISIBILITY_A, VISIBILITY_A_AND_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Property> properties = toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1"));
Assert.assertEquals(2, count(properties));
boolean foundProp1Key2 = false;
boolean foundProp1Key1VisB = false;
for (Property property : properties) {
if (property.getName().equals("prop1")) {
if (property.getKey().equals("key2")) {
foundProp1Key2 = true;
} else if (property.getKey().equals("key1")) {
if (property.getVisibility().equals(VISIBILITY_B)) {
foundProp1Key1VisB = true;
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Prop1Key2 not found", foundProp1Key2);
assertTrue("Prop1Key1VisB not found", foundProp1Key1VisB);
List<Property> hiddenProperties = toList(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(3, hiddenProperties.size());
boolean foundProp1Key1VisA = false;
foundProp1Key2 = false;
foundProp1Key1VisB = false;
for (Property property : hiddenProperties) {
if (property.getName().equals("prop1")) {
if (property.getKey().equals("key2")) {
foundProp1Key2 = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else if (property.getKey().equals("key1")) {
if (property.getVisibility().equals(VISIBILITY_A)) {
foundProp1Key1VisA = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A));
assertTrue("should be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else if (property.getVisibility().equals(VISIBILITY_B)) {
foundProp1Key1VisB = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Prop1Key2 not found", foundProp1Key2);
assertTrue("Prop1Key1VisB not found", foundProp1Key1VisB);
assertTrue("Prop1Key1VisA not found", foundProp1Key1VisA);
v1.markPropertyVisible("key1", "prop1", VISIBILITY_A, VISIBILITY_A_AND_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(3, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1")));
}
/**
* This tests simulates two workspaces w1 (via A) and w1 (vis B).
* Both w1 and w2 has e1 on it.
* e1 is linked to e2.
* What happens if w1 (vis A) marks e1 hidden, then deletes itself?
*/
@Test
public void testMarkVertexHiddenAndDeleteEdges() {
Vertex w1 = graph.addVertex("w1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex w2 = graph.addVertex("w2", VISIBILITY_B, AUTHORIZATIONS_B);
Vertex e1 = graph.addVertex("e1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex e2 = graph.addVertex("e2", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.addEdge("w1-e1", w1, e1, "test", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("w2-e1", w2, e1, "test", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge("e1-e2", e1, e2, "test", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.flush();
e1 = graph.getVertex("e1", AUTHORIZATIONS_EMPTY);
graph.markVertexHidden(e1, VISIBILITY_A, AUTHORIZATIONS_EMPTY);
graph.flush();
graph.getVertex("w1", AUTHORIZATIONS_A);
graph.deleteVertex("w1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals("e2", toList(graph.getVertices(AUTHORIZATIONS_A)).get(0).getId());
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_B)));
boolean foundW2 = false;
boolean foundE1 = false;
boolean foundE2 = false;
for (Vertex v : graph.getVertices(AUTHORIZATIONS_B)) {
if (v.getId().equals("w2")) {
foundW2 = true;
} else if (v.getId().equals("e1")) {
foundE1 = true;
} else if (v.getId().equals("e2")) {
foundE2 = true;
} else {
throw new VertexiumException("Unexpected id: " + v.getId());
}
}
assertTrue("w2", foundW2);
assertTrue("e1", foundE1);
assertTrue("e2", foundE2);
}
@Test
public void testDeleteVertexWithProperties() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Property prop1 = v1.getProperty("prop1");
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
assertEvents(
new AddVertexEvent(graph, v1),
new AddPropertyEvent(graph, v1, prop1),
new DeleteVertexEvent(graph, v1)
);
}
@Test
public void testAddEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertNotNull(addedEdge);
assertEquals("e1", addedEdge.getId());
assertEquals("label1", addedEdge.getLabel());
assertEquals("v1", addedEdge.getVertexId(Direction.OUT));
assertEquals(v1, addedEdge.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", addedEdge.getVertexId(Direction.IN));
assertEquals(v2, addedEdge.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, addedEdge.getVisibility());
EdgeVertices addedEdgeVertices = addedEdge.getVertices(AUTHORIZATIONS_A);
assertEquals(v1, addedEdgeVertices.getOutVertex());
assertEquals(v2, addedEdgeVertices.getInVertex());
graph.getVertex("v1", FetchHint.NONE, AUTHORIZATIONS_A);
graph.getVertex("v1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
graph.getVertex("v1", FetchHint.EDGE_REFS, AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.IN_EDGE_REFS), AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.OUT_EDGE_REFS), AUTHORIZATIONS_A);
graph.getEdge("e1", FetchHint.NONE, AUTHORIZATIONS_A);
graph.getEdge("e1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A);
graph.getEdge("e1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
Edge e = graph.getEdge("e1", AUTHORIZATIONS_B);
assertNull(e);
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge)
);
}
@Test
public void testGetEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2to1", v2.getId(), v1.getId(), "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.BOTH, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.OUT, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.OUT, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertArrayEquals(new String[]{"label1", "label2"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A), String.class));
Assert.assertArrayEquals(new String[]{"label1"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A), String.class));
Assert.assertArrayEquals(new String[]{"label1", "label2"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.BOTH, AUTHORIZATIONS_A), String.class));
}
@Test
public void testGetEdgeVertexPairs() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v2_label1 = graph.addEdge("v1_to_v2_label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v2_label2 = graph.addEdge("v1_to_v2_label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v3_label2 = graph.addEdge("v1_to_v3_label2", v1, v3, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<EdgeVertexPair> pairs = toList(v1.getEdgeVertexPairs(Direction.BOTH, AUTHORIZATIONS_A));
assertEquals(3, pairs.size());
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label1, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label2, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v3_label2, v3)));
pairs = toList(v1.getEdgeVertexPairs(Direction.BOTH, "label2", AUTHORIZATIONS_A));
assertEquals(2, pairs.size());
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label2, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v3_label2, v3)));
}
@Test
public void testAddEdgeWithProperties() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.setProperty("propB", "valueB", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Assert.assertEquals(0, count(e.getPropertyValues("propB")));
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals("valueB", e.getPropertyValues("propB").iterator().next());
assertEquals("valueA", e.getPropertyValue("propA"));
assertEquals("valueB", e.getPropertyValue("propB"));
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge),
new AddPropertyEvent(graph, addedEdge, addedEdge.getProperty("propA")),
new AddPropertyEvent(graph, addedEdge, addedEdge.getProperty("propB"))
);
}
@Test
public void testAddEdgeWithNullInOutVertices() {
try {
String outVertexId = null;
String inVertexId = null;
getGraph().prepareEdge("e1", outVertexId, inVertexId, "label", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
try {
Vertex outVertex = null;
Vertex inVertex = null;
getGraph().prepareEdge("e1", outVertex, inVertex, "label", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
}
@Test
public void testAddEdgeWithNullLabels() {
try {
String label = null;
getGraph().prepareEdge("e1", "v1", "v2", label, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
try {
String label = null;
Vertex outVertex = getGraph().addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
Vertex inVertex = getGraph().addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
getGraph().prepareEdge("e1", outVertex, inVertex, label, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
}
@Test
public void testChangingPropertyOnEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Property propA = e.getProperty("", "propA");
assertNotNull(propA);
e.markPropertyHidden(propA, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(0, count(e.getProperties()));
Assert.assertEquals(0, count(e.getPropertyValues("propA")));
e.setProperty(propA.getName(), "valueA_changed", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA_changed", e.getPropertyValues("propA").iterator().next());
e.markPropertyVisible(propA, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(e.getProperties()));
Assert.assertEquals(2, count(e.getPropertyValues("propA")));
List<Object> propertyValues = IterableUtils.toList(e.getPropertyValues("propA"));
assertTrue(propertyValues.contains("valueA"));
assertTrue(propertyValues.contains("valueA_changed"));
}
@Test
public void testAlterEdgeLabel() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label1", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label1", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label1", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
e.prepareMutation()
.alterEdgeLabel("label2")
.save(AUTHORIZATIONS_A);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label2", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label2", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label2", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
graph.prepareEdge(e.getId(), e.getVertexId(Direction.OUT), e.getVertexId(Direction.IN), e.getLabel(), e.getVisibility())
.alterEdgeLabel("label3")
.save(AUTHORIZATIONS_A);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label3", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label3", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label3", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testDeleteEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
try {
graph.deleteEdge("e1", AUTHORIZATIONS_B);
} catch (NullPointerException e) {
// expected
}
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.deleteEdge("e1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge),
new DeleteEdgeEvent(graph, addedEdge)
);
}
@Test
public void testAddEdgeWithVisibility() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_B, AUTHORIZATIONS_B);
graph.flush();
Iterable<Edge> aEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(aEdges));
assertEquals("edgeA", IterableUtils.single(aEdges).getLabel());
Iterable<Edge> bEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_B);
Assert.assertEquals(1, count(bEdges));
assertEquals("edgeB", IterableUtils.single(bEdges).getLabel());
Iterable<Edge> allEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(allEdges));
}
@Test
public void testGraphQueryForIds() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<String> idsIterable = graph.query(AUTHORIZATIONS_A).vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(1).vertexIds();
assertResultsCount(2, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).limit(1).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(3).vertexIds();
assertResultsCount(0, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(2).limit(2).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).edgeIds();
assertIdsAnyOrder(idsIterable, "e1", "e2");
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edgeIds();
assertIdsAnyOrder(idsIterable, "e1");
assertResultsCount(1, 1, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edgeIds();
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).elementIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3", "e1", "e2");
assertResultsCount(5, 5, idsIterable);
assumeTrue("FetchHint.NONE vertex queries are not supported", isFetchHintNoneVertexQuerySupported());
idsIterable = graph.query(AUTHORIZATIONS_A).has("name").vertexIds();
assertIdsAnyOrder(idsIterable, "v1");
assertResultsCount(1, 1, idsIterable);
QueryResultsIterable<ExtendedDataRowId> extendedDataRowIds = graph.query(AUTHORIZATIONS_A).hasExtendedData("table1").extendedDataRowIds();
List<String> rowIds = stream(extendedDataRowIds).map(ExtendedDataRowId::getRowId).collect(Collectors.toList());
assertIdsAnyOrder(rowIds, "row1", "row2");
assertResultsCount(2, 2, extendedDataRowIds);
idsIterable = graph.query(AUTHORIZATIONS_A).hasNot("name").vertexIds();
assertIdsAnyOrder(idsIterable, "v2", "v3");
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp").vertexIds();
assertResultsCount(0, 0, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasNot("notSetProp").vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.NOT_EQUAL, 5).vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.EQUAL, 5).vertexIds();
assertResultsCount(0, 0, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.LESS_THAN_EQUAL, 5).vertexIds();
assertResultsCount(0, 0, idsIterable);
}
@Test
public void testGraphQuery() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).limit(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(2).vertices();
assertResultsCount(0, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(2).vertices();
assertResultsCount(1, 2, vertices);
QueryResultsIterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertResultsCount(2, 2, edges);
edges = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edges();
assertResultsCount(1, 1, edges);
edges = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edges();
assertResultsCount(2, 2, edges);
QueryResultsIterable<Element> elements = graph.query(AUTHORIZATIONS_A).elements();
assertResultsCount(4, 4, elements);
vertices = graph.query(AUTHORIZATIONS_A).has("name").vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).hasNot("name").vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp").vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).hasNot("notSetProp").vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.NOT_EQUAL, 5).vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.EQUAL, 5).vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.LESS_THAN_EQUAL, 5).vertices();
assertResultsCount(0, 0, vertices);
}
@Test
public void testGraphQueryWithBoolean() {
graph.defineProperty("boolean").dataType(Boolean.class).define();
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "boolean", true, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<Vertex> vertices = graph.query("zzzzz", AUTHORIZATIONS_A).vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("boolean", false).vertices();
assertResultsCount(0, 0, vertices);
}
@Test
public void testGraphQueryWithFetchHints() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("k1", "name", "matt", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertTrue(graph.getVertexCount(AUTHORIZATIONS_A) == 3);
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("name", "joe")
.vertices(EnumSet.of(FetchHint.PROPERTIES));
assertResultsCount(2, 2, vertices);
assumeTrue("FetchHint.NONE vertex queries are not supported", isFetchHintNoneVertexQuerySupported());
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", "joe")
.vertices(FetchHint.NONE);
assertResultsCount(2, 2, vertices);
}
protected boolean isFetchHintNoneVertexQuerySupported() {
return true;
}
@Test
public void testSaveElementMutations() {
List<ElementMutation> mutations = new ArrayList<>();
for (int i = 0; i < 2; i++) {
ElementBuilder<Vertex> m = graph.prepareVertex("v" + i, VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.addExtendedData("table1", "row1", "col1", "extended", VISIBILITY_A);
mutations.add(m);
}
List<Element> saveVertices = toList(graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL));
graph.flush();
assertEvents(
new AddVertexEvent(graph, (Vertex) saveVertices.get(0)),
new AddPropertyEvent(graph, saveVertices.get(0), saveVertices.get(0).getProperty("k1", "name")),
new AddVertexEvent(graph, (Vertex) saveVertices.get(1)),
new AddPropertyEvent(graph, saveVertices.get(1), saveVertices.get(1).getProperty("k1", "name"))
);
clearGraphEvents();
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_ALL).vertices();
assertResultsCount(2, 2, vertices);
QueryResultsIterable<? extends VertexiumObject> items = graph.query(AUTHORIZATIONS_ALL)
.has("col1", "extended")
.search();
assertResultsCount(2, 2, items);
mutations.clear();
mutations.add(((Vertex) saveVertices.get(0)).prepareMutation());
graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL);
graph.flush();
assertEvents();
}
@Test
public void testGraphQueryWithQueryString() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_B, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
e1.setProperty("description", "This is edge 1 - dog to cat.", VISIBILITY_A, AUTHORIZATIONS_ALL);
getGraph().flush();
Iterable<Vertex> vertices = graph.query("vertex", AUTHORIZATIONS_A_AND_B).vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query("vertex", AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_B).vertices();
Assert.assertEquals(0, count(vertices));
Iterable<Element> elements = graph.query("dog", AUTHORIZATIONS_A_AND_B).elements();
Assert.assertEquals(2, count(elements));
}
@Test
public void testGraphQueryWithQueryStringWithAuthorizations() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_ALL);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_B, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
e1.setProperty("edgeDescription", "This is edge 1 - dog to cat.", VISIBILITY_A, AUTHORIZATIONS_ALL);
getGraph().flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertEquals(1, count(vertices));
if (isIterableWithTotalHitsSupported(vertices)) {
IterableWithTotalHits hits = (IterableWithTotalHits) vertices;
assertEquals(1, hits.getTotalHits());
}
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertEquals(1, count(edges));
}
protected boolean isIterableWithTotalHitsSupported(Iterable<Vertex> vertices) {
return vertices instanceof IterableWithTotalHits;
}
@Test
public void testGraphQueryHas() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("text", "hello", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1989, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 24, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("text", "world", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1984, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 25, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age")
.vertices();
Assert.assertEquals(2, count(vertices));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.hasNot("age")
.vertices();
Assert.assertEquals(0, count(vertices));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("hello", AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, createDate(2014, 2, 24, 13, 0, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", 25)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, (int) toList(vertices).get(0).getPropertyValue("age"));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.hasNot("age", 25)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, (int) toList(vertices).get(0).getPropertyValue("age"));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN_EQUAL, 25)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25})
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, (int) toList(vertices).get(0).getPropertyValue("age"));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.NOT_IN, new Integer[]{25})
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, (int) toList(vertices).get(0).getPropertyValue("age"));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25, 30})
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN, 26)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN_EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.NOT_EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, new DateOnly(2014, 2, 24))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("*", AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25, 30})
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = new CompositeGraphQuery(
graph,
graph.query(AUTHORIZATIONS_A).has("age", 25),
graph.query(AUTHORIZATIONS_A).has("age", 25),
graph.query(AUTHORIZATIONS_A).has("age", 30)
).vertices();
Assert.assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryContainsNotIn() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("status", "0", VISIBILITY_A)
.setProperty("name", "susan", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("status", "1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v5", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v6", VISIBILITY_A)
.setProperty("status", "0", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
try {
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("status", Contains.NOT_IN, new String[]{"0"})
.vertices();
Assert.assertEquals(4, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("status", Contains.NOT_IN, new String[]{"0", "1"})
.vertices();
Assert.assertEquals(3, count(vertices));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
}
@Test
public void testGraphQueryHasGeoPointAndExact() {
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.defineProperty("exact").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "val1", VISIBILITY_A)
.setProperty("exact", "val1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop2", "val2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Element> results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("prop1").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("exact").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("location").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
}
@Test
public void testGraphQueryHasNotGeoPointAndExact() {
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.defineProperty("exact").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "val1", VISIBILITY_A)
.setProperty("exact", "val1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop2", "val2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Element> results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("prop1").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("prop3").sort(Element.ID_PROPERTY_NAME, SortDirection.ASCENDING).elements();
assertEquals(2, count(results));
Iterator<Element> iterator = results.iterator();
assertEquals("v1", iterator.next().getId());
assertEquals("v2", iterator.next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("exact").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("location").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
}
@Test
public void testGraphQueryHasTwoVisibilities() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "v2", VISIBILITY_A)
.addPropertyValue("k1", "age", 30, VISIBILITY_A)
.addPropertyValue("k2", "age", 35, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age")
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.hasNot("age")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryIn() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.defineProperty("name").dataType(String.class).sortable(true).textIndexHint(TextIndexHint.ALL).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe ferner", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob smith", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "tom thumb", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> strings = new ArrayList<>();
strings.add("joe ferner");
strings.add("tom thumb");
Iterable<Vertex> results = graph.query(AUTHORIZATIONS_A_AND_B).has("name", Contains.IN, strings).vertices();
assertEquals(2, ((IterableWithTotalHits) results).getTotalHits());
assertVertexIdsAnyOrder(results, "v1", "v3");
}
@Test
public void testGraphQuerySort() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.defineProperty("name").dataType(String.class).sortable(true).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "tom", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.setProperty("name", "tom", VISIBILITY_A)
.setProperty("age", 35, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "label2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", "v1", "v2", "label1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", "v1", "v2", "label3", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("age", SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v3", "v4", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("age", SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v4", "v3", "v2", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
assertEquals("v2", vertices.get(0).getId());
assertEquals("v1", vertices.get(1).getId());
assertTrue(vertices.get(2).getId().equals("v3") || vertices.get(2).getId().equals("v4"));
assertTrue(vertices.get(3).getId().equals("v3") || vertices.get(3).getId().equals("v4"));
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.DESCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
assertTrue(vertices.get(0).getId().equals("v3") || vertices.get(0).getId().equals("v4"));
assertTrue(vertices.get(1).getId().equals("v3") || vertices.get(1).getId().equals("v4"));
assertEquals("v1", vertices.get(2).getId());
assertEquals("v2", vertices.get(3).getId());
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.sort("age", SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v1", "v3", "v4");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.sort("age", SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v1", "v4", "v3");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Element.ID_PROPERTY_NAME, SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v1", "v2", "v3", "v4");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Element.ID_PROPERTY_NAME, SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v4", "v3", "v2", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("otherfield", SortDirection.ASCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
List<Edge> edges = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Edge.LABEL_PROPERTY_NAME, SortDirection.ASCENDING)
.edges());
assertEdgeIds(edges, new String[]{"e2", "e1", "e3"});
edges = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Edge.LABEL_PROPERTY_NAME, SortDirection.DESCENDING)
.edges());
assertEdgeIds(edges, new String[]{"e3", "e1", "e2"});
}
@Test
public void testGraphQuerySortOnPropertyThatHasNoValuesInTheIndex() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
QueryResultsIterable<Vertex> vertices
= graph.query(AUTHORIZATIONS_A).sort("age", SortDirection.ASCENDING).vertices();
Assert.assertEquals(2, count(vertices));
}
@Test
public void testGraphQuerySortOnPropertyWhichIsFullTextAndExactMatchIndexed() {
graph.defineProperty("name")
.dataType(String.class)
.sortable(true)
.textIndexHint(TextIndexHint.EXACT_MATCH, TextIndexHint.FULL_TEXT)
.define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "1-2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "1-1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "3-1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
QueryResultsIterable<Vertex> vertices
= graph.query(AUTHORIZATIONS_A_AND_B).sort("name", SortDirection.ASCENDING).vertices();
assertVertexIds(vertices, "v2", "v1", "v3");
vertices = graph.query("3", AUTHORIZATIONS_A_AND_B).vertices();
assertVertexIds(vertices, "v3");
vertices = graph.query("*", AUTHORIZATIONS_A_AND_B)
.has("name", Compare.EQUAL, "3-1")
.vertices();
assertVertexIds(vertices, "v3");
}
@Test
public void testGraphQueryVertexHasWithSecurity() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(1, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = graph.query(AUTHORIZATIONS_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices)); // need auth A to see the v2 node itself
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(0, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(2, count(vertices));
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
}
}
@Test
public void testGraphQueryVertexHasWithSecurityGranularity() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("description", "v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("description", "v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.vertices();
boolean hasAgeVisA = false;
boolean hasAgeVisB = false;
for (Vertex v : vertices) {
Property prop = v.getProperty("age");
if (prop == null) {
continue;
}
if ((Integer) prop.getValue() == 25) {
if (prop.getVisibility().equals(VISIBILITY_A)) {
hasAgeVisA = true;
} else if (prop.getVisibility().equals(VISIBILITY_B)) {
hasAgeVisB = true;
}
}
}
assertEquals(2, count(vertices));
assertTrue("has a", hasAgeVisA);
assertFalse("has b", hasAgeVisB);
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityComplexFormula() {
graph.prepareVertex("v1", VISIBILITY_MIXED_CASE_a)
.setProperty("age", 25, VISIBILITY_MIXED_CASE_a)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_MIXED_CASE_a_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGetVertexWithBadAuthorizations() {
graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.flush();
try {
graph.getVertex("v1", AUTHORIZATIONS_BAD);
throw new RuntimeException("Should throw " + SecurityVertexiumException.class.getSimpleName());
} catch (SecurityVertexiumException ex) {
// ok
}
}
@Test
public void testGraphQueryVertexNoVisibility() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("text", "hello", VISIBILITY_EMPTY)
.setProperty("age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query("hello", AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("hello", AUTHORIZATIONS_A_AND_B)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexWithVisibilityChange() {
graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
// change to same visibility
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1 = v1.prepareMutation()
.alterElementVisibility(VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(VISIBILITY_EMPTY, v1.getVisibility());
vertices = graph.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeVertex() {
graph.prepareVertex("v1", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeProperty() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryEdgeHasWithSecurity() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.edges();
Assert.assertEquals(1, count(edges));
}
@Test
public void testGraphQueryUpdateVertex() throws NoSuchFieldException, IllegalAccessException {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.addEdge("v2tov3", v2, v3, "", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.setProperty("name", "Bob", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.setProperty("name", "Same", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> allVertices = toList(graph.query(AUTHORIZATIONS_A_AND_B).vertices());
Assert.assertEquals(3, count(allVertices));
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("name", Compare.EQUAL, "Joe")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.has("name", Compare.EQUAL, "Joe")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testQueryWithVertexIds() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("age", 35, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<Vertex> vertices = toList(graph.query(new String[]{"v1", "v2"}, AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 27)
.vertices());
Assert.assertEquals(1, vertices.size());
assertEquals("v2", vertices.get(0).getId());
vertices = toList(graph.query(new String[]{"v1", "v2", "v3"}, AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 27)
.vertices());
Assert.assertEquals(2, vertices.size());
List<String> vertexIds = toList(new ConvertingIterable<Vertex, String>(vertices) {
@Override
protected String convert(Vertex o) {
return o.getId();
}
});
Assert.assertTrue("v2 not found", vertexIds.contains("v2"));
Assert.assertTrue("v3 not found", vertexIds.contains("v3"));
}
@Test
public void testDisableEdgeIndexing() throws NoSuchFieldException, IllegalAccessException {
assumeTrue("disabling indexing not supported", disableEdgeIndexing(graph));
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("prop1", "value1")
.edges();
Assert.assertEquals(0, count(edges));
}
@Test
public void testGraphQueryHasWithSpaces() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithNonAlphaCharacters", "hyphen-word, etc.", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query("Ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("joe", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(2, count(vertices));
if (isLuceneQueriesSupported()) {
vertices = graph.query("joe AND ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
if (isLuceneQueriesSupported()) {
vertices = graph.query("joe smith", AUTHORIZATIONS_A)
.vertices();
List<Vertex> verticesList = toList(vertices);
assertEquals(2, verticesList.size());
boolean foundV1 = false;
boolean foundV2 = false;
for (Vertex v : verticesList) {
if (v.getId().equals("v1")) {
foundV1 = true;
} else if (v.getId().equals("v2")) {
foundV2 = true;
} else {
throw new RuntimeException("Invalid vertex id: " + v.getId());
}
}
assertTrue(foundV1);
assertTrue(foundV2);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe")
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("propWithNonAlphaCharacters", TextPredicate.CONTAINS, "hyphen-word, etc.")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryWithANDOperatorAndWithExactMatchFields() {
graph.defineProperty("firstName").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("firstName", "Joe", VISIBILITY_A)
.setProperty("lastName", "Ferner", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("firstName", "Joe", VISIBILITY_A)
.setProperty("lastName", "Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assumeTrue("lucene and queries not supported", isLuceneQueriesSupported() && isLuceneAndQueriesSupported());
Iterable<Vertex> vertices = graph.query("Joe AND ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryHasWithSpacesAndFieldedQueryString() {
assumeTrue("fielded query not supported", isFieldNamesInQuerySupported());
graph.defineProperty("http://vertexium.org#name").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("http://vertexium.org#name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("http://vertexium.org#name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assumeTrue("lucene queries", isLuceneQueriesSupported());
Iterable<Vertex> vertices = graph.query("http\\:\\/\\/vertexium.org#name:Joe", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query("http\\:\\/\\/vertexium.org#name:\"Joe Ferner\"", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
protected boolean isFieldNamesInQuerySupported() {
return true;
}
protected boolean isLuceneQueriesSupported() {
return !(graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery);
}
protected boolean isLuceneAndQueriesSupported() {
return !(graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery);
}
@Test
public void testStoreGeoPoint() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9544, -77.3464, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 1))
.vertices());
Assert.assertEquals(1, count(vertices));
GeoPoint geoPoint = (GeoPoint) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoPoint.getLatitude(), 0.001);
assertEquals(-77.2297, geoPoint.getLongitude(), 0.001);
assertEquals("Reston, VA", geoPoint.getDescription());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 25))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoRect(new GeoPoint(39, -78), new GeoPoint(38, -77)))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoHash(38.9186, -77.2297, 2))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoHash(38.9186, -77.2297, 3))
.vertices());
Assert.assertEquals(1, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", TextPredicate.CONTAINS, "Reston")
.vertices());
Assert.assertEquals(2, count(vertices));
}
@Test
public void testStoreGeoCircle() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("location", new GeoCircle(38.9186, -77.2297, 100, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.92, -77.23, 10))
.vertices());
Assert.assertEquals(1, count(vertices));
GeoCircle geoCircle = (GeoCircle) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoCircle.getLatitude(), 0.001);
assertEquals(-77.2297, geoCircle.getLongitude(), 0.001);
assertEquals(100.0, geoCircle.getRadius(), 0.001);
assertEquals("Reston, VA", geoCircle.getDescription());
}
private Date createDate(int year, int month, int day) {
return new GregorianCalendar(year, month, day).getTime();
}
private Date createDate(int year, int month, int day, int hour, int min, int sec) {
return new GregorianCalendar(year, month, day, hour, min, sec).getTime();
}
@Test
public void testGraphQueryRange() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 20, 29)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 30)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, true, 30, false)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, toList(vertices).get(0).getPropertyValue("age"));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, false, 30, true)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, toList(vertices).get(0).getPropertyValue("age"));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, true, 30, true)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, false, 30, false)
.vertices();
Assert.assertEquals(0, count(vertices));
}
@Test
public void testVertexQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("prop1", "value1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
v2.setProperty("prop1", "value2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
v3.setProperty("prop1", "value3", VISIBILITY_A, AUTHORIZATIONS_ALL);
Edge ev1v2 = graph.prepareEdge("e v1->v2", v1, v2, "edgeA", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Edge ev1v3 = graph.prepareEdge("e v1->v3", v1, v3, "edgeB", VISIBILITY_A)
.setProperty("prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e v2->v3", v2, v3, "edgeB", VISIBILITY_A)
.setProperty("prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Iterable<Vertex> vertices = v1.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(2, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
org.vertexium.test.util.IterableUtils.assertContains(v3, vertices);
if (isIterableWithTotalHitsSupported(vertices)) {
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
vertices = v1.query(AUTHORIZATIONS_A).limit(1).vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = v1.query(AUTHORIZATIONS_A)
.has("prop1", "value2")
.vertices();
Assert.assertEquals(1, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
Iterable<Edge> edges = v1.query(AUTHORIZATIONS_A).edges();
Assert.assertEquals(2, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edges();
Assert.assertEquals(2, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edges();
Assert.assertEquals(1, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
vertices = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").vertices();
Assert.assertEquals(1, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.OUT).vertices(), "v2", "v3");
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.IN).vertices());
assertEdgeIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.OUT).edges(), "e v1->v2", "e v1->v3");
assertEdgeIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.IN).edges());
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasOtherVertexId("v2").vertices(), "v2");
assertEdgeIds(v1.query(AUTHORIZATIONS_A).hasOtherVertexId("v2").edges(), "e v1->v2");
}
@Test
public void testFindPaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v6 = graph.addVertex("v6", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v2
graph.addEdge(v2, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v3, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v5
graph.addEdge(v4, v6, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v6
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2), AUTHORIZATIONS_A));
List<Path> pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
List<Path> pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2", "v4"),
new Path("v1", "v3", "v4")
);
paths = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v4", "v2", "v1"),
new Path("v4", "v3", "v1")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2", "v4", "v6"),
new Path("v1", "v3", "v4", "v6")
);
}
@Test
public void testFindPathExcludeLabels() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v4, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "b", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v3, v4, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 2), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4"),
new Path("v1", "v3", "v4")
);
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 2).setExcludedLabels("b"), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4")
);
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 3).setExcludedLabels("b"), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4")
);
}
private void assertPaths(Iterable<Path> found, Path... expected) {
List<Path> foundPaths = toList(found);
List<Path> expectedPaths = new ArrayList<>();
Collections.addAll(expectedPaths, expected);
assertEquals(expectedPaths.size(), foundPaths.size());
for (Path foundPath : foundPaths) {
if (!expectedPaths.remove(foundPath)) {
fail("Unexpected path: " + foundPath);
}
}
}
@Test
public void testFindPathsWithSoftDeletedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A); // v1 -> v2
Edge v2ToV3 = graph.addEdge(v2, v3, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A); // v2 -> v3
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v2", "v3")
);
graph.softDeleteEdge(v2ToV3, AUTHORIZATIONS_A);
graph.flush();
assertNull(graph.getEdge(v2ToV3.getId(), AUTHORIZATIONS_A));
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
}
@Test
public void testFindPathsWithHiddenEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.addVertex("v3", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B); // v1 -> v2
Edge v2ToV3 = graph.addEdge(v2, v3, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B); // v2 -> v3
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B));
assertPaths(
paths,
new Path("v1", "v2", "v3")
);
graph.markEdgeHidden(v2ToV3, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
assertNull(graph.getEdge(v2ToV3.getId(), AUTHORIZATIONS_A_AND_B));
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_B));
assertEquals(1, paths.size());
}
@Test
public void testFindPathsMultiplePaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2"),
new Path("v1", "v3", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 3), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2"),
new Path("v1", "v3", "v2"),
new Path("v1", "v3", "v4", "v2"),
new Path("v1", "v4", "v3", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 2), AUTHORIZATIONS_A));
assertPaths(paths);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 3), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2", "v5"),
new Path("v1", "v3", "v2", "v5")
);
}
@Test
public void testHasPath() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2, true), AUTHORIZATIONS_A));
assertEquals(1, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 3, true), AUTHORIZATIONS_A));
assertEquals(1, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 2, true), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
}
@Test
public void testGetVerticesFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v1.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v3.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v3.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v3.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v4.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v4.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v4.getVertices(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testGetVertexIdsFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v1.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v2.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v3.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v3.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v4.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v4.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v4.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testBlankVisibilityString() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_EMPTY, v.getVisibility());
}
@Test
public void testElementMutationDoesntChangeObjectUntilSave() throws InterruptedException {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
v.setProperty("prop1", "value1-1", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
ElementMutation<Vertex> m = v.prepareMutation()
.setProperty("prop1", "value1-2", VISIBILITY_A)
.setProperty("prop2", "value2-2", VISIBILITY_A);
Assert.assertEquals(1, count(v.getProperties()));
assertEquals("value1-1", v.getPropertyValue("prop1"));
v = m.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties()));
assertEquals("value1-2", v.getPropertyValue("prop1"));
assertEquals("value2-2", v.getPropertyValue("prop2"));
}
@Test
public void testFindRelatedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIds(vertexIds, AUTHORIZATIONS_A));
Assert.assertEquals(4, count(edgeIds));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev2v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev3v1.getId(), edgeIds);
}
@Test
public void testFindRelatedEdgeIdsForVertices() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
List<Vertex> vertices = new ArrayList<>();
vertices.add(v1);
vertices.add(v2);
vertices.add(v3);
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIdsForVertices(vertices, AUTHORIZATIONS_A));
Assert.assertEquals(4, count(edgeIds));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev2v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev3v1.getId(), edgeIds);
}
@Test
public void testFindRelatedEdgeSummary() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v1->v3", v1, v3, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v2->v3", v2, v3, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v1", v3, v1, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(4, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v3", "label1", v1.getId(), v3.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v2->v3", "label2", v2.getId(), v3.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v3->v1", "label2", v3.getId(), v1.getId()), relatedEdges);
}
@Test
public void testFindRelatedEdgeSummaryAfterSoftDelete() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(1, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
graph.softDeleteEdge(e1, AUTHORIZATIONS_A);
graph.flush();
relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(0, relatedEdges.size());
}
@Test
public void testFindRelatedEdgeSummaryAfterMarkedHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(1, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
graph.markEdgeHidden(e1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(0, relatedEdges.size());
}
// Test for performance
//@Test
@SuppressWarnings("unused")
private void testFindRelatedEdgesPerformance() {
int totalNumberOfVertices = 100;
int totalNumberOfEdges = 10000;
int totalVerticesToCheck = 100;
Date startTime, endTime;
Random random = new Random(100);
startTime = new Date();
List<Vertex> vertices = new ArrayList<>();
for (int i = 0; i < totalNumberOfVertices; i++) {
vertices.add(graph.addVertex("v" + i, VISIBILITY_A, AUTHORIZATIONS_A));
}
graph.flush();
endTime = new Date();
long insertVerticesTime = endTime.getTime() - startTime.getTime();
startTime = new Date();
for (int i = 0; i < totalNumberOfEdges; i++) {
Vertex outVertex = vertices.get(random.nextInt(vertices.size()));
Vertex inVertex = vertices.get(random.nextInt(vertices.size()));
graph.addEdge("e" + i, outVertex, inVertex, "", VISIBILITY_A, AUTHORIZATIONS_A);
}
graph.flush();
endTime = new Date();
long insertEdgesTime = endTime.getTime() - startTime.getTime();
List<String> vertexIds = new ArrayList<>();
for (int i = 0; i < totalVerticesToCheck; i++) {
Vertex v = vertices.get(random.nextInt(vertices.size()));
vertexIds.add(v.getId());
}
startTime = new Date();
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIds(vertexIds, AUTHORIZATIONS_A));
count(edgeIds);
endTime = new Date();
long findRelatedEdgesTime = endTime.getTime() - startTime.getTime();
LOGGER.info(
"RESULTS\ntotalNumberOfVertices,totalNumberOfEdges,totalVerticesToCheck,insertVerticesTime,insertEdgesTime,findRelatedEdgesTime\n%d,%d,%d,%d,%d,%d",
totalNumberOfVertices,
totalNumberOfEdges,
totalVerticesToCheck,
insertVerticesTime,
insertEdgesTime,
findRelatedEdgesTime
);
}
@Test
public void testFilterEdgeIdsByAuthorization() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
graph.prepareEdge("e1", v1, v2, "label", VISIBILITY_A)
.setProperty("propA", "propA", VISIBILITY_A)
.setProperty("propB", "propB", VISIBILITY_A_AND_B)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
List<String> edgeIds = new ArrayList<>();
edgeIds.add("e1");
List<String> foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_B_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_B_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
}
@Test
public void testFilterVertexIdsByAuthorization() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propA", "propA", VISIBILITY_A)
.setProperty("propB", "propB", VISIBILITY_A_AND_B)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
List<String> foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_B_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_B_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
}
@Test
public void testMetadataMutationsOnVertex() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
Vertex vertex = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
ExistingElementMutation<Vertex> m = vertex.prepareMutation();
m.setPropertyMetadata("propBmeta", "meta1", "meta2", VISIBILITY_A);
vertex = m.save(AUTHORIZATIONS_ALL);
assertEquals("meta2", vertex.getProperty("propBmeta").getMetadata().getEntry("meta1").getValue());
}
@Test
public void testMetadataMutationsOnEdge() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
Edge edge = graph.prepareEdge("v1", "v2", "label", VISIBILITY_A)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
ExistingElementMutation<Edge> m = edge.prepareMutation();
m.setPropertyMetadata("propBmeta", "meta1", "meta2", VISIBILITY_A);
edge = m.save(AUTHORIZATIONS_ALL);
assertEquals("meta2", edge.getProperty("propBmeta").getMetadata().getEntry("meta1").getValue());
}
@Test
public void testEmptyPropertyMutation() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.prepareMutation().save(AUTHORIZATIONS_ALL);
}
@Test
public void testTextIndex() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define(); // try calling define twice
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("none", "Test Value", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.setProperty("fullText", "Test Value", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("Test Value", v1.getPropertyValue("none"));
assertEquals("Test Value", v1.getPropertyValue("both"));
assertEquals("Test Value", v1.getPropertyValue("fullText"));
assertEquals("Test Value", v1.getPropertyValue("exactMatch"));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals("exact match shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", "Test Value").vertices()));
Assert.assertEquals("default has predicate is equals which shouldn't work for full text", 0, count(graph.query(AUTHORIZATIONS_A).has("fullText", "Test Value").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test Value").vertices()));
if (count(graph.query(AUTHORIZATIONS_A).has("none", "Test Value").vertices()) != 0) {
LOGGER.warn("default has predicate is equals which shouldn't work for un-indexed");
}
}
@Test
public void testTextIndexDoesNotContain() throws Exception {
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("both", "Temp", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("both", TextPredicate.DOES_NOT_CONTAIN, "Test")
.vertices();
Assert.assertEquals(3, count(vertices));
vertices.forEach(v -> Arrays.asList("v1", "v3", "v4").contains(v.getId()));
vertices = graph.query(AUTHORIZATIONS_A)
.has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test")
.vertices();
Assert.assertEquals(3, count(vertices));
vertices.forEach(v -> Arrays.asList("v2", "v3", "v4").contains(v.getId()));
vertices = graph.query(AUTHORIZATIONS_A)
.has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test Value")
.vertices();
Assert.assertEquals(3, count(vertices));
vertices.forEach(v -> Arrays.asList("v2", "v3", "v4").contains(v.getId()));
}
@Test
public void testTextIndexStreamingPropertyValue() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("none", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.setProperty("both", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.setProperty("fullText", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", TextPredicate.CONTAINS, "Test").vertices()));
}
@Test
public void testGetStreamingPropertyValueInputStreams() throws Exception {
graph.defineProperty("a").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("b").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("c").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("a", StreamingPropertyValue.create("Test Value A"), VISIBILITY_A)
.setProperty("b", StreamingPropertyValue.create("Test Value B"), VISIBILITY_A)
.setProperty("c", StreamingPropertyValue.create("Test Value C"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
StreamingPropertyValue spvA = (StreamingPropertyValue) v1.getPropertyValue("a");
StreamingPropertyValue spvB = (StreamingPropertyValue) v1.getPropertyValue("b");
StreamingPropertyValue spvC = (StreamingPropertyValue) v1.getPropertyValue("c");
ArrayList<StreamingPropertyValue> spvs = Lists.newArrayList(spvA, spvB, spvC);
List<InputStream> streams = graph.getStreamingPropertyValueInputStreams(spvs);
assertEquals("Test Value A", IOUtils.toString(streams.get(0)));
assertEquals("Test Value B", IOUtils.toString(streams.get(1)));
assertEquals("Test Value C", IOUtils.toString(streams.get(2)));
}
@Test
public void testFieldBoost() throws Exception {
assumeTrue("Boost not supported", graph.isFieldBoostSupported());
graph.defineProperty("a")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(1)
.define();
graph.defineProperty("b")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(2)
.define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("a", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("b", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assertVertexIds(graph.query("Test", AUTHORIZATIONS_A).vertices(), "v2", "v1");
}
@Test
public void testValueTypes() throws Exception {
Date date = createDate(2014, 2, 24, 13, 0, 5);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("int", 5, VISIBILITY_A)
.setProperty("bigInteger", BigInteger.valueOf(10), VISIBILITY_A)
.setProperty("bigDecimal", BigDecimal.valueOf(1.1), VISIBILITY_A)
.setProperty("double", 5.6, VISIBILITY_A)
.setProperty("float", 6.4f, VISIBILITY_A)
.setProperty("string", "test", VISIBILITY_A)
.setProperty("byte", (byte) 5, VISIBILITY_A)
.setProperty("long", (long) 5, VISIBILITY_A)
.setProperty("boolean", true, VISIBILITY_A)
.setProperty("geopoint", new GeoPoint(77, -33), VISIBILITY_A)
.setProperty("short", (short) 5, VISIBILITY_A)
.setProperty("date", date, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("int", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("double", 5.6).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).range("float", 6.3f, 6.5f).vertices())); // can't search for 6.4f her because of float precision
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("string", "test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("byte", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("long", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("short", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("date", date).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigInteger", BigInteger.valueOf(10)).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigInteger", 10).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", BigDecimal.valueOf(1.1)).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", 1.1).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("geopoint", GeoCompare.WITHIN, new GeoCircle(77, -33, 1)).vertices()));
}
@Test
public void testChangeVisibilityVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
// change to same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
}
@Test
public void testChangeVertexVisibilityAndAlterPropertyVisibilityAndChangePropertyAtTheSameTime() {
Metadata metadata = new Metadata();
metadata.add("m1", "m1-value1", VISIBILITY_EMPTY);
metadata.add("m2", "m2-value1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.createAuthorizations(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_ALL);
ExistingElementMutation<Vertex> m = v1.prepareMutation();
m.alterElementVisibility(VISIBILITY_B);
for (Property property : v1.getProperties()) {
m.alterPropertyVisibility(property, VISIBILITY_B);
m.setPropertyMetadata(property, "m1", "m1-value2", VISIBILITY_EMPTY);
}
m.save(AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_B);
assertEquals(VISIBILITY_B, v1.getVisibility());
List<Property> properties = toList(v1.getProperties());
assertEquals(1, properties.size());
assertEquals("age", properties.get(0).getName());
assertEquals(VISIBILITY_B, properties.get(0).getVisibility());
assertEquals(2, properties.get(0).getMetadata().entrySet().size());
assertTrue(properties.get(0).getMetadata().containsKey("m1"));
assertEquals("m1-value2", properties.get(0).getMetadata().getEntry("m1").getValue());
assertEquals(VISIBILITY_EMPTY, properties.get(0).getMetadata().getEntry("m1").getVisibility());
assertTrue(properties.get(0).getMetadata().containsKey("m2"));
assertEquals("m2-value1", properties.get(0).getMetadata().getEntry("m2").getValue());
assertEquals(VISIBILITY_EMPTY, properties.get(0).getMetadata().getEntry("m2").getVisibility());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull("v1 should not be returned for auth a", v1);
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_B)
.has("age", Compare.EQUAL, 25)
.vertices());
assertEquals(1, vertices.size());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices());
assertEquals(0, vertices.size());
}
@Test
public void testChangeVisibilityPropertiesWithPropertyKey() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("k1", "prop1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop1", "value1").vertices()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop1", "value1").vertices()));
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value1"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value1"));
}
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Property v1Prop1 = v1.getProperty("prop1");
assertNotNull(v1Prop1);
assertEquals(VISIBILITY_B, v1Prop1.getVisibility());
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_EMPTY)
.addPropertyValue("k2", "prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
e1.prepareMutation()
.alterPropertyVisibility("k2", "prop2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNull(e1.getProperty("prop2"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop2", "value2").edges()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop2", "value2").edges()));
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop2", ElementType.EDGE, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value2"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop2", ElementType.EDGE, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value2"));
}
e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Property e1prop1 = e1.getProperty("prop2");
assertNotNull(e1prop1);
assertEquals(VISIBILITY_B, e1prop1.getVisibility());
}
@Test
public void testChangeVisibilityVertexProperties() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "value1", VISIBILITY_EMPTY);
Metadata prop2Metadata = new Metadata();
prop2Metadata.add("prop2_key1", "value1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.setProperty("prop2", "value2", prop2Metadata, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop1", "value1").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop1", "value1").vertices()));
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value1"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value1"));
}
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property v1Prop1 = v1.getProperty("prop1");
assertNotNull(v1Prop1);
Assert.assertEquals(1, toList(v1Prop1.getMetadata().entrySet()).size());
assertEquals("value1", v1Prop1.getMetadata().getValue("prop1_key1"));
assertNotNull(v1.getProperty("prop2"));
// alter and set property in one mutation
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New", v1.getPropertyValue("prop1"));
// alter visibility to the same visibility
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New2", v1.getPropertyValue("prop1"));
}
@Test
public void testAlterVisibilityAndSetMetadataInOneMutation() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "metadata1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.setPropertyMetadata("prop1", "prop1_key1", "metadata1New", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals(VISIBILITY_B, v1.getProperty("prop1").getVisibility());
assertEquals("metadata1New", v1.getProperty("prop1").getMetadata().getValue("prop1_key1"));
List<HistoricalPropertyValue> historicalPropertyValues = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
assertEquals(2, historicalPropertyValues.size());
assertEquals("metadata1New", historicalPropertyValues.get(0).getMetadata().getValue("prop1_key1"));
assertEquals("metadata1", historicalPropertyValues.get(1).getMetadata().getValue("prop1_key1"));
}
@Test
public void testAlterPropertyVisibilityOverwritingProperty() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "prop1", "value1", VISIBILITY_EMPTY)
.addPropertyValue("", "prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
long beforeAlterTimestamp = IncreasingTime.currentTimeMillis();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyVisibility(v1.getProperty("", "prop1", VISIBILITY_A), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v1.getProperties()));
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_EMPTY));
assertEquals("value2", v1.getProperty("", "prop1", VISIBILITY_EMPTY).getValue());
assertNull(v1.getProperty("", "prop1", VISIBILITY_A));
v1 = graph.getVertex("v1", graph.getDefaultFetchHints(), beforeAlterTimestamp, AUTHORIZATIONS_A);
assertEquals(2, count(v1.getProperties()));
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_EMPTY));
assertEquals("value1", v1.getProperty("", "prop1", VISIBILITY_EMPTY).getValue());
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_A));
assertEquals("value2", v1.getProperty("", "prop1", VISIBILITY_A).getValue());
}
@Test
public void testChangeVisibilityEdge() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// test that we can see the edge with A and not B
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge visibility to same
e1 = graph.getEdge("e1", AUTHORIZATIONS_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testChangeVisibilityOnBadPropertyName() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_EMPTY)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
try {
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propBad", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
fail("show throw");
} catch (VertexiumException ex) {
assertNotNull(ex);
}
}
@Test
public void testChangeVisibilityOnStreamingProperty() throws IOException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@#$%^&*()[]{}|";
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propSmall", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility(largePropertyName, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
Assert.assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
}
@Test
public void testChangePropertyMetadata() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "valueOld", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", null, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.setPropertyMetadata("prop1", "prop1_key1", "valueNew", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().getEntry("prop1_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().getEntry("prop1_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.setPropertyMetadata("prop2", "prop2_key1", "valueNew", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().getEntry("prop2_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().getEntry("prop2_key1", VISIBILITY_EMPTY).getValue());
}
@Test
public void testMutationChangePropertyVisibilityFollowedByMetadataUsingPropertyObject() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "valueOld", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property p1 = v1.getProperty("prop1", VISIBILITY_A);
v1.prepareMutation()
.alterPropertyVisibility(p1, VISIBILITY_B)
.setPropertyMetadata(p1, "prop1_key1", "valueNew", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
assertEquals("valueNew", v1.getProperty("prop1", VISIBILITY_B).getMetadata().getEntry("prop1_key1", VISIBILITY_B).getValue());
}
@Test
public void testMetadata() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
ExistingElementMutation<Vertex> m = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B).prepareMutation();
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_A), "metadata1", "metadata-value1aa", VISIBILITY_A);
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_A), "metadata1", "metadata-value1ab", VISIBILITY_B);
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_B), "metadata1", "metadata-value1bb", VISIBILITY_B);
m.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property prop1A = v1.getProperty("prop1", VISIBILITY_A);
assertEquals(2, prop1A.getMetadata().entrySet().size());
assertEquals("metadata-value1aa", prop1A.getMetadata().getValue("metadata1", VISIBILITY_A));
assertEquals("metadata-value1ab", prop1A.getMetadata().getValue("metadata1", VISIBILITY_B));
Property prop1B = v1.getProperty("prop1", VISIBILITY_B);
assertEquals(1, prop1B.getMetadata().entrySet().size());
assertEquals("metadata-value1bb", prop1B.getMetadata().getValue("metadata1", VISIBILITY_B));
}
@Test
public void testIsVisibilityValid() {
assertFalse(graph.isVisibilityValid(VISIBILITY_A, AUTHORIZATIONS_C));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_A_AND_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_EMPTY, AUTHORIZATIONS_A));
}
@Test
public void testModifyVertexWithLowerAuthorizationThenOtherProperties() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1New", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, "v1");
}
@Test
public void testPartialUpdateOfVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, "v1");
}
@Test
public void testPartialUpdateOfVertexPropertyKey() {
// see https://github.com/visallo/vertexium/issues/141
assumeTrue("Known bug in partial updates", isParitalUpdateOfVertexPropertyKeySupported());
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop", "value1", VISIBILITY_A)
.addPropertyValue("key2", "prop", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value2")
.vertices();
assertVertexIds(vertices, "v1");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1New")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value2")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1")
.vertices();
assertVertexIds(vertices);
}
protected boolean isParitalUpdateOfVertexPropertyKeySupported() {
return true;
}
@Test
public void testAddVertexWithoutIndexing() {
assumeTrue("add vertex without indexing not supported", !isDefaultSearchIndex());
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop1", "value1")
.vertices();
assertVertexIds(vertices);
}
@Test
public void testAlterVertexWithoutIndexing() {
assumeTrue("alter vertex without indexing not supported", !isDefaultSearchIndex());
graph.prepareVertex("v1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("prop1", "value1")
.vertices();
assertVertexIds(vertices);
}
@Test
public void testAddEdgeWithoutIndexing() {
assumeTrue("add edge without indexing not supported", !isDefaultSearchIndex());
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop1", "value1")
.edges();
assertEdgeIds(edges, new String[]{});
}
@Test
public void testIteratorWithLessThanPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(3), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(3, count);
assertNotNull("v was null", v);
assertEquals("2", v.getId());
}
@Test
public void testIteratorWithPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(5), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("4", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(7), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("4", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageTwo() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(5);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(12), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("9", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageThree() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(10);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(12), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(2, count);
assertNotNull("v was null", v);
assertEquals("11", v.getId());
}
@Test
public void testGraphMetadata() {
List<GraphMetadataEntry> existingMetadata = toList(graph.getMetadata());
graph.setMetadata("test1", "value1old");
graph.setMetadata("test1", "value1");
graph.setMetadata("test2", "value2");
assertEquals("value1", graph.getMetadata("test1"));
assertEquals("value2", graph.getMetadata("test2"));
assertEquals(null, graph.getMetadata("missingProp"));
List<GraphMetadataEntry> newMetadata = toList(graph.getMetadata());
assertEquals(existingMetadata.size() + 2, newMetadata.size());
}
@Test
public void testSimilarityByText() {
assumeTrue("query similar", graph.isQuerySimilarToTextSupported());
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb, His fleece was white as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("text", "Mary had a little tiger, His fleece was white as snow.", VISIBILITY_B)
.save(AUTHORIZATIONS_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_A)
.setProperty("text", "His fleece was white as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v5", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb, His fleece was black as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v5", VISIBILITY_A)
.setProperty("text", "Jack and Jill went up the hill to fetch a pail of water.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<Vertex> vertices = toList(
graph.querySimilarTo(new String[]{"text"}, "Mary had a little lamb, His fleece was white as snow", AUTHORIZATIONS_A_AND_B)
.minTermFrequency(1)
.maxQueryTerms(25)
.minDocFrequency(1)
.maxDocFrequency(10)
.boost(2.0f)
.vertices()
);
assertTrue(vertices.size() > 0);
vertices = toList(
graph.querySimilarTo(new String[]{"text"}, "Mary had a little lamb, His fleece was white as snow", AUTHORIZATIONS_A)
.minTermFrequency(1)
.maxQueryTerms(25)
.minDocFrequency(1)
.maxDocFrequency(10)
.boost(2.0f)
.vertices()
);
assertTrue(vertices.size() > 0);
}
@Test
public void testAllPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
metadata.add("author", "author1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.addPropertyValue("k1", "name", "k1Time25Value", metadata, time25.getTime(), VISIBILITY_A)
.addPropertyValue("k2", "name", "k2Time25Value", metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
metadata = new Metadata();
metadata.add("author", "author2", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.addPropertyValue("k1", "name", "k1Time30Value", metadata, time30.getTime(), VISIBILITY_A)
.addPropertyValue("k2", "name", "k2Time30Value", metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A));
assertEquals(6, values.size());
for (int i = 0; i < 3; i++) {
HistoricalPropertyValue item = values.get(i);
assertEquals(time30, new Date(values.get(i).getTimestamp()));
if (item.getPropertyName().equals("age")) {
assertEquals(30, item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k1")) {
assertEquals("k1Time30Value", item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k2")) {
assertEquals("k2Time30Value", item.getValue());
} else {
fail("Invalid " + item);
}
}
for (int i = 3; i < 6; i++) {
HistoricalPropertyValue item = values.get(i);
assertEquals(time25, new Date(values.get(i).getTimestamp()));
if (item.getPropertyName().equals("age")) {
assertEquals(25, item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k1")) {
assertEquals("k1Time25Value", item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k2")) {
assertEquals("k2Time25Value", item.getValue());
} else {
fail("Invalid " + item);
}
}
}
@Test
public void testPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
metadata.add("author", "author1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
metadata = new Metadata();
metadata.add("author", "author2", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues("", "age", VISIBILITY_A, AUTHORIZATIONS_A));
assertEquals(2, values.size());
assertEquals(30, values.get(0).getValue());
assertEquals(time30, new Date(values.get(0).getTimestamp()));
assertEquals("author2", values.get(0).getMetadata().getValue("author", VISIBILITY_A));
assertEquals(25, values.get(1).getValue());
assertEquals(time25, new Date(values.get(1).getTimestamp()));
assertEquals("author1", values.get(1).getMetadata().getValue("author", VISIBILITY_A));
// make sure we get the correct age when we only ask for one value
assertEquals(30, v1.getPropertyValue("", "age"));
assertEquals("author2", v1.getProperty("", "age").getMetadata().getValue("author", VISIBILITY_A));
}
@Test
public void testStreamingPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
StreamingPropertyValue value1 = StreamingPropertyValue.create("value1");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "text", value1, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
StreamingPropertyValue value2 = StreamingPropertyValue.create("value2");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "text", value2, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues("", "text", VISIBILITY_A, AUTHORIZATIONS_A));
assertEquals(2, values.size());
assertEquals("value2", ((StreamingPropertyValue) values.get(0).getValue()).readToString());
assertEquals(time30, new Date(values.get(0).getTimestamp()));
assertEquals("value1", ((StreamingPropertyValue) values.get(1).getValue()).readToString());
assertEquals(time25, new Date(values.get(1).getTimestamp()));
// make sure we get the correct age when we only ask for one value
assertEquals("value2", ((StreamingPropertyValue) v1.getPropertyValue("", "text")).readToString());
}
@Test
public void testGetVertexAtASpecificTimeInHistory() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
Vertex v1 = graph.prepareVertex("v1", time25.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", time25.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 20, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v1", time30.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", time30.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 35, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// verify current versions
assertEquals(30, graph.getVertex("v1", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(20, graph.getVertex("v2", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(35, graph.getVertex("v3", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
// verify old version
assertEquals(25, graph.getVertex("v1", graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertNull("v3 should not exist at time25", graph.getVertex("v3", graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A));
assertEquals("e1 should not exist", 0, count(graph.getEdges(graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A)));
}
@Test
public void testSaveMultipleTimestampedValuesInSameMutationVertex() {
String vertexId = "v1";
String propertyKey = "k1";
String propertyName = "p1";
Map<String, Long> values = ImmutableMap.of(
"value1", createDate(2016, 4, 6, 9, 20, 0).getTime(),
"value2", createDate(2016, 5, 6, 9, 20, 0).getTime(),
"value3", createDate(2016, 6, 6, 9, 20, 0).getTime(),
"value4", createDate(2016, 7, 6, 9, 20, 0).getTime(),
"value5", createDate(2016, 8, 6, 9, 20, 0).getTime()
);
ElementMutation<Vertex> vertexMutation = graph.prepareVertex(vertexId, VISIBILITY_EMPTY);
for (Map.Entry<String, Long> entry : values.entrySet()) {
vertexMutation.addPropertyValue(propertyKey, propertyName, entry.getKey(), new Metadata(), entry.getValue(), VISIBILITY_EMPTY);
}
vertexMutation.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex retrievedVertex = graph.getVertex(vertexId, AUTHORIZATIONS_EMPTY);
Iterable<HistoricalPropertyValue> historicalPropertyValues = retrievedVertex.getHistoricalPropertyValues(propertyKey, propertyName, VISIBILITY_EMPTY, null, null, AUTHORIZATIONS_EMPTY);
compareHistoricalValues(values, historicalPropertyValues);
}
@Test
public void testSaveMultipleTimestampedValuesInSameMutationEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
String edgeId = "e1";
String propertyKey = "k1";
String propertyName = "p1";
Map<String, Long> values = ImmutableMap.of(
"value1", createDate(2016, 4, 6, 9, 20, 0).getTime(),
"value2", createDate(2016, 5, 6, 9, 20, 0).getTime(),
"value3", createDate(2016, 6, 6, 9, 20, 0).getTime(),
"value4", createDate(2016, 7, 6, 9, 20, 0).getTime(),
"value5", createDate(2016, 8, 6, 9, 20, 0).getTime()
);
ElementMutation<Edge> edgeMutation = graph.prepareEdge(edgeId, v1, v2, "edgeLabel", VISIBILITY_EMPTY);
for (Map.Entry<String, Long> entry : values.entrySet()) {
edgeMutation.addPropertyValue(propertyKey, propertyName, entry.getKey(), new Metadata(), entry.getValue(), VISIBILITY_EMPTY);
}
edgeMutation.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Edge retrievedEdge = graph.getEdge(edgeId, AUTHORIZATIONS_EMPTY);
Iterable<HistoricalPropertyValue> historicalPropertyValues = retrievedEdge.getHistoricalPropertyValues(propertyKey, propertyName, VISIBILITY_EMPTY, null, null, AUTHORIZATIONS_EMPTY);
compareHistoricalValues(values, historicalPropertyValues);
}
private void compareHistoricalValues(Map<String, Long> expectedValues, Iterable<HistoricalPropertyValue> historicalPropertyValues) {
Map<String, Long> expectedValuesCopy = new HashMap<>(expectedValues);
for (HistoricalPropertyValue historicalPropertyValue : historicalPropertyValues) {
String value = (String) historicalPropertyValue.getValue();
if (!expectedValuesCopy.containsKey(value)) {
throw new VertexiumException("Expected historical values to contain: " + value);
}
long expectedValue = expectedValuesCopy.remove(value);
long ts = historicalPropertyValue.getTimestamp();
assertEquals(expectedValue, ts);
}
if (expectedValuesCopy.size() > 0) {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, Long> entry : expectedValuesCopy.entrySet()) {
result.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
}
throw new VertexiumException("Missing historical values:\n" + result.toString());
}
}
@Test
public void testTimestampsInExistingElementMutation() {
long t1 = createDate(2017, 1, 18, 9, 20, 0).getTime();
long t2 = createDate(2017, 1, 19, 9, 20, 0).getTime();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "prop1", "test1", new Metadata(), t1, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
assertEquals(t1, v1.getProperty("k1", "prop1").getTimestamp());
graph.getVertex("v1", AUTHORIZATIONS_ALL)
.prepareMutation()
.addPropertyValue("k1", "prop1", "test2", new Metadata(), t2, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
assertEquals(t2, v1.getProperty("k1", "prop1").getTimestamp());
List<HistoricalPropertyValue> historicalValues = toList(v1.getHistoricalPropertyValues("k1", "prop1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL));
assertEquals(2, historicalValues.size());
assertEquals(t1, historicalValues.get(1).getTimestamp());
assertEquals(t2, historicalValues.get(0).getTimestamp());
}
@Test
public void testGraphQueryWithTermsAggregation() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_B)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "label1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", "v1", "v2", "label1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", "v1", "v2", "label2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("name", ElementType.VERTEX, AUTHORIZATIONS_EMPTY);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joe"));
assertEquals(searchIndexFieldLevelSecurity ? 1L : 2L, (long) vertexPropertyCountByValue.get("Joseph"));
vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("emptyField", ElementType.VERTEX, AUTHORIZATIONS_EMPTY);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(0, vertexPropertyCountByValue.size());
vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("name", ElementType.VERTEX, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joe"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joseph"));
Map<Object, Long> edgePropertyCountByValue = queryGraphQueryWithTermsAggregation(Edge.LABEL_PROPERTY_NAME, ElementType.EDGE, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, edgePropertyCountByValue.size());
assertEquals(2L, (long) edgePropertyCountByValue.get("label1"));
assertEquals(1L, (long) edgePropertyCountByValue.get("label2"));
}
private boolean isSearchIndexFieldLevelSecuritySupported() {
if (graph instanceof GraphWithSearchIndex) {
return ((GraphWithSearchIndex) graph).getSearchIndex().isFieldLevelSecuritySupported();
}
return true;
}
@Test
public void testGraphQueryVertexWithTermsAggregationAlterElementVisibility() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_A);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(0, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
}
@Test
public void testGraphQueryEdgeWithTermsAggregationAlterElementVisibility() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "edge", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_A);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(0, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
}
private Map<Object, Long> queryGraphQueryWithTermsAggregation(String propertyName, ElementType elementType, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
TermsAggregation agg = new TermsAggregation("terms-count", propertyName);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", agg.getClass().getName());
return null;
}
q.addAggregation(agg);
TermsResult aggregationResult = (elementType == ElementType.VERTEX ? q.vertices() : q.edges()).getAggregationResult("terms-count", TermsResult.class);
return termsBucketToMap(aggregationResult.getBuckets());
}
@Test
public void testGraphQueryWithNestedTermsAggregation() {
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.defineProperty("gender").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "male", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "male", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "female", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "female", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Map<Object, Long>> vertexPropertyCountByValue = queryGraphQueryWithNestedTermsAggregation("name", "gender", AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(1, vertexPropertyCountByValue.get("Joe").size());
assertEquals(1L, (long) vertexPropertyCountByValue.get("Joe").get("male"));
assertEquals(2, vertexPropertyCountByValue.get("Sam").size());
assertEquals(1L, (long) vertexPropertyCountByValue.get("Sam").get("male"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("Sam").get("female"));
}
private Map<Object, Map<Object, Long>> queryGraphQueryWithNestedTermsAggregation(String propertyNameFirst, String propertyNameSecond, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
TermsAggregation agg = new TermsAggregation("terms-count", propertyNameFirst);
agg.addNestedAggregation(new TermsAggregation("nested", propertyNameSecond));
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", agg.getClass().getName());
return null;
}
q.addAggregation(agg);
TermsResult aggregationResult = q.vertices().getAggregationResult("terms-count", TermsResult.class);
return nestedTermsBucketToMap(aggregationResult.getBuckets(), "nested");
}
@Test
public void testGraphQueryWithHistogramAggregation() throws ParseException {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1990-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-08-15"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_A)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-03-02"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> histogram = queryGraphQueryWithHistogramAggregation("age", "1", 0L, new HistogramAggregation.ExtendedBounds<>(20L, 25L), AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(6, histogram.size());
assertEquals(1L, (long) histogram.get("25"));
assertEquals(searchIndexFieldLevelSecurity ? 2L : 3L, (long) histogram.get("20"));
histogram = queryGraphQueryWithHistogramAggregation("age", "1", null, null, AUTHORIZATIONS_A_AND_B);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("25"));
assertEquals(3L, (long) histogram.get("20"));
// field that doesn't have any values
histogram = queryGraphQueryWithHistogramAggregation("emptyField", "1", null, null, AUTHORIZATIONS_A_AND_B);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(0, histogram.size());
// date by 'year'
histogram = queryGraphQueryWithHistogramAggregation("birthDate", "year", null, null, AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
// date by milliseconds
histogram = queryGraphQueryWithHistogramAggregation("birthDate", (365L * 24L * 60L * 60L * 1000L) + "", null, null, AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
}
private Map<Object, Long> queryGraphQueryWithHistogramAggregation(
String propertyName,
String interval,
Long minDocCount,
HistogramAggregation.ExtendedBounds extendedBounds,
Authorizations authorizations
) {
Query q = graph.query(authorizations).limit(0);
HistogramAggregation agg = new HistogramAggregation("hist-count", propertyName, interval, minDocCount);
agg.setExtendedBounds(extendedBounds);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", HistogramAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return histogramBucketToMap(q.vertices().getAggregationResult("hist-count", HistogramResult.class).getBuckets());
}
@Test
public void testGraphQueryWithRangeAggregation() throws ParseException {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1990-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-08-15"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_A)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-03-02"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// numeric range
RangeResult aggregationResult = queryGraphQueryWithRangeAggregation(
"age",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(searchIndexFieldLevelSecurity ? 2 : 3, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(0, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// numeric range with permission to see more data
aggregationResult = queryGraphQueryWithRangeAggregation(
"age",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_A_AND_B
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(3, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(0, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// range for a field with no values
aggregationResult = queryGraphQueryWithRangeAggregation(
"emptyField",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(0, IterableUtils.count(aggregationResult.getBuckets()));
// date range with dates specified as strings
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
null,
"lower",
"1991-01-01",
"middle",
"1995-08-30",
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(2, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// date range without user specified keys
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
"yyyy-MM-dd",
null,
"1991-01-01",
null,
"1995-08-30",
null,
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("*-1991-01-01").getCount());
assertEquals(2, aggregationResult.getBucketByKey("1991-01-01-1995-08-30").getCount());
assertEquals(1, aggregationResult.getBucketByKey("1995-08-30-*").getCount());
// date range with dates specified as date objects
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
null,
"lower",
simpleDateFormat.parse("1991-01-01"),
"middle",
simpleDateFormat.parse("1995-08-30"),
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(2, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
}
private RangeResult queryGraphQueryWithRangeAggregation(
String propertyName,
String format,
String keyOne,
Object boundaryOne,
String keyTwo,
Object boundaryTwo,
String keyThree,
Authorizations authorizations
) {
Query q = graph.query(authorizations).limit(0);
RangeAggregation agg = new RangeAggregation("range-count", propertyName, format);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", RangeAggregation.class.getName());
return null;
}
agg.addUnboundedTo(keyOne, boundaryOne);
agg.addRange(keyTwo, boundaryOne, boundaryTwo);
agg.addUnboundedFrom(keyThree, boundaryTwo);
q.addAggregation(agg);
return q.vertices().getAggregationResult("range-count", RangeResult.class);
}
@Test
public void testGraphQueryWithRangeAggregationAndNestedTerms() throws ParseException {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 21, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 22, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Bob", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Query q = graph.query(AUTHORIZATIONS_A_AND_B).limit(0);
RangeAggregation rangeAggregation = new RangeAggregation("range-count", "age");
TermsAggregation termsAggregation = new TermsAggregation("name-count", "name");
rangeAggregation.addNestedAggregation(termsAggregation);
assumeTrue("range aggregation not supported", q.isAggregationSupported(rangeAggregation));
assumeTrue("terms aggregation not supported", q.isAggregationSupported(termsAggregation));
rangeAggregation.addUnboundedTo("lower", 23);
rangeAggregation.addUnboundedFrom("upper", 23);
q.addAggregation(rangeAggregation);
RangeResult rangeAggResult = q.vertices().getAggregationResult("range-count", RangeResult.class);
assertEquals(3, rangeAggResult.getBucketByKey("lower").getCount());
assertEquals(1, rangeAggResult.getBucketByKey("upper").getCount());
Comparator<TermsBucket> bucketComparator = (b1, b2) -> Long.compare(b2.getCount(), b1.getCount());
Map<String, AggregationResult> lowerNestedResult = rangeAggResult.getBucketByKey("lower").getNestedResults();
TermsResult lowerTermsResult = (TermsResult) lowerNestedResult.get(termsAggregation.getAggregationName());
List<TermsBucket> lowerTermsBuckets = IterableUtils.toList(lowerTermsResult.getBuckets());
Collections.sort(lowerTermsBuckets, bucketComparator);
assertEquals(1, lowerNestedResult.size());
assertEquals(2, lowerTermsBuckets.size());
assertEquals("Alice", lowerTermsBuckets.get(0).getKey());
assertEquals(2, lowerTermsBuckets.get(0).getCount());
assertEquals("Bob", lowerTermsBuckets.get(1).getKey());
assertEquals(1, lowerTermsBuckets.get(1).getCount());
Map<String, AggregationResult> upperNestedResult = rangeAggResult.getBucketByKey("upper").getNestedResults();
TermsResult upperTermsResult = (TermsResult) upperNestedResult.get(termsAggregation.getAggregationName());
List<TermsBucket> upperTermsBuckets = IterableUtils.toList(upperTermsResult.getBuckets());
assertEquals(1, upperNestedResult.size());
assertEquals(1, upperTermsBuckets.size());
assertEquals("Alice", upperTermsBuckets.get(0).getKey());
assertEquals(1, upperTermsBuckets.get(0).getCount());
}
@Test
public void testGraphQueryWithStatisticsAggregation() throws ParseException {
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
StatisticsResult stats = queryGraphQueryWithStatisticsAggregation("age", AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(3, stats.getCount());
assertEquals(65.0, stats.getSum(), 0.1);
assertEquals(20.0, stats.getMin(), 0.1);
assertEquals(25.0, stats.getMax(), 0.1);
assertEquals(2.35702, stats.getStandardDeviation(), 0.1);
assertEquals(21.666666, stats.getAverage(), 0.1);
stats = queryGraphQueryWithStatisticsAggregation("emptyField", AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(0, stats.getCount());
assertEquals(0.0, stats.getSum(), 0.1);
assertEquals(0.0, stats.getMin(), 0.1);
assertEquals(0.0, stats.getMax(), 0.1);
assertEquals(0.0, stats.getAverage(), 0.1);
assertEquals(0.0, stats.getStandardDeviation(), 0.1);
stats = queryGraphQueryWithStatisticsAggregation("age", AUTHORIZATIONS_A_AND_B);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(4, stats.getCount());
assertEquals(95.0, stats.getSum(), 0.1);
assertEquals(20.0, stats.getMin(), 0.1);
assertEquals(30.0, stats.getMax(), 0.1);
assertEquals(23.75, stats.getAverage(), 0.1);
assertEquals(4.14578, stats.getStandardDeviation(), 0.1);
}
private StatisticsResult queryGraphQueryWithStatisticsAggregation(String propertyName, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
StatisticsAggregation agg = new StatisticsAggregation("stats", propertyName);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", StatisticsAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return q.vertices().getAggregationResult("stats", StatisticsResult.class);
}
@Test
public void testGraphQueryWithPercentilesAggregation() throws ParseException {
graph.defineProperty("emptyField").dataType(Integer.class).define();
for (int i = 0; i <= 100; i++) {
graph.prepareVertex("v" + i, VISIBILITY_EMPTY)
.addPropertyValue("", "age", i, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
}
graph.prepareVertex("v200", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
PercentilesResult percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assumeTrue("percentiles aggregation not supported", percentilesResult != null);
List<Percentile> percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(7, percentiles.size());
assertEquals(1.0, percentiles.get(0).getPercentile(), 0.1);
assertEquals(1.0, percentiles.get(0).getValue(), 0.1);
assertEquals(5.0, percentiles.get(1).getPercentile(), 0.1);
assertEquals(5.0, percentiles.get(1).getValue(), 0.1);
assertEquals(25.0, percentiles.get(2).getPercentile(), 0.1);
assertEquals(25.0, percentiles.get(2).getValue(), 0.1);
assertEquals(50.0, percentiles.get(3).getPercentile(), 0.1);
assertEquals(50.0, percentiles.get(3).getValue(), 0.1);
assertEquals(75.0, percentiles.get(4).getPercentile(), 0.1);
assertEquals(75.0, percentiles.get(4).getValue(), 0.1);
assertEquals(95.0, percentiles.get(5).getPercentile(), 0.1);
assertEquals(95.0, percentiles.get(5).getValue(), 0.1);
assertEquals(99.0, percentiles.get(6).getPercentile(), 0.1);
assertEquals(99.0, percentiles.get(6).getValue(), 0.1);
percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY, 60, 99.99);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(2, percentiles.size());
assertEquals(60.0, percentiles.get(0).getValue(), 0.1);
assertEquals(60.0, percentiles.get(0).getValue(), 0.1);
assertEquals(99.99, percentiles.get(1).getValue(), 0.1);
assertEquals(99.99, percentiles.get(1).getValue(), 0.1);
percentilesResult = queryGraphQueryWithPercentilesAggregation("emptyField", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
assertEquals(0, percentiles.size());
percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(7, percentiles.size());
assertEquals(1.0, percentiles.get(0).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(0).getValue(), 0.1);
assertEquals(5.0, percentiles.get(1).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(1).getValue(), 0.1);
assertEquals(25.0, percentiles.get(2).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(2).getValue(), 0.1);
assertEquals(50.0, percentiles.get(3).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(3).getValue(), 0.1);
assertEquals(75.0, percentiles.get(4).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(4).getValue(), 0.1);
assertEquals(95.0, percentiles.get(5).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(5).getValue(), 0.1);
assertEquals(99.0, percentiles.get(6).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(6).getValue(), 0.1);
}
private PercentilesResult queryGraphQueryWithPercentilesAggregation(
String propertyName,
Visibility visibility,
Authorizations authorizations,
double... percents
) {
Query q = graph.query(authorizations).limit(0);
PercentilesAggregation agg = new PercentilesAggregation("percentiles", propertyName, visibility);
agg.setPercents(percents);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", StatisticsAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return q.vertices().getAggregationResult("percentiles", PercentilesResult.class);
}
@Test
public void testGraphQueryWithGeohashAggregation() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("emptyField").dataType(GeoPoint.class).define();
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(50, -10, "pt1"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39, -77, "pt2"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39.1, -77.1, "pt3"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39.2, -77.2, "pt4"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<String, Long> histogram = queryGraphQueryWithGeohashAggregation("location", 2, AUTHORIZATIONS_EMPTY);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("gb"));
assertEquals(searchIndexFieldLevelSecurity ? 2L : 3L, (long) histogram.get("dq"));
histogram = queryGraphQueryWithGeohashAggregation("emptyField", 2, AUTHORIZATIONS_EMPTY);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(0, histogram.size());
histogram = queryGraphQueryWithGeohashAggregation("location", 2, AUTHORIZATIONS_A_AND_B);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("gb"));
assertEquals(3L, (long) histogram.get("dq"));
}
@Test
public void testGraphQueryWithCalendarFieldAggregation() {
graph.prepareVertex("v0", VISIBILITY_EMPTY)
.addPropertyValue("", "other_field", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2017, Calendar.MAY, 26, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v3", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v4", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 24, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v5", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 25, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v6", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 30, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
// hour of day
QueryResultsIterable<Vertex> results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.HOUR_OF_DAY))
.limit(0)
.vertices();
HistogramResult aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(2, aggResult.getBucketByKey(10).getCount());
assertEquals(4, aggResult.getBucketByKey(12).getCount());
// day of week
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_WEEK))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(5, count(aggResult.getBuckets()));
assertEquals(1, aggResult.getBucketByKey(Calendar.SUNDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.MONDAY).getCount());
assertEquals(2, aggResult.getBucketByKey(Calendar.WEDNESDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.FRIDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.SATURDAY).getCount());
// day of month
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_MONTH))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(5, count(aggResult.getBuckets()));
assertEquals(1, aggResult.getBucketByKey(24).getCount());
assertEquals(1, aggResult.getBucketByKey(25).getCount());
assertEquals(1, aggResult.getBucketByKey(26).getCount());
assertEquals(2, aggResult.getBucketByKey(27).getCount());
assertEquals(1, aggResult.getBucketByKey(30).getCount());
// month
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.MONTH))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(Calendar.APRIL).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.MAY).getCount());
// year
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.YEAR))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(2016).getCount());
assertEquals(1, aggResult.getBucketByKey(2017).getCount());
// week of year
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.WEEK_OF_YEAR))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(18).getCount());
assertEquals(1, aggResult.getBucketByKey(21).getCount());
}
@Test
public void testGraphQueryWithCalendarFieldAggregationNested() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 28, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
CalendarFieldAggregation agg = new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_WEEK);
agg.addNestedAggregation(new CalendarFieldAggregation("aggNested", "date", null, TimeZone.getDefault(), Calendar.HOUR_OF_DAY));
QueryResultsIterable<Vertex> results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(agg)
.limit(0)
.vertices();
HistogramResult aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
HistogramBucket bucket = aggResult.getBucketByKey(Calendar.WEDNESDAY);
assertEquals(3, bucket.getCount());
HistogramResult nestedResult = (HistogramResult) bucket.getNestedResults().get("aggNested");
assertEquals(2, nestedResult.getBucketByKey(10).getCount());
assertEquals(1, nestedResult.getBucketByKey(12).getCount());
bucket = aggResult.getBucketByKey(Calendar.THURSDAY);
assertEquals(1, bucket.getCount());
nestedResult = (HistogramResult) bucket.getNestedResults().get("aggNested");
assertEquals(1, nestedResult.getBucketByKey(10).getCount());
}
@Test
public void testLargeFieldValuesThatAreMarkedWithExactMatch() {
graph.defineProperty("field1").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
StringBuilder largeText = new StringBuilder();
for (int i = 0; i < 10000; i++) {
largeText.append("test ");
}
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "field1", largeText.toString(), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_EMPTY);
graph.flush();
}
private Map<String, Long> queryGraphQueryWithGeohashAggregation(String propertyName, int precision, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
GeohashAggregation agg = new GeohashAggregation("geo-count", propertyName, precision);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", GeohashAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return geoHashBucketToMap(q.vertices().getAggregationResult("geo-count", GeohashResult.class).getBuckets());
}
@Test
public void testGetVertexPropertyCountByValue() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_B)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> vertexPropertyCountByValue = graph.getVertexPropertyCountByValue("name", AUTHORIZATIONS_EMPTY);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("joe"));
assertEquals(searchIndexFieldLevelSecurity ? 1L : 2L, (long) vertexPropertyCountByValue.get("joseph"));
vertexPropertyCountByValue = graph.getVertexPropertyCountByValue("name", AUTHORIZATIONS_A_AND_B);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("joe"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("joseph"));
}
@Test
public void testGetCounts() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edge1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertEquals(2, graph.getVertexCount(AUTHORIZATIONS_A));
assertEquals(1, graph.getEdgeCount(AUTHORIZATIONS_A));
}
@Test
public void testFetchHintsEdgeLabels() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
graph.addEdge("e v1->v2", v1, v2, "labelA", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("e v1->v3", v1, v3, "labelB", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.EDGE_LABELS, AUTHORIZATIONS_ALL);
List<String> edgeLabels = toList(v1.getEdgeLabels(Direction.BOTH, AUTHORIZATIONS_ALL));
assertEquals(2, edgeLabels.size());
assertTrue("labelA missing", edgeLabels.contains("labelA"));
assertTrue("labelB missing", edgeLabels.contains("labelB"));
}
@Test
public void testIPAddress() {
graph.defineProperty("ipAddress2").dataType(IpV4Address.class).define();
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.0.1"), VISIBILITY_A)
.addPropertyValue("k1", "ipAddress2", new IpV4Address("192.168.0.2"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.0.5"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.1.1"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(new IpV4Address("192.168.0.1"), v1.getPropertyValue("ipAddress1"));
assertEquals(new IpV4Address(192, 168, 0, 2), v1.getPropertyValue("ipAddress2"));
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A).has("ipAddress1", Compare.EQUAL, new IpV4Address("192.168.0.1")).vertices());
assertEquals(1, vertices.size());
assertEquals("v1", vertices.get(0).getId());
vertices = sortById(toList(
graph.query(AUTHORIZATIONS_A)
.range("ipAddress1", new IpV4Address("192.168.0.0"), new IpV4Address("192.168.0.255"))
.vertices()
));
assertEquals(2, vertices.size());
assertEquals("v1", vertices.get(0).getId());
assertEquals("v2", vertices.get(1).getId());
}
@Test
public void testVertexHashCodeAndEquals() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1Loaded = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(v1Loaded.hashCode(), v1.hashCode());
assertTrue(v1Loaded.equals(v1));
assertNotEquals(v1Loaded.hashCode(), v2.hashCode());
assertFalse(v1Loaded.equals(v2));
}
@Test
public void testEdgeHashCodeAndEquals() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
Edge e1 = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Edge e2 = graph.prepareEdge("e2", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Edge e1Loaded = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals(e1Loaded.hashCode(), e1.hashCode());
assertTrue(e1Loaded.equals(e1));
assertNotEquals(e1Loaded.hashCode(), e2.hashCode());
assertFalse(e1Loaded.equals(e2));
}
@Test
public void testExtendedData() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
Date date3 = new Date(1487083470000L);
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value2", VISIBILITY_A)
.addExtendedData("table1", "row3", "date", date3, VISIBILITY_A)
.addExtendedData("table1", "row3", "name", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(ImmutableSet.of("table1"), v1.getExtendedDataTableNames());
Iterator<ExtendedDataRow> rows = v1.getExtendedData("table1").iterator();
ExtendedDataRow row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date3, row.getPropertyValue("date"));
assertEquals("value3", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
rows = graph.getExtendedData(
Lists.newArrayList(
new ExtendedDataRowId(ElementType.VERTEX, "v1", "table1", "row1"),
new ExtendedDataRowId(ElementType.VERTEX, "v1", "table1", "row2")
),
AUTHORIZATIONS_A
).iterator();
row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
rows = graph.getExtendedData(ElementType.VERTEX, "v1", "table1", AUTHORIZATIONS_A).iterator();
row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date3, row.getPropertyValue("date"));
assertEquals("value3", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.addExtendedData("table1", "row4", "name", "value4", VISIBILITY_A)
.addExtendedData("table2", "row1", "name", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertTrue("table1 should exist", v1.getExtendedDataTableNames().contains("table1"));
assertTrue("table2 should exist", v1.getExtendedDataTableNames().contains("table2"));
List<ExtendedDataRow> rowsList = toList(v1.getExtendedData("table1"));
assertEquals(4, rowsList.size());
rowsList = toList(v1.getExtendedData("table2"));
assertEquals(1, rowsList.size());
}
@Test
public void testExtendedDataDelete() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(0, searchResults.getTotalHits());
}
@Test
public void testExtendedDataQueryVertices() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// Should not come back when finding vertices
QueryResultsIterable<Vertex> queryResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.vertices();
assertEquals(0, queryResults.getTotalHits());
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.search();
assertEquals(1, searchResults.getTotalHits());
List<? extends VertexiumObject> searchResultsList = toList(searchResults);
assertEquals(1, searchResultsList.size());
ExtendedDataRow searchResult = (ExtendedDataRow) searchResultsList.get(0);
assertEquals("v1", searchResult.getId().getElementId());
assertEquals("row1", searchResult.getId().getRowId());
searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
searchResults = graph.query("value", AUTHORIZATIONS_A)
.hasExtendedData(ElementType.VERTEX, "v1", "table1")
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
searchResults = graph.query("value", AUTHORIZATIONS_A)
.hasExtendedData("table1")
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
}
@Test
public void testExtendedDataVertexQuery() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addExtendedData("table1", "row3", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row4", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row5", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row6", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<ExtendedDataRow> searchResultsList = toList(
v1.query(AUTHORIZATIONS_A)
.extendedDataRows()
);
assertRowIdsAnyOrder(Lists.newArrayList("row3", "row4", "row5", "row6"), searchResultsList);
}
@Test
public void testExtendedDataQueryAfterDeleteForVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<ExtendedDataRow> searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList(), searchResultsList);
}
@Test
public void testExtendedDataQueryAfterDeleteForEdge() {
graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<ExtendedDataRow> searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
graph.deleteEdge("e1", AUTHORIZATIONS_A);
graph.flush();
searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList(), searchResultsList);
}
@Test
public void testExtendedDataQueryEdges() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e2", "v1", "v2", "label", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// Should not come back when finding edges
QueryResultsIterable<Edge> queryResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.edges();
assertEquals(0, queryResults.getTotalHits());
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.search();
assertEquals(1, searchResults.getTotalHits());
List<? extends VertexiumObject> searchResultsList = toList(searchResults);
assertEquals(1, searchResultsList.size());
ExtendedDataRow searchResult = (ExtendedDataRow) searchResultsList.get(0);
assertEquals("e1", searchResult.getId().getElementId());
assertEquals("row1", searchResult.getId().getRowId());
searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
}
@Test
public void testFetchHintsExceptions() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("metadata1", "metadata1Value", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
Property prop1 = v1.getProperty("prop1");
assertThrowsException(prop1::getMetadata);
}
@Test
public void benchmark() {
assumeTrue(benchmarkEnabled());
Random random = new Random(1);
int vertexCount = 10000;
int edgeCount = 10000;
int findVerticesByIdCount = 10000;
benchmarkAddVertices(vertexCount);
benchmarkAddEdges(random, vertexCount, edgeCount);
benchmarkFindVerticesById(random, vertexCount, findVerticesByIdCount);
}
@Test
public void benchmarkGetPropertyByName() {
final int propertyCount = 100;
assumeTrue(benchmarkEnabled());
VertexBuilder m = graph.prepareVertex("v1", VISIBILITY_A);
for (int i = 0; i < propertyCount; i++) {
m.addPropertyValue("key", "prop" + i, "value " + i, VISIBILITY_A);
}
m.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
double startTime = System.currentTimeMillis();
StringBuilder optimizationBuster = new StringBuilder();
for (int i = 0; i < 10000; i++) {
for (int propIndex = 0; propIndex < propertyCount; propIndex++) {
Object value = v1.getPropertyValue("key", "prop" + propIndex);
optimizationBuster.append(value.toString().substring(0, 1));
}
}
double endTime = System.currentTimeMillis();
LOGGER.trace("optimizationBuster: %s", optimizationBuster.substring(0, 1));
LOGGER.info("get property by name and key in %.3fs", (endTime - startTime) / 1000);
startTime = System.currentTimeMillis();
optimizationBuster = new StringBuilder();
for (int i = 0; i < 10000; i++) {
for (int propIndex = 0; propIndex < propertyCount; propIndex++) {
Object value = v1.getPropertyValue("prop" + propIndex);
optimizationBuster.append(value.toString().substring(0, 1));
}
}
endTime = System.currentTimeMillis();
LOGGER.trace("optimizationBuster: %s", optimizationBuster.substring(0, 1));
LOGGER.info("get property by name in %.3fs", (endTime - startTime) / 1000);
}
@Test
public void benchmarkSaveElementMutations() {
assumeTrue(benchmarkEnabled());
int vertexCount = 1000;
benchmarkAddVertices(vertexCount);
benchmarkAddVerticesSaveElementMutations(vertexCount);
benchmarkAddVertices(vertexCount);
}
private void benchmarkAddVertices(int vertexCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < vertexCount; i++) {
String vertexId = "v" + i;
graph.prepareVertex(vertexId, VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("add vertices in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkAddVerticesSaveElementMutations(int vertexCount) {
double startTime = System.currentTimeMillis();
List<ElementMutation> mutations = new ArrayList<>();
for (int i = 0; i < vertexCount; i++) {
String vertexId = "v" + i;
ElementBuilder<Vertex> m = graph.prepareVertex(vertexId, VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A);
mutations.add(m);
}
graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL);
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("save element mutations in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkAddEdges(Random random, int vertexCount, int edgeCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < edgeCount; i++) {
String edgeId = "e" + i;
String outVertexId = "v" + random.nextInt(vertexCount);
String inVertexId = "v" + random.nextInt(vertexCount);
graph.prepareEdge(edgeId, outVertexId, inVertexId, "label", VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("add edges in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkFindVerticesById(Random random, int vertexCount, int findVerticesByIdCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < findVerticesByIdCount; i++) {
String vertexId = "v" + random.nextInt(vertexCount);
graph.getVertex(vertexId, AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("find vertices by id in %.3fs", (endTime - startTime) / 1000);
}
private boolean benchmarkEnabled() {
return Boolean.parseBoolean(System.getProperty("benchmark", "false"));
}
private List<Vertex> getVertices(long count) {
List<Vertex> vertices = new ArrayList<>();
for (int i = 0; i < count; i++) {
Vertex vertex = graph.addVertex(Integer.toString(i), VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
vertices.add(vertex);
}
return vertices;
}
private boolean isDefaultSearchIndex() {
if (!(graph instanceof GraphWithSearchIndex)) {
return false;
}
GraphWithSearchIndex graphWithSearchIndex = (GraphWithSearchIndex) graph;
return graphWithSearchIndex.getSearchIndex() instanceof DefaultSearchIndex;
}
protected List<Vertex> sortById(List<Vertex> vertices) {
Collections.sort(vertices, Comparator.comparing(Element::getId));
return vertices;
}
protected boolean disableEdgeIndexing(Graph graph) {
return false;
}
private Map<Object, Long> termsBucketToMap(Iterable<TermsBucket> buckets) {
Map<Object, Long> results = new HashMap<>();
for (TermsBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
private Map<Object, Map<Object, Long>> nestedTermsBucketToMap(Iterable<TermsBucket> buckets, String nestedAggName) {
Map<Object, Map<Object, Long>> results = new HashMap<>();
for (TermsBucket entry : buckets) {
TermsResult nestedResults = (TermsResult) entry.getNestedResults().get(nestedAggName);
if (nestedResults == null) {
throw new VertexiumException("Could not find nested: " + nestedAggName);
}
results.put(entry.getKey(), termsBucketToMap(nestedResults.getBuckets()));
}
return results;
}
private Map<Object, Long> histogramBucketToMap(Iterable<HistogramBucket> buckets) {
Map<Object, Long> results = new HashMap<>();
for (HistogramBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
private Map<String, Long> geoHashBucketToMap(Iterable<GeohashBucket> buckets) {
Map<String, Long> results = new HashMap<>();
for (GeohashBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
// Historical Property Value tests
@Test
public void historicalPropertyValueAddProp() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Add property
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(3, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals("prop3_A", values.get(2).getPropertyName());
}
@Test
public void historicalPropertyValueDeleteProp() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// remove property
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.softDeleteProperties("prop2_B")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(4, values.size());
boolean isDeletedExpected = false;
for (int i = 0; i < 4; i++) {
HistoricalPropertyValue item = values.get(i);
if (item.getPropertyName().equals("prop1_A")) {
assertEquals("prop1_A", values.get(i).getPropertyName());
assertEquals(false, values.get(i).isDeleted());
} else if (item.getPropertyName().equals("prop2_B")) {
assertEquals("prop2_B", values.get(i).getPropertyName());
assertEquals(isDeletedExpected, values.get(i).isDeleted());
isDeletedExpected = !isDeletedExpected;
} else if (item.getPropertyName().equals("prop3_A")) {
assertEquals("prop3_A", values.get(i).getPropertyName());
assertEquals(false, values.get(i).isDeleted());
} else {
fail("Invalid " + item);
}
}
}
@Test
public void historicalPropertyValueModifyPropValue() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// modify property value
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Restore
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(5, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals(false, values.get(0).isDeleted());
assertEquals("value1", values.get(0).getValue());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals(false, values.get(1).isDeleted());
assertEquals("value2", values.get(1).getValue());
assertEquals("prop3_A", values.get(2).getPropertyName());
assertEquals(false, values.get(2).isDeleted());
assertEquals("value3", values.get(2).getValue());
assertEquals("prop3_A", values.get(3).getPropertyName());
assertEquals(false, values.get(3).isDeleted());
assertEquals("value4", values.get(3).getValue());
assertEquals("prop3_A", values.get(4).getPropertyName());
assertEquals(false, values.get(4).isDeleted());
assertEquals("value3", values.get(4).getValue());
}
@Test
public void historicalPropertyValueModifyPropVisibility() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// modify property value
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.alterPropertyVisibility("prop1_A", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Restore
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.alterPropertyVisibility("prop1_A", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(5, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals(false, values.get(0).isDeleted());
assertEquals(VISIBILITY_A, values.get(0).getPropertyVisibility());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals(false, values.get(1).isDeleted());
assertEquals(VISIBILITY_B, values.get(1).getPropertyVisibility());
assertEquals("prop3_A", values.get(2).getPropertyName());
assertEquals(false, values.get(2).isDeleted());
assertEquals(VISIBILITY_A, values.get(2).getPropertyVisibility());
assertEquals("prop1_A", values.get(3).getPropertyName());
assertEquals(false, values.get(3).isDeleted());
assertEquals(VISIBILITY_B, values.get(3).getPropertyVisibility());
assertEquals("prop1_A", values.get(4).getPropertyName());
assertEquals(false, values.get(4).isDeleted());
assertEquals(VISIBILITY_A, values.get(4).getPropertyVisibility());
}
}
| test/src/main/java/org/vertexium/test/GraphTestBase.java | package org.vertexium.test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.junit.*;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.vertexium.*;
import org.vertexium.event.*;
import org.vertexium.mutation.ElementMutation;
import org.vertexium.mutation.ExistingElementMutation;
import org.vertexium.property.PropertyValue;
import org.vertexium.property.StreamingPropertyValue;
import org.vertexium.query.*;
import org.vertexium.search.DefaultSearchIndex;
import org.vertexium.search.IndexHint;
import org.vertexium.test.util.LargeStringInputStream;
import org.vertexium.type.*;
import org.vertexium.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import static org.vertexium.test.util.VertexiumAssert.*;
import static org.vertexium.util.IterableUtils.count;
import static org.vertexium.util.IterableUtils.toList;
import static org.vertexium.util.StreamUtils.stream;
@RunWith(JUnit4.class)
public abstract class GraphTestBase {
private static final VertexiumLogger LOGGER = VertexiumLoggerFactory.getLogger(GraphTestBase.class);
public static final String VISIBILITY_A_STRING = "a";
public static final String VISIBILITY_B_STRING = "b";
public static final String VISIBILITY_C_STRING = "c";
public static final String VISIBILITY_MIXED_CASE_STRING = "MIXED_CASE_a";
public static final Visibility VISIBILITY_A = new Visibility(VISIBILITY_A_STRING);
public static final Visibility VISIBILITY_A_AND_B = new Visibility("a&b");
public static final Visibility VISIBILITY_B = new Visibility("b");
public static final Visibility VISIBILITY_MIXED_CASE_a = new Visibility("((MIXED_CASE_a))|b");
public static final Visibility VISIBILITY_EMPTY = new Visibility("");
public final Authorizations AUTHORIZATIONS_A;
public final Authorizations AUTHORIZATIONS_B;
public final Authorizations AUTHORIZATIONS_C;
public final Authorizations AUTHORIZATIONS_MIXED_CASE_a_AND_B;
public final Authorizations AUTHORIZATIONS_A_AND_B;
public final Authorizations AUTHORIZATIONS_EMPTY;
public final Authorizations AUTHORIZATIONS_BAD;
public final Authorizations AUTHORIZATIONS_ALL;
public static final int LARGE_PROPERTY_VALUE_SIZE = 1024 * 1024 + 1;
protected Graph graph;
protected abstract Graph createGraph() throws Exception;
public Graph getGraph() {
return graph;
}
public GraphTestBase() {
AUTHORIZATIONS_A = createAuthorizations("a");
AUTHORIZATIONS_B = createAuthorizations("b");
AUTHORIZATIONS_C = createAuthorizations("c");
AUTHORIZATIONS_A_AND_B = createAuthorizations("a", "b");
AUTHORIZATIONS_MIXED_CASE_a_AND_B = createAuthorizations("MIXED_CASE_a", "b");
AUTHORIZATIONS_EMPTY = createAuthorizations();
AUTHORIZATIONS_BAD = createAuthorizations("bad");
AUTHORIZATIONS_ALL = createAuthorizations("a", "b", "c", "MIXED_CASE_a");
}
protected abstract Authorizations createAuthorizations(String... auths);
@Before
public void before() throws Exception {
graph = createGraph();
clearGraphEvents();
graph.addGraphEventListener(new GraphEventListener() {
@Override
public void onGraphEvent(GraphEvent graphEvent) {
addGraphEvent(graphEvent);
}
});
}
@After
public void after() throws Exception {
if (graph != null) {
graph.shutdown();
graph = null;
}
}
// Need this to given occasional output so Travis doesn't fail the build for no output
@Rule
public TestRule watcher = new TestWatcher() {
protected void starting(Description description) {
System.out.println("Starting test: " + description.getMethodName());
}
};
@Test
public void testAddVertexWithId() {
Vertex vertexAdded = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(vertexAdded);
assertEquals("v1", vertexAdded.getId());
graph.flush();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_A, v.getVisibility());
v = graph.getVertex("", AUTHORIZATIONS_A);
assertNull(v);
v = graph.getVertex(null, AUTHORIZATIONS_A);
assertNull(v);
assertEvents(
new AddVertexEvent(graph, vertexAdded)
);
}
@Test
public void testAddVertexWithoutId() {
Vertex vertexAdded = graph.addVertex(VISIBILITY_A, AUTHORIZATIONS_A);
assertNotNull(vertexAdded);
String vertexId = vertexAdded.getId();
assertNotNull(vertexId);
graph.flush();
Vertex v = graph.getVertex(vertexId, AUTHORIZATIONS_A);
assertNotNull(v);
assertNotNull(vertexId);
assertEvents(
new AddVertexEvent(graph, vertexAdded)
);
}
@Test
public void testGetSingleVertexWithSameRowPrefix() {
graph.addVertex("prefix", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
graph.addVertex("prefixA", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex v = graph.getVertex("prefix", AUTHORIZATIONS_EMPTY);
assertEquals("prefix", v.getId());
v = graph.getVertex("prefixA", AUTHORIZATIONS_EMPTY);
assertEquals("prefixA", v.getId());
}
@Test
public void testStreamingPropertyValueReadAsString() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("spv", StreamingPropertyValue.create("Hello World"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertEquals("Hello World", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString());
assertEquals("Wor", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString(6, 3));
assertEquals("", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString("Hello World".length(), 1));
assertEquals("Hello World", ((StreamingPropertyValue) v1.getPropertyValue("spv")).readToString(0, 100));
}
@SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
@Test
public void testAddStreamingPropertyValue() throws IOException, InterruptedException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class, 6);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()),
String.class, expectedLargeValue.length()
);
String largePropertyName = "propLarge/\\*!@#$%^&*()[]{}|";
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Object> propSmallValues = v1.getPropertyValues("propSmall");
Assert.assertEquals(1, count(propSmallValues));
Object propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
StreamingPropertyValue value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
Iterable<Object> propLargeValues = v1.getPropertyValues(largePropertyName);
Assert.assertEquals(1, count(propLargeValues));
Object propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
propSmallValues = v1.getPropertyValues("propSmall");
Assert.assertEquals(1, count(propSmallValues));
propSmallValue = propSmallValues.iterator().next();
assertTrue("propSmallValue was " + propSmallValue.getClass().getName(), propSmallValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propSmallValue;
assertEquals(String.class, value.getValueType());
assertEquals("value1".getBytes().length, value.getLength());
assertEquals("value1", IOUtils.toString(value.getInputStream()));
assertEquals("value1", IOUtils.toString(value.getInputStream()));
propLargeValues = v1.getPropertyValues(largePropertyName);
Assert.assertEquals(1, count(propLargeValues));
propLargeValue = propLargeValues.iterator().next();
assertTrue(largePropertyName + " was " + propLargeValue.getClass().getName(), propLargeValue instanceof StreamingPropertyValue);
value = (StreamingPropertyValue) propLargeValue;
assertEquals(String.class, value.getValueType());
assertEquals(expectedLargeValue.getBytes().length, value.getLength());
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
assertEquals(expectedLargeValue, IOUtils.toString(value.getInputStream()));
}
@Test
public void testAddVertexPropertyWithMetadata() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("metadata1", "metadata1Value", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
if (v instanceof HasTimestamp) {
assertTrue("timestamp should be more than 0", v.getTimestamp() > 0);
}
Assert.assertEquals(1, count(v.getProperties("prop1")));
Property prop1 = v.getProperties("prop1").iterator().next();
if (prop1 instanceof HasTimestamp) {
assertTrue("timestamp should be more than 0", prop1.getTimestamp() > 0);
}
prop1Metadata = prop1.getMetadata();
assertNotNull(prop1Metadata);
assertEquals(1, prop1Metadata.entrySet().size());
assertEquals("metadata1Value", prop1Metadata.getEntry("metadata1", VISIBILITY_A).getValue());
prop1Metadata.add("metadata2", "metadata2Value", VISIBILITY_A);
v.prepareMutation()
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
prop1Metadata = prop1.getMetadata();
assertEquals(2, prop1Metadata.entrySet().size());
assertEquals("metadata1Value", prop1Metadata.getEntry("metadata1", VISIBILITY_A).getValue());
assertEquals("metadata2Value", prop1Metadata.getEntry("metadata2", VISIBILITY_A).getValue());
// make sure that when we update the value the metadata is not carried over
prop1Metadata = new Metadata();
v.setProperty("prop1", "value2", prop1Metadata, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
prop1 = v.getProperties("prop1").iterator().next();
assertEquals("value2", prop1.getValue());
prop1Metadata = prop1.getMetadata();
assertEquals(0, prop1Metadata.entrySet().size());
}
@Test
public void testAddVertexWithProperties() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(vertexAdded.getProperties("prop1")));
assertEquals("value1", vertexAdded.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(vertexAdded.getProperties("prop2")));
assertEquals("value2", vertexAdded.getPropertyValues("prop2").iterator().next());
graph.flush();
Vertex v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1", v.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(v.getProperties("prop2")));
assertEquals("value2", v.getPropertyValues("prop2").iterator().next());
assertEvents(
new AddVertexEvent(graph, vertexAdded),
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop1")),
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop2"))
);
clearGraphEvents();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v.prepareMutation()
.addPropertyValue("key1", "prop1Mutation", "value1Mutation", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(v.getProperties("prop1Mutation")));
assertEquals("value1Mutation", v.getPropertyValues("prop1Mutation").iterator().next());
assertEvents(
new AddPropertyEvent(graph, vertexAdded, vertexAdded.getProperty("prop1Mutation"))
);
}
@Test
public void testNullPropertyValue() {
try {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", null, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
throw new VertexiumException("expected null check");
} catch (NullPointerException ex) {
assertTrue(ex.getMessage().contains("prop1"));
}
}
@Test
public void testConcurrentModificationOfProperties() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
int i = 0;
for (Property p : v.getProperties()) {
assertNotNull(p.toString());
if (i == 0) {
v.setProperty("prop3", "value3", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
}
i++;
}
}
@Test
public void testAddVertexWithPropertiesWithTwoDifferentVisibilities() {
Vertex v = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1a", VISIBILITY_A)
.setProperty("prop1", "value1b", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties("prop1")));
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties("prop1")));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1a", v.getPropertyValue("prop1"));
v = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v.getProperties("prop1")));
assertEquals("value1b", v.getPropertyValue("prop1"));
}
@Test
public void testMultivaluedProperties() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.addPropertyValue("propid3a", "prop3", "value3a", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("value1a", v.getPropertyValues("prop1").iterator().next());
assertEquals("value2a", v.getPropertyValues("prop2").iterator().next());
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
Assert.assertEquals(3, count(v.getProperties()));
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getPropertyValues("prop1")));
assertEquals("value1b", v.getPropertyValues("prop1").iterator().next());
Assert.assertEquals(1, count(v.getPropertyValues("prop2")));
assertEquals("value2b", v.getPropertyValues("prop2").iterator().next());
Assert.assertEquals(1, count(v.getPropertyValues("prop3")));
assertEquals("value3a", v.getPropertyValues("prop3").iterator().next());
Assert.assertEquals(3, count(v.getProperties()));
v.addPropertyValue("propid1b", "prop1", "value1a-new", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
org.vertexium.test.util.IterableUtils.assertContains("value1b", v.getPropertyValues("prop1"));
org.vertexium.test.util.IterableUtils.assertContains("value1a-new", v.getPropertyValues("prop1"));
Assert.assertEquals(4, count(v.getProperties()));
}
@Test
public void testMultivaluedPropertyOrder() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("a", "prop", "a", VISIBILITY_A)
.addPropertyValue("aa", "prop", "aa", VISIBILITY_A)
.addPropertyValue("b", "prop", "b", VISIBILITY_A)
.addPropertyValue("0", "prop", "0", VISIBILITY_A)
.addPropertyValue("A", "prop", "A", VISIBILITY_A)
.addPropertyValue("Z", "prop", "Z", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("0", v1.getPropertyValue("prop", 0));
assertEquals("A", v1.getPropertyValue("prop", 1));
assertEquals("Z", v1.getPropertyValue("prop", 2));
assertEquals("a", v1.getPropertyValue("prop", 3));
assertEquals("aa", v1.getPropertyValue("prop", 4));
assertEquals("b", v1.getPropertyValue("prop", 5));
}
@Test
public void testDeleteProperty() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
clearGraphEvents();
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Property prop1_propid1a = v.getProperty("propid1a", "prop1");
Property prop1_propid1b = v.getProperty("propid1b", "prop1");
v.deleteProperties("prop1", AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(v.getProperties()));
v = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v.getProperties()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop2", "value2a").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1a").vertices()));
assertEvents(
new DeletePropertyEvent(graph, v, prop1_propid1a),
new DeletePropertyEvent(graph, v, prop1_propid1b)
);
clearGraphEvents();
Property prop2_propid2a = v.getProperty("propid2a", "prop2");
v.deleteProperty("propid2a", "prop2", AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(v.getProperties()));
v = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, v, prop2_propid2a)
);
}
@Test
public void testDeletePropertyWithMutation() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("propid1a", "prop1", "value1a", VISIBILITY_A)
.addPropertyValue("propid1b", "prop1", "value1b", VISIBILITY_A)
.addPropertyValue("propid2a", "prop2", "value2a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "edge1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
clearGraphEvents();
// delete multiple properties
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Property prop1_propid1a = v1.getProperty("propid1a", "prop1");
Property prop1_propid1b = v1.getProperty("propid1b", "prop1");
v1.prepareMutation()
.deleteProperties("prop1")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(v1.getProperties()));
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getProperties()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop2", "value2a").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1a").vertices()));
assertEvents(
new DeletePropertyEvent(graph, v1, prop1_propid1a),
new DeletePropertyEvent(graph, v1, prop1_propid1b)
);
clearGraphEvents();
// delete property with key and name
Property prop2_propid2a = v1.getProperty("propid2a", "prop2");
v1.prepareMutation()
.deleteProperties("propid2a", "prop2")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(v1.getProperties()));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, v1, prop2_propid2a)
);
clearGraphEvents();
// delete property from edge
Edge e1 = graph.getEdge("e1", FetchHint.ALL, AUTHORIZATIONS_A);
Property edgeProperty = e1.getProperty("key1", "prop1");
e1.prepareMutation()
.deleteProperties("key1", "prop1")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(e1.getProperties()));
e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(e1.getProperties()));
assertEvents(
new DeletePropertyEvent(graph, e1, edgeProperty)
);
}
@Test
public void testDeleteElement() {
Vertex v = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v.prepareMutation()
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull(v);
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
graph.deleteVertex(v.getId(), AUTHORIZATIONS_A_AND_B);
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v);
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "value1").vertices()));
}
@Test
public void testDeleteVertex() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A)));
}
@Test
public void testSoftDeleteVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
Vertex v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(1, v2.getEdgeCount(Direction.BOTH, AUTHORIZATIONS_A));
graph.softDeleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
assertEquals(0, v2.getEdgeCount(Direction.BOTH, AUTHORIZATIONS_A));
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(4, count(graph.getVertices(AUTHORIZATIONS_A)));
assertResultsCount(3, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.softDeleteVertex("v3", AUTHORIZATIONS_A);
graph.flush();
assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
assertResultsCount(2, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testGetSoftDeletedElementWithFetchHintsAndTimestamp() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
long beforeDeleteTime = IncreasingTime.currentTimeMillis();
graph.softDeleteEdge(e1, AUTHORIZATIONS_A);
graph.softDeleteVertex(v1, AUTHORIZATIONS_A);
graph.flush();
assertNull(graph.getEdge(e1.getId(), AUTHORIZATIONS_A));
assertNull(graph.getEdge(e1.getId(), graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
assertNull(graph.getEdge(e1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
assertNull(graph.getVertex(v1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A));
assertNotNull(graph.getEdge(e1.getId(), graph.getDefaultFetchHints(), beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getEdge(e1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getVertex(v1.getId(), graph.getDefaultFetchHints(), beforeDeleteTime, AUTHORIZATIONS_A));
assertNotNull(graph.getVertex(v1.getId(), FetchHint.ALL_INCLUDING_HIDDEN, beforeDeleteTime, AUTHORIZATIONS_A));
}
@Test
public void testSoftDeleteEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.addVertex("v3", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.addEdge("e1", v1, v2, "label1", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.addEdge("e2", v1, v3, "label1", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
graph.softDeleteEdge(e1, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v1.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v1.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A_AND_B);
assertEquals(0, count(v2.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v2 = graph.getVertex("v2", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(0, count(v2.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(0, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v3.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
v3 = graph.getVertex("v3", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertEquals(1, count(v3.getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
assertEquals(1, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testSoftDeleteProperty() throws InterruptedException {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A).softDeleteProperties("name1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A).softDeleteProperties("name1", AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testSoftDeletePropertyThroughMutation() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.softDeleteProperties("name1")
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices()));
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(1, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.softDeleteProperties("name1")
.save(AUTHORIZATIONS_A);
graph.flush();
assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
assertResultsCount(0, graph.query(AUTHORIZATIONS_A).has("name1", "value1").vertices());
}
@Test
public void testSoftDeletePropertyOnEdgeNotIndexed() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
ElementBuilder<Edge> elementBuilder = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_B)
.setProperty("prop1", "value1", VISIBILITY_B);
elementBuilder.setIndexHint(IndexHint.DO_NOT_INDEX);
Edge e1 = elementBuilder.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
ExistingElementMutation<Edge> m = e1.prepareMutation();
m.softDeleteProperty("prop1", VISIBILITY_B);
m.setIndexHint(IndexHint.DO_NOT_INDEX);
m.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
assertEquals(0, IterableUtils.count(e1.getProperties()));
}
@Test
public void testSoftDeletePropertyWithVisibility() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("value1", v1.getPropertyValues("name1"));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).softDeleteProperty("key1", "name1", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getPropertyValues("key1", "name1")));
org.vertexium.test.util.IterableUtils.assertContains("value2", graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getPropertyValues("name1"));
}
@Test
public void testSoftDeletePropertyThroughMutationWithVisibility() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "name1", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("value1", v1.getPropertyValues("name1"));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B)
.prepareMutation()
.softDeleteProperty("key1", "name1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
assertEquals(1, count(v1.getPropertyValues("key1", "name1")));
org.vertexium.test.util.IterableUtils.assertContains("value2", v1.getPropertyValues("name1"));
}
@Test
public void testSoftDeletePropertyOnAHiddenVertex() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("key1", "name1", "value1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
v1.softDeleteProperty("key1", "name1", AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
assertNull(v1.getProperty("key1", "name1", VISIBILITY_EMPTY));
}
@Test
public void testMarkHiddenWithVisibilityChange() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
List<Property> properties = IterableUtils.toList(v1.getProperties());
assertEquals(2, count(properties));
boolean foundJoeProp = false;
boolean foundJosephProp = false;
for (Property property : properties) {
if (property.getName().equals("firstName")) {
if (property.getKey().equals("key1") && property.getValue().equals("Joe")) {
foundJoeProp = true;
assertTrue("should be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A));
} else if (property.getKey().equals("key1") && property.getValue().equals("Joseph")) {
if (property.getVisibility().equals(VISIBILITY_B)) {
foundJosephProp = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Joseph property value not found", foundJosephProp);
assertTrue("Joe property value not found", foundJoeProp);
}
@Test
public void testSoftDeleteWithVisibilityChanges() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1.softDeleteProperty("key1", "firstName", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1.markPropertyVisible("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v1.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Property> properties = IterableUtils.toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
Property property = properties.iterator().next();
assertEquals(VISIBILITY_A, property.getVisibility());
assertEquals("Joseph", property.getValue());
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v2.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v2.getPropertyValues("firstName"));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A_AND_B);
v2.markPropertyHidden("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v2.addPropertyValue("key1", "firstName", "Joseph", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v2.softDeleteProperty("key1", "firstName", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
v2.markPropertyVisible("key1", "firstName", VISIBILITY_A, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
v2.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
properties = IterableUtils.toList(graph.getVertex("v2", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
property = properties.iterator().next();
assertEquals(VISIBILITY_A, property.getVisibility());
assertEquals("Joe", property.getValue());
}
@Test
public void testMarkPropertyVisible() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "firstName", "Joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals(1, count(v1.getProperties()));
org.vertexium.test.util.IterableUtils.assertContains("Joe", v1.getPropertyValues("firstName"));
long t = IncreasingTime.currentTimeMillis();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.markPropertyHidden("key1", "firstName", VISIBILITY_A, t, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
t += 10;
List<Property> properties = IterableUtils.toList(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
long beforeMarkPropertyVisibleTimestamp = t;
t += 10;
v1.markPropertyVisible("key1", "firstName", VISIBILITY_A, t, VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
t += 10;
properties = IterableUtils.toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(1, count(properties));
graph.flush();
v1 = graph.getVertex("v1", graph.getDefaultFetchHints(), beforeMarkPropertyVisibleTimestamp, AUTHORIZATIONS_A_AND_B);
assertNotNull("could not find v1 before timestamp " + beforeMarkPropertyVisibleTimestamp + " current time " + t, v1);
properties = IterableUtils.toList(v1.getProperties());
assertEquals(0, count(properties));
}
@Test
public void testAddVertexWithVisibility() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_ALL);
graph.flush();
Iterable<Vertex> cVertices = graph.getVertices(AUTHORIZATIONS_C);
Assert.assertEquals(0, count(cVertices));
Iterable<Vertex> aVertices = graph.getVertices(AUTHORIZATIONS_A);
assertEquals("v1", IterableUtils.single(aVertices).getId());
Iterable<Vertex> bVertices = graph.getVertices(AUTHORIZATIONS_B);
assertEquals("v2", IterableUtils.single(bVertices).getId());
Iterable<Vertex> allVertices = graph.getVertices(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(allVertices));
}
@Test
public void testAddMultipleVertices() {
List<ElementBuilder<Vertex>> elements = new ArrayList<>();
elements.add(graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "v1", VISIBILITY_A));
elements.add(graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "v2", VISIBILITY_A));
Iterable<Vertex> vertices = graph.addVertices(elements, AUTHORIZATIONS_A_AND_B);
assertVertexIds(vertices, "v1", "v2");
graph.flush();
if (graph instanceof GraphWithSearchIndex) {
((GraphWithSearchIndex) graph).getSearchIndex().addElements(graph, vertices, AUTHORIZATIONS_A_AND_B);
assertVertexIds(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "v1").vertices(), "v1");
assertVertexIds(graph.query(AUTHORIZATIONS_A_AND_B).has("prop1", "v2").vertices(), "v2");
}
}
@Test
public void testGetVerticesWithIds() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v1b", VISIBILITY_A)
.setProperty("prop1", "v1b", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("prop1", "v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> ids = new ArrayList<>();
ids.add("v2");
ids.add("v1");
Iterable<Vertex> vertices = graph.getVertices(ids, AUTHORIZATIONS_A);
boolean foundV1 = false, foundV2 = false;
for (Vertex v : vertices) {
if (v.getId().equals("v1")) {
assertEquals("v1", v.getPropertyValue("prop1"));
foundV1 = true;
} else if (v.getId().equals("v2")) {
assertEquals("v2", v.getPropertyValue("prop1"));
foundV2 = true;
} else {
assertTrue("Unexpected vertex id: " + v.getId(), false);
}
}
assertTrue("v1 not found", foundV1);
assertTrue("v2 not found", foundV2);
List<Vertex> verticesInOrder = graph.getVerticesInOrder(ids, AUTHORIZATIONS_A);
assertEquals(2, verticesInOrder.size());
assertEquals("v2", verticesInOrder.get(0).getId());
assertEquals("v1", verticesInOrder.get(1).getId());
}
@Test
public void testGetVerticesWithPrefix() {
graph.addVertex("a", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("aa", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("az", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("b", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Vertex> vertices = sortById(toList(graph.getVerticesWithPrefix("a", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices, "a", "aa", "az");
vertices = sortById(toList(graph.getVerticesWithPrefix("b", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices, "b");
vertices = sortById(toList(graph.getVerticesWithPrefix("c", AUTHORIZATIONS_ALL)));
assertVertexIds(vertices);
}
@Test
public void testGetVerticesInRange() {
graph.addVertex("a", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("aa", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("az", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addVertex("b", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Vertex> vertices = toList(graph.getVerticesInRange(new Range(null, "a"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices);
vertices = toList(graph.getVerticesInRange(new Range(null, "b"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az");
vertices = toList(graph.getVerticesInRange(new Range(null, "bb"), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az", "b");
vertices = toList(graph.getVerticesInRange(new Range(null, null), AUTHORIZATIONS_ALL));
assertVertexIds(vertices, "a", "aa", "az", "b");
}
@Test
public void testGetEdgesInRange() {
graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("a", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("aa", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("az", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.addEdge("b", "v1", "v2", "label1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
graph.flush();
List<Edge> edges = toList(graph.getEdgesInRange(new Range(null, "a"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{});
edges = toList(graph.getEdgesInRange(new Range(null, "b"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az"});
edges = toList(graph.getEdgesInRange(new Range(null, "bb"), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az", "b"});
edges = toList(graph.getEdgesInRange(new Range(null, null), AUTHORIZATIONS_ALL));
assertEdgeIds(edges, new String[]{"a", "aa", "az", "b"});
}
@Test
public void testGetEdgesWithIds() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1a", v1, v2, "", VISIBILITY_A)
.setProperty("prop1", "e1a", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "", VISIBILITY_A)
.setProperty("prop1", "e2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", v2, v3, "", VISIBILITY_A)
.setProperty("prop1", "e3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> ids = new ArrayList<>();
ids.add("e1");
ids.add("e2");
Iterable<Edge> edges = graph.getEdges(ids, AUTHORIZATIONS_A);
boolean foundE1 = false, foundE2 = false;
for (Edge e : edges) {
if (e.getId().equals("e1")) {
assertEquals("e1", e.getPropertyValue("prop1"));
foundE1 = true;
} else if (e.getId().equals("e2")) {
assertEquals("e2", e.getPropertyValue("prop1"));
foundE2 = true;
} else {
assertTrue("Unexpected vertex id: " + e.getId(), false);
}
}
assertTrue("e1 not found", foundE1);
assertTrue("e2 not found", foundE2);
}
@Test
public void testMarkVertexAndPropertiesHidden() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("k2", "age", 30, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_ALL);
for (Property property : v1.getProperties()) {
v1.markPropertyHidden(property, VISIBILITY_A, AUTHORIZATIONS_ALL);
}
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull("v1 was found", v1);
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_ALL);
assertNotNull("could not find v1", v1);
assertEquals(2, count(v1.getProperties()));
assertEquals(25, v1.getPropertyValue("k1", "age"));
assertEquals(30, v1.getPropertyValue("k2", "age"));
v1 = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_ALL);
graph.markVertexVisible(v1, VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1AfterVisible = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull("could not find v1", v1AfterVisible);
assertEquals(0, count(v1AfterVisible.getProperties()));
for (Property property : v1.getProperties()) {
v1.markPropertyVisible(property, VISIBILITY_A, AUTHORIZATIONS_ALL);
}
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNotNull("could not find v1", v1);
assertEquals(2, count(v1.getProperties()));
assertEquals(25, v1.getPropertyValue("k1", "age"));
assertEquals(30, v1.getPropertyValue("k2", "age"));
}
@Test
public void testMarkVertexHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("v1tov2", v1, v2, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
List<String> vertexIdList = new ArrayList<>();
vertexIdList.add("v1");
vertexIdList.add("v2");
vertexIdList.add("bad"); // add "bad" to the end of the list to test ordering of results
Map<String, Boolean> verticesExist = graph.doVerticesExist(vertexIdList, AUTHORIZATIONS_A);
assertEquals(3, vertexIdList.size());
assertTrue("v1 exist", verticesExist.get("v1"));
assertTrue("v2 exist", verticesExist.get("v2"));
assertFalse("bad exist", verticesExist.get("bad"));
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertTrue("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexHidden(v1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexHidden(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertFalse("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
assertNull("found v1 but shouldn't have", graph.getVertex("v1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A));
Vertex v1Hidden = graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A);
assertNotNull("did not find v1 but should have", v1Hidden);
assertTrue("v1 should be hidden", v1Hidden.isHidden(AUTHORIZATIONS_A));
graph.markVertexVisible(v1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertFalse("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.markVertexVisible(v1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1 exists (auth A)", graph.doesVertexExist("v1", AUTHORIZATIONS_A));
assertFalse("v1 exists (auth B)", graph.doesVertexExist("v1", AUTHORIZATIONS_B));
assertTrue("v1 exists (auth A&B)", graph.doesVertexExist("v1", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
}
@Test
public void testMarkEdgeHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("v1tov2", v1, v2, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("v2tov3", v2, v3, "test", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
List<String> edgeIdList = new ArrayList<>();
edgeIdList.add("v1tov2");
edgeIdList.add("v2tov3");
edgeIdList.add("bad");
Map<String, Boolean> edgesExist = graph.doEdgesExist(edgeIdList, AUTHORIZATIONS_A);
assertEquals(3, edgeIdList.size());
assertTrue("v1tov2 exist", edgesExist.get("v1tov2"));
assertTrue("v2tov3 exist", edgesExist.get("v2tov3"));
assertFalse("bad exist", edgesExist.get("bad"));
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertTrue("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
graph.markEdgeHidden(e1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertFalse("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_B)));
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdgeInfos(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdgeIds(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getEdgeInfos(Direction.BOTH, AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(0, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A)));
assertNull("found e1 but shouldn't have", graph.getEdge("v1tov2", graph.getDefaultFetchHints(), AUTHORIZATIONS_A_AND_B));
Edge e1Hidden = graph.getEdge("v1tov2", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B);
assertNotNull("did not find e1 but should have", e1Hidden);
assertTrue("e1 should be hidden", e1Hidden.isHidden(AUTHORIZATIONS_A_AND_B));
graph.markEdgeVisible(e1, VISIBILITY_A_AND_B, AUTHORIZATIONS_A);
graph.flush();
assertTrue("v1tov2 exists (auth A)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A));
assertFalse("v1tov2 exists (auth B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_B));
assertTrue("v1tov2 exists (auth A&B)", graph.doesEdgeExist("v1tov2", AUTHORIZATIONS_A_AND_B));
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(graph.getEdges(AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B)));
Assert.assertEquals(1, count(graph.findPaths(new FindPathOptions("v1", "v3", 10), AUTHORIZATIONS_A_AND_B)));
}
@Test
public void testMarkPropertyHidden() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_A)
.addPropertyValue("key1", "prop1", "value1", VISIBILITY_B)
.addPropertyValue("key2", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Assert.assertEquals(3, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1")));
v1.markPropertyHidden("key1", "prop1", VISIBILITY_A, VISIBILITY_A_AND_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Property> properties = toList(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1"));
Assert.assertEquals(2, count(properties));
boolean foundProp1Key2 = false;
boolean foundProp1Key1VisB = false;
for (Property property : properties) {
if (property.getName().equals("prop1")) {
if (property.getKey().equals("key2")) {
foundProp1Key2 = true;
} else if (property.getKey().equals("key1")) {
if (property.getVisibility().equals(VISIBILITY_B)) {
foundProp1Key1VisB = true;
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Prop1Key2 not found", foundProp1Key2);
assertTrue("Prop1Key1VisB not found", foundProp1Key1VisB);
List<Property> hiddenProperties = toList(graph.getVertex("v1", FetchHint.ALL_INCLUDING_HIDDEN, AUTHORIZATIONS_A_AND_B).getProperties());
assertEquals(3, hiddenProperties.size());
boolean foundProp1Key1VisA = false;
foundProp1Key2 = false;
foundProp1Key1VisB = false;
for (Property property : hiddenProperties) {
if (property.getName().equals("prop1")) {
if (property.getKey().equals("key2")) {
foundProp1Key2 = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else if (property.getKey().equals("key1")) {
if (property.getVisibility().equals(VISIBILITY_A)) {
foundProp1Key1VisA = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A));
assertTrue("should be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else if (property.getVisibility().equals(VISIBILITY_B)) {
foundProp1Key1VisB = true;
assertFalse("should not be hidden", property.isHidden(AUTHORIZATIONS_A_AND_B));
} else {
throw new RuntimeException("Unexpected visibility " + property.getVisibility());
}
} else {
throw new RuntimeException("Unexpected property key " + property.getKey());
}
} else {
throw new RuntimeException("Unexpected property name " + property.getName());
}
}
assertTrue("Prop1Key2 not found", foundProp1Key2);
assertTrue("Prop1Key1VisB not found", foundProp1Key1VisB);
assertTrue("Prop1Key1VisA not found", foundProp1Key1VisA);
v1.markPropertyVisible("key1", "prop1", VISIBILITY_A, VISIBILITY_A_AND_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(3, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties("prop1")));
}
/**
* This tests simulates two workspaces w1 (via A) and w1 (vis B).
* Both w1 and w2 has e1 on it.
* e1 is linked to e2.
* What happens if w1 (vis A) marks e1 hidden, then deletes itself?
*/
@Test
public void testMarkVertexHiddenAndDeleteEdges() {
Vertex w1 = graph.addVertex("w1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex w2 = graph.addVertex("w2", VISIBILITY_B, AUTHORIZATIONS_B);
Vertex e1 = graph.addVertex("e1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex e2 = graph.addVertex("e2", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.addEdge("w1-e1", w1, e1, "test", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("w2-e1", w2, e1, "test", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge("e1-e2", e1, e2, "test", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.flush();
e1 = graph.getVertex("e1", AUTHORIZATIONS_EMPTY);
graph.markVertexHidden(e1, VISIBILITY_A, AUTHORIZATIONS_EMPTY);
graph.flush();
graph.getVertex("w1", AUTHORIZATIONS_A);
graph.deleteVertex("w1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
assertEquals("e2", toList(graph.getVertices(AUTHORIZATIONS_A)).get(0).getId());
Assert.assertEquals(3, count(graph.getVertices(AUTHORIZATIONS_B)));
boolean foundW2 = false;
boolean foundE1 = false;
boolean foundE2 = false;
for (Vertex v : graph.getVertices(AUTHORIZATIONS_B)) {
if (v.getId().equals("w2")) {
foundW2 = true;
} else if (v.getId().equals("e1")) {
foundE1 = true;
} else if (v.getId().equals("e2")) {
foundE2 = true;
} else {
throw new VertexiumException("Unexpected id: " + v.getId());
}
}
assertTrue("w2", foundW2);
assertTrue("e1", foundE1);
assertTrue("e2", foundE2);
}
@Test
public void testDeleteVertexWithProperties() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Property prop1 = v1.getProperty("prop1");
Assert.assertEquals(1, count(graph.getVertices(AUTHORIZATIONS_A)));
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getVertices(AUTHORIZATIONS_A_AND_B)));
assertEvents(
new AddVertexEvent(graph, v1),
new AddPropertyEvent(graph, v1, prop1),
new DeleteVertexEvent(graph, v1)
);
}
@Test
public void testAddEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertNotNull(addedEdge);
assertEquals("e1", addedEdge.getId());
assertEquals("label1", addedEdge.getLabel());
assertEquals("v1", addedEdge.getVertexId(Direction.OUT));
assertEquals(v1, addedEdge.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", addedEdge.getVertexId(Direction.IN));
assertEquals(v2, addedEdge.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, addedEdge.getVisibility());
EdgeVertices addedEdgeVertices = addedEdge.getVertices(AUTHORIZATIONS_A);
assertEquals(v1, addedEdgeVertices.getOutVertex());
assertEquals(v2, addedEdgeVertices.getInVertex());
graph.getVertex("v1", FetchHint.NONE, AUTHORIZATIONS_A);
graph.getVertex("v1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
graph.getVertex("v1", FetchHint.EDGE_REFS, AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.IN_EDGE_REFS), AUTHORIZATIONS_A);
graph.getVertex("v1", EnumSet.of(FetchHint.OUT_EDGE_REFS), AUTHORIZATIONS_A);
graph.getEdge("e1", FetchHint.NONE, AUTHORIZATIONS_A);
graph.getEdge("e1", graph.getDefaultFetchHints(), AUTHORIZATIONS_A);
graph.getEdge("e1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
Edge e = graph.getEdge("e1", AUTHORIZATIONS_B);
assertNull(e);
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNotNull(e);
assertEquals("e1", e.getId());
assertEquals("label1", e.getLabel());
assertEquals("v1", e.getVertexId(Direction.OUT));
assertEquals(v1, e.getVertex(Direction.OUT, AUTHORIZATIONS_A));
assertEquals("v2", e.getVertexId(Direction.IN));
assertEquals(v2, e.getVertex(Direction.IN, AUTHORIZATIONS_A));
assertEquals(VISIBILITY_A, e.getVisibility());
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge)
);
}
@Test
public void testGetEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1to2label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2to1", v2.getId(), v1.getId(), "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.BOTH, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.OUT, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, "label1", AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getEdges(v2, Direction.BOTH, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v1.getEdges(v2, Direction.OUT, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v1.getEdges(v2, Direction.IN, new String[]{"label1", "label2"}, AUTHORIZATIONS_A)));
Assert.assertArrayEquals(new String[]{"label1", "label2"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A), String.class));
Assert.assertArrayEquals(new String[]{"label1"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A), String.class));
Assert.assertArrayEquals(new String[]{"label1", "label2"}, IterableUtils.toArray(v1.getEdgeLabels(Direction.BOTH, AUTHORIZATIONS_A), String.class));
}
@Test
public void testGetEdgeVertexPairs() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v2_label1 = graph.addEdge("v1_to_v2_label1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v2_label2 = graph.addEdge("v1_to_v2_label2", v1, v2, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge v1_to_v3_label2 = graph.addEdge("v1_to_v3_label2", v1, v3, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<EdgeVertexPair> pairs = toList(v1.getEdgeVertexPairs(Direction.BOTH, AUTHORIZATIONS_A));
assertEquals(3, pairs.size());
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label1, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label2, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v3_label2, v3)));
pairs = toList(v1.getEdgeVertexPairs(Direction.BOTH, "label2", AUTHORIZATIONS_A));
assertEquals(2, pairs.size());
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v2_label2, v2)));
assertTrue(pairs.contains(new EdgeVertexPair(v1_to_v3_label2, v3)));
}
@Test
public void testAddEdgeWithProperties() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.setProperty("propB", "valueB", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Assert.assertEquals(0, count(e.getPropertyValues("propB")));
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
assertEquals("valueB", e.getPropertyValues("propB").iterator().next());
assertEquals("valueA", e.getPropertyValue("propA"));
assertEquals("valueB", e.getPropertyValue("propB"));
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge),
new AddPropertyEvent(graph, addedEdge, addedEdge.getProperty("propA")),
new AddPropertyEvent(graph, addedEdge, addedEdge.getProperty("propB"))
);
}
@Test
public void testAddEdgeWithNullInOutVertices() {
try {
String outVertexId = null;
String inVertexId = null;
getGraph().prepareEdge("e1", outVertexId, inVertexId, "label", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
try {
Vertex outVertex = null;
Vertex inVertex = null;
getGraph().prepareEdge("e1", outVertex, inVertex, "label", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
}
@Test
public void testAddEdgeWithNullLabels() {
try {
String label = null;
getGraph().prepareEdge("e1", "v1", "v2", label, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
try {
String label = null;
Vertex outVertex = getGraph().addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
Vertex inVertex = getGraph().addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
getGraph().prepareEdge("e1", outVertex, inVertex, label, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
fail("should throw an exception");
} catch (Exception ex) {
assertNotNull(ex);
}
}
@Test
public void testChangingPropertyOnEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Property propA = e.getProperty("", "propA");
assertNotNull(propA);
e.markPropertyHidden(propA, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(0, count(e.getProperties()));
Assert.assertEquals(0, count(e.getPropertyValues("propA")));
e.setProperty(propA.getName(), "valueA_changed", VISIBILITY_B, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA_changed", e.getPropertyValues("propA").iterator().next());
e.markPropertyVisible(propA, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(e.getProperties()));
Assert.assertEquals(2, count(e.getPropertyValues("propA")));
List<Object> propertyValues = IterableUtils.toList(e.getPropertyValues("propA"));
assertTrue(propertyValues.contains("valueA"));
assertTrue(propertyValues.contains("valueA_changed"));
}
@Test
public void testAlterEdgeLabel() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("propA", "valueA", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Edge e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label1", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label1", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label1", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
e.prepareMutation()
.alterEdgeLabel("label2")
.save(AUTHORIZATIONS_A);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label2", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label2", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label2", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
graph.prepareEdge(e.getId(), e.getVertexId(Direction.OUT), e.getVertexId(Direction.IN), e.getLabel(), e.getVisibility())
.alterEdgeLabel("label3")
.save(AUTHORIZATIONS_A);
graph.flush();
e = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals("label3", e.getLabel());
Assert.assertEquals(1, count(e.getProperties()));
assertEquals("valueA", e.getPropertyValues("propA").iterator().next());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals("label3", IterableUtils.single(v1.getEdgeLabels(Direction.OUT, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v2.getEdges(Direction.IN, AUTHORIZATIONS_A)));
Assert.assertEquals("label3", IterableUtils.single(v2.getEdgeLabels(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testDeleteEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge addedEdge = graph.addEdge("e1", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
try {
graph.deleteEdge("e1", AUTHORIZATIONS_B);
} catch (NullPointerException e) {
// expected
}
Assert.assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
graph.deleteEdge("e1", AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(0, count(graph.getEdges(AUTHORIZATIONS_A)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
graph.flush();
assertEvents(
new AddVertexEvent(graph, v1),
new AddVertexEvent(graph, v2),
new AddEdgeEvent(graph, addedEdge),
new DeleteEdgeEvent(graph, addedEdge)
);
}
@Test
public void testAddEdgeWithVisibility() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_B, AUTHORIZATIONS_B);
graph.flush();
Iterable<Edge> aEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A);
Assert.assertEquals(1, count(aEdges));
assertEquals("edgeA", IterableUtils.single(aEdges).getLabel());
Iterable<Edge> bEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_B);
Assert.assertEquals(1, count(bEdges));
assertEquals("edgeB", IterableUtils.single(bEdges).getLabel());
Iterable<Edge> allEdges = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getEdges(Direction.BOTH, AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(allEdges));
}
@Test
public void testGraphQueryForIds() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<String> idsIterable = graph.query(AUTHORIZATIONS_A).vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(1).vertexIds();
assertResultsCount(2, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).limit(1).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(3).vertexIds();
assertResultsCount(0, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).skip(2).limit(2).vertexIds();
assertResultsCount(1, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).edgeIds();
assertIdsAnyOrder(idsIterable, "e1", "e2");
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edgeIds();
assertIdsAnyOrder(idsIterable, "e1");
assertResultsCount(1, 1, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edgeIds();
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).elementIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3", "e1", "e2");
assertResultsCount(5, 5, idsIterable);
assumeTrue("FetchHint.NONE vertex queries are not supported", isFetchHintNoneVertexQuerySupported());
idsIterable = graph.query(AUTHORIZATIONS_A).has("name").vertexIds();
assertIdsAnyOrder(idsIterable, "v1");
assertResultsCount(1, 1, idsIterable);
QueryResultsIterable<ExtendedDataRowId> extendedDataRowIds = graph.query(AUTHORIZATIONS_A).hasExtendedData("table1").extendedDataRowIds();
List<String> rowIds = stream(extendedDataRowIds).map(ExtendedDataRowId::getRowId).collect(Collectors.toList());
assertIdsAnyOrder(rowIds, "row1", "row2");
assertResultsCount(2, 2, extendedDataRowIds);
idsIterable = graph.query(AUTHORIZATIONS_A).hasNot("name").vertexIds();
assertIdsAnyOrder(idsIterable, "v2", "v3");
assertResultsCount(2, 2, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp").vertexIds();
assertResultsCount(0, 0, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).hasNot("notSetProp").vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.NOT_EQUAL, 5).vertexIds();
assertIdsAnyOrder(idsIterable, "v1", "v2", "v3");
assertResultsCount(3, 3, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.EQUAL, 5).vertexIds();
assertResultsCount(0, 0, idsIterable);
idsIterable = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.LESS_THAN_EQUAL, 5).vertexIds();
assertResultsCount(0, 0, idsIterable);
}
@Test
public void testGraphQuery() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e2", v1, v2, "edgeB", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).limit(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(1).vertices();
assertResultsCount(1, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(2).vertices();
assertResultsCount(0, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).skip(1).limit(2).vertices();
assertResultsCount(1, 2, vertices);
QueryResultsIterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertResultsCount(2, 2, edges);
edges = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edges();
assertResultsCount(1, 1, edges);
edges = graph.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edges();
assertResultsCount(2, 2, edges);
QueryResultsIterable<Element> elements = graph.query(AUTHORIZATIONS_A).elements();
assertResultsCount(4, 4, elements);
vertices = graph.query(AUTHORIZATIONS_A).has("name").vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).hasNot("name").vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp").vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).hasNot("notSetProp").vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.NOT_EQUAL, 5).vertices();
assertResultsCount(2, 2, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.EQUAL, 5).vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("notSetProp", Compare.LESS_THAN_EQUAL, 5).vertices();
assertResultsCount(0, 0, vertices);
}
@Test
public void testGraphQueryWithBoolean() {
graph.defineProperty("boolean").dataType(Boolean.class).define();
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "boolean", true, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<Vertex> vertices = graph.query("zzzzz", AUTHORIZATIONS_A).vertices();
assertResultsCount(0, 0, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices();
assertResultsCount(1, 1, vertices);
vertices = graph.query(AUTHORIZATIONS_A).has("boolean", false).vertices();
assertResultsCount(0, 0, vertices);
}
@Test
public void testGraphQueryWithFetchHints() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("k1", "name", "matt", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
assertTrue(graph.getVertexCount(AUTHORIZATIONS_A) == 3);
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("name", "joe")
.vertices(EnumSet.of(FetchHint.PROPERTIES));
assertResultsCount(2, 2, vertices);
assumeTrue("FetchHint.NONE vertex queries are not supported", isFetchHintNoneVertexQuerySupported());
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", "joe")
.vertices(FetchHint.NONE);
assertResultsCount(2, 2, vertices);
}
protected boolean isFetchHintNoneVertexQuerySupported() {
return true;
}
@Test
public void testSaveElementMutations() {
List<ElementMutation> mutations = new ArrayList<>();
for (int i = 0; i < 2; i++) {
ElementBuilder<Vertex> m = graph.prepareVertex("v" + i, VISIBILITY_A)
.addPropertyValue("k1", "name", "joe", VISIBILITY_A)
.addExtendedData("table1", "row1", "col1", "extended", VISIBILITY_A);
mutations.add(m);
}
List<Element> saveVertices = toList(graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL));
graph.flush();
assertEvents(
new AddVertexEvent(graph, (Vertex) saveVertices.get(0)),
new AddPropertyEvent(graph, saveVertices.get(0), saveVertices.get(0).getProperty("k1", "name")),
new AddVertexEvent(graph, (Vertex) saveVertices.get(1)),
new AddPropertyEvent(graph, saveVertices.get(1), saveVertices.get(1).getProperty("k1", "name"))
);
clearGraphEvents();
QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_ALL).vertices();
assertResultsCount(2, 2, vertices);
QueryResultsIterable<? extends VertexiumObject> items = graph.query(AUTHORIZATIONS_ALL)
.has("col1", "extended")
.search();
assertResultsCount(2, 2, items);
mutations.clear();
mutations.add(((Vertex) saveVertices.get(0)).prepareMutation());
graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL);
graph.flush();
assertEvents();
}
@Test
public void testGraphQueryWithQueryString() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_B, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
e1.setProperty("description", "This is edge 1 - dog to cat.", VISIBILITY_A, AUTHORIZATIONS_ALL);
getGraph().flush();
Iterable<Vertex> vertices = graph.query("vertex", AUTHORIZATIONS_A_AND_B).vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query("vertex", AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("dog", AUTHORIZATIONS_B).vertices();
Assert.assertEquals(0, count(vertices));
Iterable<Element> elements = graph.query("dog", AUTHORIZATIONS_A_AND_B).elements();
Assert.assertEquals(2, count(elements));
}
@Test
public void testGraphQueryWithQueryStringWithAuthorizations() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("description", "This is vertex 1 - dog.", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_B, AUTHORIZATIONS_ALL);
v2.setProperty("description", "This is vertex 2 - cat.", VISIBILITY_B, AUTHORIZATIONS_ALL);
Edge e1 = graph.addEdge("e1", v1, v2, "edgeA", VISIBILITY_A, AUTHORIZATIONS_A);
e1.setProperty("edgeDescription", "This is edge 1 - dog to cat.", VISIBILITY_A, AUTHORIZATIONS_ALL);
getGraph().flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
assertEquals(1, count(vertices));
if (isIterableWithTotalHitsSupported(vertices)) {
IterableWithTotalHits hits = (IterableWithTotalHits) vertices;
assertEquals(1, hits.getTotalHits());
}
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A).edges();
assertEquals(1, count(edges));
}
protected boolean isIterableWithTotalHitsSupported(Iterable<Vertex> vertices) {
return vertices instanceof IterableWithTotalHits;
}
@Test
public void testGraphQueryHas() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("text", "hello", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1989, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 24, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("text", "world", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.setProperty("birthDate", new DateOnly(1984, 1, 5), VISIBILITY_A)
.setProperty("lastAccessed", createDate(2014, 2, 25, 13, 0, 5), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age")
.vertices();
Assert.assertEquals(2, count(vertices));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.hasNot("age")
.vertices();
Assert.assertEquals(0, count(vertices));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("hello", AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("birthDate", Compare.EQUAL, createDate(1989, 1, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, createDate(2014, 2, 24, 13, 0, 5))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", 25)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, (int) toList(vertices).get(0).getPropertyValue("age"));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.hasNot("age", 25)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, (int) toList(vertices).get(0).getPropertyValue("age"));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN_EQUAL, 25)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25})
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, (int) toList(vertices).get(0).getPropertyValue("age"));
try {
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.NOT_IN, new Integer[]{25})
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, (int) toList(vertices).get(0).getPropertyValue("age"));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25, 30})
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN, 26)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.LESS_THAN_EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.NOT_EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("lastAccessed", Compare.EQUAL, new DateOnly(2014, 2, 24))
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("*", AUTHORIZATIONS_A)
.has("age", Contains.IN, new Integer[]{25, 30})
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = new CompositeGraphQuery(
graph,
graph.query(AUTHORIZATIONS_A).has("age", 25),
graph.query(AUTHORIZATIONS_A).has("age", 25),
graph.query(AUTHORIZATIONS_A).has("age", 30)
).vertices();
Assert.assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryContainsNotIn() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("status", "0", VISIBILITY_A)
.setProperty("name", "susan", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("status", "1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v5", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v6", VISIBILITY_A)
.setProperty("status", "0", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
try {
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("status", Contains.NOT_IN, new String[]{"0"})
.vertices();
Assert.assertEquals(4, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("status", Contains.NOT_IN, new String[]{"0", "1"})
.vertices();
Assert.assertEquals(3, count(vertices));
} catch (VertexiumNotSupportedException ex) {
LOGGER.warn("skipping. Not supported", ex);
}
}
@Test
public void testGraphQueryHasGeoPointAndExact() {
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.defineProperty("exact").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "val1", VISIBILITY_A)
.setProperty("exact", "val1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop2", "val2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Element> results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("prop1").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("exact").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).has("location").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v1", results.iterator().next().getId());
}
@Test
public void testGraphQueryHasNotGeoPointAndExact() {
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.defineProperty("exact").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "val1", VISIBILITY_A)
.setProperty("exact", "val1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop2", "val2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Element> results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("prop1").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("prop3").sort(Element.ID_PROPERTY_NAME, SortDirection.ASCENDING).elements();
assertEquals(2, count(results));
Iterator<Element> iterator = results.iterator();
assertEquals("v1", iterator.next().getId());
assertEquals("v2", iterator.next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("exact").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
results = graph.query("*", AUTHORIZATIONS_A_AND_B).hasNot("location").elements();
assertEquals(1, count(results));
assertEquals(1, ((IterableWithTotalHits) results).getTotalHits());
assertEquals("v2", results.iterator().next().getId());
}
@Test
public void testGraphQueryHasTwoVisibilities() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "v2", VISIBILITY_A)
.addPropertyValue("k1", "age", 30, VISIBILITY_A)
.addPropertyValue("k2", "age", 35, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "v3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age")
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.hasNot("age")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryIn() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.defineProperty("name").dataType(String.class).sortable(true).textIndexHint(TextIndexHint.ALL).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe ferner", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob smith", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "tom thumb", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<String> strings = new ArrayList<>();
strings.add("joe ferner");
strings.add("tom thumb");
Iterable<Vertex> results = graph.query(AUTHORIZATIONS_A_AND_B).has("name", Contains.IN, strings).vertices();
assertEquals(2, ((IterableWithTotalHits) results).getTotalHits());
assertVertexIdsAnyOrder(results, "v1", "v3");
}
@Test
public void testGraphQuerySort() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.defineProperty("name").dataType(String.class).sortable(true).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "tom", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.setProperty("name", "tom", VISIBILITY_A)
.setProperty("age", 35, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "label2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", "v1", "v2", "label1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", "v1", "v2", "label3", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("age", SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v3", "v4", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("age", SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v4", "v3", "v2", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
assertEquals("v2", vertices.get(0).getId());
assertEquals("v1", vertices.get(1).getId());
assertTrue(vertices.get(2).getId().equals("v3") || vertices.get(2).getId().equals("v4"));
assertTrue(vertices.get(3).getId().equals("v3") || vertices.get(3).getId().equals("v4"));
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.DESCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
assertTrue(vertices.get(0).getId().equals("v3") || vertices.get(0).getId().equals("v4"));
assertTrue(vertices.get(1).getId().equals("v3") || vertices.get(1).getId().equals("v4"));
assertEquals("v1", vertices.get(2).getId());
assertEquals("v2", vertices.get(3).getId());
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.sort("age", SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v1", "v3", "v4");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("name", SortDirection.ASCENDING)
.sort("age", SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v2", "v1", "v4", "v3");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Element.ID_PROPERTY_NAME, SortDirection.ASCENDING)
.vertices());
assertVertexIds(vertices, "v1", "v2", "v3", "v4");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Element.ID_PROPERTY_NAME, SortDirection.DESCENDING)
.vertices());
assertVertexIds(vertices, "v4", "v3", "v2", "v1");
vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort("otherfield", SortDirection.ASCENDING)
.vertices());
Assert.assertEquals(4, count(vertices));
List<Edge> edges = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Edge.LABEL_PROPERTY_NAME, SortDirection.ASCENDING)
.edges());
assertEdgeIds(edges, new String[]{"e2", "e1", "e3"});
edges = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.sort(Edge.LABEL_PROPERTY_NAME, SortDirection.DESCENDING)
.edges());
assertEdgeIds(edges, new String[]{"e3", "e1", "e2"});
}
@Test
public void testGraphQuerySortOnPropertyThatHasNoValuesInTheIndex() {
graph.defineProperty("age").dataType(Integer.class).sortable(true).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "joe", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "bob", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
QueryResultsIterable<Vertex> vertices
= graph.query(AUTHORIZATIONS_A).sort("age", SortDirection.ASCENDING).vertices();
Assert.assertEquals(2, count(vertices));
}
@Test
public void testGraphQuerySortOnPropertyWhichIsFullTextAndExactMatchIndexed() {
graph.defineProperty("name")
.dataType(String.class)
.sortable(true)
.textIndexHint(TextIndexHint.EXACT_MATCH, TextIndexHint.FULL_TEXT)
.define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "1-2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "1-1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("name", "3-1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
QueryResultsIterable<Vertex> vertices
= graph.query(AUTHORIZATIONS_A_AND_B).sort("name", SortDirection.ASCENDING).vertices();
assertVertexIds(vertices, "v2", "v1", "v3");
vertices = graph.query("3", AUTHORIZATIONS_A_AND_B).vertices();
assertVertexIds(vertices, "v3");
vertices = graph.query("*", AUTHORIZATIONS_A_AND_B)
.has("name", Compare.EQUAL, "3-1")
.vertices();
assertVertexIds(vertices, "v3");
}
@Test
public void testGraphQueryVertexHasWithSecurity() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(1, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = graph.query(AUTHORIZATIONS_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices)); // need auth A to see the v2 node itself
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(0, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(2, count(vertices));
if (vertices instanceof IterableWithTotalHits) {
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
}
}
@Test
public void testGraphQueryVertexHasWithSecurityGranularity() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("description", "v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("description", "v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.vertices();
boolean hasAgeVisA = false;
boolean hasAgeVisB = false;
for (Vertex v : vertices) {
Property prop = v.getProperty("age");
if (prop == null) {
continue;
}
if ((Integer) prop.getValue() == 25) {
if (prop.getVisibility().equals(VISIBILITY_A)) {
hasAgeVisA = true;
} else if (prop.getVisibility().equals(VISIBILITY_B)) {
hasAgeVisB = true;
}
}
}
assertEquals(2, count(vertices));
assertTrue("has a", hasAgeVisA);
assertFalse("has b", hasAgeVisB);
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.vertices();
assertEquals(2, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityComplexFormula() {
graph.prepareVertex("v1", VISIBILITY_MIXED_CASE_a)
.setProperty("age", 25, VISIBILITY_MIXED_CASE_a)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_MIXED_CASE_a_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGetVertexWithBadAuthorizations() {
graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.flush();
try {
graph.getVertex("v1", AUTHORIZATIONS_BAD);
throw new RuntimeException("Should throw " + SecurityVertexiumException.class.getSimpleName());
} catch (SecurityVertexiumException ex) {
// ok
}
}
@Test
public void testGraphQueryVertexNoVisibility() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("text", "hello", VISIBILITY_EMPTY)
.setProperty("age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query("hello", AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("hello", AUTHORIZATIONS_A_AND_B)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexWithVisibilityChange() {
graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
// change to same visibility
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1 = v1.prepareMutation()
.alterElementVisibility(VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
Assert.assertEquals(VISIBILITY_EMPTY, v1.getVisibility());
vertices = graph.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeVertex() {
graph.prepareVertex("v1", VISIBILITY_B)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryVertexHasWithSecurityCantSeeProperty() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(0, count(vertices));
}
@Test
public void testGraphQueryEdgeHasWithSecurity() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", v1, v3, "edge", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.edges();
Assert.assertEquals(1, count(edges));
}
@Test
public void testGraphQueryUpdateVertex() throws NoSuchFieldException, IllegalAccessException {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.prepareVertex("v3", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.addEdge("v2tov3", v2, v3, "", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.setProperty("name", "Bob", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.setProperty("name", "Same", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> allVertices = toList(graph.query(AUTHORIZATIONS_A_AND_B).vertices());
Assert.assertEquals(3, count(allVertices));
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("name", Compare.EQUAL, "Joe")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("age", Compare.EQUAL, 25)
.has("name", Compare.EQUAL, "Joe")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testQueryWithVertexIds() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("age", 35, VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<Vertex> vertices = toList(graph.query(new String[]{"v1", "v2"}, AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 27)
.vertices());
Assert.assertEquals(1, vertices.size());
assertEquals("v2", vertices.get(0).getId());
vertices = toList(graph.query(new String[]{"v1", "v2", "v3"}, AUTHORIZATIONS_A)
.has("age", Compare.GREATER_THAN, 27)
.vertices());
Assert.assertEquals(2, vertices.size());
List<String> vertexIds = toList(new ConvertingIterable<Vertex, String>(vertices) {
@Override
protected String convert(Vertex o) {
return o.getId();
}
});
Assert.assertTrue("v2 not found", vertexIds.contains("v2"));
Assert.assertTrue("v3 not found", vertexIds.contains("v3"));
}
@Test
public void testDisableEdgeIndexing() throws NoSuchFieldException, IllegalAccessException {
assumeTrue("disabling indexing not supported", disableEdgeIndexing(graph));
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "edge", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A)
.has("prop1", "value1")
.edges();
Assert.assertEquals(0, count(edges));
}
@Test
public void testGraphQueryHasWithSpaces() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithNonAlphaCharacters", "hyphen-word, etc.", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query("Ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query("joe", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(2, count(vertices));
if (isLuceneQueriesSupported()) {
vertices = graph.query("joe AND ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
if (isLuceneQueriesSupported()) {
vertices = graph.query("joe smith", AUTHORIZATIONS_A)
.vertices();
List<Vertex> verticesList = toList(vertices);
assertEquals(2, verticesList.size());
boolean foundV1 = false;
boolean foundV2 = false;
for (Vertex v : verticesList) {
if (v.getId().equals("v1")) {
foundV1 = true;
} else if (v.getId().equals("v2")) {
foundV2 = true;
} else {
throw new RuntimeException("Invalid vertex id: " + v.getId());
}
}
assertTrue(foundV1);
assertTrue(foundV2);
}
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe")
.has("name", TextPredicate.CONTAINS, "Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("name", TextPredicate.CONTAINS, "Joe Ferner")
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.has("propWithNonAlphaCharacters", TextPredicate.CONTAINS, "hyphen-word, etc.")
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryWithANDOperatorAndWithExactMatchFields() {
graph.defineProperty("firstName").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("firstName", "Joe", VISIBILITY_A)
.setProperty("lastName", "Ferner", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("firstName", "Joe", VISIBILITY_A)
.setProperty("lastName", "Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assumeTrue("lucene and queries not supported", isLuceneQueriesSupported() && isLuceneAndQueriesSupported());
Iterable<Vertex> vertices = graph.query("Joe AND ferner", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
@Test
public void testGraphQueryHasWithSpacesAndFieldedQueryString() {
assumeTrue("fielded query not supported", isFieldNamesInQuerySupported());
graph.defineProperty("http://vertexium.org#name").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("http://vertexium.org#name", "Joe Ferner", VISIBILITY_A)
.setProperty("propWithHyphen", "hyphen-word", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("http://vertexium.org#name", "Joe Smith", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assumeTrue("lucene queries", isLuceneQueriesSupported());
Iterable<Vertex> vertices = graph.query("http\\:\\/\\/vertexium.org#name:Joe", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query("http\\:\\/\\/vertexium.org#name:\"Joe Ferner\"", AUTHORIZATIONS_A)
.vertices();
Assert.assertEquals(1, count(vertices));
}
protected boolean isFieldNamesInQuerySupported() {
return true;
}
protected boolean isLuceneQueriesSupported() {
return !(graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery);
}
protected boolean isLuceneAndQueriesSupported() {
return !(graph.query(AUTHORIZATIONS_A) instanceof DefaultGraphQuery);
}
@Test
public void testStoreGeoPoint() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9186, -77.2297, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("location", new GeoPoint(38.9544, -77.3464, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 1))
.vertices());
Assert.assertEquals(1, count(vertices));
GeoPoint geoPoint = (GeoPoint) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoPoint.getLatitude(), 0.001);
assertEquals(-77.2297, geoPoint.getLongitude(), 0.001);
assertEquals("Reston, VA", geoPoint.getDescription());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.9186, -77.2297, 25))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoRect(new GeoPoint(39, -78), new GeoPoint(38, -77)))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoHash(38.9186, -77.2297, 2))
.vertices());
Assert.assertEquals(2, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", GeoCompare.WITHIN, new GeoHash(38.9186, -77.2297, 3))
.vertices());
Assert.assertEquals(1, count(vertices));
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("location", TextPredicate.CONTAINS, "Reston")
.vertices());
Assert.assertEquals(2, count(vertices));
}
@Test
public void testStoreGeoCircle() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("location", new GeoCircle(38.9186, -77.2297, 100, "Reston, VA"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A_AND_B)
.has("location", GeoCompare.WITHIN, new GeoCircle(38.92, -77.23, 10))
.vertices());
Assert.assertEquals(1, count(vertices));
GeoCircle geoCircle = (GeoCircle) vertices.get(0).getPropertyValue("location");
assertEquals(38.9186, geoCircle.getLatitude(), 0.001);
assertEquals(-77.2297, geoCircle.getLongitude(), 0.001);
assertEquals(100.0, geoCircle.getRadius(), 0.001);
assertEquals("Reston, VA", geoCircle.getDescription());
}
private Date createDate(int year, int month, int day) {
return new GregorianCalendar(year, month, day).getTime();
}
private Date createDate(int year, int month, int day, int hour, int min, int sec) {
return new GregorianCalendar(year, month, day, hour, min, sec).getTime();
}
@Test
public void testGraphQueryRange() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("age", 25, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 25)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 20, 29)
.vertices();
Assert.assertEquals(1, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, 30)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, true, 30, false)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(25, toList(vertices).get(0).getPropertyValue("age"));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, false, 30, true)
.vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(30, toList(vertices).get(0).getPropertyValue("age"));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, true, 30, true)
.vertices();
Assert.assertEquals(2, count(vertices));
vertices = graph.query(AUTHORIZATIONS_A)
.range("age", 25, false, 30, false)
.vertices();
Assert.assertEquals(0, count(vertices));
}
@Test
public void testVertexQuery() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.setProperty("prop1", "value1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
v2.setProperty("prop1", "value2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
v3.setProperty("prop1", "value3", VISIBILITY_A, AUTHORIZATIONS_ALL);
Edge ev1v2 = graph.prepareEdge("e v1->v2", v1, v2, "edgeA", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Edge ev1v3 = graph.prepareEdge("e v1->v3", v1, v3, "edgeB", VISIBILITY_A)
.setProperty("prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e v2->v3", v2, v3, "edgeB", VISIBILITY_A)
.setProperty("prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Iterable<Vertex> vertices = v1.query(AUTHORIZATIONS_A).vertices();
Assert.assertEquals(2, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
org.vertexium.test.util.IterableUtils.assertContains(v3, vertices);
if (isIterableWithTotalHitsSupported(vertices)) {
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
vertices = v1.query(AUTHORIZATIONS_A).limit(1).vertices();
Assert.assertEquals(1, count(vertices));
Assert.assertEquals(2, ((IterableWithTotalHits) vertices).getTotalHits());
}
vertices = v1.query(AUTHORIZATIONS_A)
.has("prop1", "value2")
.vertices();
Assert.assertEquals(1, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
Iterable<Edge> edges = v1.query(AUTHORIZATIONS_A).edges();
Assert.assertEquals(2, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA", "edgeB").edges();
Assert.assertEquals(2, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3, edges);
edges = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").edges();
Assert.assertEquals(1, count(edges));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2, edges);
vertices = v1.query(AUTHORIZATIONS_A).hasEdgeLabel("edgeA").vertices();
Assert.assertEquals(1, count(vertices));
org.vertexium.test.util.IterableUtils.assertContains(v2, vertices);
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.OUT).vertices(), "v2", "v3");
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.IN).vertices());
assertEdgeIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.OUT).edges(), "e v1->v2", "e v1->v3");
assertEdgeIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasDirection(Direction.IN).edges());
assertVertexIdsAnyOrder(v1.query(AUTHORIZATIONS_A).hasOtherVertexId("v2").vertices(), "v2");
assertEdgeIds(v1.query(AUTHORIZATIONS_A).hasOtherVertexId("v2").edges(), "e v1->v2");
}
@Test
public void testFindPaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v6 = graph.addVertex("v6", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v2
graph.addEdge(v2, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v3, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v5
graph.addEdge(v4, v6, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v6
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2), AUTHORIZATIONS_A));
List<Path> pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
List<Path> pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2", "v4"),
new Path("v1", "v3", "v4")
);
paths = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v4", "v1", 2).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v4", "v2", "v1"),
new Path("v4", "v3", "v1")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3), AUTHORIZATIONS_A));
pathsByLabels = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3).setLabels("knows"), AUTHORIZATIONS_A));
assertEquals(pathsByLabels, paths);
pathsByBadLabel = toList(graph.findPaths(new FindPathOptions("v1", "v6", 3).setLabels("bad"), AUTHORIZATIONS_A));
assertEquals(0, pathsByBadLabel.size());
assertPaths(
paths,
new Path("v1", "v2", "v4", "v6"),
new Path("v1", "v3", "v4", "v6")
);
}
@Test
public void testFindPathExcludeLabels() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v4, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "b", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v3, v4, "a", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 2), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4"),
new Path("v1", "v3", "v4")
);
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 2).setExcludedLabels("b"), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4")
);
assertPaths(
graph.findPaths(new FindPathOptions("v1", "v4", 3).setExcludedLabels("b"), AUTHORIZATIONS_A),
new Path("v1", "v2", "v4")
);
}
private void assertPaths(Iterable<Path> found, Path... expected) {
List<Path> foundPaths = toList(found);
List<Path> expectedPaths = new ArrayList<>();
Collections.addAll(expectedPaths, expected);
assertEquals(expectedPaths.size(), foundPaths.size());
for (Path foundPath : foundPaths) {
if (!expectedPaths.remove(foundPath)) {
fail("Unexpected path: " + foundPath);
}
}
}
@Test
public void testFindPathsWithSoftDeletedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_EMPTY, AUTHORIZATIONS_A);
graph.addEdge(v1, v2, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A); // v1 -> v2
Edge v2ToV3 = graph.addEdge(v2, v3, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A); // v2 -> v3
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v2", "v3")
);
graph.softDeleteEdge(v2ToV3, AUTHORIZATIONS_A);
graph.flush();
assertNull(graph.getEdge(v2ToV3.getId(), AUTHORIZATIONS_A));
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
}
@Test
public void testFindPathsWithHiddenEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
Vertex v3 = graph.addVertex("v3", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B); // v1 -> v2
Edge v2ToV3 = graph.addEdge(v2, v3, "knows", VISIBILITY_EMPTY, AUTHORIZATIONS_A_AND_B); // v2 -> v3
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A_AND_B));
assertPaths(
paths,
new Path("v1", "v2", "v3")
);
graph.markEdgeHidden(v2ToV3, VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
assertNull(graph.getEdge(v2ToV3.getId(), AUTHORIZATIONS_A_AND_B));
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v3", 2), AUTHORIZATIONS_B));
assertEquals(1, paths.size());
}
@Test
public void testFindPathsMultiplePaths() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v4
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 2), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2"),
new Path("v1", "v3", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v2", 3), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2"),
new Path("v1", "v3", "v2"),
new Path("v1", "v3", "v4", "v2"),
new Path("v1", "v4", "v3", "v2")
);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 2), AUTHORIZATIONS_A));
assertPaths(paths);
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 3), AUTHORIZATIONS_A));
assertPaths(
paths,
new Path("v1", "v4", "v2", "v5"),
new Path("v1", "v3", "v2", "v5")
);
}
@Test
public void testHasPath() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v1 -> v3
graph.addEdge(v3, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v3 -> v4
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v3
graph.addEdge(v4, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v4 -> v2
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A); // v2 -> v5
graph.flush();
List<Path> paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 2, true), AUTHORIZATIONS_A));
assertEquals(1, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v4", 3, true), AUTHORIZATIONS_A));
assertEquals(1, paths.size());
paths = toList(graph.findPaths(new FindPathOptions("v1", "v5", 2, true), AUTHORIZATIONS_A));
assertEquals(0, paths.size());
}
@Test
public void testGetVerticesFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v1.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v2.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v3.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v3.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v3.getVertices(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v4.getVertices(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v4.getVertices(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v4.getVertices(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testGetVertexIdsFromVertex() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v5 = graph.addVertex("v5", VISIBILITY_B, AUTHORIZATIONS_B);
graph.addEdge(v1, v2, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v1, v4, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v3, "knows", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge(v2, v5, "knows", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v1.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(3, count(v1.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v1.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v2 = graph.getVertex("v2", AUTHORIZATIONS_A);
Assert.assertEquals(3, count(v2.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v2.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v2.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v3 = graph.getVertex("v3", AUTHORIZATIONS_A);
Assert.assertEquals(2, count(v3.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v3.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(2, count(v3.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
v4 = graph.getVertex("v4", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v4.getVertexIds(Direction.BOTH, AUTHORIZATIONS_A)));
Assert.assertEquals(0, count(v4.getVertexIds(Direction.OUT, AUTHORIZATIONS_A)));
Assert.assertEquals(1, count(v4.getVertexIds(Direction.IN, AUTHORIZATIONS_A)));
}
@Test
public void testBlankVisibilityString() {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
graph.flush();
v = graph.getVertex("v1", AUTHORIZATIONS_EMPTY);
assertNotNull(v);
assertEquals("v1", v.getId());
assertEquals(VISIBILITY_EMPTY, v.getVisibility());
}
@Test
public void testElementMutationDoesntChangeObjectUntilSave() throws InterruptedException {
Vertex v = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL);
v.setProperty("prop1", "value1-1", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
ElementMutation<Vertex> m = v.prepareMutation()
.setProperty("prop1", "value1-2", VISIBILITY_A)
.setProperty("prop2", "value2-2", VISIBILITY_A);
Assert.assertEquals(1, count(v.getProperties()));
assertEquals("value1-1", v.getPropertyValue("prop1"));
v = m.save(AUTHORIZATIONS_A_AND_B);
Assert.assertEquals(2, count(v.getProperties()));
assertEquals("value1-2", v.getPropertyValue("prop1"));
assertEquals("value2-2", v.getPropertyValue("prop2"));
}
@Test
public void testFindRelatedEdges() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIds(vertexIds, AUTHORIZATIONS_A));
Assert.assertEquals(4, count(edgeIds));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev2v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev3v1.getId(), edgeIds);
}
@Test
public void testFindRelatedEdgeIdsForVertices() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v2 = graph.addEdge("e v1->v2", v1, v2, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev1v3 = graph.addEdge("e v1->v3", v1, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev2v3 = graph.addEdge("e v2->v3", v2, v3, "", VISIBILITY_A, AUTHORIZATIONS_A);
Edge ev3v1 = graph.addEdge("e v3->v1", v3, v1, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
List<Vertex> vertices = new ArrayList<>();
vertices.add(v1);
vertices.add(v2);
vertices.add(v3);
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIdsForVertices(vertices, AUTHORIZATIONS_A));
Assert.assertEquals(4, count(edgeIds));
org.vertexium.test.util.IterableUtils.assertContains(ev1v2.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev1v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev2v3.getId(), edgeIds);
org.vertexium.test.util.IterableUtils.assertContains(ev3v1.getId(), edgeIds);
}
@Test
public void testFindRelatedEdgeSummary() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v4 = graph.addVertex("v4", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v1->v3", v1, v3, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v2->v3", v2, v3, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v1", v3, v1, "label2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e v3->v4", v3, v4, "", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
vertexIds.add("v3");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(4, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v3", "label1", v1.getId(), v3.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v2->v3", "label2", v2.getId(), v3.getId()), relatedEdges);
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v3->v1", "label2", v3.getId(), v1.getId()), relatedEdges);
}
@Test
public void testFindRelatedEdgeSummaryAfterSoftDelete() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(1, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
graph.softDeleteEdge(e1, AUTHORIZATIONS_A);
graph.flush();
relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(0, relatedEdges.size());
}
@Test
public void testFindRelatedEdgeSummaryAfterMarkedHidden() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Edge e1 = graph.addEdge("e v1->v2", v1, v2, "label1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
vertexIds.add("v2");
List<RelatedEdge> relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(1, relatedEdges.size());
org.vertexium.test.util.IterableUtils.assertContains(new RelatedEdgeImpl("e v1->v2", "label1", v1.getId(), v2.getId()), relatedEdges);
graph.markEdgeHidden(e1, VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
relatedEdges = toList(graph.findRelatedEdgeSummary(vertexIds, AUTHORIZATIONS_A));
assertEquals(0, relatedEdges.size());
}
// Test for performance
//@Test
@SuppressWarnings("unused")
private void testFindRelatedEdgesPerformance() {
int totalNumberOfVertices = 100;
int totalNumberOfEdges = 10000;
int totalVerticesToCheck = 100;
Date startTime, endTime;
Random random = new Random(100);
startTime = new Date();
List<Vertex> vertices = new ArrayList<>();
for (int i = 0; i < totalNumberOfVertices; i++) {
vertices.add(graph.addVertex("v" + i, VISIBILITY_A, AUTHORIZATIONS_A));
}
graph.flush();
endTime = new Date();
long insertVerticesTime = endTime.getTime() - startTime.getTime();
startTime = new Date();
for (int i = 0; i < totalNumberOfEdges; i++) {
Vertex outVertex = vertices.get(random.nextInt(vertices.size()));
Vertex inVertex = vertices.get(random.nextInt(vertices.size()));
graph.addEdge("e" + i, outVertex, inVertex, "", VISIBILITY_A, AUTHORIZATIONS_A);
}
graph.flush();
endTime = new Date();
long insertEdgesTime = endTime.getTime() - startTime.getTime();
List<String> vertexIds = new ArrayList<>();
for (int i = 0; i < totalVerticesToCheck; i++) {
Vertex v = vertices.get(random.nextInt(vertices.size()));
vertexIds.add(v.getId());
}
startTime = new Date();
Iterable<String> edgeIds = toList(graph.findRelatedEdgeIds(vertexIds, AUTHORIZATIONS_A));
count(edgeIds);
endTime = new Date();
long findRelatedEdgesTime = endTime.getTime() - startTime.getTime();
LOGGER.info(
"RESULTS\ntotalNumberOfVertices,totalNumberOfEdges,totalVerticesToCheck,insertVerticesTime,insertEdgesTime,findRelatedEdgesTime\n%d,%d,%d,%d,%d,%d",
totalNumberOfVertices,
totalNumberOfEdges,
totalVerticesToCheck,
insertVerticesTime,
insertEdgesTime,
findRelatedEdgesTime
);
}
@Test
public void testFilterEdgeIdsByAuthorization() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
graph.prepareEdge("e1", v1, v2, "label", VISIBILITY_A)
.setProperty("propA", "propA", VISIBILITY_A)
.setProperty("propB", "propB", VISIBILITY_A_AND_B)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
List<String> edgeIds = new ArrayList<>();
edgeIds.add("e1");
List<String> foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_B_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_B_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("e1", foundEdgeIds);
foundEdgeIds = toList(graph.filterEdgeIdsByAuthorization(edgeIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
assertEquals(0, foundEdgeIds.size());
}
@Test
public void testFilterVertexIdsByAuthorization() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propA", "propA", VISIBILITY_A)
.setProperty("propB", "propB", VISIBILITY_A_AND_B)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
List<String> vertexIds = new ArrayList<>();
vertexIds.add("v1");
List<String> foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_B_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, ElementFilter.ALL, AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_B_STRING, EnumSet.of(ElementFilter.ELEMENT), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_A_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
org.vertexium.test.util.IterableUtils.assertContains("v1", foundVertexIds);
foundVertexIds = toList(graph.filterVertexIdsByAuthorization(vertexIds, VISIBILITY_C_STRING, EnumSet.of(ElementFilter.PROPERTY_METADATA), AUTHORIZATIONS_ALL));
assertEquals(0, foundVertexIds.size());
}
@Test
public void testMetadataMutationsOnVertex() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
Vertex vertex = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
ExistingElementMutation<Vertex> m = vertex.prepareMutation();
m.setPropertyMetadata("propBmeta", "meta1", "meta2", VISIBILITY_A);
vertex = m.save(AUTHORIZATIONS_ALL);
assertEquals("meta2", vertex.getProperty("propBmeta").getMetadata().getEntry("meta1").getValue());
}
@Test
public void testMetadataMutationsOnEdge() {
Metadata metadataPropB = new Metadata();
metadataPropB.add("meta1", "meta1", VISIBILITY_A);
Edge edge = graph.prepareEdge("v1", "v2", "label", VISIBILITY_A)
.setProperty("propBmeta", "propBmeta", metadataPropB, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.flush();
ExistingElementMutation<Edge> m = edge.prepareMutation();
m.setPropertyMetadata("propBmeta", "meta1", "meta2", VISIBILITY_A);
edge = m.save(AUTHORIZATIONS_ALL);
assertEquals("meta2", edge.getProperty("propBmeta").getMetadata().getEntry("meta1").getValue());
}
@Test
public void testEmptyPropertyMutation() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
v1.prepareMutation().save(AUTHORIZATIONS_ALL);
}
@Test
public void testTextIndex() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define(); // try calling define twice
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("none", "Test Value", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.setProperty("fullText", "Test Value", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals("Test Value", v1.getPropertyValue("none"));
assertEquals("Test Value", v1.getPropertyValue("both"));
assertEquals("Test Value", v1.getPropertyValue("fullText"));
assertEquals("Test Value", v1.getPropertyValue("exactMatch"));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals("exact match shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", "Test Value").vertices()));
Assert.assertEquals("default has predicate is equals which shouldn't work for full text", 0, count(graph.query(AUTHORIZATIONS_A).has("fullText", "Test Value").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", "Test Value").vertices()));
if (count(graph.query(AUTHORIZATIONS_A).has("none", "Test Value").vertices()) != 0) {
LOGGER.warn("default has predicate is equals which shouldn't work for un-indexed");
}
}
@Test
public void testTextIndexDoesNotContain() throws Exception {
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("exactMatch").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("exactMatch", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("both", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("both", "Temp", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.DOES_NOT_CONTAIN, "Test").vertices()));
Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test").vertices()));
Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test Value").vertices()));
}
@Test
public void testTextIndexStreamingPropertyValue() throws Exception {
graph.defineProperty("none").dataType(String.class).textIndexHint(TextIndexHint.NONE).define();
graph.defineProperty("both").dataType(String.class).textIndexHint(TextIndexHint.ALL).define();
graph.defineProperty("fullText").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("none", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.setProperty("both", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.setProperty("fullText", StreamingPropertyValue.create("Test Value"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("fullText", TextPredicate.CONTAINS, "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", "Test").vertices()));
Assert.assertEquals("un-indexed property shouldn't match partials", 0, count(graph.query(AUTHORIZATIONS_A).has("none", TextPredicate.CONTAINS, "Test").vertices()));
}
@Test
public void testGetStreamingPropertyValueInputStreams() throws Exception {
graph.defineProperty("a").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("b").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.defineProperty("c").dataType(String.class).textIndexHint(TextIndexHint.FULL_TEXT).define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("a", StreamingPropertyValue.create("Test Value A"), VISIBILITY_A)
.setProperty("b", StreamingPropertyValue.create("Test Value B"), VISIBILITY_A)
.setProperty("c", StreamingPropertyValue.create("Test Value C"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
StreamingPropertyValue spvA = (StreamingPropertyValue) v1.getPropertyValue("a");
StreamingPropertyValue spvB = (StreamingPropertyValue) v1.getPropertyValue("b");
StreamingPropertyValue spvC = (StreamingPropertyValue) v1.getPropertyValue("c");
ArrayList<StreamingPropertyValue> spvs = Lists.newArrayList(spvA, spvB, spvC);
List<InputStream> streams = graph.getStreamingPropertyValueInputStreams(spvs);
assertEquals("Test Value A", IOUtils.toString(streams.get(0)));
assertEquals("Test Value B", IOUtils.toString(streams.get(1)));
assertEquals("Test Value C", IOUtils.toString(streams.get(2)));
}
@Test
public void testFieldBoost() throws Exception {
assumeTrue("Boost not supported", graph.isFieldBoostSupported());
graph.defineProperty("a")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(1)
.define();
graph.defineProperty("b")
.dataType(String.class)
.textIndexHint(TextIndexHint.ALL)
.boost(2)
.define();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("a", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("b", "Test Value", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
assertVertexIds(graph.query("Test", AUTHORIZATIONS_A).vertices(), "v2", "v1");
}
@Test
public void testValueTypes() throws Exception {
Date date = createDate(2014, 2, 24, 13, 0, 5);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("int", 5, VISIBILITY_A)
.setProperty("bigInteger", BigInteger.valueOf(10), VISIBILITY_A)
.setProperty("bigDecimal", BigDecimal.valueOf(1.1), VISIBILITY_A)
.setProperty("double", 5.6, VISIBILITY_A)
.setProperty("float", 6.4f, VISIBILITY_A)
.setProperty("string", "test", VISIBILITY_A)
.setProperty("byte", (byte) 5, VISIBILITY_A)
.setProperty("long", (long) 5, VISIBILITY_A)
.setProperty("boolean", true, VISIBILITY_A)
.setProperty("geopoint", new GeoPoint(77, -33), VISIBILITY_A)
.setProperty("short", (short) 5, VISIBILITY_A)
.setProperty("date", date, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("int", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("double", 5.6).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).range("float", 6.3f, 6.5f).vertices())); // can't search for 6.4f her because of float precision
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("string", "test").vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("byte", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("long", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("boolean", true).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("short", 5).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("date", date).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigInteger", BigInteger.valueOf(10)).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigInteger", 10).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", BigDecimal.valueOf(1.1)).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("bigDecimal", 1.1).vertices()));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_A).has("geopoint", GeoCompare.WITHIN, new GeoCircle(77, -33, 1)).vertices()));
}
@Test
public void testChangeVisibilityVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
// change to same visibility
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1);
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
assertNotNull(v1);
}
@Test
public void testChangeVertexVisibilityAndAlterPropertyVisibilityAndChangePropertyAtTheSameTime() {
Metadata metadata = new Metadata();
metadata.add("m1", "m1-value1", VISIBILITY_EMPTY);
metadata.add("m2", "m2-value1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.createAuthorizations(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_ALL);
ExistingElementMutation<Vertex> m = v1.prepareMutation();
m.alterElementVisibility(VISIBILITY_B);
for (Property property : v1.getProperties()) {
m.alterPropertyVisibility(property, VISIBILITY_B);
m.setPropertyMetadata(property, "m1", "m1-value2", VISIBILITY_EMPTY);
}
m.save(AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_B);
assertEquals(VISIBILITY_B, v1.getVisibility());
List<Property> properties = toList(v1.getProperties());
assertEquals(1, properties.size());
assertEquals("age", properties.get(0).getName());
assertEquals(VISIBILITY_B, properties.get(0).getVisibility());
assertEquals(2, properties.get(0).getMetadata().entrySet().size());
assertTrue(properties.get(0).getMetadata().containsKey("m1"));
assertEquals("m1-value2", properties.get(0).getMetadata().getEntry("m1").getValue());
assertEquals(VISIBILITY_EMPTY, properties.get(0).getMetadata().getEntry("m1").getVisibility());
assertTrue(properties.get(0).getMetadata().containsKey("m2"));
assertEquals("m2-value1", properties.get(0).getMetadata().getEntry("m2").getValue());
assertEquals(VISIBILITY_EMPTY, properties.get(0).getMetadata().getEntry("m2").getVisibility());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull("v1 should not be returned for auth a", v1);
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_B)
.has("age", Compare.EQUAL, 25)
.vertices());
assertEquals(1, vertices.size());
vertices = toList(graph.query(AUTHORIZATIONS_A)
.has("age", Compare.EQUAL, 25)
.vertices());
assertEquals(0, vertices.size());
}
@Test
public void testChangeVisibilityPropertiesWithPropertyKey() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("k1", "prop1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop1", "value1").vertices()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop1", "value1").vertices()));
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value1"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value1"));
}
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
Property v1Prop1 = v1.getProperty("prop1");
assertNotNull(v1Prop1);
assertEquals(VISIBILITY_B, v1Prop1.getVisibility());
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_EMPTY)
.addPropertyValue("k2", "prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
e1.prepareMutation()
.alterPropertyVisibility("k2", "prop2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
assertNull(e1.getProperty("prop2"));
assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop2", "value2").edges()));
assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop2", "value2").edges()));
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop2", ElementType.EDGE, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value2"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop2", ElementType.EDGE, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value2"));
}
e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
Property e1prop1 = e1.getProperty("prop2");
assertNotNull(e1prop1);
assertEquals(VISIBILITY_B, e1prop1.getVisibility());
}
@Test
public void testChangeVisibilityVertexProperties() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "value1", VISIBILITY_EMPTY);
Metadata prop2Metadata = new Metadata();
prop2Metadata.add("prop2_key1", "value1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.setProperty("prop2", "value2", prop2Metadata, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertNull(v1.getProperty("prop1"));
assertNotNull(v1.getProperty("prop2"));
Assert.assertEquals(1, count(graph.query(AUTHORIZATIONS_B).has("prop1", "value1").vertices()));
Assert.assertEquals(0, count(graph.query(AUTHORIZATIONS_A).has("prop1", "value1").vertices()));
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_A);
if (propertyCountByValue != null) {
assertEquals(null, propertyCountByValue.get("value1"));
}
propertyCountByValue = queryGraphQueryWithTermsAggregation("prop1", ElementType.VERTEX, AUTHORIZATIONS_B);
if (propertyCountByValue != null) {
assertEquals(1L, (long) propertyCountByValue.get("value1"));
}
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property v1Prop1 = v1.getProperty("prop1");
assertNotNull(v1Prop1);
Assert.assertEquals(1, toList(v1Prop1.getMetadata().entrySet()).size());
assertEquals("value1", v1Prop1.getMetadata().getValue("prop1_key1"));
assertNotNull(v1.getProperty("prop2"));
// alter and set property in one mutation
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New", v1.getPropertyValue("prop1"));
// alter visibility to the same visibility
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_A)
.setProperty("prop1", "value1New2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals("value1New2", v1.getPropertyValue("prop1"));
}
@Test
public void testAlterVisibilityAndSetMetadataInOneMutation() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "metadata1", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterPropertyVisibility("prop1", VISIBILITY_B)
.setPropertyMetadata("prop1", "prop1_key1", "metadata1New", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
assertNotNull(v1.getProperty("prop1"));
assertEquals(VISIBILITY_B, v1.getProperty("prop1").getVisibility());
assertEquals("metadata1New", v1.getProperty("prop1").getMetadata().getValue("prop1_key1"));
List<HistoricalPropertyValue> historicalPropertyValues = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
assertEquals(2, historicalPropertyValues.size());
assertEquals("metadata1New", historicalPropertyValues.get(0).getMetadata().getValue("prop1_key1"));
assertEquals("metadata1", historicalPropertyValues.get(1).getMetadata().getValue("prop1_key1"));
}
@Test
public void testAlterPropertyVisibilityOverwritingProperty() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "prop1", "value1", VISIBILITY_EMPTY)
.addPropertyValue("", "prop1", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
long beforeAlterTimestamp = IncreasingTime.currentTimeMillis();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.alterPropertyVisibility(v1.getProperty("", "prop1", VISIBILITY_A), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(1, count(v1.getProperties()));
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_EMPTY));
assertEquals("value2", v1.getProperty("", "prop1", VISIBILITY_EMPTY).getValue());
assertNull(v1.getProperty("", "prop1", VISIBILITY_A));
v1 = graph.getVertex("v1", graph.getDefaultFetchHints(), beforeAlterTimestamp, AUTHORIZATIONS_A);
assertEquals(2, count(v1.getProperties()));
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_EMPTY));
assertEquals("value1", v1.getProperty("", "prop1", VISIBILITY_EMPTY).getValue());
assertNotNull(v1.getProperty("", "prop1", VISIBILITY_A));
assertEquals("value2", v1.getProperty("", "prop1", VISIBILITY_A).getValue());
}
@Test
public void testChangeVisibilityEdge() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", v1, v2, "", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// test that we can see the edge with A and not B
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
// change the edge visibility to same
e1 = graph.getEdge("e1", AUTHORIZATIONS_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
// test that we can see the edge with B and not A
v1 = graph.getVertex("v1", AUTHORIZATIONS_B);
Assert.assertEquals(1, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_B)));
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
Assert.assertEquals(0, count(v1.getEdges(Direction.BOTH, AUTHORIZATIONS_A)));
}
@Test
public void testChangeVisibilityOnBadPropertyName() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_EMPTY)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
try {
graph.getVertex("v1", AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propBad", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
fail("show throw");
} catch (VertexiumException ex) {
assertNotNull(ex);
}
}
@Test
public void testChangeVisibilityOnStreamingProperty() throws IOException {
String expectedLargeValue = IOUtils.toString(new LargeStringInputStream(LARGE_PROPERTY_VALUE_SIZE));
PropertyValue propSmall = new StreamingPropertyValue(new ByteArrayInputStream("value1".getBytes()), String.class);
PropertyValue propLarge = new StreamingPropertyValue(new ByteArrayInputStream(expectedLargeValue.getBytes()), String.class);
String largePropertyName = "propLarge/\\*!@#$%^&*()[]{}|";
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("propSmall", propSmall, VISIBILITY_A)
.setProperty(largePropertyName, propLarge, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility("propSmall", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(1, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A)
.prepareMutation()
.alterPropertyVisibility(largePropertyName, VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Assert.assertEquals(0, count(graph.getVertex("v1", AUTHORIZATIONS_A).getProperties()));
Assert.assertEquals(2, count(graph.getVertex("v1", AUTHORIZATIONS_A_AND_B).getProperties()));
}
@Test
public void testChangePropertyMetadata() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "valueOld", VISIBILITY_EMPTY);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_EMPTY)
.setProperty("prop2", "value2", null, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.setPropertyMetadata("prop1", "prop1_key1", "valueNew", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().getEntry("prop1_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop1").getMetadata().getEntry("prop1_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
v1.prepareMutation()
.setPropertyMetadata("prop2", "prop2_key1", "valueNew", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().getEntry("prop2_key1", VISIBILITY_EMPTY).getValue());
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
assertEquals("valueNew", v1.getProperty("prop2").getMetadata().getEntry("prop2_key1", VISIBILITY_EMPTY).getValue());
}
@Test
public void testMutationChangePropertyVisibilityFollowedByMetadataUsingPropertyObject() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("prop1_key1", "valueOld", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property p1 = v1.getProperty("prop1", VISIBILITY_A);
v1.prepareMutation()
.alterPropertyVisibility(p1, VISIBILITY_B)
.setPropertyMetadata(p1, "prop1_key1", "valueNew", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
assertEquals("valueNew", v1.getProperty("prop1", VISIBILITY_B).getMetadata().getEntry("prop1_key1", VISIBILITY_B).getValue());
}
@Test
public void testMetadata() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
ExistingElementMutation<Vertex> m = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B).prepareMutation();
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_A), "metadata1", "metadata-value1aa", VISIBILITY_A);
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_A), "metadata1", "metadata-value1ab", VISIBILITY_B);
m.setPropertyMetadata(v1.getProperty("prop1", VISIBILITY_B), "metadata1", "metadata-value1bb", VISIBILITY_B);
m.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
Property prop1A = v1.getProperty("prop1", VISIBILITY_A);
assertEquals(2, prop1A.getMetadata().entrySet().size());
assertEquals("metadata-value1aa", prop1A.getMetadata().getValue("metadata1", VISIBILITY_A));
assertEquals("metadata-value1ab", prop1A.getMetadata().getValue("metadata1", VISIBILITY_B));
Property prop1B = v1.getProperty("prop1", VISIBILITY_B);
assertEquals(1, prop1B.getMetadata().entrySet().size());
assertEquals("metadata-value1bb", prop1B.getMetadata().getValue("metadata1", VISIBILITY_B));
}
@Test
public void testIsVisibilityValid() {
assertFalse(graph.isVisibilityValid(VISIBILITY_A, AUTHORIZATIONS_C));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_A_AND_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_B, AUTHORIZATIONS_B));
assertTrue(graph.isVisibilityValid(VISIBILITY_EMPTY, AUTHORIZATIONS_A));
}
@Test
public void testModifyVertexWithLowerAuthorizationThenOtherProperties() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.setProperty("prop1", "value1New", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, "v1");
}
@Test
public void testPartialUpdateOfVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setProperty("prop2", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop2", "value2")
.vertices();
assertVertexIds(vertices, "v1");
}
@Test
public void testPartialUpdateOfVertexPropertyKey() {
// see https://github.com/visallo/vertexium/issues/141
assumeTrue("Known bug in partial updates", isParitalUpdateOfVertexPropertyKeySupported());
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop", "value1", VISIBILITY_A)
.addPropertyValue("key2", "prop", "value2", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value2")
.vertices();
assertVertexIds(vertices, "v1");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("key1", "prop", "value1New", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1New")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value2")
.vertices();
assertVertexIds(vertices, "v1");
vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop", "value1")
.vertices();
assertVertexIds(vertices);
}
protected boolean isParitalUpdateOfVertexPropertyKeySupported() {
return true;
}
@Test
public void testAddVertexWithoutIndexing() {
assumeTrue("add vertex without indexing not supported", !isDefaultSearchIndex());
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop1", "value1")
.vertices();
assertVertexIds(vertices);
}
@Test
public void testAlterVertexWithoutIndexing() {
assumeTrue("alter vertex without indexing not supported", !isDefaultSearchIndex());
graph.prepareVertex("v1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
.has("prop1", "value1")
.vertices();
assertVertexIds(vertices);
}
@Test
public void testAddEdgeWithoutIndexing() {
assumeTrue("add edge without indexing not supported", !isDefaultSearchIndex());
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.setIndexHint(IndexHint.DO_NOT_INDEX)
.save(AUTHORIZATIONS_A);
graph.flush();
Iterable<Edge> edges = graph.query(AUTHORIZATIONS_A_AND_B)
.has("prop1", "value1")
.edges();
assertEdgeIds(edges, new String[]{});
}
@Test
public void testIteratorWithLessThanPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(3), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(3, count);
assertNotNull("v was null", v);
assertEquals("2", v.getId());
}
@Test
public void testIteratorWithPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(5), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("4", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageOne() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(0);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(7), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("4", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageTwo() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(5);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(12), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(5, count);
assertNotNull("v was null", v);
assertEquals("9", v.getId());
}
@Test
public void testIteratorWithMoreThanPageSizeResultsPageThree() {
QueryParameters parameters = new QueryStringQueryParameters("*", AUTHORIZATIONS_EMPTY);
parameters.setSkip(10);
parameters.setLimit(5);
DefaultGraphQueryIterable<Vertex> iterable = new DefaultGraphQueryIterable<>(parameters, getVertices(12), false, false, false);
int count = 0;
Iterator<Vertex> iterator = iterable.iterator();
Vertex v = null;
while (iterator.hasNext()) {
count++;
v = iterator.next();
assertNotNull(v);
}
assertEquals(2, count);
assertNotNull("v was null", v);
assertEquals("11", v.getId());
}
@Test
public void testGraphMetadata() {
List<GraphMetadataEntry> existingMetadata = toList(graph.getMetadata());
graph.setMetadata("test1", "value1old");
graph.setMetadata("test1", "value1");
graph.setMetadata("test2", "value2");
assertEquals("value1", graph.getMetadata("test1"));
assertEquals("value2", graph.getMetadata("test2"));
assertEquals(null, graph.getMetadata("missingProp"));
List<GraphMetadataEntry> newMetadata = toList(graph.getMetadata());
assertEquals(existingMetadata.size() + 2, newMetadata.size());
}
@Test
public void testSimilarityByText() {
assumeTrue("query similar", graph.isQuerySimilarToTextSupported());
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb, His fleece was white as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("text", "Mary had a little tiger, His fleece was white as snow.", VISIBILITY_B)
.save(AUTHORIZATIONS_B);
graph.prepareVertex("v3", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_A)
.setProperty("text", "His fleece was white as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v5", VISIBILITY_A)
.setProperty("text", "Mary had a little lamb, His fleece was black as snow.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v5", VISIBILITY_A)
.setProperty("text", "Jack and Jill went up the hill to fetch a pail of water.", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<Vertex> vertices = toList(
graph.querySimilarTo(new String[]{"text"}, "Mary had a little lamb, His fleece was white as snow", AUTHORIZATIONS_A_AND_B)
.minTermFrequency(1)
.maxQueryTerms(25)
.minDocFrequency(1)
.maxDocFrequency(10)
.boost(2.0f)
.vertices()
);
assertTrue(vertices.size() > 0);
vertices = toList(
graph.querySimilarTo(new String[]{"text"}, "Mary had a little lamb, His fleece was white as snow", AUTHORIZATIONS_A)
.minTermFrequency(1)
.maxQueryTerms(25)
.minDocFrequency(1)
.maxDocFrequency(10)
.boost(2.0f)
.vertices()
);
assertTrue(vertices.size() > 0);
}
@Test
public void testAllPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
metadata.add("author", "author1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.addPropertyValue("k1", "name", "k1Time25Value", metadata, time25.getTime(), VISIBILITY_A)
.addPropertyValue("k2", "name", "k2Time25Value", metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
metadata = new Metadata();
metadata.add("author", "author2", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.addPropertyValue("k1", "name", "k1Time30Value", metadata, time30.getTime(), VISIBILITY_A)
.addPropertyValue("k2", "name", "k2Time30Value", metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A));
assertEquals(6, values.size());
for (int i = 0; i < 3; i++) {
HistoricalPropertyValue item = values.get(i);
assertEquals(time30, new Date(values.get(i).getTimestamp()));
if (item.getPropertyName().equals("age")) {
assertEquals(30, item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k1")) {
assertEquals("k1Time30Value", item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k2")) {
assertEquals("k2Time30Value", item.getValue());
} else {
fail("Invalid " + item);
}
}
for (int i = 3; i < 6; i++) {
HistoricalPropertyValue item = values.get(i);
assertEquals(time25, new Date(values.get(i).getTimestamp()));
if (item.getPropertyName().equals("age")) {
assertEquals(25, item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k1")) {
assertEquals("k1Time25Value", item.getValue());
} else if (item.getPropertyName().equals("name") && item.getPropertyKey().equals("k2")) {
assertEquals("k2Time25Value", item.getValue());
} else {
fail("Invalid " + item);
}
}
}
@Test
public void testPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
metadata.add("author", "author1", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
metadata = new Metadata();
metadata.add("author", "author2", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues("", "age", VISIBILITY_A, AUTHORIZATIONS_A));
assertEquals(2, values.size());
assertEquals(30, values.get(0).getValue());
assertEquals(time30, new Date(values.get(0).getTimestamp()));
assertEquals("author2", values.get(0).getMetadata().getValue("author", VISIBILITY_A));
assertEquals(25, values.get(1).getValue());
assertEquals(time25, new Date(values.get(1).getTimestamp()));
assertEquals("author1", values.get(1).getMetadata().getValue("author", VISIBILITY_A));
// make sure we get the correct age when we only ask for one value
assertEquals(30, v1.getPropertyValue("", "age"));
assertEquals("author2", v1.getProperty("", "age").getMetadata().getValue("author", VISIBILITY_A));
}
@Test
public void testStreamingPropertyHistoricalVersions() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
StreamingPropertyValue value1 = StreamingPropertyValue.create("value1");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "text", value1, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
StreamingPropertyValue value2 = StreamingPropertyValue.create("value2");
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("", "text", value2, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues("", "text", VISIBILITY_A, AUTHORIZATIONS_A));
assertEquals(2, values.size());
assertEquals("value2", ((StreamingPropertyValue) values.get(0).getValue()).readToString());
assertEquals(time30, new Date(values.get(0).getTimestamp()));
assertEquals("value1", ((StreamingPropertyValue) values.get(1).getValue()).readToString());
assertEquals(time25, new Date(values.get(1).getTimestamp()));
// make sure we get the correct age when we only ask for one value
assertEquals("value2", ((StreamingPropertyValue) v1.getPropertyValue("", "text")).readToString());
}
@Test
public void testGetVertexAtASpecificTimeInHistory() {
Date time25 = createDate(2015, 4, 6, 16, 15, 0);
Date time30 = createDate(2015, 4, 6, 16, 16, 0);
Metadata metadata = new Metadata();
Vertex v1 = graph.prepareVertex("v1", time25.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 25, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", time25.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 20, metadata, time25.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", v1, v2, "label1", time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v1", time30.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 30, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", time30.getTime(), VISIBILITY_A)
.addPropertyValue("", "age", 35, metadata, time30.getTime(), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// verify current versions
assertEquals(30, graph.getVertex("v1", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(20, graph.getVertex("v2", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(35, graph.getVertex("v3", AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertEquals(1, count(graph.getEdges(AUTHORIZATIONS_A)));
// verify old version
assertEquals(25, graph.getVertex("v1", graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A).getPropertyValue("", "age"));
assertNull("v3 should not exist at time25", graph.getVertex("v3", graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A));
assertEquals("e1 should not exist", 0, count(graph.getEdges(graph.getDefaultFetchHints(), time25.getTime(), AUTHORIZATIONS_A)));
}
@Test
public void testSaveMultipleTimestampedValuesInSameMutationVertex() {
String vertexId = "v1";
String propertyKey = "k1";
String propertyName = "p1";
Map<String, Long> values = ImmutableMap.of(
"value1", createDate(2016, 4, 6, 9, 20, 0).getTime(),
"value2", createDate(2016, 5, 6, 9, 20, 0).getTime(),
"value3", createDate(2016, 6, 6, 9, 20, 0).getTime(),
"value4", createDate(2016, 7, 6, 9, 20, 0).getTime(),
"value5", createDate(2016, 8, 6, 9, 20, 0).getTime()
);
ElementMutation<Vertex> vertexMutation = graph.prepareVertex(vertexId, VISIBILITY_EMPTY);
for (Map.Entry<String, Long> entry : values.entrySet()) {
vertexMutation.addPropertyValue(propertyKey, propertyName, entry.getKey(), new Metadata(), entry.getValue(), VISIBILITY_EMPTY);
}
vertexMutation.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Vertex retrievedVertex = graph.getVertex(vertexId, AUTHORIZATIONS_EMPTY);
Iterable<HistoricalPropertyValue> historicalPropertyValues = retrievedVertex.getHistoricalPropertyValues(propertyKey, propertyName, VISIBILITY_EMPTY, null, null, AUTHORIZATIONS_EMPTY);
compareHistoricalValues(values, historicalPropertyValues);
}
@Test
public void testSaveMultipleTimestampedValuesInSameMutationEdge() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
Vertex v2 = graph.addVertex("v2", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
String edgeId = "e1";
String propertyKey = "k1";
String propertyName = "p1";
Map<String, Long> values = ImmutableMap.of(
"value1", createDate(2016, 4, 6, 9, 20, 0).getTime(),
"value2", createDate(2016, 5, 6, 9, 20, 0).getTime(),
"value3", createDate(2016, 6, 6, 9, 20, 0).getTime(),
"value4", createDate(2016, 7, 6, 9, 20, 0).getTime(),
"value5", createDate(2016, 8, 6, 9, 20, 0).getTime()
);
ElementMutation<Edge> edgeMutation = graph.prepareEdge(edgeId, v1, v2, "edgeLabel", VISIBILITY_EMPTY);
for (Map.Entry<String, Long> entry : values.entrySet()) {
edgeMutation.addPropertyValue(propertyKey, propertyName, entry.getKey(), new Metadata(), entry.getValue(), VISIBILITY_EMPTY);
}
edgeMutation.save(AUTHORIZATIONS_EMPTY);
graph.flush();
Edge retrievedEdge = graph.getEdge(edgeId, AUTHORIZATIONS_EMPTY);
Iterable<HistoricalPropertyValue> historicalPropertyValues = retrievedEdge.getHistoricalPropertyValues(propertyKey, propertyName, VISIBILITY_EMPTY, null, null, AUTHORIZATIONS_EMPTY);
compareHistoricalValues(values, historicalPropertyValues);
}
private void compareHistoricalValues(Map<String, Long> expectedValues, Iterable<HistoricalPropertyValue> historicalPropertyValues) {
Map<String, Long> expectedValuesCopy = new HashMap<>(expectedValues);
for (HistoricalPropertyValue historicalPropertyValue : historicalPropertyValues) {
String value = (String) historicalPropertyValue.getValue();
if (!expectedValuesCopy.containsKey(value)) {
throw new VertexiumException("Expected historical values to contain: " + value);
}
long expectedValue = expectedValuesCopy.remove(value);
long ts = historicalPropertyValue.getTimestamp();
assertEquals(expectedValue, ts);
}
if (expectedValuesCopy.size() > 0) {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, Long> entry : expectedValuesCopy.entrySet()) {
result.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
}
throw new VertexiumException("Missing historical values:\n" + result.toString());
}
}
@Test
public void testTimestampsInExistingElementMutation() {
long t1 = createDate(2017, 1, 18, 9, 20, 0).getTime();
long t2 = createDate(2017, 1, 19, 9, 20, 0).getTime();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "prop1", "test1", new Metadata(), t1, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
assertEquals(t1, v1.getProperty("k1", "prop1").getTimestamp());
graph.getVertex("v1", AUTHORIZATIONS_ALL)
.prepareMutation()
.addPropertyValue("k1", "prop1", "test2", new Metadata(), t2, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
assertEquals(t2, v1.getProperty("k1", "prop1").getTimestamp());
List<HistoricalPropertyValue> historicalValues = toList(v1.getHistoricalPropertyValues("k1", "prop1", VISIBILITY_EMPTY, AUTHORIZATIONS_ALL));
assertEquals(2, historicalValues.size());
assertEquals(t1, historicalValues.get(1).getTimestamp());
assertEquals(t2, historicalValues.get(0).getTimestamp());
}
@Test
public void testGraphQueryWithTermsAggregation() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_B)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "label1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e2", "v1", "v2", "label1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e3", "v1", "v2", "label2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("name", ElementType.VERTEX, AUTHORIZATIONS_EMPTY);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joe"));
assertEquals(searchIndexFieldLevelSecurity ? 1L : 2L, (long) vertexPropertyCountByValue.get("Joseph"));
vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("emptyField", ElementType.VERTEX, AUTHORIZATIONS_EMPTY);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(0, vertexPropertyCountByValue.size());
vertexPropertyCountByValue = queryGraphQueryWithTermsAggregation("name", ElementType.VERTEX, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joe"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("Joseph"));
Map<Object, Long> edgePropertyCountByValue = queryGraphQueryWithTermsAggregation(Edge.LABEL_PROPERTY_NAME, ElementType.EDGE, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, edgePropertyCountByValue.size());
assertEquals(2L, (long) edgePropertyCountByValue.get("label1"));
assertEquals(1L, (long) edgePropertyCountByValue.get("label2"));
}
private boolean isSearchIndexFieldLevelSecuritySupported() {
if (graph instanceof GraphWithSearchIndex) {
return ((GraphWithSearchIndex) graph).getSearchIndex().isFieldLevelSecuritySupported();
}
return true;
}
@Test
public void testGraphQueryVertexWithTermsAggregationAlterElementVisibility() {
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
v1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_A);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(0, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.VERTEX, AUTHORIZATIONS_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
}
@Test
public void testGraphQueryEdgeWithTermsAggregationAlterElementVisibility() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", "edge", VISIBILITY_A)
.addPropertyValue("k1", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Edge e1 = graph.getEdge("e1", AUTHORIZATIONS_A_AND_B);
e1.prepareMutation()
.alterElementVisibility(VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_A);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(0, propertyCountByValue.size());
propertyCountByValue = queryGraphQueryWithTermsAggregation("age", ElementType.EDGE, AUTHORIZATIONS_B);
assumeTrue("terms aggregation not supported", propertyCountByValue != null);
assertEquals(1, propertyCountByValue.size());
}
private Map<Object, Long> queryGraphQueryWithTermsAggregation(String propertyName, ElementType elementType, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
TermsAggregation agg = new TermsAggregation("terms-count", propertyName);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", agg.getClass().getName());
return null;
}
q.addAggregation(agg);
TermsResult aggregationResult = (elementType == ElementType.VERTEX ? q.vertices() : q.edges()).getAggregationResult("terms-count", TermsResult.class);
return termsBucketToMap(aggregationResult.getBuckets());
}
@Test
public void testGraphQueryWithNestedTermsAggregation() {
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.defineProperty("gender").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "male", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "male", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "female", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Sam", VISIBILITY_EMPTY)
.addPropertyValue("k1", "gender", "female", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Map<Object, Long>> vertexPropertyCountByValue = queryGraphQueryWithNestedTermsAggregation("name", "gender", AUTHORIZATIONS_A_AND_B);
assumeTrue("terms aggregation not supported", vertexPropertyCountByValue != null);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(1, vertexPropertyCountByValue.get("Joe").size());
assertEquals(1L, (long) vertexPropertyCountByValue.get("Joe").get("male"));
assertEquals(2, vertexPropertyCountByValue.get("Sam").size());
assertEquals(1L, (long) vertexPropertyCountByValue.get("Sam").get("male"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("Sam").get("female"));
}
private Map<Object, Map<Object, Long>> queryGraphQueryWithNestedTermsAggregation(String propertyNameFirst, String propertyNameSecond, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
TermsAggregation agg = new TermsAggregation("terms-count", propertyNameFirst);
agg.addNestedAggregation(new TermsAggregation("nested", propertyNameSecond));
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", agg.getClass().getName());
return null;
}
q.addAggregation(agg);
TermsResult aggregationResult = q.vertices().getAggregationResult("terms-count", TermsResult.class);
return nestedTermsBucketToMap(aggregationResult.getBuckets(), "nested");
}
@Test
public void testGraphQueryWithHistogramAggregation() throws ParseException {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1990-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-08-15"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_A)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-03-02"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> histogram = queryGraphQueryWithHistogramAggregation("age", "1", 0L, new HistogramAggregation.ExtendedBounds<>(20L, 25L), AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(6, histogram.size());
assertEquals(1L, (long) histogram.get("25"));
assertEquals(searchIndexFieldLevelSecurity ? 2L : 3L, (long) histogram.get("20"));
histogram = queryGraphQueryWithHistogramAggregation("age", "1", null, null, AUTHORIZATIONS_A_AND_B);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("25"));
assertEquals(3L, (long) histogram.get("20"));
// field that doesn't have any values
histogram = queryGraphQueryWithHistogramAggregation("emptyField", "1", null, null, AUTHORIZATIONS_A_AND_B);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(0, histogram.size());
// date by 'year'
histogram = queryGraphQueryWithHistogramAggregation("birthDate", "year", null, null, AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
// date by milliseconds
histogram = queryGraphQueryWithHistogramAggregation("birthDate", (365L * 24L * 60L * 60L * 1000L) + "", null, null, AUTHORIZATIONS_EMPTY);
assumeTrue("histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
}
private Map<Object, Long> queryGraphQueryWithHistogramAggregation(
String propertyName,
String interval,
Long minDocCount,
HistogramAggregation.ExtendedBounds extendedBounds,
Authorizations authorizations
) {
Query q = graph.query(authorizations).limit(0);
HistogramAggregation agg = new HistogramAggregation("hist-count", propertyName, interval, minDocCount);
agg.setExtendedBounds(extendedBounds);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", HistogramAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return histogramBucketToMap(q.vertices().getAggregationResult("hist-count", HistogramResult.class).getBuckets());
}
@Test
public void testGraphQueryWithRangeAggregation() throws ParseException {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1990-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-09-04"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-08-15"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_A)
.addPropertyValue("", "birthDate", simpleDateFormat.parse("1995-03-02"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// numeric range
RangeResult aggregationResult = queryGraphQueryWithRangeAggregation(
"age",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(searchIndexFieldLevelSecurity ? 2 : 3, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(0, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// numeric range with permission to see more data
aggregationResult = queryGraphQueryWithRangeAggregation(
"age",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_A_AND_B
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(3, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(0, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// range for a field with no values
aggregationResult = queryGraphQueryWithRangeAggregation(
"emptyField",
null,
"lower",
21,
"middle",
23,
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(0, IterableUtils.count(aggregationResult.getBuckets()));
// date range with dates specified as strings
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
null,
"lower",
"1991-01-01",
"middle",
"1995-08-30",
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(2, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
// date range without user specified keys
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
"yyyy-MM-dd",
null,
"1991-01-01",
null,
"1995-08-30",
null,
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("*-1991-01-01").getCount());
assertEquals(2, aggregationResult.getBucketByKey("1991-01-01-1995-08-30").getCount());
assertEquals(1, aggregationResult.getBucketByKey("1995-08-30-*").getCount());
// date range with dates specified as date objects
aggregationResult = queryGraphQueryWithRangeAggregation(
"birthDate",
null,
"lower",
simpleDateFormat.parse("1991-01-01"),
"middle",
simpleDateFormat.parse("1995-08-30"),
"upper",
AUTHORIZATIONS_EMPTY
);
assumeTrue("range aggregation not supported", aggregationResult != null);
assertEquals(1, aggregationResult.getBucketByKey("lower").getCount());
assertEquals(2, aggregationResult.getBucketByKey("middle").getCount());
assertEquals(1, aggregationResult.getBucketByKey("upper").getCount());
}
private RangeResult queryGraphQueryWithRangeAggregation(
String propertyName,
String format,
String keyOne,
Object boundaryOne,
String keyTwo,
Object boundaryTwo,
String keyThree,
Authorizations authorizations
) {
Query q = graph.query(authorizations).limit(0);
RangeAggregation agg = new RangeAggregation("range-count", propertyName, format);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", RangeAggregation.class.getName());
return null;
}
agg.addUnboundedTo(keyOne, boundaryOne);
agg.addRange(keyTwo, boundaryOne, boundaryTwo);
agg.addUnboundedFrom(keyThree, boundaryTwo);
q.addAggregation(agg);
return q.vertices().getAggregationResult("range-count", RangeResult.class);
}
@Test
public void testGraphQueryWithRangeAggregationAndNestedTerms() throws ParseException {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 21, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Alice", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 22, VISIBILITY_EMPTY)
.addPropertyValue("", "name", "Bob", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Query q = graph.query(AUTHORIZATIONS_A_AND_B).limit(0);
RangeAggregation rangeAggregation = new RangeAggregation("range-count", "age");
TermsAggregation termsAggregation = new TermsAggregation("name-count", "name");
rangeAggregation.addNestedAggregation(termsAggregation);
assumeTrue("range aggregation not supported", q.isAggregationSupported(rangeAggregation));
assumeTrue("terms aggregation not supported", q.isAggregationSupported(termsAggregation));
rangeAggregation.addUnboundedTo("lower", 23);
rangeAggregation.addUnboundedFrom("upper", 23);
q.addAggregation(rangeAggregation);
RangeResult rangeAggResult = q.vertices().getAggregationResult("range-count", RangeResult.class);
assertEquals(3, rangeAggResult.getBucketByKey("lower").getCount());
assertEquals(1, rangeAggResult.getBucketByKey("upper").getCount());
Comparator<TermsBucket> bucketComparator = (b1, b2) -> Long.compare(b2.getCount(), b1.getCount());
Map<String, AggregationResult> lowerNestedResult = rangeAggResult.getBucketByKey("lower").getNestedResults();
TermsResult lowerTermsResult = (TermsResult) lowerNestedResult.get(termsAggregation.getAggregationName());
List<TermsBucket> lowerTermsBuckets = IterableUtils.toList(lowerTermsResult.getBuckets());
Collections.sort(lowerTermsBuckets, bucketComparator);
assertEquals(1, lowerNestedResult.size());
assertEquals(2, lowerTermsBuckets.size());
assertEquals("Alice", lowerTermsBuckets.get(0).getKey());
assertEquals(2, lowerTermsBuckets.get(0).getCount());
assertEquals("Bob", lowerTermsBuckets.get(1).getKey());
assertEquals(1, lowerTermsBuckets.get(1).getCount());
Map<String, AggregationResult> upperNestedResult = rangeAggResult.getBucketByKey("upper").getNestedResults();
TermsResult upperTermsResult = (TermsResult) upperNestedResult.get(termsAggregation.getAggregationName());
List<TermsBucket> upperTermsBuckets = IterableUtils.toList(upperTermsResult.getBuckets());
assertEquals(1, upperNestedResult.size());
assertEquals(1, upperTermsBuckets.size());
assertEquals("Alice", upperTermsBuckets.get(0).getKey());
assertEquals(1, upperTermsBuckets.get(0).getCount());
}
@Test
public void testGraphQueryWithStatisticsAggregation() throws ParseException {
graph.defineProperty("emptyField").dataType(Integer.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
StatisticsResult stats = queryGraphQueryWithStatisticsAggregation("age", AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(3, stats.getCount());
assertEquals(65.0, stats.getSum(), 0.1);
assertEquals(20.0, stats.getMin(), 0.1);
assertEquals(25.0, stats.getMax(), 0.1);
assertEquals(2.35702, stats.getStandardDeviation(), 0.1);
assertEquals(21.666666, stats.getAverage(), 0.1);
stats = queryGraphQueryWithStatisticsAggregation("emptyField", AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(0, stats.getCount());
assertEquals(0.0, stats.getSum(), 0.1);
assertEquals(0.0, stats.getMin(), 0.1);
assertEquals(0.0, stats.getMax(), 0.1);
assertEquals(0.0, stats.getAverage(), 0.1);
assertEquals(0.0, stats.getStandardDeviation(), 0.1);
stats = queryGraphQueryWithStatisticsAggregation("age", AUTHORIZATIONS_A_AND_B);
assumeTrue("statistics aggregation not supported", stats != null);
assertEquals(4, stats.getCount());
assertEquals(95.0, stats.getSum(), 0.1);
assertEquals(20.0, stats.getMin(), 0.1);
assertEquals(30.0, stats.getMax(), 0.1);
assertEquals(23.75, stats.getAverage(), 0.1);
assertEquals(4.14578, stats.getStandardDeviation(), 0.1);
}
private StatisticsResult queryGraphQueryWithStatisticsAggregation(String propertyName, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
StatisticsAggregation agg = new StatisticsAggregation("stats", propertyName);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", StatisticsAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return q.vertices().getAggregationResult("stats", StatisticsResult.class);
}
@Test
public void testGraphQueryWithPercentilesAggregation() throws ParseException {
graph.defineProperty("emptyField").dataType(Integer.class).define();
for (int i = 0; i <= 100; i++) {
graph.prepareVertex("v" + i, VISIBILITY_EMPTY)
.addPropertyValue("", "age", i, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
}
graph.prepareVertex("v200", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 30, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
PercentilesResult percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assumeTrue("percentiles aggregation not supported", percentilesResult != null);
List<Percentile> percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(7, percentiles.size());
assertEquals(1.0, percentiles.get(0).getPercentile(), 0.1);
assertEquals(1.0, percentiles.get(0).getValue(), 0.1);
assertEquals(5.0, percentiles.get(1).getPercentile(), 0.1);
assertEquals(5.0, percentiles.get(1).getValue(), 0.1);
assertEquals(25.0, percentiles.get(2).getPercentile(), 0.1);
assertEquals(25.0, percentiles.get(2).getValue(), 0.1);
assertEquals(50.0, percentiles.get(3).getPercentile(), 0.1);
assertEquals(50.0, percentiles.get(3).getValue(), 0.1);
assertEquals(75.0, percentiles.get(4).getPercentile(), 0.1);
assertEquals(75.0, percentiles.get(4).getValue(), 0.1);
assertEquals(95.0, percentiles.get(5).getPercentile(), 0.1);
assertEquals(95.0, percentiles.get(5).getValue(), 0.1);
assertEquals(99.0, percentiles.get(6).getPercentile(), 0.1);
assertEquals(99.0, percentiles.get(6).getValue(), 0.1);
percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY, 60, 99.99);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(2, percentiles.size());
assertEquals(60.0, percentiles.get(0).getValue(), 0.1);
assertEquals(60.0, percentiles.get(0).getValue(), 0.1);
assertEquals(99.99, percentiles.get(1).getValue(), 0.1);
assertEquals(99.99, percentiles.get(1).getValue(), 0.1);
percentilesResult = queryGraphQueryWithPercentilesAggregation("emptyField", VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
assertEquals(0, percentiles.size());
percentilesResult = queryGraphQueryWithPercentilesAggregation("age", VISIBILITY_A, AUTHORIZATIONS_A_AND_B);
assumeTrue("statistics aggregation not supported", percentilesResult != null);
percentiles = IterableUtils.toList(percentilesResult.getPercentiles());
percentiles.sort(Comparator.comparing(Percentile::getPercentile));
assertEquals(7, percentiles.size());
assertEquals(1.0, percentiles.get(0).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(0).getValue(), 0.1);
assertEquals(5.0, percentiles.get(1).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(1).getValue(), 0.1);
assertEquals(25.0, percentiles.get(2).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(2).getValue(), 0.1);
assertEquals(50.0, percentiles.get(3).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(3).getValue(), 0.1);
assertEquals(75.0, percentiles.get(4).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(4).getValue(), 0.1);
assertEquals(95.0, percentiles.get(5).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(5).getValue(), 0.1);
assertEquals(99.0, percentiles.get(6).getPercentile(), 0.1);
assertEquals(30.0, percentiles.get(6).getValue(), 0.1);
}
private PercentilesResult queryGraphQueryWithPercentilesAggregation(
String propertyName,
Visibility visibility,
Authorizations authorizations,
double... percents
) {
Query q = graph.query(authorizations).limit(0);
PercentilesAggregation agg = new PercentilesAggregation("percentiles", propertyName, visibility);
agg.setPercents(percents);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", StatisticsAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return q.vertices().getAggregationResult("percentiles", PercentilesResult.class);
}
@Test
public void testGraphQueryWithGeohashAggregation() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("emptyField").dataType(GeoPoint.class).define();
graph.defineProperty("location").dataType(GeoPoint.class).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(50, -10, "pt1"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39, -77, "pt2"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39.1, -77.1, "pt3"), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "location", new GeoPoint(39.2, -77.2, "pt4"), VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<String, Long> histogram = queryGraphQueryWithGeohashAggregation("location", 2, AUTHORIZATIONS_EMPTY);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("gb"));
assertEquals(searchIndexFieldLevelSecurity ? 2L : 3L, (long) histogram.get("dq"));
histogram = queryGraphQueryWithGeohashAggregation("emptyField", 2, AUTHORIZATIONS_EMPTY);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(0, histogram.size());
histogram = queryGraphQueryWithGeohashAggregation("location", 2, AUTHORIZATIONS_A_AND_B);
assumeTrue("geo hash histogram aggregation not supported", histogram != null);
assertEquals(2, histogram.size());
assertEquals(1L, (long) histogram.get("gb"));
assertEquals(3L, (long) histogram.get("dq"));
}
@Test
public void testGraphQueryWithCalendarFieldAggregation() {
graph.prepareVertex("v0", VISIBILITY_EMPTY)
.addPropertyValue("", "other_field", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2017, Calendar.MAY, 26, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v3", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v4", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 24, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v5", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 25, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v6", VISIBILITY_A_AND_B)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 30, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.flush();
// hour of day
QueryResultsIterable<Vertex> results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.HOUR_OF_DAY))
.limit(0)
.vertices();
HistogramResult aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(2, aggResult.getBucketByKey(10).getCount());
assertEquals(4, aggResult.getBucketByKey(12).getCount());
// day of week
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_WEEK))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(5, count(aggResult.getBuckets()));
assertEquals(1, aggResult.getBucketByKey(Calendar.SUNDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.MONDAY).getCount());
assertEquals(2, aggResult.getBucketByKey(Calendar.WEDNESDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.FRIDAY).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.SATURDAY).getCount());
// day of month
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_MONTH))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(5, count(aggResult.getBuckets()));
assertEquals(1, aggResult.getBucketByKey(24).getCount());
assertEquals(1, aggResult.getBucketByKey(25).getCount());
assertEquals(1, aggResult.getBucketByKey(26).getCount());
assertEquals(2, aggResult.getBucketByKey(27).getCount());
assertEquals(1, aggResult.getBucketByKey(30).getCount());
// month
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.MONTH))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(Calendar.APRIL).getCount());
assertEquals(1, aggResult.getBucketByKey(Calendar.MAY).getCount());
// year
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.YEAR))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(2016).getCount());
assertEquals(1, aggResult.getBucketByKey(2017).getCount());
// week of year
results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.WEEK_OF_YEAR))
.limit(0)
.vertices();
aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
assertEquals(2, count(aggResult.getBuckets()));
assertEquals(5, aggResult.getBucketByKey(18).getCount());
assertEquals(1, aggResult.getBucketByKey(21).getCount());
}
@Test
public void testGraphQueryWithCalendarFieldAggregationNested() {
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_ALL);
graph.prepareVertex("v3", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 27, 12, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v4", VISIBILITY_EMPTY)
.addPropertyValue("", "date", createDate(2016, Calendar.APRIL, 28, 10, 18, 56), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A);
graph.flush();
CalendarFieldAggregation agg = new CalendarFieldAggregation("agg1", "date", null, TimeZone.getDefault(), Calendar.DAY_OF_WEEK);
agg.addNestedAggregation(new CalendarFieldAggregation("aggNested", "date", null, TimeZone.getDefault(), Calendar.HOUR_OF_DAY));
QueryResultsIterable<Vertex> results = graph.query(AUTHORIZATIONS_ALL)
.addAggregation(agg)
.limit(0)
.vertices();
HistogramResult aggResult = results.getAggregationResult("agg1", CalendarFieldAggregation.RESULT_CLASS);
HistogramBucket bucket = aggResult.getBucketByKey(Calendar.WEDNESDAY);
assertEquals(3, bucket.getCount());
HistogramResult nestedResult = (HistogramResult) bucket.getNestedResults().get("aggNested");
assertEquals(2, nestedResult.getBucketByKey(10).getCount());
assertEquals(1, nestedResult.getBucketByKey(12).getCount());
bucket = aggResult.getBucketByKey(Calendar.THURSDAY);
assertEquals(1, bucket.getCount());
nestedResult = (HistogramResult) bucket.getNestedResults().get("aggNested");
assertEquals(1, nestedResult.getBucketByKey(10).getCount());
}
@Test
public void testLargeFieldValuesThatAreMarkedWithExactMatch() {
graph.defineProperty("field1").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
StringBuilder largeText = new StringBuilder();
for (int i = 0; i < 10000; i++) {
largeText.append("test ");
}
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("", "field1", largeText.toString(), VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_EMPTY);
graph.flush();
}
private Map<String, Long> queryGraphQueryWithGeohashAggregation(String propertyName, int precision, Authorizations authorizations) {
Query q = graph.query(authorizations).limit(0);
GeohashAggregation agg = new GeohashAggregation("geo-count", propertyName, precision);
if (!q.isAggregationSupported(agg)) {
LOGGER.warn("%s unsupported", GeohashAggregation.class.getName());
return null;
}
q.addAggregation(agg);
return geoHashBucketToMap(q.vertices().getAggregationResult("geo-count", GeohashResult.class).getBuckets());
}
@Test
public void testGetVertexPropertyCountByValue() {
boolean searchIndexFieldLevelSecurity = isSearchIndexFieldLevelSecuritySupported();
graph.defineProperty("name").dataType(String.class).textIndexHint(TextIndexHint.EXACT_MATCH).define();
graph.prepareVertex("v1", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_EMPTY)
.addPropertyValue("", "age", 25, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareVertex("v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.addPropertyValue("k2", "name", "Joseph", VISIBILITY_B)
.addPropertyValue("", "age", 20, VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.prepareEdge("e1", "v1", "v2", VISIBILITY_EMPTY)
.addPropertyValue("k1", "name", "Joe", VISIBILITY_EMPTY)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Map<Object, Long> vertexPropertyCountByValue = graph.getVertexPropertyCountByValue("name", AUTHORIZATIONS_EMPTY);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("joe"));
assertEquals(searchIndexFieldLevelSecurity ? 1L : 2L, (long) vertexPropertyCountByValue.get("joseph"));
vertexPropertyCountByValue = graph.getVertexPropertyCountByValue("name", AUTHORIZATIONS_A_AND_B);
assertEquals(2, vertexPropertyCountByValue.size());
assertEquals(2L, (long) vertexPropertyCountByValue.get("joe"));
assertEquals(2L, (long) vertexPropertyCountByValue.get("joseph"));
}
@Test
public void testGetCounts() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_A);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_A);
graph.addEdge("e1", v1, v2, "edge1", VISIBILITY_A, AUTHORIZATIONS_A);
graph.flush();
assertEquals(2, graph.getVertexCount(AUTHORIZATIONS_A));
assertEquals(1, graph.getEdgeCount(AUTHORIZATIONS_A));
}
@Test
public void testFetchHintsEdgeLabels() {
Vertex v1 = graph.addVertex("v1", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v2 = graph.addVertex("v2", VISIBILITY_A, AUTHORIZATIONS_ALL);
Vertex v3 = graph.addVertex("v3", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
graph.addEdge("e v1->v2", v1, v2, "labelA", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.addEdge("e v1->v3", v1, v3, "labelB", VISIBILITY_A, AUTHORIZATIONS_ALL);
graph.flush();
v1 = graph.getVertex("v1", FetchHint.EDGE_LABELS, AUTHORIZATIONS_ALL);
List<String> edgeLabels = toList(v1.getEdgeLabels(Direction.BOTH, AUTHORIZATIONS_ALL));
assertEquals(2, edgeLabels.size());
assertTrue("labelA missing", edgeLabels.contains("labelA"));
assertTrue("labelB missing", edgeLabels.contains("labelB"));
}
@Test
public void testIPAddress() {
graph.defineProperty("ipAddress2").dataType(IpV4Address.class).define();
graph.prepareVertex("v1", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.0.1"), VISIBILITY_A)
.addPropertyValue("k1", "ipAddress2", new IpV4Address("192.168.0.2"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.0.5"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v3", VISIBILITY_A)
.addPropertyValue("k1", "ipAddress1", new IpV4Address("192.168.1.1"), VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(new IpV4Address("192.168.0.1"), v1.getPropertyValue("ipAddress1"));
assertEquals(new IpV4Address(192, 168, 0, 2), v1.getPropertyValue("ipAddress2"));
List<Vertex> vertices = toList(graph.query(AUTHORIZATIONS_A).has("ipAddress1", Compare.EQUAL, new IpV4Address("192.168.0.1")).vertices());
assertEquals(1, vertices.size());
assertEquals("v1", vertices.get(0).getId());
vertices = sortById(toList(
graph.query(AUTHORIZATIONS_A)
.range("ipAddress1", new IpV4Address("192.168.0.0"), new IpV4Address("192.168.0.255"))
.vertices()
));
assertEquals(2, vertices.size());
assertEquals("v1", vertices.get(0).getId());
assertEquals("v2", vertices.get(1).getId());
}
@Test
public void testVertexHashCodeAndEquals() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1Loaded = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(v1Loaded.hashCode(), v1.hashCode());
assertTrue(v1Loaded.equals(v1));
assertNotEquals(v1Loaded.hashCode(), v2.hashCode());
assertFalse(v1Loaded.equals(v2));
}
@Test
public void testEdgeHashCodeAndEquals() {
Vertex v1 = graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
Vertex v2 = graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
Edge e1 = graph.prepareEdge("e1", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
Edge e2 = graph.prepareEdge("e2", v1, v2, "label1", VISIBILITY_A)
.setProperty("prop1", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Edge e1Loaded = graph.getEdge("e1", AUTHORIZATIONS_A);
assertEquals(e1Loaded.hashCode(), e1.hashCode());
assertTrue(e1Loaded.equals(e1));
assertNotEquals(e1Loaded.hashCode(), e2.hashCode());
assertFalse(e1Loaded.equals(e2));
}
@Test
public void testExtendedData() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
Date date3 = new Date(1487083470000L);
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value2", VISIBILITY_A)
.addExtendedData("table1", "row3", "date", date3, VISIBILITY_A)
.addExtendedData("table1", "row3", "name", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertEquals(ImmutableSet.of("table1"), v1.getExtendedDataTableNames());
Iterator<ExtendedDataRow> rows = v1.getExtendedData("table1").iterator();
ExtendedDataRow row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date3, row.getPropertyValue("date"));
assertEquals("value3", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
rows = graph.getExtendedData(
Lists.newArrayList(
new ExtendedDataRowId(ElementType.VERTEX, "v1", "table1", "row1"),
new ExtendedDataRowId(ElementType.VERTEX, "v1", "table1", "row2")
),
AUTHORIZATIONS_A
).iterator();
row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
rows = graph.getExtendedData(ElementType.VERTEX, "v1", "table1", AUTHORIZATIONS_A).iterator();
row = rows.next();
assertEquals(date1, row.getPropertyValue("date"));
assertEquals("value1", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date2, row.getPropertyValue("date"));
assertEquals("value2", row.getPropertyValue("name"));
row = rows.next();
assertEquals(date3, row.getPropertyValue("date"));
assertEquals("value3", row.getPropertyValue("name"));
assertFalse(rows.hasNext());
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
v1.prepareMutation()
.addExtendedData("table1", "row4", "name", "value4", VISIBILITY_A)
.addExtendedData("table2", "row1", "name", "value1", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
assertTrue("table1 should exist", v1.getExtendedDataTableNames().contains("table1"));
assertTrue("table2 should exist", v1.getExtendedDataTableNames().contains("table2"));
List<ExtendedDataRow> rowsList = toList(v1.getExtendedData("table1"));
assertEquals(4, rowsList.size());
rowsList = toList(v1.getExtendedData("table2"));
assertEquals(1, rowsList.size());
}
@Test
public void testExtendedDataDelete() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(0, searchResults.getTotalHits());
}
@Test
public void testExtendedDataQueryVertices() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// Should not come back when finding vertices
QueryResultsIterable<Vertex> queryResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.vertices();
assertEquals(0, queryResults.getTotalHits());
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.search();
assertEquals(1, searchResults.getTotalHits());
List<? extends VertexiumObject> searchResultsList = toList(searchResults);
assertEquals(1, searchResultsList.size());
ExtendedDataRow searchResult = (ExtendedDataRow) searchResultsList.get(0);
assertEquals("v1", searchResult.getId().getElementId());
assertEquals("row1", searchResult.getId().getRowId());
searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
searchResults = graph.query("value", AUTHORIZATIONS_A)
.hasExtendedData(ElementType.VERTEX, "v1", "table1")
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
searchResults = graph.query("value", AUTHORIZATIONS_A)
.hasExtendedData("table1")
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
}
@Test
public void testExtendedDataVertexQuery() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A)
.addExtendedData("table1", "row3", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row4", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row5", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row6", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A);
List<ExtendedDataRow> searchResultsList = toList(
v1.query(AUTHORIZATIONS_A)
.extendedDataRows()
);
assertRowIdsAnyOrder(Lists.newArrayList("row3", "row4", "row5", "row6"), searchResultsList);
}
@Test
public void testExtendedDataQueryAfterDeleteForVertex() {
graph.prepareVertex("v1", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<ExtendedDataRow> searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
graph.deleteVertex("v1", AUTHORIZATIONS_A);
graph.flush();
searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList(), searchResultsList);
}
@Test
public void testExtendedDataQueryAfterDeleteForEdge() {
graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
List<ExtendedDataRow> searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
graph.deleteEdge("e1", AUTHORIZATIONS_A);
graph.flush();
searchResultsList = toList(graph.query(AUTHORIZATIONS_A).extendedDataRows());
assertRowIdsAnyOrder(Lists.newArrayList(), searchResultsList);
}
@Test
public void testExtendedDataQueryEdges() {
Date date1 = new Date(1487083490000L);
Date date2 = new Date(1487083480000L);
graph.prepareVertex("v1", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareVertex("v2", VISIBILITY_A).save(AUTHORIZATIONS_A);
graph.prepareEdge("e1", "v1", "v2", "label", VISIBILITY_A)
.addExtendedData("table1", "row1", "date", date1, VISIBILITY_A)
.addExtendedData("table1", "row1", "name", "value 1", VISIBILITY_A)
.addExtendedData("table1", "row2", "date", date2, VISIBILITY_A)
.addExtendedData("table1", "row2", "name", "value 2", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.prepareEdge("e2", "v1", "v2", "label", VISIBILITY_A)
.save(AUTHORIZATIONS_A);
graph.flush();
// Should not come back when finding edges
QueryResultsIterable<Edge> queryResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.edges();
assertEquals(0, queryResults.getTotalHits());
QueryResultsIterable<? extends VertexiumObject> searchResults = graph.query(AUTHORIZATIONS_A)
.has("date", date1)
.search();
assertEquals(1, searchResults.getTotalHits());
List<? extends VertexiumObject> searchResultsList = toList(searchResults);
assertEquals(1, searchResultsList.size());
ExtendedDataRow searchResult = (ExtendedDataRow) searchResultsList.get(0);
assertEquals("e1", searchResult.getId().getElementId());
assertEquals("row1", searchResult.getId().getRowId());
searchResults = graph.query("value", AUTHORIZATIONS_A)
.search();
assertEquals(2, searchResults.getTotalHits());
searchResultsList = toList(searchResults);
assertEquals(2, searchResultsList.size());
assertRowIdsAnyOrder(Lists.newArrayList("row1", "row2"), searchResultsList);
}
@Test
public void testFetchHintsExceptions() {
Metadata prop1Metadata = new Metadata();
prop1Metadata.add("metadata1", "metadata1Value", VISIBILITY_A);
graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1", "value1", prop1Metadata, VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
Vertex v1 = graph.getVertex("v1", EnumSet.of(FetchHint.PROPERTIES), AUTHORIZATIONS_A);
Property prop1 = v1.getProperty("prop1");
assertThrowsException(prop1::getMetadata);
}
@Test
public void benchmark() {
assumeTrue(benchmarkEnabled());
Random random = new Random(1);
int vertexCount = 10000;
int edgeCount = 10000;
int findVerticesByIdCount = 10000;
benchmarkAddVertices(vertexCount);
benchmarkAddEdges(random, vertexCount, edgeCount);
benchmarkFindVerticesById(random, vertexCount, findVerticesByIdCount);
}
@Test
public void benchmarkGetPropertyByName() {
final int propertyCount = 100;
assumeTrue(benchmarkEnabled());
VertexBuilder m = graph.prepareVertex("v1", VISIBILITY_A);
for (int i = 0; i < propertyCount; i++) {
m.addPropertyValue("key", "prop" + i, "value " + i, VISIBILITY_A);
}
m.save(AUTHORIZATIONS_ALL);
graph.flush();
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_ALL);
double startTime = System.currentTimeMillis();
StringBuilder optimizationBuster = new StringBuilder();
for (int i = 0; i < 10000; i++) {
for (int propIndex = 0; propIndex < propertyCount; propIndex++) {
Object value = v1.getPropertyValue("key", "prop" + propIndex);
optimizationBuster.append(value.toString().substring(0, 1));
}
}
double endTime = System.currentTimeMillis();
LOGGER.trace("optimizationBuster: %s", optimizationBuster.substring(0, 1));
LOGGER.info("get property by name and key in %.3fs", (endTime - startTime) / 1000);
startTime = System.currentTimeMillis();
optimizationBuster = new StringBuilder();
for (int i = 0; i < 10000; i++) {
for (int propIndex = 0; propIndex < propertyCount; propIndex++) {
Object value = v1.getPropertyValue("prop" + propIndex);
optimizationBuster.append(value.toString().substring(0, 1));
}
}
endTime = System.currentTimeMillis();
LOGGER.trace("optimizationBuster: %s", optimizationBuster.substring(0, 1));
LOGGER.info("get property by name in %.3fs", (endTime - startTime) / 1000);
}
@Test
public void benchmarkSaveElementMutations() {
assumeTrue(benchmarkEnabled());
int vertexCount = 1000;
benchmarkAddVertices(vertexCount);
benchmarkAddVerticesSaveElementMutations(vertexCount);
benchmarkAddVertices(vertexCount);
}
private void benchmarkAddVertices(int vertexCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < vertexCount; i++) {
String vertexId = "v" + i;
graph.prepareVertex(vertexId, VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("add vertices in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkAddVerticesSaveElementMutations(int vertexCount) {
double startTime = System.currentTimeMillis();
List<ElementMutation> mutations = new ArrayList<>();
for (int i = 0; i < vertexCount; i++) {
String vertexId = "v" + i;
ElementBuilder<Vertex> m = graph.prepareVertex(vertexId, VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A);
mutations.add(m);
}
graph.saveElementMutations(mutations, AUTHORIZATIONS_ALL);
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("save element mutations in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkAddEdges(Random random, int vertexCount, int edgeCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < edgeCount; i++) {
String edgeId = "e" + i;
String outVertexId = "v" + random.nextInt(vertexCount);
String inVertexId = "v" + random.nextInt(vertexCount);
graph.prepareEdge(edgeId, outVertexId, inVertexId, "label", VISIBILITY_A)
.addPropertyValue("k1", "prop1", "value1 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop2", "value2 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop3", "value3 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop4", "value4 " + i, VISIBILITY_A)
.addPropertyValue("k1", "prop5", "value5 " + i, VISIBILITY_A)
.save(AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("add edges in %.3fs", (endTime - startTime) / 1000);
}
private void benchmarkFindVerticesById(Random random, int vertexCount, int findVerticesByIdCount) {
double startTime = System.currentTimeMillis();
for (int i = 0; i < findVerticesByIdCount; i++) {
String vertexId = "v" + random.nextInt(vertexCount);
graph.getVertex(vertexId, AUTHORIZATIONS_ALL);
}
graph.flush();
double endTime = System.currentTimeMillis();
LOGGER.info("find vertices by id in %.3fs", (endTime - startTime) / 1000);
}
private boolean benchmarkEnabled() {
return Boolean.parseBoolean(System.getProperty("benchmark", "false"));
}
private List<Vertex> getVertices(long count) {
List<Vertex> vertices = new ArrayList<>();
for (int i = 0; i < count; i++) {
Vertex vertex = graph.addVertex(Integer.toString(i), VISIBILITY_EMPTY, AUTHORIZATIONS_EMPTY);
vertices.add(vertex);
}
return vertices;
}
private boolean isDefaultSearchIndex() {
if (!(graph instanceof GraphWithSearchIndex)) {
return false;
}
GraphWithSearchIndex graphWithSearchIndex = (GraphWithSearchIndex) graph;
return graphWithSearchIndex.getSearchIndex() instanceof DefaultSearchIndex;
}
protected List<Vertex> sortById(List<Vertex> vertices) {
Collections.sort(vertices, Comparator.comparing(Element::getId));
return vertices;
}
protected boolean disableEdgeIndexing(Graph graph) {
return false;
}
private Map<Object, Long> termsBucketToMap(Iterable<TermsBucket> buckets) {
Map<Object, Long> results = new HashMap<>();
for (TermsBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
private Map<Object, Map<Object, Long>> nestedTermsBucketToMap(Iterable<TermsBucket> buckets, String nestedAggName) {
Map<Object, Map<Object, Long>> results = new HashMap<>();
for (TermsBucket entry : buckets) {
TermsResult nestedResults = (TermsResult) entry.getNestedResults().get(nestedAggName);
if (nestedResults == null) {
throw new VertexiumException("Could not find nested: " + nestedAggName);
}
results.put(entry.getKey(), termsBucketToMap(nestedResults.getBuckets()));
}
return results;
}
private Map<Object, Long> histogramBucketToMap(Iterable<HistogramBucket> buckets) {
Map<Object, Long> results = new HashMap<>();
for (HistogramBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
private Map<String, Long> geoHashBucketToMap(Iterable<GeohashBucket> buckets) {
Map<String, Long> results = new HashMap<>();
for (GeohashBucket b : buckets) {
results.put(b.getKey(), b.getCount());
}
return results;
}
// Historical Property Value tests
@Test
public void historicalPropertyValueAddProp() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Add property
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(3, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals("prop3_A", values.get(2).getPropertyName());
}
@Test
public void historicalPropertyValueDeleteProp() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// remove property
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.softDeleteProperties("prop2_B")
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(4, values.size());
boolean isDeletedExpected = false;
for (int i = 0; i < 4; i++) {
HistoricalPropertyValue item = values.get(i);
if (item.getPropertyName().equals("prop1_A")) {
assertEquals("prop1_A", values.get(i).getPropertyName());
assertEquals(false, values.get(i).isDeleted());
} else if (item.getPropertyName().equals("prop2_B")) {
assertEquals("prop2_B", values.get(i).getPropertyName());
assertEquals(isDeletedExpected, values.get(i).isDeleted());
isDeletedExpected = !isDeletedExpected;
} else if (item.getPropertyName().equals("prop3_A")) {
assertEquals("prop3_A", values.get(i).getPropertyName());
assertEquals(false, values.get(i).isDeleted());
} else {
fail("Invalid " + item);
}
}
}
@Test
public void historicalPropertyValueModifyPropValue() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// modify property value
Vertex v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value4", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Restore
v1 = graph.getVertex("v1", AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(5, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals(false, values.get(0).isDeleted());
assertEquals("value1", values.get(0).getValue());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals(false, values.get(1).isDeleted());
assertEquals("value2", values.get(1).getValue());
assertEquals("prop3_A", values.get(2).getPropertyName());
assertEquals(false, values.get(2).isDeleted());
assertEquals("value3", values.get(2).getValue());
assertEquals("prop3_A", values.get(3).getPropertyName());
assertEquals(false, values.get(3).isDeleted());
assertEquals("value4", values.get(3).getValue());
assertEquals("prop3_A", values.get(4).getPropertyName());
assertEquals(false, values.get(4).isDeleted());
assertEquals("value3", values.get(4).getValue());
}
@Test
public void historicalPropertyValueModifyPropVisibility() {
Vertex vertexAdded = graph.prepareVertex("v1", VISIBILITY_A)
.setProperty("prop1_A", "value1", VISIBILITY_A)
.setProperty("prop2_B", "value2", VISIBILITY_B)
.setProperty("prop3_A", "value3", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// modify property value
Vertex v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.alterPropertyVisibility("prop1_A", VISIBILITY_B)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
// Restore
v1 = graph.getVertex("v1", FetchHint.ALL, AUTHORIZATIONS_A_AND_B);
vertexAdded = v1.prepareMutation()
.alterPropertyVisibility("prop1_A", VISIBILITY_A)
.save(AUTHORIZATIONS_A_AND_B);
graph.flush();
List<HistoricalPropertyValue> values = toList(v1.getHistoricalPropertyValues(AUTHORIZATIONS_A_AND_B));
Collections.reverse(values);
assertEquals(5, values.size());
assertEquals("prop1_A", values.get(0).getPropertyName());
assertEquals(false, values.get(0).isDeleted());
assertEquals(VISIBILITY_A, values.get(0).getPropertyVisibility());
assertEquals("prop2_B", values.get(1).getPropertyName());
assertEquals(false, values.get(1).isDeleted());
assertEquals(VISIBILITY_B, values.get(1).getPropertyVisibility());
assertEquals("prop3_A", values.get(2).getPropertyName());
assertEquals(false, values.get(2).isDeleted());
assertEquals(VISIBILITY_A, values.get(2).getPropertyVisibility());
assertEquals("prop1_A", values.get(3).getPropertyName());
assertEquals(false, values.get(3).isDeleted());
assertEquals(VISIBILITY_B, values.get(3).getPropertyVisibility());
assertEquals("prop1_A", values.get(4).getPropertyName());
assertEquals(false, values.get(4).isDeleted());
assertEquals(VISIBILITY_A, values.get(4).getPropertyVisibility());
}
}
| add test to check vertex ids of does not contain query
| test/src/main/java/org/vertexium/test/GraphTestBase.java | add test to check vertex ids of does not contain query | <ide><path>est/src/main/java/org/vertexium/test/GraphTestBase.java
<ide> .save(AUTHORIZATIONS_A_AND_B);
<ide> graph.flush();
<ide>
<del> Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("both", TextPredicate.DOES_NOT_CONTAIN, "Test").vertices()));
<del> Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test").vertices()));
<del> Assert.assertEquals(3, count(graph.query(AUTHORIZATIONS_A).has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test Value").vertices()));
<add> QueryResultsIterable<Vertex> vertices = graph.query(AUTHORIZATIONS_A)
<add> .has("both", TextPredicate.DOES_NOT_CONTAIN, "Test")
<add> .vertices();
<add> Assert.assertEquals(3, count(vertices));
<add> vertices.forEach(v -> Arrays.asList("v1", "v3", "v4").contains(v.getId()));
<add>
<add> vertices = graph.query(AUTHORIZATIONS_A)
<add> .has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test")
<add> .vertices();
<add> Assert.assertEquals(3, count(vertices));
<add> vertices.forEach(v -> Arrays.asList("v2", "v3", "v4").contains(v.getId()));
<add>
<add> vertices = graph.query(AUTHORIZATIONS_A)
<add> .has("exactMatch", TextPredicate.DOES_NOT_CONTAIN, "Test Value")
<add> .vertices();
<add> Assert.assertEquals(3, count(vertices));
<add> vertices.forEach(v -> Arrays.asList("v2", "v3", "v4").contains(v.getId()));
<ide> }
<ide>
<ide> @Test |
|
Java | lgpl-2.1 | c32491e0edbc35566e95fe9ced9e18d02240f912 | 0 | MLSDev/kurento-java,shelsonjava/kurento-java,EugenioFidel/kurento-java,bawn92/kurento-java,TribeMedia/kurento-java,bawn92/kurento-java,TribeMedia/kurento-java,bawn92/kurento-java,EugenioFidel/kurento-java,KurentoLegacy/kurento-media-framework,TribeMedia/kurento-java,KurentoLegacy/kurento-media-framework,TribeMedia/kurento-java,KurentoLegacy/kmf-media-api,Kurento/kurento-java,Kurento/kurento-java,KurentoLegacy/kurento-media-framework,EugenioFidel/kurento-java,EugenioFidel/kurento-java,shelsonjava/kurento-java,shelsonjava/kurento-java,shelsonjava/kurento-java,MLSDev/kurento-java,MLSDev/kurento-java,Kurento/kurento-java,bawn92/kurento-java,Kurento/kurento-java | package com.kurento.kmf.media;
import java.io.IOException;
public class RecorderEndPoint extends UriEndPoint {
private static final long serialVersionUID = 1L;
RecorderEndPoint(com.kurento.kms.api.MediaObject recorderEndPoint) {
super(recorderEndPoint);
}
/* SYNC */
public void record() throws IOException {
start();
}
/* ASYNC */
public void record(Continuation<Void> cont) throws IOException {
start(cont);
}
}
| src/main/java/com/kurento/kmf/media/RecorderEndPoint.java | package com.kurento.kmf.media;
import java.io.IOException;
public class RecorderEndPoint extends UriEndPoint {
private static final long serialVersionUID = 1L;
RecorderEndPoint(com.kurento.kms.api.MediaObject mediaRecorder) {
super(mediaRecorder);
}
/* SYNC */
public void record() throws IOException {
start();
}
/* ASYNC */
public void record(Continuation<Void> cont) throws IOException {
start(cont);
}
}
| Change constructor param to recorderEndPoint in RecorderEndPoint
Change-Id: Id672e9171ec7eebf6089968fbd8d4a19214e4401
| src/main/java/com/kurento/kmf/media/RecorderEndPoint.java | Change constructor param to recorderEndPoint in RecorderEndPoint | <ide><path>rc/main/java/com/kurento/kmf/media/RecorderEndPoint.java
<ide>
<ide> private static final long serialVersionUID = 1L;
<ide>
<del> RecorderEndPoint(com.kurento.kms.api.MediaObject mediaRecorder) {
<del> super(mediaRecorder);
<add> RecorderEndPoint(com.kurento.kms.api.MediaObject recorderEndPoint) {
<add> super(recorderEndPoint);
<ide> }
<ide>
<ide> /* SYNC */ |
|
Java | lgpl-2.1 | b6a352fe6c78982b405b3f88779691a56e81c16a | 0 | rhusar/wildfly,golovnin/wildfly,rhusar/wildfly,jstourac/wildfly,pferraro/wildfly,wildfly/wildfly,pferraro/wildfly,tadamski/wildfly,xasx/wildfly,jstourac/wildfly,xasx/wildfly,wildfly/wildfly,iweiss/wildfly,pferraro/wildfly,wildfly/wildfly,iweiss/wildfly,wildfly/wildfly,tadamski/wildfly,iweiss/wildfly,golovnin/wildfly,golovnin/wildfly,jstourac/wildfly,rhusar/wildfly,iweiss/wildfly,rhusar/wildfly,xasx/wildfly,tadamski/wildfly,pferraro/wildfly,jstourac/wildfly | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs.deployment;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.jboss.as.controller.PathElement;
import org.jboss.as.jaxrs.DeploymentRestResourcesDefintion;
import org.jboss.as.jaxrs.JaxrsAnnotations;
import org.jboss.as.jaxrs.JaxrsExtension;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentResourceSupport;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.ServletMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrapClasses;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_RESOURCES;
/**
* Processor that finds jax-rs classes in the deployment
*
* @author Stuart Douglas
*/
public class JaxrsScanningProcessor implements DeploymentUnitProcessor {
private static final DotName DECORATOR = DotName.createSimple("javax.decorator.Decorator");
public static final DotName APPLICATION = DotName.createSimple(Application.class.getName());
private static final String ORG_APACHE_CXF = "org.apache.cxf";
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
final Map<ModuleIdentifier, ResteasyDeploymentData> deploymentData;
if (deploymentUnit.getParent() == null) {
deploymentData = Collections.synchronizedMap(new HashMap<ModuleIdentifier, ResteasyDeploymentData>());
deploymentUnit.putAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA, deploymentData);
} else {
deploymentData = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
}
final ModuleIdentifier moduleIdentifier = deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER);
ResteasyDeploymentData resteasyDeploymentData = new ResteasyDeploymentData();
final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
try {
if (warMetaData == null) {
resteasyDeploymentData.setScanAll(true);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
deploymentData.put(moduleIdentifier, resteasyDeploymentData);
} else {
scanWebDeployment(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
// When BootStrap classes are present and no Application subclass declared
// must check context param for Application subclass declaration
if (resteasyDeploymentData.getScannedResourceClasses().isEmpty() &&
!resteasyDeploymentData.isDispatcherCreated() &&
hasBootClasses(warMetaData.getMergedJBossWebMetaData())) {
checkOtherParams(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
}
}
deploymentUnit.putAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA, resteasyDeploymentData);
List<String> rootRestClasses = new ArrayList<>(resteasyDeploymentData.getScannedResourceClasses());
Collections.sort(rootRestClasses);
for(String cls: rootRestClasses) {
addManagement(deploymentUnit, cls);
}
} catch (ModuleLoadException e) {
throw new DeploymentUnitProcessingException(e);
}
}
private void addManagement(DeploymentUnit deploymentUnit, String componentClass) {
try {
final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
deploymentResourceSupport.getDeploymentSubModel(JaxrsExtension.SUBSYSTEM_NAME, PathElement.pathElement(DeploymentRestResourcesDefintion.REST_RESOURCE_NAME, componentClass));
} catch (Exception e) {
JaxrsLogger.JAXRS_LOGGER.failedToRegisterManagementViewForRESTResources(componentClass, e);
}
}
private void checkOtherParams(final DeploymentUnit du,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException{
HashSet<String> appClazzList = new HashSet<>();
List<ParamValueMetaData> contextParamList = webdata.getContextParams();
if (contextParamList !=null) {
for(ParamValueMetaData param: contextParamList) {
if ("javax.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
List<ParamValueMetaData> initParamList = servlet.getInitParam();
if (initParamList != null) {
for(ParamValueMetaData param: initParamList) {
if ("javax.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
}
}
processDeclaredApplicationClasses(du, appClazzList, webdata, classLoader, resteasyDeploymentData);
}
private void processDeclaredApplicationClasses(final DeploymentUnit du,
final Set<String> appClazzList,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
List<AnnotationInstance> resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
Map<String, ClassInfo> resourceMap = new HashMap<>(resources.size());
if (resources != null) {
for (AnnotationInstance a: resources) {
if (a.target() instanceof ClassInfo) {
resourceMap.put(((ClassInfo)a.target()).name().toString(),
(ClassInfo)a.target());
}
}
}
for (String clazzName: appClazzList) {
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(clazzName);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
try {
Application appClazz = (Application) clazz.newInstance();
Set<Class<?>> declClazzs = appClazz.getClasses();
Set<Object> declSingletons = appClazz.getSingletons();
HashSet<Class<?>> clazzSet = new HashSet<>();
if (declClazzs != null) {
clazzSet.addAll(declClazzs);
}
if (declSingletons != null) {
for (Object obj : declSingletons) {
clazzSet.add((Class) obj);
}
}
Set<String> scannedResourceClasses = resteasyDeploymentData.getScannedResourceClasses();
for (Class<?> cClazz : clazzSet) {
if (cClazz.isAnnotationPresent(javax.ws.rs.Path.class)) {
final ClassInfo info = resourceMap.get(cClazz.getName());
if (info != null) {
if (info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
scannedResourceClasses.add(info.name().toString());
}
}
}
}
} catch (Exception e) {
JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
}
}
@Override
public void undeploy(DeploymentUnit context) {
}
public static final Set<String> BOOT_CLASSES = new HashSet<String>();
static {
Collections.addAll(BOOT_CLASSES, ResteasyBootstrapClasses.BOOTSTRAP_CLASSES);
}
/**
* If any servlet/filter classes are declared, then we probably don't want to scan.
*/
protected boolean hasBootClasses(JBossWebMetaData webdata) throws DeploymentUnitProcessingException {
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
String servletClass = servlet.getServletClass();
if (BOOT_CLASSES.contains(servletClass))
return true;
}
}
if (webdata.getFilters() != null) {
for (FilterMetaData filter : webdata.getFilters()) {
if (BOOT_CLASSES.contains(filter.getFilterClass()))
return true;
}
}
return false;
}
protected void scanWebDeployment(final DeploymentUnit du, final JBossWebMetaData webdata, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData) throws DeploymentUnitProcessingException {
// If there is a resteasy boot class in web.xml, then the default should be to not scan
// make sure this call happens before checkDeclaredApplicationClassAsServlet!!!
boolean hasBoot = hasBootClasses(webdata);
resteasyDeploymentData.setBootClasses(hasBoot);
Class<?> declaredApplicationClass = checkDeclaredApplicationClassAsServlet(webdata, classLoader);
// Assume that checkDeclaredApplicationClassAsServlet created the dispatcher
if (declaredApplicationClass != null) {
resteasyDeploymentData.setDispatcherCreated(true);
// Instigate creation of resteasy configuration switches for
// found provider and resource classes
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// set scanning on only if there are no boot classes
if (!hasBoot && !webdata.isMetadataComplete()) {
resteasyDeploymentData.setScanAll(true);
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// check resteasy configuration flags
List<ParamValueMetaData> contextParams = webdata.getContextParams();
if (contextParams != null) {
for (ParamValueMetaData param : contextParams) {
if (param.getParamName().equals(RESTEASY_SCAN)) {
resteasyDeploymentData.setScanAll(valueOf(RESTEASY_SCAN, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS)) {
resteasyDeploymentData.setScanProviders(valueOf(RESTEASY_SCAN_PROVIDERS, param.getParamValue()));
} else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
resteasyDeploymentData.setScanResources(valueOf(RESTEASY_SCAN_RESOURCES, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS)) {
resteasyDeploymentData.setUnwrappedExceptionsParameterSet(true);
}
}
}
}
protected void scan(final DeploymentUnit du, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException, ModuleLoadException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (!resteasyDeploymentData.shouldScan()) {
return;
}
if (!resteasyDeploymentData.isDispatcherCreated()) {
final Set<ClassInfo> applicationClasses = index.getAllKnownSubclasses(APPLICATION);
try {
for (ClassInfo c : applicationClasses) {
if (Modifier.isAbstract(c.flags())) continue;
@SuppressWarnings("unchecked")
Class<? extends Application> scanned = (Class<? extends Application>) classLoader.loadClass(c.name().toString());
resteasyDeploymentData.getScannedApplicationClasses().add(scanned);
}
} catch (ClassNotFoundException e) {
throw JaxrsLogger.JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
List<AnnotationInstance> resources = null;
List<AnnotationInstance> providers = null;
if (resteasyDeploymentData.isScanResources()) {
resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
}
if (resteasyDeploymentData.isScanProviders()) {
providers = index.getAnnotations(JaxrsAnnotations.PROVIDER.getDotName());
}
if ((resources == null || resources.isEmpty()) && (providers == null || providers.isEmpty()))
return;
final Set<ClassInfo> pathInterfaces = new HashSet<ClassInfo>();
if (resources != null) {
for (AnnotationInstance e : resources) {
final ClassInfo info;
if (e.target() instanceof ClassInfo) {
info = (ClassInfo) e.target();
} else if (e.target() instanceof MethodInfo) {
//ignore
continue;
} else {
JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
continue;
}
if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedResourceClasses().add(info.name().toString());
} else {
pathInterfaces.add(info);
}
}
}
if (providers != null) {
for (AnnotationInstance e : providers) {
if (e.target() instanceof ClassInfo) {
ClassInfo info = (ClassInfo) e.target();
if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as providers
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedProviderClasses().add(info.name().toString());
}
} else {
JAXRS_LOGGER.classAnnotationNotFound("@Provider", e.target());
}
}
}
// look for all implementations of interfaces annotated @Path
for (final ClassInfo iface : pathInterfaces) {
final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
for (final ClassInfo implementor : implementors) {
if(implementor.name().toString().startsWith(ORG_APACHE_CXF)) {
//do not add CXF classes
//see WFLY-9752
continue;
}
if(implementor.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
resteasyDeploymentData.getScannedResourceClasses().add(implementor.name().toString());
}
}
}
protected Class<?> checkDeclaredApplicationClassAsServlet(JBossWebMetaData webData,
ClassLoader classLoader) throws DeploymentUnitProcessingException {
if (webData.getServlets() == null)
return null;
for (ServletMetaData servlet : webData.getServlets()) {
String servletClass = servlet.getServletClass();
if (servletClass == null)
continue;
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(servletClass);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
servlet.setAsyncSupported(true);
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName("javax.ws.rs.Application");
param.setParamValue(servletClass);
List<ParamValueMetaData> params = servlet.getInitParam();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
servlet.setInitParam(params);
}
params.add(param);
return clazz;
}
}
return null;
}
private boolean valueOf(String paramName, String value) throws DeploymentUnitProcessingException {
if (value == null) {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
if (value.toLowerCase(Locale.ENGLISH).equals("true")) {
return true;
} else if (value.toLowerCase(Locale.ENGLISH).equals("false")) {
return false;
} else {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
}
}
| jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsScanningProcessor.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jaxrs.deployment;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.jboss.as.controller.PathElement;
import org.jboss.as.jaxrs.DeploymentRestResourcesDefintion;
import org.jboss.as.jaxrs.JaxrsAnnotations;
import org.jboss.as.jaxrs.JaxrsExtension;
import org.jboss.as.jaxrs.logging.JaxrsLogger;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentResourceSupport;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndex;
import org.jboss.as.web.common.WarMetaData;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.MethodInfo;
import org.jboss.metadata.javaee.spec.ParamValueMetaData;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.metadata.web.spec.FilterMetaData;
import org.jboss.metadata.web.spec.ServletMetaData;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrapClasses;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import static org.jboss.as.jaxrs.logging.JaxrsLogger.JAXRS_LOGGER;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS;
import static org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters.RESTEASY_SCAN_RESOURCES;
/**
* Processor that finds jax-rs classes in the deployment
*
* @author Stuart Douglas
*/
public class JaxrsScanningProcessor implements DeploymentUnitProcessor {
private static final DotName DECORATOR = DotName.createSimple("javax.decorator.Decorator");
public static final DotName APPLICATION = DotName.createSimple(Application.class.getName());
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
return;
}
final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
final Map<ModuleIdentifier, ResteasyDeploymentData> deploymentData;
if (deploymentUnit.getParent() == null) {
deploymentData = Collections.synchronizedMap(new HashMap<ModuleIdentifier, ResteasyDeploymentData>());
deploymentUnit.putAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA, deploymentData);
} else {
deploymentData = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
}
final ModuleIdentifier moduleIdentifier = deploymentUnit.getAttachment(Attachments.MODULE_IDENTIFIER);
ResteasyDeploymentData resteasyDeploymentData = new ResteasyDeploymentData();
final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
try {
if (warMetaData == null) {
resteasyDeploymentData.setScanAll(true);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
deploymentData.put(moduleIdentifier, resteasyDeploymentData);
} else {
scanWebDeployment(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
scan(deploymentUnit, module.getClassLoader(), resteasyDeploymentData);
// When BootStrap classes are present and no Application subclass declared
// must check context param for Application subclass declaration
if (resteasyDeploymentData.getScannedResourceClasses().isEmpty() &&
!resteasyDeploymentData.isDispatcherCreated() &&
hasBootClasses(warMetaData.getMergedJBossWebMetaData())) {
checkOtherParams(deploymentUnit, warMetaData.getMergedJBossWebMetaData(), module.getClassLoader(), resteasyDeploymentData);
}
}
deploymentUnit.putAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA, resteasyDeploymentData);
List<String> rootRestClasses = new ArrayList<>(resteasyDeploymentData.getScannedResourceClasses());
Collections.sort(rootRestClasses);
for(String cls: rootRestClasses) {
addManagement(deploymentUnit, cls);
}
} catch (ModuleLoadException e) {
throw new DeploymentUnitProcessingException(e);
}
}
private void addManagement(DeploymentUnit deploymentUnit, String componentClass) {
try {
final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
deploymentResourceSupport.getDeploymentSubModel(JaxrsExtension.SUBSYSTEM_NAME, PathElement.pathElement(DeploymentRestResourcesDefintion.REST_RESOURCE_NAME, componentClass));
} catch (Exception e) {
JaxrsLogger.JAXRS_LOGGER.failedToRegisterManagementViewForRESTResources(componentClass, e);
}
}
private void checkOtherParams(final DeploymentUnit du,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException{
HashSet<String> appClazzList = new HashSet<>();
List<ParamValueMetaData> contextParamList = webdata.getContextParams();
if (contextParamList !=null) {
for(ParamValueMetaData param: contextParamList) {
if ("javax.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
List<ParamValueMetaData> initParamList = servlet.getInitParam();
if (initParamList != null) {
for(ParamValueMetaData param: initParamList) {
if ("javax.ws.rs.core.Application".equals(param.getParamName())) {
appClazzList.add(param.getParamValue());
}
}
}
}
}
processDeclaredApplicationClasses(du, appClazzList, webdata, classLoader, resteasyDeploymentData);
}
private void processDeclaredApplicationClasses(final DeploymentUnit du,
final Set<String> appClazzList,
final JBossWebMetaData webdata,
final ClassLoader classLoader,
final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
List<AnnotationInstance> resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
Map<String, ClassInfo> resourceMap = new HashMap<>(resources.size());
if (resources != null) {
for (AnnotationInstance a: resources) {
if (a.target() instanceof ClassInfo) {
resourceMap.put(((ClassInfo)a.target()).name().toString(),
(ClassInfo)a.target());
}
}
}
for (String clazzName: appClazzList) {
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(clazzName);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
try {
Application appClazz = (Application) clazz.newInstance();
Set<Class<?>> declClazzs = appClazz.getClasses();
Set<Object> declSingletons = appClazz.getSingletons();
HashSet<Class<?>> clazzSet = new HashSet<>();
if (declClazzs != null) {
clazzSet.addAll(declClazzs);
}
if (declSingletons != null) {
for (Object obj : declSingletons) {
clazzSet.add((Class) obj);
}
}
Set<String> scannedResourceClasses = resteasyDeploymentData.getScannedResourceClasses();
for (Class<?> cClazz : clazzSet) {
if (cClazz.isAnnotationPresent(javax.ws.rs.Path.class)) {
final ClassInfo info = resourceMap.get(cClazz.getName());
if (info != null) {
if (info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
scannedResourceClasses.add(info.name().toString());
}
}
}
}
} catch (Exception e) {
JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
}
}
@Override
public void undeploy(DeploymentUnit context) {
}
public static final Set<String> BOOT_CLASSES = new HashSet<String>();
static {
Collections.addAll(BOOT_CLASSES, ResteasyBootstrapClasses.BOOTSTRAP_CLASSES);
}
/**
* If any servlet/filter classes are declared, then we probably don't want to scan.
*/
protected boolean hasBootClasses(JBossWebMetaData webdata) throws DeploymentUnitProcessingException {
if (webdata.getServlets() != null) {
for (ServletMetaData servlet : webdata.getServlets()) {
String servletClass = servlet.getServletClass();
if (BOOT_CLASSES.contains(servletClass))
return true;
}
}
if (webdata.getFilters() != null) {
for (FilterMetaData filter : webdata.getFilters()) {
if (BOOT_CLASSES.contains(filter.getFilterClass()))
return true;
}
}
return false;
}
protected void scanWebDeployment(final DeploymentUnit du, final JBossWebMetaData webdata, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData) throws DeploymentUnitProcessingException {
// If there is a resteasy boot class in web.xml, then the default should be to not scan
// make sure this call happens before checkDeclaredApplicationClassAsServlet!!!
boolean hasBoot = hasBootClasses(webdata);
resteasyDeploymentData.setBootClasses(hasBoot);
Class<?> declaredApplicationClass = checkDeclaredApplicationClassAsServlet(webdata, classLoader);
// Assume that checkDeclaredApplicationClassAsServlet created the dispatcher
if (declaredApplicationClass != null) {
resteasyDeploymentData.setDispatcherCreated(true);
// Instigate creation of resteasy configuration switches for
// found provider and resource classes
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// set scanning on only if there are no boot classes
if (!hasBoot && !webdata.isMetadataComplete()) {
resteasyDeploymentData.setScanAll(true);
resteasyDeploymentData.setScanProviders(true);
resteasyDeploymentData.setScanResources(true);
}
// check resteasy configuration flags
List<ParamValueMetaData> contextParams = webdata.getContextParams();
if (contextParams != null) {
for (ParamValueMetaData param : contextParams) {
if (param.getParamName().equals(RESTEASY_SCAN)) {
resteasyDeploymentData.setScanAll(valueOf(RESTEASY_SCAN, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_SCAN_PROVIDERS)) {
resteasyDeploymentData.setScanProviders(valueOf(RESTEASY_SCAN_PROVIDERS, param.getParamValue()));
} else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
resteasyDeploymentData.setScanResources(valueOf(RESTEASY_SCAN_RESOURCES, param.getParamValue()));
} else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS)) {
resteasyDeploymentData.setUnwrappedExceptionsParameterSet(true);
}
}
}
}
protected void scan(final DeploymentUnit du, final ClassLoader classLoader, final ResteasyDeploymentData resteasyDeploymentData)
throws DeploymentUnitProcessingException, ModuleLoadException {
final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
if (!resteasyDeploymentData.shouldScan()) {
return;
}
if (!resteasyDeploymentData.isDispatcherCreated()) {
final Set<ClassInfo> applicationClasses = index.getAllKnownSubclasses(APPLICATION);
try {
for (ClassInfo c : applicationClasses) {
if (Modifier.isAbstract(c.flags())) continue;
@SuppressWarnings("unchecked")
Class<? extends Application> scanned = (Class<? extends Application>) classLoader.loadClass(c.name().toString());
resteasyDeploymentData.getScannedApplicationClasses().add(scanned);
}
} catch (ClassNotFoundException e) {
throw JaxrsLogger.JAXRS_LOGGER.cannotLoadApplicationClass(e);
}
}
List<AnnotationInstance> resources = null;
List<AnnotationInstance> providers = null;
if (resteasyDeploymentData.isScanResources()) {
resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
}
if (resteasyDeploymentData.isScanProviders()) {
providers = index.getAnnotations(JaxrsAnnotations.PROVIDER.getDotName());
}
if ((resources == null || resources.isEmpty()) && (providers == null || providers.isEmpty()))
return;
final Set<ClassInfo> pathInterfaces = new HashSet<ClassInfo>();
if (resources != null) {
for (AnnotationInstance e : resources) {
final ClassInfo info;
if (e.target() instanceof ClassInfo) {
info = (ClassInfo) e.target();
} else if (e.target() instanceof MethodInfo) {
//ignore
continue;
} else {
JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
continue;
}
if(info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedResourceClasses().add(info.name().toString());
} else {
pathInterfaces.add(info);
}
}
}
if (providers != null) {
for (AnnotationInstance e : providers) {
if (e.target() instanceof ClassInfo) {
ClassInfo info = (ClassInfo) e.target();
if(info.annotations().containsKey(DECORATOR)) {
//we do not add decorators as providers
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
if (!Modifier.isInterface(info.flags())) {
resteasyDeploymentData.getScannedProviderClasses().add(info.name().toString());
}
} else {
JAXRS_LOGGER.classAnnotationNotFound("@Provider", e.target());
}
}
}
// look for all implementations of interfaces annotated @Path
for (final ClassInfo iface : pathInterfaces) {
final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
for (final ClassInfo implementor : implementors) {
if(implementor.annotations().containsKey(DECORATOR)) {
//we do not add decorators as resources
//we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
continue;
}
resteasyDeploymentData.getScannedResourceClasses().add(implementor.name().toString());
}
}
}
protected Class<?> checkDeclaredApplicationClassAsServlet(JBossWebMetaData webData,
ClassLoader classLoader) throws DeploymentUnitProcessingException {
if (webData.getServlets() == null)
return null;
for (ServletMetaData servlet : webData.getServlets()) {
String servletClass = servlet.getServletClass();
if (servletClass == null)
continue;
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(servletClass);
} catch (ClassNotFoundException e) {
throw new DeploymentUnitProcessingException(e);
}
if (Application.class.isAssignableFrom(clazz)) {
servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
servlet.setAsyncSupported(true);
ParamValueMetaData param = new ParamValueMetaData();
param.setParamName("javax.ws.rs.Application");
param.setParamValue(servletClass);
List<ParamValueMetaData> params = servlet.getInitParam();
if (params == null) {
params = new ArrayList<ParamValueMetaData>();
servlet.setInitParam(params);
}
params.add(param);
return clazz;
}
}
return null;
}
private boolean valueOf(String paramName, String value) throws DeploymentUnitProcessingException {
if (value == null) {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
if (value.toLowerCase(Locale.ENGLISH).equals("true")) {
return true;
} else if (value.toLowerCase(Locale.ENGLISH).equals("false")) {
return false;
} else {
throw JaxrsLogger.JAXRS_LOGGER.invalidParamValue(paramName, value);
}
}
}
| WFLY-9752 Don't add CXF JAX-RS resources
| jaxrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsScanningProcessor.java | WFLY-9752 Don't add CXF JAX-RS resources | <ide><path>axrs/src/main/java/org/jboss/as/jaxrs/deployment/JaxrsScanningProcessor.java
<ide> private static final DotName DECORATOR = DotName.createSimple("javax.decorator.Decorator");
<ide>
<ide> public static final DotName APPLICATION = DotName.createSimple(Application.class.getName());
<add> private static final String ORG_APACHE_CXF = "org.apache.cxf";
<ide>
<ide> @Override
<ide> public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
<ide> JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
<ide> continue;
<ide> }
<add> if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
<add> //do not add CXF classes
<add> //see WFLY-9752
<add> continue;
<add> }
<ide> if(info.annotations().containsKey(DECORATOR)) {
<ide> //we do not add decorators as resources
<ide> //we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
<ide> if (e.target() instanceof ClassInfo) {
<ide> ClassInfo info = (ClassInfo) e.target();
<ide>
<add> if(info.name().toString().startsWith(ORG_APACHE_CXF)) {
<add> //do not add CXF classes
<add> //see WFLY-9752
<add> continue;
<add> }
<ide> if(info.annotations().containsKey(DECORATOR)) {
<ide> //we do not add decorators as providers
<ide> //we can't pick up on programatically added decorators, but that is such an edge case it should not really matter
<ide> for (final ClassInfo iface : pathInterfaces) {
<ide> final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
<ide> for (final ClassInfo implementor : implementors) {
<add> if(implementor.name().toString().startsWith(ORG_APACHE_CXF)) {
<add> //do not add CXF classes
<add> //see WFLY-9752
<add> continue;
<add> }
<ide>
<ide> if(implementor.annotations().containsKey(DECORATOR)) {
<ide> //we do not add decorators as resources |
|
JavaScript | mit | efee9612863b09fcfb7e6646cfaca14f341ea781 | 0 | mnieves076/thunder | var Thunder = {};
Thunder.VERSION = "1.0.9";
Thunder.DEBUG = false;
Thunder.ID = 0; //Global used for instance names
Thunder.VERTICAL = 0;
Thunder.HORIZONTAL = 1;
//get Thunder's root directory
var scripts = document.getElementsByTagName("script");
var i = scripts.length;
while(i--){
var match = scripts[i].src.match(/(^|.*\/)thunder-(.*)\.js$/);
if(match){ Thunder.ROOT = match[1]; }
}
/*
* BaseObject
*
* Based on work by John Resig
*/
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base implementation does nothing
this.BaseObject = function(){};
// Create a new BaseObject that inherits from this class
BaseObject.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] === "function" &&
typeof _super[name] === "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function BaseObject() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype BaseObject
BaseObject.prototype = prototype;
// Enforce the constructor to be what we expect
BaseObject.prototype.constructor = BaseObject;
// And make this class extendable
BaseObject.extend = arguments.callee;
return BaseObject;
};
})();
/*
* Thunder Object
*
*/
(function(){
Thunder.Object = BaseObject.extend({
init: function() {
this.listeners = [];
this.responders = {};
this.eventQueue = new Thunder.EventQueue(this,this.handleEvents,0);
},
handleEvents: function(events) {
for(var i = 0, ii = events.length; i < ii; i++) {
var responder = this.responders[events[i].name];
if(typeof responder != "undefined") {
responder.apply(this,[events[i]]);
}
}
},
addListener: function(evtQue) {
this.listeners.push(evtQue);
},
removeListener: function(evtQue) {
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
if(this.listeners[i] === evtQue) {
this.listeners.splice(i,1);
return true;
}
}
return false;
},
removeListeners: function() {
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i] = null;
}
this.listeners = [];
},
addResponder: function(eventString,callBackFunction) {
this.responders[eventString] = callBackFunction;
},
removeResponder: function(eventString) {
delete this.responders[eventString];
},
removeResponders: function() {
this.responders = {};
},
broadcastEvent: function(evtName, evtObj, delayMSecs) {
if(typeof delayMSecs == "undefined") {
delayMSecs = 0;
}
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i].addEvent(evtName,delayMSecs,this,evtObj);
}
},
broadcastUniqueEvent: function(evtName, evtObj, delayMSecs) {
if(typeof delayMSecs == "undefined") {
delayMSecs = 0;
}
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i].addUniqueEvent(evtName,delayMSecs,this,evtObj);
}
},
trace: function(msg) {
if(window.console && Thunder.DEBUG) console.log(msg);
}
})
})();
/*
* Thunder DisplayObject
*
*/
(function(){
Thunder.DisplayObject = Thunder.Object.extend({
init: function(initRootElement) {
this._super();
this.container = initRootElement;
this.position = new Thunder.Point(0,0);
this.isVisible = true;
this.alpha = 1;
this.width = 0;
this.height = 0;
this.eventMap = null;
},
move: function(xOffset,yOffset) {
if(this.container !== null) {
var p = this.container.position();
this.container.css("top",p.top + yOffset);
this.container.css("left",p.left + xOffset);
}
this.position.addValues(xOffset,yOffset);
},
setPosition: function(newX,newY) {
if(this.container !== null) {
this.container.css("top",newY);
this.container.css("left",newX);
}
this.position.setValues(newX,newY);
},
getPosition: function() {
if(this.container !== null) {
var p = this.container.position();
this.position.setValues(p.left,p.top);
}
return this.position;
},
getX: function() {
return this.position.x;
},
setX: function(newX) {
if(this.container !== null)
this.container.css({left:newX});
this.position.x = newX;
},
getY: function() {
return this.position.y;
},
setY: function(newY) {
if(this.container !== null)
this.container.css({top:newY});
this.position.y = newY
},
setVisible: function(newState) {
this.isVisible = newState;
if(this.container !== null) {
if(this.isVisible) {
this.container.css("display","");
} else {
this.container.css("display","none");
}
}
},
getVisible: function() {
return this.isVisible;
},
setWidth: function(newWidth) {
if(!isNaN(newWidth)) {
if(this.container !== null) {
this.container.width(newWidth);
}
this.width = newWidth;
}
},
getWidth: function() {
return this.width;
},
setHeight: function(newHeight) {
if(!isNaN(newHeight)) {
if(this.container !== null) {
this.container.height(newHeight);
}
this.height = newHeight;
}
},
getHeight: function() {
return this.height;
},
setMask: function(top,right,bottom,left) {
if(this.container !== null) {
if(!isNaN(top) && !isNaN(right) && !isNaN(bottom) && !isNaN(left)) {
this.container.css("clip","rect(" + top + "px," + right + "px," + bottom + "px," + left + "px)");
}
}
},
setAlpha: function(newValue) {
if(this.container !== null) {
this.container.css("opacity",newValue);
}
this.alpha = newValue;
},
getAlpha: function() {
return this.alpha;
},
setContainer: function(newContainer) {
this.container = newContainer;
},
getContainer: function() {
return this.container;
},
rotate: function(degree) {
this.container.css("rotate",degree + "deg");
this.container.css("-webkit-transform","rotate(" + degree + "deg)");
this.container.css("-moz-transform","rotate(" + degree + "deg)");
},
setZIndex: function(newZIndex) {
this.container.css("z-index",newZIndex);
},
mapEvents: function(eventQueue) {
if(this.eventMap != null) {
this.unMapEvents();
}
this.eventMap = new Thunder.EventMap(this.container,this,eventQueue);
return this;
},
unMapEvents: function() {
if(this.eventMap != null) {
this.eventMap.unMapEvents();
return true;
} else {
return false;
}
},
getEventMap: function() {
return this.eventMap;
}
})
})();
/*
* Thunder Component
*
*/
(function(){
Thunder.Component = Thunder.DisplayObject.extend({
init: function(initRootElement) {
this._super(initRootElement);
this.customizers = {};
this.assetManager = new Thunder.AssetManager();
this.layerManager = new Thunder.LayerManager(this.container,this.handleCustomization,this);
},
handleCustomization: function(assetList) {
for(var i = 0, ii = assetList.length; i < ii; i++) {
var customizer = this.customizers[assetList[i].type];
if(typeof customizer != "undefined") {
customizer.apply(this,[assetList[i]]);
}
}
},
addCustomizer: function(assetType,callBackFunction) {
this.customizers[assetType] = callBackFunction;
},
removeCustomizer: function(assetType) {
delete this.customizers[assetType];
},
setContainer: function(newContainer) {
this.container = newContainer;
this.layerManager.setContainer(this.container);
}
});
})();
/*
* Thunder Event
*
*/
(function(){
Thunder.Event = function(initName, delayMSecs, initOwner, initEventObject) {
this.name = initName;
this.delay = (new Date()).getTime() + delayMSecs;
this.owner = initOwner;
this.eventObject = initEventObject;
};
Thunder.Event.prototype = {
getName: function() {
return this.name;
},
getLocalEventPosition: function() {
var t = this.eventObject;
if(typeof this.eventObject.originalEvent.touches != "undefined"
|| typeof this.eventObject.originalEvent.changedTouches != "undefined") {
t = this.eventObject.originalEvent.touches[0] || this.eventObject.originalEvent.changedTouches[0];
}
var x = t.pageX - this.owner.container.offset().left;
var y = t.pageY - this.owner.container.offset().top;
return new Thunder.Point(x,y);
}
};
})();
/*
* Thunder EventMap
*
*/
(function(){
Thunder.EventMap = function(initContainer, initOwner, initEventQueue) {
this.container = initContainer;
this.owner = initOwner;
this.eventQueue = initEventQueue;
this.mapEvents();
if(!Thunder.DEBUG) {
$(document).bind("contextmenu",function(e){ return false; });
}
};
Thunder.EventMap.prototype = {
mapEvents: function() {
var t = this;
this.container.bind('mouseup',function(event) { t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
this.container.bind('mousedown',function(event) { t.eventQueue.addEvent("MOUSEDOWN",0,t.owner,event); return false;});
this.container.bind('mouseenter',function(event) { t.eventQueue.addEvent("MOUSEENTER",0,t.owner,event); return false;});
this.container.bind('mouseleave',function(event) { t.eventQueue.addEvent("MOUSELEAVE",0,t.owner,event); return false;});
this.container.bind('dblclick',function(event) { t.eventQueue.addEvent("DOUBLECLICK",0,t.owner,event); return false;});
this.container.bind('touchstart',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEDOWN",0,t.owner,event); return false;});
this.container.bind('touchend',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
this.container.bind('tap',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
},
unMapEvents: function() {
this.container.unbind('mouseup');
this.container.unbind('mousedown');
this.container.unbind('mouseenter');
this.container.unbind('mouseleave');
this.container.unbind('dblclick');
this.container.unbind('touchstart');
this.container.unbind('touchend');
this.container.unbind('tap');
},
mapMouseMoveEvent: function() {
var t = this;
this.container.bind('mousemove',function(event) { t.eventQueue.addUniqueEvent("MOUSEMOVE",10,t.owner,event); return false; });
this.container.bind('touchmove',function(event) { event.preventDefault(); t.eventQueue.addUniqueEvent("MOUSEMOVE",10,t.owner,event); return false; });
},
unMapMouseMoveEvent: function() {
this.container.unbind('mousemove');
this.container.unbind('touchmove');
}
};
})();
/*
* Thunder KeyEventMap
*
*/
(function(){
Thunder.KeyEventMap = function(initContainer,initEventQueue) {
this.container = initContainer;
this.eventQueue = initEventQueue;
this.keyMap = [];
this.mapKeyEvents();
};
Thunder.KeyEventMap.prototype = {
mapKeyEvents: function() {
var t = this;
this.container.keypress(function(event) {
if (event.keyCode) {
var k = event.keyCode;
} else if(event.which) {
var k = event.which;
} else {
return;
}
t.onKeyDown(k);
});
},
unMapKeyEvents: function() {
this.container.unbind('keypress');
},
mapKey: function(keyCode, eventName) {
this.keyMap[keyCode] = eventName;
},
onKeyDown: function(keyCode) {
var evtName = this.keyMap[keyCode];
if(typeof evtName != "undefined") {
this.eventQueue.addEvent(evtName,0,{"keyCode":keyCode});
} else {
this.eventQueue.addEvent("KEYUP",0,{"keyCode":keyCode});
}
}
};
})();
/*
* Thunder EventQueue
*
*/
(function(){
Thunder.EventQueue = function(initCallBackObject,initCallBackFunction) {
this.callBackObject = initCallBackObject;
this.callBackFunction = initCallBackFunction;
this.eventList = [];
this.eventTimer = null;
};
Thunder.EventQueue.prototype = {
addEvent: function(eventName, delayMSecs, owner, eventObject) {
if(!delayMSecs) {
delayMSecs = 0;
}
if (eventName !== null && eventName !== "") {
this.eventList.push(new Thunder.Event(eventName, delayMSecs, owner, eventObject));
this.exitIdleState();
}
},
addUniqueEvent : function(eventName, delayMSecs, owner, eventObject) {
this.removeEvent(eventName);
this.addEvent(eventName, delayMSecs, owner, eventObject);
},
eventInQueue: function(eventName) {
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if(this.eventList[i].name === eventName) {
return true;
}
}
return false;
},
removeEvent: function(eventName) {
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if(this.eventList[i].name === eventName) {
this.eventList.splice(i,1);
this.removeEvent(eventName);
return true;
}
}
this.enterIdleState();
return false;
},
removeAllEvents: function() {
this.eventList = [];
this.enterIdleState();
},
getNextEvent: function() {
if (this.eventList.length > 0) {
var evt = this.eventList.shift();
if ((new Date()).getTime() >= evt.delay) {
return evt;
} else {
this.eventList.push(evt);
}
} else {
this.enterIdleState();
}
return null;
},
getEvents: function() {
var remainingEventList = [];
var firingEventList = [];
var time = (new Date()).getTime();
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if (time >= this.eventList[i].delay) {
firingEventList.push(this.eventList[i]);
} else {
remainingEventList.push(this.eventList[i]);
}
}
this.eventList = remainingEventList.concat();
this.enterIdleState();
return firingEventList;
},
enterIdleState: function() {
if(this.eventList.length === 0) {
if(this.eventTimer !== null) {
clearInterval(this.eventTimer);
this.eventTimer = null;
}
return true;
}
return false;
},
exitIdleState: function() {
if(this.eventList.length > 0 && this.eventTimer == null) {
var t = this;
this.eventTimer = setInterval(function() {
t.callBackFunction.apply(t.callBackObject, [t.getEvents()]);
},10);
}
}
};
})();
/*
* Thunder Layer
*
*/
(function(){
Thunder.Layer = Thunder.DisplayObject.extend({
init: function(initRootElement,initSurfaceElement,initLayerSetName,initLayerId) {
this._super(initRootElement);
this.surface = initSurfaceElement;
this.layerSetName = initLayerSetName;
this.layerId = initLayerId;
},
clear: function() {
this.surface.empty();
},
addAssets: function(assetList) {
for(var i = 0, ii = assetList.length; i < ii; i++) {
var newId = "THUNDER_ASSET_" + Thunder.ID++;
var newAsset = $('<div>', {
"id": newId,
"class": "THUNDER_ASSET",
"css": {
"position": "absolute",
"top": assetList[i].getY() + "px",
"left": assetList[i].getX() + "px",
"width": (typeof assetList[i].width != "undefined") ? assetList[i].width + "px" : "auto",
"height": (typeof assetList[i].height != "undefined") ? assetList[i].height + "px" : "auto"
}
}).appendTo(this.surface);
assetList[i].setContainer(newAsset);
}
},
setMask: function(top,right,bottom,left) {
if(this.container !== null) {
if(!isNaN(top) && !isNaN(right) && !isNaN(bottom) && !isNaN(left)) {
//layers use overflow instead of clip
this.container.css({'width': right,'height': bottom,'overflow':'hidden'});
}
}
}
})
})();
/*
* Thunder LayerManager
*
*/
(function(){
Thunder.LayerManager = function(initContainer, initCallBackFunction, initCallBackObject) {
this.container = initContainer;
this.callBackFunction = initCallBackFunction;
this.callBackObject = initCallBackObject;
this.layers = {"sets": {},"layer": null};;
this.index = 0;
};
Thunder.LayerManager.prototype = {
layOut: function(assetList, path) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.clear();
layerObj.addAssets(assetList);
this.callBackFunction.apply(this.callBackObject, [assetList]);
}
return layerObj;
},
addToLayOut: function(assetList, path) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.addAssets(assetList);
this.callBackFunction.apply(this.callBackObject, [assetList]);
}
return layerObj;
},
getLayerObject: function(path) {
return this.get(path).layer;
},
getLayerObjects: function(path) {
var r = this.get(path);
if(r != null) {
var layers = (r.layer == null) ? [] : [r.layer];
layers = layers.concat(this.getChildLayers(r.sets));
return layers;
} else {
return [];
}
},
getChildLayers: function(sets) {
var layers = [];
for(r in sets) {
layers.push(sets[r].layer);
layers = layers.concat(this.getChildLayers(sets[r].sets));
}
return layers;
},
addLayer: function(path) {
var layerId = "THUNDER_LAYER_" + Thunder.ID++;
var surfaceId = "THUNDER_LAYER_SURFACE_" + Thunder.ID++;
var newSurface = $('<div>', {
"id": surfaceId,
"class": "THUNDER_LAYER_SURFACE",
"css": {
"position": "absolute",
"top": "0px",
"left": "0px"
}
});
var newLayer = $('<div>', {
"id": layerId,
"class": "THUNDER_LAYER",
"name": path,
"css": {
"position": "absolute",
"top": "0px",
"left": "0px"
}
});
newSurface.appendTo(newLayer.appendTo(this.container));
this.get(path).layer = new Thunder.Layer(newLayer,newSurface,path,layerId);
},
get: function(path) {
if(path == "/") {
return this.layers;
}
var sets = path.replace(/^\/|\/$/g,'').split("/");
var x = this.layers.sets;
var r = null;
for(s in sets) {
if(!x.hasOwnProperty(sets[s])) {
x[sets[s]] = {"sets": {},"layer": null};
}
r = x[sets[s]];
x = r.sets;
}
return r;
},
clearSet: function(path) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].clear();
}
},
clearLayer: function(path) {
var layerObj = this.get(path);
if(layerObj != null) {
layerObj.layer.clear();
}
},
clearAll: function() {
var layers = this.getChildLayers(this.layers.sets);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].clear();
}
},
setLayerSetPosition: function(path, newPosition) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].setPosition(newPosition.x,newPosition.y);
}
},
moveLayerSet: function(path, destinationPoint) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
var newPosition = layers[i].getPosition().addPoint(destinationPoint)
layers[i].move(newPosition.x,newPosition.y);
}
},
setVisible: function(path, visible) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.setVisible(visible);
}
},
setLayerMask: function(path,top,right,bottom,left) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.setMask(top,right,bottom,left);
}
},
setContainer: function(newContainer) {
this.container.children().appendTo(newContainer);
this.container = newContainer;
},
moveToLayer: function(path,container,toRear) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
if(toRear) {
container.appendTo(layerObj.surface).insertBefore(layerObj.surface.find(".THUNDER_ASSET").first());
} else {
container.appendTo(layerObj.surface);
}
}
return false;
}
};
})();
/*
* Thunder Cookie
*
*/
(function(){
Thunder.Cookie = function() {};
Thunder.Cookie.prototype = {
create: function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
read: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0, ii = ca.length; i < ii; i++) {
var c = ca[i];
while (c.charAt(0)===' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
erase: function(name) {
this.create(name,"",-1);
}
};
})();
/*
* Thunder Point
*
*/
(function(){
Thunder.Point = function(initX, initY) {
this.x = initX;
this.y = initY;
};
Thunder.Point.prototype = {
addPoint: function(p) {
this.x += p.x;
this.y += p.y;
return this;
},
addValues: function(_x,_y) {
this.x += _x;
this.y += _y;
return this;
},
setValues: function(_x,_y) {
this.x = _x;
this.y = _y;
return this;
},
equals: function(p) {
if(this.x === p.x && this.y === p.y)
return true;
return false;
},
getDistance: function(p2) {
return Math.sqrt((this.x - p2.x) * (this.x - p2.x) + (this.y - p2.y) * (this.y - p2.y));
},
getAngle: function(p2) {
var a = 270 + (Math.atan2(this.y - p2.y, this.x - p2.x) * (180 / Math.PI));
if(a > 360) {
return a - 360;
}
return a;
},
getCopy: function() {
return new Thunder.Point(this.x, this.y);
},
toString: function() {
return "(" + this.x + "," + this.y + ")";
}
};
})();
/*
* Thunder Asset
*
*/
(function(){
Thunder.Asset = Thunder.DisplayObject.extend({
init: function(initGroup, initType, initSrc, initTag) {
this._super(null);
this.group = null;
this.type = null;
this.groupArray = [];
this.typeArray = [];
this.setGroups(initGroup);
this.setTypes(initType);
this.src = initSrc;
this.tag = initTag;
this.width = null;
this.height = null;
this.param = null;
},
attach: function(html) {
if(this.container !== null) {
this.container.append(html);
}
},
getName: function() {
return this.name;
},
setSize: function(newWidth, newHeight) {
this.width = newWidth;
this.height = newHeight;
},
getWidth: function() {
return this.width;
},
getHeight: function() {
return this.height;
},
setParam: function(newParam) {
this.param = newParam;
},
setGroups: function(newGroup) {
if(typeof newGroup == "string") {
this.group = newGroup;
this.groupArray = this.group.split("|");
}
},
getGroup: function() {
return this.group;
},
getGroupArray: function() {
return this.groupArray;
},
setTypes: function(newType) {
if(typeof newType == "string") {
this.type = newType;
this.typeArray = this.type.split("|");
}
},
getType: function() {
return this.type;
},
getTypeArray: function() {
return this.typeArray;
}
})
})();
/*
* Thunder AssetManager
*
*/
(function(){
Thunder.AssetManager = function(initGroup, initType, initSrc, initTag) {
this.assetList = {};
this.assetTagList = [];
};
Thunder.AssetManager.prototype = {
addAsset: function(initGroup, initType, initSrc, initTag, initX, initY, initWidth, initHeight, initParam) {
var asset = new Thunder.Asset(initGroup, initType, initSrc, initTag);
if(typeof initX != "undefined" && typeof initY != "undefined") {
asset.setPosition(initX, initY);
}
asset.setSize(initWidth, initHeight);
asset.setParam(initParam);
// add groups to assetList if needed
for(var g = 0, gg = asset.groupArray.length; g < gg; g++) {
if(typeof this.assetList[asset.groupArray[g]] == "undefined") {
this.assetList[asset.groupArray[g]] = {};
}
// add types to group
for(var t = 0, tt = asset.typeArray.length; t < tt; t++) {
if(typeof this.assetList[asset.groupArray[g]][asset.typeArray[t]] == "undefined") {
this.assetList[asset.groupArray[g]][asset.typeArray[t]] = [];
}
this.assetList[asset.groupArray[g]][asset.typeArray[t]].push(asset);
}
}
this.assetTagList[asset.tag] = asset;
return asset;
},
removeAssets: function(group, type) {
var groupList = [];
var typeList = [];
if(typeof group != "undefined") {
groupList = group.split("|");
}
if(typeof type != "undefined") {
typeList = type.split("|");
}
for(var g = 0, gg = groupList.length; g < gg; g++) {
if(typeof this.assetList[groupList[g]] != "undefined") {
if(typeList.length == 0) {
//delete all assets for this group
for(var t in this.assetList[groupList[g]]) {
if(typeof t != "undefined") {
for(var i = 0; i < this.assetList[groupList[g]][t].length; i++) {
delete this.assetTagList[this.assetList[groupList[g]][t][i].tag];
}
}
}
delete this.assetList[groupList[g]];
} else {
for(var t = 0, tt = typeList.length; t < tt; t++) {
var assets = this.assetList[groupList[g]][typeList[t]];
if(typeof assets != "undefined") {
for(var i = 0, ii = assets.length; i < ii; i++) {
delete this.assetTagList[assets[i].tag];
}
}
delete this.assetList[groupList[g]][typeList[t]];
}
}
}
}
},
removeAsset: function(tag) {
var asset = this.assetTagList[tag];
var result = 0;
if(typeof asset != "undefined") {
var groups = asset.getGroupArray();
for(var g = 0, gg = groups.length; g < gg; g++) {
for(var t in this.assetList[groups[g]]) {
var assets = this.assetList[groups[g]][t];
for(var i = 0; i < assets.length; i++) {
if(assets[i].tag === tag) {
assets.splice(i--,1);
}
}
}
}
delete this.assetTagList[tag];
result = 1;
}
return result;
},
getAssets: function(group, type) {
var matchList = [];
var groupList = [];
var typeList = [];
if(typeof group != "undefined") {
groupList = group.split("|");
}
if(typeof type != "undefined") {
typeList = type.split("|");
}
for(var g = 0, gg = groupList.length; g < gg; g++) {
if(typeof this.assetList[groupList[g]] != "undefined") {
if(typeList.length == 0) {
//get all assets for this group
for(var t in this.assetList[groupList[g]]) {
if(typeof t != "undefined") {
matchList = matchList.concat(this.assetList[groupList[g]][t]);
}
}
} else {
for(var t = 0, tt = typeList.length; t < tt; t++) {
var assets = this.assetList[groupList[g]][typeList[t]];
if(typeof assets != "undefined") {
matchList = matchList.concat(assets);
}
}
}
}
}
return matchList;
},
getAsset: function(tag) {
var k = this.assetTagList[tag];
if(typeof k != "undefined") {
return k;
}
return null;
},
stack: function(_assetList, direction, x, y, offSet) {
for(var i = 0, ii = _assetList.length; i < ii; i++) {
_assetList[i].setX(x);
_assetList[i].setY(y);
if (direction === Thunder.VERTICAL) {
x = x;
y = y + _assetList[i].height + offSet;
} else if (direction === Thunder.HORIZONTAL) {
x = x + _assetList[i].width + offSet;
y = y;
}
}
return _assetList;
},
getStackedSize: function(_assetList, direction, offSet) {
var d = 0;
for(var i = 0, ii = _assetList.length; i < ii; i++) {
if (direction === Thunder.VERTICAL) {
d += _assetList[i].height + offSet;
} else if (direction === Thunder.HORIZONTAL) {
d += _assetList[i].width + offSet;
}
}
return d;
}
};
})();
/*
* Thunder XMLDataManager
*
*/
(function(){
Thunder.XMLDataManager = Thunder.Object.extend({
init: function(initReadyEvent) {
this._super();
this.xml = null;
this.data = [];
if(initReadyEvent == null) {
this.readyEvent = "XML_DATA_READY";
} else {
this.readyEvent = initReadyEvent;
}
},
load: function(src) {
var t = this;
$.get(src, function(data) {
t.xml = data;
t.process(t.xml,t.data);
t.broadcastEvent(t.readyEvent);
});
},
parse: function(str) {
try {
this.xml = $.parseXML(str);
} catch(e) {
this.xml = null;
}
},
process: function(node, data) {
for(var i = 0, ii = node.childNodes.length; i < ii; i++) {
switch(node.childNodes[i].nodeName) {
default:
if (node.childNodes[i].nodeType === 3 || node.childNodes[i].nodeType == 4) { //TEXT or CDATA
var v = $.trim(node.childNodes[i].nodeValue);
if(v.length > 0) {
data["TEXT"] = v;
}
} else if (node.childNodes[i].nodeType == 1) { //ELEMENT
if(data[node.childNodes[i].nodeName] == null) {
data[node.childNodes[i].nodeName] = [];
}
data[node.childNodes[i].nodeName].push([]);
var iii = data[node.childNodes[i].nodeName].length - 1;
if(node.childNodes[i].hasChildNodes()) {
this.process(node.childNodes[i],data[node.childNodes[i].nodeName][iii]);
}
for(var a = 0, aa = node.childNodes[i].attributes.length; a < aa; a++) {
data[node.childNodes[i].nodeName][iii][node.childNodes[i].attributes[a].name] = node.childNodes[i].attributes[a].value;
}
}
}
}
}
})
})(); | thunder-1.0.9.js | // * Created by Michael Nieves ([email protected])
var Thunder = {};
Thunder.VERSION = "1.0.9";
Thunder.DEBUG = false;
Thunder.ID = 0; //Global used for instance names
Thunder.VERTICAL = 0;
Thunder.HORIZONTAL = 1;
//get Thunder's root directory
var scripts = document.getElementsByTagName("script");
var i = scripts.length;
while(i--){
var match = scripts[i].src.match(/(^|.*\/)thunder-(.*)\.js$/);
if(match){ Thunder.ROOT = match[1]; }
}
/*
* BaseObject
*
* Based on work by John Resig
*/
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base implementation does nothing
this.BaseObject = function(){};
// Create a new BaseObject that inherits from this class
BaseObject.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] === "function" &&
typeof _super[name] === "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function BaseObject() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype BaseObject
BaseObject.prototype = prototype;
// Enforce the constructor to be what we expect
BaseObject.prototype.constructor = BaseObject;
// And make this class extendable
BaseObject.extend = arguments.callee;
return BaseObject;
};
})();
/*
* Thunder Object
*
*/
(function(){
Thunder.Object = BaseObject.extend({
init: function() {
this.listeners = [];
this.responders = {};
this.eventQueue = new Thunder.EventQueue(this,this.handleEvents,0);
},
handleEvents: function(events) {
for(var i = 0, ii = events.length; i < ii; i++) {
var responder = this.responders[events[i].name];
if(typeof responder != "undefined") {
responder.apply(this,[events[i]]);
}
}
},
addListener: function(evtQue) {
this.listeners.push(evtQue);
},
removeListener: function(evtQue) {
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
if(this.listeners[i] === evtQue) {
this.listeners.splice(i,1);
return true;
}
}
return false;
},
removeListeners: function() {
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i] = null;
}
this.listeners = [];
},
addResponder: function(eventString,callBackFunction) {
this.responders[eventString] = callBackFunction;
},
removeResponder: function(eventString) {
delete this.responders[eventString];
},
removeResponders: function() {
this.responders = {};
},
broadcastEvent: function(evtName, evtObj, delayMSecs) {
if(typeof delayMSecs == "undefined") {
delayMSecs = 0;
}
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i].addEvent(evtName,delayMSecs,this,evtObj);
}
},
broadcastUniqueEvent: function(evtName, evtObj, delayMSecs) {
if(typeof delayMSecs == "undefined") {
delayMSecs = 0;
}
for(var i = 0, ii = this.listeners.length; i < ii; i++) {
this.listeners[i].addUniqueEvent(evtName,delayMSecs,this,evtObj);
}
},
trace: function(msg) {
if(window.console && Thunder.DEBUG) console.log(msg);
}
})
})();
/*
* Thunder DisplayObject
*
*/
(function(){
Thunder.DisplayObject = Thunder.Object.extend({
init: function(initRootElement) {
this._super();
this.container = initRootElement;
this.position = new Thunder.Point(0,0);
this.isVisible = true;
this.alpha = 1;
this.width = 0;
this.height = 0;
this.eventMap = null;
},
move: function(xOffset,yOffset) {
if(this.container !== null) {
var p = this.container.position();
this.container.css("top",p.top + yOffset);
this.container.css("left",p.left + xOffset);
}
this.position.addValues(xOffset,yOffset);
},
setPosition: function(newX,newY) {
if(this.container !== null) {
this.container.css("top",newY);
this.container.css("left",newX);
}
this.position.setValues(newX,newY);
},
getPosition: function() {
if(this.container !== null) {
var p = this.container.position();
this.position.setValues(p.left,p.top);
}
return this.position;
},
getX: function() {
return this.position.x;
},
setX: function(newX) {
if(this.container !== null)
this.container.css({left:newX});
this.position.x = newX;
},
getY: function() {
return this.position.y;
},
setY: function(newY) {
if(this.container !== null)
this.container.css({top:newY});
this.position.y = newY
},
setVisible: function(newState) {
this.isVisible = newState;
if(this.container !== null) {
if(this.isVisible) {
this.container.css("display","");
} else {
this.container.css("display","none");
}
}
},
getVisible: function() {
return this.isVisible;
},
setWidth: function(newWidth) {
if(!isNaN(newWidth)) {
if(this.container !== null) {
this.container.width(newWidth);
}
this.width = newWidth;
}
},
getWidth: function() {
return this.width;
},
setHeight: function(newHeight) {
if(!isNaN(newHeight)) {
if(this.container !== null) {
this.container.height(newHeight);
}
this.height = newHeight;
}
},
getHeight: function() {
return this.height;
},
setMask: function(top,right,bottom,left) {
if(this.container !== null) {
if(!isNaN(top) && !isNaN(right) && !isNaN(bottom) && !isNaN(left)) {
this.container.css("clip","rect(" + top + "px," + right + "px," + bottom + "px," + left + "px)");
}
}
},
setAlpha: function(newValue) {
if(this.container !== null) {
this.container.css("opacity",newValue);
}
this.alpha = newValue;
},
getAlpha: function() {
return this.alpha;
},
setContainer: function(newContainer) {
this.container = newContainer;
},
getContainer: function() {
return this.container;
},
rotate: function(degree) {
this.container.css("rotate",degree + "deg");
this.container.css("-webkit-transform","rotate(" + degree + "deg)");
this.container.css("-moz-transform","rotate(" + degree + "deg)");
},
setZIndex: function(newZIndex) {
this.container.css("z-index",newZIndex);
},
mapEvents: function(eventQueue) {
if(this.eventMap != null) {
this.unMapEvents();
}
this.eventMap = new Thunder.EventMap(this.container,this,eventQueue);
return this;
},
unMapEvents: function() {
if(this.eventMap != null) {
this.eventMap.unMapEvents();
return true;
} else {
return false;
}
},
getEventMap: function() {
return this.eventMap;
}
})
})();
/*
* Thunder Component
*
*/
(function(){
Thunder.Component = Thunder.DisplayObject.extend({
init: function(initRootElement) {
this._super(initRootElement);
this.customizers = {};
this.assetManager = new Thunder.AssetManager();
this.layerManager = new Thunder.LayerManager(this.container,this.handleCustomization,this);
},
handleCustomization: function(assetList) {
for(var i = 0, ii = assetList.length; i < ii; i++) {
var customizer = this.customizers[assetList[i].type];
if(typeof customizer != "undefined") {
customizer.apply(this,[assetList[i]]);
}
}
},
addCustomizer: function(assetType,callBackFunction) {
this.customizers[assetType] = callBackFunction;
},
removeCustomizer: function(assetType) {
delete this.customizers[assetType];
},
setContainer: function(newContainer) {
this.container = newContainer;
this.layerManager.setContainer(this.container);
}
});
})();
/*
* Thunder Event
*
*/
(function(){
Thunder.Event = function(initName, delayMSecs, initOwner, initEventObject) {
this.name = initName;
this.delay = (new Date()).getTime() + delayMSecs;
this.owner = initOwner;
this.eventObject = initEventObject;
};
Thunder.Event.prototype = {
getName: function() {
return this.name;
},
getLocalEventPosition: function() {
var t = this.eventObject;
if(typeof this.eventObject.originalEvent.touches != "undefined"
|| typeof this.eventObject.originalEvent.changedTouches != "undefined") {
t = this.eventObject.originalEvent.touches[0] || this.eventObject.originalEvent.changedTouches[0];
}
var x = t.pageX - this.owner.container.offset().left;
var y = t.pageY - this.owner.container.offset().top;
return new Thunder.Point(x,y);
}
};
})();
/*
* Thunder EventMap
*
*/
(function(){
Thunder.EventMap = function(initContainer, initOwner, initEventQueue) {
this.container = initContainer;
this.owner = initOwner;
this.eventQueue = initEventQueue;
this.mapEvents();
if(!Thunder.DEBUG) {
$(document).bind("contextmenu",function(e){ return false; });
}
};
Thunder.EventMap.prototype = {
mapEvents: function() {
var t = this;
this.container.bind('mouseup',function(event) { t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
this.container.bind('mousedown',function(event) { t.eventQueue.addEvent("MOUSEDOWN",0,t.owner,event); return false;});
this.container.bind('mouseenter',function(event) { t.eventQueue.addEvent("MOUSEENTER",0,t.owner,event); return false;});
this.container.bind('mouseleave',function(event) { t.eventQueue.addEvent("MOUSELEAVE",0,t.owner,event); return false;});
this.container.bind('dblclick',function(event) { t.eventQueue.addEvent("DOUBLECLICK",0,t.owner,event); return false;});
this.container.bind('touchstart',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEDOWN",0,t.owner,event); return false;});
this.container.bind('touchend',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
this.container.bind('tap',function(event) { event.preventDefault(); t.eventQueue.addEvent("MOUSEUP",0,t.owner,event); return false;});
},
unMapEvents: function() {
this.container.unbind('mouseup');
this.container.unbind('mousedown');
this.container.unbind('mouseenter');
this.container.unbind('mouseleave');
this.container.unbind('dblclick');
this.container.unbind('touchstart');
this.container.unbind('touchend');
this.container.unbind('tap');
},
mapMouseMoveEvent: function() {
var t = this;
this.container.bind('mousemove',function(event) { t.eventQueue.addUniqueEvent("MOUSEMOVE",10,t.owner,event); return false; });
this.container.bind('touchmove',function(event) { event.preventDefault(); t.eventQueue.addUniqueEvent("MOUSEMOVE",10,t.owner,event); return false; });
},
unMapMouseMoveEvent: function() {
this.container.unbind('mousemove');
this.container.unbind('touchmove');
}
};
})();
/*
* Thunder KeyEventMap
*
*/
(function(){
Thunder.KeyEventMap = function(initContainer,initEventQueue) {
this.container = initContainer;
this.eventQueue = initEventQueue;
this.keyMap = [];
this.mapKeyEvents();
};
Thunder.KeyEventMap.prototype = {
mapKeyEvents: function() {
var t = this;
this.container.keypress(function(event) {
if (event.keyCode) {
var k = event.keyCode;
} else if(event.which) {
var k = event.which;
} else {
return;
}
t.onKeyDown(k);
});
},
unMapKeyEvents: function() {
this.container.unbind('keypress');
},
mapKey: function(keyCode, eventName) {
this.keyMap[keyCode] = eventName;
},
onKeyDown: function(keyCode) {
var evtName = this.keyMap[keyCode];
if(typeof evtName != "undefined") {
this.eventQueue.addEvent(evtName,0,{"keyCode":keyCode});
} else {
this.eventQueue.addEvent("KEYUP",0,{"keyCode":keyCode});
}
}
};
})();
/*
* Thunder EventQueue
*
*/
(function(){
Thunder.EventQueue = function(initCallBackObject,initCallBackFunction) {
this.callBackObject = initCallBackObject;
this.callBackFunction = initCallBackFunction;
this.eventList = [];
this.eventTimer = null;
};
Thunder.EventQueue.prototype = {
addEvent: function(eventName, delayMSecs, owner, eventObject) {
if(!delayMSecs) {
delayMSecs = 0;
}
if (eventName !== null && eventName !== "") {
this.eventList.push(new Thunder.Event(eventName, delayMSecs, owner, eventObject));
this.exitIdleState();
}
},
addUniqueEvent : function(eventName, delayMSecs, owner, eventObject) {
this.removeEvent(eventName);
this.addEvent(eventName, delayMSecs, owner, eventObject);
},
eventInQueue: function(eventName) {
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if(this.eventList[i].name === eventName) {
return true;
}
}
return false;
},
removeEvent: function(eventName) {
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if(this.eventList[i].name === eventName) {
this.eventList.splice(i,1);
this.removeEvent(eventName);
return true;
}
}
this.enterIdleState();
return false;
},
removeAllEvents: function() {
this.eventList = [];
this.enterIdleState();
},
getNextEvent: function() {
if (this.eventList.length > 0) {
var evt = this.eventList.shift();
if ((new Date()).getTime() >= evt.delay) {
return evt;
} else {
this.eventList.push(evt);
}
} else {
this.enterIdleState();
}
return null;
},
getEvents: function() {
var remainingEventList = [];
var firingEventList = [];
var time = (new Date()).getTime();
for(var i = 0, ii = this.eventList.length; i < ii; i++) {
if (time >= this.eventList[i].delay) {
firingEventList.push(this.eventList[i]);
} else {
remainingEventList.push(this.eventList[i]);
}
}
this.eventList = remainingEventList.concat();
this.enterIdleState();
return firingEventList;
},
enterIdleState: function() {
if(this.eventList.length === 0) {
if(this.eventTimer !== null) {
clearInterval(this.eventTimer);
this.eventTimer = null;
}
return true;
}
return false;
},
exitIdleState: function() {
if(this.eventList.length > 0 && this.eventTimer == null) {
var t = this;
this.eventTimer = setInterval(function() {
t.callBackFunction.apply(t.callBackObject, [t.getEvents()]);
},10);
}
}
};
})();
/*
* Thunder Layer
*
*/
(function(){
Thunder.Layer = Thunder.DisplayObject.extend({
init: function(initRootElement,initSurfaceElement,initLayerSetName,initLayerId) {
this._super(initRootElement);
this.surface = initSurfaceElement;
this.layerSetName = initLayerSetName;
this.layerId = initLayerId;
},
clear: function() {
this.surface.empty();
},
addAssets: function(assetList) {
for(var i = 0, ii = assetList.length; i < ii; i++) {
var newId = "THUNDER_ASSET_" + Thunder.ID++;
var newAsset = $('<div>', {
"id": newId,
"class": "THUNDER_ASSET",
"css": {
"position": "absolute",
"top": assetList[i].getY() + "px",
"left": assetList[i].getX() + "px",
"width": (typeof assetList[i].width != "undefined") ? assetList[i].width + "px" : "auto",
"height": (typeof assetList[i].height != "undefined") ? assetList[i].height + "px" : "auto"
}
}).appendTo(this.surface);
assetList[i].setContainer(newAsset);
}
},
setMask: function(top,right,bottom,left) {
if(this.container !== null) {
if(!isNaN(top) && !isNaN(right) && !isNaN(bottom) && !isNaN(left)) {
//layers use overflow instead of clip
this.container.css({'width': right,'height': bottom,'overflow':'hidden'});
}
}
}
})
})();
/*
* Thunder LayerManager
*
*/
(function(){
Thunder.LayerManager = function(initContainer, initCallBackFunction, initCallBackObject) {
this.container = initContainer;
this.callBackFunction = initCallBackFunction;
this.callBackObject = initCallBackObject;
this.layers = {"sets": {},"layer": null};;
this.index = 0;
};
Thunder.LayerManager.prototype = {
layOut: function(assetList, path) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.clear();
layerObj.addAssets(assetList);
this.callBackFunction.apply(this.callBackObject, [assetList]);
}
return layerObj;
},
addToLayOut: function(assetList, path) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.addAssets(assetList);
this.callBackFunction.apply(this.callBackObject, [assetList]);
}
return layerObj;
},
getLayerObject: function(path) {
return this.get(path).layer;
},
getLayerObjects: function(path) {
var r = this.get(path);
if(r != null) {
var layers = (r.layer == null) ? [] : [r.layer];
layers = layers.concat(this.getChildLayers(r.sets));
return layers;
} else {
return [];
}
},
getChildLayers: function(sets) {
var layers = [];
for(r in sets) {
layers.push(sets[r].layer);
layers = layers.concat(this.getChildLayers(sets[r].sets));
}
return layers;
},
addLayer: function(path) {
var layerId = "THUNDER_LAYER_" + Thunder.ID++;
var surfaceId = "THUNDER_LAYER_SURFACE_" + Thunder.ID++;
var newSurface = $('<div>', {
"id": surfaceId,
"class": "THUNDER_LAYER_SURFACE",
"css": {
"position": "absolute",
"top": "0px",
"left": "0px"
}
});
var newLayer = $('<div>', {
"id": layerId,
"class": "THUNDER_LAYER",
"name": path,
"css": {
"position": "absolute",
"top": "0px",
"left": "0px"
}
});
newSurface.appendTo(newLayer.appendTo(this.container));
this.get(path).layer = new Thunder.Layer(newLayer,newSurface,path,layerId);
},
get: function(path) {
if(path == "/") {
return this.layers;
}
var sets = path.replace(/^\/|\/$/g,'').split("/");
var x = this.layers.sets;
var r = null;
for(s in sets) {
if(!x.hasOwnProperty(sets[s])) {
x[sets[s]] = {"sets": {},"layer": null};
}
r = x[sets[s]];
x = r.sets;
}
return r;
},
clearSet: function(path) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].clear();
}
},
clearLayer: function(path) {
var layerObj = this.get(path);
if(layerObj != null) {
layerObj.layer.clear();
}
},
clearAll: function() {
var layers = this.getChildLayers(this.layers.sets);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].clear();
}
},
setLayerSetPosition: function(path, newPosition) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
layers[i].setPosition(newPosition.x,newPosition.y);
}
},
moveLayerSet: function(path, destinationPoint) {
var layers = this.getLayerObjects(path);
for(var i = 0, ii = layers.length; i < ii; i++) {
var newPosition = layers[i].getPosition().addPoint(destinationPoint)
layers[i].move(newPosition.x,newPosition.y);
}
},
setVisible: function(path, visible) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.setVisible(visible);
}
},
setLayerMask: function(path,top,right,bottom,left) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
layerObj.setMask(top,right,bottom,left);
}
},
setContainer: function(newContainer) {
this.container.children().appendTo(newContainer);
this.container = newContainer;
},
moveToLayer: function(path,container,toRear) {
var layerObj = this.get(path).layer;
if(layerObj != null) {
if(toRear) {
container.appendTo(layerObj.surface).insertBefore(layerObj.surface.find(".THUNDER_ASSET").first());
} else {
container.appendTo(layerObj.surface);
}
}
return false;
}
};
})();
/*
* Thunder Cookie
*
*/
(function(){
Thunder.Cookie = function() {};
Thunder.Cookie.prototype = {
create: function(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
read: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0, ii = ca.length; i < ii; i++) {
var c = ca[i];
while (c.charAt(0)===' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
erase: function(name) {
this.create(name,"",-1);
}
};
})();
/*
* Thunder Point
*
*/
(function(){
Thunder.Point = function(initX, initY) {
this.x = initX;
this.y = initY;
};
Thunder.Point.prototype = {
addPoint: function(p) {
this.x += p.x;
this.y += p.y;
return this;
},
addValues: function(_x,_y) {
this.x += _x;
this.y += _y;
return this;
},
setValues: function(_x,_y) {
this.x = _x;
this.y = _y;
return this;
},
equals: function(p) {
if(this.x === p.x && this.y === p.y)
return true;
return false;
},
getDistance: function(p2) {
return Math.sqrt((this.x - p2.x) * (this.x - p2.x) + (this.y - p2.y) * (this.y - p2.y));
},
getAngle: function(p2) {
var a = 270 + (Math.atan2(this.y - p2.y, this.x - p2.x) * (180 / Math.PI));
if(a > 360) {
return a - 360;
}
return a;
},
getCopy: function() {
return new Thunder.Point(this.x, this.y);
},
toString: function() {
return "(" + this.x + "," + this.y + ")";
}
};
})();
/*
* Thunder Asset
*
*/
(function(){
Thunder.Asset = Thunder.DisplayObject.extend({
init: function(initGroup, initType, initSrc, initTag) {
this._super(null);
this.group = null;
this.type = null;
this.groupArray = [];
this.typeArray = [];
this.setGroups(initGroup);
this.setTypes(initType);
this.src = initSrc;
this.tag = initTag;
this.width = null;
this.height = null;
this.param = null;
},
attach: function(html) {
if(this.container !== null) {
this.container.append(html);
}
},
getName: function() {
return this.name;
},
setSize: function(newWidth, newHeight) {
this.width = newWidth;
this.height = newHeight;
},
getWidth: function() {
return this.width;
},
getHeight: function() {
return this.height;
},
setParam: function(newParam) {
this.param = newParam;
},
setGroups: function(newGroup) {
if(typeof newGroup == "string") {
this.group = newGroup;
this.groupArray = this.group.split("|");
}
},
getGroup: function() {
return this.group;
},
getGroupArray: function() {
return this.groupArray;
},
setTypes: function(newType) {
if(typeof newType == "string") {
this.type = newType;
this.typeArray = this.type.split("|");
}
},
getType: function() {
return this.type;
},
getTypeArray: function() {
return this.typeArray;
}
})
})();
/*
* Thunder AssetManager
*
*/
(function(){
Thunder.AssetManager = function(initGroup, initType, initSrc, initTag) {
this.assetList = {};
this.assetTagList = [];
};
Thunder.AssetManager.prototype = {
addAsset: function(initGroup, initType, initSrc, initTag, initX, initY, initWidth, initHeight, initParam) {
var asset = new Thunder.Asset(initGroup, initType, initSrc, initTag);
if(typeof initX != "undefined" && typeof initY != "undefined") {
asset.setPosition(initX, initY);
}
asset.setSize(initWidth, initHeight);
asset.setParam(initParam);
// add groups to assetList if needed
for(var g = 0, gg = asset.groupArray.length; g < gg; g++) {
if(typeof this.assetList[asset.groupArray[g]] == "undefined") {
this.assetList[asset.groupArray[g]] = {};
}
// add types to group
for(var t = 0, tt = asset.typeArray.length; t < tt; t++) {
if(typeof this.assetList[asset.groupArray[g]][asset.typeArray[t]] == "undefined") {
this.assetList[asset.groupArray[g]][asset.typeArray[t]] = [];
}
this.assetList[asset.groupArray[g]][asset.typeArray[t]].push(asset);
}
}
this.assetTagList[asset.tag] = asset;
return asset;
},
removeAssets: function(group, type) {
var groupList = [];
var typeList = [];
if(typeof group != "undefined") {
groupList = group.split("|");
}
if(typeof type != "undefined") {
typeList = type.split("|");
}
for(var g = 0, gg = groupList.length; g < gg; g++) {
if(typeof this.assetList[groupList[g]] != "undefined") {
if(typeList.length == 0) {
//delete all assets for this group
for(var t in this.assetList[groupList[g]]) {
if(typeof t != "undefined") {
for(var i = 0; i < this.assetList[groupList[g]][t].length; i++) {
delete this.assetTagList[this.assetList[groupList[g]][t][i].tag];
}
}
}
delete this.assetList[groupList[g]];
} else {
for(var t = 0, tt = typeList.length; t < tt; t++) {
var assets = this.assetList[groupList[g]][typeList[t]];
if(typeof assets != "undefined") {
for(var i = 0, ii = assets.length; i < ii; i++) {
delete this.assetTagList[assets[i].tag];
}
}
delete this.assetList[groupList[g]][typeList[t]];
}
}
}
}
},
removeAsset: function(tag) {
var asset = this.assetTagList[tag];
var result = 0;
if(typeof asset != "undefined") {
var groups = asset.getGroupArray();
for(var g = 0, gg = groups.length; g < gg; g++) {
for(var t in this.assetList[groups[g]]) {
var assets = this.assetList[groups[g]][t];
for(var i = 0; i < assets.length; i++) {
if(assets[i].tag === tag) {
assets.splice(i--,1);
}
}
}
}
delete this.assetTagList[tag];
result = 1;
}
return result;
},
getAssets: function(group, type) {
var matchList = [];
var groupList = [];
var typeList = [];
if(typeof group != "undefined") {
groupList = group.split("|");
}
if(typeof type != "undefined") {
typeList = type.split("|");
}
for(var g = 0, gg = groupList.length; g < gg; g++) {
if(typeof this.assetList[groupList[g]] != "undefined") {
if(typeList.length == 0) {
//get all assets for this group
for(var t in this.assetList[groupList[g]]) {
if(typeof t != "undefined") {
matchList = matchList.concat(this.assetList[groupList[g]][t]);
}
}
} else {
for(var t = 0, tt = typeList.length; t < tt; t++) {
var assets = this.assetList[groupList[g]][typeList[t]];
if(typeof assets != "undefined") {
matchList = matchList.concat(assets);
}
}
}
}
}
return matchList;
},
getAsset: function(tag) {
var k = this.assetTagList[tag];
if(typeof k != "undefined") {
return k;
}
return null;
},
stack: function(_assetList, direction, x, y, offSet) {
for(var i = 0, ii = _assetList.length; i < ii; i++) {
_assetList[i].setX(x);
_assetList[i].setY(y);
if (direction === Thunder.VERTICAL) {
x = x;
y = y + _assetList[i].height + offSet;
} else if (direction === Thunder.HORIZONTAL) {
x = x + _assetList[i].width + offSet;
y = y;
}
}
return _assetList;
},
getStackedSize: function(_assetList, direction, offSet) {
var d = 0;
for(var i = 0, ii = _assetList.length; i < ii; i++) {
if (direction === Thunder.VERTICAL) {
d += _assetList[i].height + offSet;
} else if (direction === Thunder.HORIZONTAL) {
d += _assetList[i].width + offSet;
}
}
return d;
}
};
})();
/*
* Thunder XMLDataManager
*
*/
(function(){
Thunder.XMLDataManager = Thunder.Object.extend({
init: function(initReadyEvent) {
this._super();
this.xml = null;
this.data = [];
if(initReadyEvent == null) {
this.readyEvent = "XML_DATA_READY";
} else {
this.readyEvent = initReadyEvent;
}
},
load: function(src) {
var t = this;
$.get(src, function(data) {
t.xml = data;
t.process(t.xml,t.data);
t.broadcastEvent(t.readyEvent);
});
},
parse: function(str) {
try {
this.xml = $.parseXML(str);
} catch(e) {
this.xml = null;
}
},
process: function(node, data) {
for(var i = 0, ii = node.childNodes.length; i < ii; i++) {
switch(node.childNodes[i].nodeName) {
default:
if (node.childNodes[i].nodeType === 3 || node.childNodes[i].nodeType == 4) { //TEXT or CDATA
var v = $.trim(node.childNodes[i].nodeValue);
if(v.length > 0) {
data["TEXT"] = v;
}
} else if (node.childNodes[i].nodeType == 1) { //ELEMENT
if(data[node.childNodes[i].nodeName] == null) {
data[node.childNodes[i].nodeName] = [];
}
data[node.childNodes[i].nodeName].push([]);
var iii = data[node.childNodes[i].nodeName].length - 1;
if(node.childNodes[i].hasChildNodes()) {
this.process(node.childNodes[i],data[node.childNodes[i].nodeName][iii]);
}
for(var a = 0, aa = node.childNodes[i].attributes.length; a < aa; a++) {
data[node.childNodes[i].nodeName][iii][node.childNodes[i].attributes[a].name] = node.childNodes[i].attributes[a].value;
}
}
}
}
}
})
})(); | Removed contact info
| thunder-1.0.9.js | Removed contact info | <ide><path>hunder-1.0.9.js
<del>// * Created by Michael Nieves ([email protected])
<del>
<ide> var Thunder = {};
<ide> Thunder.VERSION = "1.0.9";
<ide> Thunder.DEBUG = false; |
|
Java | mit | c37ef71f728bbcc9f25d42bd774bc176dda1c500 | 0 | Matsv/ViaVersion,MylesIsCool/ViaVersion | package us.myles.ViaVersion.protocols.protocol1_11to1_10;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import org.spacehq.opennbt.tag.builtin.CompoundTag;
import org.spacehq.opennbt.tag.builtin.StringTag;
import us.myles.ViaVersion.api.minecraft.item.Item;
public class ItemRewriter {
private static BiMap<String, String> oldToNewNames = HashBiMap.create();
static {
oldToNewNames.put("AreaEffectCloud", "minecraft:area_effect_cloud");
oldToNewNames.put("ArmorStand", "minecraft:armor_stand");
oldToNewNames.put("Arrow", "minecraft:arrow");
oldToNewNames.put("Bat", "minecraft:bat");
oldToNewNames.put("Blaze", "minecraft:blaze");
oldToNewNames.put("Boat", "minecraft:boat");
oldToNewNames.put("CaveSpider", "minecraft:cave_spider");
oldToNewNames.put("Chicken", "minecraft:chicken");
oldToNewNames.put("Cow", "minecraft:cow");
oldToNewNames.put("Creeper", "minecraft:creeper");
oldToNewNames.put("Donkey", "minecraft:donkey");
oldToNewNames.put("DragonFireball", "minecraft:dragon_fireball");
oldToNewNames.put("ElderGuardian", "minecraft:elder_guardian");
oldToNewNames.put("EnderCrystal", "minecraft:ender_crystal");
oldToNewNames.put("EnderDragon", "minecraft:ender_dragon");
oldToNewNames.put("Enderman", "minecraft:enderman");
oldToNewNames.put("Endermite", "minecraft:endermite");
oldToNewNames.put("EyeOfEnderSignal", "minecraft:eye_of_ender_signal");
oldToNewNames.put("FallingSand", "minecraft:falling_block");
oldToNewNames.put("Fireball", "minecraft:fireball");
oldToNewNames.put("FireworksRocketEntity", "minecraft:fireworks_rocket");
oldToNewNames.put("Ghast", "minecraft:ghast");
oldToNewNames.put("Giant", "minecraft:giant");
oldToNewNames.put("Guardian", "minecraft:guardian");
oldToNewNames.put("Horse", "minecraft:horse");
oldToNewNames.put("Husk", "minecraft:husk");
oldToNewNames.put("Item", "minecraft:item");
oldToNewNames.put("ItemFrame", "minecraft:item_frame");
oldToNewNames.put("LavaSlime", "minecraft:magma_cube");
oldToNewNames.put("LeashKnot", "minecraft:leash_knot");
oldToNewNames.put("MinecartChest", "minecraft:chest_minecart");
oldToNewNames.put("MinecartCommandBlock", "minecraft:commandblock_minecart");
oldToNewNames.put("MinecartFurnace", "minecraft:furnace_minecart");
oldToNewNames.put("MinecartHopper", "minecraft:hopper_minecart");
oldToNewNames.put("MinecartRideable", "minecraft:minecart");
oldToNewNames.put("MinecartSpawner", "minecraft:spawner_minecart");
oldToNewNames.put("MinecartTNT", "minecraft:tnt_minecart");
oldToNewNames.put("Mule", "minecraft:mule");
oldToNewNames.put("MushroomCow", "minecraft:mooshroom");
oldToNewNames.put("Ozelot", "minecraft:ocelot");
oldToNewNames.put("Painting", "minecraft:painting");
oldToNewNames.put("Pig", "minecraft:pig");
oldToNewNames.put("PigZombie", "minecraft:zombie_pigman");
oldToNewNames.put("PolarBear", "minecraft:polar_bear");
oldToNewNames.put("PrimedTnt", "minecraft:tnt");
oldToNewNames.put("Rabbit", "minecraft:rabbit");
oldToNewNames.put("Sheep", "minecraft:sheep");
oldToNewNames.put("Shulker", "minecraft:shulker");
oldToNewNames.put("ShulkerBullet", "minecraft:shulker_bullet");
oldToNewNames.put("Silverfish", "minecraft:silverfish");
oldToNewNames.put("Skeleton", "minecraft:skeleton");
oldToNewNames.put("SkeletonHorse", "minecraft:skeleton_horse");
oldToNewNames.put("Slime", "minecraft:slime");
oldToNewNames.put("SmallFireball", "minecraft:small_fireball");
oldToNewNames.put("Snowball", "minecraft:snowball");
oldToNewNames.put("SnowMan", "minecraft:snowman");
oldToNewNames.put("SpectralArrow", "minecraft:spectral_arrow");
oldToNewNames.put("Spider", "minecraft:spider");
oldToNewNames.put("Squid", "minecraft:squid");
oldToNewNames.put("Stray", "minecraft:stray");
oldToNewNames.put("ThrownEgg", "minecraft:egg");
oldToNewNames.put("ThrownEnderpearl", "minecraft:ender_pearl");
oldToNewNames.put("ThrownExpBottle", "minecraft:xp_bottle");
oldToNewNames.put("ThrownPotion", "minecraft:potion");
oldToNewNames.put("Villager", "minecraft:villager");
oldToNewNames.put("VillagerGolem", "minecraft:villager_golem");
oldToNewNames.put("Witch", "minecraft:witch");
oldToNewNames.put("WitherBoss", "minecraft:wither");
oldToNewNames.put("WitherSkeleton", "minecraft:wither_skeleton");
oldToNewNames.put("WitherSkull", "minecraft:wither_skull");
oldToNewNames.put("Wolf", "minecraft:wolf");
oldToNewNames.put("XPOrb", "minecraft:xp_orb");
oldToNewNames.put("Zombie", "minecraft:zombie");
oldToNewNames.put("ZombieHorse", "minecraft:zombie_horse");
oldToNewNames.put("ZombieVillager", "minecraft:zombie_villager");
}
public static void toClient(Item item) {
if (hasEntityTag(item)) {
CompoundTag entityTag = item.getTag().get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
if (oldToNewNames.containsKey(id.getValue())) {
id.setValue(oldToNewNames.get(id.getValue()));
}
}
}
}
public static void toServer(Item item) {
if (hasEntityTag(item)) {
CompoundTag entityTag = item.getTag().get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
if (oldToNewNames.inverse().containsKey(id.getValue())) {
id.setValue(oldToNewNames.inverse().get(id.getValue()));
}
}
}
}
private static boolean hasEntityTag(Item item) {
if (item != null && item.getId() == 383) { // Monster Egg
CompoundTag tag = item.getTag();
if (tag != null && tag.contains("EntityTag") && tag.get("EntityTag") instanceof CompoundTag) {
if (((CompoundTag) tag.get("EntityTag")).get("id") instanceof StringTag) {
return true;
}
}
}
return false;
}
}
| common/src/main/java/us/myles/ViaVersion/protocols/protocol1_11to1_10/ItemRewriter.java | package us.myles.ViaVersion.protocols.protocol1_11to1_10;
import org.spacehq.opennbt.tag.builtin.CompoundTag;
import org.spacehq.opennbt.tag.builtin.StringTag;
import us.myles.ViaVersion.api.minecraft.item.Item;
public class ItemRewriter {
public static void toClient(Item item) {
if (hasEntityTag(item)) {
CompoundTag entityTag = item.getTag().get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
id.setValue("minecraft:" + id.getValue().toLowerCase());
}
}
}
public static void toServer(Item item) {
if (hasEntityTag(item)) {
CompoundTag entityTag = item.getTag().get("EntityTag");
if (entityTag.get("id") instanceof StringTag) {
StringTag id = entityTag.get("id");
String value = id.getValue().replaceAll("minecraft:", "");
if (value.length() > 1)
value = value.substring(0, 1).toUpperCase() + value.substring(1);
id.setValue(value);
}
}
}
private static boolean hasEntityTag(Item item) {
if (item != null && item.getId() == 383) { // Monster Egg
CompoundTag tag = item.getTag();
if (tag != null && tag.contains("EntityTag") && tag.get("EntityTag") instanceof CompoundTag) {
if (((CompoundTag) tag.get("EntityTag")).get("id") instanceof StringTag) {
return true;
}
}
}
return false;
}
}
| Fix spawn eggs for 1.11+ #598
| common/src/main/java/us/myles/ViaVersion/protocols/protocol1_11to1_10/ItemRewriter.java | Fix spawn eggs for 1.11+ #598 | <ide><path>ommon/src/main/java/us/myles/ViaVersion/protocols/protocol1_11to1_10/ItemRewriter.java
<ide> package us.myles.ViaVersion.protocols.protocol1_11to1_10;
<ide>
<add>import com.google.common.collect.BiMap;
<add>import com.google.common.collect.HashBiMap;
<ide> import org.spacehq.opennbt.tag.builtin.CompoundTag;
<ide> import org.spacehq.opennbt.tag.builtin.StringTag;
<ide> import us.myles.ViaVersion.api.minecraft.item.Item;
<ide>
<ide> public class ItemRewriter {
<add> private static BiMap<String, String> oldToNewNames = HashBiMap.create();
<add>
<add> static {
<add> oldToNewNames.put("AreaEffectCloud", "minecraft:area_effect_cloud");
<add> oldToNewNames.put("ArmorStand", "minecraft:armor_stand");
<add> oldToNewNames.put("Arrow", "minecraft:arrow");
<add> oldToNewNames.put("Bat", "minecraft:bat");
<add> oldToNewNames.put("Blaze", "minecraft:blaze");
<add> oldToNewNames.put("Boat", "minecraft:boat");
<add> oldToNewNames.put("CaveSpider", "minecraft:cave_spider");
<add> oldToNewNames.put("Chicken", "minecraft:chicken");
<add> oldToNewNames.put("Cow", "minecraft:cow");
<add> oldToNewNames.put("Creeper", "minecraft:creeper");
<add> oldToNewNames.put("Donkey", "minecraft:donkey");
<add> oldToNewNames.put("DragonFireball", "minecraft:dragon_fireball");
<add> oldToNewNames.put("ElderGuardian", "minecraft:elder_guardian");
<add> oldToNewNames.put("EnderCrystal", "minecraft:ender_crystal");
<add> oldToNewNames.put("EnderDragon", "minecraft:ender_dragon");
<add> oldToNewNames.put("Enderman", "minecraft:enderman");
<add> oldToNewNames.put("Endermite", "minecraft:endermite");
<add> oldToNewNames.put("EyeOfEnderSignal", "minecraft:eye_of_ender_signal");
<add> oldToNewNames.put("FallingSand", "minecraft:falling_block");
<add> oldToNewNames.put("Fireball", "minecraft:fireball");
<add> oldToNewNames.put("FireworksRocketEntity", "minecraft:fireworks_rocket");
<add> oldToNewNames.put("Ghast", "minecraft:ghast");
<add> oldToNewNames.put("Giant", "minecraft:giant");
<add> oldToNewNames.put("Guardian", "minecraft:guardian");
<add> oldToNewNames.put("Horse", "minecraft:horse");
<add> oldToNewNames.put("Husk", "minecraft:husk");
<add> oldToNewNames.put("Item", "minecraft:item");
<add> oldToNewNames.put("ItemFrame", "minecraft:item_frame");
<add> oldToNewNames.put("LavaSlime", "minecraft:magma_cube");
<add> oldToNewNames.put("LeashKnot", "minecraft:leash_knot");
<add> oldToNewNames.put("MinecartChest", "minecraft:chest_minecart");
<add> oldToNewNames.put("MinecartCommandBlock", "minecraft:commandblock_minecart");
<add> oldToNewNames.put("MinecartFurnace", "minecraft:furnace_minecart");
<add> oldToNewNames.put("MinecartHopper", "minecraft:hopper_minecart");
<add> oldToNewNames.put("MinecartRideable", "minecraft:minecart");
<add> oldToNewNames.put("MinecartSpawner", "minecraft:spawner_minecart");
<add> oldToNewNames.put("MinecartTNT", "minecraft:tnt_minecart");
<add> oldToNewNames.put("Mule", "minecraft:mule");
<add> oldToNewNames.put("MushroomCow", "minecraft:mooshroom");
<add> oldToNewNames.put("Ozelot", "minecraft:ocelot");
<add> oldToNewNames.put("Painting", "minecraft:painting");
<add> oldToNewNames.put("Pig", "minecraft:pig");
<add> oldToNewNames.put("PigZombie", "minecraft:zombie_pigman");
<add> oldToNewNames.put("PolarBear", "minecraft:polar_bear");
<add> oldToNewNames.put("PrimedTnt", "minecraft:tnt");
<add> oldToNewNames.put("Rabbit", "minecraft:rabbit");
<add> oldToNewNames.put("Sheep", "minecraft:sheep");
<add> oldToNewNames.put("Shulker", "minecraft:shulker");
<add> oldToNewNames.put("ShulkerBullet", "minecraft:shulker_bullet");
<add> oldToNewNames.put("Silverfish", "minecraft:silverfish");
<add> oldToNewNames.put("Skeleton", "minecraft:skeleton");
<add> oldToNewNames.put("SkeletonHorse", "minecraft:skeleton_horse");
<add> oldToNewNames.put("Slime", "minecraft:slime");
<add> oldToNewNames.put("SmallFireball", "minecraft:small_fireball");
<add> oldToNewNames.put("Snowball", "minecraft:snowball");
<add> oldToNewNames.put("SnowMan", "minecraft:snowman");
<add> oldToNewNames.put("SpectralArrow", "minecraft:spectral_arrow");
<add> oldToNewNames.put("Spider", "minecraft:spider");
<add> oldToNewNames.put("Squid", "minecraft:squid");
<add> oldToNewNames.put("Stray", "minecraft:stray");
<add> oldToNewNames.put("ThrownEgg", "minecraft:egg");
<add> oldToNewNames.put("ThrownEnderpearl", "minecraft:ender_pearl");
<add> oldToNewNames.put("ThrownExpBottle", "minecraft:xp_bottle");
<add> oldToNewNames.put("ThrownPotion", "minecraft:potion");
<add> oldToNewNames.put("Villager", "minecraft:villager");
<add> oldToNewNames.put("VillagerGolem", "minecraft:villager_golem");
<add> oldToNewNames.put("Witch", "minecraft:witch");
<add> oldToNewNames.put("WitherBoss", "minecraft:wither");
<add> oldToNewNames.put("WitherSkeleton", "minecraft:wither_skeleton");
<add> oldToNewNames.put("WitherSkull", "minecraft:wither_skull");
<add> oldToNewNames.put("Wolf", "minecraft:wolf");
<add> oldToNewNames.put("XPOrb", "minecraft:xp_orb");
<add> oldToNewNames.put("Zombie", "minecraft:zombie");
<add> oldToNewNames.put("ZombieHorse", "minecraft:zombie_horse");
<add> oldToNewNames.put("ZombieVillager", "minecraft:zombie_villager");
<add> }
<add>
<ide> public static void toClient(Item item) {
<ide> if (hasEntityTag(item)) {
<ide> CompoundTag entityTag = item.getTag().get("EntityTag");
<ide> if (entityTag.get("id") instanceof StringTag) {
<ide> StringTag id = entityTag.get("id");
<del> id.setValue("minecraft:" + id.getValue().toLowerCase());
<add> if (oldToNewNames.containsKey(id.getValue())) {
<add> id.setValue(oldToNewNames.get(id.getValue()));
<add> }
<ide> }
<ide> }
<ide> }
<ide> CompoundTag entityTag = item.getTag().get("EntityTag");
<ide> if (entityTag.get("id") instanceof StringTag) {
<ide> StringTag id = entityTag.get("id");
<del>
<del> String value = id.getValue().replaceAll("minecraft:", "");
<del> if (value.length() > 1)
<del> value = value.substring(0, 1).toUpperCase() + value.substring(1);
<del> id.setValue(value);
<add> if (oldToNewNames.inverse().containsKey(id.getValue())) {
<add> id.setValue(oldToNewNames.inverse().get(id.getValue()));
<add> }
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 984027f0adcd0acf6df8d26502de8c3387698f69 | 0 | jviz/jviz,jviz/jviz | //Import data from the provided url
export function load (url, options) {
return new Promise(function (resolve, reject) {
let xhttp = new XMLHttpRequest();
//let requestOptions = getDefaultRequestOptions();
//TODO: parse and use options object
//Check for no request url provided
if (typeof url !== "string" || url.trim() === "") {
return reject(Error("No url provided"));
}
//Register the ready state change listener
xhttp.onreadystatechange = function () {
if (this.readyState !== 4) {
return null;
}
//Check the response code
if (this.status < 300) {
return resolve(this.responseText); //Resolve with the response text
}
//Other: reject the promise --> error processing request
return reject(new Error(`Error code: ${this.status}`));
};
//Open the connection
xhttp.open("GET", url.trim(), true);
//Add the headers to the connection
//if (requestOptions.headers !== null) {
// Object.keys(requestOptions.headers).forEach(function () {
// xhttp.setRequestHeader(key.toLowerCase(), requestOptions.headers[key]);
// });
//}
//Perform the request
xhttp.send(null);
});
}
//Load a text file
export function loadText (url, options) {
return load(url, options);
}
//Load a JSON file
export function loadJson (url, options) {
return load(url, options).then(function (content) {
return JSON.parse(content);
});
}
| src/load.js | //Default request options
let getDefaultRequestOptions = function () {
return {
"url": null,
"headers": null
};
};
//Parse a list of headers
let parseHeaders = function (headersStr) {
let headers = {};
headersStr.split("\n").forEach(function (line) {
let items = line.trim().split(": ");
if (items.length === 2) {
headers[items[0].toLowerCase().trim()] = items[1].trim();
}
});
return headers;
};
//Import data from the provided url
export function load (options, callback) {
let xhttp = new XMLHttpRequest();
let requestOptions = getDefaultRequestOptions();
//Check for only url string provided
if (typeof options === "string") {
requestOptions.url = options;
}
else if (typeof options === "object" && options !== null) {
Object.assign(requestOptions, options);
}
//Check for no request url provided
if (requestOptions.url === null) {
throw new Error("No url provided");
}
//Register the ready state change listener
xhttp.onreadystatechange = function () {
if (this.readyState !== 4) {
return null;
}
//Call the callback function with the parsed response object
return callback({
"ok": this.status < 300,
"code": this.status,
"content": this.responseText,
"headers": parseHeaders(this.getAllResponseHeaders()),
"raw": this
});
};
//Open the connection
xhttp.open("GET", requestOptions.url, true);
//Add the headers to the connection
if (requestOptions.headers !== null) {
Object.keys(requestOptions.headers).forEach(function () {
xhttp.setRequestHeader(key.toLowerCase(), requestOptions.headers[key]);
});
}
//Perform the request
xhttp.send(null);
//Return the XMLHttpRequest instance
return xhttp;
}
//Load a text file
export function text (options, callback) {
return load(options, callback);
}
//Load a JSON file
export function json (options, callback) {
return load(options, function (response) {
//Check for a successful response to parse the response content
if (response.ok === true) {
response.content = JSON.parse(response.content);
}
return callback(response);
});
}
| Rewrite load module: using promises instead of callbacks
| src/load.js | Rewrite load module: using promises instead of callbacks | <ide><path>rc/load.js
<del>//Default request options
<del>let getDefaultRequestOptions = function () {
<del> return {
<del> "url": null,
<del> "headers": null
<del> };
<del>};
<del>//Parse a list of headers
<del>let parseHeaders = function (headersStr) {
<del> let headers = {};
<del> headersStr.split("\n").forEach(function (line) {
<del> let items = line.trim().split(": ");
<del> if (items.length === 2) {
<del> headers[items[0].toLowerCase().trim()] = items[1].trim();
<add>//Import data from the provided url
<add>export function load (url, options) {
<add> return new Promise(function (resolve, reject) {
<add> let xhttp = new XMLHttpRequest();
<add> //let requestOptions = getDefaultRequestOptions();
<add> //TODO: parse and use options object
<add> //Check for no request url provided
<add> if (typeof url !== "string" || url.trim() === "") {
<add> return reject(Error("No url provided"));
<ide> }
<add> //Register the ready state change listener
<add> xhttp.onreadystatechange = function () {
<add> if (this.readyState !== 4) {
<add> return null;
<add> }
<add> //Check the response code
<add> if (this.status < 300) {
<add> return resolve(this.responseText); //Resolve with the response text
<add> }
<add> //Other: reject the promise --> error processing request
<add> return reject(new Error(`Error code: ${this.status}`));
<add> };
<add> //Open the connection
<add> xhttp.open("GET", url.trim(), true);
<add> //Add the headers to the connection
<add> //if (requestOptions.headers !== null) {
<add> // Object.keys(requestOptions.headers).forEach(function () {
<add> // xhttp.setRequestHeader(key.toLowerCase(), requestOptions.headers[key]);
<add> // });
<add> //}
<add> //Perform the request
<add> xhttp.send(null);
<ide> });
<del> return headers;
<del>};
<del>
<del>//Import data from the provided url
<del>export function load (options, callback) {
<del> let xhttp = new XMLHttpRequest();
<del> let requestOptions = getDefaultRequestOptions();
<del> //Check for only url string provided
<del> if (typeof options === "string") {
<del> requestOptions.url = options;
<del> }
<del> else if (typeof options === "object" && options !== null) {
<del> Object.assign(requestOptions, options);
<del> }
<del> //Check for no request url provided
<del> if (requestOptions.url === null) {
<del> throw new Error("No url provided");
<del> }
<del> //Register the ready state change listener
<del> xhttp.onreadystatechange = function () {
<del> if (this.readyState !== 4) {
<del> return null;
<del> }
<del> //Call the callback function with the parsed response object
<del> return callback({
<del> "ok": this.status < 300,
<del> "code": this.status,
<del> "content": this.responseText,
<del> "headers": parseHeaders(this.getAllResponseHeaders()),
<del> "raw": this
<del> });
<del> };
<del> //Open the connection
<del> xhttp.open("GET", requestOptions.url, true);
<del> //Add the headers to the connection
<del> if (requestOptions.headers !== null) {
<del> Object.keys(requestOptions.headers).forEach(function () {
<del> xhttp.setRequestHeader(key.toLowerCase(), requestOptions.headers[key]);
<del> });
<del> }
<del> //Perform the request
<del> xhttp.send(null);
<del> //Return the XMLHttpRequest instance
<del> return xhttp;
<ide> }
<ide>
<ide> //Load a text file
<del>export function text (options, callback) {
<del> return load(options, callback);
<add>export function loadText (url, options) {
<add> return load(url, options);
<ide> }
<ide>
<ide> //Load a JSON file
<del>export function json (options, callback) {
<del> return load(options, function (response) {
<del> //Check for a successful response to parse the response content
<del> if (response.ok === true) {
<del> response.content = JSON.parse(response.content);
<del> }
<del> return callback(response);
<add>export function loadJson (url, options) {
<add> return load(url, options).then(function (content) {
<add> return JSON.parse(content);
<ide> });
<ide> }
<ide> |
|
Java | apache-2.0 | b7191188cc4711f24e6642abbea7351b28eff083 | 0 | tommyettinger/libgdx,stinsonga/libgdx,bladecoder/libgdx,NathanSweet/libgdx,NathanSweet/libgdx,tommyettinger/libgdx,Zomby2D/libgdx,Zomby2D/libgdx,libgdx/libgdx,cypherdare/libgdx,NathanSweet/libgdx,Zomby2D/libgdx,NathanSweet/libgdx,stinsonga/libgdx,Zomby2D/libgdx,stinsonga/libgdx,stinsonga/libgdx,tommyettinger/libgdx,bladecoder/libgdx,bladecoder/libgdx,tommyettinger/libgdx,cypherdare/libgdx,Zomby2D/libgdx,bladecoder/libgdx,libgdx/libgdx,tommyettinger/libgdx,NathanSweet/libgdx,libgdx/libgdx,cypherdare/libgdx,bladecoder/libgdx,cypherdare/libgdx,libgdx/libgdx,libgdx/libgdx,cypherdare/libgdx,stinsonga/libgdx | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.assets;
import java.util.Stack;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.BitmapFontLoader;
import com.badlogic.gdx.assets.loaders.CubemapLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.I18NBundleLoader;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.ParticleEffectLoader;
import com.badlogic.gdx.assets.loaders.PixmapLoader;
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader;
import com.badlogic.gdx.assets.loaders.SkinLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.TextureAtlasLoader;
import com.badlogic.gdx.assets.loaders.TextureLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Cubemap;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.PolygonRegion;
import com.badlogic.gdx.graphics.g2d.PolygonRegionLoader;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.loader.ObjLoader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.Null;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.UBJsonReader;
import com.badlogic.gdx.utils.async.AsyncExecutor;
import com.badlogic.gdx.utils.async.ThreadUtils;
import com.badlogic.gdx.utils.reflect.ClassReflection;
/** Loads and stores assets like textures, bitmapfonts, tile maps, sounds, music and so on.
* @author mzechner */
public class AssetManager implements Disposable {
final ObjectMap<Class, ObjectMap<String, RefCountedContainer>> assets = new ObjectMap();
final ObjectMap<String, Class> assetTypes = new ObjectMap();
final ObjectMap<String, Array<String>> assetDependencies = new ObjectMap();
final ObjectSet<String> injected = new ObjectSet();
final ObjectMap<Class, ObjectMap<String, AssetLoader>> loaders = new ObjectMap();
final Array<AssetDescriptor> loadQueue = new Array();
final AsyncExecutor executor;
final Array<AssetLoadingTask> tasks = new Array();
AssetErrorListener listener;
int loaded;
int toLoad;
int peakTasks;
final FileHandleResolver resolver;
Logger log = new Logger("AssetManager", Application.LOG_NONE);
/** Creates a new AssetManager with all default loaders. */
public AssetManager () {
this(new InternalFileHandleResolver());
}
/** Creates a new AssetManager with all default loaders. */
public AssetManager (FileHandleResolver resolver) {
this(resolver, true);
}
/** Creates a new AssetManager with optionally all default loaders. If you don't add the default loaders then you do have to
* manually add the loaders you need, including any loaders they might depend on.
* @param defaultLoaders whether to add the default loaders */
public AssetManager (FileHandleResolver resolver, boolean defaultLoaders) {
this.resolver = resolver;
if (defaultLoaders) {
setLoader(BitmapFont.class, new BitmapFontLoader(resolver));
setLoader(Music.class, new MusicLoader(resolver));
setLoader(Pixmap.class, new PixmapLoader(resolver));
setLoader(Sound.class, new SoundLoader(resolver));
setLoader(TextureAtlas.class, new TextureAtlasLoader(resolver));
setLoader(Texture.class, new TextureLoader(resolver));
setLoader(Skin.class, new SkinLoader(resolver));
setLoader(ParticleEffect.class, new ParticleEffectLoader(resolver));
setLoader(com.badlogic.gdx.graphics.g3d.particles.ParticleEffect.class,
new com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader(resolver));
setLoader(PolygonRegion.class, new PolygonRegionLoader(resolver));
setLoader(I18NBundle.class, new I18NBundleLoader(resolver));
setLoader(Model.class, ".g3dj", new G3dModelLoader(new JsonReader(), resolver));
setLoader(Model.class, ".g3db", new G3dModelLoader(new UBJsonReader(), resolver));
setLoader(Model.class, ".obj", new ObjLoader(resolver));
setLoader(ShaderProgram.class, new ShaderProgramLoader(resolver));
setLoader(Cubemap.class, new CubemapLoader(resolver));
}
executor = new AsyncExecutor(1, "AssetManager");
}
/** Returns the {@link FileHandleResolver} for which this AssetManager was loaded with.
* @return the file handle resolver which this AssetManager uses */
public FileHandleResolver getFileHandleResolver () {
return resolver;
}
/** @param fileName the asset file name
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (String fileName) {
return get(fileName, true);
}
/** @param fileName the asset file name
* @param type the asset type
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (String fileName, Class<T> type) {
return get(fileName, type, true);
}
/** @param fileName the asset file name
* @param required true to throw GdxRuntimeException if the asset is not loaded, else null is returned
* @return the asset or null if it is not loaded and required is false */
public synchronized @Null <T> T get (String fileName, boolean required) {
Class<T> type = assetTypes.get(fileName);
if (type != null) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) return (T)assetContainer.object;
}
}
if (required) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return null;
}
/** @param fileName the asset file name
* @param type the asset type
* @param required true to throw GdxRuntimeException if the asset is not loaded, else null is returned
* @return the asset or null if it is not loaded and required is false */
public synchronized @Null <T> T get (String fileName, Class<T> type, boolean required) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) return (T)assetContainer.object;
}
if (required) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return null;
}
/** @param assetDescriptor the asset descriptor
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (AssetDescriptor<T> assetDescriptor) {
return get(assetDescriptor.fileName, assetDescriptor.type, true);
}
/** @param type the asset type
* @return all the assets matching the specified type */
public synchronized <T> Array<T> getAll (Class<T> type, Array<T> out) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
for (RefCountedContainer assetRef : assetsByType.values())
out.add((T)assetRef.object);
}
return out;
}
/** Returns true if an asset with the specified name is loading, queued to be loaded, or has been loaded. */
public synchronized boolean contains (String fileName) {
if (tasks.size > 0 && tasks.first().assetDesc.fileName.equals(fileName)) return true;
for (int i = 0; i < loadQueue.size; i++)
if (loadQueue.get(i).fileName.equals(fileName)) return true;
return isLoaded(fileName);
}
/** Returns true if an asset with the specified name and type is loading, queued to be loaded, or has been loaded. */
public synchronized boolean contains (String fileName, Class type) {
if (tasks.size > 0) {
AssetDescriptor assetDesc = tasks.first().assetDesc;
if (assetDesc.type == type && assetDesc.fileName.equals(fileName)) return true;
}
for (int i = 0; i < loadQueue.size; i++) {
AssetDescriptor assetDesc = loadQueue.get(i);
if (assetDesc.type == type && assetDesc.fileName.equals(fileName)) return true;
}
return isLoaded(fileName, type);
}
/** Removes the asset and all its dependencies, if they are not used by other assets.
* @param fileName the file name */
public synchronized void unload (String fileName) {
// convert all windows path separators to unix style
fileName = fileName.replace('\\', '/');
// check if it's currently processed (and the first element in the stack, thus not a dependency) and cancel if necessary
if (tasks.size > 0) {
AssetLoadingTask currentTask = tasks.first();
if (currentTask.assetDesc.fileName.equals(fileName)) {
log.info("Unload (from tasks): " + fileName);
currentTask.cancel = true;
currentTask.unload();
return;
}
}
Class type = assetTypes.get(fileName);
// check if it's in the queue
int foundIndex = -1;
for (int i = 0; i < loadQueue.size; i++) {
if (loadQueue.get(i).fileName.equals(fileName)) {
foundIndex = i;
break;
}
}
if (foundIndex != -1) {
toLoad--;
AssetDescriptor desc = loadQueue.removeIndex(foundIndex);
log.info("Unload (from queue): " + fileName);
// if the queued asset was already loaded, let the callback know it is available.
if (type != null && desc.params != null && desc.params.loadedCallback != null)
desc.params.loadedCallback.finishedLoading(this, desc.fileName, desc.type);
return;
}
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
RefCountedContainer assetRef = assets.get(type).get(fileName);
// if it is reference counted, decrement ref count and check if we can really get rid of it.
assetRef.refCount--;
if (assetRef.refCount <= 0) {
log.info("Unload (dispose): " + fileName);
// if it is disposable dispose it
if (assetRef.object instanceof Disposable) ((Disposable)assetRef.object).dispose();
// remove the asset from the manager.
assetTypes.remove(fileName);
assets.get(type).remove(fileName);
} else
log.info("Unload (decrement): " + fileName);
// remove any dependencies (or just decrement their ref count).
Array<String> dependencies = assetDependencies.get(fileName);
if (dependencies != null) {
for (String dependency : dependencies)
if (isLoaded(dependency)) unload(dependency);
}
// remove dependencies if ref count < 0
if (assetRef.refCount <= 0) assetDependencies.remove(fileName);
}
/** @param asset the asset
* @return whether the asset is contained in this manager */
public synchronized <T> boolean containsAsset (T asset) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(asset.getClass());
if (assetsByType == null) return false;
for (RefCountedContainer assetRef : assetsByType.values())
if (assetRef.object == asset || asset.equals(assetRef.object)) return true;
return false;
}
/** @param asset the asset
* @return the filename of the asset or null */
public synchronized <T> String getAssetFileName (T asset) {
for (Class assetType : assets.keys()) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(assetType);
for (Entry<String, RefCountedContainer> entry : assetsByType) {
Object object = entry.value.object;
if (object == asset || asset.equals(object)) return entry.key;
}
}
return null;
}
/** @param assetDesc the AssetDescriptor of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (AssetDescriptor assetDesc) {
return isLoaded(assetDesc.fileName);
}
/** @param fileName the file name of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (String fileName) {
if (fileName == null) return false;
return assetTypes.containsKey(fileName);
}
/** @param fileName the file name of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (String fileName, Class type) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType == null) return false;
return assetsByType.get(fileName) != null;
}
/** Returns the default loader for the given type.
* @param type The type of the loader to get
* @return The loader capable of loading the type, or null if none exists */
public <T> AssetLoader getLoader (final Class<T> type) {
return getLoader(type, null);
}
/** Returns the loader for the given type and the specified filename. If no loader exists for the specific filename, the
* default loader for that type is returned.
* @param type The type of the loader to get
* @param fileName The filename of the asset to get a loader for, or null to get the default loader
* @return The loader capable of loading the type and filename, or null if none exists */
public <T> AssetLoader getLoader (final Class<T> type, final String fileName) {
ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
if (loaders == null || loaders.size < 1) return null;
if (fileName == null) return loaders.get("");
AssetLoader result = null;
int length = -1;
for (Entry<String, AssetLoader> entry : loaders.entries()) {
if (entry.key.length() > length && fileName.endsWith(entry.key)) {
result = entry.value;
length = entry.key.length();
}
}
return result;
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param fileName the file name (interpretation depends on {@link AssetLoader})
* @param type the type of the asset. */
public synchronized <T> void load (String fileName, Class<T> type) {
load(fileName, type, null);
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param fileName the file name (interpretation depends on {@link AssetLoader})
* @param type the type of the asset.
* @param parameter parameters for the AssetLoader. */
public synchronized <T> void load (String fileName, Class<T> type, AssetLoaderParameters<T> parameter) {
AssetLoader loader = getLoader(type, fileName);
if (loader == null) throw new GdxRuntimeException("No loader for type: " + ClassReflection.getSimpleName(type));
// reset stats
if (loadQueue.size == 0) {
loaded = 0;
toLoad = 0;
peakTasks = 0;
}
// check if an asset with the same name but a different type has already been added.
// check preload queue
for (int i = 0; i < loadQueue.size; i++) {
AssetDescriptor desc = loadQueue.get(i);
if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException(
"Asset with name '" + fileName + "' already in preload queue, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(desc.type) + ")");
}
// check task list
for (int i = 0; i < tasks.size; i++) {
AssetDescriptor desc = tasks.get(i).assetDesc;
if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException(
"Asset with name '" + fileName + "' already in task list, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(desc.type) + ")");
}
// check loaded assets
Class otherType = assetTypes.get(fileName);
if (otherType != null && !otherType.equals(type))
throw new GdxRuntimeException("Asset with name '" + fileName + "' already loaded, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(otherType) + ")");
toLoad++;
AssetDescriptor assetDesc = new AssetDescriptor(fileName, type, parameter);
loadQueue.add(assetDesc);
log.debug("Queued: " + assetDesc);
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param desc the {@link AssetDescriptor} */
public synchronized void load (AssetDescriptor desc) {
load(desc.fileName, desc.type, desc.params);
}
/** Updates the AssetManager for a single task. Returns if the current task is still being processed or there are no tasks,
* otherwise it finishes the current task and starts the next task.
* @return true if all loading is finished. */
public synchronized boolean update () {
try {
if (tasks.size == 0) {
// loop until we have a new task ready to be processed
while (loadQueue.size != 0 && tasks.size == 0)
nextTask();
// have we not found a task? We are done!
if (tasks.size == 0) return true;
}
return updateTask() && loadQueue.size == 0 && tasks.size == 0;
} catch (Throwable t) {
handleTaskError(t);
return loadQueue.size == 0;
}
}
/** Updates the AssetManager continuously for the specified number of milliseconds, yielding the CPU to the loading thread
* between updates. This may block for less time if all loading tasks are complete. This may block for more time if the portion
* of a single task that happens in the GL thread takes a long time.
* @return true if all loading is finished. */
public boolean update (int millis) {
long endTime = TimeUtils.millis() + millis;
while (true) {
boolean done = update();
if (done || TimeUtils.millis() > endTime) return done;
ThreadUtils.yield();
}
}
/** Returns true when all assets are loaded. Can be called from any thread but note {@link #update()} or related methods must
* be called to process tasks. */
public synchronized boolean isFinished () {
return loadQueue.size == 0 && tasks.size == 0;
}
/** Blocks until all assets are loaded. */
public void finishLoading () {
log.debug("Waiting for loading to complete...");
while (!update())
ThreadUtils.yield();
log.debug("Loading complete.");
}
/** Blocks until the specified asset is loaded.
* @param assetDesc the AssetDescriptor of the asset */
public <T> T finishLoadingAsset (AssetDescriptor assetDesc) {
return finishLoadingAsset(assetDesc.fileName);
}
/** Blocks until the specified asset is loaded.
* @param fileName the file name (interpretation depends on {@link AssetLoader}) */
public <T> T finishLoadingAsset (String fileName) {
log.debug("Waiting for asset to be loaded: " + fileName);
while (true) {
synchronized (this) {
Class<T> type = assetTypes.get(fileName);
if (type != null) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) {
log.debug("Asset loaded: " + fileName);
return (T)assetContainer.object;
}
}
}
update();
}
ThreadUtils.yield();
}
}
synchronized void injectDependencies (String parentAssetFilename, Array<AssetDescriptor> dependendAssetDescs) {
ObjectSet<String> injected = this.injected;
for (AssetDescriptor desc : dependendAssetDescs) {
if (injected.contains(desc.fileName)) continue; // Ignore subsequent dependencies if there are duplicates.
injected.add(desc.fileName);
injectDependency(parentAssetFilename, desc);
}
injected.clear(32);
}
private synchronized void injectDependency (String parentAssetFilename, AssetDescriptor dependendAssetDesc) {
// add the asset as a dependency of the parent asset
Array<String> dependencies = assetDependencies.get(parentAssetFilename);
if (dependencies == null) {
dependencies = new Array();
assetDependencies.put(parentAssetFilename, dependencies);
}
dependencies.add(dependendAssetDesc.fileName);
// if the asset is already loaded, increase its reference count.
if (isLoaded(dependendAssetDesc.fileName)) {
log.debug("Dependency already loaded: " + dependendAssetDesc);
Class type = assetTypes.get(dependendAssetDesc.fileName);
RefCountedContainer assetRef = assets.get(type).get(dependendAssetDesc.fileName);
assetRef.refCount++;
incrementRefCountedDependencies(dependendAssetDesc.fileName);
} else {
// else add a new task for the asset.
log.info("Loading dependency: " + dependendAssetDesc);
addTask(dependendAssetDesc);
}
}
/** Removes a task from the loadQueue and adds it to the task stack. If the asset is already loaded (which can happen if it was
* a dependency of a previously loaded asset) its reference count will be increased. */
private void nextTask () {
AssetDescriptor assetDesc = loadQueue.removeIndex(0);
// if the asset not meant to be reloaded and is already loaded, increase its reference count
if (isLoaded(assetDesc.fileName)) {
log.debug("Already loaded: " + assetDesc);
Class type = assetTypes.get(assetDesc.fileName);
RefCountedContainer assetRef = assets.get(type).get(assetDesc.fileName);
assetRef.refCount++;
incrementRefCountedDependencies(assetDesc.fileName);
if (assetDesc.params != null && assetDesc.params.loadedCallback != null)
assetDesc.params.loadedCallback.finishedLoading(this, assetDesc.fileName, assetDesc.type);
loaded++;
} else {
// else add a new task for the asset.
log.info("Loading: " + assetDesc);
addTask(assetDesc);
}
}
/** Adds a {@link AssetLoadingTask} to the task stack for the given asset. */
private void addTask (AssetDescriptor assetDesc) {
AssetLoader loader = getLoader(assetDesc.type, assetDesc.fileName);
if (loader == null) throw new GdxRuntimeException("No loader for type: " + ClassReflection.getSimpleName(assetDesc.type));
tasks.add(new AssetLoadingTask(this, assetDesc, loader, executor));
peakTasks++;
}
/** Adds an asset to this AssetManager */
protected <T> void addAsset (final String fileName, Class<T> type, T asset) {
// add the asset to the filename lookup
assetTypes.put(fileName, type);
// add the asset to the type lookup
ObjectMap<String, RefCountedContainer> typeToAssets = assets.get(type);
if (typeToAssets == null) {
typeToAssets = new ObjectMap<String, RefCountedContainer>();
assets.put(type, typeToAssets);
}
RefCountedContainer assetRef = new RefCountedContainer();
assetRef.object = asset;
typeToAssets.put(fileName, assetRef);
}
/** Updates the current task on the top of the task stack.
* @return true if the asset is loaded or the task was cancelled. */
private boolean updateTask () {
AssetLoadingTask task = tasks.peek();
boolean complete = true;
try {
complete = task.cancel || task.update();
} catch (RuntimeException ex) {
task.cancel = true;
taskFailed(task.assetDesc, ex);
}
// if the task has been cancelled or has finished loading
if (complete) {
// increase the number of loaded assets and pop the task from the stack
if (tasks.size == 1) {
loaded++;
peakTasks = 0;
}
tasks.pop();
if (task.cancel) return true;
addAsset(task.assetDesc.fileName, task.assetDesc.type, task.asset);
// otherwise, if a listener was found in the parameter invoke it
if (task.assetDesc.params != null && task.assetDesc.params.loadedCallback != null)
task.assetDesc.params.loadedCallback.finishedLoading(this, task.assetDesc.fileName, task.assetDesc.type);
long endTime = TimeUtils.nanoTime();
log.debug("Loaded: " + (endTime - task.startTime) / 1000000f + "ms " + task.assetDesc);
return true;
}
return false;
}
/** Called when a task throws an exception during loading. The default implementation rethrows the exception. A subclass may
* supress the default implementation when loading assets where loading failure is recoverable. */
protected void taskFailed (AssetDescriptor assetDesc, RuntimeException ex) {
throw ex;
}
private void incrementRefCountedDependencies (String parent) {
Array<String> dependencies = assetDependencies.get(parent);
if (dependencies == null) return;
for (String dependency : dependencies) {
Class type = assetTypes.get(dependency);
RefCountedContainer assetRef = assets.get(type).get(dependency);
assetRef.refCount++;
incrementRefCountedDependencies(dependency);
}
}
/** Handles a runtime/loading error in {@link #update()} by optionally invoking the {@link AssetErrorListener}.
* @param t */
private void handleTaskError (Throwable t) {
log.error("Error loading asset.", t);
if (tasks.isEmpty()) throw new GdxRuntimeException(t);
// pop the faulty task from the stack
AssetLoadingTask task = tasks.pop();
AssetDescriptor assetDesc = task.assetDesc;
// remove all dependencies
if (task.dependenciesLoaded && task.dependencies != null) {
for (AssetDescriptor desc : task.dependencies)
unload(desc.fileName);
}
// clear the rest of the stack
tasks.clear();
// inform the listener that something bad happened
if (listener != null)
listener.error(assetDesc, t);
else
throw new GdxRuntimeException(t);
}
/** Sets a new {@link AssetLoader} for the given type.
* @param type the type of the asset
* @param loader the loader */
public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, AssetLoader<T, P> loader) {
setLoader(type, null, loader);
}
/** Sets a new {@link AssetLoader} for the given type.
* @param type the type of the asset
* @param suffix the suffix the filename must have for this loader to be used or null to specify the default loader.
* @param loader the loader */
public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, String suffix,
AssetLoader<T, P> loader) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (loader == null) throw new IllegalArgumentException("loader cannot be null.");
log.debug("Loader set: " + ClassReflection.getSimpleName(type) + " -> " + ClassReflection.getSimpleName(loader.getClass()));
ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
if (loaders == null) this.loaders.put(type, loaders = new ObjectMap<String, AssetLoader>());
loaders.put(suffix == null ? "" : suffix, loader);
}
/** @return the number of loaded assets */
public synchronized int getLoadedAssets () {
return assetTypes.size;
}
/** @return the number of currently queued assets */
public synchronized int getQueuedAssets () {
return loadQueue.size + tasks.size;
}
/** @return the progress in percent of completion. */
public synchronized float getProgress () {
if (toLoad == 0) return 1;
float fractionalLoaded = loaded;
if (peakTasks > 0) {
fractionalLoaded += ((peakTasks - tasks.size) / (float)peakTasks);
}
return Math.min(1, fractionalLoaded / toLoad);
}
/** Sets an {@link AssetErrorListener} to be invoked in case loading an asset failed.
* @param listener the listener or null */
public synchronized void setErrorListener (AssetErrorListener listener) {
this.listener = listener;
}
/** Disposes all assets in the manager and stops all asynchronous loading. */
@Override
public synchronized void dispose () {
log.debug("Disposing.");
clear();
executor.dispose();
}
/** Clears and disposes all assets and the preloading queue. */
public synchronized void clear () {
loadQueue.clear();
while (!update()) {
}
ObjectIntMap<String> dependencyCount = new ObjectIntMap<String>();
while (assetTypes.size > 0) {
// for each asset, figure out how often it was referenced
dependencyCount.clear();
Array<String> assets = assetTypes.keys().toArray();
for (String asset : assets) {
Array<String> dependencies = assetDependencies.get(asset);
if (dependencies == null) continue;
for (String dependency : dependencies)
dependencyCount.getAndIncrement(dependency, 0, 1);
}
// only dispose of assets that are root assets (not referenced)
for (String asset : assets)
if (dependencyCount.get(asset, 0) == 0) unload(asset);
}
this.assets.clear();
this.assetTypes.clear();
this.assetDependencies.clear();
this.loaded = 0;
this.toLoad = 0;
this.peakTasks = 0;
this.loadQueue.clear();
this.tasks.clear();
}
/** @return the {@link Logger} used by the {@link AssetManager} */
public Logger getLogger () {
return log;
}
public void setLogger (Logger logger) {
log = logger;
}
/** Returns the reference count of an asset.
* @param fileName */
public synchronized int getReferenceCount (String fileName) {
Class type = assetTypes.get(fileName);
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return assets.get(type).get(fileName).refCount;
}
/** Sets the reference count of an asset.
* @param fileName */
public synchronized void setReferenceCount (String fileName, int refCount) {
Class type = assetTypes.get(fileName);
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
assets.get(type).get(fileName).refCount = refCount;
}
/** @return a string containing ref count and dependency information for all assets. */
public synchronized String getDiagnostics () {
StringBuilder buffer = new StringBuilder(256);
for (Entry<String, Class> entry : assetTypes) {
String fileName = entry.key;
Class type = entry.value;
if (buffer.length() > 0) buffer.append('\n');
buffer.append(fileName);
buffer.append(", ");
buffer.append(ClassReflection.getSimpleName(type));
buffer.append(", refs: ");
buffer.append(assets.get(type).get(fileName).refCount);
Array<String> dependencies = assetDependencies.get(fileName);
if (dependencies != null) {
buffer.append(", deps: [");
for (String dep : dependencies) {
buffer.append(dep);
buffer.append(',');
}
buffer.append(']');
}
}
return buffer.toString();
}
/** @return the file names of all loaded assets. */
public synchronized Array<String> getAssetNames () {
return assetTypes.keys().toArray();
}
/** @return the dependencies of an asset or null if the asset has no dependencies. */
public synchronized Array<String> getDependencies (String fileName) {
return assetDependencies.get(fileName);
}
/** @return the type of a loaded asset. */
public synchronized Class getAssetType (String fileName) {
return assetTypes.get(fileName);
}
static class RefCountedContainer {
Object object;
int refCount = 1;
}
}
| gdx/src/com/badlogic/gdx/assets/AssetManager.java | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.assets;
import java.util.Stack;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.BitmapFontLoader;
import com.badlogic.gdx.assets.loaders.CubemapLoader;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.I18NBundleLoader;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.ParticleEffectLoader;
import com.badlogic.gdx.assets.loaders.PixmapLoader;
import com.badlogic.gdx.assets.loaders.ShaderProgramLoader;
import com.badlogic.gdx.assets.loaders.SkinLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.TextureAtlasLoader;
import com.badlogic.gdx.assets.loaders.TextureLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Cubemap;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.PolygonRegion;
import com.badlogic.gdx.graphics.g2d.PolygonRegionLoader;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader;
import com.badlogic.gdx.graphics.g3d.loader.ObjLoader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.Null;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectSet;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.UBJsonReader;
import com.badlogic.gdx.utils.async.AsyncExecutor;
import com.badlogic.gdx.utils.async.ThreadUtils;
import com.badlogic.gdx.utils.reflect.ClassReflection;
/** Loads and stores assets like textures, bitmapfonts, tile maps, sounds, music and so on.
* @author mzechner */
public class AssetManager implements Disposable {
final ObjectMap<Class, ObjectMap<String, RefCountedContainer>> assets = new ObjectMap();
final ObjectMap<String, Class> assetTypes = new ObjectMap();
final ObjectMap<String, Array<String>> assetDependencies = new ObjectMap();
final ObjectSet<String> injected = new ObjectSet();
final ObjectMap<Class, ObjectMap<String, AssetLoader>> loaders = new ObjectMap();
final Array<AssetDescriptor> loadQueue = new Array();
final AsyncExecutor executor;
final Stack<AssetLoadingTask> tasks = new Stack();
AssetErrorListener listener;
int loaded;
int toLoad;
int peakTasks;
final FileHandleResolver resolver;
Logger log = new Logger("AssetManager", Application.LOG_NONE);
/** Creates a new AssetManager with all default loaders. */
public AssetManager () {
this(new InternalFileHandleResolver());
}
/** Creates a new AssetManager with all default loaders. */
public AssetManager (FileHandleResolver resolver) {
this(resolver, true);
}
/** Creates a new AssetManager with optionally all default loaders. If you don't add the default loaders then you do have to
* manually add the loaders you need, including any loaders they might depend on.
* @param defaultLoaders whether to add the default loaders */
public AssetManager (FileHandleResolver resolver, boolean defaultLoaders) {
this.resolver = resolver;
if (defaultLoaders) {
setLoader(BitmapFont.class, new BitmapFontLoader(resolver));
setLoader(Music.class, new MusicLoader(resolver));
setLoader(Pixmap.class, new PixmapLoader(resolver));
setLoader(Sound.class, new SoundLoader(resolver));
setLoader(TextureAtlas.class, new TextureAtlasLoader(resolver));
setLoader(Texture.class, new TextureLoader(resolver));
setLoader(Skin.class, new SkinLoader(resolver));
setLoader(ParticleEffect.class, new ParticleEffectLoader(resolver));
setLoader(com.badlogic.gdx.graphics.g3d.particles.ParticleEffect.class,
new com.badlogic.gdx.graphics.g3d.particles.ParticleEffectLoader(resolver));
setLoader(PolygonRegion.class, new PolygonRegionLoader(resolver));
setLoader(I18NBundle.class, new I18NBundleLoader(resolver));
setLoader(Model.class, ".g3dj", new G3dModelLoader(new JsonReader(), resolver));
setLoader(Model.class, ".g3db", new G3dModelLoader(new UBJsonReader(), resolver));
setLoader(Model.class, ".obj", new ObjLoader(resolver));
setLoader(ShaderProgram.class, new ShaderProgramLoader(resolver));
setLoader(Cubemap.class, new CubemapLoader(resolver));
}
executor = new AsyncExecutor(1, "AssetManager");
}
/** Returns the {@link FileHandleResolver} for which this AssetManager was loaded with.
* @return the file handle resolver which this AssetManager uses */
public FileHandleResolver getFileHandleResolver () {
return resolver;
}
/** @param fileName the asset file name
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (String fileName) {
return get(fileName, true);
}
/** @param fileName the asset file name
* @param type the asset type
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (String fileName, Class<T> type) {
return get(fileName, type, true);
}
/** @param fileName the asset file name
* @param required true to throw GdxRuntimeException if the asset is not loaded, else null is returned
* @return the asset or null if it is not loaded and required is false */
public synchronized @Null <T> T get (String fileName, boolean required) {
Class<T> type = assetTypes.get(fileName);
if (type != null) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) return (T)assetContainer.object;
}
}
if (required) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return null;
}
/** @param fileName the asset file name
* @param type the asset type
* @param required true to throw GdxRuntimeException if the asset is not loaded, else null is returned
* @return the asset or null if it is not loaded and required is false */
public synchronized @Null <T> T get (String fileName, Class<T> type, boolean required) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) return (T)assetContainer.object;
}
if (required) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return null;
}
/** @param assetDescriptor the asset descriptor
* @return the asset
* @throws GdxRuntimeException if the asset is not loaded */
public synchronized <T> T get (AssetDescriptor<T> assetDescriptor) {
return get(assetDescriptor.fileName, assetDescriptor.type, true);
}
/** @param type the asset type
* @return all the assets matching the specified type */
public synchronized <T> Array<T> getAll (Class<T> type, Array<T> out) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
for (ObjectMap.Entry<String, RefCountedContainer> asset : assetsByType.entries())
out.add((T)asset.value.object);
}
return out;
}
/** Returns true if an asset with the specified name is loading, queued to be loaded, or has been loaded. */
public synchronized boolean contains (String fileName) {
if (tasks.size() > 0 && tasks.firstElement().assetDesc.fileName.equals(fileName)) return true;
for (int i = 0; i < loadQueue.size; i++)
if (loadQueue.get(i).fileName.equals(fileName)) return true;
return isLoaded(fileName);
}
/** Returns true if an asset with the specified name and type is loading, queued to be loaded, or has been loaded. */
public synchronized boolean contains (String fileName, Class type) {
if (tasks.size() > 0) {
AssetDescriptor assetDesc = tasks.firstElement().assetDesc;
if (assetDesc.type == type && assetDesc.fileName.equals(fileName)) return true;
}
for (int i = 0; i < loadQueue.size; i++) {
AssetDescriptor assetDesc = loadQueue.get(i);
if (assetDesc.type == type && assetDesc.fileName.equals(fileName)) return true;
}
return isLoaded(fileName, type);
}
/** Removes the asset and all its dependencies, if they are not used by other assets.
* @param fileName the file name */
public synchronized void unload (String fileName) {
// convert all windows path separators to unix style
fileName = fileName.replace('\\', '/');
// check if it's currently processed (and the first element in the stack, thus not a dependency) and cancel if necessary
if (tasks.size() > 0) {
AssetLoadingTask currentTask = tasks.firstElement();
if (currentTask.assetDesc.fileName.equals(fileName)) {
log.info("Unload (from tasks): " + fileName);
currentTask.cancel = true;
currentTask.unload();
return;
}
}
Class type = assetTypes.get(fileName);
// check if it's in the queue
int foundIndex = -1;
for (int i = 0; i < loadQueue.size; i++) {
if (loadQueue.get(i).fileName.equals(fileName)) {
foundIndex = i;
break;
}
}
if (foundIndex != -1) {
toLoad--;
AssetDescriptor desc = loadQueue.removeIndex(foundIndex);
log.info("Unload (from queue): " + fileName);
// if the queued asset was already loaded, let the callback know it is available.
if (type != null && desc.params != null && desc.params.loadedCallback != null)
desc.params.loadedCallback.finishedLoading(this, desc.fileName, desc.type);
return;
}
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
RefCountedContainer assetRef = assets.get(type).get(fileName);
// if it is reference counted, decrement ref count and check if we can really get rid of it.
assetRef.refCount--;
if (assetRef.refCount <= 0) {
log.info("Unload (dispose): " + fileName);
// if it is disposable dispose it
if (assetRef.object instanceof Disposable) ((Disposable)assetRef.object).dispose();
// remove the asset from the manager.
assetTypes.remove(fileName);
assets.get(type).remove(fileName);
} else
log.info("Unload (decrement): " + fileName);
// remove any dependencies (or just decrement their ref count).
Array<String> dependencies = assetDependencies.get(fileName);
if (dependencies != null) {
for (String dependency : dependencies)
if (isLoaded(dependency)) unload(dependency);
}
// remove dependencies if ref count < 0
if (assetRef.refCount <= 0) assetDependencies.remove(fileName);
}
/** @param asset the asset
* @return whether the asset is contained in this manager */
public synchronized <T> boolean containsAsset (T asset) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(asset.getClass());
if (assetsByType == null) return false;
for (String fileName : assetsByType.keys()) {
Object otherAsset = assetsByType.get(fileName).object;
if (otherAsset == asset || asset.equals(otherAsset)) return true;
}
return false;
}
/** @param asset the asset
* @return the filename of the asset or null */
public synchronized <T> String getAssetFileName (T asset) {
for (Class assetType : assets.keys()) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(assetType);
for (String fileName : assetsByType.keys()) {
Object otherAsset = assetsByType.get(fileName).object;
if (otherAsset == asset || asset.equals(otherAsset)) return fileName;
}
}
return null;
}
/** @param assetDesc the AssetDescriptor of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (AssetDescriptor assetDesc) {
return isLoaded(assetDesc.fileName);
}
/** @param fileName the file name of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (String fileName) {
if (fileName == null) return false;
return assetTypes.containsKey(fileName);
}
/** @param fileName the file name of the asset
* @return whether the asset is loaded */
public synchronized boolean isLoaded (String fileName, Class type) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType == null) return false;
return assetsByType.get(fileName) != null;
}
/** Returns the default loader for the given type.
* @param type The type of the loader to get
* @return The loader capable of loading the type, or null if none exists */
public <T> AssetLoader getLoader (final Class<T> type) {
return getLoader(type, null);
}
/** Returns the loader for the given type and the specified filename. If no loader exists for the specific filename, the
* default loader for that type is returned.
* @param type The type of the loader to get
* @param fileName The filename of the asset to get a loader for, or null to get the default loader
* @return The loader capable of loading the type and filename, or null if none exists */
public <T> AssetLoader getLoader (final Class<T> type, final String fileName) {
final ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
if (loaders == null || loaders.size < 1) return null;
if (fileName == null) return loaders.get("");
AssetLoader result = null;
int l = -1;
for (ObjectMap.Entry<String, AssetLoader> entry : loaders.entries()) {
if (entry.key.length() > l && fileName.endsWith(entry.key)) {
result = entry.value;
l = entry.key.length();
}
}
return result;
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param fileName the file name (interpretation depends on {@link AssetLoader})
* @param type the type of the asset. */
public synchronized <T> void load (String fileName, Class<T> type) {
load(fileName, type, null);
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param fileName the file name (interpretation depends on {@link AssetLoader})
* @param type the type of the asset.
* @param parameter parameters for the AssetLoader. */
public synchronized <T> void load (String fileName, Class<T> type, AssetLoaderParameters<T> parameter) {
AssetLoader loader = getLoader(type, fileName);
if (loader == null) throw new GdxRuntimeException("No loader for type: " + ClassReflection.getSimpleName(type));
// reset stats
if (loadQueue.size == 0) {
loaded = 0;
toLoad = 0;
peakTasks = 0;
}
// check if an asset with the same name but a different type has already been added.
// check preload queue
for (int i = 0; i < loadQueue.size; i++) {
AssetDescriptor desc = loadQueue.get(i);
if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException(
"Asset with name '" + fileName + "' already in preload queue, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(desc.type) + ")");
}
// check task list
for (int i = 0; i < tasks.size(); i++) {
AssetDescriptor desc = tasks.get(i).assetDesc;
if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException(
"Asset with name '" + fileName + "' already in task list, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(desc.type) + ")");
}
// check loaded assets
Class otherType = assetTypes.get(fileName);
if (otherType != null && !otherType.equals(type))
throw new GdxRuntimeException("Asset with name '" + fileName + "' already loaded, but has different type (expected: "
+ ClassReflection.getSimpleName(type) + ", found: " + ClassReflection.getSimpleName(otherType) + ")");
toLoad++;
AssetDescriptor assetDesc = new AssetDescriptor(fileName, type, parameter);
loadQueue.add(assetDesc);
log.debug("Queued: " + assetDesc);
}
/** Adds the given asset to the loading queue of the AssetManager.
* @param desc the {@link AssetDescriptor} */
public synchronized void load (AssetDescriptor desc) {
load(desc.fileName, desc.type, desc.params);
}
/** Updates the AssetManager for a single task. Returns if the current task is still being processed or there are no tasks,
* otherwise it finishes the current task and starts the next task.
* @return true if all loading is finished. */
public synchronized boolean update () {
try {
if (tasks.size() == 0) {
// loop until we have a new task ready to be processed
while (loadQueue.size != 0 && tasks.size() == 0)
nextTask();
// have we not found a task? We are done!
if (tasks.size() == 0) return true;
}
return updateTask() && loadQueue.size == 0 && tasks.size() == 0;
} catch (Throwable t) {
handleTaskError(t);
return loadQueue.size == 0;
}
}
/** Updates the AssetManager continuously for the specified number of milliseconds, yielding the CPU to the loading thread
* between updates. This may block for less time if all loading tasks are complete. This may block for more time if the portion
* of a single task that happens in the GL thread takes a long time.
* @return true if all loading is finished. */
public boolean update (int millis) {
long endTime = TimeUtils.millis() + millis;
while (true) {
boolean done = update();
if (done || TimeUtils.millis() > endTime) return done;
ThreadUtils.yield();
}
}
/** Returns true when all assets are loaded. Can be called from any thread but note {@link #update()} or related methods must
* be called to process tasks. */
public synchronized boolean isFinished () {
return loadQueue.size == 0 && tasks.size() == 0;
}
/** Blocks until all assets are loaded. */
public void finishLoading () {
log.debug("Waiting for loading to complete...");
while (!update())
ThreadUtils.yield();
log.debug("Loading complete.");
}
/** Blocks until the specified asset is loaded.
* @param assetDesc the AssetDescriptor of the asset */
public <T> T finishLoadingAsset (AssetDescriptor assetDesc) {
return finishLoadingAsset(assetDesc.fileName);
}
/** Blocks until the specified asset is loaded.
* @param fileName the file name (interpretation depends on {@link AssetLoader}) */
public <T> T finishLoadingAsset (String fileName) {
log.debug("Waiting for asset to be loaded: " + fileName);
while (true) {
synchronized (this) {
Class<T> type = assetTypes.get(fileName);
if (type != null) {
ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
if (assetsByType != null) {
RefCountedContainer assetContainer = assetsByType.get(fileName);
if (assetContainer != null) {
log.debug("Asset loaded: " + fileName);
return (T)assetContainer.object;
}
}
}
update();
}
ThreadUtils.yield();
}
}
synchronized void injectDependencies (String parentAssetFilename, Array<AssetDescriptor> dependendAssetDescs) {
ObjectSet<String> injected = this.injected;
for (AssetDescriptor desc : dependendAssetDescs) {
if (injected.contains(desc.fileName)) continue; // Ignore subsequent dependencies if there are duplicates.
injected.add(desc.fileName);
injectDependency(parentAssetFilename, desc);
}
injected.clear(32);
}
private synchronized void injectDependency (String parentAssetFilename, AssetDescriptor dependendAssetDesc) {
// add the asset as a dependency of the parent asset
Array<String> dependencies = assetDependencies.get(parentAssetFilename);
if (dependencies == null) {
dependencies = new Array();
assetDependencies.put(parentAssetFilename, dependencies);
}
dependencies.add(dependendAssetDesc.fileName);
// if the asset is already loaded, increase its reference count.
if (isLoaded(dependendAssetDesc.fileName)) {
log.debug("Dependency already loaded: " + dependendAssetDesc);
Class type = assetTypes.get(dependendAssetDesc.fileName);
RefCountedContainer assetRef = assets.get(type).get(dependendAssetDesc.fileName);
assetRef.refCount++;
incrementRefCountedDependencies(dependendAssetDesc.fileName);
} else {
// else add a new task for the asset.
log.info("Loading dependency: " + dependendAssetDesc);
addTask(dependendAssetDesc);
}
}
/** Removes a task from the loadQueue and adds it to the task stack. If the asset is already loaded (which can happen if it was
* a dependency of a previously loaded asset) its reference count will be increased. */
private void nextTask () {
AssetDescriptor assetDesc = loadQueue.removeIndex(0);
// if the asset not meant to be reloaded and is already loaded, increase its reference count
if (isLoaded(assetDesc.fileName)) {
log.debug("Already loaded: " + assetDesc);
Class type = assetTypes.get(assetDesc.fileName);
RefCountedContainer assetRef = assets.get(type).get(assetDesc.fileName);
assetRef.refCount++;
incrementRefCountedDependencies(assetDesc.fileName);
if (assetDesc.params != null && assetDesc.params.loadedCallback != null)
assetDesc.params.loadedCallback.finishedLoading(this, assetDesc.fileName, assetDesc.type);
loaded++;
} else {
// else add a new task for the asset.
log.info("Loading: " + assetDesc);
addTask(assetDesc);
}
}
/** Adds a {@link AssetLoadingTask} to the task stack for the given asset. */
private void addTask (AssetDescriptor assetDesc) {
AssetLoader loader = getLoader(assetDesc.type, assetDesc.fileName);
if (loader == null) throw new GdxRuntimeException("No loader for type: " + ClassReflection.getSimpleName(assetDesc.type));
tasks.push(new AssetLoadingTask(this, assetDesc, loader, executor));
peakTasks++;
}
/** Adds an asset to this AssetManager */
protected <T> void addAsset (final String fileName, Class<T> type, T asset) {
// add the asset to the filename lookup
assetTypes.put(fileName, type);
// add the asset to the type lookup
ObjectMap<String, RefCountedContainer> typeToAssets = assets.get(type);
if (typeToAssets == null) {
typeToAssets = new ObjectMap<String, RefCountedContainer>();
assets.put(type, typeToAssets);
}
RefCountedContainer assetRef = new RefCountedContainer();
assetRef.object = asset;
typeToAssets.put(fileName, assetRef);
}
/** Updates the current task on the top of the task stack.
* @return true if the asset is loaded or the task was cancelled. */
private boolean updateTask () {
AssetLoadingTask task = tasks.peek();
boolean complete = true;
try {
complete = task.cancel || task.update();
} catch (RuntimeException ex) {
task.cancel = true;
taskFailed(task.assetDesc, ex);
}
// if the task has been cancelled or has finished loading
if (complete) {
// increase the number of loaded assets and pop the task from the stack
if (tasks.size() == 1) {
loaded++;
peakTasks = 0;
}
tasks.pop();
if (task.cancel) return true;
addAsset(task.assetDesc.fileName, task.assetDesc.type, task.asset);
// otherwise, if a listener was found in the parameter invoke it
if (task.assetDesc.params != null && task.assetDesc.params.loadedCallback != null)
task.assetDesc.params.loadedCallback.finishedLoading(this, task.assetDesc.fileName, task.assetDesc.type);
long endTime = TimeUtils.nanoTime();
log.debug("Loaded: " + (endTime - task.startTime) / 1000000f + "ms " + task.assetDesc);
return true;
}
return false;
}
/** Called when a task throws an exception during loading. The default implementation rethrows the exception. A subclass may
* supress the default implementation when loading assets where loading failure is recoverable. */
protected void taskFailed (AssetDescriptor assetDesc, RuntimeException ex) {
throw ex;
}
private void incrementRefCountedDependencies (String parent) {
Array<String> dependencies = assetDependencies.get(parent);
if (dependencies == null) return;
for (String dependency : dependencies) {
Class type = assetTypes.get(dependency);
RefCountedContainer assetRef = assets.get(type).get(dependency);
assetRef.refCount++;
incrementRefCountedDependencies(dependency);
}
}
/** Handles a runtime/loading error in {@link #update()} by optionally invoking the {@link AssetErrorListener}.
* @param t */
private void handleTaskError (Throwable t) {
log.error("Error loading asset.", t);
if (tasks.isEmpty()) throw new GdxRuntimeException(t);
// pop the faulty task from the stack
AssetLoadingTask task = tasks.pop();
AssetDescriptor assetDesc = task.assetDesc;
// remove all dependencies
if (task.dependenciesLoaded && task.dependencies != null) {
for (AssetDescriptor desc : task.dependencies)
unload(desc.fileName);
}
// clear the rest of the stack
tasks.clear();
// inform the listener that something bad happened
if (listener != null)
listener.error(assetDesc, t);
else
throw new GdxRuntimeException(t);
}
/** Sets a new {@link AssetLoader} for the given type.
* @param type the type of the asset
* @param loader the loader */
public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, AssetLoader<T, P> loader) {
setLoader(type, null, loader);
}
/** Sets a new {@link AssetLoader} for the given type.
* @param type the type of the asset
* @param suffix the suffix the filename must have for this loader to be used or null to specify the default loader.
* @param loader the loader */
public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, String suffix,
AssetLoader<T, P> loader) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (loader == null) throw new IllegalArgumentException("loader cannot be null.");
log.debug("Loader set: " + ClassReflection.getSimpleName(type) + " -> " + ClassReflection.getSimpleName(loader.getClass()));
ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
if (loaders == null) this.loaders.put(type, loaders = new ObjectMap<String, AssetLoader>());
loaders.put(suffix == null ? "" : suffix, loader);
}
/** @return the number of loaded assets */
public synchronized int getLoadedAssets () {
return assetTypes.size;
}
/** @return the number of currently queued assets */
public synchronized int getQueuedAssets () {
return loadQueue.size + tasks.size();
}
/** @return the progress in percent of completion. */
public synchronized float getProgress () {
if (toLoad == 0) return 1;
float fractionalLoaded = loaded;
if (peakTasks > 0) {
fractionalLoaded += ((peakTasks - tasks.size()) / (float)peakTasks);
}
return Math.min(1, fractionalLoaded / toLoad);
}
/** Sets an {@link AssetErrorListener} to be invoked in case loading an asset failed.
* @param listener the listener or null */
public synchronized void setErrorListener (AssetErrorListener listener) {
this.listener = listener;
}
/** Disposes all assets in the manager and stops all asynchronous loading. */
@Override
public synchronized void dispose () {
log.debug("Disposing.");
clear();
executor.dispose();
}
/** Clears and disposes all assets and the preloading queue. */
public synchronized void clear () {
loadQueue.clear();
while (!update())
;
ObjectIntMap<String> dependencyCount = new ObjectIntMap<String>();
while (assetTypes.size > 0) {
// for each asset, figure out how often it was referenced
dependencyCount.clear();
Array<String> assets = assetTypes.keys().toArray();
for (String asset : assets)
dependencyCount.put(asset, 0);
for (String asset : assets) {
Array<String> dependencies = assetDependencies.get(asset);
if (dependencies == null) continue;
for (String dependency : dependencies) {
int count = dependencyCount.get(dependency, 0);
count++;
dependencyCount.put(dependency, count);
}
}
// only dispose of assets that are root assets (not referenced)
for (String asset : assets)
if (dependencyCount.get(asset, 0) == 0) unload(asset);
}
this.assets.clear();
this.assetTypes.clear();
this.assetDependencies.clear();
this.loaded = 0;
this.toLoad = 0;
this.peakTasks = 0;
this.loadQueue.clear();
this.tasks.clear();
}
/** @return the {@link Logger} used by the {@link AssetManager} */
public Logger getLogger () {
return log;
}
public void setLogger (Logger logger) {
log = logger;
}
/** Returns the reference count of an asset.
* @param fileName */
public synchronized int getReferenceCount (String fileName) {
Class type = assetTypes.get(fileName);
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
return assets.get(type).get(fileName).refCount;
}
/** Sets the reference count of an asset.
* @param fileName */
public synchronized void setReferenceCount (String fileName, int refCount) {
Class type = assetTypes.get(fileName);
if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName);
assets.get(type).get(fileName).refCount = refCount;
}
/** @return a string containing ref count and dependency information for all assets. */
public synchronized String getDiagnostics () {
StringBuilder sb = new StringBuilder(256);
for (String fileName : assetTypes.keys()) {
if (sb.length() > 0) sb.append("\n");
sb.append(fileName);
sb.append(", ");
Class type = assetTypes.get(fileName);
RefCountedContainer assetRef = assets.get(type).get(fileName);
Array<String> dependencies = assetDependencies.get(fileName);
sb.append(ClassReflection.getSimpleName(type));
sb.append(", refs: ");
sb.append(assetRef.refCount);
if (dependencies != null) {
sb.append(", deps: [");
for (String dep : dependencies) {
sb.append(dep);
sb.append(",");
}
sb.append("]");
}
}
return sb.toString();
}
/** @return the file names of all loaded assets. */
public synchronized Array<String> getAssetNames () {
return assetTypes.keys().toArray();
}
/** @return the dependencies of an asset or null if the asset has no dependencies. */
public synchronized Array<String> getDependencies (String fileName) {
return assetDependencies.get(fileName);
}
/** @return the type of a loaded asset. */
public synchronized Class getAssetType (String fileName) {
return assetTypes.get(fileName);
}
static class RefCountedContainer {
Object object;
int refCount = 1;
}
}
| AssetManager, refactoring and cleanup.
* Stack -> Array.
* Better use of iterators.
* Use ObjectIntMap#getAndIncrement.
| gdx/src/com/badlogic/gdx/assets/AssetManager.java | AssetManager, refactoring and cleanup. | <ide><path>dx/src/com/badlogic/gdx/assets/AssetManager.java
<ide> import com.badlogic.gdx.utils.Null;
<ide> import com.badlogic.gdx.utils.ObjectIntMap;
<ide> import com.badlogic.gdx.utils.ObjectMap;
<add>import com.badlogic.gdx.utils.ObjectMap.Entry;
<ide> import com.badlogic.gdx.utils.ObjectSet;
<ide> import com.badlogic.gdx.utils.TimeUtils;
<ide> import com.badlogic.gdx.utils.UBJsonReader;
<ide> final Array<AssetDescriptor> loadQueue = new Array();
<ide> final AsyncExecutor executor;
<ide>
<del> final Stack<AssetLoadingTask> tasks = new Stack();
<add> final Array<AssetLoadingTask> tasks = new Array();
<ide> AssetErrorListener listener;
<ide> int loaded;
<ide> int toLoad;
<ide> public synchronized <T> Array<T> getAll (Class<T> type, Array<T> out) {
<ide> ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type);
<ide> if (assetsByType != null) {
<del> for (ObjectMap.Entry<String, RefCountedContainer> asset : assetsByType.entries())
<del> out.add((T)asset.value.object);
<add> for (RefCountedContainer assetRef : assetsByType.values())
<add> out.add((T)assetRef.object);
<ide> }
<ide> return out;
<ide> }
<ide>
<ide> /** Returns true if an asset with the specified name is loading, queued to be loaded, or has been loaded. */
<ide> public synchronized boolean contains (String fileName) {
<del> if (tasks.size() > 0 && tasks.firstElement().assetDesc.fileName.equals(fileName)) return true;
<add> if (tasks.size > 0 && tasks.first().assetDesc.fileName.equals(fileName)) return true;
<ide>
<ide> for (int i = 0; i < loadQueue.size; i++)
<ide> if (loadQueue.get(i).fileName.equals(fileName)) return true;
<ide>
<ide> /** Returns true if an asset with the specified name and type is loading, queued to be loaded, or has been loaded. */
<ide> public synchronized boolean contains (String fileName, Class type) {
<del> if (tasks.size() > 0) {
<del> AssetDescriptor assetDesc = tasks.firstElement().assetDesc;
<add> if (tasks.size > 0) {
<add> AssetDescriptor assetDesc = tasks.first().assetDesc;
<ide> if (assetDesc.type == type && assetDesc.fileName.equals(fileName)) return true;
<ide> }
<ide>
<ide> fileName = fileName.replace('\\', '/');
<ide>
<ide> // check if it's currently processed (and the first element in the stack, thus not a dependency) and cancel if necessary
<del> if (tasks.size() > 0) {
<del> AssetLoadingTask currentTask = tasks.firstElement();
<add> if (tasks.size > 0) {
<add> AssetLoadingTask currentTask = tasks.first();
<ide> if (currentTask.assetDesc.fileName.equals(fileName)) {
<ide> log.info("Unload (from tasks): " + fileName);
<ide> currentTask.cancel = true;
<ide> public synchronized <T> boolean containsAsset (T asset) {
<ide> ObjectMap<String, RefCountedContainer> assetsByType = assets.get(asset.getClass());
<ide> if (assetsByType == null) return false;
<del> for (String fileName : assetsByType.keys()) {
<del> Object otherAsset = assetsByType.get(fileName).object;
<del> if (otherAsset == asset || asset.equals(otherAsset)) return true;
<del> }
<add> for (RefCountedContainer assetRef : assetsByType.values())
<add> if (assetRef.object == asset || asset.equals(assetRef.object)) return true;
<ide> return false;
<ide> }
<ide>
<ide> public synchronized <T> String getAssetFileName (T asset) {
<ide> for (Class assetType : assets.keys()) {
<ide> ObjectMap<String, RefCountedContainer> assetsByType = assets.get(assetType);
<del> for (String fileName : assetsByType.keys()) {
<del> Object otherAsset = assetsByType.get(fileName).object;
<del> if (otherAsset == asset || asset.equals(otherAsset)) return fileName;
<add> for (Entry<String, RefCountedContainer> entry : assetsByType) {
<add> Object object = entry.value.object;
<add> if (object == asset || asset.equals(object)) return entry.key;
<ide> }
<ide> }
<ide> return null;
<ide> * @param fileName The filename of the asset to get a loader for, or null to get the default loader
<ide> * @return The loader capable of loading the type and filename, or null if none exists */
<ide> public <T> AssetLoader getLoader (final Class<T> type, final String fileName) {
<del> final ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
<add> ObjectMap<String, AssetLoader> loaders = this.loaders.get(type);
<ide> if (loaders == null || loaders.size < 1) return null;
<ide> if (fileName == null) return loaders.get("");
<ide> AssetLoader result = null;
<del> int l = -1;
<del> for (ObjectMap.Entry<String, AssetLoader> entry : loaders.entries()) {
<del> if (entry.key.length() > l && fileName.endsWith(entry.key)) {
<add> int length = -1;
<add> for (Entry<String, AssetLoader> entry : loaders.entries()) {
<add> if (entry.key.length() > length && fileName.endsWith(entry.key)) {
<ide> result = entry.value;
<del> l = entry.key.length();
<add> length = entry.key.length();
<ide> }
<ide> }
<ide> return result;
<ide> }
<ide>
<ide> // check task list
<del> for (int i = 0; i < tasks.size(); i++) {
<add> for (int i = 0; i < tasks.size; i++) {
<ide> AssetDescriptor desc = tasks.get(i).assetDesc;
<ide> if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException(
<ide> "Asset with name '" + fileName + "' already in task list, but has different type (expected: "
<ide> * @return true if all loading is finished. */
<ide> public synchronized boolean update () {
<ide> try {
<del> if (tasks.size() == 0) {
<add> if (tasks.size == 0) {
<ide> // loop until we have a new task ready to be processed
<del> while (loadQueue.size != 0 && tasks.size() == 0)
<add> while (loadQueue.size != 0 && tasks.size == 0)
<ide> nextTask();
<ide> // have we not found a task? We are done!
<del> if (tasks.size() == 0) return true;
<del> }
<del> return updateTask() && loadQueue.size == 0 && tasks.size() == 0;
<add> if (tasks.size == 0) return true;
<add> }
<add> return updateTask() && loadQueue.size == 0 && tasks.size == 0;
<ide> } catch (Throwable t) {
<ide> handleTaskError(t);
<ide> return loadQueue.size == 0;
<ide> /** Returns true when all assets are loaded. Can be called from any thread but note {@link #update()} or related methods must
<ide> * be called to process tasks. */
<ide> public synchronized boolean isFinished () {
<del> return loadQueue.size == 0 && tasks.size() == 0;
<add> return loadQueue.size == 0 && tasks.size == 0;
<ide> }
<ide>
<ide> /** Blocks until all assets are loaded. */
<ide> private void addTask (AssetDescriptor assetDesc) {
<ide> AssetLoader loader = getLoader(assetDesc.type, assetDesc.fileName);
<ide> if (loader == null) throw new GdxRuntimeException("No loader for type: " + ClassReflection.getSimpleName(assetDesc.type));
<del> tasks.push(new AssetLoadingTask(this, assetDesc, loader, executor));
<add> tasks.add(new AssetLoadingTask(this, assetDesc, loader, executor));
<ide> peakTasks++;
<ide> }
<ide>
<ide> // if the task has been cancelled or has finished loading
<ide> if (complete) {
<ide> // increase the number of loaded assets and pop the task from the stack
<del> if (tasks.size() == 1) {
<add> if (tasks.size == 1) {
<ide> loaded++;
<ide> peakTasks = 0;
<ide> }
<ide>
<ide> /** @return the number of currently queued assets */
<ide> public synchronized int getQueuedAssets () {
<del> return loadQueue.size + tasks.size();
<add> return loadQueue.size + tasks.size;
<ide> }
<ide>
<ide> /** @return the progress in percent of completion. */
<ide> if (toLoad == 0) return 1;
<ide> float fractionalLoaded = loaded;
<ide> if (peakTasks > 0) {
<del> fractionalLoaded += ((peakTasks - tasks.size()) / (float)peakTasks);
<add> fractionalLoaded += ((peakTasks - tasks.size) / (float)peakTasks);
<ide> }
<ide> return Math.min(1, fractionalLoaded / toLoad);
<ide> }
<ide> /** Clears and disposes all assets and the preloading queue. */
<ide> public synchronized void clear () {
<ide> loadQueue.clear();
<del> while (!update())
<del> ;
<add> while (!update()) {
<add> }
<ide>
<ide> ObjectIntMap<String> dependencyCount = new ObjectIntMap<String>();
<ide> while (assetTypes.size > 0) {
<ide> // for each asset, figure out how often it was referenced
<ide> dependencyCount.clear();
<ide> Array<String> assets = assetTypes.keys().toArray();
<del> for (String asset : assets)
<del> dependencyCount.put(asset, 0);
<del>
<ide> for (String asset : assets) {
<ide> Array<String> dependencies = assetDependencies.get(asset);
<ide> if (dependencies == null) continue;
<del> for (String dependency : dependencies) {
<del> int count = dependencyCount.get(dependency, 0);
<del> count++;
<del> dependencyCount.put(dependency, count);
<del> }
<add> for (String dependency : dependencies)
<add> dependencyCount.getAndIncrement(dependency, 0, 1);
<ide> }
<ide>
<ide> // only dispose of assets that are root assets (not referenced)
<ide>
<ide> /** @return a string containing ref count and dependency information for all assets. */
<ide> public synchronized String getDiagnostics () {
<del> StringBuilder sb = new StringBuilder(256);
<del> for (String fileName : assetTypes.keys()) {
<del> if (sb.length() > 0) sb.append("\n");
<del> sb.append(fileName);
<del> sb.append(", ");
<del>
<del> Class type = assetTypes.get(fileName);
<del> RefCountedContainer assetRef = assets.get(type).get(fileName);
<add> StringBuilder buffer = new StringBuilder(256);
<add> for (Entry<String, Class> entry : assetTypes) {
<add> String fileName = entry.key;
<add> Class type = entry.value;
<add>
<add> if (buffer.length() > 0) buffer.append('\n');
<add> buffer.append(fileName);
<add> buffer.append(", ");
<add> buffer.append(ClassReflection.getSimpleName(type));
<add> buffer.append(", refs: ");
<add> buffer.append(assets.get(type).get(fileName).refCount);
<add>
<ide> Array<String> dependencies = assetDependencies.get(fileName);
<del>
<del> sb.append(ClassReflection.getSimpleName(type));
<del>
<del> sb.append(", refs: ");
<del> sb.append(assetRef.refCount);
<del>
<ide> if (dependencies != null) {
<del> sb.append(", deps: [");
<add> buffer.append(", deps: [");
<ide> for (String dep : dependencies) {
<del> sb.append(dep);
<del> sb.append(",");
<add> buffer.append(dep);
<add> buffer.append(',');
<ide> }
<del> sb.append("]");
<del> }
<del> }
<del> return sb.toString();
<add> buffer.append(']');
<add> }
<add> }
<add> return buffer.toString();
<ide> }
<ide>
<ide> /** @return the file names of all loaded assets. */ |
|
Java | mit | 497b8f0e9dda17bb786a5164cf88a5738b03e8a5 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.file.transactional;
import org.apache.commons.lang3.tuple.Pair;
import org.innovateuk.ifs.RootUnitTestMocksTest;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.file.builder.FileEntryBuilder;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.file.repository.FileEntryRepository;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.junit.After;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import static java.nio.charset.Charset.defaultCharset;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id;
import static org.innovateuk.ifs.commons.error.CommonErrors.*;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry;
import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource;
import static org.innovateuk.ifs.util.CollectionFunctions.combineLists;
import static org.innovateuk.ifs.file.util.FileFunctions.pathElementsToFile;
import static org.innovateuk.ifs.file.util.FileFunctions.pathElementsToPathString;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
/**
*
*/
public class FileServiceImplTest extends RootUnitTestMocksTest {
@InjectMocks
private FileService service = new FileServiceImpl();
@Mock
private FileEntryRepository fileEntryRepository;
@Mock(name = "temporaryHoldingFileStorageStrategy")
private FileStorageStrategy temporaryHoldingFileStorageStrategy;
@Mock(name = "quarantinedFileStorageStrategy")
private FileStorageStrategy quarantinedFileStorageStrategy;
@Mock(name = "scannedFileStorageStrategy")
private FileStorageStrategy scannedFileStorageStrategy;
@Mock(name = "finalFileStorageStrategy")
private FileStorageStrategy finalFileStorageStrategy;
@After
public void verifyMockExpectations() {
verifyNoMoreFileServiceInteractions();
}
@Test
public void testCreateFile() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry unpersistedFile = fileBuilder.with(id(null)).build();
FileEntry persistedFile = fileBuilder.with(id(456L)).build();
List<String> fullPathToNewFile = combineLists("path", "to", "file");
List<String> fullPathPlusFilename = combineLists(fullPathToNewFile, "thefilename");
when(fileEntryRepository.save(unpersistedFile)).thenReturn(persistedFile);
when(temporaryHoldingFileStorageStrategy.createFile(eq(persistedFile), isA(File.class))).thenReturn(serviceSuccess(pathElementsToFile(fullPathPlusFilename)));
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("thefilename", newFileResult.getName());
String expectedPath = pathElementsToPathString(fullPathToNewFile);
assertEquals(expectedPath + File.separator + "thefilename", newFileResult.getPath());
verify(fileEntryRepository).save(unpersistedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(persistedFile), isA(File.class));
}
@Test
public void testCreateFileFailureToCreateFileOnFilesystemHandledGracefully() {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry unpersistedFile = fileBuilder.with(id(null)).build();
FileEntry persistedFile = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.save(unpersistedFile)).thenReturn(persistedFile);
when(temporaryHoldingFileStorageStrategy.createFile(eq(persistedFile), isA(File.class))).thenReturn(serviceFailure(new Error(FILES_UNABLE_TO_CREATE_FOLDERS)));
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(new Error(FILES_UNABLE_TO_CREATE_FOLDERS)));
verify(fileEntryRepository).save(unpersistedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(persistedFile), isA(File.class));
}
@Test
public void testUpdateFile() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(finalFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(finalFileStorageStrategy).deleteFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
}
@Test
public void testUpdateFileDoesntDeleteOriginalFileUntilNewFileSuccessfullyCreated() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceFailure(internalServerErrorError()));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(internalServerErrorError()));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyAwaitingScanning() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(true);
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(temporaryHoldingFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyQuarantined() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(quarantinedFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).getFile(updatedFile);
verify(scannedFileStorageStrategy).getFile(updatedFile);
verify(quarantinedFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(quarantinedFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyScanned() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(scannedFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(scannedFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(scannedFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileButNoFileExistsOnFilesystemToUpdate() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFileEntry = fileBuilder.with(id(456L)).build();
FileEntryResource expectedFileResourceForUpdate = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(17).
build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFileEntry);
when(temporaryHoldingFileStorageStrategy.exists(updatedFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(expectedFileResourceForUpdate, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFileEntry);
verify(finalFileStorageStrategy).getFile(updatedFileEntry);
verify(temporaryHoldingFileStorageStrategy).getFile(updatedFileEntry);
verify(scannedFileStorageStrategy).getFile(updatedFileEntry);
verify(quarantinedFileStorageStrategy).getFile(updatedFileEntry);
}
@Test
public void testUpdateFileButNoFileEntryExistsInDatabase() throws IOException {
FileEntryResource expectedFileResourceForUpdate = newFileEntryResource().with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.empty());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(expectedFileResourceForUpdate, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testUpdateFileWithIncorrectContentLength() throws IOException {
int incorrectFilesize = 1234;
FileEntryResource fileResource = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(incorrectFilesize).
build();
FileEntryBuilder fileBuilder = newFileEntry().with(id(456L)).withFilesizeBytes(incorrectFilesize);
FileEntry fileToUpdate = fileBuilder.build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_FILESIZE, 17));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testUpdateFileWithIncorrectContentType() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(17).
withMediaType("application/pdf").
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17).withMediaType("application/pdf");
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_MEDIA_TYPE, "text/plain"));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testDeleteFileButCantDeleteFileFromFilesystem() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("cantdeleteme")));
when(finalFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceFailure(new Error(FILES_UNABLE_TO_DELETE_FILE)));
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(new Error(FILES_UNABLE_TO_DELETE_FILE)));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).delete(fileEntryToDelete);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(finalFileStorageStrategy).deleteFile(fileEntryToDelete);
}
@Test
public void testDeleteFileChecksEveryFolderForFile() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("foundme")));
when(quarantinedFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceSuccess());
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).delete(fileEntryToDelete);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).deleteFile(fileEntryToDelete);
}
@Test
public void testDeleteFileButNoFileEntryExistsInDatabase() throws IOException {
when(fileEntryRepository.findById(456L)).thenReturn(Optional.empty());
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testGetFileByFileEntryId() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileInQuarantine() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(true);
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isFailure());
assertTrue(inputStreamResult.getFailure().is(forbiddenError(FILES_FILE_QUARANTINED)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verifyNoMoreFileServiceInteractions();
}
@Test
public void testGetFileByFileEntryIdButFileAwaitingScanning() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(true);
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isFailure());
assertTrue(inputStreamResult.getFailure().is(forbiddenError(FILES_FILE_AWAITING_VIRUS_SCAN)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdAndFileInScannedFolder() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileEntryEntityDoesntExist() throws IOException {
when(fileEntryRepository.findById(123L)).thenReturn(Optional.empty());
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 123L)));
verify(fileEntryRepository).findById(123L);
}
@Test
public void testGetFileByFileEntryIdAndFileIsInFinalStorageLocation() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).withFilesizeBytes(10).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileDoesntExist() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).withFilesizeBytes(10).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 123L)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testCreateFileWithIncorrectContentLength() throws IOException {
int incorrectFilesize = 1234;
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(incorrectFilesize).
build();
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_FILESIZE, 17));
}
@Test
public void testCreateFileWithIncorrectContentType() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
withMediaType("application/pdf").
build();
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_MEDIA_TYPE, "text/plain"));
}
private Supplier<InputStream> fakeInputStreamSupplier() {
return fakeInputStreamSupplier("Fake Input Stream");
}
private Supplier<InputStream> fakeInputStreamSupplier(String content) {
ByteArrayInputStream fakeInputStream = new ByteArrayInputStream(content.getBytes(defaultCharset()));
return () -> fakeInputStream;
}
private void verifyNoMoreFileServiceInteractions() {
verifyNoMoreInteractions(fileEntryRepository, quarantinedFileStorageStrategy, temporaryHoldingFileStorageStrategy, finalFileStorageStrategy, scannedFileStorageStrategy);
}
@Test
public void testDeleteFileIgnoreNotFound(){
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(456L);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
verify(fileEntryRepository).delete(fileEntryToDelete);
}
}
| common/ifs-data-service-file/src/test/java/org/innovateuk/ifs/file/transactional/FileServiceImplTest.java | package org.innovateuk.ifs.file.transactional;
import org.apache.commons.lang3.tuple.Pair;
import org.innovateuk.ifs.RootUnitTestMocksTest;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.file.builder.FileEntryBuilder;
import org.innovateuk.ifs.file.domain.FileEntry;
import org.innovateuk.ifs.file.repository.FileEntryRepository;
import org.innovateuk.ifs.file.resource.FileEntryResource;
import org.junit.After;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import static java.nio.charset.Charset.defaultCharset;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id;
import static org.innovateuk.ifs.commons.error.CommonErrors.*;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry;
import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource;
import static org.innovateuk.ifs.util.CollectionFunctions.combineLists;
import static org.innovateuk.ifs.file.util.FileFunctions.pathElementsToFile;
import static org.innovateuk.ifs.file.util.FileFunctions.pathElementsToPathString;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.*;
/**
*
*/
public class FileServiceImplTest extends RootUnitTestMocksTest {
@InjectMocks
private FileService service = new FileServiceImpl();
@Mock
private FileEntryRepository fileEntryRepository;
@Mock(name = "temporaryHoldingFileStorageStrategy")
private FileStorageStrategy temporaryHoldingFileStorageStrategy;
@Mock(name = "quarantinedFileStorageStrategy")
private FileStorageStrategy quarantinedFileStorageStrategy;
@Mock(name = "scannedFileStorageStrategy")
private FileStorageStrategy scannedFileStorageStrategy;
@Mock(name = "finalFileStorageStrategy")
private FileStorageStrategy finalFileStorageStrategy;
@After
public void verifyMockExpectations() {
verifyNoMoreFileServiceInteractions();
}
@Test
public void testCreateFile() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry unpersistedFile = fileBuilder.with(id(null)).build();
FileEntry persistedFile = fileBuilder.with(id(456L)).build();
List<String> fullPathToNewFile = combineLists("path", "to", "file");
List<String> fullPathPlusFilename = combineLists(fullPathToNewFile, "thefilename");
when(fileEntryRepository.save(unpersistedFile)).thenReturn(persistedFile);
when(temporaryHoldingFileStorageStrategy.createFile(eq(persistedFile), isA(File.class))).thenReturn(serviceSuccess(pathElementsToFile(fullPathPlusFilename)));
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("thefilename", newFileResult.getName());
String expectedPath = pathElementsToPathString(fullPathToNewFile);
assertEquals(expectedPath + File.separator + "thefilename", newFileResult.getPath());
verify(fileEntryRepository).save(unpersistedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(persistedFile), isA(File.class));
}
@Test
public void testCreateFileFailureToCreateFileOnFilesystemHandledGracefully() {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry unpersistedFile = fileBuilder.with(id(null)).build();
FileEntry persistedFile = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.save(unpersistedFile)).thenReturn(persistedFile);
when(temporaryHoldingFileStorageStrategy.createFile(eq(persistedFile), isA(File.class))).thenReturn(serviceFailure(new Error(FILES_UNABLE_TO_CREATE_FOLDERS)));
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(new Error(FILES_UNABLE_TO_CREATE_FOLDERS)));
verify(fileEntryRepository).save(unpersistedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(persistedFile), isA(File.class));
}
@Test
public void testUpdateFile() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(finalFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(finalFileStorageStrategy).deleteFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
}
@Test
public void testUpdateFileDoesntDeleteOriginalFileUntilNewFileSuccessfullyCreated() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceFailure(internalServerErrorError()));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(internalServerErrorError()));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyAwaitingScanning() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(true);
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(temporaryHoldingFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyQuarantined() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(quarantinedFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).getFile(updatedFile);
verify(scannedFileStorageStrategy).getFile(updatedFile);
verify(quarantinedFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(quarantinedFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileAndOriginalFileIsCurrentlyScanned() throws IOException {
FileEntryResource updatingFileEntry = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(30).
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFile = fileBuilder.with(id(456L)).build();
File fileItselfToUpdate = new File("/tmp/path/to/updatedfile");
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFile);
when(temporaryHoldingFileStorageStrategy.exists(updatedFile)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFile)).thenReturn(serviceSuccess(fileItselfToUpdate));
when(temporaryHoldingFileStorageStrategy.createFile(eq(updatedFile), isA(File.class))).thenReturn(serviceSuccess(fileItselfToUpdate));
when(scannedFileStorageStrategy.deleteFile(updatedFile)).thenReturn(serviceSuccess());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(updatingFileEntry, fakeInputStreamSupplier("Updated content should be here"));
assertNotNull(result);
assertTrue(result.isSuccess());
File newFileResult = result.getSuccess().getKey();
assertEquals("updatedfile", newFileResult.getName());
assertEquals("/tmp/path/to/updatedfile", newFileResult.getPath());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFile);
verify(finalFileStorageStrategy).getFile(updatedFile);
verify(scannedFileStorageStrategy).getFile(updatedFile);
verify(temporaryHoldingFileStorageStrategy).createFile(eq(updatedFile), isA(File.class));
verify(scannedFileStorageStrategy).deleteFile(updatedFile);
}
@Test
public void testUpdateFileButNoFileExistsOnFilesystemToUpdate() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17);
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
FileEntry updatedFileEntry = fileBuilder.with(id(456L)).build();
FileEntryResource expectedFileResourceForUpdate = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(17).
build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
when(fileEntryRepository.save(fileToUpdate)).thenReturn(updatedFileEntry);
when(temporaryHoldingFileStorageStrategy.exists(updatedFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(updatedFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(expectedFileResourceForUpdate, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).save(fileToUpdate);
verify(temporaryHoldingFileStorageStrategy).exists(updatedFileEntry);
verify(finalFileStorageStrategy).getFile(updatedFileEntry);
verify(temporaryHoldingFileStorageStrategy).getFile(updatedFileEntry);
verify(scannedFileStorageStrategy).getFile(updatedFileEntry);
verify(quarantinedFileStorageStrategy).getFile(updatedFileEntry);
}
@Test
public void testUpdateFileButNoFileEntryExistsInDatabase() throws IOException {
FileEntryResource expectedFileResourceForUpdate = newFileEntryResource().with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.empty());
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(expectedFileResourceForUpdate, fakeInputStreamSupplier());
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testUpdateFileWithIncorrectContentLength() throws IOException {
int incorrectFilesize = 1234;
FileEntryResource fileResource = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(incorrectFilesize).
build();
FileEntryBuilder fileBuilder = newFileEntry().with(id(456L)).withFilesizeBytes(incorrectFilesize);
FileEntry fileToUpdate = fileBuilder.build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_FILESIZE, 17));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testUpdateFileWithIncorrectContentType() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(456L)).
withFilesizeBytes(17).
withMediaType("application/pdf").
build();
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(17).withMediaType("application/pdf");
FileEntry fileToUpdate = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileToUpdate));
ServiceResult<Pair<File, FileEntry>> result = service.updateFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_MEDIA_TYPE, "text/plain"));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testDeleteFile() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("foundme")));
when(finalFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceSuccess());
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(456L);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(finalFileStorageStrategy).deleteFile(fileEntryToDelete);
verify(fileEntryRepository).delete(fileEntryToDelete);
}
@Test
public void testDeleteFileButCantDeleteFileFromFilesystem() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("cantdeleteme")));
when(finalFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceFailure(new Error(FILES_UNABLE_TO_DELETE_FILE)));
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(new Error(FILES_UNABLE_TO_DELETE_FILE)));
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).delete(fileEntryToDelete);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(finalFileStorageStrategy).deleteFile(fileEntryToDelete);
}
@Test
public void testDeleteFileButNoFileExistsOnFilesystemToDelete() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
}
@Test
public void testDeleteFileChecksEveryFolderForFile() throws IOException {
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("foundme")));
when(quarantinedFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceSuccess());
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(456L);
verify(fileEntryRepository).delete(fileEntryToDelete);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).deleteFile(fileEntryToDelete);
}
@Test
public void testDeleteFileButNoFileEntryExistsInDatabase() throws IOException {
when(fileEntryRepository.findById(456L)).thenReturn(Optional.empty());
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
verify(fileEntryRepository).findById(456L);
}
@Test
public void testGetFileByFileEntryId() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileInQuarantine() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(true);
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isFailure());
assertTrue(inputStreamResult.getFailure().is(forbiddenError(FILES_FILE_QUARANTINED)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verifyNoMoreFileServiceInteractions();
}
@Test
public void testGetFileByFileEntryIdButFileAwaitingScanning() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(true);
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isFailure());
assertTrue(inputStreamResult.getFailure().is(forbiddenError(FILES_FILE_AWAITING_VIRUS_SCAN)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdAndFileInScannedFolder() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> inputStreamResult = service.getFileByFileEntryId(123L);
assertTrue(inputStreamResult.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileEntryEntityDoesntExist() throws IOException {
when(fileEntryRepository.findById(123L)).thenReturn(Optional.empty());
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 123L)));
verify(fileEntryRepository).findById(123L);
}
@Test
public void testGetFileByFileEntryIdAndFileIsInFinalStorageLocation() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).withFilesizeBytes(10).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceSuccess(new File("foundme")));
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testGetFileByFileEntryIdButFileDoesntExist() throws IOException {
FileEntry existingFileEntry = newFileEntry().with(id(123L)).withFilesizeBytes(10).build();
when(fileEntryRepository.findById(123L)).thenReturn(Optional.of(existingFileEntry));
when(quarantinedFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(temporaryHoldingFileStorageStrategy.exists(existingFileEntry)).thenReturn(false);
when(finalFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
when(scannedFileStorageStrategy.getFile(existingFileEntry)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 123L)));
ServiceResult<Supplier<InputStream>> result = service.getFileByFileEntryId(123L);
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 123L)));
verify(fileEntryRepository).findById(123L);
verify(quarantinedFileStorageStrategy).exists(existingFileEntry);
verify(temporaryHoldingFileStorageStrategy).exists(existingFileEntry);
verify(finalFileStorageStrategy).getFile(existingFileEntry);
verify(scannedFileStorageStrategy).getFile(existingFileEntry);
}
@Test
public void testCreateFileWithIncorrectContentLength() throws IOException {
int incorrectFilesize = 1234;
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(incorrectFilesize).
build();
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_FILESIZE, 17));
}
@Test
public void testCreateFileWithIncorrectContentType() throws IOException {
FileEntryResource fileResource = newFileEntryResource().
with(id(null)).
withFilesizeBytes(17).
withMediaType("application/pdf").
build();
ServiceResult<Pair<File, FileEntry>> result = service.createFile(fileResource, fakeInputStreamSupplier());
assertTrue(result.isFailure());
assertTrue(result.getFailure().is(FILES_INCORRECTLY_REPORTED_MEDIA_TYPE, "text/plain"));
}
private Supplier<InputStream> fakeInputStreamSupplier() {
return fakeInputStreamSupplier("Fake Input Stream");
}
private Supplier<InputStream> fakeInputStreamSupplier(String content) {
ByteArrayInputStream fakeInputStream = new ByteArrayInputStream(content.getBytes(defaultCharset()));
return () -> fakeInputStream;
}
private void verifyNoMoreFileServiceInteractions() {
verifyNoMoreInteractions(fileEntryRepository, quarantinedFileStorageStrategy, temporaryHoldingFileStorageStrategy, finalFileStorageStrategy, scannedFileStorageStrategy);
}
@Test
public void testDeleteFileIgnoreNotFound(){
FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
assertNotNull(result);
assertTrue(result.isSuccess());
verify(fileEntryRepository).findById(456L);
verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
verify(fileEntryRepository).delete(fileEntryToDelete);
}
}
| tests call deprecated and now removed method only
| common/ifs-data-service-file/src/test/java/org/innovateuk/ifs/file/transactional/FileServiceImplTest.java | tests call deprecated and now removed method only | <ide><path>ommon/ifs-data-service-file/src/test/java/org/innovateuk/ifs/file/transactional/FileServiceImplTest.java
<ide> }
<ide>
<ide> @Test
<del> public void testDeleteFile() throws IOException {
<del>
<del> FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
<del> FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
<del>
<del> when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
<del> when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceSuccess(new File("foundme")));
<del> when(finalFileStorageStrategy.deleteFile(fileEntryToDelete)).thenReturn(serviceSuccess());
<del>
<del> ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
<del> assertNotNull(result);
<del> assertTrue(result.isSuccess());
<del>
<del> verify(fileEntryRepository).findById(456L);
<del> verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
<del> verify(finalFileStorageStrategy).deleteFile(fileEntryToDelete);
<del> verify(fileEntryRepository).delete(fileEntryToDelete);
<del> }
<del>
<del> @Test
<ide> public void testDeleteFileButCantDeleteFileFromFilesystem() throws IOException {
<ide>
<ide> FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
<ide> verify(fileEntryRepository).delete(fileEntryToDelete);
<ide> verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
<ide> verify(finalFileStorageStrategy).deleteFile(fileEntryToDelete);
<del> }
<del>
<del> @Test
<del> public void testDeleteFileButNoFileExistsOnFilesystemToDelete() throws IOException {
<del>
<del> FileEntryBuilder fileBuilder = newFileEntry().withFilesizeBytes(30);
<del> FileEntry fileEntryToDelete = fileBuilder.with(id(456L)).build();
<del>
<del> when(fileEntryRepository.findById(456L)).thenReturn(Optional.of(fileEntryToDelete));
<del> when(finalFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
<del> when(temporaryHoldingFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
<del> when(scannedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
<del> when(quarantinedFileStorageStrategy.getFile(fileEntryToDelete)).thenReturn(serviceFailure(notFoundError(FileEntry.class, 456L)));
<del>
<del> ServiceResult<FileEntry> result = service.deleteFileIgnoreNotFound(456L);
<del> assertNotNull(result);
<del> assertTrue(result.isFailure());
<del> assertTrue(result.getFailure().is(notFoundError(FileEntry.class, 456L)));
<del>
<del> verify(fileEntryRepository).findById(456L);
<del> verify(finalFileStorageStrategy).getFile(fileEntryToDelete);
<del> verify(temporaryHoldingFileStorageStrategy).getFile(fileEntryToDelete);
<del> verify(scannedFileStorageStrategy).getFile(fileEntryToDelete);
<del> verify(quarantinedFileStorageStrategy).getFile(fileEntryToDelete);
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 05dcd864e18db8acb6774fd44c6b0fdcd8079bb3 | 0 | eg-zhang/h2o-2,rowhit/h2o-2,vbelakov/h2o,calvingit21/h2o-2,calvingit21/h2o-2,h2oai/h2o,calvingit21/h2o-2,rowhit/h2o-2,100star/h2o,h2oai/h2o,h2oai/h2o-2,h2oai/h2o-2,vbelakov/h2o,vbelakov/h2o,100star/h2o,100star/h2o,elkingtonmcb/h2o-2,h2oai/h2o-2,vbelakov/h2o,111t8e/h2o-2,elkingtonmcb/h2o-2,vbelakov/h2o,111t8e/h2o-2,vbelakov/h2o,eg-zhang/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,100star/h2o,h2oai/h2o-2,calvingit21/h2o-2,111t8e/h2o-2,h2oai/h2o,h2oai/h2o-2,100star/h2o,eg-zhang/h2o-2,eg-zhang/h2o-2,elkingtonmcb/h2o-2,vbelakov/h2o,eg-zhang/h2o-2,elkingtonmcb/h2o-2,calvingit21/h2o-2,100star/h2o,rowhit/h2o-2,111t8e/h2o-2,calvingit21/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,rowhit/h2o-2,h2oai/h2o,100star/h2o,h2oai/h2o,rowhit/h2o-2,calvingit21/h2o-2,rowhit/h2o-2,h2oai/h2o-2,elkingtonmcb/h2o-2,vbelakov/h2o,rowhit/h2o-2,111t8e/h2o-2,vbelakov/h2o,100star/h2o,rowhit/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,rowhit/h2o-2,eg-zhang/h2o-2,111t8e/h2o-2,calvingit21/h2o-2,h2oai/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,h2oai/h2o-2,h2oai/h2o,100star/h2o,h2oai/h2o,vbelakov/h2o,rowhit/h2o-2,eg-zhang/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o,eg-zhang/h2o-2,h2oai/h2o,h2oai/h2o-2,h2oai/h2o | package water.fvec;
import java.util.*;
import water.*;
import water.parser.DParseTask;
// An uncompressed chunk of data, supporting an append operation
public class NewChunk extends Chunk {
final int _cidx;
// We can record the following (mixed) data types:
// 1- doubles, in _ds including NaN for NA & 0; _ls==_xs==null
// 2- scaled decimals from parsing, in _ls & _xs; _ds==null
// 3- zero: requires _ls==0 && _xs==0
// 4- NA: either _ls==0 && _xs==Integer.MIN_VALUE, OR _ds=NaN
// 5- Enum: _xs==(Integer.MIN_VALUE+1) && _ds==null
// Chunk._len is the count of elements appended
// Sparse: if _len != _len2, then _ls/_ds are compressed to non-zero's only,
// and _xs is the row number. Still _len2 is count of elements including
// zeros, and _len is count of non-zeros.
transient long _ls[]; // Mantissa
transient int _xs[]; // Exponent, or if _ls==0, NA or Enum or Rows
transient int _id[]; // Indeces (row numbers) of stored values, used for sparse
transient double _ds[]; // Doubles, for inflating via doubles
int _len2; // Actual rows, if the data is sparse
int _naCnt=-1; // Count of NA's appended
int _strCnt; // Count of Enum's appended
int _nzCnt; // Count of non-zero's appended
final int _timCnt[] = new int[ParseTime.TIME_PARSE.length]; // Count of successful time parses
public static final int MIN_SPARSE_RATIO = 32;
public NewChunk( Vec vec, int cidx ) { _vec = vec; _cidx = cidx; }
// Constructor used when inflating a Chunk.
public NewChunk( Chunk C ) {
this(C._vec, C._vec.elem2ChunkIdx(C._start));
_len2 = C._len;
_len = C.sparseLen();
_start = C._start;
}
// Pre-sized newchunks.
public NewChunk( Vec vec, int cidx, int len ) {
this(vec,cidx);
_ds = new double[len];
Arrays.fill(_ds,Double.NaN);
_len = _len2 = len;
}
public final class Value {
int _gId; // row number in dense (ie counting zeros)
int _lId; // local array index of this value, equal to _gId if dense
public Value(int lid, int gid){_lId = lid; _gId = gid;}
public final int rowId0(){return _gId;}
public void add2Chunk(NewChunk c){
if(_ds == null) c.addNum(_ls[_lId],_xs[_lId]);
else c.addNum(_ds[_lId]);
}
}
public Iterator<Value> values(int fromIdx, int toIdx){
final int lId, gId;
final int to = Math.min(toIdx,_len2);
if(sparse()){
int x = Arrays.binarySearch(_id,0,_len,fromIdx);
if(x < 0) x = -x -1;
lId = x;
gId = x == _len?_len2:_id[x];
} else
lId = gId = fromIdx;
final Value v = new Value(lId,gId);
final Value next = new Value(lId,gId);
return new Iterator<Value>(){
@Override public final boolean hasNext(){return next._gId < to;}
@Override public final Value next(){
if(!hasNext())throw new NoSuchElementException();
v._gId = next._gId; v._lId = next._lId;
next._lId++;
if(sparse()) next._gId = next._lId < _len?_id[next._lId]:_len2;
else next._gId++;
return v;
}
@Override
public void remove() {throw new UnsupportedOperationException();}
};
}
// Heuristic to decide the basic type of a column
public byte type() {
if( _naCnt == -1 ) { // No rollups yet?
int nas=0, ss=0, nzs=0;
if( _ds != null ) {
assert _ls==null && _xs==null;
for( int i = 0; i < _len; ++i) if( Double.isNaN(_ds[i]) ) nas++; else if( _ds[i]!=0 ) nzs++;
} else {
assert _ds==null;
if( _ls != null )
for( int i=0; i<_len; i++ )
if( isNA2(i) ) nas++;
else {
if( isEnum2(i) ) ss++;
if( _ls[i] != 0 ) nzs++;
}
}
_nzCnt=nzs; _strCnt=ss; _naCnt=nas;
}
// Now run heuristic for type
if(_naCnt == _len2) // All NAs ==> NA Chunk
return AppendableVec.NA;
if(_strCnt > 0 && _strCnt + _naCnt == _len2)
return AppendableVec.ENUM; // All are Strings+NAs ==> Enum Chunk
// Larger of time & numbers
int timCnt=0; for( int t : _timCnt ) timCnt+=t;
int nums = _len2-_naCnt-timCnt;
return timCnt >= nums ? AppendableVec.TIME : AppendableVec.NUMBER;
}
protected final boolean isNA2(int idx) {
return (_ds == null) ? (_ls[idx] == Long.MAX_VALUE && _xs[idx] == Integer.MIN_VALUE) : Double.isNaN(_ds[idx]);
}
protected final boolean isEnum2(int idx) {
return _xs!=null && _xs[idx]==Integer.MIN_VALUE+1;
}
protected final boolean isEnum(int idx) {
if(_id == null)return isEnum2(idx);
int j = Arrays.binarySearch(_id,0,_len,idx);
if(j < 0)return false;
return isEnum2(j);
}
public void addEnum(int e) {append2(e,Integer.MIN_VALUE+1);}
public void addNA ( ) {append2(Long.MAX_VALUE,Integer.MIN_VALUE ); }
public void addNum (long val, int exp) {
if(_ds != null){
assert _ls == null;
addNum(val*DParseTask.pow10(exp));
} else {
if( val == 0 ) exp = 0;// Canonicalize zero
long t; // Remove extra scaling
while( exp < 0 && exp > -9999999 && (t=val/10)*10==val ) { val=t; exp++; }
append2(val,exp);
}
}
// Fast-path append double data
public void addNum(double d) {
if(_id == null || d != 0) {
if(_ls != null)switch_to_doubles();
if( _ds == null || _len >= _ds.length ) {
append2slowd();
// call addNum again since append2slow might have flipped to sparse
addNum(d);
assert _len <= _len2;
return;
}
if(_id != null)_id[_len] = _len2;
_ds[_len++] = d;
}
_len2++;
assert _len <= _len2;
}
public final boolean sparse(){return _id != null;}
public void addZeros(int n){
if(!sparse()) for(int i = 0; i < n; ++i)addNum(0,0);
else _len2 += n;
}
// Append all of 'nc' onto the current NewChunk. Kill nc.
public void add( NewChunk nc ) {
assert _cidx >= 0;
assert _len <= _len2;
assert nc._len <= nc._len2:"_len = " + nc._len + ", _len2 = " + nc._len2;
if( nc._len2 == 0 ) return;
if(_len2 == 0){
_ls = nc._ls; nc._ls = null;
_xs = nc._xs; nc._xs = null;
_id = nc._id; nc._id = null;
_ds = nc._ds; nc._ds = null;
_len = nc._len;
_len2 = nc._len2;
return;
}
if(nc.sparse() != sparse()){ // for now, just make it dense
cancel_sparse();
nc.cancel_sparse();
}
if( _ds != null ) throw H2O.unimpl();
while( _len+nc._len >= _xs.length )
_xs = MemoryManager.arrayCopyOf(_xs,_xs.length<<1);
_ls = MemoryManager.arrayCopyOf(_ls,_xs.length);
System.arraycopy(nc._ls,0,_ls,_len,nc._len);
System.arraycopy(nc._xs,0,_xs,_len,nc._len);
if(_id != null) {
assert nc._id != null;
_id = MemoryManager.arrayCopyOf(_id,_xs.length);
System.arraycopy(nc._id,0,_id,_len,nc._len);
for(int i = _len; i < _len + nc._len; ++i) _id[i] += _len2;
} else assert nc._id == null;
_len += nc._len;
_len2 += nc._len2;
nc._ls = null; nc._xs = null; nc._id = null; nc._len = nc._len2 = 0;
assert _len <= _len2;
}
// PREpend all of 'nc' onto the current NewChunk. Kill nc.
public void addr( NewChunk nc ) {
long [] tmpl = _ls; _ls = nc._ls; nc._ls = tmpl;
int [] tmpi = _xs; _xs = nc._xs; nc._xs = tmpi;
tmpi = _id; _id = nc._id; nc._id = tmpi;
double[] tmpd = _ds; _ds = nc._ds; nc._ds = tmpd;
int tmp = _len; _len=nc._len; nc._len=tmp;
tmp = _len2; _len2 = nc._len2; nc._len2 = tmp;
add(nc);
}
// Fast-path append long data
void append2( long l, int x ) {
assert _ds == null;
if(_id == null || l != 0){
if(_ls == null || _len == _ls.length) {
append2slow();
// again call append2 since calling append2slow might have changed things (eg might have switched to sparse and l could be 0)
append2(l,x);
return;
}
_ls[_len] = l;
_xs[_len] = x;
if(_id != null)_id[_len] = _len2;
_len++;
}
_len2++;
assert _len <= _len2;
}
// Slow-path append data
private void append2slowd() {
if( _len > Vec.CHUNK_SZ )
throw new ArrayIndexOutOfBoundsException(_len);
assert _ls==null;
if(_ds != null && _ds.length > 0){
if(_id == null){ // check for sparseness
int nzs = 0; // assume one non-zero for the element currently being stored
for(double d:_ds)if(d != 0)++nzs;
if((nzs+1)*MIN_SPARSE_RATIO < _len2)
set_sparse(nzs);
} else _id = MemoryManager.arrayCopyOf(_id, _len << 1);
_ds = MemoryManager.arrayCopyOf(_ds,_len<<1);
} else _ds = MemoryManager.malloc8d(4);
assert _len == 0 || _ds.length > _len:"_ds.length = " + _ds.length + ", _len = " + _len;
}
// Slow-path append data
private void append2slow( ) {
if( _len > Vec.CHUNK_SZ )
throw new ArrayIndexOutOfBoundsException(_len);
assert _ds==null;
if(_ls != null && _ls.length > 0){
if(_id == null){ // check for sparseness
int nzs = 0;
for(int i = 0; i < _ls.length; ++i) if(_ls[i] != 0 || _xs[i] != 0)++nzs;
if((nzs+1)*MIN_SPARSE_RATIO < _len2){
set_sparse(nzs);
assert _len == 0 || _len <= _ls.length:"_len = " + _len + ", _ls.length = " + _ls.length + ", nzs = " + nzs + ", len2 = " + _len2;
assert _id.length == _ls.length;
assert _len <= _len2;
return;
}
} else {
// verify we're still sufficiently sparse
if((MIN_SPARSE_RATIO*(_len) >> 1) > _len2) cancel_sparse();
else _id = MemoryManager.arrayCopyOf(_id,_len<<1);
}
_ls = MemoryManager.arrayCopyOf(_ls,_len<<1);
_xs = MemoryManager.arrayCopyOf(_xs,_len<<1);
} else {
_ls = MemoryManager.malloc8(4);
_xs = MemoryManager.malloc4(4);
_id = _id == null?null:MemoryManager.malloc4(4);
}
assert _len == 0 || _len < _ls.length:"_len = " + _len + ", _ls.length = " + _ls.length;
assert _id == null || _id.length == _ls.length;
assert _len <= _len2;
}
// Do any final actions on a completed NewVector. Mostly: compress it, and
// do a DKV put on an appropriate Key. The original NewVector goes dead
// (does not live on inside the K/V store).
public Chunk new_close() {
Chunk chk = compress();
if(_vec instanceof AppendableVec)
((AppendableVec)_vec).closeChunk(this);
return chk;
}
public void close(Futures fs) { close(_cidx,fs); }
protected void set_enum(){
for(int i = 0; i < _xs.length; ++i){
if(_xs[i] == (Integer.MIN_VALUE+1))
_xs[i] = 0;
else
setNA_impl2(i);
}
}
protected void switch_to_doubles(){
assert _ds == null;
double [] ds = MemoryManager.malloc8d(_len);
for(int i = 0; i < _len; ++i)
if(isNA2(i) || isEnum2(i))ds[i] = Double.NaN;
else ds[i] = _ls[i]*DParseTask.pow10(_xs[i]);
_ls = null;
_xs = null;
_ds = ds;
}
protected void set_sparse(int nzeros){
if(_len == nzeros)return;
if(_id != null){ // we have sparse represenation but some 0s in it!
int [] id = MemoryManager.malloc4(nzeros);
int j = 0;
if(_ds != null){
double [] ds = MemoryManager.malloc8d(nzeros);
for(int i = 0; i < _len; ++i){
if(_ds[i] != 0){
ds[j] = _ds[i];
id[j] = _id[i];
++j;
}
}
_ds = ds;
} else {
long [] ls = MemoryManager.malloc8(nzeros);
int [] xs = MemoryManager.malloc4(nzeros);
for(int i = 0; i < _len; ++i){
if(_ls[i] != 0){
ls[j] = _ls[i];
xs[j] = _xs[i];
id[j] = _id[i];
++j;
}
}
_ls = ls;
_xs = xs;
}
_id = id;
assert j == nzeros;
return;
}
assert _len == _len2:"_len = " + _len + ", _len2 = " + _len2 + ", nzeros = " + nzeros;
int zs = 0;
if(_ds == null){
assert nzeros < _ls.length;
_id = MemoryManager.malloc4(_ls.length);
for(int i = 0; i < _len; ++i){
if(_ls[i] == 0 && _xs[i] == 0)++zs;
else {
_ls[i-zs] = _ls[i];
_xs[i-zs] = _xs[i];
_id[i-zs] = i;
}
}
} else {
assert nzeros < _ds.length;
_id = MemoryManager.malloc4(_ds.length);
for(int i = 0; i < _len; ++i){
if(_ds[i] == 0)++zs;
else {
_ds[i-zs] = _ds[i];
_id[i-zs] = i;
}
}
}
assert zs == (_len - nzeros);
_len = nzeros;
}
protected void cancel_sparse(){
if(_len != _len2){
if(_ds == null){
int [] xs = MemoryManager.malloc4(_len2);
long [] ls = MemoryManager.malloc8(_len2);
for(int i = 0; i < _len; ++i){
xs[_id[i]] = _xs[i];
ls[_id[i]] = _ls[i];
}
_xs = xs;
_ls = ls;
} else {
double [] ds = MemoryManager.malloc8d(_len2);
for(int i = 0; i < _len; ++i) ds[_id[i]] = _ds[i];
_ds = ds;
}
_id = null;
_len = _len2;
}
}
// Study this NewVector and determine an appropriate compression scheme.
// Return the data so compressed.
static final int MAX_FLOAT_MANTISSA = 0x7FFFFF;
Chunk compress() {
Chunk res = compress2();
// force everything to null after compress to free up the memory
_id = null;
_xs = null;
_ds = null;
_ls = null;
return res;
}
private final Chunk compress2() {
// Check for basic mode info: all missing or all strings or mixed stuff
byte mode = type();
if( mode==AppendableVec.NA ) // ALL NAs, nothing to do
return new C0DChunk(Double.NaN,_len);
boolean rerun=false;
if(mode == AppendableVec.ENUM){
for( int i=0; i<_len; i++ )
if(isEnum2(i))
_xs[i] = 0;
else if(!isNA2(i)){
setNA_impl2(i);
++_naCnt;
}
// Smack any mismatched string/numbers
} else if(mode == AppendableVec.NUMBER){
for( int i=0; i<_len; i++ )
if(isEnum2(i)) {
setNA_impl2(i);
rerun = true;
}
}
if( rerun ) { _naCnt = -1; type(); } // Re-run rollups after dropping all numbers/enums
boolean sparse = false;
// sparse? treat as sparse iff we have at least MIN_SPARSE_RATIOx more zeros than nonzeros
if(MIN_SPARSE_RATIO*(_naCnt + _nzCnt) < _len2) {
set_sparse(_naCnt + _nzCnt);
sparse = true;
}
// If the data was set8 as doubles, we do a quick check to see if it's
// plain longs. If not, we give up and use doubles.
if( _ds != null ) {
int i=0;
for( ; i<_len; i++ ) // Attempt to inject all doubles into longs
if( !Double.isNaN(_ds[i]) && (double)(long)_ds[i] != _ds[i] ) break;
if(i < _len)
return sparse?new CXDChunk(_len2,_len,8,bufD(8)):chunkD();
_ls = new long[_ds.length]; // Else flip to longs
_xs = new int [_ds.length];
double [] ds = _ds;
_ds = null;
final int naCnt = _naCnt;
for( i=0; i<_len; i++ ) // Inject all doubles into longs
if( Double.isNaN(ds[i]) )setNA_impl2(i);
else _ls[i] = (long)ds[i];
// setNA_impl2 will set _naCnt to -1!
// we already know what the naCnt is (it did not change!) so set it back to correct value
_naCnt = naCnt;
}
// IF (_len2 > _len) THEN Sparse
// Check for compressed *during appends*. Here we know:
// - No specials; _xs[]==0.
// - No floats; _ds==null
// - NZ length in _len, actual length in _len2.
// - Huge ratio between _len2 and _len, and we do NOT want to inflate to
// the larger size; we need to keep it all small all the time.
// - Rows in _xs
// Data in some fixed-point format, not doubles
// See if we can sanely normalize all the data to the same fixed-point.
int xmin = Integer.MAX_VALUE; // min exponent found
long lemin= 0, lemax=lemin; // min/max at xmin fixed-point
boolean overflow=false;
boolean floatOverflow = false;
boolean first = true;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
int p10iLength = DParseTask.powers10i.length;
for( int i=0; i<_len; i++ ) {
if( isNA2(i) ) continue;
long l = _ls[i];
int x = _xs[i];
assert x != Integer.MIN_VALUE:"l = " + l + ", x = " + x;
if( x==Integer.MIN_VALUE+1) x=0; // Replace enum flag with no scaling
assert l!=0 || x==0:"l == 0 while x = " + x + " ls = " + Arrays.toString(_ls); // Exponent of zero is always zero
// Compute per-chunk min/max
double d = l*DParseTask.pow10(x);
if( d < min ) min = d;
if( d > max ) max = d;
long t; // Remove extra scaling
while( l!=0 && (t=l/10)*10==l ) { l=t; x++; }
floatOverflow = Math.abs(l) > MAX_FLOAT_MANTISSA;
if( first ) {
first = false;
xmin = x;
lemin = lemax = l;
continue;
}
// Track largest/smallest values at xmin scale. Note overflow.
if( x < xmin ) {
if( overflow || (overflow = ((xmin-x) >=p10iLength)) ) continue;
lemin *= DParseTask.pow10i(xmin-x);
lemax *= DParseTask.pow10i(xmin-x);
xmin = x; // Smaller xmin
}
// *this* value, as a long scaled at the smallest scale
if( overflow || (overflow = ((x-xmin) >=p10iLength)) ) continue;
long le = l*DParseTask.pow10i(x-xmin);
if( le < lemin ) lemin=le;
if( le > lemax ) lemax=le;
}
if(_len2 != _len){ // sparse? compare xmin/lemin/lemax with 0
lemin = Math.min(0, lemin);
lemax = Math.max(0, lemax);
min = Math.min(min,0);
max = Math.max(max,0);
}
// Constant column?
if( _naCnt==0 && min==max ) {
return ((long)min == min)
? new C0LChunk((long)min,_len2)
: new C0DChunk( min,_len2);
}
// Boolean column?
if (max == 1 && min == 0 && xmin == 0 && !overflow) {
if(sparse) { // Very sparse?
return _naCnt==0
?new CX0Chunk(_len2,_len,bufS(0))// No NAs, can store as sparse bitvector
:new CXIChunk(_len2,_len,1,bufS(1)); // have NAs, store as sparse 1byte values
}
int bpv = _strCnt+_naCnt > 0 ? 2 : 1; // Bit-vector
byte[] cbuf = bufB(bpv);
return new CBSChunk(cbuf, cbuf[0], cbuf[1]);
}
final boolean fpoint = xmin < 0 || min < Long.MIN_VALUE || max > Long.MAX_VALUE;
if(sparse){
if(fpoint) return new CXDChunk(_len2,_len,8,bufD(8));
int sz = 8;
if(Short.MIN_VALUE <= min && max <= Short.MAX_VALUE)sz = 2;
else if(Integer.MIN_VALUE <= min && max <= Integer.MAX_VALUE)sz = 4;
return new CXIChunk(_len2,_len,sz,bufS(sz));
}
// Exponent scaling: replacing numbers like 1.3 with 13e-1. '13' fits in a
// byte and we scale the column by 0.1. A set of numbers like
// {1.2,23,0.34} then is normalized to always be represented with 2 digits
// to the right: {1.20,23.00,0.34} and we scale by 100: {120,2300,34}.
// This set fits in a 2-byte short.
// We use exponent-scaling for bytes & shorts only; it's uncommon (and not
// worth it) for larger numbers. We need to get the exponents to be
// uniform, so we scale up the largest lmax by the largest scale we need
// and if that fits in a byte/short - then it's worth compressing. Other
// wise we just flip to a float or double representation.
if( overflow || (fpoint && floatOverflow) || -35 > xmin || xmin > 35 )
return chunkD();
if( fpoint ) {
if((int)lemin == lemin && (int)lemax == lemax){
if(lemax-lemin < 255 && (int)lemin == lemin ) // Fits in scaled biased byte?
return new C1SChunk( bufX(lemin,xmin,C1SChunk.OFF,0),(int)lemin,DParseTask.pow10(xmin));
if(lemax-lemin < 65535 ) { // we use signed 2B short, add -32k to the bias!
long bias = 32767 + lemin;
return new C2SChunk( bufX(bias,xmin,C2SChunk.OFF,1),(int)bias,DParseTask.pow10(xmin));
}
if(lemax - lemin < Integer.MAX_VALUE)
return new C4SChunk(bufX(lemin, xmin,C4SChunk.OFF,2),(int)lemin,DParseTask.pow10(xmin));
}
return chunkD();
} // else an integer column
// Compress column into a byte
if(xmin == 0 && 0<=lemin && lemax <= 255 && ((_naCnt + _strCnt)==0) )
return new C1NChunk( bufX(0,0,C1NChunk.OFF,0));
if(lemin < Integer.MIN_VALUE)return new C8Chunk( bufX(0,0,0,3));
if( lemax-lemin < 255 ) { // Span fits in a byte?
if(0 <= min && max < 255 ) // Span fits in an unbiased byte?
return new C1Chunk( bufX(0,0,C1Chunk.OFF,0));
return new C1SChunk( bufX(lemin,xmin,C1SChunk.OFF,0),(int)lemin,DParseTask.pow10i(xmin));
}
// Compress column into a short
if( lemax-lemin < 65535 ) { // Span fits in a biased short?
if( xmin == 0 && Short.MIN_VALUE < lemin && lemax <= Short.MAX_VALUE ) // Span fits in an unbiased short?
return new C2Chunk( bufX(0,0,C2Chunk.OFF,1));
int bias = (int)(lemin-(Short.MIN_VALUE+1));
return new C2SChunk( bufX(bias,xmin,C2SChunk.OFF,1),bias,DParseTask.pow10i(xmin));
}
// Compress column into ints
if( Integer.MIN_VALUE < min && max <= Integer.MAX_VALUE )
return new C4Chunk( bufX(0,0,0,2));
return new C8Chunk( bufX(0,0,0,3));
}
private static long [] NAS = {C1Chunk._NA,C2Chunk._NA,C4Chunk._NA,C8Chunk._NA};
// Compute a sparse integer buffer
private byte[] bufS(final int valsz){
int log = 0;
while((1 << log) < valsz)++log;
assert valsz == 0 || (1 << log) == valsz;
final int ridsz = _len2 >= 65535?4:2;
final int elmsz = ridsz + valsz;
int off = CXIChunk.OFF;
byte [] buf = MemoryManager.malloc1(off + _len*elmsz,true);
for( int i=0; i<_len; i++, off += elmsz ) {
if(ridsz == 2)
UDP.set2(buf,off,(short)_id[i]);
else
UDP.set4(buf,off,_id[i]);
if(valsz == 0){
assert _xs[i] == 0 && _ls[i] == 1;
continue;
}
assert _xs[i] == Integer.MIN_VALUE || _xs[i] >= 0:"unexpected exponent " + _xs[i]; // assert we have int or NA
final long lval = _xs[i] == Integer.MIN_VALUE?NAS[log]:_ls[i]*DParseTask.pow10i(_xs[i]);
switch(valsz){
case 1:
buf[off+ridsz] = (byte)lval;
break;
case 2:
short sval = (short)lval;
UDP.set2(buf,off+ridsz,sval);
break;
case 4:
int ival = (int)lval;
UDP.set4(buf, off+ridsz, ival);
break;
case 8:
UDP.set8(buf, off+ridsz, lval);
break;
default:
throw H2O.unimpl();
}
}
assert off==buf.length;
return buf;
}
// Compute a sparse float buffer
private byte[] bufD(final int valsz){
int log = 0;
while((1 << log) < valsz)++log;
assert (1 << log) == valsz;
final int ridsz = _len2 >= 65535?4:2;
final int elmsz = ridsz + valsz;
int off = CXDChunk.OFF;
byte [] buf = MemoryManager.malloc1(off + _len*elmsz,true);
for( int i=0; i<_len; i++, off += elmsz ) {
if(ridsz == 2)
UDP.set2(buf,off,(short)_id[i]);
else
UDP.set4(buf,off,_id[i]);
final double dval = _ds == null?isNA2(i)?Double.NaN:_ls[i]*DParseTask.pow10(_xs[i]):_ds[i];
switch(valsz){
case 4:
UDP.set4f(buf, off + ridsz, (float) dval);
break;
case 8:
UDP.set8d(buf, off + ridsz, dval);
break;
default:
throw H2O.unimpl();
}
}
assert off==buf.length;
return buf;
}
// Compute a compressed integer buffer
private byte[] bufX( long bias, int scale, int off, int log ) {
byte[] bs = new byte[(_len2<<log)+off];
int j = 0;
for( int i=0; i<_len2; i++ ) {
long le = -bias;
if(_id == null || (j < _id.length && _id[j] == i)){
if( isNA2(j) ) {
le = NAS[log];
} else {
int x = (_xs[j]==Integer.MIN_VALUE+1 ? 0 : _xs[j])-scale;
le += x >= 0
? _ls[j]*DParseTask.pow10i( x)
: _ls[j]/DParseTask.pow10i(-x);
}
++j;
}
switch( log ) {
case 0: bs [i +off] = (byte)le ; break;
case 1: UDP.set2(bs,(i<<1)+off, (short)le); break;
case 2: UDP.set4(bs,(i<<2)+off, (int)le); break;
case 3: UDP.set8(bs,(i<<3)+off, le); break;
default: H2O.fail();
}
}
assert j == _len:"j = " + j + ", len = " + _len + ", len2 = " + _len2 + ", id[j] = " + _id[j];
return bs;
}
// Compute a compressed double buffer
private Chunk chunkD() {
final byte [] bs = MemoryManager.malloc1(_len2*8,true);
int j = 0;
for(int i = 0; i < _len2; ++i){
double d = 0;
if(_id == null || (j < _id.length && _id[j] == i)) {
d = _ds != null?_ds[j]:(isNA2(j)||isEnum(j))?Double.NaN:_ls[j]*DParseTask.pow10(_xs[j]);
++j;
}
UDP.set8d(bs, 8*i, d);
}
assert j == _len:"j = " + j + ", _len = " + _len;
return new C8DChunk(bs);
}
// Compute compressed boolean buffer
private byte[] bufB(int bpv) {
assert bpv == 1 || bpv == 2 : "Only bit vectors with/without NA are supported";
final int off = CBSChunk.OFF;
int clen = off + CBSChunk.clen(_len2, bpv);
byte bs[] = new byte[clen];
// Save the gap = number of unfilled bits and bpv value
bs[0] = (byte) (((_len2*bpv)&7)==0 ? 0 : (8-((_len2*bpv)&7)));
bs[1] = (byte) bpv;
// Dense bitvector
int boff = 0;
byte b = 0;
int idx = CBSChunk.OFF;
int j = 0;
for (int i=0; i<_len2; i++) {
byte val = 0;
if(_id == null || (j < _id.length && _id[j] == i)) {
assert bpv == 2 || !isNA2(j);
val = (byte)(isNA2(j)?CBSChunk._NA:_ls[j]);
++j;
}
if( bpv==1 )
b = CBSChunk.write1b(b, val, boff);
else
b = CBSChunk.write2b(b, val, boff);
boff += bpv;
if (boff>8-bpv) { assert boff == 8; bs[idx] = b; boff = 0; b = 0; idx++; }
}
assert j == _len;
assert bs[0] == (byte) (boff == 0 ? 0 : 8-boff):"b[0] = " + bs[0] + ", boff = " + boff + ", bpv = " + bpv;
// Flush last byte
if (boff>0) bs[idx++] = b;
return bs;
}
// Set & At on NewChunks are weird: only used after inflating some other
// chunk. At this point the NewChunk is full size, no more appends allowed,
// and the xs exponent array should be only full of zeros. Accesses must be
// in-range and refer to the inflated values of the original Chunk.
@Override boolean set_impl(int i, long l) {
if( _ds != null ) return set_impl(i,(double)l);
if(_len != _len2){ // sparse?
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0)i = idx;
else cancel_sparse(); // for now don't bother setting the sparse value
}
_ls[i]=l; _xs[i]=0;
_naCnt = -1;
return true;
}
@Override public boolean set_impl(int i, double d) {
if(_ds == null){
assert _len == 0 || _ls != null;
switch_to_doubles();
}
if(_len != _len2){ // sparse?
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0)i = idx;
else cancel_sparse(); // for now don't bother setting the sparse value
}
while(i >= _len2) append2slowd();
_ds[i] = d;
_naCnt = -1;
return true;
}
@Override boolean set_impl(int i, float f) { return set_impl(i,(double)f); }
protected final boolean setNA_impl2(int i) {
if( isNA2(i) ) return true;
if( _ls != null ) { _ls[i] = Long.MAX_VALUE; _xs[i] = Integer.MIN_VALUE; }
if( _ds != null ) { _ds[i] = Double.NaN; }
_naCnt = -1;
return true;
}
@Override boolean setNA_impl(int i) {
if( isNA_impl(i) ) return true;
if(_len != _len2){
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else cancel_sparse(); // todo - do not necessarily cancel sparse here
}
return setNA_impl2(i);
}
@Override public long at8_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return 0;
}
if( _ls == null ) return (long)_ds[i];
return _ls[i]*DParseTask.pow10i(_xs[i]);
}
@Override public double atd_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return 0;
}
if( _ds == null ) return at8_impl(i);
assert _xs==null; return _ds[i];
}
@Override public boolean isNA_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return false;
}
return isNA2(i);
}
@Override public AutoBuffer write(AutoBuffer bb) { throw H2O.fail(); }
@Override public NewChunk read(AutoBuffer bb) { throw H2O.fail(); }
@Override NewChunk inflate_impl(NewChunk nc) { throw H2O.fail(); }
@Override boolean hasFloat() { throw H2O.fail(); }
@Override public String toString() { return "NewChunk._len="+_len; }
}
| src/main/java/water/fvec/NewChunk.java | package water.fvec;
import java.util.*;
import water.*;
import water.parser.DParseTask;
// An uncompressed chunk of data, supporting an append operation
public class NewChunk extends Chunk {
final int _cidx;
// We can record the following (mixed) data types:
// 1- doubles, in _ds including NaN for NA & 0; _ls==_xs==null
// 2- scaled decimals from parsing, in _ls & _xs; _ds==null
// 3- zero: requires _ls==0 && _xs==0
// 4- NA: either _ls==0 && _xs==Integer.MIN_VALUE, OR _ds=NaN
// 5- Enum: _xs==(Integer.MIN_VALUE+1) && _ds==null
// Chunk._len is the count of elements appended
// Sparse: if _len != _len2, then _ls/_ds are compressed to non-zero's only,
// and _xs is the row number. Still _len2 is count of elements including
// zeros, and _len is count of non-zeros.
transient long _ls[]; // Mantissa
transient int _xs[]; // Exponent, or if _ls==0, NA or Enum or Rows
transient int _id[]; // Indeces (row numbers) of stored values, used for sparse
transient double _ds[]; // Doubles, for inflating via doubles
int _len2; // Actual rows, if the data is sparse
int _naCnt=-1; // Count of NA's appended
int _strCnt; // Count of Enum's appended
int _nzCnt; // Count of non-zero's appended
final int _timCnt[] = new int[ParseTime.TIME_PARSE.length]; // Count of successful time parses
public static final int MIN_SPARSE_RATIO = 32;
public NewChunk( Vec vec, int cidx ) { _vec = vec; _cidx = cidx; }
// Constructor used when inflating a Chunk.
public NewChunk( Chunk C ) {
this(C._vec, C._vec.elem2ChunkIdx(C._start));
_len2 = C._len;
_len = C.sparseLen();
_start = C._start;
}
// Pre-sized newchunks.
public NewChunk( Vec vec, int cidx, int len ) {
this(vec,cidx);
_ds = new double[len];
Arrays.fill(_ds,Double.NaN);
_len = _len2 = len;
}
public final class Value {
int _gId; // row number in dense (ie counting zeros)
int _lId; // local array index of this value, equal to _gId if dense
public Value(int lid, int gid){_lId = lid; _gId = gid;}
public final int rowId0(){return _gId;}
public void add2Chunk(NewChunk c){
if(_ds == null) c.addNum(_ls[_lId],_xs[_lId]);
else c.addNum(_ds[_lId]);
}
}
public Iterator<Value> values(int fromIdx, int toIdx){
final int lId, gId;
final int to = Math.min(toIdx,_len2);
if(sparse()){
int x = Arrays.binarySearch(_id,0,_len,fromIdx);
if(x < 0) x = -x -1;
lId = x;
gId = x == _len?_len2:_id[x];
} else
lId = gId = fromIdx;
final Value v = new Value(lId,gId);
final Value next = new Value(lId,gId);
return new Iterator<Value>(){
@Override public final boolean hasNext(){return next._gId < to;}
@Override public final Value next(){
if(!hasNext())throw new NoSuchElementException();
v._gId = next._gId; v._lId = next._lId;
next._lId++;
if(sparse()) next._gId = next._lId < _len?_id[next._lId]:_len2;
else next._gId++;
return v;
}
@Override
public void remove() {throw new UnsupportedOperationException();}
};
}
// Heuristic to decide the basic type of a column
public byte type() {
if( _naCnt == -1 ) { // No rollups yet?
int nas=0, ss=0, nzs=0;
if( _ds != null ) {
assert _ls==null && _xs==null;
for( int i = 0; i < _len; ++i) if( Double.isNaN(_ds[i]) ) nas++; else if( _ds[i]!=0 ) nzs++;
} else {
assert _ds==null;
if( _ls != null )
for( int i=0; i<_len; i++ )
if( isNA2(i) ) nas++;
else {
if( isEnum2(i) ) ss++;
if( _ls[i] != 0 ) nzs++;
}
}
_nzCnt=nzs; _strCnt=ss; _naCnt=nas;
}
// Now run heuristic for type
if(_naCnt == _len2) // All NAs ==> NA Chunk
return AppendableVec.NA;
if(_strCnt > 0 && _strCnt + _naCnt == _len2)
return AppendableVec.ENUM; // All are Strings+NAs ==> Enum Chunk
// Larger of time & numbers
int timCnt=0; for( int t : _timCnt ) timCnt+=t;
int nums = _len2-_naCnt-timCnt;
return timCnt >= nums ? AppendableVec.TIME : AppendableVec.NUMBER;
}
protected final boolean isNA2(int idx) {
return (_ds == null) ? (_ls[idx] == Long.MAX_VALUE && _xs[idx] == Integer.MIN_VALUE) : Double.isNaN(_ds[idx]);
}
protected final boolean isEnum2(int idx) {
return _xs!=null && _xs[idx]==Integer.MIN_VALUE+1;
}
protected final boolean isEnum(int idx) {
if(_id == null)return isEnum2(idx);
int j = Arrays.binarySearch(_id,0,_len,idx);
if(j < 0)return false;
return isEnum2(j);
}
public void addEnum(int e) {append2(e,Integer.MIN_VALUE+1);}
public void addNA ( ) {append2(Long.MAX_VALUE,Integer.MIN_VALUE ); }
public void addNum (long val, int exp) {
if(_ds != null){
assert _ls == null;
addNum(val*DParseTask.pow10(exp));
} else {
if( val == 0 ) exp = 0;// Canonicalize zero
long t; // Remove extra scaling
while( exp < 0 && exp > -9999999 && (t=val/10)*10==val ) { val=t; exp++; }
append2(val,exp);
}
}
// Fast-path append double data
public void addNum(double d) {
if(_id == null || d != 0) {
if(_ls != null)switch_to_doubles();
if( _ds == null || _len >= _ds.length ) {
append2slowd();
// call addNum again since append2slow might have flipped to sparse
addNum(d);
assert _len <= _len2;
return;
}
if(_id != null)_id[_len] = _len2;
_ds[_len++] = d;
}
_len2++;
assert _len <= _len2;
}
public final boolean sparse(){return _id != null;}
public void addZeros(int n){
if(!sparse()) for(int i = 0; i < n; ++i)addNum(0,0);
else _len2 += n;
}
// Append all of 'nc' onto the current NewChunk. Kill nc.
public void add( NewChunk nc ) {
assert _cidx >= 0;
assert _len <= _len2;
assert nc._len <= nc._len2:"_len = " + nc._len + ", _len2 = " + nc._len2;
if( nc._len2 == 0 ) return;
if(_len2 == 0){
_ls = nc._ls; nc._ls = null;
_xs = nc._xs; nc._xs = null;
_id = nc._id; nc._id = null;
_ds = nc._ds; nc._ds = null;
_len = nc._len;
_len2 = nc._len2;
return;
}
if(nc.sparse() != sparse()){ // for now, just make it dense
cancel_sparse();
nc.cancel_sparse();
}
if( _ds != null ) throw H2O.unimpl();
while( _len+nc._len >= _xs.length )
_xs = MemoryManager.arrayCopyOf(_xs,_xs.length<<1);
_ls = MemoryManager.arrayCopyOf(_ls,_xs.length);
System.arraycopy(nc._ls,0,_ls,_len,nc._len);
System.arraycopy(nc._xs,0,_xs,_len,nc._len);
if(_id != null) {
assert nc._id != null;
_id = MemoryManager.arrayCopyOf(_id,_xs.length);
System.arraycopy(nc._id,0,_id,_len,nc._len);
for(int i = _len; i < _len + nc._len; ++i) _id[i] += _len2;
} else assert nc._id == null;
_len += nc._len;
_len2 += nc._len2;
nc._ls = null; nc._xs = null; nc._id = null; nc._len = nc._len2 = 0;
assert _len <= _len2;
}
// PREpend all of 'nc' onto the current NewChunk. Kill nc.
public void addr( NewChunk nc ) {
long [] tmpl = _ls; _ls = nc._ls; nc._ls = tmpl;
int [] tmpi = _xs; _xs = nc._xs; nc._xs = tmpi;
tmpi = _id; _id = nc._id; nc._id = tmpi;
double[] tmpd = _ds; _ds = nc._ds; nc._ds = tmpd;
int tmp = _len; _len=nc._len; nc._len=tmp;
tmp = _len2; _len2 = nc._len2; nc._len2 = tmp;
add(nc);
}
// Fast-path append long data
void append2( long l, int x ) {
assert _ds == null;
if(_id == null || l != 0){
if(_ls == null || _len == _ls.length) {
append2slow();
// again call append2 since calling append2slow might have changed things (eg might have switched to sparse and l could be 0)
append2(l,x);
return;
}
_ls[_len] = l;
_xs[_len] = x;
if(_id != null)_id[_len] = _len2;
_len++;
}
_len2++;
assert _len <= _len2;
}
// Slow-path append data
private void append2slowd() {
if( _len > Vec.CHUNK_SZ )
throw new ArrayIndexOutOfBoundsException(_len);
assert _ls==null;
if(_ds != null && _ds.length > 0){
if(_id == null){ // check for sparseness
int nzs = 0; // assume one non-zero for the element currently being stored
for(double d:_ds)if(d != 0)++nzs;
if((nzs+1)*MIN_SPARSE_RATIO < _len2)
set_sparse(nzs);
} else _id = MemoryManager.arrayCopyOf(_id, _len << 1);
_ds = MemoryManager.arrayCopyOf(_ds,_len<<1);
} else _ds = MemoryManager.malloc8d(4);
assert _len == 0 || _ds.length > _len:"_ds.length = " + _ds.length + ", _len = " + _len;
}
// Slow-path append data
private void append2slow( ) {
if( _len > Vec.CHUNK_SZ )
throw new ArrayIndexOutOfBoundsException(_len);
assert _ds==null;
if(_ls != null && _ls.length > 0){
if(_id == null){ // check for sparseness
int nzs = 0;
for(int i = 0; i < _ls.length; ++i) if(_ls[i] != 0 || _xs[i] != 0)++nzs;
if((nzs+1)*MIN_SPARSE_RATIO < _len2){
set_sparse(nzs);
assert _len == 0 || _len <= _ls.length:"_len = " + _len + ", _ls.length = " + _ls.length + ", nzs = " + nzs + ", len2 = " + _len2;
assert _id.length == _ls.length;
assert _len <= _len2;
return;
}
} else {
// verify we're still sufficiently sparse
if((MIN_SPARSE_RATIO*(_len) >> 1) > _len2) cancel_sparse();
else _id = MemoryManager.arrayCopyOf(_id,_len<<1);
}
_ls = MemoryManager.arrayCopyOf(_ls,_len<<1);
_xs = MemoryManager.arrayCopyOf(_xs,_len<<1);
} else {
_ls = MemoryManager.malloc8(4);
_xs = MemoryManager.malloc4(4);
_id = _id == null?null:MemoryManager.malloc4(4);
}
assert _len == 0 || _len < _ls.length:"_len = " + _len + ", _ls.length = " + _ls.length;
assert _id == null || _id.length == _ls.length;
assert _len <= _len2;
}
// Do any final actions on a completed NewVector. Mostly: compress it, and
// do a DKV put on an appropriate Key. The original NewVector goes dead
// (does not live on inside the K/V store).
public Chunk new_close() {
Chunk chk = compress();
if(_vec instanceof AppendableVec)
((AppendableVec)_vec).closeChunk(this);
return chk;
}
public void close(Futures fs) { close(_cidx,fs); }
protected void set_enum(){
for(int i = 0; i < _xs.length; ++i){
if(_xs[i] == (Integer.MIN_VALUE+1))
_xs[i] = 0;
else
setNA_impl2(i);
}
}
protected void switch_to_doubles(){
assert _ds == null;
double [] ds = MemoryManager.malloc8d(_len);
for(int i = 0; i < _len; ++i)
if(isNA2(i) || isEnum2(i))ds[i] = Double.NaN;
else ds[i] = _ls[i]*DParseTask.pow10(_xs[i]);
_ls = null;
_xs = null;
_ds = ds;
}
protected void set_sparse(int nzeros){
if(_len == nzeros)return;
if(_id != null){ // we have sparse represenation but some 0s in it!
int [] id = MemoryManager.malloc4(nzeros);
int j = 0;
if(_ds != null){
double [] ds = MemoryManager.malloc8d(nzeros);
for(int i = 0; i < _len; ++i){
if(_ds[i] != 0){
ds[j] = _ds[i];
id[j] = _id[i];
++j;
}
}
_ds = ds;
} else {
long [] ls = MemoryManager.malloc8(nzeros);
int [] xs = MemoryManager.malloc4(nzeros);
for(int i = 0; i < _len; ++i){
if(_ls[i] != 0){
ls[j] = _ls[i];
xs[j] = _xs[i];
id[j] = _id[i];
++j;
}
}
_ls = ls;
_xs = xs;
}
_id = id;
assert j == nzeros;
return;
}
assert _len == _len2:"_len = " + _len + ", _len2 = " + _len2 + ", nzeros = " + nzeros;
int zs = 0;
if(_ds == null){
assert nzeros < _ls.length;
_id = MemoryManager.malloc4(_ls.length);
for(int i = 0; i < _len; ++i){
if(_ls[i] == 0 && _xs[i] == 0)++zs;
else {
_ls[i-zs] = _ls[i];
_xs[i-zs] = _xs[i];
_id[i-zs] = i;
}
}
} else {
assert nzeros < _ds.length;
_id = MemoryManager.malloc4(_ds.length);
for(int i = 0; i < _len; ++i){
if(_ds[i] == 0)++zs;
else {
_ds[i-zs] = _ds[i];
_id[i-zs] = i;
}
}
}
assert zs == (_len - nzeros);
_len = nzeros;
}
protected void cancel_sparse(){
if(_len != _len2){
if(_ds == null){
int [] xs = MemoryManager.malloc4(_len2);
long [] ls = MemoryManager.malloc8(_len2);
for(int i = 0; i < _len; ++i){
xs[_id[i]] = _xs[i];
ls[_id[i]] = _ls[i];
}
_xs = xs;
_ls = ls;
} else {
double [] ds = MemoryManager.malloc8d(_len2);
for(int i = 0; i < _len; ++i) ds[_id[i]] = _ds[i];
_ds = ds;
}
_id = null;
_len = _len2;
}
}
// Study this NewVector and determine an appropriate compression scheme.
// Return the data so compressed.
static final int MAX_FLOAT_MANTISSA = 0x7FFFFF;
Chunk compress() {
Chunk res = compress2();
// force everything to null after compress to free up the memory
_id = null;
_xs = null;
_ds = null;
_ls = null;
return res;
}
private final Chunk compress2() {
// Check for basic mode info: all missing or all strings or mixed stuff
byte mode = type();
if( mode==AppendableVec.NA ) // ALL NAs, nothing to do
return new C0DChunk(Double.NaN,_len);
boolean rerun=false;
if(mode == AppendableVec.ENUM){
for( int i=0; i<_len; i++ )
if(isEnum2(i))
_xs[i] = 0;
else if(!isNA2(i)){
setNA_impl2(i);
++_naCnt;
}
// Smack any mismatched string/numbers
} else if(mode == AppendableVec.NUMBER){
for( int i=0; i<_len; i++ )
if(isEnum2(i)) {
setNA_impl2(i);
rerun = true;
}
}
if( rerun ) { _naCnt = -1; type(); } // Re-run rollups after dropping all numbers/enums
boolean sparse = false;
// sparse? treat as sparse iff we have at least MIN_SPARSE_RATIOx more zeros than nonzeros
if(MIN_SPARSE_RATIO*(_naCnt + _nzCnt) < _len2) {
set_sparse(_naCnt + _nzCnt);
sparse = true;
}
// If the data was set8 as doubles, we do a quick check to see if it's
// plain longs. If not, we give up and use doubles.
if( _ds != null ) {
int i=0;
for( ; i<_len; i++ ) // Attempt to inject all doubles into longs
if( !Double.isNaN(_ds[i]) && (double)(long)_ds[i] != _ds[i] ) break;
if(i < _len)
return sparse?new CXDChunk(_len2,_len,8,bufD(8)):chunkD();
_ls = new long[_ds.length]; // Else flip to longs
_xs = new int [_ds.length];
double [] ds = _ds;
_ds = null;
for( i=0; i<_len; i++ ) // Inject all doubles into longs
if( Double.isNaN(ds[i]) )setNA_impl2(i);
else _ls[i] = (long)ds[i];
}
// IF (_len2 > _len) THEN Sparse
// Check for compressed *during appends*. Here we know:
// - No specials; _xs[]==0.
// - No floats; _ds==null
// - NZ length in _len, actual length in _len2.
// - Huge ratio between _len2 and _len, and we do NOT want to inflate to
// the larger size; we need to keep it all small all the time.
// - Rows in _xs
// Data in some fixed-point format, not doubles
// See if we can sanely normalize all the data to the same fixed-point.
int xmin = Integer.MAX_VALUE; // min exponent found
long lemin= 0, lemax=lemin; // min/max at xmin fixed-point
boolean overflow=false;
boolean floatOverflow = false;
boolean first = true;
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
int p10iLength = DParseTask.powers10i.length;
for( int i=0; i<_len; i++ ) {
if( isNA2(i) ) continue;
long l = _ls[i];
int x = _xs[i];
assert x != Integer.MIN_VALUE:"l = " + l + ", x = " + x;
if( x==Integer.MIN_VALUE+1) x=0; // Replace enum flag with no scaling
assert l!=0 || x==0:"l == 0 while x = " + x + " ls = " + Arrays.toString(_ls); // Exponent of zero is always zero
// Compute per-chunk min/max
double d = l*DParseTask.pow10(x);
if( d < min ) min = d;
if( d > max ) max = d;
long t; // Remove extra scaling
while( l!=0 && (t=l/10)*10==l ) { l=t; x++; }
floatOverflow = Math.abs(l) > MAX_FLOAT_MANTISSA;
if( first ) {
first = false;
xmin = x;
lemin = lemax = l;
continue;
}
// Track largest/smallest values at xmin scale. Note overflow.
if( x < xmin ) {
if( overflow || (overflow = ((xmin-x) >=p10iLength)) ) continue;
lemin *= DParseTask.pow10i(xmin-x);
lemax *= DParseTask.pow10i(xmin-x);
xmin = x; // Smaller xmin
}
// *this* value, as a long scaled at the smallest scale
if( overflow || (overflow = ((x-xmin) >=p10iLength)) ) continue;
long le = l*DParseTask.pow10i(x-xmin);
if( le < lemin ) lemin=le;
if( le > lemax ) lemax=le;
}
if(_len2 != _len){ // sparse? compare xmin/lemin/lemax with 0
lemin = Math.min(0, lemin);
lemax = Math.max(0, lemax);
min = Math.min(min,0);
max = Math.max(max,0);
}
// Constant column?
if( _naCnt==0 && min==max ) {
return ((long)min == min)
? new C0LChunk((long)min,_len2)
: new C0DChunk( min,_len2);
}
// Boolean column?
if (max == 1 && min == 0 && xmin == 0 && !overflow) {
if(sparse) { // Very sparse?
return _naCnt==0
?new CX0Chunk(_len2,_len,bufS(0))// No NAs, can store as sparse bitvector
:new CXIChunk(_len2,_len,1,bufS(1)); // have NAs, store as sparse 1byte values
}
int bpv = _strCnt+_naCnt > 0 ? 2 : 1; // Bit-vector
byte[] cbuf = bufB(bpv);
return new CBSChunk(cbuf, cbuf[0], cbuf[1]);
}
final boolean fpoint = xmin < 0 || min < Long.MIN_VALUE || max > Long.MAX_VALUE;
if(sparse){
if(fpoint) return new CXDChunk(_len2,_len,8,bufD(8));
int sz = 8;
if(Short.MIN_VALUE <= min && max <= Short.MAX_VALUE)sz = 2;
else if(Integer.MIN_VALUE <= min && max <= Integer.MAX_VALUE)sz = 4;
return new CXIChunk(_len2,_len,sz,bufS(sz));
}
// Exponent scaling: replacing numbers like 1.3 with 13e-1. '13' fits in a
// byte and we scale the column by 0.1. A set of numbers like
// {1.2,23,0.34} then is normalized to always be represented with 2 digits
// to the right: {1.20,23.00,0.34} and we scale by 100: {120,2300,34}.
// This set fits in a 2-byte short.
// We use exponent-scaling for bytes & shorts only; it's uncommon (and not
// worth it) for larger numbers. We need to get the exponents to be
// uniform, so we scale up the largest lmax by the largest scale we need
// and if that fits in a byte/short - then it's worth compressing. Other
// wise we just flip to a float or double representation.
if( overflow || (fpoint && floatOverflow) || -35 > xmin || xmin > 35 )
return chunkD();
if( fpoint ) {
if((int)lemin == lemin && (int)lemax == lemax){
if(lemax-lemin < 255 && (int)lemin == lemin ) // Fits in scaled biased byte?
return new C1SChunk( bufX(lemin,xmin,C1SChunk.OFF,0),(int)lemin,DParseTask.pow10(xmin));
if(lemax-lemin < 65535 ) { // we use signed 2B short, add -32k to the bias!
long bias = 32767 + lemin;
return new C2SChunk( bufX(bias,xmin,C2SChunk.OFF,1),(int)bias,DParseTask.pow10(xmin));
}
if(lemax - lemin < Integer.MAX_VALUE)
return new C4SChunk(bufX(lemin, xmin,C4SChunk.OFF,2),(int)lemin,DParseTask.pow10(xmin));
}
return chunkD();
} // else an integer column
// Compress column into a byte
if(xmin == 0 && 0<=lemin && lemax <= 255 && ((_naCnt + _strCnt)==0) )
return new C1NChunk( bufX(0,0,C1NChunk.OFF,0));
if(lemin < Integer.MIN_VALUE)return new C8Chunk( bufX(0,0,0,3));
if( lemax-lemin < 255 ) { // Span fits in a byte?
if(0 <= min && max < 255 ) // Span fits in an unbiased byte?
return new C1Chunk( bufX(0,0,C1Chunk.OFF,0));
return new C1SChunk( bufX(lemin,xmin,C1SChunk.OFF,0),(int)lemin,DParseTask.pow10i(xmin));
}
// Compress column into a short
if( lemax-lemin < 65535 ) { // Span fits in a biased short?
if( xmin == 0 && Short.MIN_VALUE < lemin && lemax <= Short.MAX_VALUE ) // Span fits in an unbiased short?
return new C2Chunk( bufX(0,0,C2Chunk.OFF,1));
int bias = (int)(lemin-(Short.MIN_VALUE+1));
return new C2SChunk( bufX(bias,xmin,C2SChunk.OFF,1),bias,DParseTask.pow10i(xmin));
}
// Compress column into ints
if( Integer.MIN_VALUE < min && max <= Integer.MAX_VALUE )
return new C4Chunk( bufX(0,0,0,2));
return new C8Chunk( bufX(0,0,0,3));
}
private static long [] NAS = {C1Chunk._NA,C2Chunk._NA,C4Chunk._NA,C8Chunk._NA};
// Compute a sparse integer buffer
private byte[] bufS(final int valsz){
int log = 0;
while((1 << log) < valsz)++log;
assert valsz == 0 || (1 << log) == valsz;
final int ridsz = _len2 >= 65535?4:2;
final int elmsz = ridsz + valsz;
int off = CXIChunk.OFF;
byte [] buf = MemoryManager.malloc1(off + _len*elmsz,true);
for( int i=0; i<_len; i++, off += elmsz ) {
if(ridsz == 2)
UDP.set2(buf,off,(short)_id[i]);
else
UDP.set4(buf,off,_id[i]);
if(valsz == 0){
assert _xs[i] == 0 && _ls[i] == 1;
continue;
}
assert _xs[i] == Integer.MIN_VALUE || _xs[i] >= 0:"unexpected exponent " + _xs[i]; // assert we have int or NA
final long lval = _xs[i] == Integer.MIN_VALUE?NAS[log]:_ls[i]*DParseTask.pow10i(_xs[i]);
switch(valsz){
case 1:
buf[off+ridsz] = (byte)lval;
break;
case 2:
short sval = (short)lval;
UDP.set2(buf,off+ridsz,sval);
break;
case 4:
int ival = (int)lval;
UDP.set4(buf, off+ridsz, ival);
break;
case 8:
UDP.set8(buf, off+ridsz, lval);
break;
default:
throw H2O.unimpl();
}
}
assert off==buf.length;
return buf;
}
// Compute a sparse float buffer
private byte[] bufD(final int valsz){
int log = 0;
while((1 << log) < valsz)++log;
assert (1 << log) == valsz;
final int ridsz = _len2 >= 65535?4:2;
final int elmsz = ridsz + valsz;
int off = CXDChunk.OFF;
byte [] buf = MemoryManager.malloc1(off + _len*elmsz,true);
for( int i=0; i<_len; i++, off += elmsz ) {
if(ridsz == 2)
UDP.set2(buf,off,(short)_id[i]);
else
UDP.set4(buf,off,_id[i]);
final double dval = _ds == null?isNA2(i)?Double.NaN:_ls[i]*DParseTask.pow10(_xs[i]):_ds[i];
switch(valsz){
case 4:
UDP.set4f(buf, off + ridsz, (float) dval);
break;
case 8:
UDP.set8d(buf, off + ridsz, dval);
break;
default:
throw H2O.unimpl();
}
}
assert off==buf.length;
return buf;
}
// Compute a compressed integer buffer
private byte[] bufX( long bias, int scale, int off, int log ) {
byte[] bs = new byte[(_len2<<log)+off];
int j = 0;
for( int i=0; i<_len2; i++ ) {
long le = -bias;
if(_id == null || (j < _id.length && _id[j] == i)){
if( isNA2(j) ) {
le = NAS[log];
} else {
int x = (_xs[j]==Integer.MIN_VALUE+1 ? 0 : _xs[j])-scale;
le += x >= 0
? _ls[j]*DParseTask.pow10i( x)
: _ls[j]/DParseTask.pow10i(-x);
}
++j;
}
switch( log ) {
case 0: bs [i +off] = (byte)le ; break;
case 1: UDP.set2(bs,(i<<1)+off, (short)le); break;
case 2: UDP.set4(bs,(i<<2)+off, (int)le); break;
case 3: UDP.set8(bs,(i<<3)+off, le); break;
default: H2O.fail();
}
}
assert j == _len:"j = " + j + ", len = " + _len + ", len2 = " + _len2 + ", id[j] = " + _id[j];
return bs;
}
// Compute a compressed double buffer
private Chunk chunkD() {
final byte [] bs = MemoryManager.malloc1(_len2*8,true);
int j = 0;
for(int i = 0; i < _len2; ++i){
double d = 0;
if(_id == null || (j < _id.length && _id[j] == i)) {
d = _ds != null?_ds[j]:(isNA2(j)||isEnum(j))?Double.NaN:_ls[j]*DParseTask.pow10(_xs[j]);
++j;
}
UDP.set8d(bs, 8*i, d);
}
assert j == _len:"j = " + j + ", _len = " + _len;
return new C8DChunk(bs);
}
// Compute compressed boolean buffer
private byte[] bufB(int bpv) {
assert bpv == 1 || bpv == 2 : "Only bit vectors with/without NA are supported";
final int off = CBSChunk.OFF;
int clen = off + CBSChunk.clen(_len2, bpv);
byte bs[] = new byte[clen];
// Save the gap = number of unfilled bits and bpv value
bs[0] = (byte) (((_len2*bpv)&7)==0 ? 0 : (8-((_len2*bpv)&7)));
bs[1] = (byte) bpv;
// Dense bitvector
int boff = 0;
byte b = 0;
int idx = CBSChunk.OFF;
int j = 0;
for (int i=0; i<_len2; i++) {
byte val = 0;
if(_id == null || (j < _id.length && _id[j] == i)) {
assert bpv == 2 || !isNA2(j);
val = (byte)(isNA2(j)?CBSChunk._NA:_ls[j]);
++j;
}
if( bpv==1 )
b = CBSChunk.write1b(b, val, boff);
else
b = CBSChunk.write2b(b, val, boff);
boff += bpv;
if (boff>8-bpv) { assert boff == 8; bs[idx] = b; boff = 0; b = 0; idx++; }
}
assert j == _len;
assert bs[0] == (byte) (boff == 0 ? 0 : 8-boff):"b[0] = " + bs[0] + ", boff = " + boff + ", bpv = " + bpv;
// Flush last byte
if (boff>0) bs[idx++] = b;
return bs;
}
// Set & At on NewChunks are weird: only used after inflating some other
// chunk. At this point the NewChunk is full size, no more appends allowed,
// and the xs exponent array should be only full of zeros. Accesses must be
// in-range and refer to the inflated values of the original Chunk.
@Override boolean set_impl(int i, long l) {
if( _ds != null ) return set_impl(i,(double)l);
if(_len != _len2){ // sparse?
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0)i = idx;
else cancel_sparse(); // for now don't bother setting the sparse value
}
_ls[i]=l; _xs[i]=0;
_naCnt = -1;
return true;
}
@Override public boolean set_impl(int i, double d) {
if(_ds == null){
assert _len == 0 || _ls != null;
switch_to_doubles();
}
if(_len != _len2){ // sparse?
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0)i = idx;
else cancel_sparse(); // for now don't bother setting the sparse value
}
while(i >= _len2) append2slowd();
_ds[i] = d;
_naCnt = -1;
return true;
}
@Override boolean set_impl(int i, float f) { return set_impl(i,(double)f); }
protected final boolean setNA_impl2(int i) {
if( isNA2(i) ) return true;
if( _ls != null ) { _ls[i] = Long.MAX_VALUE; _xs[i] = Integer.MIN_VALUE; }
if( _ds != null ) { _ds[i] = Double.NaN; }
_naCnt = -1;
return true;
}
@Override boolean setNA_impl(int i) {
if( isNA_impl(i) ) return true;
if(_len != _len2){
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else cancel_sparse(); // todo - do not necessarily cancel sparse here
}
return setNA_impl2(i);
}
@Override public long at8_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return 0;
}
if( _ls == null ) return (long)_ds[i];
return _ls[i]*DParseTask.pow10i(_xs[i]);
}
@Override public double atd_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return 0;
}
if( _ds == null ) return at8_impl(i);
assert _xs==null; return _ds[i];
}
@Override public boolean isNA_impl( int i ) {
if( _len2 != _len ) {
int idx = Arrays.binarySearch(_id,0,_len,i);
if(idx >= 0) i = idx;
else return false;
}
return isNA2(i);
}
@Override public AutoBuffer write(AutoBuffer bb) { throw H2O.fail(); }
@Override public NewChunk read(AutoBuffer bb) { throw H2O.fail(); }
@Override NewChunk inflate_impl(NewChunk nc) { throw H2O.fail(); }
@Override boolean hasFloat() { throw H2O.fail(); }
@Override public String toString() { return "NewChunk._len="+_len; }
}
| Fix in new chunk: when switching from doubles to integers, new chunk will call setNA(int) which resets _naCnt to -1 which is later used to decide compression strategy. Fixed by setting _naCnt back to correct value after converting to integers.
| src/main/java/water/fvec/NewChunk.java | Fix in new chunk: when switching from doubles to integers, new chunk will call setNA(int) which resets _naCnt to -1 which is later used to decide compression strategy. Fixed by setting _naCnt back to correct value after converting to integers. | <ide><path>rc/main/java/water/fvec/NewChunk.java
<ide> _xs = new int [_ds.length];
<ide> double [] ds = _ds;
<ide> _ds = null;
<add> final int naCnt = _naCnt;
<ide> for( i=0; i<_len; i++ ) // Inject all doubles into longs
<ide> if( Double.isNaN(ds[i]) )setNA_impl2(i);
<ide> else _ls[i] = (long)ds[i];
<add> // setNA_impl2 will set _naCnt to -1!
<add> // we already know what the naCnt is (it did not change!) so set it back to correct value
<add> _naCnt = naCnt;
<ide> }
<ide>
<ide> // IF (_len2 > _len) THEN Sparse |
|
Java | apache-2.0 | 0fc637ce36ead96a6603095bece4604da2341159 | 0 | operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver | /*
Copyright 2008-2011 Opera Software ASA
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.opera.core.systems.scope.stp;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.opera.core.systems.scope.handlers.AbstractEventHandler;
import com.opera.core.systems.scope.handlers.IConnectionHandler;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.scope.protos.UmsProtos;
import com.opera.core.systems.scope.protos.UmsProtos.Command;
import com.opera.core.systems.scope.protos.UmsProtos.Error;
import com.opera.core.systems.scope.protos.UmsProtos.Event;
import com.opera.core.systems.scope.protos.UmsProtos.Response;
import com.opera.core.systems.util.SocketListener;
import com.opera.core.systems.util.SocketMonitor;
import org.openqa.selenium.WebDriverException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StpConnection implements SocketListener {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private SocketChannel socketChannel;
// Outgoing send queue
private final ArrayBlockingQueue<ByteBuffer> requests;
private ByteBuffer recvBuffer;
// For STP1
final byte[] prefix = {'S', 'T', 'P', 1};
private ByteString stpPrefix = ByteString.copyFrom(prefix);
private AbstractEventHandler eventHandler;
private UmsEventParser stp1EventHandler;
private IConnectionHandler connectionHandler;
public enum State {
SERVICELIST, HANDSHAKE, EMPTY, STP;
}
private State state = State.SERVICELIST;
private SocketMonitor monitor;
private void setState(State state) {
// logger.fine("Setting state: " + state.toString());
this.state = state;
}
public boolean isConnected() {
return (socketChannel != null);
}
/*
@Override
public void finalize() throws Throwable {
logger.severe("STPConnection cleanup");
if (socketChannel != null && socketChannel.isOpen()) {
close();
}
super.finalize();
}
*/
/**
* Initializes variables in object scope, sets 'count known' to false to read byte count (STP/0).
*/
public StpConnection(SocketChannel socket, IConnectionHandler handler,
AbstractEventHandler eventHandler, SocketMonitor monitor)
throws IOException {
connectionHandler = handler;
socketChannel = socket;
this.eventHandler = eventHandler;
this.monitor = monitor;
requests = new ArrayBlockingQueue<ByteBuffer>(1024);
recvBuffer = ByteBuffer.allocateDirect(65536);
recvBuffer.limit(0);
socket.configureBlocking(false);
monitor.add(socket, this, SelectionKey.OP_READ);
if (!handler.onConnected(this)) {
close();
throw new IOException(
"Connection not allowed from IConnectionHandler (already connected)");
}
}
private void switchToStp1() {
stp1EventHandler = new UmsEventParser(eventHandler);
sendEnableStp1();
setState(State.HANDSHAKE);
}
/**
* Queues up an STP/1 message sent from another thread and wakes up selector to register it to the
* key.
*
* @param command to add to the request queue
*/
public void send(Command command) {
logger.finest(command.toString());
byte[] payload = command.toByteArray();
int totalSize = payload.length + 1; // increment 1 for message type
ByteBuffer outMessageSize = encodeMessageSize(totalSize);
// create the message
ByteBuffer buffer = ByteBuffer.allocateDirect(prefix.length
+ outMessageSize.position() + 1 + payload.length);
buffer.put(prefix, 0, prefix.length);
outMessageSize.flip();
buffer.put(outMessageSize);
buffer.put((byte) 1);
buffer.put(payload);
// Log what is being sent.
logger.finest("SEND: " + command.toString());
requests.add(buffer);
monitor.modify(socketChannel, this, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public void sendEnableStp1() {
// Temporary fix for CORE-33057
try {
Thread.sleep(OperaIntervals.EXEC_SLEEP.getValue());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
send("*enable stp-1");
}
public void sendQuit() {
send("*quit");
}
/**
* Queues up an STP/0 message sent from another thread and wakes up selector to register it to the
* key.
*
* @param message to add to the request queue
*/
private void send(String message) {
String scopeMessage = message.length() + " " + message;
logger.finest("WRITE : " + scopeMessage);
byte[] bytes = null;
try {
bytes = scopeMessage.getBytes("UTF-16BE");
} catch (UnsupportedEncodingException e) {
close();
connectionHandler.onException(e);
return;
}
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
requests.add(buffer);
monitor.modify(socketChannel, this, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public boolean canRead(SelectableChannel channel) throws IOException {
logger.finest("canRead");
if (!channel.isOpen()) {
return false;
}
if (socketChannel == null) {
throw new IOException(
"We dont have a socket :-)");
}
// Read as much data as possible into buffer.
ByteBuffer readBuffer = ByteBuffer.allocateDirect(1000);
int readSize = 0;
// Continue to read data and read messages until there are no messages
boolean didNotFindAnyMessage = false;
while (!didNotFindAnyMessage) {
logger.finest("canReadLoop!");
// Read as much data as possible (until recvBuffer is full OR we don't get
// any more data)
do {
readBuffer.clear();
try {
// do we have a socket
if (socketChannel == null) {
readSize = -1;
// do we have room in our buffer?
} else {
readSize = socketChannel.read(readBuffer);
if (readSize > 0) {
readBuffer.limit(readSize);
readBuffer.position(0);
}
}
} catch (IOException ex) {
logger.warning("Channel closed, causing exception: " + ex.getMessage());
readSize = -1; // Same as error from socketChannel.read
}
if (readSize < 0) {
try {
logger.log(Level.FINER, "Channel closed: {0}",
socketChannel.socket().getInetAddress().getHostName());
} catch (NullPointerException e) {
// ignore
}
connectionHandler.onDisconnect();
monitor.remove(socketChannel);
return false;
} else if (readSize > 0) {
// Double buffer size if needed!
if (recvBuffer.limit() + readBuffer.limit() >= recvBuffer.capacity()) {
logger.finest("Doubled the size of our recv buffer!");
ByteBuffer newRecvBuffer = ByteBuffer.allocate(recvBuffer.capacity() * 2);
newRecvBuffer.clear();
recvBuffer.position(0);
newRecvBuffer.limit(recvBuffer.limit());
newRecvBuffer.position(0);
newRecvBuffer.put(recvBuffer);
newRecvBuffer.position(0);
recvBuffer = newRecvBuffer;
}
recvBuffer.position(recvBuffer.limit());
recvBuffer.limit(recvBuffer.limit() + readSize);// increase limit!
recvBuffer.put(readBuffer);
logger.finest("did read " + readSize + " bytes, new buffer size = "
+ recvBuffer.limit());
}
} while (readSize > 0);
// Read as many messages as possible, and only
didNotFindAnyMessage = true;
while (readMessage(recvBuffer)) {
didNotFindAnyMessage = false;
}
}
return true;
}
public boolean canWrite(SelectableChannel channel) throws IOException {
logger.finest("canWrite");
if (socketChannel == null) {
throw new IOException("We don't have a socket :-)");
}
int totalWritten = 0;
while (!requests.isEmpty()) {
ByteBuffer buffer = requests.poll();
buffer.flip();
int written = 0;
do {
written = socketChannel.write(buffer);
if (written <= 0) {
break;
}
if (written > 0) {
totalWritten += written;
}
} while (buffer.hasRemaining());
}
logger.finest("Wrote " + totalWritten + " bytes");
return (!requests.isEmpty());
}
/**
* Switches the wait state and wakes up the selector to process.
*/
public void close() {
if (socketChannel == null) {
return;
}
monitor.remove(socketChannel);
try {
socketChannel.close();
} catch (IOException ignored) {
/* nothing to be done */
} finally {
socketChannel = null;
}
}
/**
* Processes an incoming message and passes it to event handler if needed, the following events
* are to our interest: Runtime-Started : ecmascript runtime starts in Opera (that we can inject
* to) Runtime-Stopped : ecmascript runtime stops (not used, buggy) Message: fired from console
* log event Updated-Window: a window is updated OR created (opener-id=0) Active-Window: window
* focus changed Window-Closed: self explanatory If message matches none it is added to the
* response queue (probably response to command).
*/
public void parseServiceList(String message) {
logger.finer("parseServiceList: \"" + message + "\"");
int split = message.indexOf(" ");
if (split < 0) {
connectionHandler.onException(new WebDriverException("Invalid service list received."));
return;
}
List<String> services = Arrays.asList(message.substring(split + 1).split(","));
connectionHandler.onServiceList(services);
logger.fine("Service list ok");
if (!services.contains("stp-1")) {
connectionHandler.onException(new WebDriverException("STP/0 is not supported!"));
return;
}
switchToStp1();
}
private void signalResponse(int tag, Response response) {
connectionHandler.onResponseReceived(tag, response);
}
private void signalEvent(Event event) {
logger.finest("EVENT " + event.toString());
stp1EventHandler.handleEvent(event);
}
/**
* Reads a message from the buffer, and pops the used data out of the buffer.
*
* @param buffer the buffer containing messages
* @return true if we got a message from the buffer
*/
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenreading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenreading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start!
buffer.get(dst);
buffer.position(0);// reset position!
bytesWeHaveBeenreading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Handshake"));
} else {
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
}
break;
case EMPTY: // read 4 byte header: STP\0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenreading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Header"));
}
}
break;
case STP:
// Try to read size
buffer.position(0);
if (buffer.limit() <= 0) {
logger.finest("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenreading = buffer.position();
buffer.position(0);
// If we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenreading + messageSize) {
buffer.position(bytesWeHaveBeenreading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenreading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenreading += messageSize; // 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new WebDriverException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.finest("tried to read a message, but expected " + (4 + messageSize)
+ " bytes, and only got " + buffer.limit());
buffer.position(0);
bytesWeHaveBeenreading = 0;
}
break;
}
// Pop number of read bytes from
if (bytesWeHaveBeenreading > 0) {
// Pop X bytes, and keep message for the rest
int rest = buffer.limit() - bytesWeHaveBeenreading;
if (rest <= 0) {
buffer.clear();
buffer.limit(0);
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenreading);
buffer.get(temp, 0, rest);
buffer.clear();
buffer.limit(rest);
buffer.position(0);
buffer.put(temp, 0, rest);
buffer.position(0);// set position back to start!
}
logger.finest("Did read message of " + bytesWeHaveBeenreading
+ " bytes, new buffer size = " + buffer.limit());
return true; // We did read a message :-)
} else {
if (buffer.limit() > 0) {
logger.finest("did NOT read message from buffer of size = "
+ buffer.limit());
} else {
logger.finest("no messages in empty buffer");
}
return false;
}
}
private void processMessage(int stpType, byte[] payload) throws IOException {
logger.finest("processMessage: " + stpType);
switch (stpType) {
//case 1: //command //commands are not supposed to be received
//throw new WebDriverException("Received command from host?");
case 2: // response
// Log what is being sent.
Response response = Response.parseFrom(payload);
logger.finest("RECV RESPONSE: " + response.toString());
signalResponse(response.getTag(), response);
break;
case 3: // event
Event event = Event.parseFrom(payload);
logger.finest("RECV EVENT: " + event.toString());
signalEvent(event);
break;
case 4: // error
Error error = Error.parseFrom(payload);
logger.finest("RECV ERROR: " + error.toString());
if (error.getService().equals("ecmascript-debugger")
&& error.getStatus() == UmsProtos.Status.INTERNAL_ERROR.getNumber()) {
signalResponse(error.getTag(), null);
} else {
logger.log(Level.SEVERE, "Error : {0}", error.toString());
connectionHandler.onException(new WebDriverException(
"Error on command: " + error.toString()));
}
break;
default:
connectionHandler.onException(new WebDriverException(
"Unhandled STP type: " + stpType));
}
}
// protobuf methods, taken from the protobuf library by Google
// explained: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
private int readRawVarint32(ByteBuffer bytes) {
byte tmp = bytes.get();
if (tmp >= 0) {
return tmp;
}
int result = tmp & 0x7f;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = bytes.get()) << 28;
if (tmp < 0) {
// Discard upper 32 bits.
for (int i = 0; i < 5; i++) {
if (bytes.get() >= 0) {
return result;
}
}
connectionHandler.onException(new WebDriverException(
"Error while reading raw int"));
}
}
}
}
return result;
}
private ByteBuffer encodeMessageSize(int value) {
ByteBuffer buffer = ByteBuffer.allocateDirect(CodedOutputStream.computeRawVarint32Size(value));
while (true) {
if ((value & ~0x7F) == 0) {
buffer.put((byte) (value));
return buffer;
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
}
} | src/com/opera/core/systems/scope/stp/StpConnection.java | /*
Copyright 2008-2011 Opera Software ASA
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.opera.core.systems.scope.stp;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.opera.core.systems.scope.handlers.AbstractEventHandler;
import com.opera.core.systems.scope.handlers.IConnectionHandler;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.scope.protos.UmsProtos;
import com.opera.core.systems.scope.protos.UmsProtos.Command;
import com.opera.core.systems.scope.protos.UmsProtos.Error;
import com.opera.core.systems.scope.protos.UmsProtos.Event;
import com.opera.core.systems.scope.protos.UmsProtos.Response;
import com.opera.core.systems.util.SocketListener;
import com.opera.core.systems.util.SocketMonitor;
import org.openqa.selenium.WebDriverException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StpConnection implements SocketListener {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private SocketChannel socketChannel;
// Outgoing send queue
private final ArrayBlockingQueue<ByteBuffer> requests;
private ByteBuffer recvBuffer;
// For STP1
final byte[] prefix = {'S', 'T', 'P', 1};
private ByteString stpPrefix = ByteString.copyFrom(prefix);
private AbstractEventHandler eventHandler;
private UmsEventParser stp1EventHandler;
private IConnectionHandler connectionHandler;
public enum State {
SERVICELIST, HANDSHAKE, EMPTY, STP;
}
private State state = State.SERVICELIST;
private SocketMonitor monitor;
private void setState(State state) {
// logger.fine("Setting state: " + state.toString());
this.state = state;
}
public boolean isConnected() {
return (socketChannel != null);
}
/*
@Override
public void finalize() throws Throwable {
logger.severe("STPConnection cleanup");
if (socketChannel != null && socketChannel.isOpen()) {
close();
}
super.finalize();
}
*/
/**
* Initializes variables in object scope, sets 'count known' to false to read byte count (STP/0).
*/
public StpConnection(SocketChannel socket, IConnectionHandler handler,
AbstractEventHandler eventHandler, SocketMonitor monitor)
throws IOException {
connectionHandler = handler;
socketChannel = socket;
this.eventHandler = eventHandler;
this.monitor = monitor;
requests = new ArrayBlockingQueue<ByteBuffer>(1024);
recvBuffer = ByteBuffer.allocateDirect(65536);
recvBuffer.limit(0);
socket.configureBlocking(false);
monitor.add(socket, this, SelectionKey.OP_READ);
if (!handler.onConnected(this)) {
close();
throw new IOException(
"Connection not allowed from IConnectionHandler (already connected)");
}
}
private void switchToStp1() {
stp1EventHandler = new UmsEventParser(eventHandler);
sendEnableStp1();
setState(State.HANDSHAKE);
}
/**
* Queues up an STP/1 message sent from another thread and wakes up selector to register it to the
* key.
*
* @param command to add to the request queue
*/
public void send(Command command) {
logger.finest(command.toString());
byte[] payload = command.toByteArray();
int totalSize = payload.length + 1; // increment 1 for message type
ByteBuffer outMessageSize = encodeMessageSize(totalSize);
// create the message
ByteBuffer buffer = ByteBuffer.allocateDirect(prefix.length
+ outMessageSize.position() + 1 + payload.length);
buffer.put(prefix, 0, prefix.length);
outMessageSize.flip();
buffer.put(outMessageSize);
buffer.put((byte) 1);
buffer.put(payload);
// Log what is being sent.
logger.finest("SEND: " + command.toString());
requests.add(buffer);
monitor.modify(socketChannel, this, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public void sendEnableStp1() {
// Temporary fix for CORE-33057
try {
Thread.sleep(OperaIntervals.EXEC_SLEEP.getValue());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
send("*enable stp-1");
}
public void sendQuit() {
send("*quit");
}
/**
* Queues up an STP/0 message sent from another thread and wakes up selector to register it to the
* key.
*
* @param message to add to the request queue
*/
private void send(String message) {
String scopeMessage = message.length() + " " + message;
logger.finest("WRITE : " + scopeMessage);
byte[] bytes = null;
try {
bytes = scopeMessage.getBytes("UTF-16BE");
} catch (UnsupportedEncodingException e) {
close();
connectionHandler.onException(e);
return;
}
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
requests.add(buffer);
monitor.modify(socketChannel, this, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public boolean canRead(SelectableChannel channel) throws IOException {
logger.finest("canRead");
if (!channel.isOpen()) {
return false;
}
if (socketChannel == null) {
throw new IOException(
"We dont have a socket :-)");
}
// Read as much data as possible into buffer.
ByteBuffer readBuffer = ByteBuffer.allocateDirect(1000);
int readSize = 0;
// Continue to read data and read messages until there are no messages
boolean didNotFindAnyMessage = false;
while (!didNotFindAnyMessage) {
logger.finest("canReadLoop!");
// Read as much data as possible (until recvBuffer is full OR we don't get
// any more data)
do {
readBuffer.clear();
try {
// do we have a socket
if (socketChannel == null) {
readSize = -1;
// do we have room in our buffer?
} else {
readSize = socketChannel.read(readBuffer);
if (readSize > 0) {
readBuffer.limit(readSize);
readBuffer.position(0);
}
}
} catch (IOException ex) {
logger.warning("Channel closed, causing exception: " + ex.getMessage());
readSize = -1; // Same as error from socketChannel.read
}
if (readSize < 0) {
try {
logger.log(Level.FINER, "Channel closed: {0}",
socketChannel.socket().getInetAddress().getHostName());
} catch (NullPointerException e) {
// ignore
}
connectionHandler.onDisconnect();
monitor.remove(socketChannel);
return false;
} else if (readSize > 0) {
// Double buffer size if needed!
if (recvBuffer.limit() + readBuffer.limit() >= recvBuffer.capacity()) {
logger.finest("Doubled the size of our recv buffer!");
ByteBuffer newRecvBuffer = ByteBuffer.allocate(recvBuffer.capacity() * 2);
newRecvBuffer.clear();
recvBuffer.position(0);
newRecvBuffer.limit(recvBuffer.limit());
newRecvBuffer.position(0);
newRecvBuffer.put(recvBuffer);
newRecvBuffer.position(0);
recvBuffer = newRecvBuffer;
}
recvBuffer.position(recvBuffer.limit());
recvBuffer.limit(recvBuffer.limit() + readSize);// increase limit!
recvBuffer.put(readBuffer);
logger.finest("did read " + readSize + " bytes, new buffer size = "
+ recvBuffer.limit());
}
} while (readSize > 0);
// Read as many messages as possible, and only
didNotFindAnyMessage = true;
while (readMessage(recvBuffer)) {
didNotFindAnyMessage = false;
}
}
return true;
}
public boolean canWrite(SelectableChannel channel) throws IOException {
logger.finest("canWrite");
if (socketChannel == null) {
throw new IOException("We don't have a socket :-)");
}
int totalWritten = 0;
while (!requests.isEmpty()) {
ByteBuffer buffer = requests.poll();
buffer.flip();
int written = 0;
do {
written = socketChannel.write(buffer);
if (written <= 0) {
break;
}
if (written > 0) {
totalWritten += written;
}
} while (buffer.hasRemaining());
}
logger.finest("Wrote " + totalWritten + " bytes");
return (!requests.isEmpty());
}
/**
* Switches the wait state and wakes up the selector to process.
*/
public void close() {
if (socketChannel == null) {
return;
}
monitor.remove(socketChannel);
try {
socketChannel.close();
} catch (IOException ignored) {
/* nothing to be done */
} finally {
socketChannel = null;
}
}
/**
* Processes an incoming message and passes it to event handler if needed, the following events
* are to our interest: Runtime-Started : ecmascript runtime starts in Opera (that we can inject
* to) Runtime-Stopped : ecmascript runtime stops (not used, buggy) Message: fired from console
* log event Updated-Window: a window is updated OR created (opener-id=0) Active-Window: window
* focus changed Window-Closed: self explanatory If message matches none it is added to the
* response queue (probably response to command).
*/
public void parseServiceList(String message) {
logger.finer("parseServiceList: \"" + message + "\"");
int split = message.indexOf(" ");
if (split < 0) {
connectionHandler.onException(new WebDriverException("Invalid service list received."));
return;
}
List<String> services = Arrays.asList(message.substring(split + 1).split(","));
connectionHandler.onServiceList(services);
logger.fine("Service list ok");
if (!services.contains("stp-1")) {
connectionHandler.onException(new WebDriverException("STP/0 is not supported!"));
return;
}
switchToStp1();
}
private void signalResponse(int tag, Response response) {
connectionHandler.onResponseReceived(tag, response);
}
private void signalEvent(Event event) {
logger.finest("EVENT " + event.toString());
stp1EventHandler.handleEvent(event);
}
/**
* Reads a message from the buffer, and pops the used data out of the buffer.
*
* @param buffer the buffer containing messages
* @return true if we got a message from the buffer
*/
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenreading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenreading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start!
buffer.get(dst);
buffer.position(0);// reset position!
bytesWeHaveBeenreading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Handshake"));
} else {
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
}
break;
case EMPTY: // read 4 byte header: STP\0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenreading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Header"));
}
}
break;
case STP:
// Try to read size
buffer.position(0);
if (buffer.limit() <= 0) {
logger.finest("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenreading = buffer.position();
buffer.position(0);
// If we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenreading + messageSize) {
buffer.position(bytesWeHaveBeenreading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenreading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenreading += messageSize; // 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new WebDriverException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.finest("tried to read a message, but expected " + (4 + messageSize)
+ " bytes, and only got " + buffer.limit());
buffer.position(0);
bytesWeHaveBeenreading = 0;
}
break;
}
// Pop number of read bytes from
if (bytesWeHaveBeenreading > 0) {
// Pop X bytes, and keep message for the rest
int rest = buffer.limit() - bytesWeHaveBeenreading;
if (rest <= 0) {
buffer.clear();
buffer.limit(0);
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenreading);
buffer.get(temp, 0, rest);
buffer.clear();
buffer.limit(rest);
buffer.position(0);
buffer.put(temp, 0, rest);
buffer.position(0);// set position back to start!
}
logger.finest("Did read message of " + bytesWeHaveBeenreading
+ " bytes, new buffer size = " + buffer.limit());
return true; // We did read a message :-)
} else {
if (buffer.limit() > 0) {
logger.finest("did NOT read message from buffer of size = "
+ buffer.limit());
} else {
logger.finest("no messages in empty buffer");
}
return false;
}
}
private void processMessage(int stpType, byte[] payload) throws IOException {
logger.finest("processMessage: " + stpType);
switch (stpType) {
/*
* case 1://command //commands are not supposed to be received
* throw new WebDriverException("Received command from host?");
*/
case 2:// response
// Log what is being sent.
Response response = Response.parseFrom(payload);
logger.finest("RECV RESPONSE: " + response.toString());
signalResponse(response.getTag(), response);
break;
case 3:// event
Event event = Event.parseFrom(payload);
logger.finest("RECV EVENT: " + event.toString());
signalEvent(event);
break;
case 4:// error
Error error = Error.parseFrom(payload);
logger.finest("RECV ERROR: " + error.toString());
if (error.getService().equals("ecmascript-debugger")
&& error.getStatus() == UmsProtos.Status.INTERNAL_ERROR.getNumber()) {
signalResponse(error.getTag(), null);
} else {
logger.log(Level.SEVERE, "Error : {0}", error.toString());
connectionHandler.onException(new WebDriverException(
"Error on command : " + error.toString()));
}
break;
default:
connectionHandler.onException(new WebDriverException(
"Unhandled STP type: " + stpType));
}
}
// protobuf methods, taken from the protobuf library by Google
// explained: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
private int readRawVarint32(ByteBuffer bytes) {
byte tmp = bytes.get();
if (tmp >= 0) {
return tmp;
}
int result = tmp & 0x7f;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = bytes.get()) << 28;
if (tmp < 0) {
// Discard upper 32 bits.
for (int i = 0; i < 5; i++) {
if (bytes.get() >= 0) {
return result;
}
}
connectionHandler.onException(new WebDriverException(
"Error while reading raw int"));
}
}
}
}
return result;
}
private ByteBuffer encodeMessageSize(int value) {
ByteBuffer buffer = ByteBuffer.allocateDirect(CodedOutputStream.computeRawVarint32Size(value));
while (true) {
if ((value & ~0x7F) == 0) {
buffer.put((byte) (value));
return buffer;
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
}
}
| Colon misplaced
| src/com/opera/core/systems/scope/stp/StpConnection.java | Colon misplaced | <ide><path>rc/com/opera/core/systems/scope/stp/StpConnection.java
<ide> logger.finest("processMessage: " + stpType);
<ide>
<ide> switch (stpType) {
<del> /*
<del> * case 1://command //commands are not supposed to be received
<del> * throw new WebDriverException("Received command from host?");
<del> */
<del> case 2:// response
<add> //case 1: //command //commands are not supposed to be received
<add> //throw new WebDriverException("Received command from host?");
<add> case 2: // response
<ide> // Log what is being sent.
<ide> Response response = Response.parseFrom(payload);
<ide> logger.finest("RECV RESPONSE: " + response.toString());
<ide> signalResponse(response.getTag(), response);
<ide> break;
<ide>
<del> case 3:// event
<add> case 3: // event
<ide> Event event = Event.parseFrom(payload);
<ide> logger.finest("RECV EVENT: " + event.toString());
<ide> signalEvent(event);
<ide> break;
<ide>
<del> case 4:// error
<add> case 4: // error
<ide> Error error = Error.parseFrom(payload);
<ide> logger.finest("RECV ERROR: " + error.toString());
<add>
<ide> if (error.getService().equals("ecmascript-debugger")
<ide> && error.getStatus() == UmsProtos.Status.INTERNAL_ERROR.getNumber()) {
<ide> signalResponse(error.getTag(), null);
<ide> } else {
<ide> logger.log(Level.SEVERE, "Error : {0}", error.toString());
<ide> connectionHandler.onException(new WebDriverException(
<del> "Error on command : " + error.toString()));
<del> }
<add> "Error on command: " + error.toString()));
<add> }
<add>
<ide> break;
<ide>
<ide> default: |
|
Java | mit | d15565fb6df01c4605093f992bdf7bb36ed0add8 | 0 | uber/phabricator-jenkins-plugin,liuhaotian/phabricator-jenkins-plugin,jenkinsci/phabricator-plugin,liuhaotian/phabricator-jenkins-plugin,uber/phabricator-jenkins-plugin,jenkinsci/phabricator-plugin | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.uber.jenkins.phabricator;
import com.uber.jenkins.phabricator.conduit.Differential;
import com.uber.jenkins.phabricator.uberalls.UberallsClient;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.plugins.cobertura.CoberturaBuildAction;
import hudson.plugins.cobertura.Ratio;
import hudson.plugins.cobertura.targets.CoverageMetric;
import hudson.plugins.cobertura.targets.CoverageResult;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.*;
import static java.lang.Integer.parseInt;
public class PhabricatorNotifier extends Notifier {
// Post a comment on success. Useful for lengthy builds.
private final boolean commentOnSuccess;
private final boolean uberallsEnabled;
private final boolean commentWithConsoleLinkOnFailure;
private final String commentFile;
private final String commentSize;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public PhabricatorNotifier(boolean commentOnSuccess, boolean uberallsEnabled,
String commentFile, String commentSize, boolean commentWithConsoleLinkOnFailure) {
this.commentOnSuccess = commentOnSuccess;
this.uberallsEnabled = uberallsEnabled;
this.commentFile = commentFile;
this.commentSize = commentSize;
this.commentWithConsoleLinkOnFailure = commentWithConsoleLinkOnFailure;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher,
final BuildListener listener) throws InterruptedException, IOException {
EnvVars environment = build.getEnvironment(listener);
PrintStream logger = listener.getLogger();
CoverageResult coverage = getUberallsCoverage(build, listener);
if (coverage != null) {
coverage.setOwner(build);
}
UberallsClient uberalls = new UberallsClient(getDescriptor().getUberallsURL(), environment, logger);
boolean needsDecoration = environment.get(PhabricatorPlugin.WRAP_KEY, null) == null;
boolean uberallsConfigured = !CommonUtils.isBlank(uberalls.getBaseURL());
String diffID = environment.get(PhabricatorPlugin.DIFFERENTIAL_ID_FIELD);
if (CommonUtils.isBlank(diffID)) {
if (needsDecoration) {
build.addAction(PhabricatorPostbuildAction.createShortText("master", null));
}
if (uberallsEnabled && coverage != null) {
if (!uberallsConfigured) {
logger.println("[uberalls] enabled but no server configured. skipping.");
} else {
String currentSHA = environment.get("GIT_COMMIT");
CodeCoverageMetrics codeCoverageMetrics = new CodeCoverageMetrics(coverage);
if (!CommonUtils.isBlank(currentSHA) && codeCoverageMetrics.isValid()) {
logger.println("[uberalls] sending coverage report for " + currentSHA + " as " +
codeCoverageMetrics.toString());
uberalls.recordCoverage(currentSHA, environment.get("GIT_BRANCH"), codeCoverageMetrics);
} else {
logger.println("[uberalls] no line coverage available for " + currentSHA);
}
}
}
return this.ignoreBuild(logger, "No differential ID found.");
}
LauncherFactory starter = new LauncherFactory(launcher, environment, listener.getLogger(), build.getWorkspace());
Differential diff = Differential.fromDiffID(diffID, starter);
String revisionID = diff.getRevisionID();
if (CommonUtils.isBlank(revisionID)) {
return this.ignoreBuild(logger, "Unable to load revisionID from conduit for diff ID " + diffID);
}
String phid = environment.get(PhabricatorPlugin.PHID_FIELD);
boolean runHarbormaster = phid != null && !"".equals(phid);
boolean harbormasterSuccess = false;
String comment = null;
if (coverage != null) {
Ratio lineCoverage = coverage.getCoverage(CoverageMetric.LINE);
if (lineCoverage == null) {
logger.println("[uberalls] no line coverage found, skipping...");
} else {
if (uberallsConfigured) {
comment = getCoverageComment(lineCoverage, uberalls, diff, logger, environment.get("BUILD_URL"));
} else {
logger.println("[uberalls] no backend configured, skipping...");
}
}
}
if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
harbormasterSuccess = true;
if (comment == null && (this.commentOnSuccess || !runHarbormaster)) {
comment = "Build is green";
}
} else if (build.getResult() == Result.UNSTABLE) {
comment = "Build is unstable";
} else if (build.getResult() == Result.FAILURE) {
// TODO look for message here.
if (!runHarbormaster || this.commentWithConsoleLinkOnFailure) {
comment = "Build has FAILED";
}
} else if (build.getResult() == Result.ABORTED) {
comment = "Build was aborted";
} else {
logger.print("Unknown build status " + build.getResult().toString());
}
String commentAction = "none";
if (runHarbormaster) {
logger.println("Sending build result to Harbormaster with PHID '" + phid + "', success: " + harbormasterSuccess);
diff.harbormaster(phid, harbormasterSuccess);
} else {
logger.println("Harbormaster integration not enabled for this build.");
if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
commentAction = "resign";
} else if (build.getResult().isWorseOrEqualTo(Result.UNSTABLE)) {
commentAction = "reject";
}
}
String customComment;
try {
customComment = getRemoteComment(build, logger, this.commentFile, this.commentSize);
if (!CommonUtils.isBlank(customComment)) {
if (comment == null) {
comment = String.format("```\n%s\n```\n\n", customComment);
} else {
comment = String.format("%s\n\n```\n%s\n```\n", comment, customComment);
}
}
} catch(InterruptedException e) {
e.printStackTrace(logger);
} catch (IOException e) {
Util.displayIOException(e, listener);
}
if (comment != null) {
boolean silent = false;
if (this.commentWithConsoleLinkOnFailure && build.getResult().isWorseOrEqualTo(Result.UNSTABLE)) {
comment += String.format("\n\nLink to build: %s", environment.get("BUILD_URL"));
comment += String.format("\nSee console output for more information: %sconsole", environment.get("BUILD_URL"));
} else {
comment += String.format(" %s for more details.", environment.get("BUILD_URL"));
}
JSONObject result = diff.postComment(comment, silent, commentAction);
if(!(result.get("errorMessage") instanceof JSONNull)) {
logger.println("Get error " + result.get("errorMessage") + " with action " +
commentAction +"; trying again with action 'none'");
diff.postComment(comment, silent, "none");
}
}
return true;
}
private String getCoverageComment(Ratio lineCoverage, UberallsClient uberalls, Differential diff,
PrintStream logger, String buildUrl) {
Float lineCoveragePercent = lineCoverage.getPercentageFloat();
logger.println("[uberalls] line coverage: " + lineCoveragePercent);
logger.println("[uberalls] fetching coverage from " + uberalls.getBaseURL());
CodeCoverageMetrics parentCoverage = uberalls.getParentCoverage(diff);
if (parentCoverage == null) {
logger.println("[uberalls] unable to find coverage for parent commit (" + diff.getBaseCommit() + ")");
return null;
} else {
logger.println("[uberalls] found parent coverage as " + parentCoverage.getLineCoveragePercent());
String coverageComment;
float coverageDelta = lineCoveragePercent - parentCoverage.getLineCoveragePercent();
String coverageDeltaDisplay = String.format("%.3f", coverageDelta);
String lineCoverageDisplay = String.format("%.3f", lineCoveragePercent);
if (coverageDelta > 0) {
coverageComment = "Coverage increased (+" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else if (coverageDelta < 0) {
coverageComment = "Coverage decreased (" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else {
coverageComment = "Coverage remained the same (" + lineCoverageDisplay + "%)";
}
final String coberturaUrl = buildUrl + "cobertura";
coverageComment += " when pulling **" + diff.getBranch() + "** into " +
parentCoverage.getSha1().substring(0, 7) + ". See " + coberturaUrl + " for the coverage report";
return coverageComment;
}
}
/**
* Attempt to read a remote comment file
* @param build the build
* @param logger the logger
* @return the contents of the string
* @throws InterruptedException
*/
private String getRemoteComment(AbstractBuild<?, ?> build, PrintStream logger, String commentFile, String maxSize) throws InterruptedException, IOException {
if (CommonUtils.isBlank(commentFile)) {
logger.println("[comment-file] no comment file configured");
return null;
}
FilePath workspace = build.getWorkspace();
FilePath[] src = workspace.list(commentFile);
if (src.length == 0) {
logger.println("[comment-file] no files found by path: '" + commentFile + "'");
return null;
}
if (src.length > 1) {
logger.println("[comment-file] Found multiple matches. Reading first only.");
}
FilePath source = src[0];
int DEFAULT_COMMENT_SIZE = 1000;
int maxLength = DEFAULT_COMMENT_SIZE;
if (!CommonUtils.isBlank(maxSize)) {
maxLength = parseInt(maxSize, 10);
}
if (source.length() < maxLength) {
maxLength = (int)source.length();
}
byte[] buffer = new byte[maxLength];
source.read().read(buffer, 0, maxLength);
return new String(buffer);
}
private CoverageResult getUberallsCoverage(AbstractBuild<?, ?> build, BuildListener listener) {
if (!build.getResult().isBetterOrEqualTo(Result.UNSTABLE) || !uberallsEnabled) {
return null;
}
PrintStream logger = listener.getLogger();
CoberturaBuildAction coberturaAction = build.getAction(CoberturaBuildAction.class);
if (coberturaAction == null) {
logger.println("[uberalls] no cobertura results found");
return null;
}
return coberturaAction.getResult();
}
/**
* Get the base phabricator URL
* @return a phabricator URL
*/
private String getPhabricatorURL() {
return this.getDescriptor().getConduitURL();
}
private boolean ignoreBuild(PrintStream logger, String message) {
logger.println(message);
logger.println("Skipping Phabricator notification.");
return true;
}
/**
* These are used in the config.jelly file to populate the state of the fields
*/
@SuppressWarnings("UnusedDeclaration")
public boolean isCommentOnSuccess() {
return commentOnSuccess;
}
@SuppressWarnings("UnusedDeclaration")
public boolean isUberallsEnabled() {
return uberallsEnabled;
}
@SuppressWarnings("UnusedDeclaration")
public boolean isCommentWithConsoleLinkOnFailure() {
return commentWithConsoleLinkOnFailure;
}
@SuppressWarnings("UnusedDeclaration")
public String getCommentFile() {
return commentFile;
}
// Overridden for better type safety.
@Override
public PhabricatorNotifierDescriptor getDescriptor() {
return (PhabricatorNotifierDescriptor) super.getDescriptor();
}
}
| src/main/java/com/uber/jenkins/phabricator/PhabricatorNotifier.java | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.uber.jenkins.phabricator;
import com.uber.jenkins.phabricator.conduit.Differential;
import com.uber.jenkins.phabricator.uberalls.UberallsClient;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.plugins.cobertura.CoberturaBuildAction;
import hudson.plugins.cobertura.Ratio;
import hudson.plugins.cobertura.targets.CoverageMetric;
import hudson.plugins.cobertura.targets.CoverageResult;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.*;
import static java.lang.Integer.parseInt;
public class PhabricatorNotifier extends Notifier {
// Post a comment on success. Useful for lengthy builds.
private final boolean commentOnSuccess;
private final boolean uberallsEnabled;
private final boolean commentWithConsoleLinkOnFailure;
private final String commentFile;
private final String commentSize;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public PhabricatorNotifier(boolean commentOnSuccess, boolean uberallsEnabled,
String commentFile, String commentSize, boolean commentWithConsoleLinkOnFailure) {
this.commentOnSuccess = commentOnSuccess;
this.uberallsEnabled = uberallsEnabled;
this.commentFile = commentFile;
this.commentSize = commentSize;
this.commentWithConsoleLinkOnFailure = commentWithConsoleLinkOnFailure;
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher,
final BuildListener listener) throws InterruptedException, IOException {
EnvVars environment = build.getEnvironment(listener);
PrintStream logger = listener.getLogger();
if (environment == null) {
return this.ignoreBuild(logger, "No environment variables found?!");
}
CoverageResult coverage = getUberallsCoverage(build, listener);
if (coverage != null) {
coverage.setOwner(build);
}
UberallsClient uberalls = new UberallsClient(getDescriptor().getUberallsURL(), environment, logger);
boolean needsDecoration = environment.get(PhabricatorPlugin.WRAP_KEY, null) == null;
boolean uberallsConfigured = !CommonUtils.isBlank(uberalls.getBaseURL());
String diffID = environment.get(PhabricatorPlugin.DIFFERENTIAL_ID_FIELD);
if (CommonUtils.isBlank(diffID)) {
if (needsDecoration) {
build.addAction(PhabricatorPostbuildAction.createShortText("master", null));
}
if (uberallsEnabled && coverage != null) {
if (!uberallsConfigured) {
logger.println("[uberalls] enabled but no server configured. skipping.");
} else {
String currentSHA = environment.get("GIT_COMMIT");
CodeCoverageMetrics codeCoverageMetrics = new CodeCoverageMetrics(coverage);
if (!CommonUtils.isBlank(currentSHA) && codeCoverageMetrics.isValid()) {
logger.println("[uberalls] sending coverage report for " + currentSHA + " as " +
codeCoverageMetrics.toString());
uberalls.recordCoverage(currentSHA, environment.get("GIT_BRANCH"), codeCoverageMetrics);
} else {
logger.println("[uberalls] no line coverage available for " + currentSHA);
}
}
}
return this.ignoreBuild(logger, "No differential ID found.");
}
LauncherFactory starter = new LauncherFactory(launcher, environment, listener.getLogger(), build.getWorkspace());
Differential diff = Differential.fromDiffID(diffID, starter);
String revisionID = diff.getRevisionID();
if (CommonUtils.isBlank(revisionID)) {
return this.ignoreBuild(logger, "Unable to load revisionID from conduit for diff ID " + diffID);
}
if (needsDecoration) {
diff.decorate(build, this.getPhabricatorURL());
}
String phid = environment.get(PhabricatorPlugin.PHID_FIELD);
boolean runHarbormaster = phid != null && !"".equals(phid);
boolean harbormasterSuccess = false;
String comment = null;
if (coverage != null) {
Ratio lineCoverage = coverage.getCoverage(CoverageMetric.LINE);
if (lineCoverage == null) {
logger.println("[uberalls] no line coverage found, skipping...");
} else {
if (uberallsConfigured) {
comment = getCoverageComment(lineCoverage, uberalls, diff, logger, environment.get("BUILD_URL"));
} else {
logger.println("[uberalls] no backend configured, skipping...");
}
}
}
if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
harbormasterSuccess = true;
if (comment == null && (this.commentOnSuccess || !runHarbormaster)) {
comment = "Build is green";
}
} else if (build.getResult() == Result.UNSTABLE) {
comment = "Build is unstable";
} else if (build.getResult() == Result.FAILURE) {
// TODO look for message here.
if (!runHarbormaster || this.commentWithConsoleLinkOnFailure) {
comment = "Build has FAILED";
}
} else if (build.getResult() == Result.ABORTED) {
comment = "Build was aborted";
} else {
logger.print("Unknown build status " + build.getResult().toString());
}
String commentAction = "none";
if (runHarbormaster) {
logger.println("Sending build result to Harbormaster with PHID '" + phid + "', success: " + harbormasterSuccess);
diff.harbormaster(phid, harbormasterSuccess);
} else {
logger.println("Harbormaster integration not enabled for this build.");
if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
commentAction = "resign";
} else if (build.getResult().isWorseOrEqualTo(Result.UNSTABLE)) {
commentAction = "reject";
}
}
String customComment;
try {
customComment = getRemoteComment(build, logger, this.commentFile, this.commentSize);
if (!CommonUtils.isBlank(customComment)) {
if (comment == null) {
comment = String.format("```\n%s\n```\n\n", customComment);
} else {
comment = String.format("%s\n\n```\n%s\n```\n", comment, customComment);
}
}
} catch(InterruptedException e) {
e.printStackTrace(logger);
} catch (IOException e) {
Util.displayIOException(e, listener);
}
if (comment != null) {
boolean silent = false;
if (this.commentWithConsoleLinkOnFailure && build.getResult().isWorseOrEqualTo(Result.UNSTABLE)) {
comment += String.format("\n\nLink to build: %s", environment.get("BUILD_URL"));
comment += String.format("\nSee console output for more information: %sconsole", environment.get("BUILD_URL"));
} else {
comment += String.format(" %s for more details.", environment.get("BUILD_URL"));
}
JSONObject result = diff.postComment(comment, silent, commentAction);
if(!(result.get("errorMessage") instanceof JSONNull)) {
logger.println("Get error " + result.get("errorMessage") + " with action " +
commentAction +"; trying again with action 'none'");
diff.postComment(comment, silent, "none");
}
}
return true;
}
private String getCoverageComment(Ratio lineCoverage, UberallsClient uberalls, Differential diff,
PrintStream logger, String buildUrl) {
Float lineCoveragePercent = lineCoverage.getPercentageFloat();
logger.println("[uberalls] line coverage: " + lineCoveragePercent);
logger.println("[uberalls] fetching coverage from " + uberalls.getBaseURL());
CodeCoverageMetrics parentCoverage = uberalls.getParentCoverage(diff);
if (parentCoverage == null) {
logger.println("[uberalls] unable to find coverage for parent commit (" + diff.getBaseCommit() + ")");
return null;
} else {
logger.println("[uberalls] found parent coverage as " + parentCoverage.getLineCoveragePercent());
String coverageComment;
float coverageDelta = lineCoveragePercent - parentCoverage.getLineCoveragePercent();
String coverageDeltaDisplay = String.format("%.3f", coverageDelta);
String lineCoverageDisplay = String.format("%.3f", lineCoveragePercent);
if (coverageDelta > 0) {
coverageComment = "Coverage increased (+" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else if (coverageDelta < 0) {
coverageComment = "Coverage decreased (" + coverageDeltaDisplay + "%) to " + lineCoverageDisplay + "%";
} else {
coverageComment = "Coverage remained the same (" + lineCoverageDisplay + "%)";
}
final String coberturaUrl = buildUrl + "cobertura";
coverageComment += " when pulling **" + diff.getBranch() + "** into " +
parentCoverage.getSha1().substring(0, 7) + ". See " + coberturaUrl + " for the coverage report";
return coverageComment;
}
}
/**
* Attempt to read a remote comment file
* @param build the build
* @param logger the logger
* @return the contents of the string
* @throws InterruptedException
*/
private String getRemoteComment(AbstractBuild<?, ?> build, PrintStream logger, String commentFile, String maxSize) throws InterruptedException, IOException {
if (CommonUtils.isBlank(commentFile)) {
logger.println("[comment-file] no comment file configured");
return null;
}
FilePath workspace = build.getWorkspace();
FilePath[] src = workspace.list(commentFile);
if (src.length == 0) {
logger.println("[comment-file] no files found by path: '" + commentFile + "'");
return null;
}
if (src.length > 1) {
logger.println("[comment-file] Found multiple matches. Reading first only.");
}
FilePath source = src[0];
int DEFAULT_COMMENT_SIZE = 1000;
int maxLength = DEFAULT_COMMENT_SIZE;
if (!CommonUtils.isBlank(maxSize)) {
maxLength = parseInt(maxSize, 10);
}
if (source.length() < maxLength) {
maxLength = (int)source.length();
}
byte[] buffer = new byte[maxLength];
source.read().read(buffer, 0, maxLength);
return new String(buffer);
}
private CoverageResult getUberallsCoverage(AbstractBuild<?, ?> build, BuildListener listener) {
if (!build.getResult().isBetterOrEqualTo(Result.UNSTABLE) || !uberallsEnabled) {
return null;
}
PrintStream logger = listener.getLogger();
CoberturaBuildAction coberturaAction = build.getAction(CoberturaBuildAction.class);
if (coberturaAction == null) {
logger.println("[uberalls] no cobertura results found");
return null;
}
return coberturaAction.getResult();
}
/**
* Get the base phabricator URL
* @return a phabricator URL
*/
private String getPhabricatorURL() {
return this.getDescriptor().getConduitURL();
}
private boolean ignoreBuild(PrintStream logger, String message) {
logger.println(message);
logger.println("Skipping Phabricator notification.");
return true;
}
/**
* These are used in the config.jelly file to populate the state of the fields
*/
@SuppressWarnings("UnusedDeclaration")
public boolean isCommentOnSuccess() {
return commentOnSuccess;
}
@SuppressWarnings("UnusedDeclaration")
public boolean isUberallsEnabled() {
return uberallsEnabled;
}
@SuppressWarnings("UnusedDeclaration")
public boolean isCommentWithConsoleLinkOnFailure() {
return commentWithConsoleLinkOnFailure;
}
@SuppressWarnings("UnusedDeclaration")
public String getCommentFile() {
return commentFile;
}
// Overridden for better type safety.
@Override
public PhabricatorNotifierDescriptor getDescriptor() {
return (PhabricatorNotifierDescriptor) super.getDescriptor();
}
}
| Remove some unused code
| src/main/java/com/uber/jenkins/phabricator/PhabricatorNotifier.java | Remove some unused code | <ide><path>rc/main/java/com/uber/jenkins/phabricator/PhabricatorNotifier.java
<ide> final BuildListener listener) throws InterruptedException, IOException {
<ide> EnvVars environment = build.getEnvironment(listener);
<ide> PrintStream logger = listener.getLogger();
<del> if (environment == null) {
<del> return this.ignoreBuild(logger, "No environment variables found?!");
<del> }
<ide>
<ide> CoverageResult coverage = getUberallsCoverage(build, listener);
<ide> if (coverage != null) {
<ide> String revisionID = diff.getRevisionID();
<ide> if (CommonUtils.isBlank(revisionID)) {
<ide> return this.ignoreBuild(logger, "Unable to load revisionID from conduit for diff ID " + diffID);
<del> }
<del>
<del> if (needsDecoration) {
<del> diff.decorate(build, this.getPhabricatorURL());
<ide> }
<ide>
<ide> String phid = environment.get(PhabricatorPlugin.PHID_FIELD); |
|
Java | lgpl-2.1 | f28e4dd5ec43a581e0cb580e537f08f5cbf44341 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.ctl.extensions;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jetel.ctl.Stack;
import org.jetel.ctl.data.TLType;
import org.jetel.ctl.data.TLType.TLTypeList;
import org.jetel.data.DataRecord;
public class ContainerLib extends TLFunctionLibrary {
@Override
public TLFunctionPrototype getExecutable(String functionName)
throws IllegalArgumentException {
TLFunctionPrototype ret =
"clear".equals(functionName) ? new ClearFunction() :
"pop".equals(functionName) ? new PopFunction() :
"poll".equals(functionName) ? new PollFunction() :
"push".equals(functionName) ? new PushFunction() :
"append".equals(functionName) ? new AppendFunction() :
"insert".equals(functionName) ? new InsertFunction() :
"remove".equals(functionName) ? new RemoveFunction() :
"sort".equals(functionName) ? new SortFunction() :
"reverse".equals(functionName) ? new ReverseFunction() :
"isEmpty".equals(functionName) ? new IsEmptyFunction() :
"copy".equals(functionName) ? new CopyFunction() :
"containsAll".equals(functionName) ? new ContainsAllFunction() :
"containsKey".equals(functionName) ? new ContainsKeyFunction() :
"containsValue".equals(functionName) ? new ContainsValueFunction() :
// "binarySearch".equals(functionName) ? new BinarySearchFunction() :
"getKeys".equals(functionName) ? new GetKeysFunction() :
"getValues".equals(functionName) ? new GetValuesFunction() :
"toMap".equals(functionName) ? new ToMapFunction() : null;
if (ret == null) {
throw new IllegalArgumentException("Unknown function '" + functionName + "'");
}
return ret;
}
private static String LIBRARY_NAME = "Container";
@Override
public String getName() {
return LIBRARY_NAME;
}
// CLEAR
@TLFunctionAnnotation("Removes all elements from a list")
public static final <E> void clear(TLFunctionCallContext context, List<E> list) {
list.clear();
}
@TLFunctionAnnotation("Removes all elements from a map")
public static final <K,V> void clear(TLFunctionCallContext context, Map<K,V> map) {
map.clear();
}
class ClearFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
clear(context, stack.popList());
} else {
clear(context, stack.popMap());
}
}
}
// POP
@TLFunctionAnnotation("Removes last element from a list and returns it.")
public static final <E> E pop(TLFunctionCallContext context, List<E> list) {
return list.size() > 0 ? list.remove(list.size()-1) : null;
}
class PopFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(pop(context, stack.popList()));
}
}
// POLL
@TLFunctionAnnotation("Removes first element from a list and returns it.")
public static final <E> E poll(TLFunctionCallContext context, List<E> list) {
return list.size() > 0 ? list.remove(0) : null;
}
class PollFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(poll(context, stack.popList()));
}
}
// APPEND
@TLFunctionAnnotation("Appends element at the end of the list.")
public static final <E> List<E> append(TLFunctionCallContext context, List<E> list, E item) {
list.add(item);
return list;
}
class AppendFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Object item = stack.pop();
final List<Object> list = stack.popList();
stack.push(append(context, list, item));
}
}
// PUSH
@TLFunctionAnnotation("Appends element at the end of the list.")
public static final <E> List<E> push(TLFunctionCallContext context, List<E> list, E item) {
list.add(item);
return list;
}
class PushFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Object item = stack.pop();
final List<Object> list = stack.popList();
stack.push(push(context, list, item));
}
}
// INSERT
@TLFunctionAnnotation("Inserts elements at the specified index.")
public static final <E> List<E> insert(TLFunctionCallContext context, List<E> list, int position, E... items) {
for (int i = 0; i < items.length; i++) {
list.add(position++, items[i]);
}
return list;
}
@TLFunctionAnnotation("Inserts elements at the specified index.")
public static final <E> List<E> insert(TLFunctionCallContext context, List<E> list, int position, List<E> items) {
for (int i = 0; i < items.size(); i++) {
list.add(position++, items.get(i));
}
return list;
}
class InsertFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[2].isList()) {
List<Object> items = stack.popList();
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(insert(context, list, pos, items));
} else {
Object[] items = new Object[context.getParams().length - 2];
for (int i = items.length - 1; i >= 0; i--) {
items[i] = stack.pop();
}
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(insert(context, list, pos, items));
}
}
}
// REMOVE
@TLFunctionAnnotation("Removes element at the specified index and returns it.")
public static final <E> E remove(TLFunctionCallContext context, List<E> list, int position) {
return list.remove(position);
}
class RemoveFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(remove(context, list, pos));
}
}
private static class MyComparator<T extends Comparable<T>> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}
};
// all CTL types are comparable so this will work in runtime
@TLFunctionAnnotation("Sorts elements contained in list - ascending order.")
public static final <E extends Comparable<E>> List<E> sort(TLFunctionCallContext context, List<E> list) {
Collections.sort(list, new MyComparator<E>());
return list;
}
class SortFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
@SuppressWarnings("unchecked")
public void execute(Stack stack, TLFunctionCallContext context) {
List<Object> orig = (List<Object>)stack.peek();
TLType elem = ((TLTypeList)context.getParams()[0]).getElementType();
List<?> s = null;
if (elem.isString()) {
s = sort(context, TLFunctionLibrary.<String>convertTo(orig));
} else if (elem.isInteger()) {
s = sort(context, TLFunctionLibrary.<Integer>convertTo(orig));
} else if (elem.isLong()) {
s = sort(context, TLFunctionLibrary.<Long>convertTo(orig));
} else if (elem.isDouble()) {
s = sort(context, TLFunctionLibrary.<Double>convertTo(orig));
} else if (elem.isDecimal()) {
s = sort(context, TLFunctionLibrary.<BigDecimal>convertTo(orig));
} else if (elem.isBoolean()) {
s = sort(context, TLFunctionLibrary.<Boolean>convertTo(orig));
} else if (elem.isDate()) {
s = sort(context, TLFunctionLibrary.<Date>convertTo(orig));
} else {
throw new IllegalArgumentException("Unknown type for sort: '" + elem.name() + "'");
}
orig.clear();
orig.addAll(s);
}
}
// all CTL types are comparable so this will work in runtime
@TLFunctionAnnotation("Inverts order of elements within a list.")
public static final <E> List<E> reverse(TLFunctionCallContext context, List<E> list) {
Collections.reverse(list);
return list;
}
// REVERSE
class ReverseFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
@SuppressWarnings("unchecked")
public void execute(Stack stack, TLFunctionCallContext context) {
List<Object> orig = (List<Object>)stack.peek();
TLType elem = ((TLTypeList)context.getParams()[0]).getElementType();
List<?> s = null;
if (elem.isString()) {
s = reverse(context, TLFunctionLibrary.<String>convertTo(orig));
} else if (elem.isInteger()) {
s = reverse(context, TLFunctionLibrary.<Integer>convertTo(orig));
} else if (elem.isLong()) {
s = reverse(context, TLFunctionLibrary.<Long>convertTo(orig));
} else if (elem.isDouble()) {
s = reverse(context, TLFunctionLibrary.<Double>convertTo(orig));
} else if (elem.isDecimal()) {
s = reverse(context, TLFunctionLibrary.<BigDecimal>convertTo(orig));
} else if (elem.isBoolean()) {
s = reverse(context, TLFunctionLibrary.<Boolean>convertTo(orig));
} else if (elem.isDate()) {
s = reverse(context, TLFunctionLibrary.<Date>convertTo(orig));
} else if (elem.isRecord()) {
s = reverse(context, TLFunctionLibrary.<DataRecord>convertTo(orig));
} else {
throw new IllegalArgumentException("Unknown type for reverse: '" + elem.name() + "'");
}
orig.clear();
orig.addAll(s);
}
}
// ISEMPTY
@TLFunctionAnnotation("Checks if list is empty.")
public static final <E> Boolean isEmpty(TLFunctionCallContext context, List<E> list) {
return list.isEmpty();
}
@TLFunctionAnnotation("Checks if map is empty.")
public static final <K, V> Boolean isEmpty(TLFunctionCallContext context, Map<K, V> map) {
return map.isEmpty();
}
class IsEmptyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
stack.push(isEmpty(context, stack.popMap()));
} else {
stack.push(isEmpty(context, stack.popList()));
}
}
}
// COPY
@TLFunctionAnnotation("Adds all elements from second argument into the first argument. Returns the first argument")
public static final <E> List<E> copy(TLFunctionCallContext context, List<E> to, List<E> from) {
to.addAll(from);
return to;
}
@TLFunctionAnnotation("Adds all elements from second argument into the first argument, replacing existing key mappings. Returns the first argument")
public static final <K,V> Map<K,V> copy(TLFunctionCallContext context, Map<K,V> to, Map<K,V> from) {
to.putAll(from);
return to;
}
class CopyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
List<Object> from = stack.popList();
List<Object> to = stack.popList();
stack.push(copy(context, to,from));
}
if (context.getParams()[0].isMap()) {
Map<Object,Object> from = stack.popMap();
Map<Object,Object> to = stack.popMap();
stack.push(copy(context, to,from));
}
}
}
@TLFunctionAnnotation("Checks if a list contains all elements from another list.")
public static final <E> boolean containsAll(TLFunctionCallContext context, List<E> collection, List<E> subList) {
return collection.containsAll(subList);
}
class ContainsAllFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
List<Object> subList = stack.popList();
List<Object> list = stack.popList();
stack.push(containsAll(context, list, subList));
}
}
}
@TLFunctionAnnotation("Checks if a map contains a specified key.")
public static final <K, V> boolean containsKey(TLFunctionCallContext context, Map<K, V> map, K key) {
return map.containsKey(key);
}
class ContainsKeyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Object key = stack.pop();
Map<Object, Object> map = stack.popMap();
stack.push(containsKey(context, map, key));
}
}
}
@TLFunctionAnnotation("Checks if a map contains a specified value.")
public static final <K, V> boolean containsValue(TLFunctionCallContext context, Map<K, V> map, V value) {
return map.containsValue(value);
}
@TLFunctionAnnotation("Checks if a list contains a specified value.")
public static final <V> boolean containsValue(TLFunctionCallContext context, List<V> list, V value) {
return list.contains(value);
}
class ContainsValueFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
TLType type=context.getParams()[0];
if (type.isMap()) {
Object value = stack.pop();
Map<Object, Object> map = stack.popMap();
stack.push(containsValue(context, map, value));
}else if (type.isList()){
Object value = stack.pop();
List<Object> list = stack.popList();
stack.push(containsValue(context, list, value));
}
}
}
// @SuppressWarnings("unchecked")
// @TLFunctionAnnotation("Searches a list for the specified value. The list must be sorted in ascending order.")
// public static final <V> Integer binarySearch(TLFunctionCallContext context, List<V> list, V value) {
// return Collections.binarySearch(((List<? extends Comparable<? super V>>) list), value);
// }
//
// class BinarySearchFunction implements TLFunctionPrototype{
//
// @Override
// public void init(TLFunctionCallContext context) {
// }
//
// @Override
// public void execute(Stack stack, TLFunctionCallContext context) {
// Object value = stack.pop();
// List<Object> list = stack.popList();
// stack.push(binarySearch(context, list, value));
// }
// }
@TLFunctionAnnotation("Returns the keys of the map.")
public static final <K, V> List<K> getKeys(TLFunctionCallContext context, Map<K, V> map) {
return new ArrayList<K>(map.keySet());
}
class GetKeysFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Map<Object, Object> map = stack.popMap();
stack.push(getKeys(context, map));
}
}
}
@TLFunctionAnnotation("Returns the values of the map.")
public static final <K, V> List<V> getValues(TLFunctionCallContext context, Map<K, V> map) {
return new ArrayList<V>(map.values());
}
class GetValuesFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Map<Object, Object> map = stack.popMap();
stack.push(getValues(context, map));
}
}
}
@TLFunctionAnnotation("Converts input list to map where list items become map's keys, all values are the same constant.")
public static final <K, V> Map<K,V> toMap(TLFunctionCallContext context, List<K> keys, V constant) {
Map <K,V> map = new HashMap<K,V>(keys.size());
for(K key: keys){
map.put(key, constant);
}
return map;
}
@TLFunctionAnnotation("Converts two input lists to map where first list items become map's keys and second list corresponding values.")
public static final <K, V> Map<K,V> toMap(TLFunctionCallContext context, List<K> keys, List<V> values) {
Map <K,V> map = new HashMap<K,V>(keys.size());
Iterator<V> iter = values.iterator();
if (keys.size()!=values.size()){
throw new IllegalArgumentException("Keys list does not match values list in size.");
}
for(K key: keys){
map.put(key, iter.next());
}
return map;
}
class ToMapFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[1].isList()) {
List<Object> values = stack.popList();
stack.push(toMap(context, stack.popList(), values));
}else{
Object constant = stack.pop();
stack.push(toMap(context, stack.popList(), constant));
}
}
}
}
| cloveretl.ctlfunction/src/org/jetel/ctl/extensions/ContainerLib.java | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.ctl.extensions;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jetel.ctl.Stack;
import org.jetel.ctl.data.TLType;
import org.jetel.ctl.data.TLType.TLTypeList;
import org.jetel.data.DataRecord;
public class ContainerLib extends TLFunctionLibrary {
@Override
public TLFunctionPrototype getExecutable(String functionName)
throws IllegalArgumentException {
TLFunctionPrototype ret =
"clear".equals(functionName) ? new ClearFunction() :
"pop".equals(functionName) ? new PopFunction() :
"poll".equals(functionName) ? new PollFunction() :
"push".equals(functionName) ? new PushFunction() :
"append".equals(functionName) ? new AppendFunction() :
"insert".equals(functionName) ? new InsertFunction() :
"remove".equals(functionName) ? new RemoveFunction() :
"sort".equals(functionName) ? new SortFunction() :
"reverse".equals(functionName) ? new ReverseFunction() :
"isEmpty".equals(functionName) ? new IsEmptyFunction() :
"copy".equals(functionName) ? new CopyFunction() :
"containsAll".equals(functionName) ? new ContainsAllFunction() :
"containsKey".equals(functionName) ? new ContainsKeyFunction() :
"containsValue".equals(functionName) ? new ContainsValueFunction() :
"binarySearch".equals(functionName) ? new BinarySearchFunction() :
"getKeys".equals(functionName) ? new GetKeysFunction() :
"getValues".equals(functionName) ? new GetValuesFunction() :
"toMap".equals(functionName) ? new ToMapFunction() : null;
if (ret == null) {
throw new IllegalArgumentException("Unknown function '" + functionName + "'");
}
return ret;
}
private static String LIBRARY_NAME = "Container";
@Override
public String getName() {
return LIBRARY_NAME;
}
// CLEAR
@TLFunctionAnnotation("Removes all elements from a list")
public static final <E> void clear(TLFunctionCallContext context, List<E> list) {
list.clear();
}
@TLFunctionAnnotation("Removes all elements from a map")
public static final <K,V> void clear(TLFunctionCallContext context, Map<K,V> map) {
map.clear();
}
class ClearFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
clear(context, stack.popList());
} else {
clear(context, stack.popMap());
}
}
}
// POP
@TLFunctionAnnotation("Removes last element from a list and returns it.")
public static final <E> E pop(TLFunctionCallContext context, List<E> list) {
return list.size() > 0 ? list.remove(list.size()-1) : null;
}
class PopFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(pop(context, stack.popList()));
}
}
// POLL
@TLFunctionAnnotation("Removes first element from a list and returns it.")
public static final <E> E poll(TLFunctionCallContext context, List<E> list) {
return list.size() > 0 ? list.remove(0) : null;
}
class PollFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
stack.push(poll(context, stack.popList()));
}
}
// APPEND
@TLFunctionAnnotation("Appends element at the end of the list.")
public static final <E> List<E> append(TLFunctionCallContext context, List<E> list, E item) {
list.add(item);
return list;
}
class AppendFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Object item = stack.pop();
final List<Object> list = stack.popList();
stack.push(append(context, list, item));
}
}
// PUSH
@TLFunctionAnnotation("Appends element at the end of the list.")
public static final <E> List<E> push(TLFunctionCallContext context, List<E> list, E item) {
list.add(item);
return list;
}
class PushFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Object item = stack.pop();
final List<Object> list = stack.popList();
stack.push(push(context, list, item));
}
}
// INSERT
@TLFunctionAnnotation("Inserts elements at the specified index.")
public static final <E> List<E> insert(TLFunctionCallContext context, List<E> list, int position, E... items) {
for (int i = 0; i < items.length; i++) {
list.add(position++, items[i]);
}
return list;
}
@TLFunctionAnnotation("Inserts elements at the specified index.")
public static final <E> List<E> insert(TLFunctionCallContext context, List<E> list, int position, List<E> items) {
for (int i = 0; i < items.size(); i++) {
list.add(position++, items.get(i));
}
return list;
}
class InsertFunction implements TLFunctionPrototype {
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[2].isList()) {
List<Object> items = stack.popList();
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(insert(context, list, pos, items));
} else {
Object[] items = new Object[context.getParams().length - 2];
for (int i = items.length - 1; i >= 0; i--) {
items[i] = stack.pop();
}
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(insert(context, list, pos, items));
}
}
}
// REMOVE
@TLFunctionAnnotation("Removes element at the specified index and returns it.")
public static final <E> E remove(TLFunctionCallContext context, List<E> list, int position) {
return list.remove(position);
}
class RemoveFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
final Integer pos = stack.popInt();
final List<Object> list = stack.popList();
stack.push(remove(context, list, pos));
}
}
private static class MyComparator<T extends Comparable<T>> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}
};
// all CTL types are comparable so this will work in runtime
@TLFunctionAnnotation("Sorts elements contained in list - ascending order.")
public static final <E extends Comparable<E>> List<E> sort(TLFunctionCallContext context, List<E> list) {
Collections.sort(list, new MyComparator<E>());
return list;
}
class SortFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
@SuppressWarnings("unchecked")
public void execute(Stack stack, TLFunctionCallContext context) {
List<Object> orig = (List<Object>)stack.peek();
TLType elem = ((TLTypeList)context.getParams()[0]).getElementType();
List<?> s = null;
if (elem.isString()) {
s = sort(context, TLFunctionLibrary.<String>convertTo(orig));
} else if (elem.isInteger()) {
s = sort(context, TLFunctionLibrary.<Integer>convertTo(orig));
} else if (elem.isLong()) {
s = sort(context, TLFunctionLibrary.<Long>convertTo(orig));
} else if (elem.isDouble()) {
s = sort(context, TLFunctionLibrary.<Double>convertTo(orig));
} else if (elem.isDecimal()) {
s = sort(context, TLFunctionLibrary.<BigDecimal>convertTo(orig));
} else if (elem.isBoolean()) {
s = sort(context, TLFunctionLibrary.<Boolean>convertTo(orig));
} else if (elem.isDate()) {
s = sort(context, TLFunctionLibrary.<Date>convertTo(orig));
} else {
throw new IllegalArgumentException("Unknown type for sort: '" + elem.name() + "'");
}
orig.clear();
orig.addAll(s);
}
}
// all CTL types are comparable so this will work in runtime
@TLFunctionAnnotation("Inverts order of elements within a list.")
public static final <E> List<E> reverse(TLFunctionCallContext context, List<E> list) {
Collections.reverse(list);
return list;
}
// REVERSE
class ReverseFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
@SuppressWarnings("unchecked")
public void execute(Stack stack, TLFunctionCallContext context) {
List<Object> orig = (List<Object>)stack.peek();
TLType elem = ((TLTypeList)context.getParams()[0]).getElementType();
List<?> s = null;
if (elem.isString()) {
s = reverse(context, TLFunctionLibrary.<String>convertTo(orig));
} else if (elem.isInteger()) {
s = reverse(context, TLFunctionLibrary.<Integer>convertTo(orig));
} else if (elem.isLong()) {
s = reverse(context, TLFunctionLibrary.<Long>convertTo(orig));
} else if (elem.isDouble()) {
s = reverse(context, TLFunctionLibrary.<Double>convertTo(orig));
} else if (elem.isDecimal()) {
s = reverse(context, TLFunctionLibrary.<BigDecimal>convertTo(orig));
} else if (elem.isBoolean()) {
s = reverse(context, TLFunctionLibrary.<Boolean>convertTo(orig));
} else if (elem.isDate()) {
s = reverse(context, TLFunctionLibrary.<Date>convertTo(orig));
} else if (elem.isRecord()) {
s = reverse(context, TLFunctionLibrary.<DataRecord>convertTo(orig));
} else {
throw new IllegalArgumentException("Unknown type for reverse: '" + elem.name() + "'");
}
orig.clear();
orig.addAll(s);
}
}
// ISEMPTY
@TLFunctionAnnotation("Checks if list is empty.")
public static final <E> Boolean isEmpty(TLFunctionCallContext context, List<E> list) {
return list.isEmpty();
}
@TLFunctionAnnotation("Checks if map is empty.")
public static final <K, V> Boolean isEmpty(TLFunctionCallContext context, Map<K, V> map) {
return map.isEmpty();
}
class IsEmptyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
stack.push(isEmpty(context, stack.popMap()));
} else {
stack.push(isEmpty(context, stack.popList()));
}
}
}
// COPY
@TLFunctionAnnotation("Adds all elements from second argument into the first argument. Returns the first argument")
public static final <E> List<E> copy(TLFunctionCallContext context, List<E> to, List<E> from) {
to.addAll(from);
return to;
}
@TLFunctionAnnotation("Adds all elements from second argument into the first argument, replacing existing key mappings. Returns the first argument")
public static final <K,V> Map<K,V> copy(TLFunctionCallContext context, Map<K,V> to, Map<K,V> from) {
to.putAll(from);
return to;
}
class CopyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
List<Object> from = stack.popList();
List<Object> to = stack.popList();
stack.push(copy(context, to,from));
}
if (context.getParams()[0].isMap()) {
Map<Object,Object> from = stack.popMap();
Map<Object,Object> to = stack.popMap();
stack.push(copy(context, to,from));
}
}
}
@TLFunctionAnnotation("Checks if a list contains all elements from another list.")
public static final <E> boolean containsAll(TLFunctionCallContext context, List<E> collection, List<E> subList) {
return collection.containsAll(subList);
}
class ContainsAllFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isList()) {
List<Object> subList = stack.popList();
List<Object> list = stack.popList();
stack.push(containsAll(context, list, subList));
}
}
}
@TLFunctionAnnotation("Checks if a map contains a specified key.")
public static final <K, V> boolean containsKey(TLFunctionCallContext context, Map<K, V> map, K key) {
return map.containsKey(key);
}
class ContainsKeyFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Object key = stack.pop();
Map<Object, Object> map = stack.popMap();
stack.push(containsKey(context, map, key));
}
}
}
@TLFunctionAnnotation("Checks if a map contains a specified value.")
public static final <K, V> boolean containsValue(TLFunctionCallContext context, Map<K, V> map, V value) {
return map.containsValue(value);
}
@TLFunctionAnnotation("Checks if a list contains a specified value.")
public static final <V> boolean containsValue(TLFunctionCallContext context, List<V> list, V value) {
return list.contains(value);
}
class ContainsValueFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
TLType type=context.getParams()[0];
if (type.isMap()) {
Object value = stack.pop();
Map<Object, Object> map = stack.popMap();
stack.push(containsValue(context, map, value));
}else if (type.isList()){
Object value = stack.pop();
List<Object> list = stack.popList();
stack.push(containsValue(context, list, value));
}
}
}
@SuppressWarnings("unchecked")
@TLFunctionAnnotation("Searches a list for the specified value. The list must be sorted in ascending order.")
public static final <V> Integer binarySearch(TLFunctionCallContext context, List<V> list, V value) {
return Collections.binarySearch(((List<? extends Comparable<? super V>>) list), value);
}
class BinarySearchFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
Object value = stack.pop();
List<Object> list = stack.popList();
stack.push(binarySearch(context, list, value));
}
}
@TLFunctionAnnotation("Returns the keys of the map.")
public static final <K, V> List<K> getKeys(TLFunctionCallContext context, Map<K, V> map) {
return new ArrayList<K>(map.keySet());
}
class GetKeysFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Map<Object, Object> map = stack.popMap();
stack.push(getKeys(context, map));
}
}
}
@TLFunctionAnnotation("Returns the values of the map.")
public static final <K, V> List<V> getValues(TLFunctionCallContext context, Map<K, V> map) {
return new ArrayList<V>(map.values());
}
class GetValuesFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[0].isMap()) {
Map<Object, Object> map = stack.popMap();
stack.push(getValues(context, map));
}
}
}
@TLFunctionAnnotation("Converts input list to map where list items become map's keys, all values are the same constant.")
public static final <K, V> Map<K,V> toMap(TLFunctionCallContext context, List<K> keys, V constant) {
Map <K,V> map = new HashMap<K,V>(keys.size());
for(K key: keys){
map.put(key, constant);
}
return map;
}
@TLFunctionAnnotation("Converts two input lists to map where first list items become map's keys and second list corresponding values.")
public static final <K, V> Map<K,V> toMap(TLFunctionCallContext context, List<K> keys, List<V> values) {
Map <K,V> map = new HashMap<K,V>(keys.size());
Iterator<V> iter = values.iterator();
if (keys.size()!=values.size()){
throw new IllegalArgumentException("Keys list does not match values list in size.");
}
for(K key: keys){
map.put(key, iter.next());
}
return map;
}
class ToMapFunction implements TLFunctionPrototype{
@Override
public void init(TLFunctionCallContext context) {
}
@Override
public void execute(Stack stack, TLFunctionCallContext context) {
if (context.getParams()[1].isList()) {
List<Object> values = stack.popList();
stack.push(toMap(context, stack.popList(), values));
}else{
Object constant = stack.pop();
stack.push(toMap(context, stack.popList(), constant));
}
}
}
}
| UPDATE: CLO-4981 - Removed ContainerLib.binarySearch().
git-svn-id: 9f0029f1b6ec0a28b374ab8b218854801a9e0104@16514 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.ctlfunction/src/org/jetel/ctl/extensions/ContainerLib.java | UPDATE: CLO-4981 - Removed ContainerLib.binarySearch(). | <ide><path>loveretl.ctlfunction/src/org/jetel/ctl/extensions/ContainerLib.java
<ide> "containsAll".equals(functionName) ? new ContainsAllFunction() :
<ide> "containsKey".equals(functionName) ? new ContainsKeyFunction() :
<ide> "containsValue".equals(functionName) ? new ContainsValueFunction() :
<del> "binarySearch".equals(functionName) ? new BinarySearchFunction() :
<add>// "binarySearch".equals(functionName) ? new BinarySearchFunction() :
<ide> "getKeys".equals(functionName) ? new GetKeysFunction() :
<ide> "getValues".equals(functionName) ? new GetValuesFunction() :
<ide> "toMap".equals(functionName) ? new ToMapFunction() : null;
<ide> }
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<del> @TLFunctionAnnotation("Searches a list for the specified value. The list must be sorted in ascending order.")
<del> public static final <V> Integer binarySearch(TLFunctionCallContext context, List<V> list, V value) {
<del> return Collections.binarySearch(((List<? extends Comparable<? super V>>) list), value);
<del> }
<del>
<del> class BinarySearchFunction implements TLFunctionPrototype{
<del>
<del> @Override
<del> public void init(TLFunctionCallContext context) {
<del> }
<del>
<del> @Override
<del> public void execute(Stack stack, TLFunctionCallContext context) {
<del> Object value = stack.pop();
<del> List<Object> list = stack.popList();
<del> stack.push(binarySearch(context, list, value));
<del> }
<del> }
<add>// @SuppressWarnings("unchecked")
<add>// @TLFunctionAnnotation("Searches a list for the specified value. The list must be sorted in ascending order.")
<add>// public static final <V> Integer binarySearch(TLFunctionCallContext context, List<V> list, V value) {
<add>// return Collections.binarySearch(((List<? extends Comparable<? super V>>) list), value);
<add>// }
<add>//
<add>// class BinarySearchFunction implements TLFunctionPrototype{
<add>//
<add>// @Override
<add>// public void init(TLFunctionCallContext context) {
<add>// }
<add>//
<add>// @Override
<add>// public void execute(Stack stack, TLFunctionCallContext context) {
<add>// Object value = stack.pop();
<add>// List<Object> list = stack.popList();
<add>// stack.push(binarySearch(context, list, value));
<add>// }
<add>// }
<ide>
<ide> @TLFunctionAnnotation("Returns the keys of the map.")
<ide> public static final <K, V> List<K> getKeys(TLFunctionCallContext context, Map<K, V> map) { |
|
Java | mit | 9795a050e1f70340d86c66c3322667164f75f3c1 | 0 | CoreNetwork/MobLimiter | package us.corenetwork.moblimiter.commands;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import us.corenetwork.moblimiter.*;
import us.corenetwork.moblimiter.CreatureSettingsStorage.CreatureGroup;
import us.corenetwork.moblimiter.CreatureSettingsStorage.CreatureGroupSettings;
import java.util.HashMap;
import java.util.Map;
public abstract class CountCommand extends BaseCommand
{
private CreatureGroup group;
static private HashMap<Player, Cleanup> cleanups = new HashMap<Player, Cleanup>();
public CountCommand(CreatureGroup group)
{
needPlayer = true;
this.group = group;
}
@Override
public void run(CommandSender sender, String[] args)
{
Player player = (Player) sender;
boolean visualize = args.length > 0 && args[0].equals("show");
boolean keep = args.length > 1 && args[1].equals("keep");
boolean clear = args.length > 0 && args[0].equals("hide");
if (visualize && !clear)
{
visualize(player, !keep);
}
else if (!clear)
{
showCount(player);
}
else if (clear)
{
cleanup(player);
}
}
private void visualize(Player player, boolean autocleanup)
{
cleanup(player);
Cleanup cleanup;
CreatureGroupSettings group = CreatureSettingsStorage.getGroupSettings(this.group);
int cx = player.getLocation().getChunk().getX();
int cz = player.getLocation().getChunk().getZ();
int drawY = player.getLocation().getBlockY() + 10;
HashMap<Chunk, Float> limits = new HashMap();
for (int x = cx - 6; x < cx + 6; x++)
{
for (int z = cz - 6; z < cz + 6; z++)
{
Chunk chunk = player.getLocation().getWorld().getChunkAt(x, z);
Entity creatures[] = chunk.getEntities();
HashMap<EntityType, Integer> count = new HashMap<EntityType, Integer>();
for (Entity creature : creatures)
{
Integer value = count.get(creature.getType());
if (value == null)
{
value = 0;
}
value++;
count.put(creature.getType(), value);
}
float max = 0;
int sum = 0;
for (Map.Entry<EntityType, Integer> e : count.entrySet())
{
CreatureSettings settings = group.creatureSettings.get(e.getKey());
if (settings != null)
{
float full = (float) e.getValue() / (float) settings.getChunkLimit();
if (full > max)
{
max = full;
}
sum += e.getValue();
}
}
float full = (float) sum / group.globalChunkLimit;
if (full > max)
{
max = full;
}
limits.put(chunk, max);
int id = Settings.getInt(Setting.GRID_NONE_ID);
int color = Settings.getInt(Setting.GRID_NONE_DATA);
VisualizeLayout layout = VisualizeLayout.LAYOUT_NONE;
if (max > 0)
{
id = Settings.getInt(Setting.GRID_LOW_ID);
color = Settings.getInt(Setting.GRID_LOW_DATA);
layout = VisualizeLayout.LAYOUT_LOW;
}
if (max >= 0.8)
{
id = Settings.getInt(Setting.GRID_MEDIUM_ID);
color = Settings.getInt(Setting.GRID_MEDIUM_DATA);
layout = VisualizeLayout.LAYOUT_MEDIUM;
}
if (max >= 0.9)
{
id = Settings.getInt(Setting.GRID_HIGH_ID);
color = Settings.getInt(Setting.GRID_HIGH_DATA);
layout = VisualizeLayout.LAYOUT_HIGH;
}
if (max > 1)
{
id = Settings.getInt(Setting.GRID_EXCEED_ID);
color = Settings.getInt(Setting.GRID_EXCEED_DATA);
layout = VisualizeLayout.LAYOUT_EXCEED;
}
layout.draw(chunk, player, drawY, id, (byte) color);
}
}
cleanup = new Cleanup(cx, cz, drawY, player.getWorld(), player);
if (autocleanup)
{
cleanup.setTaskId(
Bukkit.getScheduler().scheduleSyncDelayedTask(MobLimiter.instance, cleanup, Settings.getInt(Setting.GRID_DURATION)));
}
cleanups.put(player, cleanup);
}
private void cleanup(Player player)
{
Cleanup cleanup = cleanups.get(player);
if (cleanup != null)
{
if (Bukkit.getScheduler().isQueued(cleanup.getTaskId()))
{
Bukkit.getScheduler().cancelTask(cleanup.getTaskId());
cleanup.fired = true;
cleanup.run();
}
}
}
private void showCount(Player player)
{
Chunk playerChunk = player.getLocation().getChunk();
CreatureGroupSettings groupSettings = CreatureSettingsStorage.getGroupSettings(group);
HashMap<CreatureSettings, Integer> perCreatureCountsChunk = new HashMap<CreatureSettings, Integer>();
int allCountChunk = 0;
HashMap<CreatureSettings, Integer> perCreatureCountsViewDistance = new HashMap<CreatureSettings, Integer>();
int allCountViewDistance = 0;
boolean tooMany = false;
for (CreatureSettings settings : groupSettings.creatureSettings.values())
{
perCreatureCountsChunk.put(settings, 0);
perCreatureCountsViewDistance.put(settings, 0);
}
Iterable<Creature> viewDistanceCreatures = CreatureUtil.getCreaturesInRange(playerChunk);
Entity[] chunkCreatures = playerChunk.getEntities();
for (Entity e : chunkCreatures)
{
if (e instanceof Creature)
{
CreatureSettings creatureSettings = groupSettings.creatureSettings.get(e.getType());
if (creatureSettings == null)
continue;
int curCount = perCreatureCountsChunk.get(creatureSettings);
allCountChunk++;
perCreatureCountsChunk.put(creatureSettings, curCount + 1);
}
}
for (Creature c : viewDistanceCreatures)
{
CreatureSettings creatureSettings = groupSettings.creatureSettings.get(c.getType());
if (creatureSettings == null)
continue;
int curCount = perCreatureCountsViewDistance.get(creatureSettings);
allCountViewDistance++;
perCreatureCountsViewDistance.put(creatureSettings, curCount + 1);
if (!tooMany)
{
tooMany = curCount > creatureSettings.getViewDistanceLimit() || allCountChunk > groupSettings.globalViewDistanceLimit;
}
}
messageCount(player, groupSettings.groupPlural, allCountChunk, groupSettings.globalChunkLimit, allCountViewDistance, groupSettings.globalViewDistanceLimit);
for (CreatureSettings settings : groupSettings.creatureSettings.values())
{
messageCount(player, settings.getPluralName(), perCreatureCountsChunk.get(settings), settings.getChunkLimit(), perCreatureCountsViewDistance.get(settings), settings.getViewDistanceLimit());
}
if (tooMany)
{
Util.Message(Settings.getString(Setting.MESSAGE_TOO_MANY), player);
}
}
private void messageCount(Player player, String creature, int chunkCount, int chunkMax, int vdCount, int vdMax)
{
char chunkColor = Util.getPercentageColor((double) chunkCount / chunkMax);
char vdColor = Util.getPercentageColor((double) vdCount / vdMax);
String message = Settings.getString(Setting.MESSAGE_MOB_COUNT_LINE);
message = message.replace("<MobName>", creature);
message = message.replace("<ChunkCount>", "&" + chunkColor + chunkCount);
message = message.replace("<ChunkLimit>", Integer.toString(chunkMax));
message = message.replace("<ViewDistanceCount>", "&" + vdColor + vdCount);
message = message.replace("<ViewDistanceLimit>", Integer.toString(vdMax));
Util.Message(message, player);
//"<MobName>: <ChunkCount>/<ChunkLimit> in Chunk, <ViewDistanceCount>/<ViewDistanceLimit> in View distance"),
//"&cYou have too many mobs for the server to handle. Please, if you can, consider killing some or moving them further to keep the server healthy. Many thanks, we appreciate it.");
}
class Cleanup implements Runnable
{
private int cx, cz, height;
private World world;
private Player player;
private int taskId = -1;
boolean fired = false;
Cleanup(int cx, int cz, int height, World world, Player player)
{
this.cx = cx;
this.cz = cz;
this.height = height;
this.world = world;
this.player = player;
}
@Override
public void run()
{
if (!fired)
{
fired = true;
MobLimiter.instance.pool.addTask(this);
}
else
{
for (int x = cx - 6; x < cx + 6; x++)
{
for (int z = cz - 6; z < cz + 6; z++)
{
if (!world.isChunkLoaded(x, z))
continue;
Chunk chunk = world.getChunkAt(x, z);
for (int bx = 0; bx < 16; bx++)
{
for (int bz = 0; bz < 16; bz++)
{
Block block = chunk.getBlock(bx, height, bz);
if (bx == 0 || bx == 15 || bz == 0 || bz == 15)
{
player.sendBlockChange(block.getLocation(), block.getTypeId(), block.getData());
}
}
}
}
}
}
}
public void setTaskId(int taskId)
{
this.taskId = taskId;
}
public int getTaskId()
{
return taskId;
}
}
}
| src/us/corenetwork/moblimiter/commands/CountCommand.java | package us.corenetwork.moblimiter.commands;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import us.corenetwork.moblimiter.*;
import us.corenetwork.moblimiter.CreatureSettingsStorage.CreatureGroup;
import us.corenetwork.moblimiter.CreatureSettingsStorage.CreatureGroupSettings;
import java.util.HashMap;
import java.util.Map;
public abstract class CountCommand extends BaseCommand
{
private CreatureGroup group;
static private HashMap<Player, Cleanup> cleanups = new HashMap<Player, Cleanup>();
public CountCommand(CreatureGroup group)
{
needPlayer = true;
this.group = group;
}
@Override
public void run(CommandSender sender, String[] args)
{
Player player = (Player) sender;
boolean visualize = args.length > 0 && args[0].equals("show");
boolean keep = args.length > 1 && args[1].equals("keep");
boolean clear = args.length > 0 && args[0].equals("hide");
if (visualize && !clear)
{
visualize(player, !keep);
}
else if (!clear)
{
showCount(player);
}
else if (clear)
{
cleanup(player);
}
}
private void visualize(Player player, boolean autocleanup)
{
cleanup(player);
Cleanup cleanup;
CreatureGroupSettings group = CreatureSettingsStorage.getGroupSettings(this.group);
int cx = player.getLocation().getChunk().getX();
int cz = player.getLocation().getChunk().getZ();
int drawY = player.getLocation().getBlockY() + 10;
HashMap<Chunk, Float> limits = new HashMap();
for (int x = cx - 6; x < cx + 6; x++)
{
for (int z = cz - 6; z < cz + 6; z++)
{
Chunk chunk = player.getLocation().getWorld().getChunkAt(x, z);
Entity creatures[] = chunk.getEntities();
HashMap<EntityType, Integer> count = new HashMap<EntityType, Integer>();
for (Entity creature : creatures)
{
Integer value = count.get(creature.getType());
if (value == null)
{
value = 0;
}
value++;
count.put(creature.getType(), value);
}
float max = 0;
int sum = 0;
for (Map.Entry<EntityType, Integer> e : count.entrySet())
{
CreatureSettings settings = group.creatureSettings.get(e.getKey());
if (settings != null)
{
float full = (float) e.getValue() / (float) settings.getChunkLimit();
if (full > max)
{
max = full;
}
sum += e.getValue();
}
}
float full = (float) sum / group.globalChunkLimit;
if (full > max)
{
max = full;
}
limits.put(chunk, max);
int id = Settings.getInt(Setting.GRID_NONE_ID);
int color = Settings.getInt(Setting.GRID_NONE_DATA);
VisualizeLayout layout = VisualizeLayout.LAYOUT_NONE;
if (max > 0)
{
id = Settings.getInt(Setting.GRID_LOW_ID);
color = Settings.getInt(Setting.GRID_LOW_DATA);
layout = VisualizeLayout.LAYOUT_LOW;
}
if (max >= 0.8)
{
id = Settings.getInt(Setting.GRID_MEDIUM_ID);
color = Settings.getInt(Setting.GRID_MEDIUM_DATA);
layout = VisualizeLayout.LAYOUT_MEDIUM;
}
if (max >= 0.9)
{
id = Settings.getInt(Setting.GRID_HIGH_ID);
color = Settings.getInt(Setting.GRID_HIGH_DATA);
layout = VisualizeLayout.LAYOUT_HIGH;
}
if (max > 1)
{
id = Settings.getInt(Setting.GRID_EXCEED_ID);
color = Settings.getInt(Setting.GRID_EXCEED_DATA);
layout = VisualizeLayout.LAYOUT_EXCEED;
}
layout.draw(chunk, player, drawY, id, (byte) color);
}
}
cleanup = new Cleanup(cx, cz, drawY, player.getWorld(), player);
if (autocleanup)
{
cleanup.setTaskId(
Bukkit.getScheduler().scheduleSyncDelayedTask(MobLimiter.instance, cleanup, Settings.getInt(Setting.GRID_DURATION)));
}
cleanups.put(player, cleanup);
}
private void cleanup(Player player)
{
Cleanup cleanup = cleanups.get(player);
if (cleanup != null)
{
if (Bukkit.getScheduler().isQueued(cleanup.getTaskId()))
{
Bukkit.getScheduler().cancelTask(cleanup.getTaskId());
cleanup.fired = true;
cleanup.run();
}
}
}
private void showCount(Player player)
{
Chunk playerChunk = player.getLocation().getChunk();
CreatureGroupSettings groupSettings = CreatureSettingsStorage.getGroupSettings(group);
HashMap<CreatureSettings, Integer> perCreatureCountsChunk = new HashMap<CreatureSettings, Integer>();
int allCountChunk = 0;
HashMap<CreatureSettings, Integer> perCreatureCountsViewDistance = new HashMap<CreatureSettings, Integer>();
int allCountViewDistance = 0;
boolean tooMany = false;
for (CreatureSettings settings : groupSettings.creatureSettings.values())
{
perCreatureCountsChunk.put(settings, 0);
perCreatureCountsViewDistance.put(settings, 0);
}
Iterable<Creature> viewDistanceCreatures = CreatureUtil.getCreaturesInRange(playerChunk);
Entity[] chunkCreatures = playerChunk.getEntities();
for (Entity e : chunkCreatures)
{
if (e instanceof Creature)
{
CreatureSettings creatureSettings = groupSettings.creatureSettings.get(e.getType());
if (creatureSettings == null)
continue;
int curCount = perCreatureCountsChunk.get(creatureSettings);
allCountChunk++;
perCreatureCountsChunk.put(creatureSettings, curCount + 1);
}
}
for (Creature c : viewDistanceCreatures)
{
CreatureSettings creatureSettings = groupSettings.creatureSettings.get(c.getType());
if (creatureSettings == null)
continue;
int curCount = perCreatureCountsViewDistance.get(creatureSettings);
allCountViewDistance++;
perCreatureCountsViewDistance.put(creatureSettings, curCount + 1);
if (!tooMany)
{
tooMany = curCount > creatureSettings.getViewDistanceLimit() || allCountChunk > groupSettings.globalViewDistanceLimit;
}
}
messageCount(player, groupSettings.groupPlural, allCountChunk, groupSettings.globalChunkLimit, allCountViewDistance, groupSettings.globalViewDistanceLimit);
for (CreatureSettings settings : groupSettings.creatureSettings.values())
{
messageCount(player, settings.getPluralName(), perCreatureCountsChunk.get(settings), settings.getChunkLimit(), perCreatureCountsViewDistance.get(settings), settings.getViewDistanceLimit());
}
if (tooMany)
{
Util.Message(Settings.getString(Setting.MESSAGE_TOO_MANY), player);
}
}
private void messageCount(Player player, String creature, int chunkCount, int chunkMax, int vdCount, int vdMax)
{
char chunkColor = Util.getPercentageColor((double) chunkCount / chunkMax);
char vdColor = Util.getPercentageColor((double) vdCount / vdMax);
String message = Settings.getString(Setting.MESSAGE_MOB_COUNT_LINE);
message = message.replace("<MobName>", creature);
message = message.replace("<ChunkCount>", "&" + chunkColor + chunkCount);
message = message.replace("<ChunkLimit>", Integer.toString(chunkMax));
message = message.replace("<ViewDistanceCount>", "&" + vdColor + vdCount);
message = message.replace("<ViewDistanceLimit>", Integer.toString(vdMax));
Util.Message(message, player);
//"<MobName>: <ChunkCount>/<ChunkLimit> in Chunk, <ViewDistanceCount>/<ViewDistanceLimit> in View distance"),
//"&cYou have too many mobs for the server to handle. Please, if you can, consider killing some or moving them further to keep the server healthy. Many thanks, we appreciate it.");
}
class Cleanup implements Runnable
{
private int cx, cz, height;
private World world;
private Player player;
private int taskId = -1;
boolean fired = false;
Cleanup(int cx, int cz, int height, World world, Player player)
{
this.cx = cx;
this.cz = cz;
this.height = height;
this.world = world;
this.player = player;
}
@Override
public void run()
{
if (!fired)
{
fired = true;
MobLimiter.instance.pool.addTask(this);
}
else
{
for (int x = cx - 6; x < cx + 6; x++)
{
for (int z = cz - 6; z < cz + 6; z++)
{
Chunk chunk = world.getChunkAt(x, z);
for (int bx = 0; bx < 16; bx++)
{
for (int bz = 0; bz < 16; bz++)
{
Block block = chunk.getBlock(bx, height, bz);
if (bx == 0 || bx == 15 || bz == 0 || bz == 15)
{
player.sendBlockChange(block.getLocation(), block.getTypeId(), block.getData());
}
}
}
}
}
}
}
public void setTaskId(int taskId)
{
this.taskId = taskId;
}
public int getTaskId()
{
return taskId;
}
}
}
| Probable fix for #10 - getChunkAt automatically loads chunk which is not
best thing to do async. Lets skip any unloaded chunks, they will be
resent anyway. | src/us/corenetwork/moblimiter/commands/CountCommand.java | Probable fix for #10 - getChunkAt automatically loads chunk which is not best thing to do async. Lets skip any unloaded chunks, they will be resent anyway. | <ide><path>rc/us/corenetwork/moblimiter/commands/CountCommand.java
<ide> {
<ide> for (int z = cz - 6; z < cz + 6; z++)
<ide> {
<add> if (!world.isChunkLoaded(x, z))
<add> continue;
<add>
<ide> Chunk chunk = world.getChunkAt(x, z);
<ide> for (int bx = 0; bx < 16; bx++)
<ide> { |
|
Java | bsd-2-clause | 09fcf6460182a3ea1ff323572d24d0b8b940b698 | 0 | scifio/scifio-ome-xml | /*
* #%L
* SCIFIO support for the OME data model, including OME-XML and OME-TIFF.
* %%
* Copyright (C) 2013 - 2014 Board of Regents of the University of
* Wisconsin-Madison
* %%
* 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.
*
* 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 HOLDERS 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.
* #L%
*/
package io.scif.ome.formats;
import io.scif.AbstractChecker;
import io.scif.AbstractFormat;
import io.scif.AbstractParser;
import io.scif.AbstractTranslator;
import io.scif.ByteArrayPlane;
import io.scif.ByteArrayReader;
import io.scif.DefaultImageMetadata;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.Plane;
import io.scif.Translator;
import io.scif.config.SCIFIOConfig;
import io.scif.formats.MinimalTIFFFormat;
import io.scif.formats.TIFFFormat;
import io.scif.formats.tiff.IFD;
import io.scif.formats.tiff.IFDList;
import io.scif.formats.tiff.PhotoInterp;
import io.scif.formats.tiff.TiffIFDEntry;
import io.scif.formats.tiff.TiffParser;
import io.scif.formats.tiff.TiffSaver;
import io.scif.io.Location;
import io.scif.io.RandomAccessInputStream;
import io.scif.io.RandomAccessOutputStream;
import io.scif.ome.OMEMetadata;
import io.scif.ome.services.OMEMetadataService;
import io.scif.ome.services.OMEXMLService;
import io.scif.services.FormatService;
import io.scif.services.TranslatorService;
import io.scif.util.FormatTools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import loci.common.services.ServiceException;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.ome.OMEXMLMetadata;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import org.scijava.Context;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* OMETiffReader is the file format reader for <a
* href="http://ome-xml.org/wiki/OmeTiff">OME-TIFF</a> files.
*
* @author Mark Hiner hinerm at gmail.com
*/
@Plugin(type = Format.class, priority = OMETIFFFormat.PRIORITY)
public class OMETIFFFormat extends AbstractFormat {
// -- Constants --
public static final String URL_OME_TIFF =
"http://www.openmicroscopy.org/site/support/ome-model/ome-tiff/";
public static final double PRIORITY = TIFFFormat.PRIORITY + 1;
// -- Fields --
@Parameter
private static OMEXMLService service;
@Parameter
private static OMEMetadataService metaService;
// -- Format API Methods --
@Override
public String getFormatName() {
return "OME-TIFF";
}
@Override
protected String[] makeSuffixArray() {
return new String[] { "ome.tif", "ome.tiff" };
}
// -- Nested Classes --
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Metadata extends TIFFFormat.Metadata {
// -- Fields --
/** Mapping from series and plane numbers to files and IFD entries. */
protected OMETIFFPlane[][] info; // dimensioned [numSeries][numPlanes]
private IFD firstIFD;
private List<Integer> samples;
private List<Boolean> adjustedSamples;
/** List of used files. */
protected String[] used;
// TODO maybe this should be an o mexmlmetadata...
private OMEMetadata omeMeta;
private long lastPlane = 0;
private boolean hasSPW;
private int[] tileWidth;
private int[] tileHeight;
// -- OMETIFF Metadata API methods --
/**
* Returns a MetadataStore that is populated in such a way as to produce
* valid OME-XML. The returned MetadataStore cannot be used by an
* IFormatWriter, as it will not contain the required BinData.BigEndian
* attributes.
*/
public MetadataStore getMetadataStoreForDisplay() {
final MetadataStore store = omeMeta.getRoot();
if (service.isOMEXMLMetadata(store)) {
service.removeBinData((OMEXMLMetadata) store);
for (int i = 0; i < getImageCount(); i++) {
if (((OMEXMLMetadata) store).getTiffDataCount(i) == 0) {
service.addMetadataOnly((OMEXMLMetadata) store, i);
}
}
}
return store;
}
/**
* Returns a MetadataStore that is populated in such a way as to be usable
* by an IFormatWriter. Any OME-XML generated from this MetadataStore is
* <em>very unlikely</em> to be valid, as more than likely both BinData and
* TiffData element will be present.
*/
public MetadataStore getMetadataStoreForConversion() {
final MetadataStore store = omeMeta.getRoot();
for (int i = 0; i < getImageCount(); i++) {
store.setPixelsBinDataBigEndian(new Boolean(!get(i).isLittleEndian()),
i, 0);
}
return store;
}
// -- OMETIFFMetadata getters and setters --
public OMETIFFPlane[][] getPlaneInfo() {
return info;
}
public void setPlaneInfo(final OMETIFFPlane[][] info) {
this.info = info;
}
public String[] getUsed() {
return used;
}
public void setUsed(final String[] used) {
this.used = used;
}
public OMEMetadata getOmeMeta() {
return omeMeta;
}
public void setOmeMeta(final OMEMetadata omeMeta) {
this.omeMeta = omeMeta;
}
@Override
public long getLastPlane() {
return lastPlane;
}
@Override
public void setLastPlane(final long lastPlane) {
this.lastPlane = lastPlane;
}
public IFD getFirstIFD() {
return firstIFD;
}
public void setFirstIFD(final IFD firstIFD) {
this.firstIFD = firstIFD;
}
public boolean isHasSPW() {
return hasSPW;
}
public void setHasSPW(final boolean hasSPW) {
this.hasSPW = hasSPW;
}
public int[] getTileWidth() {
return tileWidth;
}
public void setTileWidth(final int[] tileWidth) {
this.tileWidth = tileWidth;
}
public int[] getTileHeight() {
return tileHeight;
}
public void setTileHeight(final int[] tileHeight) {
this.tileHeight = tileHeight;
}
// -- Metadata API Methods --
/*
* @see io.scif.Metadata#populateImageMetadata()
*/
@Override
public void populateImageMetadata() {
// populate core metadata
final OMEXMLMetadata omexmlMeta = getOmeMeta().getRoot();
for (int s = 0; s < getImageCount(); s++) {
final ImageMetadata m = get(s);
try {
m.setPlanarAxisCount(2);
m.setAxisLength(Axes.X, omexmlMeta.getPixelsSizeX(s).getValue()
.intValue());
final int tiffWidth = (int) firstIFD.getImageWidth();
if (m.getAxisLength(Axes.X) != tiffWidth && s == 0) {
log().warn(
"SizeX mismatch: OME=" + m.getAxisLength(Axes.X) + ", TIFF=" +
tiffWidth);
}
m.setAxisLength(Axes.Y, omexmlMeta.getPixelsSizeY(s).getValue()
.intValue());
final int tiffHeight = (int) firstIFD.getImageLength();
if (m.getAxisLength(Axes.Y) != tiffHeight && s == 0) {
log().warn(
"SizeY mismatch: OME=" + m.getAxisLength(Axes.Y) + ", TIFF=" +
tiffHeight);
}
m.setAxisLength(Axes.Z, omexmlMeta.getPixelsSizeZ(s).getValue()
.intValue());
m.setAxisLength(Axes.CHANNEL, omexmlMeta.getPixelsSizeC(s).getValue()
.intValue());
m.setAxisLength(Axes.TIME, omexmlMeta.getPixelsSizeT(s).getValue()
.intValue());
m.setPixelType(FormatTools.pixelTypeFromString(omexmlMeta
.getPixelsType(s).toString()));
final int tiffPixelType = firstIFD.getPixelType();
if (m.getPixelType() != tiffPixelType &&
(s == 0 || adjustedSamples.get(s)))
{
log().warn(
"PixelType mismatch: OME=" + m.getPixelType() + ", TIFF=" +
tiffPixelType);
m.setPixelType(tiffPixelType);
}
m.setBitsPerPixel(FormatTools.getBitsPerPixel(m.getPixelType()));
String dimensionOrder =
omexmlMeta.getPixelsDimensionOrder(s).toString();
// hackish workaround for files exported by OMERO that have an
// incorrect dimension order
String uuidFileName = "";
try {
if (omexmlMeta.getTiffDataCount(s) > 0) {
uuidFileName = omexmlMeta.getUUIDFileName(s, 0);
}
}
catch (final NullPointerException e) {}
if (omexmlMeta.getChannelCount(s) > 0 &&
omexmlMeta.getChannelName(s, 0) == null &&
omexmlMeta.getTiffDataCount(s) > 0 &&
uuidFileName.indexOf("__omero_export") != -1)
{
dimensionOrder = "XYZCT";
}
m.setAxisTypes(metaService.findDimensionList(dimensionOrder));
m.setOrderCertain(true);
final PhotoInterp photo = firstIFD.getPhotometricInterpretation();
if (samples.get(s) > 1 || photo == PhotoInterp.RGB) {
m.setPlanarAxisCount(3);
}
if ((samples.get(s) != m.getAxisLength(Axes.CHANNEL) &&
(samples.get(s) % m.getAxisLength(Axes.CHANNEL)) != 0 && (m
.getAxisLength(Axes.CHANNEL) % samples.get(s)) != 0) ||
m.getAxisLength(Axes.CHANNEL) == 1 || adjustedSamples.get(s))
{
m.setAxisLength(Axes.CHANNEL, m.getAxisLength(Axes.CHANNEL) *
samples.get(s));
}
if (m.getAxisLength(Axes.Z) * m.getAxisLength(Axes.TIME) *
m.getAxisLength(Axes.CHANNEL) > info[s].length &&
!m.isMultichannel())
{
if (m.getAxisLength(Axes.Z) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.TIME) == info[s].length) {
m.setAxisLength(Axes.Z, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.CHANNEL) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.Z, 1);
}
}
if (omexmlMeta.getPixelsBinDataCount(s) > 1) {
log().warn(
"OME-TIFF Pixels element contains BinData elements! "
+ "Ignoring.");
}
m.setLittleEndian(firstIFD.isLittleEndian());
m.setIndexed(photo == PhotoInterp.RGB_PALETTE &&
firstIFD.getIFDValue(IFD.COLOR_MAP) != null);
m.setFalseColor(true);
m.setMetadataComplete(true);
}
catch (final NullPointerException exc) {
log().error("Incomplete Pixels metadata", exc);
}
catch (final FormatException exc) {
log().error("Format exception when creating ImageMetadata", exc);
}
// Set the physical pixel sizes
FormatTools.calibrate(m.getAxis(Axes.X), getValue(omexmlMeta
.getPixelsPhysicalSizeX(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Y), getValue(omexmlMeta
.getPixelsPhysicalSizeY(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Z), getValue(omexmlMeta
.getPixelsPhysicalSizeZ(s)), 0.0);
}
// if (getImageCount() == 1) {
// CoreMetadata ms0 = core.get(0);
// ms0.sizeZ = 1;
// if (!ms0.rgb) {
// ms0.sizeC = 1;
// }
// ms0.sizeT = 1;
// }
// metaService.populatePixels(getOmeMeta().getRoot(), this, false, false);
getOmeMeta().setRoot((OMEXMLMetadata) getMetadataStoreForConversion());
}
@Override
public void close(final boolean fileOnly) throws IOException {
super.close(fileOnly);
if (info != null) {
for (final OMETIFFPlane[] dimension : info) {
for (final OMETIFFPlane plane : dimension) {
if (plane.reader != null) {
try {
plane.reader.close();
}
catch (final Exception e) {
log().error("Plane closure failure!", e);
}
}
}
}
}
if (!fileOnly) {
info = null;
lastPlane = 0;
tileWidth = null;
tileHeight = null;
}
}
// -- HasColorTable API Methods --
@Override
public ColorTable
getColorTable(final int imageIndex, final long planeIndex)
{
if (info[imageIndex][(int) lastPlane] == null ||
info[imageIndex][(int) lastPlane].reader == null ||
info[imageIndex][(int) lastPlane].id == null)
{
return null;
}
try {
info[imageIndex][(int) lastPlane].reader
.setSource(info[imageIndex][(int) lastPlane].id);
return info[imageIndex][(int) lastPlane].reader.getMetadata()
.getColorTable(imageIndex, planeIndex);
}
catch (final IOException e) {
log().error("IOException when trying to read color table", e);
return null;
}
}
/**
* Helper method to extract values out of {@link PositiveFloat}s, for
* physical pixel sizes (calibration values). Returns 1.0 if given a null or
* invalid (< 0) calibration.
*/
private double getValue(PositiveFloat pixelPhysicalSize) {
if (pixelPhysicalSize == null) return 1.0;
Double physSize = pixelPhysicalSize.getValue();
if (physSize < 0) return 1.0;
return physSize;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Checker extends AbstractChecker {
// -- Checker API Methods --
@Override
public boolean suffixNecessary() {
return false;
}
@Override
public boolean suffixSufficient() {
return false;
}
@Override
public boolean isFormat(final RandomAccessInputStream stream)
throws IOException
{
final TiffParser tp = new TiffParser(getContext(), stream);
tp.setDoCaching(false);
final boolean validHeader = tp.isValidHeader();
if (!validHeader) return false;
// look for OME-XML in first IFD's comment
final IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
final Object description = ifd.get(IFD.IMAGE_DESCRIPTION);
if (description == null) {
return false;
}
String comment = null;
if (description instanceof TiffIFDEntry) {
comment = tp.getIFDValue((TiffIFDEntry) description).toString();
}
else if (description instanceof String) {
comment = (String) description;
}
if (comment == null || comment.trim().length() == 0) return false;
comment = comment.trim();
// do a basic sanity check before attempting to parse the comment as XML
// the parsing step is a bit slow, so there is no sense in trying unless
// we are reasonably sure that the comment contains XML
if (!comment.startsWith("<") || !comment.endsWith(">")) {
return false;
}
try {
final IMetadata meta = service.createOMEXMLMetadata(comment);
for (int i = 0; i < meta.getImageCount(); i++) {
meta.setPixelsBinDataBigEndian(Boolean.TRUE, i, 0);
metaService.verifyMinimumPopulated(meta, i);
}
return meta.getImageCount() > 0;
}
catch (final ServiceException se) {
log().debug("OME-XML parsing failed", se);
}
catch (final NullPointerException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final IndexOutOfBoundsException e) {
log().debug("OME-XML parsing failed", e);
}
return false;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Parser extends AbstractParser<Metadata> {
// -- Fields --
@Parameter
private FormatService formatService;
// -- Parser API Methods --
@Override
public String[] getImageUsedFiles(final int imageIndex,
final boolean noPixels)
{
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
if (noPixels) return null;
final Vector<String> usedFiles = new Vector<String>();
for (int i = 0; i < getMetadata().info[imageIndex].length; i++) {
if (!usedFiles.contains(getMetadata().info[imageIndex][i].id)) {
usedFiles.add(getMetadata().info[imageIndex][i].id);
}
}
return usedFiles.toArray(new String[usedFiles.size()]);
}
@Override
public Metadata parse(final String fileName, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, fileName), meta, config);
}
@Override
public Metadata parse(final File file, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, file.getPath()), meta, config);
}
@Override
public int fileGroupOption(final String id) throws FormatException,
IOException
{
final boolean single = isSingleFile(id);
return single ? FormatTools.CAN_GROUP : FormatTools.MUST_GROUP;
}
@Override
public Metadata parse(final RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
FormatException
{
super.parse(stream, meta, config);
for (int s = 0; s < meta.getImageCount(); s++) {
final OMETIFFPlane[][] info = meta.getPlaneInfo();
try {
if (!info[s][0].reader.getFormat().createChecker().isFormat(
info[s][0].id))
{
info[s][0].id = meta.getSource().getFileName();
}
for (int plane = 0; plane < info[s].length; plane++) {
if (!info[s][plane].reader.getFormat().createChecker().isFormat(
info[s][plane].id))
{
info[s][plane].id = info[s][0].id;
}
}
info[s][0].reader.setSource(info[s][0].id);
meta.getTileWidth()[s] =
(int) info[s][0].reader.getOptimalTileWidth(s);
meta.getTileHeight()[s] =
(int) info[s][0].reader.getOptimalTileHeight(s);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
}
return meta;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
// -- Abstract Parser API Methods --
@Override
protected void typedParse(final io.scif.io.RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
io.scif.FormatException
{
// normalize file name
final String id = stream.getFileName();
final String dir = new File(id).getParent();
// parse and populate OME-XML metadata
String fileName =
new Location(getContext(), id).getAbsoluteFile().getAbsolutePath();
if (!new File(fileName).exists()) {
fileName = stream.getFileName();
}
final RandomAccessInputStream ras =
new RandomAccessInputStream(getContext(), fileName);
String xml;
IFD firstIFD;
try {
final TiffParser tp = new TiffParser(getContext(), ras);
firstIFD = tp.getFirstIFD();
xml = firstIFD.getComment();
}
finally {
ras.close();
}
meta.setFirstIFD(firstIFD);
OMEXMLMetadata omexmlMeta;
try {
omexmlMeta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
meta.setHasSPW(omexmlMeta.getPlateCount() > 0);
for (int i = 0; i < meta.getImageCount(); i++) {
final int sizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
service.removeChannels(omexmlMeta, i, sizeC);
}
final Hashtable<String, Object> originalMetadata =
service.getOriginalMetadata(omexmlMeta);
if (originalMetadata != null) meta.getTable().putAll(originalMetadata);
log().trace(xml);
if (omexmlMeta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
meta.setOmeMeta(new OMEMetadata(getContext(), omexmlMeta));
final String[] acquiredDates = new String[meta.getImageCount()];
for (int i = 0; i < acquiredDates.length; i++) {
final Timestamp acquisitionDate = omexmlMeta.getImageAcquisitionDate(i);
if (acquisitionDate != null) {
acquiredDates[i] = acquisitionDate.getValue();
}
}
final String currentUUID = omexmlMeta.getUUID();
// determine series count from Image and Pixels elements
final int imageCount = omexmlMeta.getImageCount();
meta.createImageMetadata(imageCount);
OMETIFFPlane[][] info = new OMETIFFPlane[imageCount][];
meta.setPlaneInfo(info);
final int[] tileWidth = new int[imageCount];
final int[] tileHeight = new int[imageCount];
meta.setTileWidth(tileWidth);
meta.setTileHeight(tileHeight);
// compile list of file/UUID mappings
final Hashtable<String, String> files = new Hashtable<String, String>();
boolean needSearch = false;
for (int i = 0; i < imageCount; i++) {
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
for (int td = 0; td < tiffDataCount; td++) {
String uuid = null;
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {}
String filename = null;
if (uuid == null) {
// no UUID means that TiffData element refers to this file
uuid = "";
filename = id;
}
else {
filename = omexmlMeta.getUUIDFileName(i, td);
if (!new Location(getContext(), dir, filename).exists()) filename =
null;
if (filename == null) {
if (uuid.equals(currentUUID) || currentUUID == null) {
// UUID references this file
filename = id;
}
else {
// will need to search for this UUID
filename = "";
needSearch = true;
}
}
else filename = normalizeFilename(dir, filename);
}
final String existing = files.get(uuid);
if (existing == null) files.put(uuid, filename);
else if (!existing.equals(filename)) {
throw new FormatException("Inconsistent UUID filenames");
}
}
}
// search for missing filenames
if (needSearch) {
final Enumeration<String> en = files.keys();
while (en.hasMoreElements()) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
if (filename.equals("")) {
// TODO search...
// should scan only other .ome.tif files
// to make this work with OME server may be a little tricky?
throw new FormatException("Unmatched UUID: " + uuid);
}
}
}
// build list of used files
final Enumeration<String> en = files.keys();
final int numUUIDs = files.size();
final HashSet<String> fileSet = new HashSet<String>(); // ensure no
// duplicate
// filenames
for (int i = 0; i < numUUIDs; i++) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
fileSet.add(filename);
}
final String[] used = new String[fileSet.size()];
meta.setUsed(used);
final Iterator<String> iter = fileSet.iterator();
for (int i = 0; i < used.length; i++)
used[i] = iter.next();
// process TiffData elements
final Hashtable<String, MinimalTIFFFormat.Reader<?>> readers =
new Hashtable<String, MinimalTIFFFormat.Reader<?>>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
final List<Integer> samples = new ArrayList<Integer>();
meta.adjustedSamples = adjustedSamples;
meta.samples = samples;
for (int i = 0; i < imageCount; i++) {
final int s = i;
log().debug("Image[" + i + "] {");
log().debug(" id = " + omexmlMeta.getImageID(i));
adjustedSamples.add(false);
final String order = omexmlMeta.getPixelsDimensionOrder(i).toString();
PositiveInteger samplesPerPixel = null;
if (omexmlMeta.getChannelCount(i) > 0) {
samplesPerPixel = omexmlMeta.getChannelSamplesPerPixel(i, 0);
}
samples.add(i, samplesPerPixel == null ? -1 : samplesPerPixel
.getValue());
final int tiffSamples = firstIFD.getSamplesPerPixel();
if (adjustedSamples.get(i) ||
(samples.get(i) != tiffSamples && (i == 0 || samples.get(i) < 0)))
{
log().warn(
"SamplesPerPixel mismatch: OME=" + samples.get(i) + ", TIFF=" +
tiffSamples);
samples.set(i, tiffSamples);
adjustedSamples.set(i, true);
}
else {
adjustedSamples.set(i, false);
}
if (adjustedSamples.get(i) && omexmlMeta.getChannelCount(i) <= 1) {
adjustedSamples.set(i, false);
}
int effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
if (!adjustedSamples.get(i)) {
effSizeC /= samples.get(i);
}
if (effSizeC == 0) effSizeC = 1;
if (effSizeC * samples.get(i) != omexmlMeta.getPixelsSizeC(i)
.getValue().intValue())
{
effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
}
final int sizeT = omexmlMeta.getPixelsSizeT(i).getValue().intValue();
final int sizeZ = omexmlMeta.getPixelsSizeZ(i).getValue().intValue();
int num = effSizeC * sizeT * sizeZ;
OMETIFFPlane[] planes = new OMETIFFPlane[num];
for (int no = 0; no < num; no++)
planes[no] = new OMETIFFPlane();
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
Boolean zOneIndexed = null;
Boolean cOneIndexed = null;
Boolean tOneIndexed = null;
// pre-scan TiffData indices to see if any of them are indexed from 1
for (int td = 0; td < tiffDataCount; td++) {
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
final int c = firstC == null ? 0 : firstC.getValue();
final int t = firstT == null ? 0 : firstT.getValue();
final int z = firstZ == null ? 0 : firstZ.getValue();
if (c >= effSizeC && cOneIndexed == null) {
cOneIndexed = true;
}
else if (c == 0) {
cOneIndexed = false;
}
if (z >= sizeZ && zOneIndexed == null) {
zOneIndexed = true;
}
else if (z == 0) {
zOneIndexed = false;
}
if (t >= sizeT && tOneIndexed == null) {
tOneIndexed = true;
}
else if (t == 0) {
tOneIndexed = false;
}
}
for (int td = 0; td < tiffDataCount; td++) {
log().debug(" TiffData[" + td + "] {");
// extract TiffData parameters
String filename = null;
String uuid = null;
try {
filename = omexmlMeta.getUUIDFileName(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving filename.");
}
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving value.");
}
final NonNegativeInteger tdIFD = omexmlMeta.getTiffDataIFD(i, td);
final int ifd = tdIFD == null ? 0 : tdIFD.getValue();
final NonNegativeInteger numPlanes =
omexmlMeta.getTiffDataPlaneCount(i, td);
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
int c = firstC == null ? 0 : firstC.getValue();
int t = firstT == null ? 0 : firstT.getValue();
int z = firstZ == null ? 0 : firstZ.getValue();
// NB: some writers index FirstC, FirstZ and FirstT from 1
if (cOneIndexed != null && cOneIndexed) c--;
if (zOneIndexed != null && zOneIndexed) z--;
if (tOneIndexed != null && tOneIndexed) t--;
if (z >= sizeZ || c >= effSizeC || t >= sizeT) {
log().warn(
"Found invalid TiffData: Z=" + z + ", C=" + c + ", T=" + t);
break;
}
final long[] pos = metaService.zctToArray(order, z, c, t);
final long[] lengths =
metaService.zctToArray(order, sizeZ, effSizeC, sizeT);
final long index = FormatTools.positionToRaster(lengths, pos);
final int count = numPlanes == null ? 1 : numPlanes.getValue();
if (count == 0) {
meta.get(s);
break;
}
// get reader object for this filename
if (filename == null) {
if (uuid == null) filename = id;
else filename = files.get(uuid);
}
else filename = normalizeFilename(dir, filename);
MinimalTIFFFormat.Reader<?> r = readers.get(filename);
if (r == null) {
r =
(io.scif.formats.MinimalTIFFFormat.Reader<?>) formatService
.getFormatFromClass(MinimalTIFFFormat.class).createReader();
readers.put(filename, r);
}
final Location file = new Location(getContext(), filename);
if (!file.exists()) {
// if this is an absolute file name, try using a relative name
// old versions of OMETiffWriter wrote an absolute path to
// UUID.FileName, which causes problems if the file is moved to
// a different directory
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
filename = dir + File.separator + filename;
if (!new Location(getContext(), filename).exists()) {
filename = stream.getFileName();
}
}
// populate plane index -> IFD mapping
for (int q = 0; q < count; q++) {
final int no = (int) (index + q);
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = ifd + q;
planes[no].certain = true;
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
}
if (numPlanes == null) {
// unknown number of planes; fill down
for (int no = (int) (index + 1); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = planes[no - 1].ifd + 1;
log().debug(" Plane[" + no + "]: FILLED");
}
}
else {
// known number of planes; clear anything subsequently filled
for (int no = (int) (index + count); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = null;
planes[no].id = null;
planes[no].ifd = -1;
log().debug(" Plane[" + no + "]: CLEARED");
}
}
log().debug(" }");
}
if (meta.get(s) == null) continue;
// verify that all planes are available
log().debug(" --------------------------------");
for (int no = 0; no < num; no++) {
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
if (planes[no].reader == null) {
log().warn(
"Image ID '" + omexmlMeta.getImageID(i) + "': missing plane #" +
no + ". " +
"Using TiffReader to determine the number of planes.");
final TIFFFormat.Reader<?> r =
(io.scif.formats.TIFFFormat.Reader<?>) formatService
.getFormatFromClass(TIFFFormat.class).createReader();
r.setSource(stream.getFileName());
try {
planes = new OMETIFFPlane[r.getImageCount()];
for (int plane = 0; plane < planes.length; plane++) {
planes[plane] = new OMETIFFPlane();
planes[plane].id = stream.getFileName();
planes[plane].reader = r;
planes[plane].ifd = plane;
}
num = planes.length;
}
finally {
r.close();
}
}
}
info[i] = planes;
log().debug(" }");
}
// remove null CoreMetadata entries
final Vector<OMETIFFPlane[]> planeInfo = new Vector<OMETIFFPlane[]>();
for (int i = meta.getImageCount() - 1; i >= 0; i--) {
if (meta.get(i) == null) {
meta.getAll().remove(i);
adjustedSamples.remove(i);
samples.remove(i);
}
else {
planeInfo.add(0, info[i]);
}
}
info = planeInfo.toArray(new OMETIFFPlane[0][0]);
// meta.getOmeMeta().populateImageMetadata();
}
// -- Helper methods --
private String normalizeFilename(final String dir, final String name) {
final File file = new File(dir, name);
if (file.exists()) return file.getAbsolutePath();
return name;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Reader extends ByteArrayReader<Metadata> {
// -- Reader API Methods --
@Override
public long getOptimalTileWidth(final int imageIndex) {
return getMetadata().getTileWidth()[imageIndex];
}
@Override
public long getOptimalTileHeight(final int imageIndex) {
return getMetadata().getTileHeight()[imageIndex];
}
@Override
public String[] getDomains() {
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
return getMetadata().isHasSPW() ? new String[] { FormatTools.HCS_DOMAIN }
: FormatTools.NON_SPECIAL_DOMAINS;
}
@Override
public ByteArrayPlane openPlane(final int imageIndex,
final long planeIndex, final ByteArrayPlane plane, final long[] offsets,
final long[] lengths, final SCIFIOConfig config)
throws io.scif.FormatException, IOException
{
final Metadata meta = getMetadata();
final byte[] buf = plane.getBytes();
final OMETIFFPlane[][] info = meta.getPlaneInfo();
FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex,
buf.length, offsets, lengths);
meta.setLastPlane(planeIndex);
final int i = info[imageIndex][(int) planeIndex].ifd;
final MinimalTIFFFormat.Reader<?> r =
info[imageIndex][(int) planeIndex].reader;
if (r.getCurrentFile() == null) {
r.setSource(info[imageIndex][(int) planeIndex].id);
}
final IFDList ifdList = r.getMetadata().getIfds();
if (i >= ifdList.size()) {
log()
.warn("Error untangling IFDs; the OME-TIFF file may be malformed.");
return plane;
}
final IFD ifd = ifdList.get(i);
final RandomAccessInputStream s =
new RandomAccessInputStream(getContext(),
info[imageIndex][(int) planeIndex].id);
final TiffParser p = new TiffParser(getContext(), s);
final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X), yIndex =
meta.get(imageIndex).getAxisIndex(Axes.Y);
final int x = (int) offsets[xIndex], y = (int) offsets[yIndex], w =
(int) lengths[xIndex], h = (int) lengths[yIndex];
p.getSamples(ifd, buf, x, y, w, h);
s.close();
return plane;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
@Override
public boolean hasCompanionFiles() {
return true;
}
@Override
protected String[] createDomainArray() {
return FormatTools.NON_GRAPHICS_DOMAINS;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Writer extends TIFFFormat.Writer<Metadata> {
// -- Constants --
private static final String WARNING_COMMENT =
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
URL_OME_TIFF + ". -->";
// -- Fields --
private List<Integer> imageMap;
private String[][] imageLocations;
private OMEXMLMetadata omeMeta;
private OMEXMLService service;
private final Map<String, Integer> ifdCounts =
new HashMap<String, Integer>();
private final Map<String, String> uuids = new HashMap<String, String>();
// -- Writer API Methods --
/* @see IFormatHandler#setId(String) */
@Override
public void
setDest(final RandomAccessOutputStream out, final int imageIndex)
throws FormatException, IOException
{
// TODO if already set, return
super.setDest(out, imageIndex);
if (imageLocations == null) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
imageLocations = new String[r.getImageCount()][];
for (int i = 0; i < imageLocations.length; i++) {
imageLocations[i] = new String[planeCount(imageIndex)];
}
}
}
/*
* @see io.scif.Writer#savePlane(int, int, io.scif.Plane, int, int, int, int)
*/
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane, final long[] offsets, final long[] lengths)
throws FormatException, IOException
{
savePlane(imageIndex, planeIndex, plane, null, offsets, lengths);
}
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane, final IFD ifd, final long[] offsets,
final long[] lengths) throws io.scif.FormatException, IOException
{
if (imageMap == null) imageMap = new ArrayList<Integer>();
if (!imageMap.contains(imageIndex)) {
imageMap.add(new Integer(imageIndex));
}
super.savePlane(imageIndex, planeIndex, plane, ifd, offsets, lengths);
// TODO should this be the output id?
imageLocations[imageIndex][(int) planeIndex] =
getMetadata().getDatasetName();
}
/* @see loci.formats.IFormatHandler#close() */
@Override
public void close() throws IOException {
try {
if (getStream() != null) {
setupServiceAndMetadata();
// remove any BinData elements from the OME-XML
service.removeBinData(omeMeta);
for (int series = 0; series < omeMeta.getImageCount(); series++) {
populateImage(omeMeta, series);
}
final List<String> files = new ArrayList<String>();
for (final String[] s : imageLocations) {
for (final String f : s) {
if (!files.contains(f) && f != null) {
files.add(f);
final String xml = getOMEXML(f);
// write OME-XML to the first IFD's comment
saveComment(f, xml);
}
}
}
}
}
catch (final ServiceException se) {
throw new RuntimeException(se);
}
catch (final FormatException fe) {
throw new RuntimeException(fe);
}
catch (final IllegalArgumentException iae) {
throw new RuntimeException(iae);
}
finally {
super.close();
boolean canReallyClose =
omeMeta == null || ifdCounts.size() == omeMeta.getImageCount();
if (omeMeta != null && canReallyClose) {
int omePlaneCount = 0;
for (int i = 0; i < omeMeta.getImageCount(); i++) {
final int sizeZ = omeMeta.getPixelsSizeZ(i).getValue();
final int sizeC = omeMeta.getPixelsSizeC(i).getValue();
final int sizeT = omeMeta.getPixelsSizeT(i).getValue();
omePlaneCount += sizeZ * sizeC * sizeT;
}
int ifdCount = 0;
for (final String key : ifdCounts.keySet()) {
ifdCount += ifdCounts.get(key);
}
canReallyClose = omePlaneCount == ifdCount;
}
if (canReallyClose) {
imageMap = null;
imageLocations = null;
omeMeta = null;
ifdCounts.clear();
}
else {
for (final String k : ifdCounts.keySet())
ifdCounts.put(k, 0);
}
}
}
// -- Helper methods --
/** Gets the UUID corresponding to the given filename. */
private String getUUID(final String filename) {
String uuid = uuids.get(filename);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
uuids.put(filename, uuid);
}
return uuid;
}
private void setupServiceAndMetadata() throws ServiceException {
// extract OME-XML string from metadata object
final MetadataRetrieve retrieve = getMetadata().getOmeMeta().getRoot();
final OMEXMLMetadata originalOMEMeta = service.getOMEMetadata(retrieve);
originalOMEMeta.resolveReferences();
final String omexml = service.getOMEXML(originalOMEMeta);
omeMeta = service.createOMEXMLMetadata(omexml);
}
private String getOMEXML(final String file) throws FormatException,
IOException
{
// generate UUID and add to OME element
final String uuid =
"urn:uuid:" + getUUID(new Location(getContext(), file).getName());
omeMeta.setUUID(uuid);
String xml;
try {
xml = service.getOMEXML(omeMeta);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
// insert warning comment
final String prefix = xml.substring(0, xml.indexOf(">") + 1);
final String suffix = xml.substring(xml.indexOf(">") + 1);
return prefix + WARNING_COMMENT + suffix;
}
private void saveComment(final String file, final String xml)
throws IOException, FormatException
{
if (getStream() != null) getStream().close();
setDest(new RandomAccessOutputStream(getContext(), file));
RandomAccessInputStream in = null;
try {
final TiffSaver saver = new TiffSaver(getContext(), getStream(), file);
saver.setBigTiff(isBigTiff());
in = new RandomAccessInputStream(getContext(), file);
saver.overwriteLastIFDOffset(in);
saver.overwriteComment(in, xml);
in.close();
}
catch (final FormatException exc) {
final IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
finally {
if (getStream() != null) getStream().close();
if (in != null) in.close();
}
}
private void populateTiffData(final OMEXMLMetadata omeMeta,
final long[] zct, final int ifd, final int series, final int plane)
{
omeMeta.setTiffDataFirstZ(new NonNegativeInteger((int) zct[0]), series,
plane);
omeMeta.setTiffDataFirstC(new NonNegativeInteger((int) zct[1]), series,
plane);
omeMeta.setTiffDataFirstT(new NonNegativeInteger((int) zct[2]), series,
plane);
omeMeta.setTiffDataIFD(new NonNegativeInteger(ifd), series, plane);
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(1), series, plane);
}
private void populateImage(final OMEXMLMetadata omeMeta,
final int imageIndex)
{
final String dimensionOrder =
omeMeta.getPixelsDimensionOrder(imageIndex).toString();
final int sizeZ =
omeMeta.getPixelsSizeZ(imageIndex).getValue().intValue();
int sizeC = omeMeta.getPixelsSizeC(imageIndex).getValue().intValue();
final int sizeT =
omeMeta.getPixelsSizeT(imageIndex).getValue().intValue();
final long planeCount = getMetadata().get(imageIndex).getPlaneCount();
final int ifdCount = imageMap.size();
if (planeCount == 0) {
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(0), imageIndex, 0);
return;
}
final PositiveInteger samplesPerPixel =
new PositiveInteger((int) ((sizeZ * sizeC * sizeT) / planeCount));
for (int c = 0; c < omeMeta.getChannelCount(imageIndex); c++) {
omeMeta.setChannelSamplesPerPixel(samplesPerPixel, imageIndex, c);
}
sizeC /= samplesPerPixel.getValue();
final long[] lengths =
metaService.zctToArray(dimensionOrder, sizeC, sizeC, sizeT);
int nextPlane = 0;
for (int plane = 0; plane < planeCount; plane++) {
metaService.zctToArray(dimensionOrder, sizeC, sizeC, sizeT);
final long[] zct = FormatTools.rasterToPosition(lengths, planeCount);
int planeIndex = plane;
if (imageLocations[imageIndex].length < planeCount) {
planeIndex /= (planeCount / imageLocations[imageIndex].length);
}
String filename = imageLocations[imageIndex][planeIndex];
if (filename != null) {
filename = new Location(getContext(), filename).getName();
final Integer ifdIndex = ifdCounts.get(filename);
final int ifd = ifdIndex == null ? 0 : ifdIndex.intValue();
omeMeta.setUUIDFileName(filename, imageIndex, nextPlane);
final String uuid = "urn:uuid:" + getUUID(filename);
omeMeta.setUUIDValue(uuid, imageIndex, nextPlane);
// fill in any non-default TiffData attributes
populateTiffData(omeMeta, zct, ifd, imageIndex, nextPlane);
ifdCounts.put(filename, ifd + 1);
nextPlane++;
}
}
}
private int planeCount(final int imageIndex) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
final int z = r.getPixelsSizeZ(imageIndex).getValue().intValue();
final int t = r.getPixelsSizeT(imageIndex).getValue().intValue();
int c = r.getChannelCount(imageIndex);
final String pixelType = r.getPixelsType(imageIndex).getValue();
final int bytes = FormatTools.getBytesPerPixel(pixelType);
if (bytes > 1 && c == 1) {
c = r.getChannelSamplesPerPixel(imageIndex, 0).getValue();
}
return z * c * t;
}
}
// -- Helper Methods --
private static boolean isSingleFile(final Context context, final String id)
throws FormatException, IOException
{
// parse and populate OME-XML metadata
final String fileName =
new Location(context, id).getAbsoluteFile().getAbsolutePath();
final RandomAccessInputStream ras =
new RandomAccessInputStream(context, fileName);
final TiffParser tp = new TiffParser(context, ras);
final IFD ifd = tp.getFirstIFD();
final long[] ifdOffsets = tp.getIFDOffsets();
ras.close();
final String xml = ifd.getComment();
OMEXMLMetadata meta;
try {
meta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
if (meta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
int nImages = 0;
for (int i = 0; i < meta.getImageCount(); i++) {
int nChannels = meta.getChannelCount(i);
if (nChannels == 0) nChannels = 1;
final int z = meta.getPixelsSizeZ(i).getValue().intValue();
final int t = meta.getPixelsSizeT(i).getValue().intValue();
nImages += z * t * nChannels;
}
return nImages <= ifdOffsets.length;
}
/**
* This class can be used for translating any io.scif.Metadata to Metadata for
* writing OME-TIFF. files.
* <p>
* Note that Metadata translated from Core is only write-safe.
* </p>
* <p>
* If trying to read, there should already exist an originally-parsed OME-TIFF
* Metadata object which can be used.
* </p>
* <p>
* Note also that any OME-TIFF image written must be reparsed, as the Metadata
* used to write it can not be guaranteed valid.
* </p>
*/
@Plugin(type = Translator.class, priority = OMETIFFFormat.PRIORITY)
public static class OMETIFFTranslator extends
AbstractTranslator<io.scif.Metadata, Metadata>
{
// -- Fields --
@Parameter
private FormatService formatService;
@Parameter
private TranslatorService translatorService;
// -- Translator API Methods --
@Override
public Class<? extends io.scif.Metadata> source() {
return io.scif.Metadata.class;
}
@Override
public Class<? extends io.scif.Metadata> dest() {
return Metadata.class;
}
@Override
public void translateFormatMetadata(final io.scif.Metadata source,
final Metadata dest)
{
if (dest.getOmeMeta() == null) {
final OMEMetadata omeMeta = new OMEMetadata(getContext());
translatorService.translate(source, omeMeta, false);
dest.setOmeMeta(omeMeta);
}
try {
final TIFFFormat.Metadata tiffMeta =
(TIFFFormat.Metadata) formatService.getFormatFromClass(
TIFFFormat.class).createMetadata();
translatorService.translate(source, tiffMeta, false);
dest.setFirstIFD(tiffMeta.getIfds().get(0));
}
catch (final FormatException e) {
log().error("Failed to generate TIFF data", e);
}
final OMETIFFPlane[][] info = new OMETIFFPlane[source.getImageCount()][];
dest.setPlaneInfo(info);
final List<Integer> samples = new ArrayList<Integer>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
dest.samples = samples;
dest.adjustedSamples = adjustedSamples;
dest.createImageMetadata(0);
for (int i = 0; i < source.getImageCount(); i++) {
info[i] = new OMETIFFPlane[(int) source.get(i).getPlaneCount()];
for (int j = 0; j < source.get(i).getPlaneCount(); j++) {
info[i][j] = new OMETIFFPlane();
}
dest.add(new DefaultImageMetadata());
samples.add((int) (source.get(i).isMultichannel() ? source.get(i)
.getAxisLength(Axes.CHANNEL) : 1));
adjustedSamples.add(false);
}
}
@Override
protected void translateImageMetadata(final List<ImageMetadata> source,
final Metadata dest)
{
// No implementation necessary. See translateFormatMetadata
}
}
// -- Helper classes --
/** Structure containing details on where to find a particular image plane. */
private static class OMETIFFPlane {
/** Reader to use for accessing this plane. */
public MinimalTIFFFormat.Reader<?> reader;
/** File containing this plane. */
public String id;
/** IFD number of this plane. */
public int ifd = -1;
/** Certainty flag, for dealing with unspecified NumPlanes. */
public boolean certain = false;
}
}
| src/main/java/io/scif/ome/formats/OMETIFFFormat.java | /*
* #%L
* SCIFIO support for the OME data model, including OME-XML and OME-TIFF.
* %%
* Copyright (C) 2013 - 2014 Board of Regents of the University of
* Wisconsin-Madison
* %%
* 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.
*
* 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 HOLDERS 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.
* #L%
*/
package io.scif.ome.formats;
import io.scif.AbstractChecker;
import io.scif.AbstractFormat;
import io.scif.AbstractParser;
import io.scif.AbstractTranslator;
import io.scif.ByteArrayPlane;
import io.scif.ByteArrayReader;
import io.scif.DefaultImageMetadata;
import io.scif.Format;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.Plane;
import io.scif.Translator;
import io.scif.config.SCIFIOConfig;
import io.scif.formats.MinimalTIFFFormat;
import io.scif.formats.TIFFFormat;
import io.scif.formats.tiff.IFD;
import io.scif.formats.tiff.IFDList;
import io.scif.formats.tiff.PhotoInterp;
import io.scif.formats.tiff.TiffIFDEntry;
import io.scif.formats.tiff.TiffParser;
import io.scif.formats.tiff.TiffSaver;
import io.scif.io.Location;
import io.scif.io.RandomAccessInputStream;
import io.scif.io.RandomAccessOutputStream;
import io.scif.ome.OMEMetadata;
import io.scif.ome.services.OMEMetadataService;
import io.scif.ome.services.OMEXMLService;
import io.scif.services.FormatService;
import io.scif.services.TranslatorService;
import io.scif.util.FormatTools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
import loci.common.services.ServiceException;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.meta.MetadataStore;
import loci.formats.ome.OMEXMLMetadata;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveFloat;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import org.scijava.Context;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* OMETiffReader is the file format reader for <a
* href="http://ome-xml.org/wiki/OmeTiff">OME-TIFF</a> files.
*
* @author Mark Hiner hinerm at gmail.com
*/
@Plugin(type = Format.class, priority = OMETIFFFormat.PRIORITY)
public class OMETIFFFormat extends AbstractFormat {
// -- Constants --
public static final String URL_OME_TIFF =
"http://www.openmicroscopy.org/site/support/ome-model/ome-tiff/";
public static final double PRIORITY = TIFFFormat.PRIORITY + 1;
// -- Fields --
// FIXME: These should not be static.
private static OMEXMLService service;
private static OMEMetadataService metaService;
// -- Format API Methods --
@Override
public String getFormatName() {
return "OME-TIFF";
}
@Override
protected String[] makeSuffixArray() {
return new String[] { "ome.tif", "ome.tiff" };
}
// -- Nested Classes --
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Metadata extends TIFFFormat.Metadata {
// -- Fields --
/** Mapping from series and plane numbers to files and IFD entries. */
protected OMETIFFPlane[][] info; // dimensioned [numSeries][numPlanes]
private IFD firstIFD;
private List<Integer> samples;
private List<Boolean> adjustedSamples;
/** List of used files. */
protected String[] used;
// TODO maybe this should be an o mexmlmetadata...
private OMEMetadata omeMeta;
private long lastPlane = 0;
private boolean hasSPW;
private int[] tileWidth;
private int[] tileHeight;
// -- OMETIFF Metadata API methods --
/**
* Returns a MetadataStore that is populated in such a way as to produce
* valid OME-XML. The returned MetadataStore cannot be used by an
* IFormatWriter, as it will not contain the required BinData.BigEndian
* attributes.
*/
public MetadataStore getMetadataStoreForDisplay() {
final MetadataStore store = omeMeta.getRoot();
if (service.isOMEXMLMetadata(store)) {
service.removeBinData((OMEXMLMetadata) store);
for (int i = 0; i < getImageCount(); i++) {
if (((OMEXMLMetadata) store).getTiffDataCount(i) == 0) {
service.addMetadataOnly((OMEXMLMetadata) store, i);
}
}
}
return store;
}
/**
* Returns a MetadataStore that is populated in such a way as to be usable
* by an IFormatWriter. Any OME-XML generated from this MetadataStore is
* <em>very unlikely</em> to be valid, as more than likely both BinData and
* TiffData element will be present.
*/
public MetadataStore getMetadataStoreForConversion() {
final MetadataStore store = omeMeta.getRoot();
for (int i = 0; i < getImageCount(); i++) {
store.setPixelsBinDataBigEndian(new Boolean(!get(i).isLittleEndian()),
i, 0);
}
return store;
}
// -- OMETIFFMetadata getters and setters --
public OMETIFFPlane[][] getPlaneInfo() {
return info;
}
public void setPlaneInfo(final OMETIFFPlane[][] info) {
this.info = info;
}
public String[] getUsed() {
return used;
}
public void setUsed(final String[] used) {
this.used = used;
}
public OMEMetadata getOmeMeta() {
return omeMeta;
}
public void setOmeMeta(final OMEMetadata omeMeta) {
this.omeMeta = omeMeta;
}
@Override
public long getLastPlane() {
return lastPlane;
}
@Override
public void setLastPlane(final long lastPlane) {
this.lastPlane = lastPlane;
}
public IFD getFirstIFD() {
return firstIFD;
}
public void setFirstIFD(final IFD firstIFD) {
this.firstIFD = firstIFD;
}
public boolean isHasSPW() {
return hasSPW;
}
public void setHasSPW(final boolean hasSPW) {
this.hasSPW = hasSPW;
}
public int[] getTileWidth() {
return tileWidth;
}
public void setTileWidth(final int[] tileWidth) {
this.tileWidth = tileWidth;
}
public int[] getTileHeight() {
return tileHeight;
}
public void setTileHeight(final int[] tileHeight) {
this.tileHeight = tileHeight;
}
// -- Metadata API Methods --
/*
* @see io.scif.Metadata#populateImageMetadata()
*/
@Override
public void populateImageMetadata() {
// populate core metadata
final OMEXMLMetadata omexmlMeta = getOmeMeta().getRoot();
for (int s = 0; s < getImageCount(); s++) {
final ImageMetadata m = get(s);
try {
m.setPlanarAxisCount(2);
m.setAxisLength(Axes.X, omexmlMeta.getPixelsSizeX(s).getValue()
.intValue());
final int tiffWidth = (int) firstIFD.getImageWidth();
if (m.getAxisLength(Axes.X) != tiffWidth && s == 0) {
log().warn(
"SizeX mismatch: OME=" + m.getAxisLength(Axes.X) + ", TIFF=" +
tiffWidth);
}
m.setAxisLength(Axes.Y, omexmlMeta.getPixelsSizeY(s).getValue()
.intValue());
final int tiffHeight = (int) firstIFD.getImageLength();
if (m.getAxisLength(Axes.Y) != tiffHeight && s == 0) {
log().warn(
"SizeY mismatch: OME=" + m.getAxisLength(Axes.Y) + ", TIFF=" +
tiffHeight);
}
m.setAxisLength(Axes.Z, omexmlMeta.getPixelsSizeZ(s).getValue()
.intValue());
m.setAxisLength(Axes.CHANNEL, omexmlMeta.getPixelsSizeC(s).getValue()
.intValue());
m.setAxisLength(Axes.TIME, omexmlMeta.getPixelsSizeT(s).getValue()
.intValue());
m.setPixelType(FormatTools.pixelTypeFromString(omexmlMeta
.getPixelsType(s).toString()));
final int tiffPixelType = firstIFD.getPixelType();
if (m.getPixelType() != tiffPixelType &&
(s == 0 || adjustedSamples.get(s)))
{
log().warn(
"PixelType mismatch: OME=" + m.getPixelType() + ", TIFF=" +
tiffPixelType);
m.setPixelType(tiffPixelType);
}
m.setBitsPerPixel(FormatTools.getBitsPerPixel(m.getPixelType()));
String dimensionOrder =
omexmlMeta.getPixelsDimensionOrder(s).toString();
// hackish workaround for files exported by OMERO that have an
// incorrect dimension order
String uuidFileName = "";
try {
if (omexmlMeta.getTiffDataCount(s) > 0) {
uuidFileName = omexmlMeta.getUUIDFileName(s, 0);
}
}
catch (final NullPointerException e) {}
if (omexmlMeta.getChannelCount(s) > 0 &&
omexmlMeta.getChannelName(s, 0) == null &&
omexmlMeta.getTiffDataCount(s) > 0 &&
uuidFileName.indexOf("__omero_export") != -1)
{
dimensionOrder = "XYZCT";
}
m.setAxisTypes(metaService.findDimensionList(dimensionOrder));
m.setOrderCertain(true);
final PhotoInterp photo = firstIFD.getPhotometricInterpretation();
if (samples.get(s) > 1 || photo == PhotoInterp.RGB) {
m.setPlanarAxisCount(3);
}
if ((samples.get(s) != m.getAxisLength(Axes.CHANNEL) &&
(samples.get(s) % m.getAxisLength(Axes.CHANNEL)) != 0 && (m
.getAxisLength(Axes.CHANNEL) % samples.get(s)) != 0) ||
m.getAxisLength(Axes.CHANNEL) == 1 || adjustedSamples.get(s))
{
m.setAxisLength(Axes.CHANNEL, m.getAxisLength(Axes.CHANNEL) *
samples.get(s));
}
if (m.getAxisLength(Axes.Z) * m.getAxisLength(Axes.TIME) *
m.getAxisLength(Axes.CHANNEL) > info[s].length &&
!m.isMultichannel())
{
if (m.getAxisLength(Axes.Z) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.TIME) == info[s].length) {
m.setAxisLength(Axes.Z, 1);
m.setAxisLength(Axes.CHANNEL, 1);
}
else if (m.getAxisLength(Axes.CHANNEL) == info[s].length) {
m.setAxisLength(Axes.TIME, 1);
m.setAxisLength(Axes.Z, 1);
}
}
if (omexmlMeta.getPixelsBinDataCount(s) > 1) {
log().warn(
"OME-TIFF Pixels element contains BinData elements! "
+ "Ignoring.");
}
m.setLittleEndian(firstIFD.isLittleEndian());
m.setIndexed(photo == PhotoInterp.RGB_PALETTE &&
firstIFD.getIFDValue(IFD.COLOR_MAP) != null);
m.setFalseColor(true);
m.setMetadataComplete(true);
}
catch (final NullPointerException exc) {
log().error("Incomplete Pixels metadata", exc);
}
catch (final FormatException exc) {
log().error("Format exception when creating ImageMetadata", exc);
}
// Set the physical pixel sizes
FormatTools.calibrate(m.getAxis(Axes.X), getValue(omexmlMeta
.getPixelsPhysicalSizeX(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Y), getValue(omexmlMeta
.getPixelsPhysicalSizeY(s)), 0.0);
FormatTools.calibrate(m.getAxis(Axes.Z), getValue(omexmlMeta
.getPixelsPhysicalSizeZ(s)), 0.0);
}
// if (getImageCount() == 1) {
// CoreMetadata ms0 = core.get(0);
// ms0.sizeZ = 1;
// if (!ms0.rgb) {
// ms0.sizeC = 1;
// }
// ms0.sizeT = 1;
// }
// metaService.populatePixels(getOmeMeta().getRoot(), this, false, false);
getOmeMeta().setRoot((OMEXMLMetadata) getMetadataStoreForConversion());
}
@Override
public void close(final boolean fileOnly) throws IOException {
super.close(fileOnly);
if (info != null) {
for (final OMETIFFPlane[] dimension : info) {
for (final OMETIFFPlane plane : dimension) {
if (plane.reader != null) {
try {
plane.reader.close();
}
catch (final Exception e) {
log().error("Plane closure failure!", e);
}
}
}
}
}
if (!fileOnly) {
info = null;
lastPlane = 0;
tileWidth = null;
tileHeight = null;
}
}
// -- HasColorTable API Methods --
@Override
public ColorTable
getColorTable(final int imageIndex, final long planeIndex)
{
if (info[imageIndex][(int) lastPlane] == null ||
info[imageIndex][(int) lastPlane].reader == null ||
info[imageIndex][(int) lastPlane].id == null)
{
return null;
}
try {
info[imageIndex][(int) lastPlane].reader
.setSource(info[imageIndex][(int) lastPlane].id);
return info[imageIndex][(int) lastPlane].reader.getMetadata()
.getColorTable(imageIndex, planeIndex);
}
catch (final IOException e) {
log().error("IOException when trying to read color table", e);
return null;
}
}
/**
* Helper method to extract values out of {@link PositiveFloat}s, for
* physical pixel sizes (calibration values). Returns 1.0 if given a null or
* invalid (< 0) calibration.
*/
private double getValue(PositiveFloat pixelPhysicalSize) {
if (pixelPhysicalSize == null) return 1.0;
Double physSize = pixelPhysicalSize.getValue();
if (physSize < 0) return 1.0;
return physSize;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Checker extends AbstractChecker {
// -- Checker API Methods --
@Override
public boolean suffixNecessary() {
return false;
}
@Override
public boolean suffixSufficient() {
return false;
}
@Override
public boolean isFormat(final RandomAccessInputStream stream)
throws IOException
{
final TiffParser tp = new TiffParser(getContext(), stream);
tp.setDoCaching(false);
final boolean validHeader = tp.isValidHeader();
if (!validHeader) return false;
// look for OME-XML in first IFD's comment
final IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
final Object description = ifd.get(IFD.IMAGE_DESCRIPTION);
if (description == null) {
return false;
}
String comment = null;
if (description instanceof TiffIFDEntry) {
comment = tp.getIFDValue((TiffIFDEntry) description).toString();
}
else if (description instanceof String) {
comment = (String) description;
}
if (comment == null || comment.trim().length() == 0) return false;
comment = comment.trim();
// do a basic sanity check before attempting to parse the comment as XML
// the parsing step is a bit slow, so there is no sense in trying unless
// we are reasonably sure that the comment contains XML
if (!comment.startsWith("<") || !comment.endsWith(">")) {
return false;
}
try {
if (service == null) setupServices(getContext());
final IMetadata meta = service.createOMEXMLMetadata(comment);
for (int i = 0; i < meta.getImageCount(); i++) {
meta.setPixelsBinDataBigEndian(Boolean.TRUE, i, 0);
metaService.verifyMinimumPopulated(meta, i);
}
return meta.getImageCount() > 0;
}
catch (final ServiceException se) {
log().debug("OME-XML parsing failed", se);
}
catch (final NullPointerException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
catch (final IndexOutOfBoundsException e) {
log().debug("OME-XML parsing failed", e);
}
return false;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Parser extends AbstractParser<Metadata> {
// -- Fields --
@Parameter
private FormatService formatService;
// -- Parser API Methods --
@Override
public String[] getImageUsedFiles(final int imageIndex,
final boolean noPixels)
{
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
if (noPixels) return null;
final Vector<String> usedFiles = new Vector<String>();
for (int i = 0; i < getMetadata().info[imageIndex].length; i++) {
if (!usedFiles.contains(getMetadata().info[imageIndex][i].id)) {
usedFiles.add(getMetadata().info[imageIndex][i].id);
}
}
return usedFiles.toArray(new String[usedFiles.size()]);
}
@Override
public Metadata parse(final String fileName, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, fileName), meta, config);
}
@Override
public Metadata parse(final File file, final Metadata meta,
final SCIFIOConfig config) throws IOException, FormatException
{
return super.parse(normalizeFilename(null, file.getPath()), meta, config);
}
@Override
public int fileGroupOption(final String id) throws FormatException,
IOException
{
final boolean single = isSingleFile(id);
return single ? FormatTools.CAN_GROUP : FormatTools.MUST_GROUP;
}
@Override
public Metadata parse(final RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
FormatException
{
super.parse(stream, meta, config);
for (int s = 0; s < meta.getImageCount(); s++) {
final OMETIFFPlane[][] info = meta.getPlaneInfo();
try {
if (!info[s][0].reader.getFormat().createChecker().isFormat(
info[s][0].id))
{
info[s][0].id = meta.getSource().getFileName();
}
for (int plane = 0; plane < info[s].length; plane++) {
if (!info[s][plane].reader.getFormat().createChecker().isFormat(
info[s][plane].id))
{
info[s][plane].id = info[s][0].id;
}
}
info[s][0].reader.setSource(info[s][0].id);
meta.getTileWidth()[s] =
(int) info[s][0].reader.getOptimalTileWidth(s);
meta.getTileHeight()[s] =
(int) info[s][0].reader.getOptimalTileHeight(s);
}
catch (final FormatException e) {
log().debug("OME-XML parsing failed", e);
}
}
return meta;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
// -- Abstract Parser API Methods --
@Override
protected void typedParse(final io.scif.io.RandomAccessInputStream stream,
final Metadata meta, final SCIFIOConfig config) throws IOException,
io.scif.FormatException
{
// normalize file name
final String id = stream.getFileName();
final String dir = new File(id).getParent();
// parse and populate OME-XML metadata
String fileName =
new Location(getContext(), id).getAbsoluteFile().getAbsolutePath();
if (!new File(fileName).exists()) {
fileName = stream.getFileName();
}
final RandomAccessInputStream ras =
new RandomAccessInputStream(getContext(), fileName);
String xml;
IFD firstIFD;
try {
final TiffParser tp = new TiffParser(getContext(), ras);
firstIFD = tp.getFirstIFD();
xml = firstIFD.getComment();
}
finally {
ras.close();
}
meta.setFirstIFD(firstIFD);
if (service == null) setupServices(getContext());
OMEXMLMetadata omexmlMeta;
try {
omexmlMeta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
meta.setHasSPW(omexmlMeta.getPlateCount() > 0);
for (int i = 0; i < meta.getImageCount(); i++) {
final int sizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
service.removeChannels(omexmlMeta, i, sizeC);
}
final Hashtable<String, Object> originalMetadata =
service.getOriginalMetadata(omexmlMeta);
if (originalMetadata != null) meta.getTable().putAll(originalMetadata);
log().trace(xml);
if (omexmlMeta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
meta.setOmeMeta(new OMEMetadata(getContext(), omexmlMeta));
final String[] acquiredDates = new String[meta.getImageCount()];
for (int i = 0; i < acquiredDates.length; i++) {
final Timestamp acquisitionDate = omexmlMeta.getImageAcquisitionDate(i);
if (acquisitionDate != null) {
acquiredDates[i] = acquisitionDate.getValue();
}
}
final String currentUUID = omexmlMeta.getUUID();
// determine series count from Image and Pixels elements
final int imageCount = omexmlMeta.getImageCount();
meta.createImageMetadata(imageCount);
OMETIFFPlane[][] info = new OMETIFFPlane[imageCount][];
meta.setPlaneInfo(info);
final int[] tileWidth = new int[imageCount];
final int[] tileHeight = new int[imageCount];
meta.setTileWidth(tileWidth);
meta.setTileHeight(tileHeight);
// compile list of file/UUID mappings
final Hashtable<String, String> files = new Hashtable<String, String>();
boolean needSearch = false;
for (int i = 0; i < imageCount; i++) {
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
for (int td = 0; td < tiffDataCount; td++) {
String uuid = null;
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {}
String filename = null;
if (uuid == null) {
// no UUID means that TiffData element refers to this file
uuid = "";
filename = id;
}
else {
filename = omexmlMeta.getUUIDFileName(i, td);
if (!new Location(getContext(), dir, filename).exists()) filename =
null;
if (filename == null) {
if (uuid.equals(currentUUID) || currentUUID == null) {
// UUID references this file
filename = id;
}
else {
// will need to search for this UUID
filename = "";
needSearch = true;
}
}
else filename = normalizeFilename(dir, filename);
}
final String existing = files.get(uuid);
if (existing == null) files.put(uuid, filename);
else if (!existing.equals(filename)) {
throw new FormatException("Inconsistent UUID filenames");
}
}
}
// search for missing filenames
if (needSearch) {
final Enumeration<String> en = files.keys();
while (en.hasMoreElements()) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
if (filename.equals("")) {
// TODO search...
// should scan only other .ome.tif files
// to make this work with OME server may be a little tricky?
throw new FormatException("Unmatched UUID: " + uuid);
}
}
}
// build list of used files
final Enumeration<String> en = files.keys();
final int numUUIDs = files.size();
final HashSet<String> fileSet = new HashSet<String>(); // ensure no
// duplicate
// filenames
for (int i = 0; i < numUUIDs; i++) {
final String uuid = en.nextElement();
final String filename = files.get(uuid);
fileSet.add(filename);
}
final String[] used = new String[fileSet.size()];
meta.setUsed(used);
final Iterator<String> iter = fileSet.iterator();
for (int i = 0; i < used.length; i++)
used[i] = iter.next();
// process TiffData elements
final Hashtable<String, MinimalTIFFFormat.Reader<?>> readers =
new Hashtable<String, MinimalTIFFFormat.Reader<?>>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
final List<Integer> samples = new ArrayList<Integer>();
meta.adjustedSamples = adjustedSamples;
meta.samples = samples;
for (int i = 0; i < imageCount; i++) {
final int s = i;
log().debug("Image[" + i + "] {");
log().debug(" id = " + omexmlMeta.getImageID(i));
adjustedSamples.add(false);
final String order = omexmlMeta.getPixelsDimensionOrder(i).toString();
PositiveInteger samplesPerPixel = null;
if (omexmlMeta.getChannelCount(i) > 0) {
samplesPerPixel = omexmlMeta.getChannelSamplesPerPixel(i, 0);
}
samples.add(i, samplesPerPixel == null ? -1 : samplesPerPixel
.getValue());
final int tiffSamples = firstIFD.getSamplesPerPixel();
if (adjustedSamples.get(i) ||
(samples.get(i) != tiffSamples && (i == 0 || samples.get(i) < 0)))
{
log().warn(
"SamplesPerPixel mismatch: OME=" + samples.get(i) + ", TIFF=" +
tiffSamples);
samples.set(i, tiffSamples);
adjustedSamples.set(i, true);
}
else {
adjustedSamples.set(i, false);
}
if (adjustedSamples.get(i) && omexmlMeta.getChannelCount(i) <= 1) {
adjustedSamples.set(i, false);
}
int effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
if (!adjustedSamples.get(i)) {
effSizeC /= samples.get(i);
}
if (effSizeC == 0) effSizeC = 1;
if (effSizeC * samples.get(i) != omexmlMeta.getPixelsSizeC(i)
.getValue().intValue())
{
effSizeC = omexmlMeta.getPixelsSizeC(i).getValue().intValue();
}
final int sizeT = omexmlMeta.getPixelsSizeT(i).getValue().intValue();
final int sizeZ = omexmlMeta.getPixelsSizeZ(i).getValue().intValue();
int num = effSizeC * sizeT * sizeZ;
OMETIFFPlane[] planes = new OMETIFFPlane[num];
for (int no = 0; no < num; no++)
planes[no] = new OMETIFFPlane();
final int tiffDataCount = omexmlMeta.getTiffDataCount(i);
Boolean zOneIndexed = null;
Boolean cOneIndexed = null;
Boolean tOneIndexed = null;
// pre-scan TiffData indices to see if any of them are indexed from 1
for (int td = 0; td < tiffDataCount; td++) {
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
final int c = firstC == null ? 0 : firstC.getValue();
final int t = firstT == null ? 0 : firstT.getValue();
final int z = firstZ == null ? 0 : firstZ.getValue();
if (c >= effSizeC && cOneIndexed == null) {
cOneIndexed = true;
}
else if (c == 0) {
cOneIndexed = false;
}
if (z >= sizeZ && zOneIndexed == null) {
zOneIndexed = true;
}
else if (z == 0) {
zOneIndexed = false;
}
if (t >= sizeT && tOneIndexed == null) {
tOneIndexed = true;
}
else if (t == 0) {
tOneIndexed = false;
}
}
for (int td = 0; td < tiffDataCount; td++) {
log().debug(" TiffData[" + td + "] {");
// extract TiffData parameters
String filename = null;
String uuid = null;
try {
filename = omexmlMeta.getUUIDFileName(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving filename.");
}
try {
uuid = omexmlMeta.getUUIDValue(i, td);
}
catch (final NullPointerException e) {
log().debug("Ignoring null UUID object when retrieving value.");
}
final NonNegativeInteger tdIFD = omexmlMeta.getTiffDataIFD(i, td);
final int ifd = tdIFD == null ? 0 : tdIFD.getValue();
final NonNegativeInteger numPlanes =
omexmlMeta.getTiffDataPlaneCount(i, td);
final NonNegativeInteger firstC = omexmlMeta.getTiffDataFirstC(i, td);
final NonNegativeInteger firstT = omexmlMeta.getTiffDataFirstT(i, td);
final NonNegativeInteger firstZ = omexmlMeta.getTiffDataFirstZ(i, td);
int c = firstC == null ? 0 : firstC.getValue();
int t = firstT == null ? 0 : firstT.getValue();
int z = firstZ == null ? 0 : firstZ.getValue();
// NB: some writers index FirstC, FirstZ and FirstT from 1
if (cOneIndexed != null && cOneIndexed) c--;
if (zOneIndexed != null && zOneIndexed) z--;
if (tOneIndexed != null && tOneIndexed) t--;
if (z >= sizeZ || c >= effSizeC || t >= sizeT) {
log().warn(
"Found invalid TiffData: Z=" + z + ", C=" + c + ", T=" + t);
break;
}
final long[] pos = metaService.zctToArray(order, z, c, t);
final long[] lengths =
metaService.zctToArray(order, sizeZ, effSizeC, sizeT);
final long index = FormatTools.positionToRaster(lengths, pos);
final int count = numPlanes == null ? 1 : numPlanes.getValue();
if (count == 0) {
meta.get(s);
break;
}
// get reader object for this filename
if (filename == null) {
if (uuid == null) filename = id;
else filename = files.get(uuid);
}
else filename = normalizeFilename(dir, filename);
MinimalTIFFFormat.Reader<?> r = readers.get(filename);
if (r == null) {
r =
(io.scif.formats.MinimalTIFFFormat.Reader<?>) formatService
.getFormatFromClass(MinimalTIFFFormat.class).createReader();
readers.put(filename, r);
}
final Location file = new Location(getContext(), filename);
if (!file.exists()) {
// if this is an absolute file name, try using a relative name
// old versions of OMETiffWriter wrote an absolute path to
// UUID.FileName, which causes problems if the file is moved to
// a different directory
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
filename = dir + File.separator + filename;
if (!new Location(getContext(), filename).exists()) {
filename = stream.getFileName();
}
}
// populate plane index -> IFD mapping
for (int q = 0; q < count; q++) {
final int no = (int) (index + q);
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = ifd + q;
planes[no].certain = true;
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
}
if (numPlanes == null) {
// unknown number of planes; fill down
for (int no = (int) (index + 1); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = r;
planes[no].id = filename;
planes[no].ifd = planes[no - 1].ifd + 1;
log().debug(" Plane[" + no + "]: FILLED");
}
}
else {
// known number of planes; clear anything subsequently filled
for (int no = (int) (index + count); no < num; no++) {
if (planes[no].certain) break;
planes[no].reader = null;
planes[no].id = null;
planes[no].ifd = -1;
log().debug(" Plane[" + no + "]: CLEARED");
}
}
log().debug(" }");
}
if (meta.get(s) == null) continue;
// verify that all planes are available
log().debug(" --------------------------------");
for (int no = 0; no < num; no++) {
log().debug(
" Plane[" + no + "]: file=" + planes[no].id + ", IFD=" +
planes[no].ifd);
if (planes[no].reader == null) {
log().warn(
"Image ID '" + omexmlMeta.getImageID(i) + "': missing plane #" +
no + ". " +
"Using TiffReader to determine the number of planes.");
final TIFFFormat.Reader<?> r =
(io.scif.formats.TIFFFormat.Reader<?>) formatService
.getFormatFromClass(TIFFFormat.class).createReader();
r.setSource(stream.getFileName());
try {
planes = new OMETIFFPlane[r.getImageCount()];
for (int plane = 0; plane < planes.length; plane++) {
planes[plane] = new OMETIFFPlane();
planes[plane].id = stream.getFileName();
planes[plane].reader = r;
planes[plane].ifd = plane;
}
num = planes.length;
}
finally {
r.close();
}
}
}
info[i] = planes;
log().debug(" }");
}
// remove null CoreMetadata entries
final Vector<OMETIFFPlane[]> planeInfo = new Vector<OMETIFFPlane[]>();
for (int i = meta.getImageCount() - 1; i >= 0; i--) {
if (meta.get(i) == null) {
meta.getAll().remove(i);
adjustedSamples.remove(i);
samples.remove(i);
}
else {
planeInfo.add(0, info[i]);
}
}
info = planeInfo.toArray(new OMETIFFPlane[0][0]);
// meta.getOmeMeta().populateImageMetadata();
}
// -- Helper methods --
private String normalizeFilename(final String dir, final String name) {
final File file = new File(dir, name);
if (file.exists()) return file.getAbsolutePath();
return name;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Reader extends ByteArrayReader<Metadata> {
// -- Reader API Methods --
@Override
public long getOptimalTileWidth(final int imageIndex) {
return getMetadata().getTileWidth()[imageIndex];
}
@Override
public long getOptimalTileHeight(final int imageIndex) {
return getMetadata().getTileHeight()[imageIndex];
}
@Override
public String[] getDomains() {
FormatTools.assertId(getMetadata().getDatasetName(), true, 1);
return getMetadata().isHasSPW() ? new String[] { FormatTools.HCS_DOMAIN }
: FormatTools.NON_SPECIAL_DOMAINS;
}
@Override
public ByteArrayPlane openPlane(final int imageIndex,
final long planeIndex, final ByteArrayPlane plane, final long[] offsets,
final long[] lengths, final SCIFIOConfig config)
throws io.scif.FormatException, IOException
{
final Metadata meta = getMetadata();
final byte[] buf = plane.getBytes();
final OMETIFFPlane[][] info = meta.getPlaneInfo();
FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex,
buf.length, offsets, lengths);
meta.setLastPlane(planeIndex);
final int i = info[imageIndex][(int) planeIndex].ifd;
final MinimalTIFFFormat.Reader<?> r =
info[imageIndex][(int) planeIndex].reader;
if (r.getCurrentFile() == null) {
r.setSource(info[imageIndex][(int) planeIndex].id);
}
final IFDList ifdList = r.getMetadata().getIfds();
if (i >= ifdList.size()) {
log()
.warn("Error untangling IFDs; the OME-TIFF file may be malformed.");
return plane;
}
final IFD ifd = ifdList.get(i);
final RandomAccessInputStream s =
new RandomAccessInputStream(getContext(),
info[imageIndex][(int) planeIndex].id);
final TiffParser p = new TiffParser(getContext(), s);
final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X), yIndex =
meta.get(imageIndex).getAxisIndex(Axes.Y);
final int x = (int) offsets[xIndex], y = (int) offsets[yIndex], w =
(int) lengths[xIndex], h = (int) lengths[yIndex];
p.getSamples(ifd, buf, x, y, w, h);
s.close();
return plane;
}
// -- Groupable API Methods --
@Override
public boolean isSingleFile(final String id) throws FormatException,
IOException
{
return OMETIFFFormat.isSingleFile(getContext(), id);
}
@Override
public boolean hasCompanionFiles() {
return true;
}
@Override
protected String[] createDomainArray() {
return FormatTools.NON_GRAPHICS_DOMAINS;
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*/
public static class Writer extends TIFFFormat.Writer<Metadata> {
// -- Constants --
private static final String WARNING_COMMENT =
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
URL_OME_TIFF + ". -->";
// -- Fields --
private List<Integer> imageMap;
private String[][] imageLocations;
private OMEXMLMetadata omeMeta;
private OMEXMLService service;
private final Map<String, Integer> ifdCounts =
new HashMap<String, Integer>();
private final Map<String, String> uuids = new HashMap<String, String>();
// -- Writer API Methods --
/* @see IFormatHandler#setId(String) */
@Override
public void
setDest(final RandomAccessOutputStream out, final int imageIndex)
throws FormatException, IOException
{
// TODO if already set, return
super.setDest(out, imageIndex);
if (imageLocations == null) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
imageLocations = new String[r.getImageCount()][];
for (int i = 0; i < imageLocations.length; i++) {
imageLocations[i] = new String[planeCount(imageIndex)];
}
}
}
/*
* @see io.scif.Writer#savePlane(int, int, io.scif.Plane, int, int, int, int)
*/
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane, final long[] offsets, final long[] lengths)
throws FormatException, IOException
{
savePlane(imageIndex, planeIndex, plane, null, offsets, lengths);
}
@Override
public void savePlane(final int imageIndex, final long planeIndex,
final Plane plane, final IFD ifd, final long[] offsets,
final long[] lengths) throws io.scif.FormatException, IOException
{
if (imageMap == null) imageMap = new ArrayList<Integer>();
if (!imageMap.contains(imageIndex)) {
imageMap.add(new Integer(imageIndex));
}
super.savePlane(imageIndex, planeIndex, plane, ifd, offsets, lengths);
// TODO should this be the output id?
imageLocations[imageIndex][(int) planeIndex] =
getMetadata().getDatasetName();
}
/* @see loci.formats.IFormatHandler#close() */
@Override
public void close() throws IOException {
try {
if (getStream() != null) {
setupServiceAndMetadata();
// remove any BinData elements from the OME-XML
service.removeBinData(omeMeta);
for (int series = 0; series < omeMeta.getImageCount(); series++) {
populateImage(omeMeta, series);
}
final List<String> files = new ArrayList<String>();
for (final String[] s : imageLocations) {
for (final String f : s) {
if (!files.contains(f) && f != null) {
files.add(f);
final String xml = getOMEXML(f);
// write OME-XML to the first IFD's comment
saveComment(f, xml);
}
}
}
}
}
catch (final ServiceException se) {
throw new RuntimeException(se);
}
catch (final FormatException fe) {
throw new RuntimeException(fe);
}
catch (final IllegalArgumentException iae) {
throw new RuntimeException(iae);
}
finally {
super.close();
boolean canReallyClose =
omeMeta == null || ifdCounts.size() == omeMeta.getImageCount();
if (omeMeta != null && canReallyClose) {
int omePlaneCount = 0;
for (int i = 0; i < omeMeta.getImageCount(); i++) {
final int sizeZ = omeMeta.getPixelsSizeZ(i).getValue();
final int sizeC = omeMeta.getPixelsSizeC(i).getValue();
final int sizeT = omeMeta.getPixelsSizeT(i).getValue();
omePlaneCount += sizeZ * sizeC * sizeT;
}
int ifdCount = 0;
for (final String key : ifdCounts.keySet()) {
ifdCount += ifdCounts.get(key);
}
canReallyClose = omePlaneCount == ifdCount;
}
if (canReallyClose) {
imageMap = null;
imageLocations = null;
omeMeta = null;
service = null;
ifdCounts.clear();
}
else {
for (final String k : ifdCounts.keySet())
ifdCounts.put(k, 0);
}
}
}
// -- Helper methods --
/** Gets the UUID corresponding to the given filename. */
private String getUUID(final String filename) {
String uuid = uuids.get(filename);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
uuids.put(filename, uuid);
}
return uuid;
}
private void setupServiceAndMetadata() throws ServiceException {
// extract OME-XML string from metadata object
final MetadataRetrieve retrieve = getMetadata().getOmeMeta().getRoot();
service = getContext().getService(OMEXMLService.class);
final OMEXMLMetadata originalOMEMeta = service.getOMEMetadata(retrieve);
originalOMEMeta.resolveReferences();
final String omexml = service.getOMEXML(originalOMEMeta);
omeMeta = service.createOMEXMLMetadata(omexml);
}
private String getOMEXML(final String file) throws FormatException,
IOException
{
// generate UUID and add to OME element
final String uuid =
"urn:uuid:" + getUUID(new Location(getContext(), file).getName());
omeMeta.setUUID(uuid);
String xml;
try {
xml = service.getOMEXML(omeMeta);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
// insert warning comment
final String prefix = xml.substring(0, xml.indexOf(">") + 1);
final String suffix = xml.substring(xml.indexOf(">") + 1);
return prefix + WARNING_COMMENT + suffix;
}
private void saveComment(final String file, final String xml)
throws IOException, FormatException
{
if (getStream() != null) getStream().close();
setDest(new RandomAccessOutputStream(getContext(), file));
RandomAccessInputStream in = null;
try {
final TiffSaver saver = new TiffSaver(getContext(), getStream(), file);
saver.setBigTiff(isBigTiff());
in = new RandomAccessInputStream(getContext(), file);
saver.overwriteLastIFDOffset(in);
saver.overwriteComment(in, xml);
in.close();
}
catch (final FormatException exc) {
final IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
finally {
if (getStream() != null) getStream().close();
if (in != null) in.close();
}
}
private void populateTiffData(final OMEXMLMetadata omeMeta,
final long[] zct, final int ifd, final int series, final int plane)
{
omeMeta.setTiffDataFirstZ(new NonNegativeInteger((int) zct[0]), series,
plane);
omeMeta.setTiffDataFirstC(new NonNegativeInteger((int) zct[1]), series,
plane);
omeMeta.setTiffDataFirstT(new NonNegativeInteger((int) zct[2]), series,
plane);
omeMeta.setTiffDataIFD(new NonNegativeInteger(ifd), series, plane);
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(1), series, plane);
}
private void populateImage(final OMEXMLMetadata omeMeta,
final int imageIndex)
{
final String dimensionOrder =
omeMeta.getPixelsDimensionOrder(imageIndex).toString();
final int sizeZ =
omeMeta.getPixelsSizeZ(imageIndex).getValue().intValue();
int sizeC = omeMeta.getPixelsSizeC(imageIndex).getValue().intValue();
final int sizeT =
omeMeta.getPixelsSizeT(imageIndex).getValue().intValue();
final long planeCount = getMetadata().get(imageIndex).getPlaneCount();
final int ifdCount = imageMap.size();
if (planeCount == 0) {
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(0), imageIndex, 0);
return;
}
final PositiveInteger samplesPerPixel =
new PositiveInteger((int) ((sizeZ * sizeC * sizeT) / planeCount));
for (int c = 0; c < omeMeta.getChannelCount(imageIndex); c++) {
omeMeta.setChannelSamplesPerPixel(samplesPerPixel, imageIndex, c);
}
sizeC /= samplesPerPixel.getValue();
final long[] lengths =
metaService.zctToArray(dimensionOrder, sizeC, sizeC, sizeT);
int nextPlane = 0;
for (int plane = 0; plane < planeCount; plane++) {
metaService.zctToArray(dimensionOrder, sizeC, sizeC, sizeT);
final long[] zct = FormatTools.rasterToPosition(lengths, planeCount);
int planeIndex = plane;
if (imageLocations[imageIndex].length < planeCount) {
planeIndex /= (planeCount / imageLocations[imageIndex].length);
}
String filename = imageLocations[imageIndex][planeIndex];
if (filename != null) {
filename = new Location(getContext(), filename).getName();
final Integer ifdIndex = ifdCounts.get(filename);
final int ifd = ifdIndex == null ? 0 : ifdIndex.intValue();
omeMeta.setUUIDFileName(filename, imageIndex, nextPlane);
final String uuid = "urn:uuid:" + getUUID(filename);
omeMeta.setUUIDValue(uuid, imageIndex, nextPlane);
// fill in any non-default TiffData attributes
populateTiffData(omeMeta, zct, ifd, imageIndex, nextPlane);
ifdCounts.put(filename, ifd + 1);
nextPlane++;
}
}
}
private int planeCount(final int imageIndex) {
final MetadataRetrieve r = getMetadata().getOmeMeta().getRoot();
final int z = r.getPixelsSizeZ(imageIndex).getValue().intValue();
final int t = r.getPixelsSizeT(imageIndex).getValue().intValue();
int c = r.getChannelCount(imageIndex);
final String pixelType = r.getPixelsType(imageIndex).getValue();
final int bytes = FormatTools.getBytesPerPixel(pixelType);
if (bytes > 1 && c == 1) {
c = r.getChannelSamplesPerPixel(imageIndex, 0).getValue();
}
return z * c * t;
}
}
// -- Helper Methods --
private static void setupServices(final Context ctx) {
service = ctx.getService(OMEXMLService.class);
metaService = ctx.getService(OMEMetadataService.class);
}
private static boolean isSingleFile(final Context context, final String id)
throws FormatException, IOException
{
// parse and populate OME-XML metadata
final String fileName =
new Location(context, id).getAbsoluteFile().getAbsolutePath();
final RandomAccessInputStream ras =
new RandomAccessInputStream(context, fileName);
final TiffParser tp = new TiffParser(context, ras);
final IFD ifd = tp.getFirstIFD();
final long[] ifdOffsets = tp.getIFDOffsets();
ras.close();
final String xml = ifd.getComment();
if (service == null) setupServices(context);
OMEXMLMetadata meta;
try {
meta = service.createOMEXMLMetadata(xml);
}
catch (final ServiceException se) {
throw new FormatException(se);
}
if (meta.getRoot() == null) {
throw new FormatException("Could not parse OME-XML from TIFF comment");
}
int nImages = 0;
for (int i = 0; i < meta.getImageCount(); i++) {
int nChannels = meta.getChannelCount(i);
if (nChannels == 0) nChannels = 1;
final int z = meta.getPixelsSizeZ(i).getValue().intValue();
final int t = meta.getPixelsSizeT(i).getValue().intValue();
nImages += z * t * nChannels;
}
return nImages <= ifdOffsets.length;
}
/**
* This class can be used for translating any io.scif.Metadata to Metadata for
* writing OME-TIFF. files.
* <p>
* Note that Metadata translated from Core is only write-safe.
* </p>
* <p>
* If trying to read, there should already exist an originally-parsed OME-TIFF
* Metadata object which can be used.
* </p>
* <p>
* Note also that any OME-TIFF image written must be reparsed, as the Metadata
* used to write it can not be guaranteed valid.
* </p>
*/
@Plugin(type = Translator.class, priority = OMETIFFFormat.PRIORITY)
public static class OMETIFFTranslator extends
AbstractTranslator<io.scif.Metadata, Metadata>
{
// -- Fields --
@Parameter
private FormatService formatService;
@Parameter
private TranslatorService translatorService;
// -- Translator API Methods --
@Override
public Class<? extends io.scif.Metadata> source() {
return io.scif.Metadata.class;
}
@Override
public Class<? extends io.scif.Metadata> dest() {
return Metadata.class;
}
@Override
public void translateFormatMetadata(final io.scif.Metadata source,
final Metadata dest)
{
if (dest.getOmeMeta() == null) {
final OMEMetadata omeMeta = new OMEMetadata(getContext());
translatorService.translate(source, omeMeta, false);
dest.setOmeMeta(omeMeta);
}
try {
final TIFFFormat.Metadata tiffMeta =
(TIFFFormat.Metadata) formatService.getFormatFromClass(
TIFFFormat.class).createMetadata();
translatorService.translate(source, tiffMeta, false);
dest.setFirstIFD(tiffMeta.getIfds().get(0));
}
catch (final FormatException e) {
log().error("Failed to generate TIFF data", e);
}
final OMETIFFPlane[][] info = new OMETIFFPlane[source.getImageCount()][];
dest.setPlaneInfo(info);
final List<Integer> samples = new ArrayList<Integer>();
final List<Boolean> adjustedSamples = new ArrayList<Boolean>();
dest.samples = samples;
dest.adjustedSamples = adjustedSamples;
dest.createImageMetadata(0);
for (int i = 0; i < source.getImageCount(); i++) {
info[i] = new OMETIFFPlane[(int) source.get(i).getPlaneCount()];
for (int j = 0; j < source.get(i).getPlaneCount(); j++) {
info[i][j] = new OMETIFFPlane();
}
dest.add(new DefaultImageMetadata());
samples.add((int) (source.get(i).isMultichannel() ? source.get(i)
.getAxisLength(Axes.CHANNEL) : 1));
adjustedSamples.add(false);
}
}
@Override
protected void translateImageMetadata(final List<ImageMetadata> source,
final Metadata dest)
{
// No implementation necessary. See translateFormatMetadata
}
}
// -- Helper classes --
/** Structure containing details on where to find a particular image plane. */
private static class OMETIFFPlane {
/** Reader to use for accessing this plane. */
public MinimalTIFFFormat.Reader<?> reader;
/** File containing this plane. */
public String id;
/** IFD number of this plane. */
public int ifd = -1;
/** Certainty flag, for dealing with unspecified NumPlanes. */
public boolean certain = false;
}
}
| OMETIFFFormat: remove unnecessary static services
the OMEXML and OMEXMLMetadata services were static for no reason, as
they can be automatically populated via context injection (and there was
no reason to null them on closing).
This also removes completely unnecessary service creation logic.
| src/main/java/io/scif/ome/formats/OMETIFFFormat.java | OMETIFFFormat: remove unnecessary static services | <ide><path>rc/main/java/io/scif/ome/formats/OMETIFFFormat.java
<ide>
<ide> // -- Fields --
<ide>
<del> // FIXME: These should not be static.
<add> @Parameter
<ide> private static OMEXMLService service;
<add>
<add> @Parameter
<ide> private static OMEMetadataService metaService;
<ide>
<ide> // -- Format API Methods --
<ide> }
<ide>
<ide> try {
<del> if (service == null) setupServices(getContext());
<ide> final IMetadata meta = service.createOMEXMLMetadata(comment);
<ide> for (int i = 0; i < meta.getImageCount(); i++) {
<ide> meta.setPixelsBinDataBigEndian(Boolean.TRUE, i, 0);
<ide>
<ide> meta.setFirstIFD(firstIFD);
<ide>
<del> if (service == null) setupServices(getContext());
<ide> OMEXMLMetadata omexmlMeta;
<ide> try {
<ide> omexmlMeta = service.createOMEXMLMetadata(xml);
<ide> imageMap = null;
<ide> imageLocations = null;
<ide> omeMeta = null;
<del> service = null;
<ide> ifdCounts.clear();
<ide> }
<ide> else {
<ide> // extract OME-XML string from metadata object
<ide> final MetadataRetrieve retrieve = getMetadata().getOmeMeta().getRoot();
<ide>
<del> service = getContext().getService(OMEXMLService.class);
<ide> final OMEXMLMetadata originalOMEMeta = service.getOMEMetadata(retrieve);
<ide> originalOMEMeta.resolveReferences();
<ide>
<ide> }
<ide>
<ide> // -- Helper Methods --
<del>
<del> private static void setupServices(final Context ctx) {
<del> service = ctx.getService(OMEXMLService.class);
<del> metaService = ctx.getService(OMEMetadataService.class);
<del> }
<ide>
<ide> private static boolean isSingleFile(final Context context, final String id)
<ide> throws FormatException, IOException
<ide> ras.close();
<ide> final String xml = ifd.getComment();
<ide>
<del> if (service == null) setupServices(context);
<ide> OMEXMLMetadata meta;
<ide> try {
<ide> meta = service.createOMEXMLMetadata(xml); |
|
JavaScript | mit | 38df54fc414d110d8ac27ce03720995602df3fd0 | 0 | EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/GreenUp,EdgeCaseBerg/green-web,EdgeCaseBerg/GreenUp |
/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */
(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e<d)e in c&&(f=b.call(a,f,c[e],e,c)),e++;return f})})();var Zepto=function(){function E(a){return a==null?String(a):y[z.call(a)]||"object"}function F(a){return E(a)=="function"}function G(a){return a!=null&&a==a.window}function H(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function I(a){return E(a)=="object"}function J(a){return I(a)&&!G(a)&&a.__proto__==Object.prototype}function K(a){return a instanceof Array}function L(a){return typeof a.length=="number"}function M(a){return g.call(a,function(a){return a!=null})}function N(a){return a.length>0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return N(d)},c.each=function(a,b){var c,d;if(L(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){y["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return u.test(h.readyState)?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto)
// connector class for hooking up to API
function ApiConnector(){
var heatmapData = [];
var markerData = [];
var commentData = [];
var BASE = "http://localhost:30002/api";
// api URLs
var forumURI = "/comments?type=forum";
var needsURI = "/comments?type=needs";
var messagesURI = "/comments?type=message";
var commentsUri = "/comments";
var heatmapURI = "/heatmap?";
var pinsURI = "/pins";
// performs the ajax call to get our data
ApiConnector.prototype.pullApiData = function pullApiData(URL, DATATYPE, QUERYTYPE, CALLBACK){
// zepto
$.ajax({
type: QUERYTYPE,
url: URL,
dataType: DATATYPE,
success: function(data){
CALLBACK(data);
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
} // end pullApiData
ApiConnector.prototype.pushApiData = function pushApiData(URL, DATATYPE, QUERYTYPE, CALLBACK){
}
ApiConnector.prototype.pushNewPin = function pushNewPin(jsonObj){
$.ajax({
type: "POST",
url: BASE+pinsURI,
data: jsonObj,
cache: false,
// processData: false,
dataType: "json",
// contentType: "application/json",
success: function(data){
console.log("INFO: Pin successfully sent")
window.ApiConnector.pullMarkerData();
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 503:
console.log("Service Unavailable");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
case 200:
console.log("Request successful");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
//zepto
}
// ********** specific data pullers *************
ApiConnector.prototype.pullHeatmapData = function pullHeatmapData(latDegrees, latOffset, lonDegrees, lonOffset){
/*
To be extra safe we could do if(typeof(param) === "undefined" || param == null),
but there is an implicit cast against undefined defined for double equals in javascript
*/
params = "?";
if(latDegrees != null)
params += "latDegrees=" + latDegrees + "&";
if(latOffset != null)
params += "latOffset=" + latOffset + "&";
if(lonDegrees != null)
params += "lonDegrees" + lonDegrees + "&";
if(lonOffset != null)
params += "lonOffset" + lonOffset + "&";
var URL = BASE+heatmapURI+params;
this.pullApiData(URL, "JSON", "GET", window.UI.updateHeatmap);
}
ApiConnector.prototype.pullMarkerData = function pullMarkerData(){
console.log("in pullMarkerData");
var URL = BASE+pinsURI;
this.pullApiData(URL, "JSON", "GET", window.UI.updateMarker);
}
// by passing the url as an argument, we can use this method to get next pages
ApiConnector.prototype.pullCommentData = function pullCommentData(commentType, url){
var urlStr = "";
switch(commentType){
case "needs":
(url == null) ? (urlStr = BASE+needsURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateNeeds);
break;
case "messages":
(url == null) ? (urlStr = BASE+messagesURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateMessages);
break;
case "forum":
(url == null) ? (urlStr = BASE+forumURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateForum);
break;
default:
(url == null) ? (urlStr = BASE+forumURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateForum);
break;
}
} // end pullCommentData()
ApiConnector.prototype.pushCommentData = function pushCommentData(commentType, message, pinType){
var jsonObj = '{ "type" : ' + commentType + ', "message" : ' + message + ', "pin" : ' + pinType + '}';
$.ajax({
type: "POST",
url: BASE+commentsUri,
data: jsonObj,
cache: false,
// processData: false,
dataType: "json",
// contentType: "application/json",
success: function(data){
console.log("INFO: Comment successfully sent");
window.ApiConnector.pullCommentData(commentType,null);
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 503:
console.log("Service Unavailable");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
case 200:
console.log("Request successful");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
}
ApiConnector.prototype.pullTestData = function pullTestData(){
this.pullApiData(BASE, "JSON", "GET", window.UI.updateTest);
this.pullCommentData("needs", null);
this.pullCommentData("messages", null);
this.pullCommentData("", null);
this.pullHeatmapData();
this.pullMarkerData();
}
//Uploads all local database entries to the Server
//Clears the local storage after upload
ApiConnector.prototype.pushHeatmapData = function pushHeatmapData(database){
if(window.logging){
//server/addgriddata.php
database.all(function(data){
//Make sure to not just send null data up or you'll get a 400 back
if(data.length == 00){
data = "[]";
}
// zepto code
$.ajax({
type:'PUT',
url: BASE + heatmapURI,
dataType:"json",
data: data,
failure: function(errMsg){
// alert(errMsg);
console.log("Failed to PUT heatmap: "+errMsg);
},
success: function(data){
console.log("PUT heatmap success: "+data);
}
});//Ajax
//Remove all uploaded database records
for(var i=1;i<data.length;i++){
database.remove(i);
}
});
}
}
// baseline testing
ApiConnector.prototype.testObj = function testObj(){
var URL = testurl;
this.pullApiData(URL, "JSON", "GET", this.updateTest);
}
} // end ApiConnector class def
/**
* manage the loading screen
*
*/
function LoadingScreen(loadingDiv){
var ISVISIBLE = false;
this.loadingText = "Loading...";
var loadingTextDiv = document.getElementById("loadingText");
LoadingScreen.prototype.show = function show(){
this.ISVISIBLE = true;
loadingDiv.style.display = "block";
loadingTextDiv.innerHTML = window.LS.loadingText;
}
LoadingScreen.prototype.hide = function hide(){
this.ISVISIBLE = false;
loadingDiv.style.display = "none";
}
LoadingScreen.prototype.isVisible = function isVisible(){
return this.ISVISIBLE;
}
LoadingScreen.prototype.setLoadingText = function setLoadingText(text){
this.loadingText = text;
}
} // end LoadingScreen class def
// class for managing the UI
function UiHandle(){
this.currentDisplay = 1;
this.isMarkerDisplayVisible = false;
this.MOUSEDOWN_TIME;
this.MOUSEUP_TIME;
this.markerDisplay;
this.isMarkerVisible = false;
this.isMapLoaded = false;
UiHandle.prototype.init = function init(){
// controls the main panel movement
document.getElementById("pan1").addEventListener('mousedown', function(){UI.setActiveDisplay(0);});
document.getElementById("pan2").addEventListener('mousedown', function(){UI.setActiveDisplay(1);});
document.getElementById("pan3").addEventListener('mousedown', function(){UI.setActiveDisplay(2);});
// marker type selectors
document.getElementById("selectPickup").addEventListener('mousedown', function(){window.UI.markerTypeSelect("pickup")});
document.getElementById("selectComment").addEventListener('mousedown', function(){window.UI.markerTypeSelect("comment")});
document.getElementById("selectTrash").addEventListener('mousedown', function(){window.UI.markerTypeSelect("trash")});
document.getElementById("dialogCommentOk").addEventListener('mousedown', function(){
window.MAP.addMarkerFromUi(document.getElementById("dialogSliderTextarea").value);
window.UI.dialogSliderDown();
});
document.getElementById("dialogCommentCancel").addEventListener('mousedown', function(){
window.UI.dialogSliderDown();
});
this.markerDisplay = document.getElementById("markerTypeDialog");
// toggle map overlays
window.UI.toggleHeat = document.getElementById('toggleHeat');
window.UI.toggleIcons = document.getElementById('toggleIcons');
window.UI.toggleIcons.addEventListener('mousedown', function(){
window.MAP.toggleIcons();
});
// for comment pagination
this.commentsType = ""
this.commentsNextPageUrl = "";
this.commentsPrevPageUrl = "";
document.getElementById("prevPage").addEventListener('mousedown', function(){
// load the previous page
window.ApiConnector.pullCommentData(this.commentsType, this.commentsPrevPageUrl);
});
document.getElementById("nextPage").addEventListener('mousedown', function(){
// load the previous page
window.ApiConnector.pullCommentData(this.commentsType, this.commentsNextPageUrl);
});
}
UiHandle.prototype.hideMarkerTypeSelect = function hideMarkerTypeSelect(){
console.log("in hideMarkerTypeSelect()");
window.UI.markerDisplay.style.display = "none";
window.UI.isMarkerDisplayVisible = false;
}
UiHandle.prototype.showMarkerTypeSelect = function showMarkerTypeSelect(){
console.log("in showMarkerTypeSelect()");
window.UI.markerDisplay.style.display = "block";
window.UI.isMarkerDisplayVisible = true;
}
UiHandle.prototype.setBigButtonColor = function setBigButtonColor(colorHex){
document.getElementById('bigButton').style.backgroundColor=colorHex;
}
UiHandle.prototype.setBigButtonText = function setBigButtonText(buttonText){
document.getElementById('bigButton').innerHTML = buttonText;
}
UiHandle.prototype.setMapLoaded = function setMapLoaded(){
window.MAP.isMapLoaded = true;
window.LS.hide();
}
// centers the appropriate panels
UiHandle.prototype.setActiveDisplay = function setActiveDisplay(displayNum){
var container = document.getElementById("container");
container.className = "";
switch(displayNum){
case 0:
this.currentDisplay = 1;
container.className = "panel1Center";
break;
case 1:
this.currentDisplay = 2;
container.className = "panel2Center";
break;
case 2:
this.currentDisplay = 3;
container.className = "panel3Center";
break;
default:
this.currentDisplay = 1;
container.className = "panel1Center";
}
}
// when the user chooses which type of marker to add to the map
UiHandle.prototype.markerTypeSelect = function markerTypeSelect(markerType){
// first we need to show the marker on the map
var iconUrl = "img/icons/blueCircle.png";
switch(markerType){
case "comment":
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
iconUrl = "img/icons/redCircle.png";
break;
default:
iconUrl = "img/icons/blueCircle.png";
break;
}
window.MAP.markerType = markerType;
var marker = new google.maps.Marker({
position: window.MAP.markerEvent.latLng,
map: window.MAP.map,
icon: iconUrl
});
// second we need to get the user's message
// third we need to
// (bug) need to get the message input from the user
// var message = "DEFAULT MESSAGE TEXT";
// here we add the appropriate marker to the map
// window.MAP.addMarkerFromUi(markerType, message);
// window.UI.markerDisplay.style.display = "none";
// window.UI.isMarkerDisplayVisible = false;
window.UI.hideMarkerTypeSelect();
window.UI.dialogSliderUp();
// (bug) here we need to prevent more map touches
}
UiHandle.prototype.dialogSliderUp = function dialogSliderUp(){
document.getElementById("dialogSlider").style.top = "72%";
document.getElementById("dialogSlider").style.opacity = "1.0";
document.getElementById("dialogSliderTextarea").focus();
}
UiHandle.prototype.dialogSliderDown = function dialogSliderDown(){
document.getElementById("dialogSlider").style.top = "86%";
document.getElementById("dialogSlider").style.opacity = "0.0";
}
UiHandle.prototype.markerSelectUp = function markerSelectUp(){
// set the coords of the marker event
MOUSEUP_TIME = new Date().getTime() / 1000;
if((MOUSEUP_TIME - this.MOUSEDOWN_TIME) < 0.3){
if(this.isMarkerDisplayVisible){
window.UI.hideMarkerTypeSelect();
}else{
window.UI.showMarkerTypeSelect();
}
this.MOUSEDOWN_TIME =0;
this.MOUSEDOWN_TIME =0;
}else{
this.MOUSEDOWN_TIME =0;
this.MOUSEDOWN_TIME =0;
}
}
UiHandle.prototype.markerSelectDown = function markerSelectDown(event){
// set the coords of the marker event
window.MAP.markerEvent = event;
this.MOUSEDOWN_TIME = new Date().getTime() / 1000;
}
// ******* DOM updaters (callbacks for the ApiConnector pull methods) ***********
UiHandle.prototype.updateHeatmap = function updateHeatmap(data){
console.log(data);
}
UiHandle.prototype.updateMarker = function updateMarker(data){
//console.log("marker response: "+data);
var dataArr = eval("("+data+")");
// var dataArr = data;
for(ii=0; ii<dataArr.length; ii++){
// var dataA = dataArr[ii].split(",");
window.MAP.addMarkerFromApi(dataArr[ii].type, dataArr[ii].message, dataArr[ii].latDegrees, dataArr[ii].lonDegrees);
// heatmapData.push({location: new google.maps.LatLng(dataArr[ii][0], dataArr[ii][1]), weight: dataArr[ii][2]});
}
}
UiHandle.prototype.updateMessages = function updateMessages(data){
window.UI.commentsNextPageUrl = data.page.next;
window.UI.commentsPrevPageUrl = data.page.previous;
var messagesContainer = document.getElementById("messagesContainer");
var messages = new Array();
(window.UI.commentsNextPageUrl != null) ?
window.UI.showNextCommentsButton() : window.UI.hideNextCommentsButton();
(window.UI.commentsPrevPageUrl != null) ?
window.UI.showPrevCommentsButton() : window.UI.hidePrevCommentsButton();
for(ii=0; ii<3; ii++){
// for(ii=0; ii<data.comments.length; ii++){
messages[ii] = document.createElement('div');
messages[ii].className = "messageListItem";
messages[ii].style.border = "1px solid red";
// create the div where the timestamp will display
var commentDateContainer = document.createElement('div');
commentDateContainer.className = "commentDateContainer";
// commentDateContainer.innerHTML = data.comments.timestamp;
commentDateContainer.innerHTML = "1970-01-01 00:00:01";
// create the div where the message content will be stored
var messageContentContainer = document.createElement('div');
messageContentContainer.className = "messageContentContainer";
// messageContentContainer.innerHTML = data.comments.message;
messageContentContainer.innerHTML = "sdfasdfasdfasdfadsfasdfadsfa";
messages[ii].appendChild(commentDateContainer);
messages[ii].appendChild(messageContentContainer);
messagesContainer.appendChild(messages[ii]);
}
// // alert(window.UI.commentsNextPageUrl);
console.log(data);
}
UiHandle.prototype.updateNeeds = function updateNeeds(data){
console.log(data);
}
UiHandle.prototype.updateForum = function updateForum(data){
console.log(data);
}
UiHandle.prototype.updateTest = function updateTest(data){
console.log(data);
}
// ******** End DOM Updaters *********
// ---- begin pagination control toggle ----
UiHandle.prototype.showNextCommentsButton = function showNextCommentsButton(){
document.getElementById("nextPage").style.display = "inline-block";
}
UiHandle.prototype.hideNextCommentsButton = function hideNextCommentsButton(){
document.getElementById("nextPage").style.display = "none";
}
UiHandle.prototype.showPrevCommentsButton = function showPrevCommentsButton(){
document.getElementById("prevPage").style.display = "inline-block";
}
UiHandle.prototype.hidePrevCommentsButton = function hidePrevCommentsButton(){
document.getElementById("prevPage").style.display = "none";
}
// ---- end pagination control toggle
} // end UiHandle class def
// class for managing all geolocation work
function GpsHandle(){
GpsHandle.prototype.initGps = function initGps(){
db = Lawnchair({name : 'db'}, function(store) {
lawnDB = store;
setInterval(function() {window.GPS.runUpdate(store)},5000);//update user location every 5 seconds
setInterval(function() {window.ApiConnector.pushHeatmapData(store)},3000);//upload locations to the server every 30 seconds
});
}
//Runs the update script:
GpsHandle.prototype.runUpdate = function runUpdate(database){
//Grab the geolocation data from the local machine
navigator.geolocation.getCurrentPosition(function(position) {
window.GPS.updateLocation(database, position.coords.latitude, position.coords.longitude);
});
}
GpsHandle.prototype.updateLocation = function updateLocation(database, latitude, longitude){
if(window.logging){
var datetime = new Date().getTime();//generate timestamp
var location = {
"latitude" : latitude,
"longitude" : longitude,
"datetime" : datetime,
}
database.save({value:location});//Save the record
}
};
GpsHandle.prototype.recenterMap = function recenterMap(lat, lon){
console.log(lon);
var newcenter = new google.maps.LatLng(lat, lon);
centerPoint = newcenter;
map.panTo(newcenter);
}
GpsHandle.prototype.start = function start(){
window.UI.setBigButtonColor("#ff0000");
window.UI.setBigButtonText("Stop Cleaning");
window.logging = true;
this.initGps();
console.log("initializing GPS...");
navigator.geolocation.getCurrentPosition(function(p){
window.MAP.updateMap(p.coords.latitude, p.coords.longitude, 10);
});
}
GpsHandle.prototype.stop = function stop(){
window.ApiConnector.pushHeatmapData(lawnDB);
window.logging = false;
console.log("stopping...");
window.UI.setBigButtonColor("#00ff00");
window.UI.setBigButtonText("Start Cleaning");
}
} // end GpsHandle class def
// class for managing all Map work
function MapHandle(){
// BTV coords
this.currentLat = 44.476621500000000;
this.currentLon = -73.209998100000000;
this.currentZoom = 10;
this.markerEvent;
this.markerType;
this.map;
this.pickupMarkers = [];
// fire up our google map
MapHandle.prototype.initMap = function initMap(){
window.LS.setLoadingText("Please wait while the map loads");
window.LS.show();
// define the initial location of our map
centerPoint = new google.maps.LatLng(window.MAP.currentLat, window.MAP.currentLon);
var mapOptions = {
zoom: window.MAP.currentZoom,
center: centerPoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
window.MAP.map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// for activating the loading screen while map loads
google.maps.event.addListener(window.MAP.map, 'idle', window.UI.setMapLoaded);
google.maps.event.addListener(window.MAP.map, 'center_changed', window.LS.show);
google.maps.event.addListener(window.MAP.map, 'zoom_changed', window.LS.show);
// our comment selector initializers
// google.maps.event.addListener(window.MAP.map, 'mousedown', this.setMarkerEvent);
google.maps.event.addListener(window.MAP.map, 'mousedown', window.UI.markerSelectDown);
google.maps.event.addListener(window.MAP.map, 'mouseup', window.UI.markerSelectUp);
}
MapHandle.prototype.addMarkerFromUi = function addMarkerFromUi(message){
// console.log("in addMarker()");
var pin = new Pin();
pin.message = message;
pin.type = window.MAP.markerType;
// pin.latDegrees = lat;
// pin.lonDegrees = lon;
var iconUrl;
switch(window.MAP.markerType){
case "comment":
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
pin.type = "help needed";
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
pin.type = "trash pickup";
iconUrl = "img/icons/redCircle.png";
break;
default:
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
}
var eventLatLng = window.MAP.markerEvent;
// console.log(eventLatLng.latLng);
pin.latDegrees = eventLatLng.latLng.jb;
pin.lonDegrees = eventLatLng.latLng.kb;
var serializedPin = JSON.stringify(pin);
console.log(serializedPin);
window.ApiConnector.pushNewPin(serializedPin);
}
MapHandle.prototype.addMarkerFromApi = function addMarkerFromApi(markerType, message, lat, lon){
// console.log("in addMarker()");
var pin = new Pin();
pin.message = message;
pin.type = markerType;
pin.latDegrees = lat;
pin.lonDegrees = lon;
var iconUrl;
switch(markerType){
case "comment":
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
pin.type = "help needed";
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
pin.type = "trash pickup";
iconUrl = "img/icons/redCircle.png";
break;
default:
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
}
// test "bad type" response
// pin.type = "bullshit";
var marker = new google.maps.Marker({
position: new google.maps.LatLng(pin.latDegrees, pin.lonDegrees),
map: window.MAP.map,
icon: iconUrl
});
// pin.latDegrees = marker.getPosition().lat();
// pin.lonDegrees = marker.getPosition().lng();
// var serializedPin = JSON.stringify(pin);
// // alert(serializedPin);
// window.UI.markerDisplay.style.display = "none";
// window.UI.isMarkerDisplayVisible = false;
window.MAP.pickupMarkers.push(marker);
// console.log(window.MAP.pickupMarkers);
// window.MAP.updateMap(this.currentLat,this.currentLon, this.currentZoom);
// window.ApiConnector.pushNewPin(serializedPin);
}
MapHandle.prototype.updateMap = function updateMap(lat, lon, zoom){
window.UI.isMapLoaded = false;
var newcenter = new google.maps.LatLng(lat, lon);
window.MAP.map.panTo(newcenter);
}
MapHandle.prototype.toggleIcons = function toggleIcons(){
console.log("toggle icons: "+window.MAP.pickupMarkers.length);
if(window.UI.isMarkerVisible){
for(var ii=0; ii<window.MAP.pickupMarkers.length; ii++){
window.MAP.pickupMarkers[ii].setVisible(false);
window.UI.isMarkerVisible = false;
}
}else{
for(var ii=0; ii<window.MAP.pickupMarkers.length; ii++){
window.MAP.pickupMarkers[ii].setVisible(true);
window.UI.isMarkerVisible = true;
}
}
}
MapHandle.prototype.toggleHeatmap = function toggleHeatmap(){
}
MapHandle.prototype.setCurrentLat = function setCurrentLat(CurrentLat){
this.currentLat = CurrentLat;
}
MapHandle.prototype.setCurrentLon = function setCurrentLon(CurrentLon){
this.currentLon = CurrentLon;
}
MapHandle.prototype.setCurrentZoom = function setCurrentZoom(CurrentZoom){
this.currentZoom = CurrentZoom;
}
MapHandle.prototype.setMarkerEvent = function setMarkerEvent(event){
this.markerEvent = event;
}
MapHandle.prototype.getCurrentLat = function getCurrentLat(){
return currentLat;
}
MapHandle.prototype.getCurrentLon = function getCurrentLon(){
return this.currentLon;
}
MapHandle.prototype.getCurrentZoom = function getCurrentZoom(){
return this.currentZoom;
}
} //end MapHandle
// prototype objects for posting to API
function Pin(){
this.latDegrees;
this.lonDegrees;
this.type;
this.message = "I had to run to feed my cat, had to leave my Trash here sorry! Can someone pick it up?";
}
/**
* This is where all the action begins (once content is loaded)
* @author Josh
*/
document.addEventListener('DOMContentLoaded',function(){
document.addEventListener("touchmove", function(e){e.preventDefault();}, false);
window.ApiConnector = new ApiConnector();
window.UI = new UiHandle();
window.UI.init();
window.LS = new LoadingScreen(document.getElementById("loadingScreen"));
window.GPS = new GpsHandle();
window.MAP = new MapHandle();
window.MAP.initMap();
window.logging = false;
// window.ApiConnector.pullTestData();
window.ApiConnector.pullMarkerData();
document.getElementById("bigButton").addEventListener('mousedown', function(){
if(!window.logging){
window.GPS.start();
}else{
window.GPS.stop();
}
});
});
| web/client/js/ApiConnector.js |
/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */
(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e<d)e in c&&(f=b.call(a,f,c[e],e,c)),e++;return f})})();var Zepto=function(){function E(a){return a==null?String(a):y[z.call(a)]||"object"}function F(a){return E(a)=="function"}function G(a){return a!=null&&a==a.window}function H(a){return a!=null&&a.nodeType==a.DOCUMENT_NODE}function I(a){return E(a)=="object"}function J(a){return I(a)&&!G(a)&&a.__proto__==Object.prototype}function K(a){return a instanceof Array}function L(a){return typeof a.length=="number"}function M(a){return g.call(a,function(a){return a!=null})}function N(a){return a.length>0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1></$2>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e<a.length;e++)c=b(a[e],e),c!=null&&d.push(c);else for(f in a)c=b(a[f],f),c!=null&&d.push(c);return N(d)},c.each=function(a,b){var c,d;if(L(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},c.grep=function(a,b){return g.call(a,b)},window.JSON&&(c.parseJSON=JSON.parse),c.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){y["[object "+b+"]"]=b.toLowerCase()}),c.fn={forEach:e.forEach,reduce:e.reduce,push:e.push,sort:e.sort,indexOf:e.indexOf,concat:e.concat,map:function(a){return c(c.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return c(f.apply(this,arguments))},ready:function(a){return u.test(h.readyState)?a(c):h.addEventListener("DOMContentLoaded",function(){a(c)},!1),this},get:function(b){return b===a?f.call(this):this[b>=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("<div>").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto)
// connector class for hooking up to API
function ApiConnector(){
var heatmapData = [];
var markerData = [];
var commentData = [];
var BASE = "http://localhost:30002/api";
// api URLs
var forumURI = "/comments?type=forum";
var needsURI = "/comments?type=needs";
var messagesURI = "/comments?type=message";
var commentsUri = "/comments";
var heatmapURI = "/heatmap?";
var pinsURI = "/pins";
// performs the ajax call to get our data
ApiConnector.prototype.pullApiData = function pullApiData(URL, DATATYPE, QUERYTYPE, CALLBACK){
// zepto
$.ajax({
type: QUERYTYPE,
url: URL,
dataType: DATATYPE,
success: function(data){
CALLBACK(data);
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
} // end pullApiData
ApiConnector.prototype.pushApiData = function pushApiData(URL, DATATYPE, QUERYTYPE, CALLBACK){
}
ApiConnector.prototype.pushNewPin = function pushNewPin(jsonObj){
$.ajax({
type: "POST",
url: BASE+pinsURI,
data: jsonObj,
cache: false,
// processData: false,
dataType: "json",
// contentType: "application/json",
success: function(data){
console.log("INFO: Pin successfully sent")
window.ApiConnector.pullMarkerData();
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 503:
console.log("Service Unavailable");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
case 200:
console.log("Request successful");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
//zepto
}
// ********** specific data pullers *************
ApiConnector.prototype.pullHeatmapData = function pullHeatmapData(latDegrees, latOffset, lonDegrees, lonOffset){
/*
To be extra safe we could do if(typeof(param) === "undefined" || param == null),
but there is an implicit cast against undefined defined for double equals in javascript
*/
params = "?";
if(latDegrees != null)
params += "latDegrees=" + latDegrees + "&";
if(latOffset != null)
params += "latOffset=" + latOffset + "&";
if(lonDegrees != null)
params += "lonDegrees" + lonDegrees + "&";
if(lonOffset != null)
params += "lonOffset" + lonOffset + "&";
var URL = BASE+heatmapURI+params;
this.pullApiData(URL, "JSON", "GET", window.UI.updateHeatmap);
}
ApiConnector.prototype.pullMarkerData = function pullMarkerData(){
console.log("in pullMarkerData");
var URL = BASE+pinsURI;
this.pullApiData(URL, "JSON", "GET", window.UI.updateMarker);
}
// by passing the url as an argument, we can use this method to get next pages
ApiConnector.prototype.pullCommentData = function pullCommentData(commentType, url){
var urlStr = "";
switch(commentType){
case "needs":
(url == null) ? (urlStr = BASE+needsURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateNeeds);
break;
case "messages":
(url == null) ? (urlStr = BASE+messagesURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateMessages);
break;
case "forum":
(url == null) ? (urlStr = BASE+forumURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateForum);
break;
default:
(url == null) ? (urlStr = BASE+forumURI) : (urlStr = url);
this.pullApiData(urlStr, "JSON", "GET", window.UI.updateForum);
break;
}
} // end pullCommentData()
ApiConnector.prototype.pushCommentData = function pushCommentData(commentType, message, pinType){
var jsonObj = '{ "type" : ' + commentType + ', "message" : ' + message + ', "pin" : ' + pinType + '}';
$.ajax({
type: "POST",
url: BASE+commentsUri,
data: jsonObj,
cache: false,
// processData: false,
dataType: "json",
// contentType: "application/json",
success: function(data){
console.log("INFO: Comment successfully sent");
window.ApiConnector.pullCommentData(commentType,null);
},
error: function(xhr, errorType, error){
// // alert("error: "+xhr.status);
switch(xhr.status){
case 500:
// internal server error
// consider leaving app
console.log("Error: api response = 500");
break;
case 503:
console.log("Service Unavailable");
break;
case 404:
// not found, stop trying
// consider leaving app
console.log('Error: api response = 404');
break;
case 400:
// bad request
console.log("Error: api response = 400");
break;
case 422:
console.log("Error: api response = 422");
break;
case 200:
console.log("Request successful");
break;
default:
// alert("Error Contacting API: "+xhr.status);
break;
}
}
});
}
ApiConnector.prototype.pullTestData = function pullTestData(){
this.pullApiData(BASE, "JSON", "GET", window.UI.updateTest);
this.pullCommentData("needs", null);
this.pullCommentData("messages", null);
this.pullCommentData("", null);
this.pullHeatmapData();
this.pullMarkerData();
}
//Uploads all local database entries to the Server
//Clears the local storage after upload
ApiConnector.prototype.pushHeatmapData = function pushHeatmapData(database){
if(window.logging){
//server/addgriddata.php
database.all(function(data){
//Make sure to not just send null data up or you'll get a 400 back
if(data.length == 00){
data = "[]";
}
// zepto code
$.ajax({
type:'PUT',
url: BASE + heatmapURI,
dataType:"json",
data: data,
failure: function(errMsg){
// alert(errMsg);
console.log("Failed to PUT heatmap: "+errMsg);
},
success: function(data){
console.log("PUT heatmap success: "+data);
}
});//Ajax
//Remove all uploaded database records
for(var i=1;i<data.length;i++){
database.remove(i);
}
});
}
}
// baseline testing
ApiConnector.prototype.testObj = function testObj(){
var URL = testurl;
this.pullApiData(URL, "JSON", "GET", this.updateTest);
}
} // end ApiConnector class def
/**
* manage the loading screen
*
*/
function LoadingScreen(loadingDiv){
var ISVISIBLE = false;
this.loadingText = "Loading...";
var loadingTextDiv = document.getElementById("loadingText");
LoadingScreen.prototype.show = function show(){
this.ISVISIBLE = true;
loadingDiv.style.display = "block";
loadingTextDiv.innerHTML = window.LS.loadingText;
}
LoadingScreen.prototype.hide = function hide(){
this.ISVISIBLE = false;
loadingDiv.style.display = "none";
}
LoadingScreen.prototype.isVisible = function isVisible(){
return this.ISVISIBLE;
}
LoadingScreen.prototype.setLoadingText = function setLoadingText(text){
this.loadingText = text;
}
} // end LoadingScreen class def
// class for managing the UI
function UiHandle(){
this.currentDisplay = 1;
this.isMarkerDisplayVisible = false;
this.MOUSEDOWN_TIME;
this.MOUSEUP_TIME;
this.markerDisplay;
this.isMarkerVisible = false;
this.isMapLoaded = false;
UiHandle.prototype.init = function init(){
// controls the main panel movement
document.getElementById("pan1").addEventListener('mousedown', function(){UI.setActiveDisplay(0);});
document.getElementById("pan2").addEventListener('mousedown', function(){UI.setActiveDisplay(1);});
document.getElementById("pan3").addEventListener('mousedown', function(){UI.setActiveDisplay(2);});
// marker type selectors
document.getElementById("selectPickup").addEventListener('mousedown', function(){window.UI.markerTypeSelect("pickup")});
document.getElementById("selectComment").addEventListener('mousedown', function(){window.UI.markerTypeSelect("comment")});
document.getElementById("selectTrash").addEventListener('mousedown', function(){window.UI.markerTypeSelect("trash")});
document.getElementById("dialogCommentOk").addEventListener('mousedown', function(){
window.UI.dialogSliderDown();
});
document.getElementById("dialogCommentCancel").addEventListener('mousedown', function(){
window.UI.dialogSliderDown();
});
this.markerDisplay = document.getElementById("markerTypeDialog");
// toggle map overlays
window.UI.toggleHeat = document.getElementById('toggleHeat');
window.UI.toggleIcons = document.getElementById('toggleIcons');
window.UI.toggleIcons.addEventListener('mousedown', function(){
window.MAP.toggleIcons();
});
// for comment pagination
this.commentsType = ""
this.commentsNextPageUrl = "";
this.commentsPrevPageUrl = "";
document.getElementById("prevPage").addEventListener('mousedown', function(){
// load the previous page
window.ApiConnector.pullCommentData(this.commentsType, this.commentsPrevPageUrl);
});
document.getElementById("nextPage").addEventListener('mousedown', function(){
// load the previous page
window.ApiConnector.pullCommentData(this.commentsType, this.commentsNextPageUrl);
});
}
UiHandle.prototype.hideMarkerTypeSelect = function hideMarkerTypeSelect(){
console.log("in hideMarkerTypeSelect()");
window.UI.markerDisplay.style.display = "none";
window.UI.isMarkerDisplayVisible = false;
}
UiHandle.prototype.showMarkerTypeSelect = function showMarkerTypeSelect(){
console.log("in showMarkerTypeSelect()");
window.UI.markerDisplay.style.display = "block";
window.UI.isMarkerDisplayVisible = true;
}
UiHandle.prototype.setBigButtonColor = function setBigButtonColor(colorHex){
document.getElementById('bigButton').style.backgroundColor=colorHex;
}
UiHandle.prototype.setBigButtonText = function setBigButtonText(buttonText){
document.getElementById('bigButton').innerHTML = buttonText;
}
UiHandle.prototype.setMapLoaded = function setMapLoaded(){
window.MAP.isMapLoaded = true;
window.LS.hide();
}
// centers the appropriate panels
UiHandle.prototype.setActiveDisplay = function setActiveDisplay(displayNum){
var container = document.getElementById("container");
container.className = "";
switch(displayNum){
case 0:
this.currentDisplay = 1;
container.className = "panel1Center";
break;
case 1:
this.currentDisplay = 2;
container.className = "panel2Center";
break;
case 2:
this.currentDisplay = 3;
container.className = "panel3Center";
break;
default:
this.currentDisplay = 1;
container.className = "panel1Center";
}
}
// when the user chooses which type of marker to add to the map
UiHandle.prototype.markerTypeSelect = function markerTypeSelect(markerType){
// first we need to show the marker on the map
var iconUrl = "img/icons/blueCircle.png";
switch(markerType){
case "comment":
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
iconUrl = "img/icons/redCircle.png";
break;
default:
iconUrl = "img/icons/blueCircle.png";
break;
}
var marker = new google.maps.Marker({
position: window.MAP.markerEvent.latLng,
map: window.MAP.map,
icon: iconUrl
});
// second we need to get the user's message
// third we need to
// (bug) need to get the message input from the user
var message = "DEFAULT MESSAGE TEXT";
// here we add the appropriate marker to the map
window.MAP.addMarkerFromUi(markerType, message);
// window.UI.markerDisplay.style.display = "none";
// window.UI.isMarkerDisplayVisible = false;
window.UI.hideMarkerTypeSelect();
window.UI.dialogSliderUp();
// (bug) here we need to prevent more map touches
}
UiHandle.prototype.dialogSliderUp = function dialogSliderUp(){
document.getElementById("dialogSlider").style.top = "72%";
document.getElementById("dialogSlider").style.opacity = "1.0";
document.getElementById("dialogSliderTextarea").focus();
}
UiHandle.prototype.dialogSliderDown = function dialogSliderDown(){
document.getElementById("dialogSlider").style.top = "86%";
document.getElementById("dialogSlider").style.opacity = "0.0";
}
UiHandle.prototype.markerSelectUp = function markerSelectUp(){
// set the coords of the marker event
MOUSEUP_TIME = new Date().getTime() / 1000;
if((MOUSEUP_TIME - this.MOUSEDOWN_TIME) < 0.3){
if(this.isMarkerDisplayVisible){
window.UI.hideMarkerTypeSelect();
}else{
window.UI.showMarkerTypeSelect();
}
this.MOUSEDOWN_TIME =0;
this.MOUSEDOWN_TIME =0;
}else{
this.MOUSEDOWN_TIME =0;
this.MOUSEDOWN_TIME =0;
}
}
UiHandle.prototype.markerSelectDown = function markerSelectDown(event){
// set the coords of the marker event
window.MAP.markerEvent = event;
this.MOUSEDOWN_TIME = new Date().getTime() / 1000;
}
// ******* DOM updaters (callbacks for the ApiConnector pull methods) ***********
UiHandle.prototype.updateHeatmap = function updateHeatmap(data){
console.log(data);
}
UiHandle.prototype.updateMarker = function updateMarker(data){
//console.log("marker response: "+data);
var dataArr = eval("("+data+")");
// var dataArr = data;
for(ii=0; ii<dataArr.length; ii++){
// var dataA = dataArr[ii].split(",");
window.MAP.addMarkerFromApi(dataArr[ii].type, dataArr[ii].message, dataArr[ii].latDegrees, dataArr[ii].lonDegrees);
// heatmapData.push({location: new google.maps.LatLng(dataArr[ii][0], dataArr[ii][1]), weight: dataArr[ii][2]});
}
}
UiHandle.prototype.updateMessages = function updateMessages(data){
window.UI.commentsNextPageUrl = data.page.next;
window.UI.commentsPrevPageUrl = data.page.previous;
var messagesContainer = document.getElementById("messagesContainer");
var messages = new Array();
(window.UI.commentsNextPageUrl != null) ?
window.UI.showNextCommentsButton() : window.UI.hideNextCommentsButton();
(window.UI.commentsPrevPageUrl != null) ?
window.UI.showPrevCommentsButton() : window.UI.hidePrevCommentsButton();
for(ii=0; ii<3; ii++){
// for(ii=0; ii<data.comments.length; ii++){
messages[ii] = document.createElement('div');
messages[ii].className = "messageListItem";
messages[ii].style.border = "1px solid red";
// create the div where the timestamp will display
var commentDateContainer = document.createElement('div');
commentDateContainer.className = "commentDateContainer";
// commentDateContainer.innerHTML = data.comments.timestamp;
commentDateContainer.innerHTML = "1970-01-01 00:00:01";
// create the div where the message content will be stored
var messageContentContainer = document.createElement('div');
messageContentContainer.className = "messageContentContainer";
// messageContentContainer.innerHTML = data.comments.message;
messageContentContainer.innerHTML = "sdfasdfasdfasdfadsfasdfadsfa";
messages[ii].appendChild(commentDateContainer);
messages[ii].appendChild(messageContentContainer);
messagesContainer.appendChild(messages[ii]);
}
// // alert(window.UI.commentsNextPageUrl);
console.log(data);
}
UiHandle.prototype.updateNeeds = function updateNeeds(data){
console.log(data);
}
UiHandle.prototype.updateForum = function updateForum(data){
console.log(data);
}
UiHandle.prototype.updateTest = function updateTest(data){
console.log(data);
}
// ******** End DOM Updaters *********
// ---- begin pagination control toggle ----
UiHandle.prototype.showNextCommentsButton = function showNextCommentsButton(){
document.getElementById("nextPage").style.display = "inline-block";
}
UiHandle.prototype.hideNextCommentsButton = function hideNextCommentsButton(){
document.getElementById("nextPage").style.display = "none";
}
UiHandle.prototype.showPrevCommentsButton = function showPrevCommentsButton(){
document.getElementById("prevPage").style.display = "inline-block";
}
UiHandle.prototype.hidePrevCommentsButton = function hidePrevCommentsButton(){
document.getElementById("prevPage").style.display = "none";
}
// ---- end pagination control toggle
} // end UiHandle class def
// class for managing all geolocation work
function GpsHandle(){
GpsHandle.prototype.initGps = function initGps(){
db = Lawnchair({name : 'db'}, function(store) {
lawnDB = store;
setInterval(function() {window.GPS.runUpdate(store)},5000);//update user location every 5 seconds
setInterval(function() {window.ApiConnector.pushHeatmapData(store)},3000);//upload locations to the server every 30 seconds
});
}
//Runs the update script:
GpsHandle.prototype.runUpdate = function runUpdate(database){
//Grab the geolocation data from the local machine
navigator.geolocation.getCurrentPosition(function(position) {
window.GPS.updateLocation(database, position.coords.latitude, position.coords.longitude);
});
}
GpsHandle.prototype.updateLocation = function updateLocation(database, latitude, longitude){
if(window.logging){
var datetime = new Date().getTime();//generate timestamp
var location = {
"latitude" : latitude,
"longitude" : longitude,
"datetime" : datetime,
}
database.save({value:location});//Save the record
}
};
GpsHandle.prototype.recenterMap = function recenterMap(lat, lon){
console.log(lon);
var newcenter = new google.maps.LatLng(lat, lon);
centerPoint = newcenter;
map.panTo(newcenter);
}
GpsHandle.prototype.start = function start(){
window.UI.setBigButtonColor("#ff0000");
window.UI.setBigButtonText("Stop Cleaning");
window.logging = true;
this.initGps();
console.log("initializing GPS...");
navigator.geolocation.getCurrentPosition(function(p){
window.MAP.updateMap(p.coords.latitude, p.coords.longitude, 10);
});
}
GpsHandle.prototype.stop = function stop(){
window.ApiConnector.pushHeatmapData(lawnDB);
window.logging = false;
console.log("stopping...");
window.UI.setBigButtonColor("#00ff00");
window.UI.setBigButtonText("Start Cleaning");
}
} // end GpsHandle class def
// class for managing all Map work
function MapHandle(){
// BTV coords
this.currentLat = 44.476621500000000;
this.currentLon = -73.209998100000000;
this.currentZoom = 10;
this.markerEvent;
this.map;
this.pickupMarkers = [];
// fire up our google map
MapHandle.prototype.initMap = function initMap(){
window.LS.setLoadingText("Please wait while the map loads");
window.LS.show();
// define the initial location of our map
centerPoint = new google.maps.LatLng(window.MAP.currentLat, window.MAP.currentLon);
var mapOptions = {
zoom: window.MAP.currentZoom,
center: centerPoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
window.MAP.map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// for activating the loading screen while map loads
google.maps.event.addListener(window.MAP.map, 'idle', window.UI.setMapLoaded);
google.maps.event.addListener(window.MAP.map, 'center_changed', window.LS.show);
google.maps.event.addListener(window.MAP.map, 'zoom_changed', window.LS.show);
// our comment selector initializers
// google.maps.event.addListener(window.MAP.map, 'mousedown', this.setMarkerEvent);
google.maps.event.addListener(window.MAP.map, 'mousedown', window.UI.markerSelectDown);
google.maps.event.addListener(window.MAP.map, 'mouseup', window.UI.markerSelectUp);
}
MapHandle.prototype.addMarkerFromUi = function addMarkerFromUi(markerType, message){
// console.log("in addMarker()");
var pin = new Pin();
pin.message = message;
pin.type = markerType;
// pin.latDegrees = lat;
// pin.lonDegrees = lon;
var iconUrl;
switch(markerType){
case "comment":
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
pin.type = "help needed";
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
pin.type = "trash pickup";
iconUrl = "img/icons/redCircle.png";
break;
default:
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
}
var eventLatLng = window.MAP.markerEvent;
// console.log(eventLatLng.latLng);
pin.latDegrees = eventLatLng.latLng.jb;
pin.lonDegrees = eventLatLng.latLng.kb;
var serializedPin = JSON.stringify(pin);
console.log(serializedPin);
window.ApiConnector.pushNewPin(serializedPin);
}
MapHandle.prototype.addMarkerFromApi = function addMarkerFromApi(markerType, message, lat, lon){
// console.log("in addMarker()");
var pin = new Pin();
pin.message = message;
pin.type = markerType;
pin.latDegrees = lat;
pin.lonDegrees = lon;
var iconUrl;
switch(markerType){
case "comment":
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
case "pickup":
pin.type = "help needed";
iconUrl = "img/icons/greenCircle.png";
break;
case "trash":
pin.type = "trash pickup";
iconUrl = "img/icons/redCircle.png";
break;
default:
pin.type = "general message";
iconUrl = "img/icons/blueCircle.png";
break;
}
// test "bad type" response
// pin.type = "bullshit";
var marker = new google.maps.Marker({
position: new google.maps.LatLng(pin.latDegrees, pin.lonDegrees),
map: window.MAP.map,
icon: iconUrl
});
// pin.latDegrees = marker.getPosition().lat();
// pin.lonDegrees = marker.getPosition().lng();
// var serializedPin = JSON.stringify(pin);
// // alert(serializedPin);
// window.UI.markerDisplay.style.display = "none";
// window.UI.isMarkerDisplayVisible = false;
window.MAP.pickupMarkers.push(marker);
// console.log(window.MAP.pickupMarkers);
// window.MAP.updateMap(this.currentLat,this.currentLon, this.currentZoom);
// window.ApiConnector.pushNewPin(serializedPin);
}
MapHandle.prototype.updateMap = function updateMap(lat, lon, zoom){
window.UI.isMapLoaded = false;
var newcenter = new google.maps.LatLng(lat, lon);
window.MAP.map.panTo(newcenter);
}
MapHandle.prototype.toggleIcons = function toggleIcons(){
console.log("toggle icons: "+window.MAP.pickupMarkers.length);
if(window.UI.isMarkerVisible){
for(var ii=0; ii<window.MAP.pickupMarkers.length; ii++){
window.MAP.pickupMarkers[ii].setVisible(false);
window.UI.isMarkerVisible = false;
}
}else{
for(var ii=0; ii<window.MAP.pickupMarkers.length; ii++){
window.MAP.pickupMarkers[ii].setVisible(true);
window.UI.isMarkerVisible = true;
}
}
}
MapHandle.prototype.toggleHeatmap = function toggleHeatmap(){
}
MapHandle.prototype.setCurrentLat = function setCurrentLat(CurrentLat){
this.currentLat = CurrentLat;
}
MapHandle.prototype.setCurrentLon = function setCurrentLon(CurrentLon){
this.currentLon = CurrentLon;
}
MapHandle.prototype.setCurrentZoom = function setCurrentZoom(CurrentZoom){
this.currentZoom = CurrentZoom;
}
MapHandle.prototype.setMarkerEvent = function setMarkerEvent(event){
this.markerEvent = event;
}
MapHandle.prototype.getCurrentLat = function getCurrentLat(){
return currentLat;
}
MapHandle.prototype.getCurrentLon = function getCurrentLon(){
return this.currentLon;
}
MapHandle.prototype.getCurrentZoom = function getCurrentZoom(){
return this.currentZoom;
}
} //end MapHandle
// prototype objects for posting to API
function Pin(){
this.latDegrees;
this.lonDegrees;
this.type;
this.message = "I had to run to feed my cat, had to leave my Trash here sorry! Can someone pick it up?";
}
/**
* This is where all the action begins (once content is loaded)
* @author Josh
*/
document.addEventListener('DOMContentLoaded',function(){
document.addEventListener("touchmove", function(e){e.preventDefault();}, false);
window.ApiConnector = new ApiConnector();
window.UI = new UiHandle();
window.UI.init();
window.LS = new LoadingScreen(document.getElementById("loadingScreen"));
window.GPS = new GpsHandle();
window.MAP = new MapHandle();
window.MAP.initMap();
window.logging = false;
// window.ApiConnector.pullTestData();
window.ApiConnector.pullMarkerData();
document.getElementById("bigButton").addEventListener('mousedown', function(){
if(!window.logging){
window.GPS.start();
}else{
window.GPS.stop();
}
});
});
| #44 - Pin flow ui now working propery: The user taps the map --> presented with markerTypeSelect dialog --> user selects marker type ---> markerTypeSelect dialog fades ot --> marker icon is made visible on the map --> message input dialog slides up, user types a message and hits ok, the message is attached to the pin object, serialized, and then POSTed
| web/client/js/ApiConnector.js | #44 - Pin flow ui now working propery: The user taps the map --> presented with markerTypeSelect dialog --> user selects marker type ---> markerTypeSelect dialog fades ot --> marker icon is made visible on the map --> message input dialog slides up, user types a message and hits ok, the message is attached to the pin object, serialized, and then POSTed | <ide><path>eb/client/js/ApiConnector.js
<ide> document.getElementById("selectTrash").addEventListener('mousedown', function(){window.UI.markerTypeSelect("trash")});
<ide>
<ide> document.getElementById("dialogCommentOk").addEventListener('mousedown', function(){
<add> window.MAP.addMarkerFromUi(document.getElementById("dialogSliderTextarea").value);
<ide> window.UI.dialogSliderDown();
<ide> });
<ide>
<ide> break;
<ide> }
<ide>
<add> window.MAP.markerType = markerType;
<add>
<ide> var marker = new google.maps.Marker({
<ide> position: window.MAP.markerEvent.latLng,
<ide> map: window.MAP.map,
<ide>
<ide> // third we need to
<ide> // (bug) need to get the message input from the user
<del> var message = "DEFAULT MESSAGE TEXT";
<add> // var message = "DEFAULT MESSAGE TEXT";
<ide> // here we add the appropriate marker to the map
<del> window.MAP.addMarkerFromUi(markerType, message);
<add> // window.MAP.addMarkerFromUi(markerType, message);
<ide> // window.UI.markerDisplay.style.display = "none";
<ide> // window.UI.isMarkerDisplayVisible = false;
<ide> window.UI.hideMarkerTypeSelect();
<ide> this.currentLon = -73.209998100000000;
<ide> this.currentZoom = 10;
<ide> this.markerEvent;
<add> this.markerType;
<ide> this.map;
<ide> this.pickupMarkers = [];
<ide> // fire up our google map
<ide> google.maps.event.addListener(window.MAP.map, 'mouseup', window.UI.markerSelectUp);
<ide> }
<ide>
<del> MapHandle.prototype.addMarkerFromUi = function addMarkerFromUi(markerType, message){
<add> MapHandle.prototype.addMarkerFromUi = function addMarkerFromUi(message){
<ide> // console.log("in addMarker()");
<ide> var pin = new Pin();
<ide> pin.message = message;
<del> pin.type = markerType;
<add> pin.type = window.MAP.markerType;
<ide> // pin.latDegrees = lat;
<ide> // pin.lonDegrees = lon;
<ide>
<ide> var iconUrl;
<del> switch(markerType){
<add> switch(window.MAP.markerType){
<ide> case "comment":
<ide> pin.type = "general message";
<ide> iconUrl = "img/icons/blueCircle.png"; |
|
Java | agpl-3.0 | 263a61109eb5e257227872686c0fe99621644e9d | 0 | mnlipp/jgrapes,mnlipp/jgrapes | /*
* JGrapes Event Driven Framework
* Copyright (C) 2016-2018 Michael N. Lipp
*
* This program 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.jgrapes.core;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* A class for events using a simple name as the event's kind.
*/
public final class NamedEvent<T> extends Event<T> {
private String kind;
private Map<Object,Object> data;
/**
* Creates a new named event with the given name.
*
* @param kind the event's kind
*/
public NamedEvent(String kind) {
super();
this.kind = kind;
}
/**
* Returns the kind of the event as the String passed to the
* constructor.
*
* @return the kind
*
* @see org.jgrapes.core.Channel#defaultCriterion()
*/
@Override
public Object defaultCriterion() {
return kind;
}
/**
* Returns `true` if the criterion is `Event.class` (representing
* "any event") or if the criterion is a String equal to this
* event's kind (the String passed to the constructor).
*
* @see org.jgrapes.core.Eligible#isEligibleFor(java.lang.Object)
*/
@Override
public boolean isEligibleFor(Object criterion) {
return criterion.equals(Event.class) || criterion.equals(kind);
}
/**
* Returns a map with data that belongs to the event. The map
* is only created if requested. If a component uses
* {@link NamedEvent}s and data that consists of JDK types only,
* it is completely loosely coupled.
*
* @return the map
*/
public Map<Object,Object> data() {
if (data == null) {
data = new HashMap<>();
}
return data;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("NamedEvent [name=");
result.append(kind);
if (channels() != null) {
result.append(", " + "channels=" + Arrays.toString(channels()));
}
result.append("]");
return result.toString();
}
}
| org.jgrapes.core/src/org/jgrapes/core/NamedEvent.java | /*
* JGrapes Event Driven Framework
* Copyright (C) 2016-2018 Michael N. Lipp
*
* This program 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.jgrapes.core;
import java.util.Arrays;
/**
* A class for events using a simple name as the event's kind.
*/
public final class NamedEvent<T> extends Event<T> {
private String kind;
/**
* Creates a new named event with the given name.
*
* @param kind the event's kind
*/
public NamedEvent(String kind) {
super();
this.kind = kind;
}
/**
* Returns the kind of the event as the String passed to the
* constructor.
*
* @return the kind
*
* @see org.jgrapes.core.Channel#defaultCriterion()
*/
@Override
public Object defaultCriterion() {
return kind;
}
/**
* Returns `true` if the criterion is `Event.class` (representing
* "any event") or if the criterion is a String equal to this
* event's kind (the String passed to the constructor).
*
* @see org.jgrapes.core.Eligible#isEligibleFor(java.lang.Object)
*/
@Override
public boolean isEligibleFor(Object criterion) {
return criterion.equals(Event.class) || criterion.equals(kind);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("NamedEvent [name=");
result.append(kind);
if (channels() != null) {
result.append(", " + "channels=" + Arrays.toString(channels()));
}
result.append("]");
return result.toString();
}
}
| Added data(). | org.jgrapes.core/src/org/jgrapes/core/NamedEvent.java | Added data(). | <ide><path>rg.jgrapes.core/src/org/jgrapes/core/NamedEvent.java
<ide> package org.jgrapes.core;
<ide>
<ide> import java.util.Arrays;
<add>import java.util.HashMap;
<add>import java.util.Map;
<ide>
<ide> /**
<ide> * A class for events using a simple name as the event's kind.
<ide> public final class NamedEvent<T> extends Event<T> {
<ide>
<ide> private String kind;
<add> private Map<Object,Object> data;
<ide>
<ide> /**
<ide> * Creates a new named event with the given name.
<ide> return criterion.equals(Event.class) || criterion.equals(kind);
<ide> }
<ide>
<add> /**
<add> * Returns a map with data that belongs to the event. The map
<add> * is only created if requested. If a component uses
<add> * {@link NamedEvent}s and data that consists of JDK types only,
<add> * it is completely loosely coupled.
<add> *
<add> * @return the map
<add> */
<add> public Map<Object,Object> data() {
<add> if (data == null) {
<add> data = new HashMap<>();
<add> }
<add> return data;
<add> }
<add>
<ide> /* (non-Javadoc)
<ide> * @see java.lang.Object#toString()
<ide> */ |
|
Java | apache-2.0 | 4a94fd1da931446faf8bc08b4da111bde131db2f | 0 | blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle | /*
* Copyright 2007 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.gradle.api.tasks.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import groovy.lang.Closure;
import org.apache.tools.ant.DirectoryScanner;
import org.gradle.api.Action;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.RelativePathSpec;
import org.gradle.api.internal.file.pattern.PatternMatcherFactory;
import org.gradle.api.specs.*;
import org.gradle.api.tasks.AntBuilderAware;
import org.gradle.api.tasks.util.internal.PatternSetAntBuilderDelegate;
import org.gradle.util.CollectionUtils;
import java.util.*;
/**
* Standalone implementation of {@link PatternFilterable}.
*/
public class PatternSet implements AntBuilderAware, PatternFilterable {
private final Set<String> includes = Sets.newLinkedHashSet();
private final Set<String> excludes = Sets.newLinkedHashSet();
private final Set<Spec<FileTreeElement>> includeSpecs = Sets.newLinkedHashSet();
private final Set<Spec<FileTreeElement>> excludeSpecs = Sets.newLinkedHashSet();
boolean caseSensitive = true;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatternSet that = (PatternSet) o;
if (caseSensitive != that.caseSensitive) {
return false;
}
if (!excludes.equals(that.excludes)) {
return false;
}
if (!includes.equals(that.includes)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = includes.hashCode();
result = 31 * result + excludes.hashCode();
result = 31 * result + (caseSensitive ? 1 : 0);
return result;
}
public PatternSet copyFrom(PatternFilterable sourcePattern) {
setIncludes(sourcePattern.getIncludes());
setExcludes(sourcePattern.getExcludes());
PatternSet other = (PatternSet) sourcePattern;
includeSpecs.clear();
includeSpecs.addAll(other.includeSpecs);
excludeSpecs.clear();
excludeSpecs.addAll(other.excludeSpecs);
return this;
}
public PatternSet intersect() {
return new IntersectionPatternSet(this);
}
private static class IntersectionPatternSet extends PatternSet {
private final PatternSet other;
public IntersectionPatternSet(PatternSet other) {
this.other = other;
}
public Spec<FileTreeElement> getAsSpec() {
return new AndSpec<FileTreeElement>(super.getAsSpec(), other.getAsSpec());
}
public Object addToAntBuilder(Object node, String childNodeName) {
return PatternSetAntBuilderDelegate.and(node, new Action<Object>() {
public void execute(Object andNode) {
IntersectionPatternSet.super.addToAntBuilder(andNode, null);
other.addToAntBuilder(andNode, null);
}
});
}
}
public Spec<FileTreeElement> getAsSpec() {
return new AndSpec<FileTreeElement>(getAsIncludeSpec(), new NotSpec<FileTreeElement>(getAsExcludeSpec()));
}
public Spec<FileTreeElement> getAsIncludeSpec() {
List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
for (String include : includes) {
Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(true, caseSensitive, include);
matchers.add(new RelativePathSpec(patternMatcher));
}
matchers.addAll(includeSpecs);
return new OrSpec<FileTreeElement>(matchers);
}
public Spec<FileTreeElement> getAsExcludeSpec() {
Collection<String> allExcludes = Sets.newLinkedHashSet(excludes);
Collections.addAll(allExcludes, DirectoryScanner.getDefaultExcludes());
List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
for (String exclude : allExcludes) {
Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(false, caseSensitive, exclude);
matchers.add(new RelativePathSpec(patternMatcher));
}
matchers.addAll(excludeSpecs);
return new OrSpec<FileTreeElement>(matchers);
}
public Set<String> getIncludes() {
return includes;
}
public Set<Spec<FileTreeElement>> getIncludeSpecs() {
return includeSpecs;
}
public PatternSet setIncludes(Iterable<String> includes) {
this.includes.clear();
return include(includes);
}
public PatternSet include(String... includes) {
Collections.addAll(this.includes, includes);
return this;
}
public PatternSet include(Iterable includes) {
// handles GStrings
for (Object include : includes) {
this.includes.add(include.toString());
}
return this;
}
public PatternSet include(Spec<FileTreeElement> spec) {
includeSpecs.add(spec);
return this;
}
public Set<String> getExcludes() {
return excludes;
}
public Set<Spec<FileTreeElement>> getExcludeSpecs() {
return excludeSpecs;
}
public PatternSet setExcludes(Iterable<String> excludes) {
this.excludes.clear();
return exclude(excludes);
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/*
This can't be called just include, because it has the same erasure as include(Iterable<String>).
*/
public PatternSet includeSpecs(Iterable<Spec<FileTreeElement>> includeSpecs) {
CollectionUtils.addAll(this.includeSpecs, includeSpecs);
return this;
}
public PatternSet include(Closure closure) {
include(Specs.<FileTreeElement>convertClosureToSpec(closure));
return this;
}
public PatternSet exclude(String... excludes) {
Collections.addAll(this.excludes, excludes);
return this;
}
public PatternSet exclude(Iterable excludes) {
// handles GStrings
for (Object exclude : excludes) {
this.excludes.add(exclude.toString());
}
return this;
}
public PatternSet exclude(Spec<FileTreeElement> spec) {
excludeSpecs.add(spec);
return this;
}
public PatternSet excludeSpecs(Iterable<Spec<FileTreeElement>> excludes) {
CollectionUtils.addAll(this.excludeSpecs, excludes);
return this;
}
public PatternSet exclude(Closure closure) {
exclude(Specs.<FileTreeElement>convertClosureToSpec(closure));
return this;
}
public Object addToAntBuilder(Object node, String childNodeName) {
if (!includeSpecs.isEmpty() || !excludeSpecs.isEmpty()) {
throw new UnsupportedOperationException("Cannot add include/exclude specs to Ant node. Only include/exclude patterns are currently supported.");
}
return new PatternSetAntBuilderDelegate(includes, excludes, caseSensitive).addToAntBuilder(node, childNodeName);
}
}
| subprojects/core/src/main/groovy/org/gradle/api/tasks/util/PatternSet.java | /*
* Copyright 2007 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.gradle.api.tasks.util;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import groovy.lang.Closure;
import org.apache.tools.ant.DirectoryScanner;
import org.gradle.api.Action;
import org.gradle.api.file.FileTreeElement;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.RelativePathSpec;
import org.gradle.api.internal.file.pattern.PatternMatcherFactory;
import org.gradle.api.specs.*;
import org.gradle.api.tasks.AntBuilderAware;
import org.gradle.api.tasks.util.internal.PatternSetAntBuilderDelegate;
import org.gradle.util.CollectionUtils;
import java.util.*;
/**
* Standalone implementation of {@link PatternFilterable}.
*/
public class PatternSet implements AntBuilderAware, PatternFilterable {
private final Set<String> includes = Sets.newLinkedHashSet();
private final Set<String> excludes = Sets.newLinkedHashSet();
private final Set<Spec<FileTreeElement>> includeSpecs = Sets.newLinkedHashSet();
private final Set<Spec<FileTreeElement>> excludeSpecs = Sets.newLinkedHashSet();
boolean caseSensitive = true;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatternSet that = (PatternSet) o;
if (caseSensitive != that.caseSensitive) {
return false;
}
if (!excludes.equals(that.excludes)) {
return false;
}
if (!includes.equals(that.includes)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = includes.hashCode();
result = 31 * result + excludes.hashCode();
result = 31 * result + (caseSensitive ? 1 : 0);
return result;
}
public PatternSet copyFrom(PatternFilterable sourcePattern) {
setIncludes(sourcePattern.getIncludes());
setExcludes(sourcePattern.getExcludes());
PatternSet other = (PatternSet) sourcePattern;
includeSpecs.clear();
includeSpecs.addAll(other.includeSpecs);
excludeSpecs.clear();
excludeSpecs.addAll(other.excludeSpecs);
return this;
}
public PatternSet intersect() {
return new IntersectionPatternSet(this);
}
private static class IntersectionPatternSet extends PatternSet {
private final PatternSet other;
public IntersectionPatternSet(PatternSet other) {
this.other = other;
}
public Spec<FileTreeElement> getAsSpec() {
return new AndSpec<FileTreeElement>(super.getAsSpec(), other.getAsSpec());
}
public Object addToAntBuilder(Object node, String childNodeName) {
return PatternSetAntBuilderDelegate.and(node, new Action<Object>() {
public void execute(Object andNode) {
IntersectionPatternSet.super.addToAntBuilder(andNode, null);
other.addToAntBuilder(andNode, null);
}
});
}
}
public Spec<FileTreeElement> getAsSpec() {
return new AndSpec<FileTreeElement>(getAsIncludeSpec(), new NotSpec<FileTreeElement>(getAsExcludeSpec()));
}
public Spec<FileTreeElement> getAsIncludeSpec() {
List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
for (String include : includes) {
Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(true, caseSensitive, include);
matchers.add(new RelativePathSpec(patternMatcher));
}
matchers.addAll(includeSpecs);
return new OrSpec<FileTreeElement>(matchers);
}
public Spec<FileTreeElement> getAsExcludeSpec() {
Collection<String> allExcludes = Sets.newLinkedHashSet(excludes);
Collections.addAll(allExcludes, DirectoryScanner.getDefaultExcludes());
List<Spec<FileTreeElement>> matchers = Lists.newArrayList();
for (String exclude : allExcludes) {
Spec<RelativePath> patternMatcher = PatternMatcherFactory.getPatternMatcher(false, caseSensitive, exclude);
matchers.add(new RelativePathSpec(patternMatcher));
}
matchers.addAll(excludeSpecs);
return new OrSpec<FileTreeElement>(matchers);
}
public Set<String> getIncludes() {
return includes;
}
public Set<Spec<FileTreeElement>> getIncludeSpecs() {
return includeSpecs;
}
public PatternSet setIncludes(Iterable<String> includes) {
this.includes.clear();
return include(includes);
}
public PatternSet include(String... includes) {
Collections.addAll(this.includes, includes);
return this;
}
public PatternSet include(Iterable<String> includes) {
// handles GStrings
for (Object include : includes) {
this.includes.add(include.toString());
}
return this;
}
public PatternSet include(Spec<FileTreeElement> spec) {
includeSpecs.add(spec);
return this;
}
public Set<String> getExcludes() {
return excludes;
}
public Set<Spec<FileTreeElement>> getExcludeSpecs() {
return excludeSpecs;
}
public PatternSet setExcludes(Iterable<String> excludes) {
this.excludes.clear();
return exclude(excludes);
}
public boolean isCaseSensitive() {
return caseSensitive;
}
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/*
This can't be called just include, because it has the same erasure as include(Iterable<String>).
*/
public PatternSet includeSpecs(Iterable<Spec<FileTreeElement>> includeSpecs) {
CollectionUtils.addAll(this.includeSpecs, includeSpecs);
return this;
}
public PatternSet include(Closure closure) {
include(Specs.<FileTreeElement>convertClosureToSpec(closure));
return this;
}
public PatternSet exclude(String... excludes) {
Collections.addAll(this.excludes, excludes);
return this;
}
public PatternSet exclude(Iterable<String> excludes) {
// handles GStrings
for (Object exclude : excludes) {
this.excludes.add(exclude.toString());
}
return this;
}
public PatternSet exclude(Spec<FileTreeElement> spec) {
excludeSpecs.add(spec);
return this;
}
public PatternSet excludeSpecs(Iterable<Spec<FileTreeElement>> excludes) {
CollectionUtils.addAll(this.excludeSpecs, excludes);
return this;
}
public PatternSet exclude(Closure closure) {
exclude(Specs.<FileTreeElement>convertClosureToSpec(closure));
return this;
}
public Object addToAntBuilder(Object node, String childNodeName) {
if (!includeSpecs.isEmpty() || !excludeSpecs.isEmpty()) {
throw new UnsupportedOperationException("Cannot add include/exclude specs to Ant node. Only include/exclude patterns are currently supported.");
}
return new PatternSetAntBuilderDelegate(includes, excludes, caseSensitive).addToAntBuilder(node, childNodeName);
}
}
| experimental change to allow passing of GStrings to include/exclude methods
| subprojects/core/src/main/groovy/org/gradle/api/tasks/util/PatternSet.java | experimental change to allow passing of GStrings to include/exclude methods | <ide><path>ubprojects/core/src/main/groovy/org/gradle/api/tasks/util/PatternSet.java
<ide> return this;
<ide> }
<ide>
<del> public PatternSet include(Iterable<String> includes) {
<add> public PatternSet include(Iterable includes) {
<ide> // handles GStrings
<ide> for (Object include : includes) {
<ide> this.includes.add(include.toString());
<ide> return this;
<ide> }
<ide>
<del> public PatternSet exclude(Iterable<String> excludes) {
<add> public PatternSet exclude(Iterable excludes) {
<ide> // handles GStrings
<ide> for (Object exclude : excludes) {
<ide> this.excludes.add(exclude.toString()); |
|
JavaScript | mit | 609f03480e25cec7c86dcdcc1da1611334038d13 | 0 | mjgreeno/webscraper,mjgreeno/webscraper | let express = require('express');
const app = require('express')();
const routes = require('./app/routes');
let router = express.Router();
app.set('view engine', 'pug');
const bodyParser = require('body-parser');
let port = process.env.PORT || 3434;
const request = require('request');
const fs = require('fs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', routes);
app.listen(port);
console.log('Welcome Srappy the WordPress scraper is running: ' + port);
| server.js | var express = require('express');
const app = require('express')();
const routes = require('./app/routes');
var router = express.Router();
app.set('view engine', 'pug');
const bodyParser = require('body-parser');
var port = process.env.PORT || 3434;
var x = require('x-ray');
const request = require('request');
const fs = require('fs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', routes);
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);
| adding server cleanup
| server.js | adding server cleanup | <ide><path>erver.js
<del>var express = require('express');
<add>let express = require('express');
<ide> const app = require('express')();
<ide> const routes = require('./app/routes');
<del>var router = express.Router();
<add>let router = express.Router();
<ide> app.set('view engine', 'pug');
<ide> const bodyParser = require('body-parser');
<del>var port = process.env.PORT || 3434;
<del>var x = require('x-ray');
<add>let port = process.env.PORT || 3434;
<ide> const request = require('request');
<ide> const fs = require('fs');
<add>
<ide> app.use(bodyParser.json());
<ide> app.use(bodyParser.urlencoded({
<ide> extended: true
<ide>
<ide> app.use('/', routes);
<ide>
<del>
<del>
<ide> app.listen(port);
<del>console.log('todo list RESTful API server started on: ' + port);
<add>console.log('Welcome Srappy the WordPress scraper is running: ' + port);
<ide>
<ide> |
|
Java | apache-2.0 | 48a5646946533835fc1efb9ad04f74c35232893d | 0 | subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/base,subutai-io/Subutai | package org.safehaus.subutai.core.peer.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.safehaus.subutai.common.enums.ResponseType;
import org.safehaus.subutai.common.exception.CommandException;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.CommandCallback;
import org.safehaus.subutai.common.protocol.CommandResult;
import org.safehaus.subutai.common.protocol.CommandStatus;
import org.safehaus.subutai.common.protocol.NullAgent;
import org.safehaus.subutai.common.protocol.RequestBuilder;
import org.safehaus.subutai.common.protocol.Response;
import org.safehaus.subutai.common.protocol.ResponseListener;
import org.safehaus.subutai.common.protocol.Template;
import org.safehaus.subutai.core.agent.api.AgentManager;
import org.safehaus.subutai.core.command.api.CommandRunner;
import org.safehaus.subutai.core.command.api.command.AgentResult;
import org.safehaus.subutai.core.command.api.command.Command;
import org.safehaus.subutai.core.communication.api.CommunicationManager;
import org.safehaus.subutai.core.lxc.quota.api.QuotaEnum;
import org.safehaus.subutai.core.lxc.quota.api.QuotaException;
import org.safehaus.subutai.core.lxc.quota.api.QuotaManager;
import org.safehaus.subutai.core.peer.api.BindHostException;
import org.safehaus.subutai.core.peer.api.ContainerHost;
import org.safehaus.subutai.core.peer.api.ContainerState;
import org.safehaus.subutai.core.peer.api.Host;
import org.safehaus.subutai.core.peer.api.LocalPeer;
import org.safehaus.subutai.core.peer.api.ManagementHost;
import org.safehaus.subutai.core.peer.api.Payload;
import org.safehaus.subutai.core.peer.api.PeerException;
import org.safehaus.subutai.core.peer.api.PeerInfo;
import org.safehaus.subutai.core.peer.api.PeerManager;
import org.safehaus.subutai.core.peer.api.RequestListener;
import org.safehaus.subutai.core.peer.api.ResourceHost;
import org.safehaus.subutai.core.peer.api.ResourceHostException;
import org.safehaus.subutai.core.peer.api.SubutaiHost;
import org.safehaus.subutai.core.peer.api.SubutaiInitException;
import org.safehaus.subutai.core.peer.impl.dao.PeerDAO;
import org.safehaus.subutai.core.registry.api.RegistryException;
import org.safehaus.subutai.core.registry.api.TemplateRegistry;
import org.safehaus.subutai.core.strategy.api.Criteria;
import org.safehaus.subutai.core.strategy.api.ServerMetric;
import org.safehaus.subutai.core.strategy.api.StrategyException;
import org.safehaus.subutai.core.strategy.api.StrategyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Local peer implementation
*/
public class LocalPeerImpl implements LocalPeer, ResponseListener
{
private static final Logger LOG = LoggerFactory.getLogger( LocalPeerImpl.class );
private static final String SOURCE_MANAGEMENT_HOST = "MANAGEMENT_HOST";
private static final String SOURCE_RESOURCE_HOST = "RESOURCE_HOST";
private static final long HOST_INACTIVE_TIME = 5 * 1000 * 60; // 5 min
private static final int MAX_LXC_NAME = 15;
private PeerManager peerManager;
// private ContainerManager containerManager;
private TemplateRegistry templateRegistry;
private CommunicationManager communicationManager;
private PeerDAO peerDAO;
private ManagementHost managementHost;
private Set<ResourceHost> resourceHosts = Sets.newHashSet();
private CommandRunner commandRunner;
private AgentManager agentManager;
private StrategyManager strategyManager;
private QuotaManager quotaManager;
private ConcurrentMap<String, AtomicInteger> sequences;
private Set<RequestListener> requestListeners;
public LocalPeerImpl( PeerManager peerManager, AgentManager agentManager, TemplateRegistry templateRegistry,
PeerDAO peerDao, CommunicationManager communicationManager, CommandRunner commandRunner,
QuotaManager quotaManager, StrategyManager strategyManager,
Set<RequestListener> requestListeners )
{
this.agentManager = agentManager;
this.strategyManager = strategyManager;
this.peerManager = peerManager;
// this.containerManager = containerManager;
this.templateRegistry = templateRegistry;
this.peerDAO = peerDao;
this.communicationManager = communicationManager;
this.commandRunner = commandRunner;
this.quotaManager = quotaManager;
this.requestListeners = requestListeners;
}
@Override
public void init()
{
List<ManagementHost> r1 = peerDAO.getInfo( SOURCE_MANAGEMENT_HOST, ManagementHost.class );
if ( r1.size() > 0 )
{
managementHost = r1.get( 0 );
managementHost.resetHeartbeat();
}
resourceHosts = Sets.newHashSet( peerDAO.getInfo( SOURCE_RESOURCE_HOST, ResourceHost.class ) );
for ( ResourceHost resourceHost : resourceHosts )
{
resourceHost.resetHeartbeat();
}
communicationManager.addListener( this );
sequences = new ConcurrentHashMap<>();
}
@Override
public void shutdown()
{
communicationManager.removeListener( this );
}
@Override
public UUID getId()
{
return peerManager.getLocalPeerInfo().getId();
}
@Override
public String getName()
{
return peerManager.getLocalPeerInfo().getName();
}
@Override
public UUID getOwnerId()
{
return peerManager.getLocalPeerInfo().getOwnerId();
}
@Override
public PeerInfo getPeerInfo()
{
return peerManager.getLocalPeerInfo();
}
@Override
public ContainerHost createContainer( final String hostName, final String templateName, final String cloneName,
final UUID envId ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( hostName );
ContainerHost containerHost = resourceHost
.createContainer( getId(), envId, Lists.newArrayList( getTemplate( templateName ) ), cloneName );
resourceHost.addContainerHost( containerHost );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
return containerHost;
}
// public ContainerHost createContainer( final ResourceHost resourceHost, final UUID creatorPeerId,
// final UUID environmentId, final List<Template> templates,
// final String containerName ) throws PeerException
// {
// return resourceHost.createContainer( creatorPeerId, environmentId, templates, containerName );
// }
// @Override
// public Set<ContainerHost> createContainers( final UUID creatorPeerId, final UUID environmentId,
// final List<Template> templates, final int quantity,
// final String strategyId, final List<Criteria> criteria )
// throws ContainerCreateException
// {
// Set<ContainerHost> result = new HashSet<>();
// try
// {
// for ( Template t : templates )
// {
// if ( t.isRemote() )
// {
// tryToRegister( t );
// }
// }
// String templateName = templates.get( templates.size() - 1 ).getTemplateName();
// Set<Agent> agents = containerManager.clone( environmentId, templateName, quantity, strategyId,
// criteria );
//
//
// for ( Agent agent : agents )
// {
// ResourceHost resourceHost = getResourceHostByName( agent.getParentHostName() );
// ContainerHost containerHost = new ContainerHost( agent, getId(), environmentId );
// containerHost.setParentAgent( resourceHost.getAgent() );
// containerHost.setCreatorPeerId( creatorPeerId );
// containerHost.setTemplateName( templateName );
// containerHost.updateHeartbeat();
// resourceHost.addContainerHost( containerHost );
// result.add( containerHost );
// peerDAO.saveInfo( SOURCE_MANAGEMENT, managementHost.getId().toString(), managementHost );
// }
// }
// catch ( PeerException | RegistryException e )
// {
// throw new ContainerCreateException( e.toString() );
// }
// return result;
// }
@Override
public Set<ContainerHost> createContainers( final UUID creatorPeerId, final UUID environmentId,
final List<Template> templates, final int quantity,
final String strategyId, final List<Criteria> criteria )
throws PeerException
{
Set<ContainerHost> result = new HashSet<>();
try
{
for ( Template t : templates )
{
if ( t.isRemote() )
{
tryToRegister( t );
}
}
String templateName = templates.get( templates.size() - 1 ).getTemplateName();
List<ServerMetric> serverMetricMap = new ArrayList<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.isConnected() )
{
serverMetricMap.add( resourceHost.getMetric() );
}
}
Map<ServerMetric, Integer> slots;
try
{
slots = strategyManager.getPlacementDistribution( serverMetricMap, quantity, strategyId, criteria );
}
catch ( StrategyException e )
{
throw new PeerException( e.getMessage() );
}
Set<String> existingContainerNames = getContainerNames();
// clone specified number of instances and store their names
Map<ResourceHost, Set<String>> cloneNames = new HashMap<>();
for ( Map.Entry<ServerMetric, Integer> e : slots.entrySet() )
{
Set<String> hostCloneNames = new HashSet<>();
for ( int i = 0; i < e.getValue(); i++ )
{
String newContainerName = nextHostName( templateName, existingContainerNames );
hostCloneNames.add( newContainerName );
}
ResourceHost resourceHost = getResourceHostByName( e.getKey().getHostname() );
cloneNames.put( resourceHost, hostCloneNames );
}
for ( final Map.Entry<ResourceHost, Set<String>> e : cloneNames.entrySet() )
{
ResourceHost rh = e.getKey();
Set<String> clones = e.getValue();
ResourceHost resourceHost = getResourceHostByName( rh.getHostname() );
for ( String cloneName : clones )
{
ContainerHost containerHost =
resourceHost.createContainer( creatorPeerId, environmentId, templates, cloneName );
resourceHost.addContainerHost( containerHost );
result.add( containerHost );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
}
}
}
catch ( RegistryException e )
{
throw new PeerException( e.toString() );
}
return result;
}
private String nextHostName( String templateName, Set<String> existingNames )
{
AtomicInteger i = sequences.putIfAbsent( templateName, new AtomicInteger() );
if ( i == null )
{
i = sequences.get( templateName );
}
while ( true )
{
String suffix = String.valueOf( i.incrementAndGet() );
int prefixLen = MAX_LXC_NAME - suffix.length();
String name = ( templateName.length() > prefixLen ? templateName.substring( 0, prefixLen ) : templateName )
+ suffix;
if ( !existingNames.contains( name ) )
{
return name;
}
}
}
private Set<String> getContainerNames() throws PeerException
{
Set<String> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
for ( ContainerHost containerHost : resourceHost.getContainerHosts() )
{
result.add( containerHost.getHostname() );
}
}
return result;
}
private void tryToRegister( final Template template ) throws RegistryException
{
if ( templateRegistry.getTemplate( template.getTemplateName() ) == null )
{
templateRegistry.registerTemplate( template );
}
}
@Override
public ContainerHost getContainerHostByName( String hostname )
{
ContainerHost result = null;
Iterator<ResourceHost> iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
result = iterator.next().getContainerHostByName( hostname );
}
return result;
}
@Override
public ResourceHost getResourceHostByName( String hostname )
{
ResourceHost result = null;
Iterator iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
ResourceHost host = ( ResourceHost ) iterator.next();
if ( host.getHostname().equals( hostname ) )
{
result = host;
}
}
return result;
}
@Override
public Set<ContainerHost> getContainerHostsByEnvironmentId( final UUID environmentId ) throws PeerException
{
Set<ContainerHost> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
result.addAll( resourceHost.getContainerHostsByEnvironmentId( environmentId ) );
}
return result;
}
@Override
public Host bindHost( UUID id ) throws PeerException
{
Host result = null;
ManagementHost managementHost = getManagementHost();
if ( managementHost != null && managementHost.getId().equals( id ) )
{
result = managementHost;
}
else
{
Iterator<ResourceHost> iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
ResourceHost rh = iterator.next();
if ( rh.getId().equals( id ) )
{
result = rh;
}
else
{
result = rh.getContainerHostById( id );
}
}
}
if ( result == null )
{
throw new BindHostException( id );
}
return result;
}
@Override
public void startContainer( final ContainerHost containerHost ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getParentHostname() );
try
{
if ( resourceHost.startContainerHost( containerHost ) )
{
containerHost.setState( ContainerState.RUNNING );
}
}
catch ( CommandException e )
{
containerHost.setState( ContainerState.UNKNOWN );
throw new PeerException( String.format( "Could not start LXC container [%s]", e.toString() ) );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public void stopContainer( final ContainerHost containerHost ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getParentHostname() );
try
{
if ( resourceHost.stopContainerHost( containerHost ) )
{
containerHost.setState( ContainerState.STOPPED );
}
}
catch ( CommandException e )
{
containerHost.setState( ContainerState.UNKNOWN );
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public void destroyContainer( final ContainerHost containerHost ) throws PeerException
{
Host result = bindHost( containerHost.getId() );
if ( result == null )
{
throw new PeerException( "Container Host not found." );
}
try
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getAgent().getParentHostName() );
resourceHost.destroyContainerHost( containerHost );
resourceHost.removeContainerHost( result );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
}
catch ( ResourceHostException e )
{
throw new PeerException( e.toString() );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public boolean isConnected( final Host host ) throws PeerException
{
if ( host instanceof ContainerHost )
{
return ContainerState.RUNNING.equals( ( ( ContainerHost ) host ).getState() ) && checkHeartbeat(
host.getLastHeartbeat() );
}
else
{
return checkHeartbeat( host.getLastHeartbeat() );
}
}
@Override
public String getQuota( ContainerHost host, final QuotaEnum quota ) throws PeerException
{
try
{
return quotaManager.getQuota( host.getHostname(), quota, host.getParentAgent() );
}
catch ( QuotaException e )
{
throw new PeerException( e.toString() );
}
}
@Override
public void setQuota( ContainerHost host, final QuotaEnum quota, final String value ) throws PeerException
{
try
{
quotaManager.setQuota( host.getHostname(), quota, value, host.getParentAgent() );
}
catch ( QuotaException e )
{
throw new PeerException( e.toString() );
}
}
private boolean checkHeartbeat( long lastHeartbeat )
{
return ( System.currentTimeMillis() - lastHeartbeat ) < HOST_INACTIVE_TIME;
}
@Override
public ManagementHost getManagementHost() throws PeerException
{
return managementHost;
}
@Override
public Set<ResourceHost> getResourceHosts()
{
return resourceHosts;
}
@Override
public List<String> getTemplates()
{
List<Template> templates = templateRegistry.getAllTemplates();
List<String> result = new ArrayList<>();
for ( Template template : templates )
{
result.add( template.getTemplateName() );
}
return result;
}
public void addResourceHost( final ResourceHost host )
{
if ( host == null )
{
throw new IllegalArgumentException( "Resource host could not be null." );
}
resourceHosts.add( host );
}
@Override
public void onResponse( final Response response )
{
if ( response == null || response.getType() == null )
{
return;
}
if ( response.getType().equals( ResponseType.REGISTRATION_REQUEST ) || response.getType().equals(
ResponseType.HEARTBEAT_RESPONSE ) )
{
if ( response.getHostname().equals( "management" ) )
{
if ( managementHost == null )
{
managementHost = new ManagementHost( PeerUtils.buildAgent( response ), getId() );
managementHost.setParentAgent( NullAgent.getInstance() );
try
{
managementHost.init();
}
catch ( SubutaiInitException e )
{
LOG.error( e.toString() );
}
}
managementHost.updateHeartbeat();
peerDAO.saveInfo( SOURCE_MANAGEMENT_HOST, managementHost.getId().toString(), managementHost );
return;
}
if ( response.getHostname().startsWith( "py" ) )
{
ResourceHost host = getResourceHostByName( response.getHostname() );
if ( host == null )
{
host = new ResourceHost( PeerUtils.buildAgent( response ), getId() );
host.setParentAgent( NullAgent.getInstance() );
addResourceHost( host );
}
host.updateHeartbeat();
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, host.getId().toString(), host );
return;
}
try
{
SubutaiHost host = ( SubutaiHost ) bindHost( response.getUuid() );
host.updateHeartbeat();
}
catch ( PeerException p )
{
LOG.warn( p.toString() );
}
}
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
return execute( requestBuilder, host, null );
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host host, final CommandCallback callback )
throws CommandException
{
if ( !host.isConnected() )
{
throw new CommandException( "Host disconnected." );
}
Agent agent = host.getAgent();
Command command = commandRunner.createCommand( requestBuilder, Sets.newHashSet( agent ) );
command.execute( new org.safehaus.subutai.core.command.api.command.CommandCallback()
{
@Override
public void onResponse( final Response response, final AgentResult agentResult, final Command command )
{
if ( callback != null )
{
callback.onResponse( response,
new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(),
agentResult.getStdErr(), command.getCommandStatus() ) );
}
}
} );
AgentResult agentResult = command.getResults().get( agent.getUuid() );
if ( agentResult != null )
{
return new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(), agentResult.getStdErr(),
command.getCommandStatus() );
}
else
{
return new CommandResult( null, null, null, CommandStatus.TIMEOUT );
}
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host host, final CommandCallback callback )
throws CommandException
{
if ( !host.isConnected() )
{
throw new CommandException( "Host disconnected." );
}
final Agent agent = host.getAgent();
Command command = commandRunner.createCommand( requestBuilder, Sets.newHashSet( agent ) );
command.executeAsync( new org.safehaus.subutai.core.command.api.command.CommandCallback()
{
@Override
public void onResponse( final Response response, final AgentResult agentResult, final Command command )
{
if ( callback != null )
{
callback.onResponse( response,
new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(),
agentResult.getStdErr(), command.getCommandStatus() ) );
}
}
} );
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
executeAsync( requestBuilder, host, null );
}
@Override
public boolean isLocal()
{
return true;
}
@Override
public void clean()
{
if ( managementHost != null && managementHost.getId() != null )
{
peerDAO.deleteInfo( SOURCE_MANAGEMENT_HOST, managementHost.getId().toString() );
managementHost = null;
}
for ( ResourceHost resourceHost : getResourceHosts() )
{
peerDAO.deleteInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString() );
}
resourceHosts.clear();
}
@Override
public Template getTemplate( final String templateName )
{
return templateRegistry.getTemplate( templateName );
}
@Override
public boolean isOnline() throws PeerException
{
return true;
}
@Override
public <T, V> V sendRequest( final T request, final String recipient, final int timeout,
final Class<V> responseType ) throws PeerException
{
Preconditions.checkNotNull( responseType, "Invalid response type" );
return sendRequestInternal( request, recipient, timeout, responseType );
}
@Override
public <T> void sendRequest( final T request, final String recipient, final int timeout ) throws PeerException
{
sendRequestInternal( request, recipient, timeout, null );
}
private <T, V> V sendRequestInternal( final T request, final String recipient, final int timeout,
final Class<V> responseType ) throws PeerException
{
Preconditions.checkNotNull( request, "Invalid request" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( recipient ), "Invalid recipient" );
Preconditions.checkArgument( timeout > 0, "Timeout must be greater than 0" );
for ( RequestListener requestListener : requestListeners )
{
if ( recipient.equalsIgnoreCase( requestListener.getRecipient() ) )
{
try
{
Object response = requestListener.onRequest( new Payload( request, getId() ) );
if ( response != null && responseType != null )
{
return responseType.cast( response );
}
}
catch ( Exception e )
{
throw new PeerException( e );
}
}
}
return null;
}
@Override
public Agent waitForAgent( final String containerName, final int timeout )
{
return agentManager.waitForRegistration( containerName, timeout );
}
}
| management/server/core/peer-manager/peer-manager-impl/src/main/java/org/safehaus/subutai/core/peer/impl/LocalPeerImpl.java | package org.safehaus.subutai.core.peer.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.safehaus.subutai.common.enums.ResponseType;
import org.safehaus.subutai.common.exception.CommandException;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.CommandCallback;
import org.safehaus.subutai.common.protocol.CommandResult;
import org.safehaus.subutai.common.protocol.CommandStatus;
import org.safehaus.subutai.common.protocol.NullAgent;
import org.safehaus.subutai.common.protocol.RequestBuilder;
import org.safehaus.subutai.common.protocol.Response;
import org.safehaus.subutai.common.protocol.ResponseListener;
import org.safehaus.subutai.common.protocol.Template;
import org.safehaus.subutai.core.agent.api.AgentManager;
import org.safehaus.subutai.core.command.api.CommandRunner;
import org.safehaus.subutai.core.command.api.command.AgentResult;
import org.safehaus.subutai.core.command.api.command.Command;
import org.safehaus.subutai.core.communication.api.CommunicationManager;
import org.safehaus.subutai.core.lxc.quota.api.QuotaEnum;
import org.safehaus.subutai.core.lxc.quota.api.QuotaException;
import org.safehaus.subutai.core.lxc.quota.api.QuotaManager;
import org.safehaus.subutai.core.peer.api.BindHostException;
import org.safehaus.subutai.core.peer.api.ContainerHost;
import org.safehaus.subutai.core.peer.api.ContainerState;
import org.safehaus.subutai.core.peer.api.Host;
import org.safehaus.subutai.core.peer.api.LocalPeer;
import org.safehaus.subutai.core.peer.api.ManagementHost;
import org.safehaus.subutai.core.peer.api.Payload;
import org.safehaus.subutai.core.peer.api.PeerException;
import org.safehaus.subutai.core.peer.api.PeerInfo;
import org.safehaus.subutai.core.peer.api.PeerManager;
import org.safehaus.subutai.core.peer.api.RequestListener;
import org.safehaus.subutai.core.peer.api.ResourceHost;
import org.safehaus.subutai.core.peer.api.ResourceHostException;
import org.safehaus.subutai.core.peer.api.SubutaiInitException;
import org.safehaus.subutai.core.peer.impl.dao.PeerDAO;
import org.safehaus.subutai.core.registry.api.RegistryException;
import org.safehaus.subutai.core.registry.api.TemplateRegistry;
import org.safehaus.subutai.core.strategy.api.Criteria;
import org.safehaus.subutai.core.strategy.api.ServerMetric;
import org.safehaus.subutai.core.strategy.api.StrategyException;
import org.safehaus.subutai.core.strategy.api.StrategyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Local peer implementation
*/
public class LocalPeerImpl implements LocalPeer, ResponseListener
{
private static final Logger LOG = LoggerFactory.getLogger( LocalPeerImpl.class );
private static final String SOURCE_MANAGEMENT_HOST = "MANAGEMENT_HOST";
private static final String SOURCE_RESOURCE_HOST = "RESOURCE_HOST";
private static final long HOST_INACTIVE_TIME = 5 * 1000 * 60; // 5 min
private static final int MAX_LXC_NAME = 15;
private PeerManager peerManager;
// private ContainerManager containerManager;
private TemplateRegistry templateRegistry;
private CommunicationManager communicationManager;
private PeerDAO peerDAO;
private ManagementHost managementHost;
private Set<ResourceHost> resourceHosts = Sets.newHashSet();
private CommandRunner commandRunner;
private AgentManager agentManager;
private StrategyManager strategyManager;
private QuotaManager quotaManager;
private ConcurrentMap<String, AtomicInteger> sequences;
private Set<RequestListener> requestListeners;
public LocalPeerImpl( PeerManager peerManager, AgentManager agentManager, TemplateRegistry templateRegistry,
PeerDAO peerDao, CommunicationManager communicationManager, CommandRunner commandRunner,
QuotaManager quotaManager, StrategyManager strategyManager,
Set<RequestListener> requestListeners )
{
this.agentManager = agentManager;
this.strategyManager = strategyManager;
this.peerManager = peerManager;
// this.containerManager = containerManager;
this.templateRegistry = templateRegistry;
this.peerDAO = peerDao;
this.communicationManager = communicationManager;
this.commandRunner = commandRunner;
this.quotaManager = quotaManager;
this.requestListeners = requestListeners;
}
@Override
public void init()
{
List<ManagementHost> r1 = peerDAO.getInfo( SOURCE_MANAGEMENT_HOST, ManagementHost.class );
if ( r1.size() > 0 )
{
managementHost = r1.get( 0 );
managementHost.resetHeartbeat();
}
resourceHosts = Sets.newHashSet( peerDAO.getInfo( SOURCE_RESOURCE_HOST, ResourceHost.class ) );
for ( ResourceHost resourceHost : resourceHosts )
{
resourceHost.resetHeartbeat();
}
communicationManager.addListener( this );
sequences = new ConcurrentHashMap<>();
}
@Override
public void shutdown()
{
communicationManager.removeListener( this );
}
@Override
public UUID getId()
{
return peerManager.getLocalPeerInfo().getId();
}
@Override
public String getName()
{
return peerManager.getLocalPeerInfo().getName();
}
@Override
public UUID getOwnerId()
{
return peerManager.getLocalPeerInfo().getOwnerId();
}
@Override
public PeerInfo getPeerInfo()
{
return peerManager.getLocalPeerInfo();
}
@Override
public ContainerHost createContainer( final String hostName, final String templateName, final String cloneName,
final UUID envId ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( hostName );
ContainerHost containerHost = resourceHost
.createContainer( getId(), envId, Lists.newArrayList( getTemplate( templateName ) ), cloneName );
resourceHost.addContainerHost( containerHost );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
return containerHost;
}
// public ContainerHost createContainer( final ResourceHost resourceHost, final UUID creatorPeerId,
// final UUID environmentId, final List<Template> templates,
// final String containerName ) throws PeerException
// {
// return resourceHost.createContainer( creatorPeerId, environmentId, templates, containerName );
// }
// @Override
// public Set<ContainerHost> createContainers( final UUID creatorPeerId, final UUID environmentId,
// final List<Template> templates, final int quantity,
// final String strategyId, final List<Criteria> criteria )
// throws ContainerCreateException
// {
// Set<ContainerHost> result = new HashSet<>();
// try
// {
// for ( Template t : templates )
// {
// if ( t.isRemote() )
// {
// tryToRegister( t );
// }
// }
// String templateName = templates.get( templates.size() - 1 ).getTemplateName();
// Set<Agent> agents = containerManager.clone( environmentId, templateName, quantity, strategyId,
// criteria );
//
//
// for ( Agent agent : agents )
// {
// ResourceHost resourceHost = getResourceHostByName( agent.getParentHostName() );
// ContainerHost containerHost = new ContainerHost( agent, getId(), environmentId );
// containerHost.setParentAgent( resourceHost.getAgent() );
// containerHost.setCreatorPeerId( creatorPeerId );
// containerHost.setTemplateName( templateName );
// containerHost.updateHeartbeat();
// resourceHost.addContainerHost( containerHost );
// result.add( containerHost );
// peerDAO.saveInfo( SOURCE_MANAGEMENT, managementHost.getId().toString(), managementHost );
// }
// }
// catch ( PeerException | RegistryException e )
// {
// throw new ContainerCreateException( e.toString() );
// }
// return result;
// }
@Override
public Set<ContainerHost> createContainers( final UUID creatorPeerId, final UUID environmentId,
final List<Template> templates, final int quantity,
final String strategyId, final List<Criteria> criteria )
throws PeerException
{
Set<ContainerHost> result = new HashSet<>();
try
{
for ( Template t : templates )
{
if ( t.isRemote() )
{
tryToRegister( t );
}
}
String templateName = templates.get( templates.size() - 1 ).getTemplateName();
List<ServerMetric> serverMetricMap = new ArrayList<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
if ( resourceHost.isConnected() )
{
serverMetricMap.add( resourceHost.getMetric() );
}
}
Map<ServerMetric, Integer> slots;
try
{
slots = strategyManager.getPlacementDistribution( serverMetricMap, quantity, strategyId, criteria );
}
catch ( StrategyException e )
{
throw new PeerException( e.getMessage() );
}
Set<String> existingContainerNames = getContainerNames();
// clone specified number of instances and store their names
Map<ResourceHost, Set<String>> cloneNames = new HashMap<>();
for ( Map.Entry<ServerMetric, Integer> e : slots.entrySet() )
{
Set<String> hostCloneNames = new HashSet<>();
for ( int i = 0; i < e.getValue(); i++ )
{
String newContainerName = nextHostName( templateName, existingContainerNames );
hostCloneNames.add( newContainerName );
}
ResourceHost resourceHost = getResourceHostByName( e.getKey().getHostname() );
cloneNames.put( resourceHost, hostCloneNames );
}
for ( final Map.Entry<ResourceHost, Set<String>> e : cloneNames.entrySet() )
{
ResourceHost rh = e.getKey();
Set<String> clones = e.getValue();
ResourceHost resourceHost = getResourceHostByName( rh.getHostname() );
for ( String cloneName : clones )
{
ContainerHost containerHost =
resourceHost.createContainer( creatorPeerId, environmentId, templates, cloneName );
resourceHost.addContainerHost( containerHost );
result.add( containerHost );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
}
}
}
catch ( RegistryException e )
{
throw new PeerException( e.toString() );
}
return result;
}
private String nextHostName( String templateName, Set<String> existingNames )
{
AtomicInteger i = sequences.putIfAbsent( templateName, new AtomicInteger() );
if ( i == null )
{
i = sequences.get( templateName );
}
while ( true )
{
String suffix = String.valueOf( i.incrementAndGet() );
int prefixLen = MAX_LXC_NAME - suffix.length();
String name = ( templateName.length() > prefixLen ? templateName.substring( 0, prefixLen ) : templateName )
+ suffix;
if ( !existingNames.contains( name ) )
{
return name;
}
}
}
private Set<String> getContainerNames() throws PeerException
{
Set<String> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
for ( ContainerHost containerHost : resourceHost.getContainerHosts() )
{
result.add( containerHost.getHostname() );
}
}
return result;
}
private void tryToRegister( final Template template ) throws RegistryException
{
if ( templateRegistry.getTemplate( template.getTemplateName() ) == null )
{
templateRegistry.registerTemplate( template );
}
}
@Override
public ContainerHost getContainerHostByName( String hostname )
{
ContainerHost result = null;
Iterator<ResourceHost> iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
result = iterator.next().getContainerHostByName( hostname );
}
return result;
}
@Override
public ResourceHost getResourceHostByName( String hostname )
{
ResourceHost result = null;
Iterator iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
ResourceHost host = ( ResourceHost ) iterator.next();
if ( host.getHostname().equals( hostname ) )
{
result = host;
}
}
return result;
}
@Override
public Set<ContainerHost> getContainerHostsByEnvironmentId( final UUID environmentId ) throws PeerException
{
Set<ContainerHost> result = new HashSet<>();
for ( ResourceHost resourceHost : getResourceHosts() )
{
result.addAll( resourceHost.getContainerHostsByEnvironmentId( environmentId ) );
}
return result;
}
@Override
public Host bindHost( UUID id ) throws PeerException
{
Host result = null;
ManagementHost managementHost = getManagementHost();
if ( managementHost.getId().equals( id ) )
{
result = managementHost;
}
else
{
Iterator<ResourceHost> iterator = getResourceHosts().iterator();
while ( result == null && iterator.hasNext() )
{
ResourceHost rh = iterator.next();
if ( rh.getId().equals( id ) )
{
result = rh;
}
else
{
result = rh.getContainerHostById( id );
}
}
}
if ( result == null )
{
throw new BindHostException( id );
}
return result;
}
@Override
public void startContainer( final ContainerHost containerHost ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getParentHostname() );
try
{
if ( resourceHost.startContainerHost( containerHost ) )
{
containerHost.setState( ContainerState.RUNNING );
}
}
catch ( CommandException e )
{
containerHost.setState( ContainerState.UNKNOWN );
throw new PeerException( String.format( "Could not start LXC container [%s]", e.toString() ) );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public void stopContainer( final ContainerHost containerHost ) throws PeerException
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getParentHostname() );
try
{
if ( resourceHost.stopContainerHost( containerHost ) )
{
containerHost.setState( ContainerState.STOPPED );
}
}
catch ( CommandException e )
{
containerHost.setState( ContainerState.UNKNOWN );
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public void destroyContainer( final ContainerHost containerHost ) throws PeerException
{
Host result = bindHost( containerHost.getId() );
if ( result == null )
{
throw new PeerException( "Container Host not found." );
}
try
{
ResourceHost resourceHost = getResourceHostByName( containerHost.getAgent().getParentHostName() );
resourceHost.destroyContainerHost( containerHost );
resourceHost.removeContainerHost( result );
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString(), resourceHost );
}
catch ( ResourceHostException e )
{
throw new PeerException( e.toString() );
}
catch ( Exception e )
{
throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) );
}
}
@Override
public boolean isConnected( final Host host ) throws PeerException
{
if ( host instanceof ContainerHost )
{
return ContainerState.RUNNING.equals( ( ( ContainerHost ) host ).getState() ) && checkHeartbeat(
host.getLastHeartbeat() );
}
else
{
return checkHeartbeat( host.getLastHeartbeat() );
}
}
@Override
public String getQuota( ContainerHost host, final QuotaEnum quota ) throws PeerException
{
try
{
return quotaManager.getQuota( host.getHostname(), quota, host.getParentAgent() );
}
catch ( QuotaException e )
{
throw new PeerException( e.toString() );
}
}
@Override
public void setQuota( ContainerHost host, final QuotaEnum quota, final String value ) throws PeerException
{
try
{
quotaManager.setQuota( host.getHostname(), quota, value, host.getParentAgent() );
}
catch ( QuotaException e )
{
throw new PeerException( e.toString() );
}
}
private boolean checkHeartbeat( long lastHeartbeat )
{
return ( System.currentTimeMillis() - lastHeartbeat ) < HOST_INACTIVE_TIME;
}
@Override
public ManagementHost getManagementHost() throws PeerException
{
return managementHost;
}
@Override
public Set<ResourceHost> getResourceHosts()
{
return resourceHosts;
}
@Override
public List<String> getTemplates()
{
List<Template> templates = templateRegistry.getAllTemplates();
List<String> result = new ArrayList<>();
for ( Template template : templates )
{
result.add( template.getTemplateName() );
}
return result;
}
public void addResourceHost( final ResourceHost host )
{
if ( host == null )
{
throw new IllegalArgumentException( "Resource host could not be null." );
}
resourceHosts.add( host );
}
@Override
public void onResponse( final Response response )
{
if ( response == null || response.getType() == null )
{
return;
}
if ( response.getType().equals( ResponseType.REGISTRATION_REQUEST ) || response.getType().equals(
ResponseType.HEARTBEAT_RESPONSE ) )
{
if ( response.getHostname().equals( "management" ) )
{
if ( managementHost == null )
{
managementHost = new ManagementHost( PeerUtils.buildAgent( response ), getId() );
managementHost.setParentAgent( NullAgent.getInstance() );
try
{
managementHost.init();
}
catch ( SubutaiInitException e )
{
LOG.error( e.toString() );
}
}
managementHost.updateHeartbeat();
peerDAO.saveInfo( SOURCE_MANAGEMENT_HOST, managementHost.getId().toString(), managementHost );
return;
}
if ( response.getHostname().startsWith( "py" ) )
{
ResourceHost host = getResourceHostByName( response.getHostname() );
if ( host == null )
{
host = new ResourceHost( PeerUtils.buildAgent( response ), getId() );
host.setParentAgent( NullAgent.getInstance() );
addResourceHost( host );
}
host.updateHeartbeat();
peerDAO.saveInfo( SOURCE_RESOURCE_HOST, host.getId().toString(), host );
return;
}
// assume response from container host agent
ContainerHost containerHost = getContainerHostByName( response.getHostname() );
if ( containerHost != null )
{
containerHost.updateHeartbeat();
}
}
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
return execute( requestBuilder, host, null );
}
@Override
public CommandResult execute( final RequestBuilder requestBuilder, final Host host, final CommandCallback callback )
throws CommandException
{
if ( !host.isConnected() )
{
throw new CommandException( "Host disconnected." );
}
Agent agent = host.getAgent();
Command command = commandRunner.createCommand( requestBuilder, Sets.newHashSet( agent ) );
command.execute( new org.safehaus.subutai.core.command.api.command.CommandCallback()
{
@Override
public void onResponse( final Response response, final AgentResult agentResult, final Command command )
{
if ( callback != null )
{
callback.onResponse( response,
new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(),
agentResult.getStdErr(), command.getCommandStatus() ) );
}
}
} );
AgentResult agentResult = command.getResults().get( agent.getUuid() );
if ( agentResult != null )
{
return new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(), agentResult.getStdErr(),
command.getCommandStatus() );
}
else
{
return new CommandResult( null, null, null, CommandStatus.TIMEOUT );
}
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host host, final CommandCallback callback )
throws CommandException
{
if ( !host.isConnected() )
{
throw new CommandException( "Host disconnected." );
}
final Agent agent = host.getAgent();
Command command = commandRunner.createCommand( requestBuilder, Sets.newHashSet( agent ) );
command.executeAsync( new org.safehaus.subutai.core.command.api.command.CommandCallback()
{
@Override
public void onResponse( final Response response, final AgentResult agentResult, final Command command )
{
if ( callback != null )
{
callback.onResponse( response,
new CommandResult( agentResult.getExitCode(), agentResult.getStdOut(),
agentResult.getStdErr(), command.getCommandStatus() ) );
}
}
} );
}
@Override
public void executeAsync( final RequestBuilder requestBuilder, final Host host ) throws CommandException
{
executeAsync( requestBuilder, host, null );
}
@Override
public boolean isLocal()
{
return true;
}
@Override
public void clean()
{
if ( managementHost != null && managementHost.getId() != null )
{
peerDAO.deleteInfo( SOURCE_MANAGEMENT_HOST, managementHost.getId().toString() );
managementHost = null;
}
for ( ResourceHost resourceHost : getResourceHosts() )
{
peerDAO.deleteInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString() );
}
resourceHosts.clear();
}
@Override
public Template getTemplate( final String templateName )
{
return templateRegistry.getTemplate( templateName );
}
@Override
public boolean isOnline() throws PeerException
{
return true;
}
@Override
public <T, V> V sendRequest( final T request, final String recipient, final int timeout,
final Class<V> responseType ) throws PeerException
{
Preconditions.checkNotNull( responseType, "Invalid response type" );
return sendRequestInternal( request, recipient, timeout, responseType );
}
@Override
public <T> void sendRequest( final T request, final String recipient, final int timeout ) throws PeerException
{
sendRequestInternal( request, recipient, timeout, null );
}
private <T, V> V sendRequestInternal( final T request, final String recipient, final int timeout,
final Class<V> responseType ) throws PeerException
{
Preconditions.checkNotNull( request, "Invalid request" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( recipient ), "Invalid recipient" );
Preconditions.checkArgument( timeout > 0, "Timeout must be greater than 0" );
for ( RequestListener requestListener : requestListeners )
{
if ( recipient.equalsIgnoreCase( requestListener.getRecipient() ) )
{
try
{
Object response = requestListener.onRequest( new Payload( request, getId() ) );
if ( response != null && responseType != null )
{
return responseType.cast( response );
}
}
catch ( Exception e )
{
throw new PeerException( e );
}
}
}
return null;
}
@Override
public Agent waitForAgent( final String containerName, final int timeout )
{
return agentManager.waitForRegistration( containerName, timeout );
}
}
| bug fix
| management/server/core/peer-manager/peer-manager-impl/src/main/java/org/safehaus/subutai/core/peer/impl/LocalPeerImpl.java | bug fix | <ide><path>anagement/server/core/peer-manager/peer-manager-impl/src/main/java/org/safehaus/subutai/core/peer/impl/LocalPeerImpl.java
<ide> import org.safehaus.subutai.core.peer.api.RequestListener;
<ide> import org.safehaus.subutai.core.peer.api.ResourceHost;
<ide> import org.safehaus.subutai.core.peer.api.ResourceHostException;
<add>import org.safehaus.subutai.core.peer.api.SubutaiHost;
<ide> import org.safehaus.subutai.core.peer.api.SubutaiInitException;
<ide> import org.safehaus.subutai.core.peer.impl.dao.PeerDAO;
<ide> import org.safehaus.subutai.core.registry.api.RegistryException;
<ide> {
<ide> Host result = null;
<ide> ManagementHost managementHost = getManagementHost();
<del> if ( managementHost.getId().equals( id ) )
<add> if ( managementHost != null && managementHost.getId().equals( id ) )
<ide> {
<ide> result = managementHost;
<ide> }
<ide> return;
<ide> }
<ide>
<del> // assume response from container host agent
<del>
<del> ContainerHost containerHost = getContainerHostByName( response.getHostname() );
<del>
<del> if ( containerHost != null )
<del> {
<del> containerHost.updateHeartbeat();
<add> try
<add> {
<add> SubutaiHost host = ( SubutaiHost ) bindHost( response.getUuid() );
<add> host.updateHeartbeat();
<add> }
<add> catch ( PeerException p )
<add> {
<add> LOG.warn( p.toString() );
<ide> }
<ide> }
<ide> } |
|
JavaScript | isc | a9773c9899f290e6933dc7b248095193338e7c23 | 0 | npm/fstream-npm | var Ignore = require("fstream-ignore")
, inherits = require("inherits")
, path = require("path")
, fs = require("fs")
module.exports = Packer
inherits(Packer, Ignore)
function Packer (props) {
if (!(this instanceof Packer)) {
return new Packer(props)
}
if (typeof props === "string") {
props = { path: props }
}
props.ignoreFiles = [ ".npmignore",
".gitignore",
"package.json" ]
Ignore.call(this, props)
this.bundled = props.bundled
this.package = props.package
// in a node_modules folder, resolve symbolic links to
// bundled dependencies when creating the package.
props.follow = this.follow = this.basename === "node_modules"
// console.error("follow?", this.path, props.follow)
if (this === this.root ||
this.parent && this.parent.basename === "node_modules") {
// very likely a package. try read the package.json asap.
this.on("stat", function () {
this.pause()
fs.readFile(this.path + "/package.json", function (er, data) {
if (er) {
// guessed wrong. no harm.
return this.resume()
}
this.readRules(data, "package.json")
this.resume()
}.bind(this))
})
}
this.on("entryStat", function (entry, props) {
// files should *always* get into tarballs
// in a user-writable state, even if they're
// being installed from some wackey vm-mounted
// read-only filesystem.
entry.mode = props.mode = props.mode | 0200
})
}
Packer.prototype.applyIgnores = function (entry, partial, entryObj) {
// package.json files can never be ignored.
if (entry === "package.json") return true
if (entryObj &&
entryObj.packageRoot &&
this.basename === "node_modules") {
// a bundled package. Check if it should be here.
if (this.parent.parent &&
this.parent.parent.bundledVersions &&
this.parent.parent.bundledVersions === entryObj.package.version) {
return false
}
this.parent.bundledVersions = this.parent.bundledVersions || {}
this.parent.bundledVersions[entry] = entryObj.package.version
return true
}
// some files are *never* allowed under any circumstances
if (entry === ".git" ||
entry === ".lock-wscript" ||
entry.match(/^\.wafpickle-[0-9]+$/) ||
entry === "CVS" ||
entry === ".svn" ||
entry === ".hg" ||
entry.match(/^\..*\.swp$/) ||
entry === ".DS_Store" ||
entry.match(/^\._/) ||
entry === "npm-debug.log"
) {
return false
}
// in a node_modules folder, we only include bundled dependencies
// also, prevent packages in node_modules from being affected
// by rules set in the containing package, so that
// bundles don't get busted.
// Also, once in a bundle, everything is installed as-is
// To prevent infinite cycles in the case of cyclic deps that are
// linked with npm link, even in a bundle, deps are only bundled
// if they're not already present at a higher level.
if (this.basename === "node_modules") {
// bubbling up. stop here and allow anything the bundled pkg allows
if (entry.indexOf("/") !== -1) return true
// never include the .bin. It's typically full of platform-specific
// stuff like symlinks and .cmd files anyway.
if (entry === ".bin") return false
var shouldBundle = false
if (this.parent && this.parent.bundled) {
// only bundle if the parent doesn't already have it, and it's
// not a devDependency.
var dd = this.package && this.package.devDependencies
shouldBundle = !dd || !dd.hasOwnProperty(entry)
shouldBundle = shouldBundle &&
this.parent.bundled.indexOf(entry) === -1
} else {
var bd = this.package && this.package.bundleDependencies
var shouldBundle = bd && bd.indexOf(entry) !== -1
}
if (shouldBundle) {
this.bundled = this.bundled || []
if (this.bundled.indexOf(entry) === -1) {
this.bundled.push(entry)
}
}
return shouldBundle
}
// if (this.bundled) return true
return Ignore.prototype.applyIgnores.call(this, entry, partial)
}
Packer.prototype.addIgnoreFiles = function () {
var entries = this.entries
// if there's a .npmignore, then we do *not* want to
// read the .gitignore.
if (-1 !== entries.indexOf(".npmignore")) {
var i = entries.indexOf(".gitignore")
if (i !== -1) {
entries.splice(i, 1)
}
}
this.entries = entries
Ignore.prototype.addIgnoreFiles.call(this)
}
Packer.prototype.readRules = function (buf, e) {
if (e !== "package.json") {
return Ignore.prototype.readRules.call(this, buf, e)
}
var p = this.package = JSON.parse(buf.toString())
this.packageRoot = true
this.emit("package", p)
// make bundle deps predictable
if (p.bundledDependencies && !p.bundleDependencies) {
p.bundleDependencies = p.bundledDependencies
delete p.bundledDependencies
}
if (!p.files || !Array.isArray(p.files)) return []
// ignore everything except what's in the files array.
return ["*"].concat(p.files.map(function (f) {
return "!" + f
}))
}
Packer.prototype.getChildProps = function (stat) {
var props = Ignore.prototype.getChildProps.call(this, stat)
props.package = this.package
props.bundled = this.bundled && this.bundled.slice(0)
props.bundledVersions = this.bundledVersions &&
Object.create(this.bundledVersions)
// Directories have to be read as Packers
// otherwise fstream.Reader will create a DirReader instead.
if (stat.isDirectory()) {
props.type = this.constructor
}
// only follow symbolic links directly in the node_modules folder.
props.follow = false
return props
}
var order =
[ "package.json"
, ".npmignore"
, ".gitignore"
, /^README(\.md)?$/
, "LICENCE"
, "LICENSE"
, /\.js$/ ]
Packer.prototype.sort = function (a, b) {
for (var i = 0, l = order.length; i < l; i ++) {
var o = order[i]
if (typeof o === "string") {
if (a === o) return -1
if (b === o) return 1
} else {
if (a.match(o)) return -1
if (b.match(o)) return 1
}
}
// deps go in the back
if (a === "node_modules") return 1
if (b === "node_modules") return -1
return Ignore.prototype.sort.call(this, a, b)
}
Packer.prototype.emitEntry = function (entry) {
if (this._paused) {
this.once("resume", this.emitEntry.bind(this, entry))
return
}
// if there is a .gitignore, then we're going to
// rename it to .npmignore in the output.
if (entry.basename === ".gitignore") {
entry.basename = ".npmignore"
entry.path = path.resolve(entry.dirname, entry.basename)
}
// all *.gyp files are renamed to binding.gyp for node-gyp
if (entry.basename.match(/\.gyp$/)) {
entry.basename = "binding.gyp"
entry.path = path.resolve(entry.dirname, entry.basename)
}
// skip over symbolic links
if (entry.type === "SymbolicLink") {
entry.abort()
return
}
if (entry.type !== "Directory") {
// make it so that the folder in the tarball is named "package"
var h = path.dirname((entry.root || entry).path)
, t = entry.path.substr(h.length + 1).replace(/^[^\/\\]+/, "package")
, p = h + "/" + t
entry.path = p
entry.dirname = path.dirname(p)
return Ignore.prototype.emitEntry.call(this, entry)
}
// we don't want empty directories to show up in package
// tarballs.
// don't emit entry events for dirs, but still walk through
// and read them. This means that we need to proxy up their
// entry events so that those entries won't be missed, since
// .pipe() doesn't do anythign special with "child" events, on
// with "entry" events.
var me = this
entry.on("entry", function (e) {
if (e.parent === entry) {
e.parent = me
me.emit("entry", e)
}
})
entry.on("package", this.emit.bind(this, "package"))
}
| fstream-npm.js | var Ignore = require("fstream-ignore")
, inherits = require("inherits")
, path = require("path")
, fs = require("fs")
module.exports = Packer
inherits(Packer, Ignore)
function Packer (props) {
if (!(this instanceof Packer)) {
return new Packer(props)
}
if (typeof props === "string") {
props = { path: props }
}
props.ignoreFiles = [ ".npmignore",
".gitignore",
"package.json" ]
Ignore.call(this, props)
this.bundled = props.bundled
this.package = props.package
// in a node_modules folder, resolve symbolic links to
// bundled dependencies when creating the package.
props.follow = this.follow = this.basename === "node_modules"
// console.error("follow?", this.path, props.follow)
if (this === this.root ||
this.parent && this.parent.basename === "node_modules") {
// very likely a package. try read the package.json asap.
this.on("stat", function () {
this.pause()
fs.readFile(this.path + "/package.json", function (er, data) {
if (er) {
// guessed wrong. no harm.
return this.resume()
}
this.readRules(data, "package.json")
this.resume()
}.bind(this))
})
}
this.on("entryStat", function (entry, props) {
// files should *always* get into tarballs
// in a user-writable state, even if they're
// being installed from some wackey vm-mounted
// read-only filesystem.
entry.mode = props.mode = props.mode | 0200
})
}
Packer.prototype.applyIgnores = function (entry, partial, entryObj) {
// package.json files can never be ignored.
if (entry === "package.json") return true
if (entryObj &&
entryObj.packageRoot &&
this.basename === "node_modules") {
// a bundled package. Check if it should be here.
if (this.parent.parent &&
this.parent.parent.bundledVersions &&
this.parent.parent.bundledVersions === entryObj.package.version) {
return false
}
this.parent.bundledVersions = this.parent.bundledVersions || {}
this.parent.bundledVersions[entry] = entryObj.package.version
return true
}
// some files are *never* allowed under any circumstances
if (entry === ".git" ||
entry === ".lock-wscript" ||
entry.match(/^\.wafpickle-[0-9]+$/) ||
entry === "CVS" ||
entry === ".svn" ||
entry === ".hg" ||
entry.match(/^\..*\.swp$/) ||
entry === ".DS_Store" ||
entry.match(/^\._/) ||
entry === "npm-debug.log"
) {
return false
}
// in a node_modules folder, we only include bundled dependencies
// also, prevent packages in node_modules from being affected
// by rules set in the containing package, so that
// bundles don't get busted.
// Also, once in a bundle, everything is installed as-is
// To prevent infinite cycles in the case of cyclic deps that are
// linked with npm link, even in a bundle, deps are only bundled
// if they're not already present at a higher level.
if (this.basename === "node_modules") {
// bubbling up. stop here and allow anything the bundled pkg allows
if (entry.indexOf("/") !== -1) return true
// never include the .bin. It's typically full of platform-specific
// stuff like symlinks and .cmd files anyway.
if (entry === ".bin") return false
var shouldBundle = false
if (this.parent.bundled) {
// only bundle if the parent doesn't already have it, and it's
// not a devDependency.
var dd = this.package && this.package.devDependencies
shouldBundle = !dd || !dd.hasOwnProperty(entry)
} else {
var bd = this.package && this.package.bundleDependencies
var shouldBundle = bd && bd.indexOf(entry) !== -1
}
if (shouldBundle) {
this.bundled = this.bundled || []
this.bundled.push(entry)
}
return shouldBundle
}
// if (this.bundled) return true
return Ignore.prototype.applyIgnores.call(this, entry, partial)
}
Packer.prototype.addIgnoreFiles = function () {
var entries = this.entries
// if there's a .npmignore, then we do *not* want to
// read the .gitignore.
if (-1 !== entries.indexOf(".npmignore")) {
var i = entries.indexOf(".gitignore")
if (i !== -1) {
entries.splice(i, 1)
}
}
this.entries = entries
Ignore.prototype.addIgnoreFiles.call(this)
}
Packer.prototype.readRules = function (buf, e) {
if (e !== "package.json") {
return Ignore.prototype.readRules.call(this, buf, e)
}
var p = this.package = JSON.parse(buf.toString())
this.packageRoot = true
this.emit("package", p)
// make bundle deps predictable
if (p.bundledDependencies && !p.bundleDependencies) {
p.bundleDependencies = p.bundledDependencies
delete p.bundledDependencies
}
if (!p.files || !Array.isArray(p.files)) return []
// ignore everything except what's in the files array.
return ["*"].concat(p.files.map(function (f) {
return "!" + f
}))
}
Packer.prototype.getChildProps = function (stat) {
var props = Ignore.prototype.getChildProps.call(this, stat)
props.package = this.package
props.bundled = this.bundled && this.bundled.slice(0)
props.bundledVersions = this.bundledVersions &&
Object.create(this.bundledVersions)
// Directories have to be read as Packers
// otherwise fstream.Reader will create a DirReader instead.
if (stat.isDirectory()) {
props.type = this.constructor
}
// only follow symbolic links directly in the node_modules folder.
props.follow = false
return props
}
var order =
[ "package.json"
, ".npmignore"
, ".gitignore"
, /^README(\.md)?$/
, "LICENCE"
, "LICENSE"
, /\.js$/ ]
Packer.prototype.sort = function (a, b) {
for (var i = 0, l = order.length; i < l; i ++) {
var o = order[i]
if (typeof o === "string") {
if (a === o) return -1
if (b === o) return 1
} else {
if (a.match(o)) return -1
if (b.match(o)) return 1
}
}
// deps go in the back
if (a === "node_modules") return 1
if (b === "node_modules") return -1
return Ignore.prototype.sort.call(this, a, b)
}
Packer.prototype.emitEntry = function (entry) {
if (this._paused) {
this.once("resume", this.emitEntry.bind(this, entry))
return
}
// if there is a .gitignore, then we're going to
// rename it to .npmignore in the output.
if (entry.basename === ".gitignore") {
entry.basename = ".npmignore"
entry.path = path.resolve(entry.dirname, entry.basename)
}
// all *.gyp files are renamed to binding.gyp for node-gyp
if (entry.basename.match(/\.gyp$/)) {
entry.basename = "binding.gyp"
entry.path = path.resolve(entry.dirname, entry.basename)
}
// skip over symbolic links
if (entry.type === "SymbolicLink") {
entry.abort()
return
}
if (entry.type !== "Directory") {
// make it so that the folder in the tarball is named "package"
var h = path.dirname((entry.root || entry).path)
, t = entry.path.substr(h.length + 1).replace(/^[^\/\\]+/, "package")
, p = h + "/" + t
entry.path = p
entry.dirname = path.dirname(p)
return Ignore.prototype.emitEntry.call(this, entry)
}
// we don't want empty directories to show up in package
// tarballs.
// don't emit entry events for dirs, but still walk through
// and read them. This means that we need to proxy up their
// entry events so that those entries won't be missed, since
// .pipe() doesn't do anythign special with "child" events, on
// with "entry" events.
var me = this
entry.on("entry", function (e) {
if (e.parent === entry) {
e.parent = me
me.emit("entry", e)
}
})
entry.on("package", this.emit.bind(this, "package"))
}
| Simpler way to prevent infinite cycles. Not correct, though
| fstream-npm.js | Simpler way to prevent infinite cycles. Not correct, though | <ide><path>stream-npm.js
<ide> if (entry === ".bin") return false
<ide>
<ide> var shouldBundle = false
<del> if (this.parent.bundled) {
<add> if (this.parent && this.parent.bundled) {
<ide> // only bundle if the parent doesn't already have it, and it's
<ide> // not a devDependency.
<ide> var dd = this.package && this.package.devDependencies
<ide> shouldBundle = !dd || !dd.hasOwnProperty(entry)
<add> shouldBundle = shouldBundle &&
<add> this.parent.bundled.indexOf(entry) === -1
<ide> } else {
<ide> var bd = this.package && this.package.bundleDependencies
<ide> var shouldBundle = bd && bd.indexOf(entry) !== -1
<ide>
<ide> if (shouldBundle) {
<ide> this.bundled = this.bundled || []
<del> this.bundled.push(entry)
<add> if (this.bundled.indexOf(entry) === -1) {
<add> this.bundled.push(entry)
<add> }
<ide> }
<ide> return shouldBundle
<ide> } |
|
Java | apache-2.0 | error: pathspec 'MEDIUM/src/medium/AddTwoNumbers.java' did not match any file(s) known to git
| 43f5fbd40c1eff61378b6b332e53d470a995d0c4 | 1 | fishercoder1534/Leetcode,fishercoder1534/Leetcode,cy19890513/Leetcode-1,fishercoder1534/Leetcode,fishercoder1534/Leetcode,cy19890513/Leetcode-1,fishercoder1534/Leetcode | package medium;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import utils.CommonUtils;
import classes.ListNode;
/**2. Add Two Numbers QuestionEditorial Solution My Submissions
Total Accepted: 164672
Total Submissions: 675656
Difficulty: Medium
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8*/
public class AddTwoNumbers {
//Last, I went to Discuss and like this solution the best: https://discuss.leetcode.com/topic/6220/my-accepted-java-solution
//it's really much more concise and elegant:
//we don't actually need to collect all values from each node out and put them into a list and then do calculations
//I could get out of that thinking box, I could direclty manipulate the values from the nodes and do the computation, cool!
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode prev = new ListNode(0);
ListNode head = prev;
int carry = 0;
while(l1 != null || l2 != null || carry != 0){
ListNode curr = new ListNode(0);
int sum = (l2 != null ? l2.val : 0) + (l1 != null ? l1.val : 0) + carry;
curr.val = sum % 10;
carry = sum / 10;
prev.next = curr;
prev = curr;
l1 = (l1 == null) ? l1 : l1.next;
l2 = (l2 == null) ? l2 : l2.next;
}
return head.next;
}
//then I came up with this approach: do addition digit by digit in the ArrayList, thus no matter how big the number is, it could always be computed
public ListNode addTwoNumbers_ACed(ListNode l1, ListNode l2) {
List<Integer> nums1 = new ArrayList();
List<Integer> nums2 = new ArrayList();
ListNode tmp1 = l1, tmp2 = l2;
while(tmp1 != null){
nums1.add(tmp1.val);
tmp1 = tmp1.next;
}
while(tmp2 != null){
nums2.add(tmp2.val);
tmp2 = tmp2.next;
}
//we don't need to reverse the two lists, just start adding them up from index 0
List<Integer> shorter = (nums1.size() > nums2.size()) ? nums2 : nums1;
List<Integer> longer = (shorter == nums1) ? nums2 : nums1;
int[] res = new int[longer.size()+1];
boolean carry = false;
int i = 0;
for(; i < shorter.size(); i++){
int thisResult = 0;
if(carry){
thisResult = shorter.get(i) + longer.get(i) + 1;
} else {
thisResult = shorter.get(i) + longer.get(i);
}
if(thisResult >= 10){
res[i] = Character.getNumericValue(String.valueOf(thisResult).charAt(1));
carry = true;
} else {
res[i] = thisResult;
carry = false;
}
}
if(shorter.size() == longer.size()){
if(carry) res[i] = 1;
}
for(; i < longer.size(); i++){
int thisResult = 0;
if(carry){
thisResult = longer.get(i)+1;
} else {
thisResult = longer.get(i);
}
if(thisResult >= 10){
res[i] = Character.getNumericValue(String.valueOf(thisResult).charAt(1));
carry = true;
} else {
res[i] = thisResult;
carry = false;
}
}
if(carry) res[i] = 1;
CommonUtils.printArray(res);
ListNode pre = new ListNode(-1);
ListNode next = new ListNode(-1);
pre.next = next;
for(int j = 0; j < res.length;){
next.val = res[j];
j++;
if(j == res.length-1 && res[j] == 0) break;
if(j < res.length)
next.next = new ListNode(-1);
next = next.next;
}
return pre.next;
}
public static void main(String...strings){
// ListNode l1 = new ListNode(2);
// l1.next = new ListNode(4);
// l1.next.next = new ListNode(3);
// ListNode l2 = new ListNode(5);
// l2.next = new ListNode(6);
// l2.next.next = new ListNode(4);
// ListNode l1 = new ListNode(5);
// ListNode l2 = new ListNode(5);
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(9);
l2.next = new ListNode(9);
AddTwoNumbers test = new AddTwoNumbers();
ListNode result = test.addTwoNumbers_ACed(l1, l2);
CommonUtils.printList(result);
}
//the most naive approach will result in overflow/NumberFormatException, since if the number is greater than 2^64, it won't work
//sample test case: [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
// [1]
public ListNode addTwoNumbers_overflowed(ListNode l1, ListNode l2) {
long num1 = 0, num2 = 0;
List<Integer> nums1 = new ArrayList();
List<Integer> nums2 = new ArrayList();
ListNode tmp1 = l1, tmp2 = l2;
while(tmp1 != null){
nums1.add(tmp1.val);
tmp1 = tmp1.next;
}
while(tmp2 != null){
nums2.add(tmp2.val);
tmp2 = tmp2.next;
}
StringBuilder sb = new StringBuilder();
for(int i = nums1.size()-1; i >= 0; i--){
sb.append(nums1.get(i));
}
num1 = Long.valueOf(sb.toString());
sb.setLength(0);
for(int i = nums2.size()-1; i >= 0; i--){
sb.append(nums2.get(i));
}
num2 = Long.valueOf(sb.toString());
long res = num1 + num2;
String resStr = String.valueOf(res);
sb.setLength(0);
String reverse = sb.append(resStr).reverse().toString();
char[] chars = reverse.toCharArray();
ListNode dummy = new ListNode(-1);
ListNode result = new ListNode(-1);
dummy.next = result;
for(int i = 0; i < chars.length; i++){
result.val = Character.getNumericValue(chars[i]);
if(i < chars.length-1)
result.next = new ListNode(-1);
result = result.next;
}
return dummy.next;
}
}
| MEDIUM/src/medium/AddTwoNumbers.java | add two numbers
| MEDIUM/src/medium/AddTwoNumbers.java | add two numbers | <ide><path>EDIUM/src/medium/AddTwoNumbers.java
<add>package medium;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import utils.CommonUtils;
<add>import classes.ListNode;
<add>
<add>/**2. Add Two Numbers QuestionEditorial Solution My Submissions
<add>Total Accepted: 164672
<add>Total Submissions: 675656
<add>Difficulty: Medium
<add>You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
<add>
<add>Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
<add>Output: 7 -> 0 -> 8*/
<add>public class AddTwoNumbers {
<add> //Last, I went to Discuss and like this solution the best: https://discuss.leetcode.com/topic/6220/my-accepted-java-solution
<add> //it's really much more concise and elegant:
<add> //we don't actually need to collect all values from each node out and put them into a list and then do calculations
<add> //I could get out of that thinking box, I could direclty manipulate the values from the nodes and do the computation, cool!
<add> public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
<add> ListNode prev = new ListNode(0);
<add> ListNode head = prev;
<add> int carry = 0;
<add> while(l1 != null || l2 != null || carry != 0){
<add> ListNode curr = new ListNode(0);
<add> int sum = (l2 != null ? l2.val : 0) + (l1 != null ? l1.val : 0) + carry;
<add> curr.val = sum % 10;
<add> carry = sum / 10;
<add> prev.next = curr;
<add> prev = curr;
<add>
<add> l1 = (l1 == null) ? l1 : l1.next;
<add> l2 = (l2 == null) ? l2 : l2.next;
<add> }
<add> return head.next;
<add> }
<add>
<add> //then I came up with this approach: do addition digit by digit in the ArrayList, thus no matter how big the number is, it could always be computed
<add> public ListNode addTwoNumbers_ACed(ListNode l1, ListNode l2) {
<add> List<Integer> nums1 = new ArrayList();
<add> List<Integer> nums2 = new ArrayList();
<add> ListNode tmp1 = l1, tmp2 = l2;
<add> while(tmp1 != null){
<add> nums1.add(tmp1.val);
<add> tmp1 = tmp1.next;
<add> }
<add> while(tmp2 != null){
<add> nums2.add(tmp2.val);
<add> tmp2 = tmp2.next;
<add> }
<add>
<add> //we don't need to reverse the two lists, just start adding them up from index 0
<add> List<Integer> shorter = (nums1.size() > nums2.size()) ? nums2 : nums1;
<add> List<Integer> longer = (shorter == nums1) ? nums2 : nums1;
<add> int[] res = new int[longer.size()+1];
<add> boolean carry = false;
<add> int i = 0;
<add> for(; i < shorter.size(); i++){
<add> int thisResult = 0;
<add> if(carry){
<add> thisResult = shorter.get(i) + longer.get(i) + 1;
<add> } else {
<add> thisResult = shorter.get(i) + longer.get(i);
<add> }
<add> if(thisResult >= 10){
<add> res[i] = Character.getNumericValue(String.valueOf(thisResult).charAt(1));
<add> carry = true;
<add> } else {
<add> res[i] = thisResult;
<add> carry = false;
<add> }
<add> }
<add>
<add> if(shorter.size() == longer.size()){
<add> if(carry) res[i] = 1;
<add> }
<add>
<add> for(; i < longer.size(); i++){
<add> int thisResult = 0;
<add> if(carry){
<add> thisResult = longer.get(i)+1;
<add> } else {
<add> thisResult = longer.get(i);
<add> }
<add> if(thisResult >= 10){
<add> res[i] = Character.getNumericValue(String.valueOf(thisResult).charAt(1));
<add> carry = true;
<add> } else {
<add> res[i] = thisResult;
<add> carry = false;
<add> }
<add> }
<add> if(carry) res[i] = 1;
<add>
<add> CommonUtils.printArray(res);
<add>
<add> ListNode pre = new ListNode(-1);
<add> ListNode next = new ListNode(-1);
<add> pre.next = next;
<add> for(int j = 0; j < res.length;){
<add> next.val = res[j];
<add> j++;
<add> if(j == res.length-1 && res[j] == 0) break;
<add> if(j < res.length)
<add> next.next = new ListNode(-1);
<add> next = next.next;
<add> }
<add> return pre.next;
<add> }
<add>
<add> public static void main(String...strings){
<add>// ListNode l1 = new ListNode(2);
<add>// l1.next = new ListNode(4);
<add>// l1.next.next = new ListNode(3);
<add>// ListNode l2 = new ListNode(5);
<add>// l2.next = new ListNode(6);
<add>// l2.next.next = new ListNode(4);
<add>
<add>// ListNode l1 = new ListNode(5);
<add>// ListNode l2 = new ListNode(5);
<add>
<add> ListNode l1 = new ListNode(1);
<add> ListNode l2 = new ListNode(9);
<add> l2.next = new ListNode(9);
<add>
<add> AddTwoNumbers test = new AddTwoNumbers();
<add> ListNode result = test.addTwoNumbers_ACed(l1, l2);
<add> CommonUtils.printList(result);
<add> }
<add>
<add> //the most naive approach will result in overflow/NumberFormatException, since if the number is greater than 2^64, it won't work
<add> //sample test case: [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
<add>// [1]
<add> public ListNode addTwoNumbers_overflowed(ListNode l1, ListNode l2) {
<add> long num1 = 0, num2 = 0;
<add> List<Integer> nums1 = new ArrayList();
<add> List<Integer> nums2 = new ArrayList();
<add> ListNode tmp1 = l1, tmp2 = l2;
<add> while(tmp1 != null){
<add> nums1.add(tmp1.val);
<add> tmp1 = tmp1.next;
<add> }
<add> while(tmp2 != null){
<add> nums2.add(tmp2.val);
<add> tmp2 = tmp2.next;
<add> }
<add> StringBuilder sb = new StringBuilder();
<add> for(int i = nums1.size()-1; i >= 0; i--){
<add> sb.append(nums1.get(i));
<add> }
<add> num1 = Long.valueOf(sb.toString());
<add> sb.setLength(0);
<add> for(int i = nums2.size()-1; i >= 0; i--){
<add> sb.append(nums2.get(i));
<add> }
<add> num2 = Long.valueOf(sb.toString());
<add> long res = num1 + num2;
<add> String resStr = String.valueOf(res);
<add> sb.setLength(0);
<add> String reverse = sb.append(resStr).reverse().toString();
<add> char[] chars = reverse.toCharArray();
<add> ListNode dummy = new ListNode(-1);
<add> ListNode result = new ListNode(-1);
<add> dummy.next = result;
<add> for(int i = 0; i < chars.length; i++){
<add> result.val = Character.getNumericValue(chars[i]);
<add> if(i < chars.length-1)
<add> result.next = new ListNode(-1);
<add> result = result.next;
<add> }
<add> return dummy.next;
<add> }
<add>
<add>} |
|
Java | mit | 97074b8773463e9d037ee59ed6b7483f2e45f37e | 0 | bedrin/jdbc-sniffer,sniffy/sniffy,sniffy/sniffy,sniffy/sniffy | package io.sniffy.servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
class BufferedServletResponseWrapper extends HttpServletResponseWrapper {
private BufferedServletOutputStream bufferedServletOutputStream;
private ServletOutputStream outputStream;
private PrintWriter writer;
private boolean committed;
private final BufferedServletResponseListener servletResponseListener;
protected BufferedServletResponseWrapper(HttpServletResponse response,
BufferedServletResponseListener servletResponseListener) {
super(response);
this.servletResponseListener = servletResponseListener;
}
protected void notifyBeforeCommit() throws IOException {
notifyBeforeCommit(null); // TODO: check for possible NPE
}
protected void notifyBeforeCommit(Buffer buffer) throws IOException {
servletResponseListener.onBeforeCommit(this, buffer);
}
protected void notifyBeforeClose() throws IOException {
servletResponseListener.beforeClose(this, null); // TODO: check for possible NPE
}
protected void notifyBeforeClose(Buffer buffer) throws IOException {
servletResponseListener.beforeClose(this, buffer);
}
protected BufferedServletOutputStream getBufferedServletOutputStream() throws IOException {
if (null == bufferedServletOutputStream) {
bufferedServletOutputStream = new BufferedServletOutputStream(this, super.getOutputStream());
}
return bufferedServletOutputStream;
}
/**
* Flush the sniffer buffer and append the information about the executed queries to the output stream
* Also close the underlying stream if it has been requested previously
* @throws IOException
*/
protected void close() throws IOException {
if (null != writer) writer.close();
else if (null != outputStream) outputStream.close();
else {
if (!isCommitted()) {
notifyBeforeCommit();
}
notifyBeforeClose();
}
}
protected void setCommitted(boolean committed) {
this.committed = committed;
}
protected void setCommitted() {
setCommitted(true);
}
// capture content length
private int contentLength;
@Override
public void setContentLength(int len) {
super.setContentLength(contentLength = len);
}
public int getContentLength() {
return contentLength;
}
private String contentEncoding;
@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
if ("Content-Encoding".equals(name)) {
contentEncoding = value;
} else if ("Content-Length".equals(name)) {
try {
contentLength = Integer.parseInt(value);
} catch (NumberFormatException e) {
// todo: can we log it somehow plz?
}
}
}
@Override
public void setHeader(String name, String value) {
super.setHeader(name, value);
if ("Content-Encoding".equals(name)) {
contentEncoding = value;
} else if ("Content-Length".equals(name)) {
try {
contentLength = Integer.parseInt(value);
} catch (NumberFormatException e) {
// todo: can we log it somehow plz?
}
}
}
@Override
public void setIntHeader(String name, int value) {
super.setIntHeader(name, value);
if ("Content-Length".equals(name)) {
contentLength = value;
}
}
public String getContentEncoding() {
return contentEncoding;
}
private String contentType;
public String getContentType() {
return contentType;
}
@Override
public void setContentType(String contentType) {
super.setContentType(this.contentType = contentType);
}
// headers relates methods
@Override
public void sendError(int sc, String msg) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendError(sc, msg);
setCommitted();
}
@Override
public void sendError(int sc) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendError(sc);
setCommitted();
}
@Override
public void sendRedirect(String location) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendRedirect(location);
setCommitted();
}
// content related methods
@Override
public void setBufferSize(int size) {
if (null != bufferedServletOutputStream) bufferedServletOutputStream.setBufferSize(size);
}
@Override
public int getBufferSize() {
return null == bufferedServletOutputStream ? super.getBufferSize() : bufferedServletOutputStream.getBufferSize();
}
@Override
public void flushBuffer() throws IOException {
getBufferedServletOutputStream().flush();
}
@Override
public void resetBuffer() {
if (isCommitted()) {
throw new IllegalStateException("Cannot reset buffer - response is already committed");
}
if (null != bufferedServletOutputStream) bufferedServletOutputStream.reset();
}
@Override
public boolean isCommitted() {
return committed;
}
@Override
public void reset() {
resetBuffer();
super.reset();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (null != outputStream) {
return outputStream;
} else if (null != writer) {
throw new IllegalStateException("getWriter() method has been called on this response");
} else {
return outputStream = getBufferedServletOutputStream() ;
}
}
@Override
public PrintWriter getWriter() throws IOException {
if (null != writer) {
return writer;
} else if (null != outputStream) {
throw new IllegalStateException("getOutputStream() method has been called on this response");
} else {
return writer = new PrintWriter(new OutputStreamWriter(getBufferedServletOutputStream()), false);
}
}
}
| src/main/java/io/sniffy/servlet/BufferedServletResponseWrapper.java | package io.sniffy.servlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
class BufferedServletResponseWrapper extends HttpServletResponseWrapper {
private BufferedServletOutputStream bufferedServletOutputStream;
private ServletOutputStream outputStream;
private PrintWriter writer;
private boolean committed;
private final BufferedServletResponseListener servletResponseListener;
protected BufferedServletResponseWrapper(HttpServletResponse response,
BufferedServletResponseListener servletResponseListener) {
super(response);
this.servletResponseListener = servletResponseListener;
}
protected void notifyBeforeCommit() throws IOException {
notifyBeforeCommit(null);
}
protected void notifyBeforeCommit(Buffer buffer) throws IOException {
servletResponseListener.onBeforeCommit(this, buffer);
}
protected void notifyBeforeClose() throws IOException {
servletResponseListener.beforeClose(this, null);
}
protected void notifyBeforeClose(Buffer buffer) throws IOException {
servletResponseListener.beforeClose(this, buffer);
}
protected BufferedServletOutputStream getBufferedServletOutputStream() throws IOException {
if (null == bufferedServletOutputStream) {
bufferedServletOutputStream = new BufferedServletOutputStream(this, super.getOutputStream());
}
return bufferedServletOutputStream;
}
/**
* Flush the sniffer buffer and append the information about the executed queries to the output stream
* Also close the underlying stream if it has been requested previously
* @throws IOException
*/
protected void close() throws IOException {
if (null != writer) writer.close();
else if (null != outputStream) outputStream.close();
else {
if (!isCommitted()) {
notifyBeforeCommit();
}
notifyBeforeClose();
}
}
protected void setCommitted(boolean committed) {
this.committed = committed;
}
protected void setCommitted() {
setCommitted(true);
}
// capture content length
private int contentLength;
@Override
public void setContentLength(int len) {
super.setContentLength(contentLength = len);
}
public int getContentLength() {
return contentLength;
}
private String contentEncoding;
@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
if ("Content-Encoding".equals(name)) {
contentEncoding = value;
} else if ("Content-Length".equals(name)) {
try {
contentLength = Integer.parseInt(value);
} catch (NumberFormatException e) {
// todo: can we log it somehow plz?
}
}
}
@Override
public void setHeader(String name, String value) {
super.setHeader(name, value);
if ("Content-Encoding".equals(name)) {
contentEncoding = value;
} else if ("Content-Length".equals(name)) {
try {
contentLength = Integer.parseInt(value);
} catch (NumberFormatException e) {
// todo: can we log it somehow plz?
}
}
}
@Override
public void setIntHeader(String name, int value) {
super.setIntHeader(name, value);
if ("Content-Length".equals(name)) {
contentLength = value;
}
}
public String getContentEncoding() {
return contentEncoding;
}
private String contentType;
public String getContentType() {
return contentType;
}
@Override
public void setContentType(String contentType) {
super.setContentType(this.contentType = contentType);
}
// headers relates methods
@Override
public void sendError(int sc, String msg) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendError(sc, msg);
setCommitted();
}
@Override
public void sendError(int sc) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendError(sc);
setCommitted();
}
@Override
public void sendRedirect(String location) throws IOException {
if (isCommitted()) {
throw new IllegalStateException("Cannot set error status - response is already committed");
}
notifyBeforeCommit();
super.sendRedirect(location);
setCommitted();
}
// content related methods
@Override
public void setBufferSize(int size) {
if (null != bufferedServletOutputStream) bufferedServletOutputStream.setBufferSize(size);
}
@Override
public int getBufferSize() {
return null == bufferedServletOutputStream ? super.getBufferSize() : bufferedServletOutputStream.getBufferSize();
}
@Override
public void flushBuffer() throws IOException {
getBufferedServletOutputStream().flush();
}
@Override
public void resetBuffer() {
if (isCommitted()) {
throw new IllegalStateException("Cannot reset buffer - response is already committed");
}
if (null != bufferedServletOutputStream) bufferedServletOutputStream.reset();
}
@Override
public boolean isCommitted() {
return committed;
}
@Override
public void reset() {
resetBuffer();
super.reset();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (null != outputStream) {
return outputStream;
} else if (null != writer) {
throw new IllegalStateException("getWriter() method has been called on this response");
} else {
return outputStream = getBufferedServletOutputStream() ;
}
}
@Override
public PrintWriter getWriter() throws IOException {
if (null != writer) {
return writer;
} else if (null != outputStream) {
throw new IllegalStateException("getOutputStream() method has been called on this response");
} else {
return writer = new PrintWriter(new OutputStreamWriter(getBufferedServletOutputStream()), false);
}
}
}
| Added TODOs to check for possible NPEs
| src/main/java/io/sniffy/servlet/BufferedServletResponseWrapper.java | Added TODOs to check for possible NPEs | <ide><path>rc/main/java/io/sniffy/servlet/BufferedServletResponseWrapper.java
<ide> }
<ide>
<ide> protected void notifyBeforeCommit() throws IOException {
<del> notifyBeforeCommit(null);
<add> notifyBeforeCommit(null); // TODO: check for possible NPE
<ide> }
<ide>
<ide> protected void notifyBeforeCommit(Buffer buffer) throws IOException {
<ide> }
<ide>
<ide> protected void notifyBeforeClose() throws IOException {
<del> servletResponseListener.beforeClose(this, null);
<add> servletResponseListener.beforeClose(this, null); // TODO: check for possible NPE
<ide> }
<ide>
<ide> protected void notifyBeforeClose(Buffer buffer) throws IOException { |
|
Java | lgpl-2.1 | 48d2c5c75df5a89ba5ba59609cf8735e355a3a67 | 0 | kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,JoeCarlson/intermine,elsiklab/intermine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,JoeCarlson/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,zebrafishmine/intermine,kimrutherford/intermine,zebrafishmine/intermine,tomck/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,tomck/intermine,tomck/intermine,justincc/intermine,elsiklab/intermine,justincc/intermine,drhee/toxoMine,justincc/intermine,drhee/toxoMine,joshkh/intermine,JoeCarlson/intermine,elsiklab/intermine,joshkh/intermine,zebrafishmine/intermine,zebrafishmine/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,drhee/toxoMine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,kimrutherford/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,kimrutherford/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,drhee/toxoMine,elsiklab/intermine,drhee/toxoMine,tomck/intermine,JoeCarlson/intermine,drhee/toxoMine,kimrutherford/intermine,drhee/toxoMine | package org.intermine.dwr;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.BagQueryConfig;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.Scope;
import org.intermine.api.search.SearchFilterEngine;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateQuery;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.PortalHelper;
import org.intermine.web.logic.bag.BagConverter;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.HTMLWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.HTMLWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final String INVALID_NAME_MSG = "Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
String nameCopy = name.replaceAll("#039;", "'");
TagManager tagManager = getTagManager();
// already a favourite. turning off.
if (isFavourite) {
tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
// not a favourite. turning on.
} else {
tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processWidgetException(Exception e, String widgetId) {
String msg = "Failed to render widget: " + widgetId;
LOG.error(msg, e);
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return INVALID_NAME_MSG;
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ProfileManager pm = im.getProfileManager();
Profile profile = SessionMethods.getProfile(session);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
//Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
SearchRepository globalSearchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
globalSearchRepository,
hitMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals(Scope.USER)) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
if (scope.equals(Scope.GLOBAL)) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type,
pm.getSuperuser(), getTagManager());
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type,
profile.getUsername(), getTagManager());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
// We need a modifiable map so we can filter out invalid templates
LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap =
new LinkedHashMap(filteredWsMap);
SearchRepository.filterOutInvalidTemplates(modifiableWsMap);
for (WebSearchable ws: modifiableWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
InterMineBag imBag = null;
int count = 0;
try {
imBag = bagManager.getUserOrGlobalBag(profile, bagName);
List<TemplateQuery> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new bag
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (("".equals(bagName) || (bagName.equalsIgnoreCase(defaultName)))) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map savedQueries, String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
return graphWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @return graph widget
*/
public static HTMLWidget getProcessHTMLWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
Model model = im.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
HTMLWidgetConfig htmlWidgetConf = (HTMLWidgetConfig) widget;
HTMLWidget htmlWidget = new HTMLWidget(htmlWidgetConf);
return htmlWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max, String filters, String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Get the news
* @param rssURI the URI of the rss feed
* @return the news feed as html
* @deprecated use getNewsPreview() instead
*/
public static String getNewsRead(String rssURI) {
try {
URL feedUrl = new URL(rssURI);
SyndFeedInput input = new SyndFeedInput();
XmlReader reader;
try {
reader = new XmlReader(feedUrl);
} catch (Throwable e) {
// xml document at this url doesn't exist or is invalid, so the news cannot be read
return "<i>No news</i>";
}
SyndFeed feed = input.build(reader);
List<SyndEntry> entries = feed.getEntries();
StringBuffer html = new StringBuffer("<ol id=\"news\">");
int counter = 0;
for (SyndEntry syndEntry : entries) {
if (counter > 4) {
break;
}
// NB: apparently, the only accepted formats for getPublishedDate are
// Fri, 28 Jan 2008 11:02 GMT
// or
// Fri, 8 Jan 2008 11:02 GMT
// or
// Fri, 8 Jan 08 11:02 GMT
//
// an annoying error appears if the format is not followed, and news tile hangs.
//
// the following is used to display the date without timestamp.
// this should always work since the retrieved date has a fixed format,
// independent of the one used in the xml.
// longDate = Wed Aug 19 14:44:19 BST 2009
String longDate = syndEntry.getPublishedDate().toString();
String dayMonth = longDate.substring(0, 10);
String year = longDate.substring(24);
DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
Date date = df.parse(longDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// month starts at zero
int month = calendar.get(calendar.MONTH) + 1;
String monthString = String.valueOf(month);
if (monthString.length() == 1) {
monthString = "0" + monthString;
}
//http://blog.flymine.org/2009/08/
// WebContext ctx = WebContextFactory.get();
// ServletContext servletContext = ctx.getServletContext();
// Properties properties = SessionMethods.getWebProperties(servletContext);
String url = syndEntry.getLink();
// properties.getProperty("project.news") + "/" + year + "/" + monthString;
html.append("<li>");
html.append("<strong>");
html.append("<a href=\"" + url + "\">");
html.append(syndEntry.getTitle());
html.append("</a>");
html.append("</strong>");
// html.append(" - <em>" + dayMonth + " " + year + "</em><br/>");
html.append("- <em>" + syndEntry.getPublishedDate().toString() + "</em><br/>");
html.append(syndEntry.getDescription().getValue());
html.append("</li>");
counter++;
}
html.append("</ol>");
return html.toString();
} catch (MalformedURLException e) {
return "<i>No news at specified URL</i>";
} catch (IllegalArgumentException e) {
return "<i>No news at specified URL</i>";
} catch (FeedException e) {
return "<i>No news at specified URL</i>";
} catch (java.text.ParseException e) {
return "<i>No news at specified URL</i>";
}
}
//*****************************************************************************
// Tags AJAX Interface
//*****************************************************************************
/**
* Returns all objects names tagged with specified tag type and tag name.
* @param type tag type
* @param tag tag name
* @return objects names
*/
public static Set<String> filterByTag(String type, String tag) {
Profile profile = getProfile(getRequest());
SearchRepository searchRepository = profile.getSearchRepository();
Map<String, WebSearchable> map = (Map<String, WebSearchable>) searchRepository.
getWebSearchableMap(type);
if (map == null) {
return null;
}
Map<String, WebSearchable> filteredMap = new TreeMap<String, WebSearchable>();
List<String> tagList = new ArrayList<String>();
tagList.add(tag);
filteredMap.putAll(new SearchFilterEngine().filterByTags(map, tagList, type,
profile.getUsername(), getTagManager()));
return filteredMap.keySet();
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
tagName = tagName.trim();
HttpSession session = request.getSession();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
if (!TagManager.isValidTagName(tagName)) {
return INVALID_NAME_MSG;
}
if (tagName.startsWith(TagNames.IM_PREFIX)
&& !SessionMethods.isSuperUser(session)) {
return "You cannot add a tag starting with " + TagNames.IM_PREFIX + ", "
+ "that is a reserved word.";
}
TagManager tagManager = getTagManager();
tagManager.addTag(tagName, taggedObject, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.
getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
}
return "Adding tag failed.";
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
manager.deleteTag(tagName, tagged, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr =
SessionMethods.getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @throws PathException if the query is invalid
*/
public static void setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
for (String message : messages) {
SessionMethods.recordMessage(message, session);
}
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* Used on list analysis page to convert list contents to orthologues. then forwarded to
* another intermine instance.
*
* @param bagType class of bag
* @param bagName name of bag
* @param param name of parameter value, eg. `orthologue`
* @param selectedValue orthologue organism
* @return converted list of orthologues
* @throws UnsupportedEncodingException bad encoding
*/
public String convertObjects(String bagType, String bagName, String param,
String selectedValue) throws UnsupportedEncodingException {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
BagQueryConfig bagQueryConfig = im.getBagQueryConfig();
// Use custom converters
Map<String, String []> additionalConverters =
bagQueryConfig.getAdditionalConverters(bagType);
if (additionalConverters != null) {
for (String converterClassName : additionalConverters.keySet()) {
String addparameter = PortalHelper.getAdditionalParameter(param,
additionalConverters.get(converterClassName));
if (StringUtils.isNotEmpty(addparameter)) {
BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig,
converterClassName);
return bagConverter.getConvertedObjectFields(profile, bagType, bagName,
selectedValue);
}
}
}
return null;
}
}
| intermine/web/main/src/org/intermine/dwr/AjaxServices.java | package org.intermine.dwr;
/*
* Copyright (C) 2002-2010 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.queryParser.ParseException;
import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.intermine.InterMineException;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagManager;
import org.intermine.api.bag.BagQueryConfig;
import org.intermine.api.bag.TypeConverter;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.ProfileAlreadyExistsException;
import org.intermine.api.profile.ProfileManager;
import org.intermine.api.profile.SavedQuery;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebTable;
import org.intermine.api.search.Scope;
import org.intermine.api.search.SearchFilterEngine;
import org.intermine.api.search.SearchRepository;
import org.intermine.api.search.WebSearchable;
import org.intermine.api.tag.TagNames;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplateQuery;
import org.intermine.api.template.TemplateSummariser;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.util.TypeUtil;
import org.intermine.web.autocompletion.AutoCompleter;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.PortalHelper;
import org.intermine.web.logic.bag.BagConverter;
import org.intermine.web.logic.config.Type;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.query.PageTableQueryMonitor;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.WebState;
import org.intermine.web.logic.session.QueryCountQueryMonitor;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.widget.EnrichmentWidget;
import org.intermine.web.logic.widget.GraphWidget;
import org.intermine.web.logic.widget.HTMLWidget;
import org.intermine.web.logic.widget.TableWidget;
import org.intermine.web.logic.widget.config.EnrichmentWidgetConfig;
import org.intermine.web.logic.widget.config.GraphWidgetConfig;
import org.intermine.web.logic.widget.config.HTMLWidgetConfig;
import org.intermine.web.logic.widget.config.TableWidgetConfig;
import org.intermine.web.logic.widget.config.WidgetConfig;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* This class contains the methods called through DWR Ajax
*
* @author Xavier Watkins
*
*/
public class AjaxServices
{
protected static final Logger LOG = Logger.getLogger(AjaxServices.class);
private static final Object ERROR_MSG = "Error happened during DWR ajax service.";
private static final String INVALID_NAME_MSG = "Invalid name. Names may only contain letters, "
+ "numbers, spaces, and underscores.";
/**
* Creates a favourite Tag for the given templateName
*
* @param name the name of the template we want to set as a favourite
* @param type type of tag (bag or template)
* @param isFavourite whether or not this item is currently a favourite
*/
public void setFavourite(String name, String type, boolean isFavourite) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
String nameCopy = name.replaceAll("#039;", "'");
TagManager tagManager = getTagManager();
// already a favourite. turning off.
if (isFavourite) {
tagManager.deleteTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
// not a favourite. turning on.
} else {
tagManager.addTag(TagNames.IM_FAVOURITE, nameCopy, type, profile.getUsername());
}
} catch (RuntimeException e) {
processException(e);
}
}
private static void processWidgetException(Exception e, String widgetId) {
String msg = "Failed to render widget: " + widgetId;
LOG.error(msg, e);
}
private static void processException(Exception e) {
LOG.error(ERROR_MSG, e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
/**
* Precomputes the given template query
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String preCompute(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery t = templates.get(templateName);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
try {
session.setAttribute("precomputing_" + templateName, "true");
executor.precomputeTemplate(t);
} catch (ObjectStoreException e) {
LOG.error("Error while precomputing", e);
} finally {
session.removeAttribute("precomputing_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "precomputed";
}
/**
* Summarises the given template query.
*
* @param templateName the template query name
* @return a String to guarantee the service ran properly
*/
public String summarise(String templateName) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
Map<String, TemplateQuery> templates = profile.getSavedTemplates();
TemplateQuery template = templates.get(templateName);
TemplateSummariser summariser = im.getTemplateSummariser();
try {
session.setAttribute("summarising_" + templateName, "true");
summariser.summarise(template);
} catch (ObjectStoreException e) {
LOG.error("Failed to summarise " + templateName, e);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("No such template "
+ templateName);
e2.initCause(e);
throw e2;
} finally {
session.removeAttribute("summarising_" + templateName);
}
} catch (RuntimeException e) {
processException(e);
}
return "summarised";
}
/**
* Rename a element such as history, name, bag
* @param name the name of the element
* @param type history, saved, bag
* @param reName the new name for the element
* @return the new name of the element as a String
* @exception Exception if the application business logic throws
* an exception
*/
public String rename(String name, String type, String reName)
throws Exception {
String newName;
try {
newName = reName.trim();
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
SavedQuery sq;
if (name.equals(newName) || StringUtils.isEmpty(newName)) {
return name;
}
// TODO get error text from properties file
if (!NameUtil.isValidName(newName)) {
return INVALID_NAME_MSG;
}
if ("history".equals(type)) {
if (profile.getHistory().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getHistory().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
profile.renameHistory(name, newName);
} else if ("saved".equals(type)) {
if (profile.getSavedQueries().get(name) == null) {
return "<i>" + name + " does not exist</i>";
}
if (profile.getSavedQueries().get(newName) != null) {
return "<i>" + newName + " already exists</i>";
}
sq = profile.getSavedQueries().get(name);
profile.deleteQuery(sq.getName());
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
profile.saveQuery(sq.getName(), sq);
} else if ("bag".equals(type)) {
try {
profile.renameBag(name, newName);
} catch (IllegalArgumentException e) {
return "<i>" + name + " does not exist</i>";
} catch (ProfileAlreadyExistsException e) {
return "<i>" + newName + " already exists</i>";
}
} else {
return "Type unknown";
}
return newName;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag, set its description
* @param bagName the bag
* @param description the description as entered by the user
* @return the description for display on the jsp page
* @throws Exception an exception
*/
public String saveBagDescription(String bagName, String description) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
Profile profile = SessionMethods.getProfile(session);
InterMineBag bag = profile.getSavedBags().get(bagName);
if (bag == null) {
throw new InterMineException("List \"" + bagName + "\" not found.");
}
bag.setDescription(description);
profile.getSearchRepository().descriptionChanged(bag);
return description;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Set the description of a view path.
* @param pathString the string representation of the path
* @param description the new description
* @return the description, or null if the description was empty
*/
public String changeViewPathDescription(String pathString, String description) {
try {
String descr = description;
if (description.trim().length() == 0) {
descr = null;
}
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
Path path = query.makePath(pathString);
Path prefixPath = path.getPrefix();
if (descr == null) {
// setting to null removes the description
query.setDescription(prefixPath.getNoConstraintsString(), null);
} else {
query.setDescription(prefixPath.getNoConstraintsString(), descr);
}
if (descr == null) {
return null;
}
return descr.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
} catch (RuntimeException e) {
processException(e);
return null;
} catch (PathException e) {
processException(e);
return null;
}
}
/*
* Cannot be refactored from AjaxServices, else WebContextFactory.get() returns null
*/
private static WebState getWebState() {
HttpSession session = WebContextFactory.get().getSession();
return SessionMethods.getWebState(session);
}
/**
* Get the summary for the given column
* @param summaryPath the path for the column as a String
* @param tableName name of column-owning table
* @return a collection of rows
* @throws Exception an exception
*/
public static List getColumnSummary(String tableName, String summaryPath) throws Exception {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
WebTable webTable = (SessionMethods.getResultsTable(session, tableName))
.getWebTable();
PathQuery pathQuery = webTable.getPathQuery();
List<ResultsRow> results = (List) webResultsExecutor.summariseQuery(pathQuery,
summaryPath);
// Start the count of results
Query countQuery = webResultsExecutor.makeSummaryQuery(pathQuery, summaryPath);
QueryCountQueryMonitor clientState
= new QueryCountQueryMonitor(Constants.QUERY_TIMEOUT_SECONDS * 1000, countQuery);
MessageResources messages = (MessageResources) ctx.getHttpServletRequest()
.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQueryCount(clientState, session, messages);
List<ResultsRow> pageSizeResults = new ArrayList<ResultsRow>();
int rowCount = 0;
for (ResultsRow row : results) {
rowCount++;
if (rowCount > 10) {
break;
}
pageSizeResults.add(row);
}
return Arrays.asList(new Object[] {pageSizeResults, qid, new Integer(rowCount)});
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Return the number of rows of results from the query with the given query id. If the size
* isn't yet available, return null. The query must be started with
* SessionMethods.startPagedTableCount().
* @param qid the id
* @return the row count or null if not yet available
*/
public static Integer getResultsSize(String qid) {
try {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
QueryMonitorTimeout controller = (QueryMonitorTimeout)
SessionMethods.getRunningQueryController(qid, session);
// this could happen if the user navigates away then back to the page
if (controller == null) {
return null;
}
// First tickle the controller to avoid timeout
controller.tickle();
if (controller.isCancelledWithError()) {
LOG.debug("query qid " + qid + " error");
return null;
} else if (controller.isCancelled()) {
LOG.debug("query qid " + qid + " cancelled");
return null;
} else if (controller.isCompleted()) {
LOG.debug("query qid " + qid + " complete");
if (controller instanceof PageTableQueryMonitor) {
PagedTable pt = ((PageTableQueryMonitor) controller).getPagedTable();
return new Integer(pt.getExactSize());
}
if (controller instanceof QueryCountQueryMonitor) {
return new Integer(((QueryCountQueryMonitor) controller).getCount());
}
LOG.debug("query qid " + qid + " - unknown controller type");
return null;
} else {
// query still running
LOG.debug("query qid " + qid + " still running, making client wait");
return null;
}
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Given a scope, type, tags and some filter text, produce a list of matching WebSearchable, in
* a format useful in JavaScript. Each element of the returned List is a List containing a
* WebSearchable name, a score (from Lucene) and a string with the matching parts of the
* description highlighted.
* @param scope the scope (from TemplateHelper.GLOBAL_TEMPLATE or TemplateHelper.USER_TEMPLATE,
* even though not all WebSearchables are templates)
* @param type the type (from TagTypes)
* @param tags the tags to filter on
* @param filterText the text to pass to Lucene
* @param filterAction toggles favourites filter off an on; will be blank or 'favourites'
* @param callId unique id
* @return a List of Lists
*/
public static List<String> filterWebSearchables(String scope, String type,
List<String> tags, String filterText,
String filterAction, String callId) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ProfileManager pm = im.getProfileManager();
Profile profile = SessionMethods.getProfile(session);
Map<String, WebSearchable> wsMap;
Map<WebSearchable, Float> hitMap = new LinkedHashMap<WebSearchable, Float>();
Map<WebSearchable, String> highlightedDescMap = new HashMap<WebSearchable, String>();
if (filterText != null && filterText.length() > 1) {
wsMap = new LinkedHashMap<String, WebSearchable>();
//Map<WebSearchable, String> scopeMap = new LinkedHashMap<WebSearchable, String>();
SearchRepository globalSearchRepository =
SessionMethods.getGlobalSearchRepository(servletContext);
try {
long time =
SearchRepository.runLeuceneSearch(filterText, scope, type, profile,
globalSearchRepository,
hitMap, null, highlightedDescMap);
LOG.info("Lucene search took " + time + " milliseconds");
} catch (ParseException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
} catch (IOException e) {
LOG.error("couldn't run lucene filter", e);
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add(callId);
return emptyList;
}
//long time = System.currentTimeMillis();
for (WebSearchable ws: hitMap.keySet()) {
wsMap.put(ws.getName(), ws);
}
} else {
if (scope.equals(Scope.USER)) {
SearchRepository searchRepository = profile.getSearchRepository();
wsMap = (Map<String, WebSearchable>) searchRepository.getWebSearchableMap(type);
} else {
SearchRepository globalRepository = SessionMethods
.getGlobalSearchRepository(servletContext);
if (scope.equals(Scope.GLOBAL)) {
wsMap = (Map<String, WebSearchable>) globalRepository.
getWebSearchableMap(type);
} else {
// must be "all"
SearchRepository userSearchRepository = profile.getSearchRepository();
Map<String, ? extends WebSearchable> userWsMap =
userSearchRepository.getWebSearchableMap(type);
Map<String, ? extends WebSearchable> globalWsMap =
globalRepository.getWebSearchableMap(type);
wsMap = new HashMap<String, WebSearchable>(userWsMap);
wsMap.putAll(globalWsMap);
}
}
}
Map<String, ? extends WebSearchable> filteredWsMap
= new LinkedHashMap<String, WebSearchable>();
//Filter by aspects (defined in superuser account)
List<String> aspectTags = new ArrayList<String>();
List<String> userTags = new ArrayList<String>();
for (String tag :tags) {
if (tag.startsWith(TagNames.IM_ASPECT_PREFIX)) {
aspectTags.add(tag);
} else {
userTags.add(tag);
}
}
if (aspectTags.size() > 0) {
wsMap = new SearchFilterEngine().filterByTags(wsMap, aspectTags, type,
pm.getSuperuser(), getTagManager());
}
if (profile.getUsername() != null && userTags.size() > 0) {
filteredWsMap = new SearchFilterEngine().filterByTags(wsMap, userTags, type,
profile.getUsername(), getTagManager());
} else {
filteredWsMap = wsMap;
}
List returnList = new ArrayList<String>();
returnList.add(callId);
// We need a modifiable map so we can filter out invalid templates
LinkedHashMap<String, ? extends WebSearchable> modifiableWsMap =
new LinkedHashMap(filteredWsMap);
SearchRepository.filterOutInvalidTemplates(modifiableWsMap);
for (WebSearchable ws: modifiableWsMap.values()) {
List row = new ArrayList();
row.add(ws.getName());
if (filterText != null && filterText.length() > 1) {
row.add(highlightedDescMap.get(ws));
row.add(hitMap.get(ws));
} else {
row.add(ws.getDescription());
}
returnList.add(row);
}
return returnList;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* For a given bag name and a type different from the bag type, give the number of
* converted objects
*
* @param bagName the name of the bag
* @param type the type to convert to
* @return the number of converted objects
*/
public static int getConvertCountForBag(String bagName, String type) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
String pckName = im.getModel().getPackageName();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
TemplateManager templateManager = im.getTemplateManager();
WebResultsExecutor webResultsExecutor = im.getWebResultsExecutor(profile);
InterMineBag imBag = null;
int count = 0;
try {
imBag = bagManager.getUserOrGlobalBag(profile, bagName);
List<TemplateQuery> conversionTemplates = templateManager.getConversionTemplates();
PathQuery pathQuery = TypeConverter.getConversionQuery(conversionTemplates,
TypeUtil.instantiate(pckName + "." + imBag.getType()),
TypeUtil.instantiate(pckName + "." + type), imBag);
count = webResultsExecutor.count(pathQuery);
} catch (Exception e) {
throw new RuntimeException(e);
}
return count;
} catch (RuntimeException e) {
processException(e);
return 0;
}
}
/**
* Saves information, that some element was toggled - displayed or hidden.
*
* @param elementId element id
* @param opened new aspect state
*/
public static void saveToggleState(String elementId, boolean opened) {
try {
AjaxServices.getWebState().getToggledElements().put(elementId,
Boolean.valueOf(opened));
} catch (RuntimeException e) {
processException(e);
}
}
/**
* Set state that should be saved during the session.
* @param name name of state
* @param value value of state
*/
public static void setState(String name, String value) {
try {
AjaxServices.getWebState().setState(name, value);
} catch (RuntimeException e) {
processException(e);
}
}
/**
* validate bag upload
* @param bagName name of new bag to be validated
* @return error msg to display, if any
*/
public static String validateBagName(String bagName) {
try {
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
bagName = bagName.trim();
// TODO get message text from the properties file
if ("".equals(bagName)) {
return "You cannot save a list with a blank name";
}
if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
if (profile.getSavedBags().get(bagName) != null) {
return "The list name you have chosen is already in use";
}
if (bagManager.getGlobalBag(bagName) != null) {
return "The list name you have chosen is already in use -"
+ " there is a public list called " + bagName;
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* validation that happens before new bag is saved
* @param bagName name of new bag
* @param selectedBags bags involved in operation
* @param operation which operation is taking place - delete, union, intersect or subtract
* @return error msg, if any
*/
public static String validateBagOperations(String bagName, String[] selectedBags,
String operation) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
Profile profile = SessionMethods.getProfile(session);
// TODO get error text from the properties file
if (selectedBags.length == 0) {
return "No lists are selected";
}
if ("delete".equals(operation)) {
for (int i = 0; i < selectedBags.length; i++) {
Set<String> queries = new HashSet<String>();
queries.addAll(queriesThatMentionBag(profile.getSavedQueries(),
selectedBags[i]));
queries.addAll(queriesThatMentionBag(profile.getHistory(), selectedBags[i]));
if (queries.size() > 0) {
return "List " + selectedBags[i] + " cannot be deleted as it is referenced "
+ "by other queries " + queries;
}
}
} else if (!"copy".equals(operation)) {
Properties properties = SessionMethods.getWebProperties(servletContext);
String defaultName = properties.getProperty("lists.input.example");
if (("".equals(bagName) || (bagName.equalsIgnoreCase(defaultName)))) {
return "New list name is required";
} else if (!NameUtil.isValidName(bagName)) {
return INVALID_NAME_MSG;
}
}
return "";
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* Provide a list of queries that mention a named bag
* @param savedQueries a saved queries map (name -> query)
* @param bagName the name of a bag
* @return the list of queries
*/
private static List<String> queriesThatMentionBag(Map savedQueries, String bagName) {
try {
List<String> queries = new ArrayList<String>();
for (Iterator i = savedQueries.keySet().iterator(); i.hasNext();) {
String queryName = (String) i.next();
SavedQuery query = (SavedQuery) savedQueries.get(queryName);
if (query.getPathQuery().getBagNames().contains(bagName)) {
queries.add(queryName);
}
}
return queries;
} catch (RuntimeException e) {
processException(e);
return null;
}
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @param selectedExtraAttribute extra attribute (like organism)
* @return graph widget
*/
public static GraphWidget getProcessGraphWidget(String widgetId, String bagName,
String selectedExtraAttribute) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
GraphWidgetConfig graphWidgetConf = (GraphWidgetConfig) widget;
graphWidgetConf.setSession(session);
GraphWidget graphWidget = new GraphWidget(graphWidgetConf, imBag, os,
selectedExtraAttribute);
return graphWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* @param widgetId unique id for this widget
* @param bagName name of list
* @return graph widget
*/
public static HTMLWidget getProcessHTMLWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
Model model = im.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widget: widgets) {
if (widget.getId().equals(widgetId)) {
HTMLWidgetConfig htmlWidgetConf = (HTMLWidgetConfig) widget;
HTMLWidget htmlWidget = new HTMLWidget(htmlWidgetConf);
return htmlWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for this widget
* @param bagName name of list
* @return table widget
*/
public static TableWidget getProcessTableWidget(String widgetId, String bagName) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig: widgets) {
if (widgetConfig.getId().equals(widgetId)) {
TableWidgetConfig tableWidgetConfig = (TableWidgetConfig) widgetConfig;
tableWidgetConfig.setClassKeys(classKeys);
tableWidgetConfig.setWebConfig(webConfig);
TableWidget tableWidget = new TableWidget(tableWidgetConfig, imBag, os, null);
return tableWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
*
* @param widgetId unique ID for each widget
* @param bagName name of list
* @param errorCorrection error correction method to use
* @param max maximum value to display
* @param filters list of strings used to filter widget results, ie Ontology
* @param externalLink link to external datasource
* @param externalLinkLabel name of external datasource.
* @return enrichment widget
*/
public static EnrichmentWidget getProcessEnrichmentWidget(String widgetId, String bagName,
String errorCorrection, String max, String filters, String externalLink,
String externalLinkLabel) {
try {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpSession session = WebContextFactory.get().getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
ObjectStore os = im.getObjectStore();
Model model = os.getModel();
Profile profile = SessionMethods.getProfile(session);
BagManager bagManager = im.getBagManager();
InterMineBag imBag = bagManager.getUserOrGlobalBag(profile, bagName);
Type type = webConfig.getTypes().get(model.getPackageName()
+ "." + imBag.getType());
List<WidgetConfig> widgets = type.getWidgets();
for (WidgetConfig widgetConfig : widgets) {
if (widgetConfig.getId().equals(widgetId)) {
EnrichmentWidgetConfig enrichmentWidgetConfig =
(EnrichmentWidgetConfig) widgetConfig;
enrichmentWidgetConfig.setExternalLink(externalLink);
enrichmentWidgetConfig.setExternalLinkLabel(externalLinkLabel);
EnrichmentWidget enrichmentWidget = new EnrichmentWidget(
enrichmentWidgetConfig, imBag, os, filters, max,
errorCorrection);
return enrichmentWidget;
}
}
} catch (RuntimeException e) {
processWidgetException(e, widgetId);
}
return null;
}
/**
* Add an ID to the PagedTable selection
* @param selectedId the id
* @param tableId the identifier for the PagedTable
* @param columnIndex the column of the selected id
* @return the field values of the first selected objects
*/
public static List<String> selectId(String selectedId, String tableId, String columnIndex) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.selectId(new Integer(selectedId), (new Integer(columnIndex)).intValue());
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* remove an Id from the PagedTable
* @param deSelectId the ID to remove from the selection
* @param tableId the PagedTable identifier
* @return the field values of the first selected objects
*/
public static List<String> deSelectId(String deSelectId, String tableId) {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.deSelectId(new Integer(deSelectId));
Map<String, List<FieldDescriptor>> classKeys = im.getClassKeys();
ObjectStore os = im.getObjectStore();
return pt.getFirstSelectedFields(os, classKeys);
}
/**
* Select all the elements in a PagedTable
* @param index the index of the selected column
* @param tableId the PagedTable identifier
*/
public static void selectAll(int index, String tableId) {
HttpSession session = WebContextFactory.get().getSession();
PagedTable pt = SessionMethods.getResultsTable(session, tableId);
pt.clearSelectIds();
pt.setAllSelectedColumn(index);
}
/**
* AJAX request - reorder view.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorder(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
List<String> view = SessionMethods.getEditingView(session);
ArrayList<String> newView = new ArrayList<String>();
for (int i = 0; i < view.size(); i++) {
String newi = newOrderList.get(i);
int oldi = oldOrderList.indexOf(newi);
newView.add(view.get(oldi));
}
PathQuery query = SessionMethods.getQuery(session);
query.clearView();
query.addViews(newView);
}
/**
* AJAX request - reorder the constraints.
* @param newOrder the new order as a String
* @param oldOrder the previous order as a String
*/
public void reorderConstraints(String newOrder, String oldOrder) {
HttpSession session = WebContextFactory.get().getSession();
List<String> newOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(newOrder).values());
List<String> oldOrderList =
new LinkedList<String>(StringUtil.serializedSortOrderToMap(oldOrder).values());
PathQuery query = SessionMethods.getQuery(session);
if (query instanceof TemplateQuery) {
TemplateQuery template = (TemplateQuery) query;
for (int index = 0; index < newOrderList.size() - 1; index++) {
String newi = newOrderList.get(index);
int oldi = oldOrderList.indexOf(newi);
if (index != oldi) {
List<PathConstraint> editableConstraints =
template.getModifiableEditableConstraints();
PathConstraint editableConstraint = editableConstraints.remove(oldi);
editableConstraints.add(index, editableConstraint);
template.setEditableConstraints(editableConstraints);
break;
}
}
}
}
/**
* Add a Node from the sort order
* @param path the Path as a String
* @param direction the direction to sort by
* @exception Exception if the application business logic throws
*/
public void addToSortOrder(String path, String direction)
throws Exception {
HttpSession session = WebContextFactory.get().getSession();
PathQuery query = SessionMethods.getQuery(session);
OrderDirection orderDirection = OrderDirection.ASC;
if ("DESC".equals(direction.toUpperCase())) {
orderDirection = OrderDirection.DESC;
}
query.clearOrderBy();
query.addOrderBy(path, orderDirection);
}
/**
* Work as a proxy for fetching remote file (RSS)
* @param rssURL the url
* @return String representation of a file
*/
public static String getNewsPreview(String rssURL) {
try {
URL url = new URL(rssURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuffer sb = new StringBuffer();
// append to string buffer
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
} catch (MalformedURLException e) {
return "";
} catch (IOException e) {
return "";
}
}
/**
* Get the news
* @param rssURI the URI of the rss feed
* @return the news feed as html
*
* @deprecated use getNewsPreview() instead
*/
public static String getNewsRead(String rssURI) {
try {
URL feedUrl = new URL(rssURI);
SyndFeedInput input = new SyndFeedInput();
XmlReader reader;
try {
reader = new XmlReader(feedUrl);
} catch (Throwable e) {
// xml document at this url doesn't exist or is invalid, so the news cannot be read
return "<i>No news</i>";
}
SyndFeed feed = input.build(reader);
List<SyndEntry> entries = feed.getEntries();
StringBuffer html = new StringBuffer("<ol id=\"news\">");
int counter = 0;
for (SyndEntry syndEntry : entries) {
if (counter > 4) {
break;
}
// NB: apparently, the only accepted formats for getPublishedDate are
// Fri, 28 Jan 2008 11:02 GMT
// or
// Fri, 8 Jan 2008 11:02 GMT
// or
// Fri, 8 Jan 08 11:02 GMT
//
// an annoying error appears if the format is not followed, and news tile hangs.
//
// the following is used to display the date without timestamp.
// this should always work since the retrieved date has a fixed format,
// independent of the one used in the xml.
// longDate = Wed Aug 19 14:44:19 BST 2009
String longDate = syndEntry.getPublishedDate().toString();
String dayMonth = longDate.substring(0, 10);
String year = longDate.substring(24);
DateFormat df = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
Date date = df.parse(longDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// month starts at zero
int month = calendar.get(calendar.MONTH) + 1;
String monthString = String.valueOf(month);
if (monthString.length() == 1) {
monthString = "0" + monthString;
}
//http://blog.flymine.org/2009/08/
// WebContext ctx = WebContextFactory.get();
// ServletContext servletContext = ctx.getServletContext();
// Properties properties = SessionMethods.getWebProperties(servletContext);
String url = syndEntry.getLink();
// properties.getProperty("project.news") + "/" + year + "/" + monthString;
html.append("<li>");
html.append("<strong>");
html.append("<a href=\"" + url + "\">");
html.append(syndEntry.getTitle());
html.append("</a>");
html.append("</strong>");
// html.append(" - <em>" + dayMonth + " " + year + "</em><br/>");
html.append("- <em>" + syndEntry.getPublishedDate().toString() + "</em><br/>");
html.append(syndEntry.getDescription().getValue());
html.append("</li>");
counter++;
}
html.append("</ol>");
return html.toString();
} catch (MalformedURLException e) {
return "<i>No news at specified URL</i>";
} catch (IllegalArgumentException e) {
return "<i>No news at specified URL</i>";
} catch (FeedException e) {
return "<i>No news at specified URL</i>";
} catch (java.text.ParseException e) {
return "<i>No news at specified URL</i>";
}
}
//*****************************************************************************
// Tags AJAX Interface
//*****************************************************************************
/**
* Returns all objects names tagged with specified tag type and tag name.
* @param type tag type
* @param tag tag name
* @return objects names
*/
public static Set<String> filterByTag(String type, String tag) {
Profile profile = getProfile(getRequest());
SearchRepository searchRepository = profile.getSearchRepository();
Map<String, WebSearchable> map = (Map<String, WebSearchable>) searchRepository.
getWebSearchableMap(type);
if (map == null) {
return null;
}
Map<String, WebSearchable> filteredMap = new TreeMap<String, WebSearchable>();
List<String> tagList = new ArrayList<String>();
tagList.add(tag);
filteredMap.putAll(new SearchFilterEngine().filterByTags(map, tagList, type,
profile.getUsername(), getTagManager()));
return filteredMap.keySet();
}
/**
* Adds tag and assures that there is only one tag for this combination of tag name, tagged
* Object and type.
* @param tag tag name
* @param taggedObject object id that is tagged by this tag
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String addTag(String tag, String taggedObject, String type) {
String tagName = tag;
LOG.info("Called addTag(). tagName:" + tagName + " taggedObject:"
+ taggedObject + " type: " + type);
try {
HttpServletRequest request = getRequest();
Profile profile = getProfile(request);
tagName = tagName.trim();
HttpSession session = request.getSession();
if (profile.getUsername() != null
&& !StringUtils.isEmpty(tagName)
&& !StringUtils.isEmpty(type)
&& !StringUtils.isEmpty(taggedObject)) {
if (tagExists(tagName, taggedObject, type)) {
return "Already tagged with this tag.";
}
if (!TagManager.isValidTagName(tagName)) {
return INVALID_NAME_MSG;
}
if (tagName.startsWith(TagNames.IM_PREFIX)
&& !SessionMethods.isSuperUser(session)) {
return "You cannot add a tag starting with " + TagNames.IM_PREFIX + ", "
+ "that is a reserved word.";
}
TagManager tagManager = getTagManager();
tagManager.addTag(tagName, taggedObject, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr = SessionMethods.
getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
}
return "Adding tag failed.";
} catch (Throwable e) {
LOG.error("Adding tag failed", e);
return "Adding tag failed.";
}
}
/**
* Deletes tag.
* @param tagName tag name
* @param tagged id of tagged object
* @param type tag type
* @return 'ok' string if succeeded else error string
*/
public static String deleteTag(String tagName, String tagged, String type) {
LOG.info("Called deleteTag(). tagName:" + tagName + " taggedObject:"
+ tagged + " type: " + type);
try {
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = getProfile(request);
TagManager manager = im.getTagManager();
manager.deleteTag(tagName, tagged, type, profile.getUsername());
ServletContext servletContext = session.getServletContext();
if (SessionMethods.isSuperUser(session)) {
SearchRepository tr =
SessionMethods.getGlobalSearchRepository(servletContext);
tr.webSearchableTagChange(type, tagName);
}
return "ok";
} catch (Throwable e) {
LOG.error("Deleting tag failed", e);
return "Deleting tag failed.";
}
}
/**
* Returns all tags of specified tag type together with prefixes of these tags.
* For instance: for tag 'bio:experiment' it automatically adds 'bio' tag.
* @param type tag type
* @return tags
*/
public static Set<String> getTags(String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getUserTagNames(type, profile.getUsername());
}
return new TreeSet<String>();
}
/**
* Returns all tags by which is specified object tagged.
* @param type tag type
* @param tagged id of tagged object
* @return tags
*/
public static Set<String> getObjectTags(String type, String tagged) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
Profile profile = getProfile(request);
if (profile.isLoggedIn()) {
return tagManager.getObjectTagNames(tagged, type, profile.getUsername());
}
return new TreeSet<String>();
}
private static boolean tagExists(String tag, String taggedObject, String type) {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
TagManager tagManager = im.getTagManager();
String userName = getProfile(request).getUsername();
return tagManager.getObjectTagNames(taggedObject, type, userName).contains(tag);
}
private static Profile getProfile(HttpServletRequest request) {
return SessionMethods.getProfile(request.getSession());
}
private static HttpServletRequest getRequest() {
return WebContextFactory.get().getHttpServletRequest();
}
private static TagManager getTagManager() {
HttpServletRequest request = getRequest();
final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());
return im.getTagManager();
}
/**
* Set the constraint logic on a query to be the given expression.
*
* @param expression the constraint logic for the query
* @throws PathException if the query is invalid
*/
public static void setConstraintLogic(String expression) throws PathException {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
query.setConstraintLogic(expression);
List<String> messages = query.fixUpForJoinStyle();
for (String message : messages) {
SessionMethods.recordMessage(message, session);
}
}
/**
* Get the grouped constraint logic
* @return a list representing the grouped constraint logic
*/
public static String getConstraintLogic() {
WebContext ctx = WebContextFactory.get();
HttpSession session = ctx.getSession();
PathQuery query = SessionMethods.getQuery(session);
return (query.getConstraintLogic());
}
/**
* @param suffix string of input before request for more results
* @param wholeList whether or not to show the entire list or a truncated version
* @param field field name from the table for the lucene search
* @param className class name (table in the database) for lucene search
* @return an array of values for this classname.field
*/
public String[] getContent(String suffix, boolean wholeList, String field, String className) {
ServletContext servletContext = WebContextFactory.get().getServletContext();
AutoCompleter ac = SessionMethods.getAutoCompleter(servletContext);
ac.createRAMIndex(className + "." + field);
if (!wholeList && suffix.length() > 0) {
String[] shortList = ac.getFastList(suffix, field, 31);
return shortList;
} else if (suffix.length() > 2 && wholeList) {
String[] longList = ac.getList(suffix, field);
return longList;
}
String[] defaultList = {""};
return defaultList;
}
/**
* Used on list analysis page to convert list contents to orthologues. then forwarded to
* another intermine instance.
*
* @param bagType class of bag
* @param bagName name of bag
* @param param name of parameter value, eg. `orthologue`
* @param selectedValue orthologue organism
* @return converted list of orthologues
* @throws UnsupportedEncodingException bad encoding
*/
public String convertObjects(String bagType, String bagName, String param,
String selectedValue) throws UnsupportedEncodingException {
ServletContext servletContext = WebContextFactory.get().getServletContext();
HttpServletRequest request = getRequest();
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
Profile profile = SessionMethods.getProfile(session);
WebConfig webConfig = SessionMethods.getWebConfig(servletContext);
BagQueryConfig bagQueryConfig = im.getBagQueryConfig();
// Use custom converters
Map<String, String []> additionalConverters =
bagQueryConfig.getAdditionalConverters(bagType);
if (additionalConverters != null) {
for (String converterClassName : additionalConverters.keySet()) {
String addparameter = PortalHelper.getAdditionalParameter(param,
additionalConverters.get(converterClassName));
if (StringUtils.isNotEmpty(addparameter)) {
BagConverter bagConverter = PortalHelper.getBagConverter(im, webConfig,
converterClassName);
return bagConverter.getConvertedObjectFields(profile, bagType, bagName,
selectedValue);
}
}
}
return null;
}
}
| checkstyle
| intermine/web/main/src/org/intermine/dwr/AjaxServices.java | checkstyle | <ide><path>ntermine/web/main/src/org/intermine/dwr/AjaxServices.java
<ide> * Get the news
<ide> * @param rssURI the URI of the rss feed
<ide> * @return the news feed as html
<del> *
<ide> * @deprecated use getNewsPreview() instead
<ide> */
<ide> public static String getNewsRead(String rssURI) { |
|
Java | apache-2.0 | 6b013f365702d1ef95168da4a7801873255c9ee8 | 0 | farmerbb/Taskbar,farmerbb/Taskbar | /* Copyright 2016 Braden Farmer
*
* 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.farmerbb.taskbar.util;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.Toast;
import com.farmerbb.taskbar.BuildConfig;
import com.farmerbb.taskbar.R;
import com.farmerbb.taskbar.activity.DummyActivity;
import com.farmerbb.taskbar.activity.InvisibleActivityFreeform;
import com.farmerbb.taskbar.activity.ShortcutActivity;
import com.farmerbb.taskbar.activity.StartTaskbarActivity;
import com.farmerbb.taskbar.receiver.LockDeviceReceiver;
import com.farmerbb.taskbar.service.DashboardService;
import com.farmerbb.taskbar.service.NotificationService;
import com.farmerbb.taskbar.service.PowerMenuService;
import com.farmerbb.taskbar.service.StartMenuService;
import com.farmerbb.taskbar.service.TaskbarService;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import moe.banana.support.ToastCompat;
public class U {
private U() {}
private static SharedPreferences pref;
private static Integer cachedRotation;
private static final int MAXIMIZED = 0;
private static final int LEFT = -1;
private static final int RIGHT = 1;
public static final int HIDDEN = 0;
public static final int TOP_APPS = 1;
// From android.app.ActivityManager.StackId
private static final int FULLSCREEN_WORKSPACE_STACK_ID = 1;
private static final int FREEFORM_WORKSPACE_STACK_ID = 2;
public static SharedPreferences getSharedPreferences(Context context) {
if(pref == null) pref = context.getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE);
return pref;
}
@TargetApi(Build.VERSION_CODES.M)
public static void showPermissionDialog(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.permission_dialog_title)
.setMessage(R.string.permission_dialog_message)
.setPositiveButton(R.string.action_grant_permission, (dialog, which) -> {
try {
context.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
} catch (ActivityNotFoundException e) {
showErrorDialog(context, "SYSTEM_ALERT_WINDOW");
}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
}
public static void showErrorDialog(final Context context, String appopCmd) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.error_dialog_title)
.setMessage(context.getString(R.string.error_dialog_message, BuildConfig.APPLICATION_ID, appopCmd))
.setPositiveButton(R.string.action_ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
public static void lockDevice(Context context) {
ComponentName component = new ComponentName(context, LockDeviceReceiver.class);
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
if(mDevicePolicyManager.isAdminActive(component))
mDevicePolicyManager.lockNow();
else {
Intent intent = new Intent(context, DummyActivity.class);
intent.putExtra("device_admin", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public static void sendAccessibilityAction(Context context, int action) {
ComponentName component = new ComponentName(context, PowerMenuService.class);
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
if(isAccessibilityServiceEnabled(context)) {
Intent intent = new Intent("com.farmerbb.taskbar.ACCESSIBILITY_ACTION");
intent.putExtra("action", action);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
showToastLong(context, R.string.enable_accessibility);
} catch (ActivityNotFoundException e) {
showToast(context, R.string.lock_device_not_supported);
}
}
}
private static boolean isAccessibilityServiceEnabled(Context context) {
String accessibilityServices = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
ComponentName component = new ComponentName(context, PowerMenuService.class);
return accessibilityServices != null
&& (accessibilityServices.contains(component.flattenToString())
|| accessibilityServices.contains(component.flattenToShortString()));
}
public static void showToast(Context context, int message) {
showToast(context, context.getString(message), Toast.LENGTH_SHORT);
}
public static void showToastLong(Context context, int message) {
showToast(context, context.getString(message), Toast.LENGTH_LONG);
}
public static void showToast(Context context, String message, int length) {
cancelToast();
ToastCompat toast = ToastCompat.makeText(context.getApplicationContext(), message, length);
toast.show();
ToastHelper.getInstance().setLastToast(toast);
}
public static void cancelToast() {
ToastCompat toast = ToastHelper.getInstance().getLastToast();
if(toast != null) toast.cancel();
}
public static void startShortcut(Context context, String packageName, String componentName, ShortcutInfo shortcut) {
launchApp(context,
packageName,
componentName,
0,
null,
false,
false,
shortcut);
}
public static void launchApp(final Context context,
final String packageName,
final String componentName,
final long userId, final String windowSize,
final boolean launchedFromTaskbar,
final boolean openInNewWindow) {
launchApp(context,
packageName,
componentName,
userId,
windowSize,
launchedFromTaskbar,
openInNewWindow,
null);
}
private static void launchApp(final Context context,
final String packageName,
final String componentName,
final long userId, final String windowSize,
final boolean launchedFromTaskbar,
final boolean openInNewWindow,
final ShortcutInfo shortcut) {
SharedPreferences pref = getSharedPreferences(context);
FreeformHackHelper helper = FreeformHackHelper.getInstance();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& pref.getBoolean("freeform_hack", false)
&& !helper.isInFreeformWorkspace()) {
new Handler().postDelayed(() -> {
startFreeformHack(context, true, launchedFromTaskbar);
new Handler().postDelayed(() -> continueLaunchingApp(context, packageName, componentName, userId,
windowSize, launchedFromTaskbar, openInNewWindow, shortcut), helper.isFreeformHackActive() ? 0 : 100);
}, launchedFromTaskbar ? 0 : 100);
} else
continueLaunchingApp(context, packageName, componentName, userId,
windowSize, launchedFromTaskbar, openInNewWindow, shortcut);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
public static void startFreeformHack(Context context, boolean checkMultiWindow, boolean launchedFromTaskbar) {
Intent freeformHackIntent = new Intent(context, InvisibleActivityFreeform.class);
freeformHackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
if(checkMultiWindow)
freeformHackIntent.putExtra("check_multiwindow", true);
if(launchedFromTaskbar) {
SharedPreferences pref = getSharedPreferences(context);
if(pref.getBoolean("disable_animations", false))
freeformHackIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
if(U.canDrawOverlays(context))
launchAppLowerRight(context, freeformHackIntent);
}
@TargetApi(Build.VERSION_CODES.N)
private static void continueLaunchingApp(Context context,
String packageName,
String componentName,
long userId,
String windowSize,
boolean launchedFromTaskbar,
boolean openInNewWindow,
ShortcutInfo shortcut) {
SharedPreferences pref = getSharedPreferences(context);
Intent intent = new Intent();
intent.setComponent(ComponentName.unflattenFromString(componentName));
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if(FreeformHackHelper.getInstance().isInFreeformWorkspace()
&& Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1
&& !isOPreview())
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
if(launchedFromTaskbar) {
if(pref.getBoolean("disable_animations", false))
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
if(openInNewWindow || pref.getBoolean("force_new_window", false)) {
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
ActivityInfo activityInfo = intent.resolveActivityInfo(context.getPackageManager(), 0);
if(activityInfo != null) {
switch(activityInfo.launchMode) {
case ActivityInfo.LAUNCH_SINGLE_TASK:
case ActivityInfo.LAUNCH_SINGLE_INSTANCE:
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
break;
}
}
}
boolean specialLaunch = isOPreview() && FreeformHackHelper.getInstance().isFreeformHackActive() && openInNewWindow;
if(windowSize == null) {
if(pref.getBoolean("save_window_sizes", true))
windowSize = SavedWindowSizes.getInstance(context).getWindowSize(context, packageName);
else
windowSize = pref.getString("window_size", "standard");
}
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !pref.getBoolean("freeform_hack", false)) {
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
context.startActivity(intent, null);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), null, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), null, userId);
} else
launchShortcut(context, shortcut, null);
} else switch(windowSize) {
case "standard":
if(FreeformHackHelper.getInstance().isInFreeformWorkspace() && !specialLaunch) {
Bundle bundle = getActivityOptions(getApplicationType(context, packageName)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
context.startActivity(intent, bundle);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
} else
launchMode1(context, intent, 1, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "large":
launchMode1(context, intent, 2, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "fullscreen":
launchMode2(context, intent, MAXIMIZED, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "half_left":
launchMode2(context, intent, LEFT, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "half_right":
launchMode2(context, intent, RIGHT, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "phone_size":
launchMode3(context, intent, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
}
if(pref.getBoolean("hide_taskbar", true) && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_TASKBAR"));
else
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode1(Context context, Intent intent, int factor, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int width1 = display.getWidth() / (4 * factor);
int width2 = display.getWidth() - width1;
int height1 = display.getHeight() / (4 * factor);
int height2 = display.getHeight() - height1;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
width1,
height1,
width2,
height2
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode2(Context context, Intent intent, int launchType, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int statusBarHeight = getStatusBarHeight(context);
String position = getTaskbarPosition(context);
boolean isPortrait = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
boolean isLandscape = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
int left = launchType == RIGHT && isLandscape
? display.getWidth() / 2
: 0;
int top = launchType == RIGHT && isPortrait
? display.getHeight() / 2
: statusBarHeight;
int right = launchType == LEFT && isLandscape
? display.getWidth() / 2
: display.getWidth();
int bottom = launchType == LEFT && isPortrait
? display.getHeight() / 2
: display.getHeight();
int iconSize = context.getResources().getDimensionPixelSize(R.dimen.icon_size);
if(position.contains("vertical_left")) {
if(launchType != RIGHT || isPortrait) left = left + iconSize;
} else if(position.contains("vertical_right")) {
if(launchType != LEFT || isPortrait) right = right - iconSize;
} else if(position.contains("bottom")) {
if(isLandscape || (launchType != LEFT && isPortrait))
bottom = bottom - iconSize;
} else if(isLandscape || (launchType != RIGHT && isPortrait))
top = top + iconSize;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
left,
top,
right,
bottom
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode3(Context context, Intent intent, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int width1 = display.getWidth() / 2;
int width2 = context.getResources().getDimensionPixelSize(R.dimen.phone_size_width) / 2;
int height1 = display.getHeight() / 2;
int height2 = context.getResources().getDimensionPixelSize(R.dimen.phone_size_height) / 2;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
width1 - width2,
height1 - height2,
width1 + width2,
height1 + height2
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
private static void launchAndroidForWork(Context context, ComponentName componentName, Bundle bundle, long userId) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
try {
launcherApps.startMainActivity(componentName, userManager.getUserForSerialNumber(userId), null, bundle);
} catch (ActivityNotFoundException | NullPointerException e) { /* Gracefully fail */ }
}
@TargetApi(Build.VERSION_CODES.N_MR1)
private static void launchShortcut(Context context, ShortcutInfo shortcut, Bundle bundle) {
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
if(launcherApps.hasShortcutHostPermission()) {
try {
launcherApps.startShortcut(shortcut, null, bundle);
} catch (ActivityNotFoundException | NullPointerException e) { /* Gracefully fail */ }
}
}
public static void launchAppMaximized(Context context, Intent intent) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
long userId = userManager.getSerialNumberForUser(Process.myUserHandle());
launchMode2(context, intent, MAXIMIZED, userId, null, ApplicationType.CONTEXT_MENU, false);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
public static void launchAppLowerRight(Context context, Intent intent) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
try {
context.startActivity(intent, getActivityOptions(ApplicationType.FREEFORM_HACK).setLaunchBounds(new Rect(
display.getWidth(),
display.getHeight(),
display.getWidth() + 1,
display.getHeight() + 1
)).toBundle());
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
}
public static void checkForUpdates(Context context) {
if(!BuildConfig.DEBUG) {
String url;
try {
context.getPackageManager().getPackageInfo("com.android.vending", 0);
url = "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID;
} catch (PackageManager.NameNotFoundException e) {
url = "https://f-droid.org/repository/browse/?fdid=" + BuildConfig.BASE_APPLICATION_ID;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) { /* Gracefully fail */ }
} else
showToast(context, R.string.debug_build);
}
public static boolean launcherIsDefault(Context context) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo defaultLauncher = context.getPackageManager().resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);
return defaultLauncher.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID);
}
public static void setCachedRotation(int cachedRotation) {
U.cachedRotation = cachedRotation;
}
public static String getTaskbarPosition(Context context) {
SharedPreferences pref = getSharedPreferences(context);
String position = pref.getString("position", "bottom_left");
if(pref.getBoolean("anchor", false)) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int rotation = cachedRotation != null ? cachedRotation : windowManager.getDefaultDisplay().getRotation();
switch(position) {
case "bottom_left":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_left";
case Surface.ROTATION_90:
return "bottom_vertical_right";
case Surface.ROTATION_180:
return "top_right";
case Surface.ROTATION_270:
return "top_vertical_left";
}
break;
case "bottom_vertical_left":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_vertical_left";
case Surface.ROTATION_90:
return "bottom_right";
case Surface.ROTATION_180:
return "top_vertical_right";
case Surface.ROTATION_270:
return "top_left";
}
break;
case "bottom_right":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_right";
case Surface.ROTATION_90:
return "top_vertical_right";
case Surface.ROTATION_180:
return "top_left";
case Surface.ROTATION_270:
return "bottom_vertical_left";
}
break;
case "bottom_vertical_right":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_vertical_right";
case Surface.ROTATION_90:
return "top_right";
case Surface.ROTATION_180:
return "top_vertical_left";
case Surface.ROTATION_270:
return "bottom_left";
}
break;
case "top_left":
switch(rotation) {
case Surface.ROTATION_0:
return "top_left";
case Surface.ROTATION_90:
return "bottom_vertical_left";
case Surface.ROTATION_180:
return "bottom_right";
case Surface.ROTATION_270:
return "top_vertical_right";
}
break;
case "top_vertical_left":
switch(rotation) {
case Surface.ROTATION_0:
return "top_vertical_left";
case Surface.ROTATION_90:
return "bottom_left";
case Surface.ROTATION_180:
return "bottom_vertical_right";
case Surface.ROTATION_270:
return "top_right";
}
break;
case "top_right":
switch(rotation) {
case Surface.ROTATION_0:
return "top_right";
case Surface.ROTATION_90:
return "top_vertical_left";
case Surface.ROTATION_180:
return "bottom_left";
case Surface.ROTATION_270:
return "bottom_vertical_right";
}
break;
case "top_vertical_right":
switch(rotation) {
case Surface.ROTATION_0:
return "top_vertical_right";
case Surface.ROTATION_90:
return "top_left";
case Surface.ROTATION_180:
return "bottom_vertical_left";
case Surface.ROTATION_270:
return "bottom_right";
}
break;
}
}
return position;
}
private static int getMaxNumOfColumns(Context context) {
SharedPreferences pref = getSharedPreferences(context);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float baseTaskbarSize = getBaseTaskbarSizeFloat(context) / metrics.density;
int numOfColumns = 0;
float maxScreenSize = getTaskbarPosition(context).contains("vertical")
? (metrics.heightPixels - getStatusBarHeight(context)) / metrics.density
: metrics.widthPixels / metrics.density;
float iconSize = context.getResources().getDimension(R.dimen.icon_size) / metrics.density;
int userMaxNumOfColumns = Integer.valueOf(pref.getString("max_num_of_recents", "10"));
while(baseTaskbarSize + iconSize < maxScreenSize
&& numOfColumns < userMaxNumOfColumns) {
baseTaskbarSize = baseTaskbarSize + iconSize;
numOfColumns++;
}
return numOfColumns;
}
public static int getMaxNumOfEntries(Context context) {
SharedPreferences pref = getSharedPreferences(context);
return pref.getBoolean("disable_scrolling_list", false)
? getMaxNumOfColumns(context)
: Integer.valueOf(pref.getString("max_num_of_recents", "10"));
}
public static int getStatusBarHeight(Context context) {
int statusBarHeight = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if(resourceId > 0)
statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
return statusBarHeight;
}
public static void refreshPinnedIcons(Context context) {
IconCache.getInstance(context).clearCache();
PinnedBlockedApps pba = PinnedBlockedApps.getInstance(context);
List<AppEntry> pinnedAppsList = new ArrayList<>(pba.getPinnedApps());
List<AppEntry> blockedAppsList = new ArrayList<>(pba.getBlockedApps());
PackageManager pm = context.getPackageManager();
pba.clear(context);
for(AppEntry entry : pinnedAppsList) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
final List<UserHandle> userHandles = userManager.getUserProfiles();
LauncherActivityInfo appInfo = null;
for(UserHandle handle : userHandles) {
List<LauncherActivityInfo> list = launcherApps.getActivityList(entry.getPackageName(), handle);
if(!list.isEmpty()) {
// Google App workaround
if(!entry.getPackageName().equals("com.google.android.googlequicksearchbox"))
appInfo = list.get(0);
else {
boolean added = false;
for(LauncherActivityInfo info : list) {
if(info.getName().equals("com.google.android.googlequicksearchbox.SearchActivity")) {
appInfo = info;
added = true;
}
}
if(!added) appInfo = list.get(0);
}
break;
}
}
if(appInfo != null) {
AppEntry newEntry = new AppEntry(
entry.getPackageName(),
entry.getComponentName(),
entry.getLabel(),
IconCache.getInstance(context).getIcon(context, pm, appInfo),
true);
newEntry.setUserId(entry.getUserId(context));
pba.addPinnedApp(context, newEntry);
}
}
for(AppEntry entry : blockedAppsList) {
pba.addBlockedApp(context, entry);
}
}
public static Intent getShortcutIntent(Context context) {
Intent shortcutIntent = new Intent(context, ShortcutActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.putExtra("is_launching_shortcut", true);
BitmapDrawable drawable = (BitmapDrawable) context.getDrawable(R.mipmap.ic_freeform_mode);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if(drawable != null) intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, drawable.getBitmap());
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.pref_header_freeform));
return intent;
}
public static Intent getStartStopIntent(Context context) {
Intent shortcutIntent = new Intent(context, StartTaskbarActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.putExtra("is_launching_shortcut", true);
BitmapDrawable drawable = (BitmapDrawable) context.getDrawable(R.mipmap.ic_launcher);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if(drawable != null) intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, drawable.getBitmap());
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.start_taskbar));
return intent;
}
public static boolean hasFreeformSupport(Context context) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT)
|| Settings.Global.getInt(context.getContentResolver(), "enable_freeform_support", -1) == 1
|| Settings.Global.getInt(context.getContentResolver(), "force_resizable_activities", -1) == 1);
}
public static boolean isServiceRunning(Context context, Class<? extends Service> cls) {
return isServiceRunning(context, cls.getName());
}
public static boolean isServiceRunning(Context context, String className) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if(className.equals(service.service.getClassName()))
return true;
}
return false;
}
public static int getBackgroundTint(Context context) {
SharedPreferences pref = getSharedPreferences(context);
// Import old background tint preference
if(pref.contains("show_background")) {
SharedPreferences.Editor editor = pref.edit();
if(!pref.getBoolean("show_background", true))
editor.putInt("background_tint", 0).apply();
editor.remove("show_background");
editor.apply();
}
return pref.getInt("background_tint", context.getResources().getInteger(R.integer.translucent_gray));
}
public static int getAccentColor(Context context) {
SharedPreferences pref = getSharedPreferences(context);
return pref.getInt("accent_color", context.getResources().getInteger(R.integer.translucent_white));
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean canDrawOverlays(Context context) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context);
}
public static boolean isGame(Context context, String packageName) {
SharedPreferences pref = getSharedPreferences(context);
if(pref.getBoolean("launch_games_fullscreen", true)) {
PackageManager pm = context.getPackageManager();
try {
ApplicationInfo info = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
return (info.flags & ApplicationInfo.FLAG_IS_GAME) != 0 || (info.metaData != null && info.metaData.getBoolean("isGame", false));
} catch (PackageManager.NameNotFoundException e) {
return false;
}
} else
return false;
}
@TargetApi(Build.VERSION_CODES.M)
public static ActivityOptions getActivityOptions(ApplicationType applicationType) {
ActivityOptions options = ActivityOptions.makeBasic();
Integer stackId = null;
switch(applicationType) {
case APPLICATION:
// Let the system determine the stack id
break;
case GAME:
stackId = FULLSCREEN_WORKSPACE_STACK_ID;
break;
case FREEFORM_HACK:
stackId = FREEFORM_WORKSPACE_STACK_ID;
break;
case CONTEXT_MENU:
if(isOPreview()) stackId = FULLSCREEN_WORKSPACE_STACK_ID;
}
if(stackId != null) {
try {
Method method = ActivityOptions.class.getMethod("setLaunchStackId", int.class);
method.invoke(options, stackId);
} catch (Exception e) { /* Gracefully fail */ }
}
return options;
}
private static ApplicationType getApplicationType(Context context, String packageName) {
return isGame(context, packageName) ? ApplicationType.GAME : ApplicationType.APPLICATION;
}
public static boolean isSystemApp(Context context) {
try {
ApplicationInfo info = context.getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID, 0);
int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
return (info.flags & mask) != 0;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean isOPreview() {
return Build.VERSION.RELEASE.equals("O") && Build.VERSION.PREVIEW_SDK_INT > 0;
}
public static boolean hasSupportLibrary(Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(BuildConfig.SUPPORT_APPLICATION_ID, 0);
return pm.checkSignatures(BuildConfig.SUPPORT_APPLICATION_ID, BuildConfig.APPLICATION_ID) == PackageManager.SIGNATURE_MATCH
&& BuildConfig.APPLICATION_ID.equals(BuildConfig.BASE_APPLICATION_ID)
&& isSystemApp(context);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private static void startActivity(Context context, Intent intent, Bundle options, boolean specialLaunch) {
if(specialLaunch) {
startFreeformHack(context, true, false);
new Handler().post(() -> context.startActivity(intent, options));
} else
context.startActivity(intent, options);
}
public static int getBaseTaskbarSize(Context context) {
return Math.round(getBaseTaskbarSizeFloat(context));
}
private static float getBaseTaskbarSizeFloat(Context context) {
SharedPreferences pref = getSharedPreferences(context);
float baseTaskbarSize = context.getResources().getDimension(R.dimen.base_taskbar_size);
boolean navbarButtonsEnabled = false;
if(pref.getBoolean("dashboard", false))
baseTaskbarSize += context.getResources().getDimension(R.dimen.dashboard_button_size);
if(pref.getBoolean("button_back", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(pref.getBoolean("button_home", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(pref.getBoolean("button_recents", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(navbarButtonsEnabled)
baseTaskbarSize += context.getResources().getDimension(R.dimen.navbar_buttons_margin);
return baseTaskbarSize;
}
private static void startTaskbarService(Context context, boolean fullRestart) {
context.startService(new Intent(context, TaskbarService.class));
context.startService(new Intent(context, StartMenuService.class));
context.startService(new Intent(context, DashboardService.class));
if(fullRestart) context.startService(new Intent(context, NotificationService.class));
}
private static void stopTaskbarService(Context context, boolean fullRestart) {
context.stopService(new Intent(context, TaskbarService.class));
context.stopService(new Intent(context, StartMenuService.class));
context.stopService(new Intent(context, DashboardService.class));
if(fullRestart) context.stopService(new Intent(context, NotificationService.class));
}
public static void restartTaskbar(Context context) {
SharedPreferences pref = U.getSharedPreferences(context);
if(pref.getBoolean("taskbar_active", false) && !pref.getBoolean("is_hidden", false)) {
pref.edit().putBoolean("is_restarting", true).apply();
stopTaskbarService(context, true);
startTaskbarService(context, true);
} else if(U.isServiceRunning(context, StartMenuService.class)) {
stopTaskbarService(context, false);
startTaskbarService(context, false);
}
}
}
| app/src/main/java/com/farmerbb/taskbar/util/U.java | /* Copyright 2016 Braden Farmer
*
* 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.farmerbb.taskbar.util;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.LauncherApps;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.Toast;
import com.farmerbb.taskbar.BuildConfig;
import com.farmerbb.taskbar.R;
import com.farmerbb.taskbar.activity.DummyActivity;
import com.farmerbb.taskbar.activity.InvisibleActivityFreeform;
import com.farmerbb.taskbar.activity.ShortcutActivity;
import com.farmerbb.taskbar.activity.StartTaskbarActivity;
import com.farmerbb.taskbar.receiver.LockDeviceReceiver;
import com.farmerbb.taskbar.service.DashboardService;
import com.farmerbb.taskbar.service.NotificationService;
import com.farmerbb.taskbar.service.PowerMenuService;
import com.farmerbb.taskbar.service.StartMenuService;
import com.farmerbb.taskbar.service.TaskbarService;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import moe.banana.support.ToastCompat;
public class U {
private U() {}
private static SharedPreferences pref;
private static Integer cachedRotation;
private static final int MAXIMIZED = 0;
private static final int LEFT = -1;
private static final int RIGHT = 1;
public static final int HIDDEN = 0;
public static final int TOP_APPS = 1;
// From android.app.ActivityManager.StackId
private static final int FULLSCREEN_WORKSPACE_STACK_ID = 1;
private static final int FREEFORM_WORKSPACE_STACK_ID = 2;
public static SharedPreferences getSharedPreferences(Context context) {
if(pref == null) pref = context.getSharedPreferences(BuildConfig.APPLICATION_ID + "_preferences", Context.MODE_PRIVATE);
return pref;
}
@TargetApi(Build.VERSION_CODES.M)
public static void showPermissionDialog(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.permission_dialog_title)
.setMessage(R.string.permission_dialog_message)
.setPositiveButton(R.string.action_grant_permission, (dialog, which) -> {
try {
context.startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
} catch (ActivityNotFoundException e) {
showErrorDialog(context, "SYSTEM_ALERT_WINDOW");
}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.setCancelable(false);
}
public static void showErrorDialog(final Context context, String appopCmd) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.error_dialog_title)
.setMessage(context.getString(R.string.error_dialog_message, BuildConfig.APPLICATION_ID, appopCmd))
.setPositiveButton(R.string.action_ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
public static void lockDevice(Context context) {
ComponentName component = new ComponentName(context, LockDeviceReceiver.class);
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
if(mDevicePolicyManager.isAdminActive(component))
mDevicePolicyManager.lockNow();
else {
Intent intent = new Intent(context, DummyActivity.class);
intent.putExtra("device_admin", true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public static void sendAccessibilityAction(Context context, int action) {
ComponentName component = new ComponentName(context, PowerMenuService.class);
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
if(isAccessibilityServiceEnabled(context)) {
Intent intent = new Intent("com.farmerbb.taskbar.ACCESSIBILITY_ACTION");
intent.putExtra("action", action);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} else {
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
showToastLong(context, R.string.enable_accessibility);
} catch (ActivityNotFoundException e) {
showToast(context, R.string.lock_device_not_supported);
}
}
}
private static boolean isAccessibilityServiceEnabled(Context context) {
String accessibilityServices = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
ComponentName component = new ComponentName(context, PowerMenuService.class);
return accessibilityServices != null
&& (accessibilityServices.contains(component.flattenToString())
|| accessibilityServices.contains(component.flattenToShortString()));
}
public static void showToast(Context context, int message) {
showToast(context, context.getString(message), Toast.LENGTH_SHORT);
}
public static void showToastLong(Context context, int message) {
showToast(context, context.getString(message), Toast.LENGTH_LONG);
}
public static void showToast(Context context, String message, int length) {
cancelToast();
ToastCompat toast = ToastCompat.makeText(context.getApplicationContext(), message, length);
toast.show();
ToastHelper.getInstance().setLastToast(toast);
}
public static void cancelToast() {
ToastCompat toast = ToastHelper.getInstance().getLastToast();
if(toast != null) toast.cancel();
}
public static void startShortcut(Context context, String packageName, String componentName, ShortcutInfo shortcut) {
launchApp(context,
packageName,
componentName,
0,
null,
false,
false,
shortcut);
}
public static void launchApp(final Context context,
final String packageName,
final String componentName,
final long userId, final String windowSize,
final boolean launchedFromTaskbar,
final boolean openInNewWindow) {
launchApp(context,
packageName,
componentName,
userId,
windowSize,
launchedFromTaskbar,
openInNewWindow,
null);
}
private static void launchApp(final Context context,
final String packageName,
final String componentName,
final long userId, final String windowSize,
final boolean launchedFromTaskbar,
final boolean openInNewWindow,
final ShortcutInfo shortcut) {
SharedPreferences pref = getSharedPreferences(context);
FreeformHackHelper helper = FreeformHackHelper.getInstance();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& pref.getBoolean("freeform_hack", false)
&& !helper.isInFreeformWorkspace()) {
new Handler().postDelayed(() -> {
startFreeformHack(context, true, launchedFromTaskbar);
new Handler().postDelayed(() -> continueLaunchingApp(context, packageName, componentName, userId,
windowSize, launchedFromTaskbar, openInNewWindow, shortcut), helper.isFreeformHackActive() ? 0 : 100);
}, launchedFromTaskbar ? 0 : 100);
} else
continueLaunchingApp(context, packageName, componentName, userId,
windowSize, launchedFromTaskbar, openInNewWindow, shortcut);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
public static void startFreeformHack(Context context, boolean checkMultiWindow, boolean launchedFromTaskbar) {
Intent freeformHackIntent = new Intent(context, InvisibleActivityFreeform.class);
freeformHackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
if(checkMultiWindow)
freeformHackIntent.putExtra("check_multiwindow", true);
if(launchedFromTaskbar) {
SharedPreferences pref = getSharedPreferences(context);
if(pref.getBoolean("disable_animations", false))
freeformHackIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
if(U.canDrawOverlays(context))
launchAppLowerRight(context, freeformHackIntent);
}
@TargetApi(Build.VERSION_CODES.N)
private static void continueLaunchingApp(Context context,
String packageName,
String componentName,
long userId,
String windowSize,
boolean launchedFromTaskbar,
boolean openInNewWindow,
ShortcutInfo shortcut) {
SharedPreferences pref = getSharedPreferences(context);
Intent intent = new Intent();
intent.setComponent(ComponentName.unflattenFromString(componentName));
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if(launchedFromTaskbar) {
if(pref.getBoolean("disable_animations", false))
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
}
if(openInNewWindow || pref.getBoolean("force_new_window", false)) {
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
ActivityInfo activityInfo = intent.resolveActivityInfo(context.getPackageManager(), 0);
if(activityInfo != null) {
switch(activityInfo.launchMode) {
case ActivityInfo.LAUNCH_SINGLE_TASK:
case ActivityInfo.LAUNCH_SINGLE_INSTANCE:
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);
break;
}
}
}
boolean specialLaunch = isOPreview() && FreeformHackHelper.getInstance().isFreeformHackActive() && openInNewWindow;
if(windowSize == null) {
if(pref.getBoolean("save_window_sizes", true))
windowSize = SavedWindowSizes.getInstance(context).getWindowSize(context, packageName);
else
windowSize = pref.getString("window_size", "standard");
}
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !pref.getBoolean("freeform_hack", false)) {
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
context.startActivity(intent, null);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), null, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), null, userId);
} else
launchShortcut(context, shortcut, null);
} else switch(windowSize) {
case "standard":
if(FreeformHackHelper.getInstance().isInFreeformWorkspace() && !specialLaunch) {
Bundle bundle = getActivityOptions(getApplicationType(context, packageName)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
context.startActivity(intent, bundle);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
} else
launchMode1(context, intent, 1, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "large":
launchMode1(context, intent, 2, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "fullscreen":
launchMode2(context, intent, MAXIMIZED, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "half_left":
launchMode2(context, intent, LEFT, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "half_right":
launchMode2(context, intent, RIGHT, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
case "phone_size":
launchMode3(context, intent, userId, shortcut, getApplicationType(context, packageName), specialLaunch);
break;
}
if(pref.getBoolean("hide_taskbar", true) && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_TASKBAR"));
else
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode1(Context context, Intent intent, int factor, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int width1 = display.getWidth() / (4 * factor);
int width2 = display.getWidth() - width1;
int height1 = display.getHeight() / (4 * factor);
int height2 = display.getHeight() - height1;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
width1,
height1,
width2,
height2
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode2(Context context, Intent intent, int launchType, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int statusBarHeight = getStatusBarHeight(context);
String position = getTaskbarPosition(context);
boolean isPortrait = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
boolean isLandscape = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
int left = launchType == RIGHT && isLandscape
? display.getWidth() / 2
: 0;
int top = launchType == RIGHT && isPortrait
? display.getHeight() / 2
: statusBarHeight;
int right = launchType == LEFT && isLandscape
? display.getWidth() / 2
: display.getWidth();
int bottom = launchType == LEFT && isPortrait
? display.getHeight() / 2
: display.getHeight();
int iconSize = context.getResources().getDimensionPixelSize(R.dimen.icon_size);
if(position.contains("vertical_left")) {
if(launchType != RIGHT || isPortrait) left = left + iconSize;
} else if(position.contains("vertical_right")) {
if(launchType != LEFT || isPortrait) right = right - iconSize;
} else if(position.contains("bottom")) {
if(isLandscape || (launchType != LEFT && isPortrait))
bottom = bottom - iconSize;
} else if(isLandscape || (launchType != RIGHT && isPortrait))
top = top + iconSize;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
left,
top,
right,
bottom
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
private static void launchMode3(Context context, Intent intent, long userId, ShortcutInfo shortcut, ApplicationType type, boolean specialLaunch) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
int width1 = display.getWidth() / 2;
int width2 = context.getResources().getDimensionPixelSize(R.dimen.phone_size_width) / 2;
int height1 = display.getHeight() / 2;
int height2 = context.getResources().getDimensionPixelSize(R.dimen.phone_size_height) / 2;
Bundle bundle = getActivityOptions(type).setLaunchBounds(new Rect(
width1 - width2,
height1 - height2,
width1 + width2,
height1 + height2
)).toBundle();
if(shortcut == null) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if(userId == userManager.getSerialNumberForUser(Process.myUserHandle())) {
try {
startActivity(context, intent, bundle, specialLaunch);
} catch (ActivityNotFoundException e) {
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
} else
launchAndroidForWork(context, intent.getComponent(), bundle, userId);
} else
launchShortcut(context, shortcut, bundle);
}
private static void launchAndroidForWork(Context context, ComponentName componentName, Bundle bundle, long userId) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
try {
launcherApps.startMainActivity(componentName, userManager.getUserForSerialNumber(userId), null, bundle);
} catch (ActivityNotFoundException | NullPointerException e) { /* Gracefully fail */ }
}
@TargetApi(Build.VERSION_CODES.N_MR1)
private static void launchShortcut(Context context, ShortcutInfo shortcut, Bundle bundle) {
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
if(launcherApps.hasShortcutHostPermission()) {
try {
launcherApps.startShortcut(shortcut, null, bundle);
} catch (ActivityNotFoundException | NullPointerException e) { /* Gracefully fail */ }
}
}
public static void launchAppMaximized(Context context, Intent intent) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
long userId = userManager.getSerialNumberForUser(Process.myUserHandle());
launchMode2(context, intent, MAXIMIZED, userId, null, ApplicationType.CONTEXT_MENU, false);
}
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N)
public static void launchAppLowerRight(Context context, Intent intent) {
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);
try {
context.startActivity(intent, getActivityOptions(ApplicationType.FREEFORM_HACK).setLaunchBounds(new Rect(
display.getWidth(),
display.getHeight(),
display.getWidth() + 1,
display.getHeight() + 1
)).toBundle());
} catch (IllegalArgumentException e) { /* Gracefully fail */ }
}
public static void checkForUpdates(Context context) {
if(!BuildConfig.DEBUG) {
String url;
try {
context.getPackageManager().getPackageInfo("com.android.vending", 0);
url = "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID;
} catch (PackageManager.NameNotFoundException e) {
url = "https://f-droid.org/repository/browse/?fdid=" + BuildConfig.BASE_APPLICATION_ID;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) { /* Gracefully fail */ }
} else
showToast(context, R.string.debug_build);
}
public static boolean launcherIsDefault(Context context) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo defaultLauncher = context.getPackageManager().resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);
return defaultLauncher.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID);
}
public static void setCachedRotation(int cachedRotation) {
U.cachedRotation = cachedRotation;
}
public static String getTaskbarPosition(Context context) {
SharedPreferences pref = getSharedPreferences(context);
String position = pref.getString("position", "bottom_left");
if(pref.getBoolean("anchor", false)) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int rotation = cachedRotation != null ? cachedRotation : windowManager.getDefaultDisplay().getRotation();
switch(position) {
case "bottom_left":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_left";
case Surface.ROTATION_90:
return "bottom_vertical_right";
case Surface.ROTATION_180:
return "top_right";
case Surface.ROTATION_270:
return "top_vertical_left";
}
break;
case "bottom_vertical_left":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_vertical_left";
case Surface.ROTATION_90:
return "bottom_right";
case Surface.ROTATION_180:
return "top_vertical_right";
case Surface.ROTATION_270:
return "top_left";
}
break;
case "bottom_right":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_right";
case Surface.ROTATION_90:
return "top_vertical_right";
case Surface.ROTATION_180:
return "top_left";
case Surface.ROTATION_270:
return "bottom_vertical_left";
}
break;
case "bottom_vertical_right":
switch(rotation) {
case Surface.ROTATION_0:
return "bottom_vertical_right";
case Surface.ROTATION_90:
return "top_right";
case Surface.ROTATION_180:
return "top_vertical_left";
case Surface.ROTATION_270:
return "bottom_left";
}
break;
case "top_left":
switch(rotation) {
case Surface.ROTATION_0:
return "top_left";
case Surface.ROTATION_90:
return "bottom_vertical_left";
case Surface.ROTATION_180:
return "bottom_right";
case Surface.ROTATION_270:
return "top_vertical_right";
}
break;
case "top_vertical_left":
switch(rotation) {
case Surface.ROTATION_0:
return "top_vertical_left";
case Surface.ROTATION_90:
return "bottom_left";
case Surface.ROTATION_180:
return "bottom_vertical_right";
case Surface.ROTATION_270:
return "top_right";
}
break;
case "top_right":
switch(rotation) {
case Surface.ROTATION_0:
return "top_right";
case Surface.ROTATION_90:
return "top_vertical_left";
case Surface.ROTATION_180:
return "bottom_left";
case Surface.ROTATION_270:
return "bottom_vertical_right";
}
break;
case "top_vertical_right":
switch(rotation) {
case Surface.ROTATION_0:
return "top_vertical_right";
case Surface.ROTATION_90:
return "top_left";
case Surface.ROTATION_180:
return "bottom_vertical_left";
case Surface.ROTATION_270:
return "bottom_right";
}
break;
}
}
return position;
}
private static int getMaxNumOfColumns(Context context) {
SharedPreferences pref = getSharedPreferences(context);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float baseTaskbarSize = getBaseTaskbarSizeFloat(context) / metrics.density;
int numOfColumns = 0;
float maxScreenSize = getTaskbarPosition(context).contains("vertical")
? (metrics.heightPixels - getStatusBarHeight(context)) / metrics.density
: metrics.widthPixels / metrics.density;
float iconSize = context.getResources().getDimension(R.dimen.icon_size) / metrics.density;
int userMaxNumOfColumns = Integer.valueOf(pref.getString("max_num_of_recents", "10"));
while(baseTaskbarSize + iconSize < maxScreenSize
&& numOfColumns < userMaxNumOfColumns) {
baseTaskbarSize = baseTaskbarSize + iconSize;
numOfColumns++;
}
return numOfColumns;
}
public static int getMaxNumOfEntries(Context context) {
SharedPreferences pref = getSharedPreferences(context);
return pref.getBoolean("disable_scrolling_list", false)
? getMaxNumOfColumns(context)
: Integer.valueOf(pref.getString("max_num_of_recents", "10"));
}
public static int getStatusBarHeight(Context context) {
int statusBarHeight = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if(resourceId > 0)
statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
return statusBarHeight;
}
public static void refreshPinnedIcons(Context context) {
IconCache.getInstance(context).clearCache();
PinnedBlockedApps pba = PinnedBlockedApps.getInstance(context);
List<AppEntry> pinnedAppsList = new ArrayList<>(pba.getPinnedApps());
List<AppEntry> blockedAppsList = new ArrayList<>(pba.getBlockedApps());
PackageManager pm = context.getPackageManager();
pba.clear(context);
for(AppEntry entry : pinnedAppsList) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
final List<UserHandle> userHandles = userManager.getUserProfiles();
LauncherActivityInfo appInfo = null;
for(UserHandle handle : userHandles) {
List<LauncherActivityInfo> list = launcherApps.getActivityList(entry.getPackageName(), handle);
if(!list.isEmpty()) {
// Google App workaround
if(!entry.getPackageName().equals("com.google.android.googlequicksearchbox"))
appInfo = list.get(0);
else {
boolean added = false;
for(LauncherActivityInfo info : list) {
if(info.getName().equals("com.google.android.googlequicksearchbox.SearchActivity")) {
appInfo = info;
added = true;
}
}
if(!added) appInfo = list.get(0);
}
break;
}
}
if(appInfo != null) {
AppEntry newEntry = new AppEntry(
entry.getPackageName(),
entry.getComponentName(),
entry.getLabel(),
IconCache.getInstance(context).getIcon(context, pm, appInfo),
true);
newEntry.setUserId(entry.getUserId(context));
pba.addPinnedApp(context, newEntry);
}
}
for(AppEntry entry : blockedAppsList) {
pba.addBlockedApp(context, entry);
}
}
public static Intent getShortcutIntent(Context context) {
Intent shortcutIntent = new Intent(context, ShortcutActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.putExtra("is_launching_shortcut", true);
BitmapDrawable drawable = (BitmapDrawable) context.getDrawable(R.mipmap.ic_freeform_mode);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if(drawable != null) intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, drawable.getBitmap());
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.pref_header_freeform));
return intent;
}
public static Intent getStartStopIntent(Context context) {
Intent shortcutIntent = new Intent(context, StartTaskbarActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.putExtra("is_launching_shortcut", true);
BitmapDrawable drawable = (BitmapDrawable) context.getDrawable(R.mipmap.ic_launcher);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
if(drawable != null) intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, drawable.getBitmap());
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.start_taskbar));
return intent;
}
public static boolean hasFreeformSupport(Context context) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
&& (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT)
|| Settings.Global.getInt(context.getContentResolver(), "enable_freeform_support", -1) == 1
|| Settings.Global.getInt(context.getContentResolver(), "force_resizable_activities", -1) == 1);
}
public static boolean isServiceRunning(Context context, Class<? extends Service> cls) {
return isServiceRunning(context, cls.getName());
}
public static boolean isServiceRunning(Context context, String className) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for(ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if(className.equals(service.service.getClassName()))
return true;
}
return false;
}
public static int getBackgroundTint(Context context) {
SharedPreferences pref = getSharedPreferences(context);
// Import old background tint preference
if(pref.contains("show_background")) {
SharedPreferences.Editor editor = pref.edit();
if(!pref.getBoolean("show_background", true))
editor.putInt("background_tint", 0).apply();
editor.remove("show_background");
editor.apply();
}
return pref.getInt("background_tint", context.getResources().getInteger(R.integer.translucent_gray));
}
public static int getAccentColor(Context context) {
SharedPreferences pref = getSharedPreferences(context);
return pref.getInt("accent_color", context.getResources().getInteger(R.integer.translucent_white));
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean canDrawOverlays(Context context) {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context);
}
public static boolean isGame(Context context, String packageName) {
SharedPreferences pref = getSharedPreferences(context);
if(pref.getBoolean("launch_games_fullscreen", true)) {
PackageManager pm = context.getPackageManager();
try {
ApplicationInfo info = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
return (info.flags & ApplicationInfo.FLAG_IS_GAME) != 0 || (info.metaData != null && info.metaData.getBoolean("isGame", false));
} catch (PackageManager.NameNotFoundException e) {
return false;
}
} else
return false;
}
@TargetApi(Build.VERSION_CODES.M)
public static ActivityOptions getActivityOptions(ApplicationType applicationType) {
ActivityOptions options = ActivityOptions.makeBasic();
Integer stackId = null;
switch(applicationType) {
case APPLICATION:
// Let the system determine the stack id
break;
case GAME:
stackId = FULLSCREEN_WORKSPACE_STACK_ID;
break;
case FREEFORM_HACK:
stackId = FREEFORM_WORKSPACE_STACK_ID;
break;
case CONTEXT_MENU:
if(isOPreview()) stackId = FULLSCREEN_WORKSPACE_STACK_ID;
}
if(stackId != null) {
try {
Method method = ActivityOptions.class.getMethod("setLaunchStackId", int.class);
method.invoke(options, stackId);
} catch (Exception e) { /* Gracefully fail */ }
}
return options;
}
private static ApplicationType getApplicationType(Context context, String packageName) {
return isGame(context, packageName) ? ApplicationType.GAME : ApplicationType.APPLICATION;
}
public static boolean isSystemApp(Context context) {
try {
ApplicationInfo info = context.getPackageManager().getApplicationInfo(BuildConfig.APPLICATION_ID, 0);
int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
return (info.flags & mask) != 0;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
@TargetApi(Build.VERSION_CODES.M)
public static boolean isOPreview() {
return Build.VERSION.RELEASE.equals("O") && Build.VERSION.PREVIEW_SDK_INT == 1;
}
public static boolean hasSupportLibrary(Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(BuildConfig.SUPPORT_APPLICATION_ID, 0);
return pm.checkSignatures(BuildConfig.SUPPORT_APPLICATION_ID, BuildConfig.APPLICATION_ID) == PackageManager.SIGNATURE_MATCH
&& BuildConfig.APPLICATION_ID.equals(BuildConfig.BASE_APPLICATION_ID)
&& isSystemApp(context);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
private static void startActivity(Context context, Intent intent, Bundle options, boolean specialLaunch) {
if(specialLaunch) {
startFreeformHack(context, true, false);
new Handler().post(() -> context.startActivity(intent, options));
} else
context.startActivity(intent, options);
}
public static int getBaseTaskbarSize(Context context) {
return Math.round(getBaseTaskbarSizeFloat(context));
}
private static float getBaseTaskbarSizeFloat(Context context) {
SharedPreferences pref = getSharedPreferences(context);
float baseTaskbarSize = context.getResources().getDimension(R.dimen.base_taskbar_size);
boolean navbarButtonsEnabled = false;
if(pref.getBoolean("dashboard", false))
baseTaskbarSize += context.getResources().getDimension(R.dimen.dashboard_button_size);
if(pref.getBoolean("button_back", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(pref.getBoolean("button_home", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(pref.getBoolean("button_recents", false)) {
navbarButtonsEnabled = true;
baseTaskbarSize += context.getResources().getDimension(R.dimen.icon_size);
}
if(navbarButtonsEnabled)
baseTaskbarSize += context.getResources().getDimension(R.dimen.navbar_buttons_margin);
return baseTaskbarSize;
}
private static void startTaskbarService(Context context, boolean fullRestart) {
context.startService(new Intent(context, TaskbarService.class));
context.startService(new Intent(context, StartMenuService.class));
context.startService(new Intent(context, DashboardService.class));
if(fullRestart) context.startService(new Intent(context, NotificationService.class));
}
private static void stopTaskbarService(Context context, boolean fullRestart) {
context.stopService(new Intent(context, TaskbarService.class));
context.stopService(new Intent(context, StartMenuService.class));
context.stopService(new Intent(context, DashboardService.class));
if(fullRestart) context.stopService(new Intent(context, NotificationService.class));
}
public static void restartTaskbar(Context context) {
SharedPreferences pref = U.getSharedPreferences(context);
if(pref.getBoolean("taskbar_active", false) && !pref.getBoolean("is_hidden", false)) {
pref.edit().putBoolean("is_restarting", true).apply();
stopTaskbarService(context, true);
startTaskbarService(context, true);
} else if(U.isServiceRunning(context, StartMenuService.class)) {
stopTaskbarService(context, false);
startTaskbarService(context, false);
}
}
}
| Re-add task on home flag
| app/src/main/java/com/farmerbb/taskbar/util/U.java | Re-add task on home flag | <ide><path>pp/src/main/java/com/farmerbb/taskbar/util/U.java
<ide> intent.addCategory(Intent.CATEGORY_LAUNCHER);
<ide> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
<ide> intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
<add>
<add> if(FreeformHackHelper.getInstance().isInFreeformWorkspace()
<add> && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1
<add> && !isOPreview())
<add> intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
<ide>
<ide> if(launchedFromTaskbar) {
<ide> if(pref.getBoolean("disable_animations", false))
<ide>
<ide> @TargetApi(Build.VERSION_CODES.M)
<ide> public static boolean isOPreview() {
<del> return Build.VERSION.RELEASE.equals("O") && Build.VERSION.PREVIEW_SDK_INT == 1;
<add> return Build.VERSION.RELEASE.equals("O") && Build.VERSION.PREVIEW_SDK_INT > 0;
<ide> }
<ide>
<ide> public static boolean hasSupportLibrary(Context context) { |
|
JavaScript | mit | 03da4978f30a43345f24650365a8521ad80bd0a3 | 0 | ambethia/omnominator,ambethia/omnominator | google.load("maps", "2");
var MAX_NOMS = 5;
var DEFAULT_LOCATION = "Anytown, USA";
var EPSILON = 0.00001;
function initializeGoogleMaps()
{
geocoder = new GClientGeocoder();
/* Opera Hack */
setTimeout( function()
{
initializeMap();
initializeMarkers();
},
100 );
}
function initializeMap() {
var zoom = 3;
var location = DEFAULT_LOCATION;
var latLng = new GLatLng(39.50, -98.35);
if (google.loader.ClientLocation) {
zoom = 12;
latLng = new GLatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
location = formattedClientLocation();
}
$("#location_text").get(0).value = location;
map = new GMap2($("#map_canvas").get(0));
GEvent.addListener(map, "moveend", function() { yelp(); });
map.setCenter(latLng, zoom);
map.setUIToDefault();
}
function initializeMarkers() {
var icon = new GIcon();
icon.image = "/images/markers/yelp_star.png";
icon.shadow = "/images/markers/yelp_shadow.png";
icon.iconSize = new GSize(20, 29);
icon.shadowSize = new GSize(38, 29);
icon.iconAnchor = new GPoint(15, 29);
// Example of how we'd add custom icons for food genres.
// var sushi = new GIcon(icon, "/images/markers/sushi.png")
categoryIcons = {
// "sushi": sushi
}
defaultIcon = icon;
};
function formattedClientLocation() {
var address = google.loader.ClientLocation.address;
if (address.country_code == "US" && address.region) {
return address.city + ", " + address.region.toUpperCase();
} else {
return address.city + ", " + address.country_code;
}
}
function createMapMarker(business, position, index) {
var info = markupForTooltip(business);
var icon = getBusinessIcon(business);
var marker = new GMarker(position, icon);
GEvent.addListener(marker, "mouseover",function() { showTooltip(this, info); });
GEvent.addListener(marker, "mouseout", function() { $("#tooltip").fadeOut(); });
GEvent.addListener(marker, "click", function() { addYelpishNom(business); });
map.addOverlay(marker);
}
function addYelpishNom(business) {
var formatPhone = function(num) {
if(num.length != 10) return '';
return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10);
}
var yelp_details = {
address: [business.address1, business.address2, business.address3].join(" "),
phone: formatPhone(business.phone),
url: business.url
}
var details = $.template('${address}<br>${phone} (<a href="${url}">Details</a>)').apply(yelp_details);
addNom({
name: business.name,
details: details
})
}
function markupForTooltip(business) {
var business_address = [business.address1, business.address2, business.address3].join(" ");
var html = '<p class="name">' + business.name + '</p><p class="address">' + business_address + '</p>';
return html;
}
function showTooltip(marker, infoHTML) {
var tooltip = $("#tooltip");
var bounds = map.getBounds();
var icon = marker.getIcon();
var top = -999;
var left = -999;
tooltip.html("<div class='content'>"+infoHTML+"</div>");
if(bounds.contains(marker.getPoint())) {
var mapPx = $(map.getContainer()).position();
var pinPx = map.fromLatLngToContainerPixel(marker.getPoint());
top = (pinPx.y + mapPx.top) - (icon.iconAnchor.y + tooltip.height());
left = (pinPx.x + mapPx.left) - (icon.iconAnchor.x + tooltip.width());
if (left < 10) { left = 10 }; // keep it on the page
}
/* Ensure the tooltip doesn't obscure the pin */
tooltip.css({ top: top - 22, left: left }).fadeIn();
}
function getBusinessIcon(business) {
var icon = null;
$.each(business.categories, function() {
icon = categoryIcons[this.category_filter];
if (icon)
return false;
});
return icon || defaultIcon;
}
function map_message(message,klass)
{
$("#map_message p").text(message);
$("#map_message").get(0).className = klass;
}
function yelp() {
var bounds = map.getBounds();
var tl_lat = bounds.getSouthWest().lat();
var tl_lng = bounds.getSouthWest().lng();
var br_lat = bounds.getNorthEast().lat();
var br_lng = bounds.getNorthEast().lng();
var URI = "http://api.yelp.com/business_review_search?" +
"&num_biz_requested=10&callback=?" +
"&category=" + categoriesFilterString() +
"&tl_lat=" + tl_lat +
"&tl_long=" + tl_lng +
"&br_lat=" + br_lat +
"&br_long=" + br_lng +
"&ywsid=" + "kIXgBO4ryiAN3oPxskwNmg";
var ajaxSuccess = function(data)
{
if(data.message.text == "OK")
{
map_message("Om nom nom nom...", "happy");
map.clearOverlays();
if (data.businesses.length > 0)
{
for(var i = 0; i < data.businesses.length; i++)
{
var business = data.businesses[i];
var position = new GLatLng(business.latitude, business.longitude);
createMapMarker(business, position, i);
}
}
else
{
map_message("No noms... qq.", "mad");
}
}
else
{
var message = data.message.text;
if (message == "Area too large")
{
map_message("Zoom moar!", "content");
}
else
{
map_message("Error: " + message, "mad");
}
}
};
var ajaxError = function(XMLHttpRequest, textStatus, errorThrown)
{
};
$.ajax({
type: "GET",
url: URI,
cache: false,
contentType: "application/json",
dataType: "json",
error: ajaxError,
success: ajaxSuccess
});
}
function categoriesFilterString() {
var inputs = $("#categories li input");
var filters = [];
inputs.each(function() {
if (this.checked) {
filters.push(this.value);
}
});
if (filters.length > 0 && filters.length < inputs.length) {
return filters.join("+");
} else {
return "restaurants";
}
}
function iCanHazLocation(query) {
geocoder.getLatLng(query, function(point) {
if (!point) {
map_message("A Google says wut?", "mad");
} else {
map.setCenter(point, 12);
}
});
}
function howManyNoms()
{
return $("#sum_noms").children("li").length;
}
function has_omnoms()
{
$("#omnom").show();
$("#empty_omnom").hide();
}
function empty_omnom()
{
$("#omnom").hide();
$("#empty_omnom").show();
}
function findNom(name,details)
{
var found_existing_nom = false;
var list = $("#sum_noms li").each( function()
{
var nom_name = $(this).children(".name").text();
var nom_details = $(this).children(".details").html();
if(nom_name == name && nom_details == details )
{
found_existing_nom = true;
}
}
);
return found_existing_nom;
}
function addNom(omnom) {
var list = $("#sum_noms");
if ( howManyNoms() < MAX_NOMS) {
if(findNom(omnom.name, omnom.details))
{
$.flash.warn("Already nomz there", "dupliCAT");
return;
}
var nom_template = $.template('<li><div class="name">${name}</div><div class="details">${details}</div><a href="#" class="remove">X</a></li>');
var nom_item = nom_template.apply(omnom);
list.append(nom_item).children(':last').hide().slideDown();
$("#sum_noms .remove").click(removeNom);
} else {
$.flash.warn("Too much noms.", "My belly hurts")
};
has_omnoms();
$("#new_nom")[0].reset();
}
function removeNom() {
var nom_count = howManyNoms();
$(this).parent().slideUp().remove();
if( nom_count == 1 )
{
empty_omnom();
}
return false;
}
function createOmnom() {
var nomMapper = function()
{
var nom = {
name: $(this).children(".name").text(),
details: $(this).children(".details").html()
};
return nom;
};
var pplMapper = function()
{
return this.value ? { email: this.value } : null
};
var ajaxSuccess = function(response)
{
try { top.location.href = response.redirect_to; } catch(e) {}
};
var ajaxError = function(XMLHttpRequest, textStatus, errorThrown)
{
try
{
var json = JSON.parse( XMLHttpRequest.responseText );
var first_error = json[0][1];
$.flash.failure(first_error, "Eek!");
}
catch(e)
{
}
return false;
};
var ajaxData = JSON.stringify({
omnom: {
pplz_attributes: $.makeArray($("#sum_pplz input:text[name=ppl_emailz]").map(pplMapper)),
noms_attributes: $.makeArray($("#sum_noms li").map(nomMapper)),
creator_email: $("#creator_email").val()
}
});
$.ajax({
type: "POST",
url: "/omnom",
cache: false,
contentType: "application/json",
dataType: "json",
data: ajaxData,
error: ajaxError,
success: ajaxSuccess
});
return false;
}
function scewie6()
{
var IE6 = (navigator.userAgent.indexOf("MSIE 6")>=0) ? true : false;
if(IE6)
{
$(function()
{
$("#oh_hai").hide();
$("#header").hide();
$("body").css( { "background" : "none"} );
$("<div id='screwie6'><img src='/images/no-ie6.png'/></div>").appendTo('body');
$("#screwie6").css({"width":"213px","margin":"0 auto"});
});
}
}
$(document).ready(function() {
scewie6();
if ($("#oh_hai").length > 0) {
initializeGoogleMaps();
$("#location_form").submit(function() {
iCanHazLocation($("#location_text").get(0).value);
return false;
});
$("#categories li input").change(function() {
yelp();
});
$("#tooltip").hide();
$("#location_text").click( function()
{
if( this.value == DEFAULT_LOCATION )
{
this.value = "";
}
}
);
$("#new_nom").submit(function() {
var name = $(this.new_nom_name).val();
var details = $(this.new_nom_details).val();
if( !name )
{
$.flash.warn("Must tell me the name of the location", "Need moar info")
return false;
}
addNom( {
name: name,
details: details
} );
return false;
});
$("#sum_pplz").submit(function() {
createOmnom();
return false;
});
$("#empty_omnom").show();
$("#omnom").hide();
$("label.inside").inFieldLabels();
$("#sum_noms .remove").click(removeNom);
}
}); | public/javascripts/application.js | google.load("maps", "2");
var MAX_NOMS = 5;
var DEFAULT_LOCATION = "Anytown, USA";
var EPSILON = 0.00001;
function initializeGoogleMaps()
{
geocoder = new GClientGeocoder();
/* Opera Hack */
setTimeout( function()
{
initializeMap();
initializeMarkers();
},
100 );
}
function initializeMap() {
var zoom = 3;
var location = DEFAULT_LOCATION;
var latLng = new GLatLng(39.50, -98.35);
if (google.loader.ClientLocation) {
zoom = 12;
latLng = new GLatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
location = formattedClientLocation();
}
$("#location_text").get(0).value = location;
map = new GMap2($("#map_canvas").get(0));
GEvent.addListener(map, "moveend", function() { yelp(); });
map.setCenter(latLng, zoom);
map.setUIToDefault();
}
function initializeMarkers() {
var icon = new GIcon();
icon.image = "/images/markers/yelp_star.png";
icon.shadow = "/images/markers/yelp_shadow.png";
icon.iconSize = new GSize(20, 29);
icon.shadowSize = new GSize(38, 29);
icon.iconAnchor = new GPoint(15, 29);
// Example of how we'd add custom icons for food genres.
// var sushi = new GIcon(icon, "/images/markers/sushi.png")
categoryIcons = {
// "sushi": sushi
}
defaultIcon = icon;
};
function formattedClientLocation() {
var address = google.loader.ClientLocation.address;
if (address.country_code == "US" && address.region) {
return address.city + ", " + address.region.toUpperCase();
} else {
return address.city + ", " + address.country_code;
}
}
function createMapMarker(business, position, index) {
var info = markupForTooltip(business);
var icon = getBusinessIcon(business);
var marker = new GMarker(position, icon);
GEvent.addListener(marker, "mouseover",function() { showTooltip(this, info); });
GEvent.addListener(marker, "mouseout", function() { $("#tooltip").fadeOut(); });
GEvent.addListener(marker, "click", function() { addYelpishNom(business); });
map.addOverlay(marker);
}
function addYelpishNom(business) {
var formatPhone = function(num) {
if(num.length != 10) return '';
return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10);
}
var yelp_details = {
address: [business.address1, business.address2, business.address3].join(" "),
phone: formatPhone(business.phone),
url: business.url
}
var details = $.template('${address}<br>${phone} (<a href="${url}">Details</a>)').apply(yelp_details);
addNom({
name: business.name,
details: details
})
}
function markupForTooltip(business) {
var business_address = [business.address1, business.address2, business.address3].join(" ");
var html = '<p class="name">' + business.name + '</p><p class="address">' + business_address + '</p>';
return html;
}
function showTooltip(marker, infoHTML) {
var tooltip = $("#tooltip");
var bounds = map.getBounds();
var icon = marker.getIcon();
var top = -999;
var left = -999;
tooltip.html("<div class='content'>"+infoHTML+"</div>");
if(bounds.contains(marker.getPoint())) {
var mapPx = $(map.getContainer()).position();
var pinPx = map.fromLatLngToContainerPixel(marker.getPoint());
top = (pinPx.y + mapPx.top) - (icon.iconAnchor.y + tooltip.height());
left = (pinPx.x + mapPx.left) - (icon.iconAnchor.x + tooltip.width());
if (left < 10) { left = 10 }; // keep it on the page
}
/* Ensure the tooltip doesn't obscure the pin */
tooltip.css({ top: top - 22, left: left }).fadeIn();
}
function getBusinessIcon(business) {
var icon = null;
$.each(business.categories, function() {
icon = categoryIcons[this.category_filter];
if (icon)
return false;
});
return icon || defaultIcon;
}
function map_message(message,klass)
{
$("#map_message p").text(message);
$("#map_message").get(0).className = klass;
}
function yelp() {
var bounds = map.getBounds();
var tl_lat = bounds.getSouthWest().lat();
var tl_lng = bounds.getSouthWest().lng();
var br_lat = bounds.getNorthEast().lat();
var br_lng = bounds.getNorthEast().lng();
var URI = "http://api.yelp.com/business_review_search?" +
"&num_biz_requested=10&callback=?" +
"&category=" + categoriesFilterString() +
"&tl_lat=" + tl_lat +
"&tl_long=" + tl_lng +
"&br_lat=" + br_lat +
"&br_long=" + br_lng +
"&ywsid=" + "kIXgBO4ryiAN3oPxskwNmg";
var ajaxSuccess = function(data)
{
if(data.message.text == "OK")
{
map_message("Om nom nom nom...", "happy");
map.clearOverlays();
if (data.businesses.length > 0)
{
for(var i = 0; i < data.businesses.length; i++)
{
var business = data.businesses[i];
var position = new GLatLng(business.latitude, business.longitude);
createMapMarker(business, position, i);
}
}
else
{
map_message("No noms... qq.", "mad");
}
}
else
{
var message = data.message.text;
if (message == "Area too large")
{
map_message("Zoom moar!", "content");
}
else
{
map_message("Error: " + message, "mad");
}
}
};
var ajaxError = function(XMLHttpRequest, textStatus, errorThrown)
{
};
$.ajax({
type: "GET",
url: URI,
cache: false,
contentType: "application/json",
dataType: "json",
error: ajaxError,
success: ajaxSuccess
});
}
function categoriesFilterString() {
var inputs = $("#categories li input");
var filters = [];
inputs.each(function() {
if (this.checked) {
filters.push(this.value);
}
});
if (filters.length > 0 && filters.length < inputs.length) {
return filters.join("+");
} else {
return "restaurants";
}
}
function iCanHazLocation(query) {
geocoder.getLatLng(query, function(point) {
if (!point) {
map_message("A Google says wut?", "mad");
} else {
map.setCenter(point, 12);
}
});
}
function howManyNoms()
{
return $("#sum_noms").children("li").length;
}
function has_omnoms()
{
$("#omnom").show();
$("#empty_omnom").hide();
}
function empty_omnom()
{
$("#omnom").hide();
$("#empty_omnom").show();
}
function findNom(name,details)
{
var found_existing_nom = false;
var list = $("#sum_noms li").each( function()
{
var nom_name = $(this).children(".name").text();
var nom_details = $(this).children(".details").html();
if(nom_name == name && nom_details == details )
{
found_existing_nom = true;
}
}
);
return found_existing_nom;
}
function addNom(omnom) {
var list = $("#sum_noms");
if ( howManyNoms() < MAX_NOMS) {
if(findNom(omnom.name, omnom.details))
{
$.flash.warn("Already nomz there", "dupliCAT");
return;
}
var nom_template = $.template('<li><div class="name">${name}</div><div class="details">${details}</div><a href="#" class="remove">X</a></li>');
var nom_item = nom_template.apply(omnom);
list.append(nom_item).children(':last').hide().slideDown();
$("#sum_noms .remove").click(removeNom);
} else {
$.flash.warn("Too much noms.", "My belly hurts")
};
has_omnoms();
$("#new_nom")[0].reset();
}
function removeNom() {
var nom_count = howManyNoms();
$(this).parent().blindUp().remove();
if( nom_count == 1 )
{
empty_omnom();
}
return false;
}
function createOmnom() {
var nomMapper = function()
{
var nom = {
name: $(this).children(".name").text(),
details: $(this).children(".details").html()
};
return nom;
};
var pplMapper = function()
{
return this.value ? { email: this.value } : null
};
var ajaxSuccess = function(response)
{
try { top.location.href = response.redirect_to; } catch(e) {}
};
var ajaxError = function(XMLHttpRequest, textStatus, errorThrown)
{
try
{
var json = JSON.parse( XMLHttpRequest.responseText );
var first_error = json[0][1];
$.flash.failure(first_error, "Eek!");
}
catch(e)
{
}
return false;
};
var ajaxData = JSON.stringify({
omnom: {
pplz_attributes: $.makeArray($("#sum_pplz input:text[name=ppl_emailz]").map(pplMapper)),
noms_attributes: $.makeArray($("#sum_noms li").map(nomMapper)),
creator_email: $("#creator_email").val()
}
});
$.ajax({
type: "POST",
url: "/omnom",
cache: false,
contentType: "application/json",
dataType: "json",
data: ajaxData,
error: ajaxError,
success: ajaxSuccess
});
return false;
}
function scewie6()
{
var IE6 = (navigator.userAgent.indexOf("MSIE 6")>=0) ? true : false;
if(IE6)
{
$(function()
{
$("#oh_hai").hide();
$("#header").hide();
$("body").css( { "background" : "none"} );
$("<div id='screwie6'><img src='/images/no-ie6.png'/></div>").appendTo('body');
$("#screwie6").css({"width":"213px","margin":"0 auto"});
});
}
}
$(document).ready(function() {
scewie6();
if ($("#oh_hai").length > 0) {
initializeGoogleMaps();
$("#location_form").submit(function() {
iCanHazLocation($("#location_text").get(0).value);
return false;
});
$("#categories li input").change(function() {
yelp();
});
$("#tooltip").hide();
$("#location_text").click( function()
{
if( this.value == DEFAULT_LOCATION )
{
this.value = "";
}
}
);
$("#new_nom").submit(function() {
var name = $(this.new_nom_name).val();
var details = $(this.new_nom_details).val();
if( !name )
{
$.flash.warn("Must tell me the name of the location", "Need moar info")
return false;
}
addNom( {
name: name,
details: details
} );
return false;
});
$("#sum_pplz").submit(function() {
createOmnom();
return false;
});
$("#empty_omnom").show();
$("#omnom").hide();
$("label.inside").inFieldLabels();
$("#sum_noms .remove").click(removeNom);
}
}); | Missed one of the jRails/prototype -> jQuery fixes. | public/javascripts/application.js | Missed one of the jRails/prototype -> jQuery fixes. | <ide><path>ublic/javascripts/application.js
<ide> function removeNom() {
<ide> var nom_count = howManyNoms();
<ide>
<del> $(this).parent().blindUp().remove();
<add> $(this).parent().slideUp().remove();
<ide>
<ide> if( nom_count == 1 )
<ide> { |
|
JavaScript | mit | 33cbf3c7fe67bd60a9fc1044e01f47ef94566233 | 0 | klpdotorg/dubdubdub,klpdotorg/dubdubdub,klpdotorg/dubdubdub,klpdotorg/dubdubdub | var KLPRouter = function(routes) {
this.routes = routes || {};
var that = this;
var getQueryParams = function(hash) {
var queryParams = {};
var hashSplit = hash.split("?");
if (hashSplit.length > 1) {
hash = hashSplit[0];
var queryParamsString = hashSplit[1];
var queryParamsSplit = queryParamsString.split("&");
for (var i = 0; i < queryParamsSplit.length; i++) {
var temp = queryParamsSplit[i].split("=");
if (temp.length == 2){
queryParams[temp[0]] = temp[1];
}
};
}
return queryParams;
};
var getQueryString = function(queryObj) {
var paramsArray = [];
for (var param in queryObj) {
if (queryObj.hasOwnProperty(param)) {
var s = param + '=' + queryObj[param];
paramsArray.push(s);
}
}
return paramsArray.join('&');
};
this.hashChanged = function() {
var hash = window.location.hash.substr(1, window.location.hash.length-1);
var queryParams = getQueryParams(hash);
for (pattern in routes) {
var regex = new RegExp(pattern, "i");
var matches = regex.exec(hash);
if (matches !== null && matches.length > 0) {
routes[pattern](matches, queryParams);
}
}
that.events.trigger("hashchange", [hash.split("?")[0], queryParams]);
};
this.setHash = function(url, queryParams, options) {
/*
url <string>: new url base fragment
queryParams <obj>: object of query params to change
options: obj
- trigger <boolean> whether to trigger hashchange event
- replace <boolean> whether to 'replace' URL without
creating event in history
replace can be set to true only if trigger is false.
*/
var defaults = {
'trigger': true,
'replace': false
};
var opts = $.extend(defaults, options);
var hash = window.location.hash.substr(1, window.location.hash.length-1);
var hashSplit = hash.split("?");
if (!url) {
url = hashSplit[0];
}
var currentParams = getQueryParams(hash);
var newParams = $.extend(currentParams, queryParams);
var queryString = getQueryString(newParams);
if (queryString !== '') {
var newHash = url + '?' + queryString;
} else {
var newHash = url;
}
if (opts.trigger) {
location.hash = newHash;
} else if (!opts.replace) {
history.pushState(null, null, '#' + newHash);
} else {
history.replaceState(null, null, '#' + newHash);
}
};
this.start = function() {
if (window.location.hash !== "") {
this.hashChanged();
}
};
this.init = function() {
window.addEventListener("hashchange", this.hashChanged, false);
that.events = $('<div />');
};
};
| assets/static/js/lib/klprouter.js | var KLPRouter = function(routes) {
this.routes = routes || {};
var that = this;
var getQueryParams = function(hash) {
var queryParams = {};
var hashSplit = hash.split("?");
if (hashSplit.length > 1) {
hash = hashSplit[0];
var queryParamsString = hashSplit[1];
var queryParamsSplit = queryParamsString.split("&");
for (var i = 0; i < queryParamsSplit.length; i++) {
var temp = queryParamsSplit[i].split("=");
if (temp.length == 2){
queryParams[temp[0]] = temp[1];
}
};
}
return queryParams;
};
var getQueryString = function(queryObj) {
var paramsArray = [];
for (var param in queryObj) {
if (queryObj.hasOwnProperty(param)) {
var s = param + '=' + queryObj[param];
paramsArray.push(s);
}
}
return paramsArray.join('&');
};
this.hashChanged = function() {
var hash = window.location.hash.substr(1, window.location.hash.length-1);
var queryParams = getQueryParams(hash);
for (pattern in routes) {
var regex = new RegExp(pattern, "i");
var matches = regex.exec(hash);
if (matches !== null && matches.length > 0) {
routes[pattern](matches, queryParams);
}
}
that.events.trigger("hashchanged", [hash.split("?")[0], queryParams]);
};
this.setHash = function(url, queryParams, options) {
/*
url <string>: new url base fragment
queryParams <obj>: object of query params to change
options: obj
- trigger <boolean> whether to trigger hashchange event
- replace <boolean> whether to 'replace' URL without
creating event in history
replace can be set to true only if trigger is false.
*/
var defaults = {
'trigger': true,
'replace': false
};
var opts = $.extend(defaults, options);
var hash = window.location.hash.substr(1, window.location.hash.length-1);
var hashSplit = hash.split("?");
if (!url) {
url = hashSplit[0];
}
var currentParams = getQueryParams(hash);
var newParams = $.extend(currentParams, queryParams);
var newHash = url + '?' + getQueryString(newParams);
if (opts.trigger) {
location.hash = newHash;
} else if (!opts.replace) {
history.pushState(null, null, '#' + newHash);
} else {
history.replaceState(null, null, '#' + newHash);
}
};
this.start = function() {
if (window.location.hash !== "") {
this.hashChanged();
}
};
this.init = function() {
window.addEventListener("hashchange", this.hashChanged, false);
that.events = $('<div />');
};
};
| change event name, fix bug of ? if query params is empty
| assets/static/js/lib/klprouter.js | change event name, fix bug of ? if query params is empty | <ide><path>ssets/static/js/lib/klprouter.js
<ide> routes[pattern](matches, queryParams);
<ide> }
<ide> }
<del> that.events.trigger("hashchanged", [hash.split("?")[0], queryParams]);
<add> that.events.trigger("hashchange", [hash.split("?")[0], queryParams]);
<ide> };
<ide>
<ide> this.setHash = function(url, queryParams, options) {
<ide> }
<ide> var currentParams = getQueryParams(hash);
<ide> var newParams = $.extend(currentParams, queryParams);
<del> var newHash = url + '?' + getQueryString(newParams);
<add> var queryString = getQueryString(newParams);
<add> if (queryString !== '') {
<add> var newHash = url + '?' + queryString;
<add> } else {
<add> var newHash = url;
<add> }
<add>
<ide> if (opts.trigger) {
<ide> location.hash = newHash;
<ide> } else if (!opts.replace) { |
|
JavaScript | mit | 58002ff1228db67f03cf56e3fe90aa174be9a5f1 | 0 | drakenm/js-test-code,drakenm/js-test-code | "use strict";
// chess board
//var str = "", rowFlag = true, size = 8;
//for (var i = 1; i <= size; i++) {
// for (var j = 1; j <= size; j++) {
// if (j % 2 === 0) {
// str += (rowFlag ? "#" : " ");
// } else {
// str += (rowFlag ? " " : "#");
// }
// }
// str += "\n";
// rowFlag = !rowFlag;
//}
//console.log(str);
/* CH3 FXNS */
// find minimum of 2 values
//function getMin(x, y) {
// if (x < y) {
// var min = x;
// } else {
// min = y;
// }
// return min;
//}
//console.log(getMin(35, 24));
// evenness
// recursive fxns must have a return value in all branches or will return undefined...
//var isEven = function evenness(x) {
// if (x < 0 ) {
// x = -1 * x;
// }
// if (x > 1) {
// return isEven(x - 2);
// } else if (x < 1) {
// return true;
// } else {
// return false;
// }
//};
//console.log(isEven(2532));
// bean counting
//var charCount = function beanCount(str, char) {
// var cnt = 0;
// for (var i = 0; i < str.length; i++) {
// if (str[i] === char) {
// cnt += 1;
// }
// }
// return cnt;
//};
//console.log(charCount("BBC", "B"));
//console.log(charCount("kakkerlak", "k"));
/* CH4 DATA */
// range fxn
//var range = function rangeFxn(start, end, step) {
// step = step || 1;
// var arr = [];
// if (start < end && step < 0) return undefined;
// for (var i = start; ((step > 0) ? i <= end : i >= end); i += step) {
// arr.push(i);
// }
// return arr;
//};
//console.log("1-10: ",range(1,10));
//console.log("5-2 neg step: ",range(5,2,-1));
//console.log("1-10, 2 step: ",range(1,10,2));
// sum a array of nums
//var sum = function sumFxn(arr) {
// var sum = 0;
// for (var i = 0; i < arr.length; i++) {
// sum += arr[i];
// }
// return sum;
//};
//console.log("sum of range 1-10: ",sum(range(1,10)));
// reverse array
//var alpha = "abcdefghijklmnopqrstuvwxyz";
//var myArr = alpha.split("");
//var myNArr = alpha.split("");
//console.log("arrays: ",myArr,"\n",myNArr);
//function reverseIp(arr) {
// var lenHlf = Math.floor(arr.length / 2), len = arr.length;
// for (var i = 0; i < lenHlf; i++) {
// var tmp = arr[i];
// arr[i] = arr[arr.length - 1 - i];
// arr[arr.length - 1 - i] = tmp;
// }
//}
//
//// return new array that is reverse of the array passed
//var reverse = function reverseFxn(arr) {
// var newArr = [], len = arr.length;
// for (var i = 0; i < len; i++) {
// newArr[i] = arr.pop();
// }
// return newArr;
//};
//
//reverseIp(myNArr);
//console.log("new reversed arr: ",reverse(myArr));
//console.log("old myNArr reversed in place: ",myNArr);
// lists
var arrayToList = function makeArrayFromList(arr) {
var list = {}, inArr = arr;
for (var i = inArr.length; i > 0; i--) {
list = {value: inArr.pop(), rest: (Object.keys(list).length === 0 && list.constructor === Object ? null : list) };
}
return list;
}
console.log("LIST: ",arrayToList([10,20]));
var listToArray = function makeListFromArray(listObj) {
var arr = [], inObj = listObj;
while ( (inObj.rest !== null ? (Object.keys(inObj.rest).length !== 0 && inObj.rest.constructor === Object) : false) ) {
arr.push(inObj.value);
inObj = inObj.rest;
}
arr.push(inObj.value);
return arr;
}
console.log("ARRAY: ",listToArray(arrayToList([10,20,30])));
var prependToList = function prependElement2List(value, list) {
return {value: value, rest: list};
}
console.log(prependToList(10, prependToList(20, null)));
var getListValue = function nthValueOfList(list, index) {
var defInd = index || 0; // return first value
if (defInd > 0 && list.rest !== null) {
return getListValue(list.rest, defInd - 1);
} else if (defInd === 0) {
return list.value;
} else {
return undefined;
}
}
console.log("VALUE: ",getListValue(arrayToList([10,20,30]),2)) | sb1.js | "use strict";
// chess board
//var str = "", rowFlag = true, size = 8;
//for (var i = 1; i <= size; i++) {
// for (var j = 1; j <= size; j++) {
// if (j % 2 === 0) {
// str += (rowFlag ? "#" : " ");
// } else {
// str += (rowFlag ? " " : "#");
// }
// }
// str += "\n";
// rowFlag = !rowFlag;
//}
//console.log(str);
/* CH3 FXNS */
// find minimum of 2 values
//function getMin(x, y) {
// if (x < y) {
// var min = x;
// } else {
// min = y;
// }
// return min;
//}
//console.log(getMin(35, 24));
// evenness
// recursive fxns must have a return value in all branches or will return undefined...
//var isEven = function evenness(x) {
// if (x < 0 ) {
// x = -1 * x;
// }
// if (x > 1) {
// return isEven(x - 2);
// } else if (x < 1) {
// return true;
// } else {
// return false;
// }
//};
//console.log(isEven(2532));
// bean counting
//var charCount = function beanCount(str, char) {
// var cnt = 0;
// for (var i = 0; i < str.length; i++) {
// if (str[i] === char) {
// cnt += 1;
// }
// }
// return cnt;
//};
//console.log(charCount("BBC", "B"));
//console.log(charCount("kakkerlak", "k"));
/* CH4 DATA */
// range fxn
//var range = function rangeFxn(start, end, step) {
// step = step || 1;
// var arr = [];
// if (start < end && step < 0) return undefined;
// for (var i = start; ((step > 0) ? i <= end : i >= end); i += step) {
// arr.push(i);
// }
// return arr;
//};
//console.log("1-10: ",range(1,10));
//console.log("5-2 neg step: ",range(5,2,-1));
//console.log("1-10, 2 step: ",range(1,10,2));
// sum a array of nums
//var sum = function sumFxn(arr) {
// var sum = 0;
// for (var i = 0; i < arr.length; i++) {
// sum += arr[i];
// }
// return sum;
//};
//console.log("sum of range 1-10: ",sum(range(1,10)));
// reverse array
//var alpha = "abcdefghijklmnopqrstuvwxyz";
//var myArr = alpha.split("");
//var myNArr = alpha.split("");
//console.log("arrays: ",myArr,"\n",myNArr);
//function reverseIp(arr) {
// var lenHlf = Math.floor(arr.length / 2), len = arr.length;
// for (var i = 0; i < lenHlf; i++) {
// var tmp = arr[i];
// arr[i] = arr[arr.length - 1 - i];
// arr[arr.length - 1 - i] = tmp;
// }
//}
//
//// return new array that is reverse of the array passed
//var reverse = function reverseFxn(arr) {
// var newArr = [], len = arr.length;
// for (var i = 0; i < len; i++) {
// newArr[i] = arr.pop();
// }
// return newArr;
//};
//
//reverseIp(myNArr);
//console.log("new reversed arr: ",reverse(myArr));
//console.log("old myNArr reversed in place: ",myNArr);
// lists
var arrayToList = function makeArrayFromList(arr) {
var list = {}, inArr = arr;
for (var i = inArr.length; i > 0; i--) {
list = {value: inArr.pop(), rest: (Object.keys(list).length === 0 && list.constructor === Object ? null : list) };
}
return list;
}
console.log("LIST: ",arrayToList([10,20]));
var listToArray = function makeListFromArray(listObj) {
var arr = [], inObj = listObj;
while ( (inObj.rest !== null ? (Object.keys(inObj.rest).length !== 0 && inObj.rest.constructor === Object) : false) ) {
arr.push(inObj.value);
inObj = inObj.rest;
}
arr.push(inObj.value);
return arr;
}
console.log("ARRAY: ",listToArray(arrayToList([10,20,30])));
var prependToList = function prependElement2List(value, list) {
return {value: value, rest: list};
}
console.log(prependToList(10, prependToList(20, null)));
var getListValue = function nthValueOfList(list, index) {
var defaultIndex = index || 0; // return first value
if (index > 0 && list.rest !== null) {
return getListValue(list.rest, index - 1);
} else if (list.rest !== null) {
return list.value;
} else {
return undefined;
}
}
console.log(getListValue(arrayToList([10,20,30]),0)) | fixed getListValue to return the proper value; added default index
| sb1.js | fixed getListValue to return the proper value; added default index | <ide><path>b1.js
<ide> console.log(prependToList(10, prependToList(20, null)));
<ide>
<ide> var getListValue = function nthValueOfList(list, index) {
<del> var defaultIndex = index || 0; // return first value
<del> if (index > 0 && list.rest !== null) {
<del> return getListValue(list.rest, index - 1);
<del> } else if (list.rest !== null) {
<add> var defInd = index || 0; // return first value
<add> if (defInd > 0 && list.rest !== null) {
<add> return getListValue(list.rest, defInd - 1);
<add> } else if (defInd === 0) {
<ide> return list.value;
<ide> } else {
<ide> return undefined;
<ide> }
<ide> }
<del>console.log(getListValue(arrayToList([10,20,30]),0))
<add>console.log("VALUE: ",getListValue(arrayToList([10,20,30]),2)) |
|
Java | mit | error: pathspec 'hackerrank/src/week_of_code_30/RangeModularQueries.java' did not match any file(s) known to git
| c21cbe05430bdfd4372190b832a4c6ae2521ff76 | 1 | scaffeinate/crack-the-code | package week_of_code_30;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class RangeModularQueries {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.nextInt();
int q = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
while (q-- > 0) {
int count = 0;
int left = in.nextInt();
int right = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
for (int i = left; i <= right; i++) {
if(arr[i] % x == y) {
count++;
}
}
writer.write(String.valueOf(count));
writer.newLine();
}
writer.flush();
in.close();
}
}
| hackerrank/src/week_of_code_30/RangeModularQueries.java | Added solution for RangeModularQueries. It’s probably gonna TLE when additional test cases run :unamused:
| hackerrank/src/week_of_code_30/RangeModularQueries.java | Added solution for RangeModularQueries. It’s probably gonna TLE when additional test cases run :unamused: | <ide><path>ackerrank/src/week_of_code_30/RangeModularQueries.java
<add>package week_of_code_30;
<add>
<add>import java.io.BufferedWriter;
<add>import java.io.IOException;
<add>import java.io.OutputStreamWriter;
<add>import java.util.Scanner;
<add>
<add>public class RangeModularQueries {
<add> public static void main(String[] args) throws IOException {
<add> Scanner in = new Scanner(System.in);
<add> BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
<add> int n = in.nextInt();
<add> int q = in.nextInt();
<add> int[] arr = new int[n];
<add>
<add> for (int i = 0; i < n; i++) {
<add> arr[i] = in.nextInt();
<add> }
<add>
<add> while (q-- > 0) {
<add> int count = 0;
<add> int left = in.nextInt();
<add> int right = in.nextInt();
<add> int x = in.nextInt();
<add> int y = in.nextInt();
<add>
<add> for (int i = left; i <= right; i++) {
<add> if(arr[i] % x == y) {
<add> count++;
<add> }
<add> }
<add>
<add> writer.write(String.valueOf(count));
<add> writer.newLine();
<add> }
<add>
<add> writer.flush();
<add> in.close();
<add> }
<add>} |
|
Java | apache-2.0 | 5e3956d517e21d7901348b16605f8f5d0c60c698 | 0 | jbb-project/jbb,jbb-project/jbb | /*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.security.rest.lockout;
import org.jbb.lib.restful.domain.ErrorInfoCodes;
import org.jbb.lib.restful.error.ErrorResponse;
import org.jbb.members.api.base.Member;
import org.jbb.members.api.base.MemberNotFoundException;
import org.jbb.members.api.base.MemberService;
import org.jbb.security.api.lockout.MemberLock;
import org.jbb.security.api.lockout.MemberLockoutService;
import org.jbb.security.rest.lockout.exception.MemberLockNotFound;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import static org.jbb.lib.restful.RestAuthorize.IS_AN_ADMINISTRATOR;
import static org.jbb.lib.restful.RestConstants.API_V1;
import static org.jbb.lib.restful.domain.ErrorInfo.ACTIVE_MEMBER_LOCK_NOT_FOUND;
import static org.jbb.lib.restful.domain.ErrorInfo.FORBIDDEN;
import static org.jbb.lib.restful.domain.ErrorInfo.MEMBER_NOT_FOUND;
import static org.jbb.lib.restful.domain.ErrorInfo.UNAUTHORIZED;
import static org.jbb.security.rest.SecurityRestConstants.ACTIVE_LOCK;
import static org.jbb.security.rest.SecurityRestConstants.MEMBERS;
import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID;
import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID_VAR;
@RestController
@RequiredArgsConstructor
@PreAuthorize(IS_AN_ADMINISTRATOR)
@Api(tags = API_V1 + MEMBERS + MEMBER_ID + ACTIVE_LOCK)
@RequestMapping(value = API_V1 + MEMBERS + MEMBER_ID
+ ACTIVE_LOCK, produces = MediaType.APPLICATION_JSON_VALUE)
public class ActiveMemberLockResource {
private final MemberService memberService;
private final MemberLockoutService memberLockoutService;
private final MemberLockTranslator translator;
@GetMapping
@ErrorInfoCodes({MEMBER_NOT_FOUND, ACTIVE_MEMBER_LOCK_NOT_FOUND, UNAUTHORIZED, FORBIDDEN})
@ApiOperation("Gets active lock for given member")
public MemberLockDto activeLockGet(@PathVariable(MEMBER_ID_VAR) Long memberId)
throws MemberNotFoundException {
MemberLock lock = getMemberLock(memberId);
return translator.toDto(lock);
}
@DeleteMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
@ErrorInfoCodes({MEMBER_NOT_FOUND, ACTIVE_MEMBER_LOCK_NOT_FOUND, UNAUTHORIZED, FORBIDDEN})
@ApiOperation("Deactivates active lock for given member")
public void activeLockDelete(@PathVariable(MEMBER_ID_VAR) Long memberId)
throws MemberNotFoundException {
getMemberLock(memberId);
memberLockoutService.releaseMemberLock(memberId);
}
private MemberLock getMemberLock(Long memberId) throws MemberNotFoundException {
Member member = memberService.getMemberWithIdChecked(memberId);
return memberLockoutService.getMemberActiveLock(member.getId())
.orElseThrow(MemberLockNotFound::new);
}
@ExceptionHandler(MemberLockNotFound.class)
ResponseEntity<ErrorResponse> handle(MemberLockNotFound ex) {
return ErrorResponse.getErrorResponseEntity(ACTIVE_MEMBER_LOCK_NOT_FOUND);
}
}
| domain-rest/jbb-security-rest/src/main/java/org/jbb/security/rest/lockout/ActiveMemberLockResource.java | /*
* Copyright (C) 2018 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.security.rest.lockout;
import static org.jbb.lib.restful.RestAuthorize.IS_AN_ADMINISTRATOR;
import static org.jbb.lib.restful.RestConstants.API_V1;
import static org.jbb.lib.restful.domain.ErrorInfo.ACTIVE_MEMBER_LOCK_NOT_FOUND;
import static org.jbb.lib.restful.domain.ErrorInfo.FORBIDDEN;
import static org.jbb.lib.restful.domain.ErrorInfo.MEMBER_NOT_FOUND;
import static org.jbb.lib.restful.domain.ErrorInfo.UNAUTHORIZED;
import static org.jbb.security.rest.SecurityRestConstants.ACTIVE_LOCK;
import static org.jbb.security.rest.SecurityRestConstants.MEMBERS;
import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID;
import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID_VAR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.jbb.lib.restful.domain.ErrorInfoCodes;
import org.jbb.lib.restful.error.ErrorResponse;
import org.jbb.members.api.base.Member;
import org.jbb.members.api.base.MemberNotFoundException;
import org.jbb.members.api.base.MemberService;
import org.jbb.security.api.lockout.MemberLock;
import org.jbb.security.api.lockout.MemberLockoutService;
import org.jbb.security.rest.lockout.exception.MemberLockNotFound;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@PreAuthorize(IS_AN_ADMINISTRATOR)
@Api(tags = API_V1 + MEMBERS + MEMBER_ID + ACTIVE_LOCK)
@RequestMapping(value = API_V1 + MEMBERS + MEMBER_ID
+ ACTIVE_LOCK, produces = MediaType.APPLICATION_JSON_VALUE)
public class ActiveMemberLockResource {
private final MemberService memberService;
private final MemberLockoutService memberLockoutService;
private final MemberLockTranslator translator;
@GetMapping
@ErrorInfoCodes({MEMBER_NOT_FOUND, ACTIVE_MEMBER_LOCK_NOT_FOUND, UNAUTHORIZED, FORBIDDEN})
@ApiOperation("Gets active lock for given member")
public MemberLockDto activeLockGet(@PathVariable(MEMBER_ID_VAR) Long memberId)
throws MemberNotFoundException {
MemberLock lock = getMemberLock(memberId);
return translator.toDto(lock);
}
@DeleteMapping
@ErrorInfoCodes({MEMBER_NOT_FOUND, ACTIVE_MEMBER_LOCK_NOT_FOUND, UNAUTHORIZED, FORBIDDEN})
@ApiOperation("Deactivates active lock for given member")
public void activeLockDelete(@PathVariable(MEMBER_ID_VAR) Long memberId)
throws MemberNotFoundException {
getMemberLock(memberId);
memberLockoutService.releaseMemberLock(memberId);
}
private MemberLock getMemberLock(Long memberId) throws MemberNotFoundException {
Member member = memberService.getMemberWithIdChecked(memberId);
return memberLockoutService.getMemberActiveLock(member.getId())
.orElseThrow(MemberLockNotFound::new);
}
@ExceptionHandler(MemberLockNotFound.class)
ResponseEntity<ErrorResponse> handle(MemberLockNotFound ex) {
return ErrorResponse.getErrorResponseEntity(ACTIVE_MEMBER_LOCK_NOT_FOUND);
}
}
| Add missing response http status no content for delete endpoint
| domain-rest/jbb-security-rest/src/main/java/org/jbb/security/rest/lockout/ActiveMemberLockResource.java | Add missing response http status no content for delete endpoint | <ide><path>omain-rest/jbb-security-rest/src/main/java/org/jbb/security/rest/lockout/ActiveMemberLockResource.java
<ide>
<ide> package org.jbb.security.rest.lockout;
<ide>
<add>import org.jbb.lib.restful.domain.ErrorInfoCodes;
<add>import org.jbb.lib.restful.error.ErrorResponse;
<add>import org.jbb.members.api.base.Member;
<add>import org.jbb.members.api.base.MemberNotFoundException;
<add>import org.jbb.members.api.base.MemberService;
<add>import org.jbb.security.api.lockout.MemberLock;
<add>import org.jbb.security.api.lockout.MemberLockoutService;
<add>import org.jbb.security.rest.lockout.exception.MemberLockNotFound;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.http.MediaType;
<add>import org.springframework.http.ResponseEntity;
<add>import org.springframework.security.access.prepost.PreAuthorize;
<add>import org.springframework.web.bind.annotation.DeleteMapping;
<add>import org.springframework.web.bind.annotation.ExceptionHandler;
<add>import org.springframework.web.bind.annotation.GetMapping;
<add>import org.springframework.web.bind.annotation.PathVariable;
<add>import org.springframework.web.bind.annotation.RequestMapping;
<add>import org.springframework.web.bind.annotation.ResponseStatus;
<add>import org.springframework.web.bind.annotation.RestController;
<add>
<add>import io.swagger.annotations.Api;
<add>import io.swagger.annotations.ApiOperation;
<add>import lombok.RequiredArgsConstructor;
<add>
<ide> import static org.jbb.lib.restful.RestAuthorize.IS_AN_ADMINISTRATOR;
<ide> import static org.jbb.lib.restful.RestConstants.API_V1;
<ide> import static org.jbb.lib.restful.domain.ErrorInfo.ACTIVE_MEMBER_LOCK_NOT_FOUND;
<ide> import static org.jbb.security.rest.SecurityRestConstants.MEMBERS;
<ide> import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID;
<ide> import static org.jbb.security.rest.SecurityRestConstants.MEMBER_ID_VAR;
<del>
<del>import io.swagger.annotations.Api;
<del>import io.swagger.annotations.ApiOperation;
<del>import lombok.RequiredArgsConstructor;
<del>import org.jbb.lib.restful.domain.ErrorInfoCodes;
<del>import org.jbb.lib.restful.error.ErrorResponse;
<del>import org.jbb.members.api.base.Member;
<del>import org.jbb.members.api.base.MemberNotFoundException;
<del>import org.jbb.members.api.base.MemberService;
<del>import org.jbb.security.api.lockout.MemberLock;
<del>import org.jbb.security.api.lockout.MemberLockoutService;
<del>import org.jbb.security.rest.lockout.exception.MemberLockNotFound;
<del>import org.springframework.http.MediaType;
<del>import org.springframework.http.ResponseEntity;
<del>import org.springframework.security.access.prepost.PreAuthorize;
<del>import org.springframework.web.bind.annotation.DeleteMapping;
<del>import org.springframework.web.bind.annotation.ExceptionHandler;
<del>import org.springframework.web.bind.annotation.GetMapping;
<del>import org.springframework.web.bind.annotation.PathVariable;
<del>import org.springframework.web.bind.annotation.RequestMapping;
<del>import org.springframework.web.bind.annotation.RestController;
<ide>
<ide> @RestController
<ide> @RequiredArgsConstructor
<ide> }
<ide>
<ide> @DeleteMapping
<add> @ResponseStatus(HttpStatus.NO_CONTENT)
<ide> @ErrorInfoCodes({MEMBER_NOT_FOUND, ACTIVE_MEMBER_LOCK_NOT_FOUND, UNAUTHORIZED, FORBIDDEN})
<ide> @ApiOperation("Deactivates active lock for given member")
<ide> public void activeLockDelete(@PathVariable(MEMBER_ID_VAR) Long memberId) |
|
JavaScript | mit | 4d0fff7c04fb5f221675ac7ea0baff56b462e0ad | 0 | sindresorhus/refined-github,sindresorhus/refined-github,busches/refined-github,busches/refined-github | import {h} from 'dom-chef';
import select from 'select-dom';
import delegate from 'delegate';
import * as icons from '../libs/icons';
import observeEl from '../libs/simplified-element-observer';
function addButton() {
const filesHeader = select('.commit-tease .float-right');
if (!filesHeader || select.exists('.rgh-toggle-files')) {
return;
}
filesHeader.append(
<button
class="btn-octicon p-1 pr-2 rgh-toggle-files"
aria-label="Toggle files section"
aria-expanded="true">
{icons.chevronDown()}
</button>
);
}
export default function () {
const repoContent = select('.repository-content');
observeEl(repoContent, addButton);
delegate('.rgh-toggle-files', 'click', ({delegateTarget}) => {
delegateTarget.setAttribute('aria-expanded', !repoContent.classList.toggle('rgh-files-hidden'));
});
}
| source/features/add-toggle-files-button.js | import {h} from 'dom-chef';
import select from 'select-dom';
import delegate from 'delegate';
import * as icons from '../libs/icons';
import observeEl from '../libs/simplified-element-observer';
function addButton() {
const filesHeader = select('.commit-tease .float-right');
if (!filesHeader) {
return;
}
filesHeader.append(
<button
class="btn-octicon p-1 pr-2 rgh-toggle-files"
aria-label="Toggle files section"
aria-expanded="true">
{icons.chevronDown()}
</button>
);
}
export default function () {
const repoContent = select('.repository-content');
observeEl(repoContent, addButton);
delegate('.rgh-toggle-files', 'click', ({delegateTarget}) => {
delegateTarget.setAttribute('aria-expanded', !repoContent.classList.toggle('rgh-files-hidden'));
});
}
| Fix Toggle Files button /2
| source/features/add-toggle-files-button.js | Fix Toggle Files button /2 | <ide><path>ource/features/add-toggle-files-button.js
<ide>
<ide> function addButton() {
<ide> const filesHeader = select('.commit-tease .float-right');
<del> if (!filesHeader) {
<add> if (!filesHeader || select.exists('.rgh-toggle-files')) {
<ide> return;
<ide> }
<ide> filesHeader.append( |
|
Java | bsd-3-clause | ea03132237676cc08decb5238b73cb5d7a04e0f3 | 0 | yungsters/rain-workload-toolkit,yungsters/rain-workload-toolkit,sguazt/rain-workload-toolkit,yungsters/rain-workload-toolkit,sguazt/rain-workload-toolkit,sguazt/rain-workload-toolkit | /*
* Copyright (c) 2010, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the University of California, Berkeley
* 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.
*
* Author: Marco Guazzone ([email protected]), 2013.
*/
package radlab.rain.workload.rubis.util;
import java.util.Arrays;
import java.util.Random;
/**
* Generate random numbers according to the given probability table.
*
* @author Marco Guazzone ([email protected])
*/
public final class DiscreteDistribution
{
private double[] _cdf;
public DiscreteDistribution(double[] probs)
{
if (probs.length > 0)
{
this._cdf = new double[probs.length];
// Compute CDF
double cumProb = probs[0];
this._cdf[0] = probs[0];
for (int i = 1; i < probs.length; ++i)
{
//this._cdf[i] = this._cdf[i-1]+probs[i];
this._cdf[i] = cumProb;
cumProb += probs[i];
}
// Normalize
for (int i = 0; i < probs.length; ++i)
{
this._cdf[i] /= cumProb;
}
}
}
public int nextInt(Random rng)
{
double p = rng.nextDouble();
// for (int x = 0; x < this._cdf.length; ++x)
// {
// if (p > this._cdf[x])
// {
// return x;
// }
// }
// return this._cdf.length-1;
int x = Arrays.binarySearch(this._cdf, p);
return (x >= 0 ? x : -x);
}
}
| src/radlab/rain/workload/rubis/util/DiscreteDistribution.java | /*
* Copyright (c) 2010, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the University of California, Berkeley
* 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.
*
* Author: Marco Guazzone ([email protected]), 2013.
*/
package radlab.rain.workload.rubis.util;
import java.util.Arrays;
import java.util.Random;
/**
* Generate random numbers according to the given probability table.
*
* @author Marco Guazzone ([email protected])
*/
public final class DiscreteDistribution
{
private double[] _cdf;
public DiscreteDistribution(double[] probs)
{
if (probs.length > 0)
{
this._cdf = new double[probs.length];
this._cdf[0] = probs[0];
for (int i = 1; i < probs.length; ++i)
{
this._cdf[i] = this._cdf[i-1]+probs[i];
}
}
}
public int nextInt(Random rng)
{
double p = rng.nextDouble();
// for (int x = 0; x < this._cdf.length; ++x)
// {
// if (p > this._cdf[x])
// {
// return x;
// }
// }
// return this._cdf.length-1;
int x = Arrays.binarySearch(this._cdf, p);
return (x >= 0 ? x : -x);
}
}
| [rubis] (change:minor) Added normalization in the computation of CDF.
| src/radlab/rain/workload/rubis/util/DiscreteDistribution.java | [rubis] (change:minor) Added normalization in the computation of CDF. | <ide><path>rc/radlab/rain/workload/rubis/util/DiscreteDistribution.java
<ide> if (probs.length > 0)
<ide> {
<ide> this._cdf = new double[probs.length];
<add>
<add> // Compute CDF
<add> double cumProb = probs[0];
<ide> this._cdf[0] = probs[0];
<ide> for (int i = 1; i < probs.length; ++i)
<ide> {
<del> this._cdf[i] = this._cdf[i-1]+probs[i];
<add> //this._cdf[i] = this._cdf[i-1]+probs[i];
<add> this._cdf[i] = cumProb;
<add> cumProb += probs[i];
<add> }
<add> // Normalize
<add> for (int i = 0; i < probs.length; ++i)
<add> {
<add> this._cdf[i] /= cumProb;
<ide> }
<ide> }
<ide> } |
|
Java | mit | c2e8a43ae97f5d0cf6fdedb0b37bcfcff4192de0 | 0 | TejasBhitle/Matrix2017 | package spit.matrix2017.Activities;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.transition.Slide;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import spit.matrix2017.R;
public class EventDetails
extends AppCompatActivity
{
private boolean isFavouriteEvent;
private boolean isReminderSet;
FloatingActionButton fab;
private String event_name;
private MenuItem mi_reminder;
private long mEventID;
private boolean visitedCalendar, isFirstLaunch;
ImageView mainImageView;
View background;
CollapsingToolbarLayout collapsingToolbarLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
final AppCompatTextView textViews[] = {
(AppCompatTextView) findViewById(R.id.tv_event_description),
(AppCompatTextView) findViewById(R.id.tv_event_venue_time),
(AppCompatTextView) findViewById(R.id.tv_event_registration),
(AppCompatTextView) findViewById(R.id.tv_event_prizes),
(AppCompatTextView) findViewById(R.id.tv_event_organizers)
};
background = findViewById(R.id.event_details_background);
collapsingToolbarLayout=(CollapsingToolbarLayout)findViewById(R.id.collapsingToolbar_event);
visitedCalendar = false;
isFirstLaunch = true;
//get intent from eventlist adapter
if (getIntent().getStringExtra("name") != null && getSupportActionBar() != null) {
event_name = getIntent().getStringExtra("name");
this.setTitle(event_name);
}
else
this.setTitle("Some event");
setDescription(getIntent().getStringExtra("description"));
setVenueAndTime(getIntent().getStringExtra("venue"), getIntent().getStringExtra("time"));
setRegistration(getIntent().getStringExtra("registration"));
setPrizes(getIntent().getStringExtra("prizes"));
setContacts(getIntent().getStringExtra("contact1name"), getIntent().getStringExtra("contact1no"), getIntent().getStringExtra("contact2name"), getIntent().getStringExtra("contact2no"));
isFavouriteEvent = getIntent().getLongExtra("favorite", 0) == 1;
isReminderSet = getIntent().getLongExtra("reminder", 0) == 1;
mainImageView = (ImageView) findViewById(R.id.main_imageView);
assert mainImageView != null;
mainImageView.setImageResource(getIntent().getIntExtra("image", R.drawable.virtual_stock_market));
fab = (FloatingActionButton) findViewById(R.id.fab);
assert fab != null;
if (isFavouriteEvent)
fab.setImageResource(R.drawable.svg_favorite_white_48px);
Bitmap bitmap = ((BitmapDrawable)mainImageView.getDrawable()).getBitmap();
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener()
{
@Override
public void onGenerated(Palette palette)
{
Palette.Swatch swatch = palette.getVibrantSwatch();
if(swatch == null)
swatch = palette.getMutedSwatch();
if(swatch != null)
{
int color = swatch.getRgb();
if(Color.red(color)+Color.green(color)+Color.green(color) > 420)
color = Color.rgb((int)(Color.red(color)*0.8), (int)(Color.green(color)*0.8), (int)(Color.blue(color)*0.8));
fab.setBackgroundTintList(ColorStateList.valueOf(color));
fab.setRippleColor(swatch.getTitleTextColor());
collapsingToolbarLayout.setContentScrimColor(color);
collapsingToolbarLayout.setBackgroundColor(color);
collapsingToolbarLayout.setStatusBarScrimColor(color);
if(Build.VERSION.SDK_INT >= 21){
getWindow().setStatusBarColor(color);
}
for (AppCompatTextView textView : textViews) textView.setTextColor(color);
}
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isFavouriteEvent = !isFavouriteEvent;
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://spit.matrix2017.provider");
String selection = "name = ?";
String[] selectionArgs = {getIntent().getStringExtra("name")};
ContentValues cv = new ContentValues();
if (isFavouriteEvent) {
cv.put("favorite", 1);
contentResolver.update(uri, cv, selection, selectionArgs);
Toast.makeText(EventDetails.this, "Added to favorites", Toast.LENGTH_SHORT).show();
fab.setImageResource(R.drawable.svg_favorite_white_48px);
} else {
cv.put("favorite", 0);
contentResolver.update(uri, cv, selection, selectionArgs);
fab.setImageResource(R.drawable.svg_favorite_border_white_48px);
}
}
});
}
@Override
protected void onStart() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
Slide slide = new Slide(Gravity.BOTTOM);
if(isFirstLaunch) {
fab.hide();
isFirstLaunch = false;
}
slide.addTarget(R.id.description_card);
slide.addTarget(R.id.venue_time_card);
slide.addTarget(R.id.registration_card);
slide.addTarget(R.id.prizes_card);
slide.addTarget(R.id.organizers_card);
slide.setInterpolator(new LinearOutSlowInInterpolator());
getWindow().setEnterTransition(slide);
getWindow().setExitTransition(slide);
getWindow().setReenterTransition(slide);
setupEnterAnimation();
}
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event_details, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
mi_reminder = menu.findItem(R.id.action_set_reminder);
if(isReminderSet)
mi_reminder.setIcon(R.drawable.svg_alarm_on_white_48px);
return super.onPrepareOptionsMenu(menu);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setupEnterAnimation() {
Transition transition = TransitionInflater.from(this).inflateTransition(R.transition.transition);
transition.setDuration(300);
getWindow().setSharedElementEnterTransition(transition);
transition.addListener(new Transition.TransitionListener() {
@Override
public void onTransitionStart(Transition transition) {
}
@Override
public void onTransitionEnd(Transition transition) {
fab.show();
}
@Override
public void onTransitionCancel(Transition transition) {
}
@Override
public void onTransitionPause(Transition transition) {
}
@Override
public void onTransitionResume(Transition transition) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_set_reminder:
setReminder();
break;
case R.id.action_share:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Check out the event '"+event_name+"' at Matrix 17! For more details, download the official app here:\n"+getResources().getString(R.string.playstore_link));
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, "Share event via"));
break;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void setTitle(final String title) {
/*Code to make title visible only in collapsed state*/
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar_event);
collapsingToolbarLayout.setTitle(title);
collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
}
private void setDescription(String description) {
AppCompatTextView descriptionTextView = (AppCompatTextView) findViewById(R.id.description_textView);
assert descriptionTextView != null;
descriptionTextView.setText(description);
}
private void setVenueAndTime(String venue, String time) {
AppCompatTextView venueTimeTextView = (AppCompatTextView) findViewById(R.id.venue_time_textView);
assert venueTimeTextView != null;
venueTimeTextView.setText(venue + "\n" + time);
}
private void setRegistration(String registration) {
AppCompatTextView registrationTextView = (AppCompatTextView) findViewById(R.id.registration_textView);
assert registrationTextView != null;
registrationTextView.setText(registration);
}
private void setPrizes(String prizes) {
AppCompatTextView prizesTextView = (AppCompatTextView) findViewById(R.id.prizes_textView);
assert prizesTextView != null;
prizesTextView.setText(prizes);
}
private void setContacts(final String name1, final String number1, final String name2, final String number2) {
TextView contactTextViewOne = (TextView) findViewById(R.id.contact_name_one);
TextView contactTextViewTwo = (TextView) findViewById(R.id.contact_name_two);
ImageButton callOne = (ImageButton) findViewById(R.id.call_contact_person_one);
ImageButton saveOne = (ImageButton) findViewById(R.id.save_contact_person_one);
ImageButton callTwo = (ImageButton) findViewById(R.id.call_contact_person_two);
ImageButton saveTwo = (ImageButton) findViewById(R.id.save_contact_person_two);
assert contactTextViewOne != null;
contactTextViewOne.setText(name1 + "\n" + number1);
assert contactTextViewTwo != null;
contactTextViewTwo.setText(name2 + "\n" + number2);
View.OnClickListener callOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
switch (v.getId()) {
case R.id.call_contact_person_one:
intent.setData(Uri.parse("tel:" + number1));
break;
case R.id.call_contact_person_two:
intent.setData(Uri.parse("tel:" + number2));
break;
}
startActivity(intent);
}
};
View.OnClickListener saveOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
switch (v.getId()) {
case android.R.id.home:
EventDetails.super.onBackPressed();
break;
case R.id.save_contact_person_one:
intent.putExtra(ContactsContract.Intents.Insert.NAME, name1);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, "" + number1);
break;
case R.id.save_contact_person_two:
intent.putExtra(ContactsContract.Intents.Insert.NAME, name2);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, "" + number2);
break;
}
startActivity(intent);
}
};
assert callOne != null;
callOne.setOnClickListener(callOnClickListener);
assert callTwo != null;
callTwo.setOnClickListener(callOnClickListener);
assert saveOne != null;
saveOne.setOnClickListener(saveOnClickListener);
assert saveTwo != null;
saveTwo.setOnClickListener(saveOnClickListener);
}
private void setReminder()
{
if(ContextCompat.checkSelfPermission(EventDetails.this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR}, 1);
else
{
if (isReminderSet)
Toast.makeText(this, "Reminder already set", Toast.LENGTH_SHORT).show();
else {
final Calendar beginTime = Calendar.getInstance();
final Calendar endTime = Calendar.getInstance();
if(event_name != null && event_name.equals("VSM"))
{
beginTime.set(2017, 1, 16, 13, 0);
endTime.set(2017, 1, 16, 14, 0);
}
else
{
beginTime.set(2017, 1, 16, 9, 0);
endTime.set(2017, 1, 16, 18, 0);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remind on?");
builder.setItems(new String[]{"Day 1", "Day 2"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 1)
{
if(event_name != null && event_name.equals("VSM"))
{
beginTime.set(2017, 1, 17, 13, 0);
endTime.set(2017, 1, 17, 14, 0);
}
else
{
beginTime.set(2017, 1, 17, 9, 0);
endTime.set(2017, 1, 17, 18, 0);
}
goToCalendar(beginTime, endTime);
}
else
goToCalendar(beginTime, endTime);
}
});
builder.show();
}
}
}
private void goToCalendar(Calendar beginTime, Calendar endTime)
{
mEventID = getLastEventId(getContentResolver())+1;
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
.putExtra(CalendarContract.Events._ID, mEventID)
.putExtra(CalendarContract.Events.TITLE, event_name)
.putExtra(CalendarContract.Events.DESCRIPTION, "Event at Matrix 17")
.putExtra(CalendarContract.Events.EVENT_LOCATION, getIntent().getStringExtra("venue"))
.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
visitedCalendar = true;
startActivity(intent);
}
private long getLastEventId(ContentResolver cr)
{
if(ContextCompat.checkSelfPermission(EventDetails.this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
Cursor cursor = cr.query(CalendarContract.Events.CONTENT_URI, new String[]{"MAX(_id) as max_id"}, null, null, "_id");
assert cursor != null;
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
cursor.close();
return max_val;
}
return 0;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if(grantResults[0] != 0)
Toast.makeText(EventDetails.this, "Reminder cannot be added without permission to read calendar", Toast.LENGTH_SHORT).show();
else
setReminder();
}
@Override
public void onResume()
{
super.onResume();
if (visitedCalendar)
{
if (getLastEventId(getContentResolver()) == mEventID)
{
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://spit.matrix2017.provider");
String selection = "name = ?";
String[] selectionArgs = {getIntent().getStringExtra("name")+", S.P.I.T."};
ContentValues cv = new ContentValues();
cv.put("reminder", 1);
contentResolver.update(uri, cv, selection, selectionArgs);
isReminderSet = true;
mi_reminder.setIcon(R.drawable.svg_alarm_on_white_48px);
Toast.makeText(EventDetails.this, "Successfully added reminder", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(EventDetails.this, "Reminder not added", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
if(fab.isShown())
mainImageView.bringToFront();
fab.setVisibility(View.GONE);
super.onBackPressed();
}
} | app/src/main/java/spit/matrix2017/Activities/EventDetails.java | package spit.matrix2017.Activities;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.transition.Slide;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import spit.matrix2017.R;
public class EventDetails
extends AppCompatActivity
{
private boolean isFavouriteEvent;
private boolean isReminderSet;
FloatingActionButton fab;
private String event_name;
private MenuItem mi_reminder;
private long mEventID;
private boolean visitedCalendar, isFirstLaunch;
ImageView mainImageView;
View background;
CollapsingToolbarLayout collapsingToolbarLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
final AppCompatTextView textViews[] = {
(AppCompatTextView) findViewById(R.id.tv_event_description),
(AppCompatTextView) findViewById(R.id.tv_event_venue_time),
(AppCompatTextView) findViewById(R.id.tv_event_registration),
(AppCompatTextView) findViewById(R.id.tv_event_prizes),
(AppCompatTextView) findViewById(R.id.tv_event_organizers)
};
background = findViewById(R.id.event_details_background);
collapsingToolbarLayout=(CollapsingToolbarLayout)findViewById(R.id.collapsingToolbar_event);
visitedCalendar = false;
isFirstLaunch = true;
//get intent from eventlist adapter
if (getIntent().getStringExtra("name") != null && getSupportActionBar() != null) {
event_name = getIntent().getStringExtra("name");
this.setTitle(event_name);
}
else
this.setTitle("Some event");
setDescription(getIntent().getStringExtra("description"));
setVenueAndTime(getIntent().getStringExtra("venue"), getIntent().getStringExtra("time"));
setRegistration(getIntent().getStringExtra("registration"));
setPrizes(getIntent().getStringExtra("prizes"));
setContacts(getIntent().getStringExtra("contact1name"), getIntent().getStringExtra("contact1no"), getIntent().getStringExtra("contact2name"), getIntent().getStringExtra("contact2no"));
isFavouriteEvent = getIntent().getLongExtra("favorite", 0) == 1;
isReminderSet = getIntent().getLongExtra("reminder", 0) == 1;
mainImageView = (ImageView) findViewById(R.id.main_imageView);
assert mainImageView != null;
mainImageView.setImageResource(getIntent().getIntExtra("image", R.drawable.virtual_stock_market));
fab = (FloatingActionButton) findViewById(R.id.fab);
assert fab != null;
if (isFavouriteEvent)
fab.setImageResource(R.drawable.svg_favorite_white_48px);
Bitmap bitmap = ((BitmapDrawable)mainImageView.getDrawable()).getBitmap();
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener()
{
@Override
public void onGenerated(Palette palette)
{
Palette.Swatch swatch = palette.getVibrantSwatch();
if(swatch == null)
swatch = palette.getMutedSwatch();
if(swatch != null)
{
int color = swatch.getRgb();
if(Color.red(color)+Color.green(color)+Color.green(color) > 420)
color = Color.rgb((int)(Color.red(color)*0.8), (int)(Color.green(color)*0.8), (int)(Color.blue(color)*0.8));
fab.setBackgroundTintList(ColorStateList.valueOf(color));
fab.setRippleColor(swatch.getTitleTextColor());
collapsingToolbarLayout.setContentScrimColor(color);
collapsingToolbarLayout.setBackgroundColor(color);
collapsingToolbarLayout.setStatusBarScrimColor(color);
if(Build.VERSION.SDK_INT >= 21){
getWindow().setStatusBarColor(color);
}
for (AppCompatTextView textView : textViews) textView.setTextColor(color);
}
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isFavouriteEvent = !isFavouriteEvent;
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://spit.matrix2017.provider");
String selection = "name = ?";
String[] selectionArgs = {getIntent().getStringExtra("name")};
ContentValues cv = new ContentValues();
if (isFavouriteEvent) {
cv.put("favorite", 1);
contentResolver.update(uri, cv, selection, selectionArgs);
Toast.makeText(EventDetails.this, "Added to favorites", Toast.LENGTH_SHORT).show();
fab.setImageResource(R.drawable.svg_favorite_white_48px);
} else {
cv.put("favorite", 0);
contentResolver.update(uri, cv, selection, selectionArgs);
fab.setImageResource(R.drawable.svg_favorite_border_white_48px);
}
}
});
}
@Override
protected void onStart() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
Slide slide = new Slide(Gravity.BOTTOM);
if(isFirstLaunch) {
fab.hide();
isFirstLaunch = false;
}
slide.addTarget(R.id.description_card);
slide.addTarget(R.id.venue_time_card);
slide.addTarget(R.id.registration_card);
slide.addTarget(R.id.prizes_card);
slide.addTarget(R.id.organizers_card);
slide.setInterpolator(new LinearOutSlowInInterpolator());
getWindow().setEnterTransition(slide);
getWindow().setExitTransition(slide);
getWindow().setReenterTransition(slide);
setupEnterAnimation();
}
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event_details, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
mi_reminder = menu.findItem(R.id.action_set_reminder);
if(isReminderSet)
mi_reminder.setIcon(R.drawable.svg_alarm_on_white_48px);
return super.onPrepareOptionsMenu(menu);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setupEnterAnimation() {
Transition transition = TransitionInflater.from(this).inflateTransition(R.transition.transition);
transition.setDuration(300);
getWindow().setSharedElementEnterTransition(transition);
transition.addListener(new Transition.TransitionListener() {
@Override
public void onTransitionStart(Transition transition) {
}
@Override
public void onTransitionEnd(Transition transition) {
fab.show();
}
@Override
public void onTransitionCancel(Transition transition) {
}
@Override
public void onTransitionPause(Transition transition) {
}
@Override
public void onTransitionResume(Transition transition) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_set_reminder:
setReminder();
break;
case R.id.action_share:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Check out the event '"+event_name+"' at Matrix 17! For more details, download the official app here:\n"+getResources().getString(R.string.playstore_link));
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, "Share event via"));
break;
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
private void setTitle(final String title) {
/*Code to make title visible only in collapsed state*/
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar_event);
collapsingToolbarLayout.setTitle(title);
collapsingToolbarLayout.setExpandedTitleColor(Color.TRANSPARENT);
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
}
private void setDescription(String description) {
AppCompatTextView descriptionTextView = (AppCompatTextView) findViewById(R.id.description_textView);
assert descriptionTextView != null;
descriptionTextView.setText(description);
}
private void setVenueAndTime(String venue, String time) {
AppCompatTextView venueTimeTextView = (AppCompatTextView) findViewById(R.id.venue_time_textView);
assert venueTimeTextView != null;
venueTimeTextView.setText(venue + "\n" + time);
}
private void setRegistration(String registration) {
AppCompatTextView registrationTextView = (AppCompatTextView) findViewById(R.id.registration_textView);
assert registrationTextView != null;
registrationTextView.setText(registration);
}
private void setPrizes(String prizes) {
AppCompatTextView prizesTextView = (AppCompatTextView) findViewById(R.id.prizes_textView);
assert prizesTextView != null;
prizesTextView.setText(prizes);
}
private void setContacts(final String name1, final String number1, final String name2, final String number2) {
TextView contactTextViewOne = (TextView) findViewById(R.id.contact_name_one);
TextView contactTextViewTwo = (TextView) findViewById(R.id.contact_name_two);
ImageButton callOne = (ImageButton) findViewById(R.id.call_contact_person_one);
ImageButton saveOne = (ImageButton) findViewById(R.id.save_contact_person_one);
ImageButton callTwo = (ImageButton) findViewById(R.id.call_contact_person_two);
ImageButton saveTwo = (ImageButton) findViewById(R.id.save_contact_person_two);
assert contactTextViewOne != null;
contactTextViewOne.setText(name1 + "\n" + number1);
assert contactTextViewTwo != null;
contactTextViewTwo.setText(name2 + "\n" + number2);
View.OnClickListener callOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_DIAL);
switch (v.getId()) {
case R.id.call_contact_person_one:
intent.setData(Uri.parse("tel:" + number1));
break;
case R.id.call_contact_person_two:
intent.setData(Uri.parse("tel:" + number2));
break;
}
startActivity(intent);
}
};
View.OnClickListener saveOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
switch (v.getId()) {
case android.R.id.home:
EventDetails.super.onBackPressed();
break;
case R.id.save_contact_person_one:
intent.putExtra(ContactsContract.Intents.Insert.NAME, name1);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, "" + number1);
break;
case R.id.save_contact_person_two:
intent.putExtra(ContactsContract.Intents.Insert.NAME, name2);
intent.putExtra(ContactsContract.Intents.Insert.PHONE, "" + number2);
break;
}
startActivity(intent);
}
};
assert callOne != null;
callOne.setOnClickListener(callOnClickListener);
assert callTwo != null;
callTwo.setOnClickListener(callOnClickListener);
assert saveOne != null;
saveOne.setOnClickListener(saveOnClickListener);
assert saveTwo != null;
saveTwo.setOnClickListener(saveOnClickListener);
}
private void setReminder()
{
if(ContextCompat.checkSelfPermission(EventDetails.this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALENDAR}, 1);
else
{
if (isReminderSet)
Toast.makeText(this, "Reminder already set", Toast.LENGTH_SHORT).show();
else {
final Calendar beginTime = Calendar.getInstance();
final Calendar endTime = Calendar.getInstance();
if(event_name != null && event_name.equals("VSM"))
{
beginTime.set(2017, 1, 16, 13, 0);
endTime.set(2017, 1, 16, 14, 0);
}
else
{
beginTime.set(2017, 1, 16, 9, 0);
endTime.set(2017, 1, 16, 18, 0);
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remind on?");
builder.setItems(new String[]{"Day 1", "Day 2"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 1)
{
if(event_name != null && event_name.equals("VSM"))
{
beginTime.set(2017, 1, 17, 13, 0);
endTime.set(2017, 1, 17, 14, 0);
}
else
{
beginTime.set(2017, 1, 17, 9, 0);
endTime.set(2017, 1, 17, 18, 0);
}
goToCalendar(beginTime, endTime);
}
else
goToCalendar(beginTime, endTime);
}
});
builder.show();
}
}
}
private void goToCalendar(Calendar beginTime, Calendar endTime)
{
mEventID = getLastEventId(getContentResolver())+1;
Intent intent = new Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
.putExtra(CalendarContract.Events._ID, mEventID)
.putExtra(CalendarContract.Events.TITLE, event_name)
.putExtra(CalendarContract.Events.DESCRIPTION, "Event at Matrix 17")
.putExtra(CalendarContract.Events.EVENT_LOCATION, getIntent().getStringExtra("venue"))
.putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
visitedCalendar = true;
startActivity(intent);
}
private long getLastEventId(ContentResolver cr)
{
if(ContextCompat.checkSelfPermission(EventDetails.this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED) {
Cursor cursor = cr.query(CalendarContract.Events.CONTENT_URI, new String[]{"MAX(_id) as max_id"}, null, null, "_id");
assert cursor != null;
cursor.moveToFirst();
long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));
cursor.close();
return max_val;
}
return 0;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
if(grantResults[0] != 0)
Toast.makeText(EventDetails.this, "Reminder cannot be added without permission to read calendar", Toast.LENGTH_SHORT).show();
else
setReminder();
}
@Override
public void onResume()
{
super.onResume();
if (visitedCalendar)
{
if (getLastEventId(getContentResolver()) == mEventID)
{
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://spit.matrix2017.provider");
String selection = "name = ?";
String[] selectionArgs = {getIntent().getStringExtra("name")+", S.P.I.T."};
ContentValues cv = new ContentValues();
cv.put("reminder", 1);
contentResolver.update(uri, cv, selection, selectionArgs);
isReminderSet = true;
mi_reminder.setIcon(R.drawable.svg_alarm_on_white_48px);
Toast.makeText(EventDetails.this, "Successfully added reminder", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(EventDetails.this, "Reminder not added", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
if(fab.isShown())
mainImageView.bringToFront();
fab.setVisibility(View.GONE);
super.onBackPressed();
}
} | Fix issue #9
| app/src/main/java/spit/matrix2017/Activities/EventDetails.java | Fix issue #9 | <ide><path>pp/src/main/java/spit/matrix2017/Activities/EventDetails.java
<ide> break;
<ide> case android.R.id.home:
<ide> onBackPressed();
<del> break;
<add> return true;
<ide> }
<ide> return super.onOptionsItemSelected(item);
<ide> } |
|
JavaScript | mit | 0eae6ac385e915d6c5dc2ba85227d05f5394a13d | 0 | orlovmax/front-end-scaffold,orlovmax/front-end-scaffold,orlovmax/front-end-scaffold | module.exports = function(grunt) {
grunt.initConfig({
//Assemble *.js files
concat: {
main: {
files: [{
src: ['dev/js/*.js', '!dev/js/assembled.js'],
dest: 'dev/js/assembled.js'
}]
},
head: {
files: [{
src: ['dev/js/head/*.js', '!dev/js/head/head.js'],
dest: 'dev/js/head/head.js'
}]
}
},
//Uglify assembled *.js file
uglify: {
options: {
mangle: false
},
vendor: {
files: [{
expand: true,
cwd: 'dev/js/vendor',
src: '**/*.js',
dest: 'build/js/vendor',
ext: '.min.js'
}]
},
main: {
files: {
'build/js/assembled.min.js': 'dev/js/assembled.js'
}
},
head: {
files: {
'build/js/head/head.min.js': 'dev/js/head/head.js'
}
}
},
//Compile *.scss files
sass: {
main: {
options: {
style: 'expanded',
sourcemap: 'none'
},
files: [{
expand: true,
cwd: 'dev/styles',
src: ['*.{sass,scss}'],
dest: 'dev/css',
ext: '.css'
}]
}
},
//Compile *.less files
less: {
main: {
files: [{
expand: true,
cwd: 'dev/styles',
src: ['*.less'],
dest: 'dev/css',
ext: '.css'
}]
}
},
//Combine media queries in result *.css files
cmq: {
options: {
log: false
},
main: {
files: {
'dev/css': ['dev/css/*.css']
}
}
},
//Autoprefixer
autoprefixer: {
options: {
browsers: ['last 2 versions', 'ie 8', 'ie 9']
//By default >1%, last 2 versions, Firefox ESR, Opera 12.1;
},
main: {
files:[{
expand: true,
flatten: true,
src: 'dev/css/*.css',
dest: 'dev/css/'
}]
}
},
//Minify and organize *.css files
csso: {
options: {
keepSpecialComments: '*'
},
main: {
files:[{
expand: true,
cwd: 'dev/css/',
src: ['*.css', '!*.min.css'],
dest: 'build/css/',
ext: '.min.css'
}]
}
},
//Compile *.jade files
jade: {
main: {
options: {
client: false,
pretty: true
},
files: [ {
cwd: "dev/markup",
src: "*.jade",
dest: "dev/html/",
expand: true,
ext: ".html"
} ]
}
},
//Compile *.haml files
haml: {
main: {
files: [ {
cwd: "dev/markup",
src: "*.haml",
dest: "dev/html/",
expand: true,
ext: ".html"
} ]
}
},
//Minify *.html files
htmlmin: {
main: {
options: {
collapseWhitespace: true,
minifyJS: true,
minifyCSS: true
},
files: [ {
cwd: "dev/html",
src: "*.html",
dest: "build/",
expand: true,
ext: ".html"
} ]
}
},
//Minify image files
imagemin: {
main: {
options: {
optimizationLevel: 7
},
files: [{
expand: true,
cwd: 'dev/img',
src: ['**/*.{png,jpg,gif}'],
dest: 'build/img/'
}]
}
},
//Copy some folders or files (ex. *.php) from dev to build
copy: {
php: {
files: [{
expand: true,
cwd: 'dev/php/',
src: '**',
dest: 'build/php/'
}]
},
fonts: {
files: [{
expand: true,
cwd: 'dev/fonts/',
src: ['**/*.{eot,svg,ttf,woff}'],
dest: 'build/fonts/'
}]
},
js: {
files: [{
expand: true,
cwd: 'dev/js/',
src: [
'**/assembled.js',
'**/vendor.js',
'**/head.js'],
dest: 'build/js/'
}]
},
livejs: {
files: [{
expand: true,
cwd: 'dev/devtools/',
src: '**/live.js',
dest: 'build/js/'
}]
},
css: {
files: [{
expand: true,
cwd: 'dev/css',
src: ['**/*.css'],
dest: 'build/css/'
}]
},
html: {
files: [{
expand: true,
cwd: 'dev/html',
src: ['**/*.html'],
dest: 'build/'
}]
},
helpers: {
files: [{
expand: true,
cwd: 'dev/main/helpers',
src: ['**/*.*', '**/.htaccess'],
dest: 'build'
}]
}
},
//Assemble bower components in right order
bower_concat: {
main: {
dest: 'dev/js/vendor/vendor.js'
}
},
//Copy bower components to the custom folder
// bowercopy: {
// options: {
// clean: true,
// ignore: ['modernizr']
// },
// jquery: {
// options: {
// destPrefix: 'dev/js/vendor'
// },
// files: {
// 'jquery': 'jquery/dist/jquery.js'
// },
// }
// },
//Delete .gitkeep files. If you don't use Bower - just run `grunt clean`
clean: {
gitkeep: ['dev/**/.gitkeep', 'build/**/.gitkeep'],
less: 'dev/**/*.less',
sass: 'dev/**/*.scss',
haml: 'dev/**/*.haml',
jade: 'dev/**/*.jade',
debug: ['build/js/**/*.js',
'!build/js/**/*.min.js',
'build/css/**/*.css',
'!build/css/**/*.min.css'],
bower: 'bower_components'
},
//Delete some dev code and references from files
preprocess : {
options: {
context : {
BUILD: true
}
},
html : {
src : [ 'dev/html/*.html' ],
options: {
inline : true
}
},
css : {
src : [ 'dev/css/*.css' ],
options: {
inline : true
}
},
js : {
src : [ 'dev/js/*.js' ],
options: {
inline : true
}
}
},
//Watch for changes
watch: {
all: {
files: ['dev/html/**/*.html',
'dev/styles/**/*.{scss,less}',
'dev/css/*.css',
'dev/js/**/*.js',
'dev/img/**/*.{png,jpg,gif}',
'dev/markup/**/*.{haml,jade}',
'dev/php/**/*.php',
'dev/fonts/**/*.{eot,svg,ttf,woff}'],
tasks: ['default'],
options: {
spawn: false,
},
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-combine-media-queries');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-csso');
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-haml2html');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('grunt-bower-concat');
// grunt.loadNpmTasks('grunt-bowercopy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-preprocess');
grunt.registerTask('default', ['newer:concat',
'newer:sass',
'newer:less',
'newer:jade',
'newer:haml',
'preprocess',
'newer:imagemin',
'newer:copy',
'watch'
]);
grunt.registerTask('bower-dev', ['bower_concat',
// 'bowercopy',
'clean:gitkeep',
'clean:bower'
]);
grunt.registerTask('build', ['preprocess',
'cmq',
'autoprefixer',
'uglify',
'csso',
'htmlmin',
'clean:debug'
]);
}; | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
//Assemble *.js files
concat: {
main: {
files: [{
src: ['dev/js/*.js', '!dev/js/assembled.js'],
dest: 'dev/js/assembled.js'
}]
},
head: {
files: [{
src: ['dev/js/head/*.js', '!dev/js/head/head.js'],
dest: 'dev/js/head/head.js'
}]
}
},
//Uglify assembled *.js file
uglify: {
options: {
mangle: false
},
vendor: {
files: [{
expand: true,
cwd: 'dev/js/vendor',
src: '**/*.js',
dest: 'build/js/vendor',
ext: '.min.js'
}]
},
main: {
files: {
'build/js/assembled.min.js': 'dev/js/assembled.js'
}
},
head: {
files: {
'build/js/head/head.min.js': 'dev/js/head/head.js'
}
}
},
//Compile *.scss files
sass: {
main: {
options: {
style: 'expanded',
sourcemap: 'none'
},
files: [{
expand: true,
cwd: 'dev/styles',
src: ['*.{sass,scss}'],
dest: 'dev/css',
ext: '.css'
}]
}
},
//Compile *.less files
less: {
main: {
files: [{
expand: true,
cwd: 'dev/styles',
src: ['*.less'],
dest: 'dev/css',
ext: '.css'
}]
}
},
//Combine media queries in result *.css files
cmq: {
options: {
log: false
},
main: {
files: {
'dev/css': ['dev/css/*.css']
}
}
},
//Autoprefixer
autoprefixer: {
options: {
browsers: ['last 2 versions', 'ie 8', 'ie 9']
//By default >1%, last 2 versions, Firefox ESR, Opera 12.1;
},
main: {
files:[{
expand: true,
flatten: true,
src: 'dev/css/*.css',
dest: 'dev/css/'
}]
}
},
//Minify and organize *.css files
csso: {
options: {
keepSpecialComments: '*'
},
main: {
files:[{
expand: true,
cwd: 'dev/css/',
src: ['*.css', '!*.min.css'],
dest: 'build/css/',
ext: '.min.css'
}]
}
},
//Compile *.jade files
jade: {
main: {
options: {
client: false,
pretty: true
},
files: [ {
cwd: "dev/markup",
src: "*.jade",
dest: "dev/html/",
expand: true,
ext: ".html"
} ]
}
},
//Compile *.haml files
haml: {
main: {
files: [ {
cwd: "dev/markup",
src: "*.haml",
dest: "dev/html/",
expand: true,
ext: ".html"
} ]
}
},
//Minify *.html files
htmlmin: {
main: {
options: {
collapseWhitespace: true,
minifyJS: true,
minifyCSS: true
},
files: [ {
cwd: "dev/html",
src: "*.html",
dest: "build/",
expand: true,
ext: ".html"
} ]
}
},
//Minify image files
imagemin: {
main: {
options: {
optimizationLevel: 7
},
files: [{
expand: true,
cwd: 'dev/img',
src: ['**/*.{png,jpg,gif}'],
dest: 'build/img/'
}]
}
},
//Copy some folders or files (ex. *.php) from dev to build
copy: {
php: {
files: [{
expand: true,
cwd: 'dev/php/',
src: '**',
dest: 'build/php/'
}]
},
fonts: {
files: [{
expand: true,
cwd: 'dev/fonts/',
src: ['**/*.{eot,svg,ttf,woff}'],
dest: 'build/fonts/'
}]
},
js: {
files: [{
expand: true,
cwd: 'dev/js/',
src: [
'**/assembled.js',
'**/vendor.js',
'**/head.js'],
dest: 'build/js/'
}]
},
livejs: {
files: [{
expand: true,
cwd: 'dev/devtools/',
src: '**/live.js',
dest: 'build/js/'
}]
},
css: {
files: [{
expand: true,
cwd: 'dev/css',
src: ['**/*.css'],
dest: 'build/css/'
}]
},
html: {
files: [{
expand: true,
cwd: 'dev/html',
src: ['**/*.html'],
dest: 'build/'
}]
},
helpers: {
files: [{
expand: true,
cwd: 'dev/main/helpers',
src: ['**/*.*', '**/.htaccess'],
dest: 'build'
}]
}
},
//Assemble bower components in right order
bower_concat: {
main: {
dest: 'dev/js/vendor/vendor.js'
}
},
//Copy bower components to the custom folder
// bowercopy: {
// options: {
// clean: true,
// ignore: ['modernizr']
// },
// jquery: {
// options: {
// destPrefix: 'dev/js/vendor'
// },
// files: {
// 'jquery': 'jquery/dist/jquery.js'
// },
// }
// },
//Delete .gitkeep files. If you don't use Bower - just run `grunt clean`
clean: {
gitkeep: ['dev/**/.gitkeep', 'build/**/.gitkeep'],
less: 'dev/**/*.less',
sass: 'dev/**/*.scss',
haml: 'dev/**/*.haml',
jade: 'dev/**/*.jade',
debug: ['build/js/**/*.js',
'!build/js/**/*.min.js',
'build/css/**/*.css',
'!build/css/**/*.min.css'],
bower: 'bower_components'
},
//Delete some dev code and references from files
preprocess : {
options: {
context : {
BUILD: true
}
},
html : {
src : [ 'dev/html/*.html' ],
options: {
inline : true
}
},
css : {
src : [ 'dev/css/*.css' ],
options: {
inline : true
}
},
js : {
src : [ 'dev/js/*.js' ],
options: {
inline : true
}
}
},
//Watch for changes
watch: {
all: {
files: ['dev/html/**/*.html',
'dev/styles/**/*.{scss,less}',
'dev/css/*.css',
'dev/js/**/*.js',
'dev/img/**/*.{png,jpg,gif}',
'dev/markup/**/*.{haml,jade}',
'dev/php/**/*.php',
'dev/fonts/**/*.{eot,svg,ttf,woff}'],
tasks: ['default'],
options: {
spawn: false,
},
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-combine-media-queries');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-csso');
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-haml2html');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.loadNpmTasks('grunt-bower-concat');
// grunt.loadNpmTasks('grunt-bowercopy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-preprocess');
grunt.registerTask('default', ['newer:concat',
'newer:sass',
'newer:less',
'newer:jade',
'newer:haml',
'newer:imagemin',
'newer:copy',
'watch'
]);
grunt.registerTask('bower-dev', ['bower_concat',
// 'bowercopy',
'clean:gitkeep',
'clean:bower'
]);
grunt.registerTask('build', ['preprocess',
'cmq',
'autoprefixer',
'uglify',
'csso',
'htmlmin',
'clean:debug'
]);
}; | minor task fix
| Gruntfile.js | minor task fix | <ide><path>runtfile.js
<ide> 'newer:less',
<ide> 'newer:jade',
<ide> 'newer:haml',
<add> 'preprocess',
<ide> 'newer:imagemin',
<ide> 'newer:copy',
<ide> 'watch' |
|
Java | lgpl-2.1 | 4f54da59cf6cf3f92b5a34cf5986a3e6fef20ad5 | 0 | cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl | package org.cytoscape.app.internal.manager;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService;
import org.cytoscape.app.AbstractCyApp;
import org.cytoscape.app.CyAppAdapter;
import org.cytoscape.app.internal.event.AppsChangedEvent;
import org.cytoscape.app.internal.event.AppsChangedListener;
import org.cytoscape.app.internal.exception.AppInstallException;
import org.cytoscape.app.internal.exception.AppParsingException;
import org.cytoscape.app.internal.exception.AppUninstallException;
import org.cytoscape.app.internal.manager.App.AppStatus;
import org.cytoscape.app.internal.net.WebQuerier;
import org.cytoscape.application.CyApplicationConfiguration;
import org.cytoscape.app.internal.net.server.LocalHttpServer;
import org.cytoscape.app.internal.util.DebugHelper;
import org.cytoscape.app.swing.CySwingAppAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents an App Manager, which is capable of maintaining a list of all currently installed and available apps. The class
* also provides functionalities for installing and uninstalling apps.
*/
public class AppManager {
private static final Logger logger = LoggerFactory.getLogger(AppManager.class);
/** Only files with these extensions are checked when looking for apps in a given subdirectory.
*/
private static final String[] APP_EXTENSIONS = {"jar", "kar"};
/** Installed apps are moved to this subdirectory under the local app storage directory. */
private static final String INSTALLED_APPS_DIRECTORY_NAME = "installed";
/** Uninstalled apps are moved to this subdirectory under the local app storage directory. */
private static final String UNINSTALLED_APPS_DIRECTORY_NAME = "uninstalled";
/** Disabled apps are moved to this subdirectory under the local app storage directory. */
private static final String DISABLED_APPS_DIRECTORY_NAME = "disabled";
/** Apps are downloaded from the web store to this subdirectory under local app storage directory. */
private static final String DOWNLOADED_APPS_DIRECTORY_NAME = "download-temp";
/** Apps that are loaded are stored in this temporary directory. */
private static final String TEMPORARY_LOADED_APPS_DIRECTORY_NAME = ".temp-installed";
/** This subdirectory in the local Cytoscape storage directory is used to store app data, as
* well as installed and uninstalled apps. */
private static final String APPS_DIRECTORY_NAME = "3.0/apps";
/** The set of all apps, represented by {@link App} objects, registered to this App Manager. */
private Set<App> apps;
private Set<AppsChangedListener> appListeners;
/** An {@link AppParser} object used to parse File objects and possibly URLs into {@link App} objects
* into a format we can more easily work with
*/
private AppParser appParser;
/**
* A reference to the {@link WebQuerier} object used to make queries to the app store website.
*/
private WebQuerier webQuerier;
/**
* The {@link FeaturesService} used to communicate with Apache Karaf to manage OSGi bundle based apps
*/
private FeaturesService featuresService;
// private KarService karService;
/**
* {@link CyApplicationConfiguration} service used to obtain the directories used to store the apps.
*/
private CyApplicationConfiguration applicationConfiguration;
/**
* The {@link CySwingAppAdapter} service reference provided to the constructor of the app's {@link AbstractCyApp}-implementing class.
*/
private CySwingAppAdapter swingAppAdapter;
private FileAlterationMonitor fileAlterationMonitor;
/**
* A {@link FileFilter} that accepts only files in the first depth level of a given directory
*/
private class SingleLevelFileFilter implements FileFilter {
private File parentDirectory;
public SingleLevelFileFilter(File parentDirectory) {
this.parentDirectory = parentDirectory;
}
@Override
public boolean accept(File pathName) {
if (!pathName.getParentFile().equals(parentDirectory)) {
return false;
} else if (pathName.isDirectory()) {
return false;
}
return true;
}
}
public AppManager(CySwingAppAdapter swingAppAdapter, CyApplicationConfiguration applicationConfiguration,
final WebQuerier webQuerier, FeaturesService featuresService) {
this.applicationConfiguration = applicationConfiguration;
this.swingAppAdapter = swingAppAdapter;
this.webQuerier = webQuerier;
this.featuresService = featuresService;
apps = new HashSet<App>();
appParser = new AppParser();
// cleanKarafDeployDirectory();
purgeTemporaryDirectories();
initializeAppsDirectories();
setupAlterationMonitor();
this.appListeners = new HashSet<AppsChangedListener>();
// Install previously enabled apps
installAppsInDirectory(new File(getKarafDeployDirectory()), false);
installAppsInDirectory(new File(getInstalledAppsPath()), true);
// Load apps from the "uninstalled apps" directory
Set<App> uninstalledApps = obtainAppsFromDirectory(new File(getUninstalledAppsPath()), true);
apps.addAll(uninstalledApps);
DebugHelper.print(this, "config dir: " + applicationConfiguration.getConfigurationDirectoryLocation());
}
public FeaturesService getFeaturesService() {
return this.featuresService;
}
public void setFeaturesService(FeaturesService featuresService) {
this.featuresService = featuresService;
}
private void setupAlterationMonitor() {
// Set up the FileAlterationMonitor to install/uninstall apps when apps are moved in/out of the
// installed/uninstalled app directories
fileAlterationMonitor = new FileAlterationMonitor(30000L);
File installedAppsPath = new File(getInstalledAppsPath());
FileAlterationObserver installAlterationObserver = new FileAlterationObserver(
installedAppsPath, new SingleLevelFileFilter(installedAppsPath), IOCase.SYSTEM);
// Listen for events on the "installed apps" folder
installAlterationObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileDelete(File file) {
DebugHelper.print("Install directory file deleted");
try {
String canonicalPath = file.getCanonicalPath();
for (App app : apps) {
File appFile = app.getAppFile();
if (appFile != null
&& appFile.getCanonicalPath().equals(canonicalPath)) {
app.setAppFile(new File(getUninstalledAppsPath() + File.separator + appFile.getName()));
try {
uninstallApp(app);
} catch (AppUninstallException e) {
logger.warn("Failed to uninstall app " + app.getAppName() + " when it was removed from the local install directory.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFileCreate(File file) {
DebugHelper.print("Install directory file created");
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
installApp(parsedApp);
DebugHelper.print("Installed: " + parsedApp.getAppName());
} catch (AppParsingException e) {
DebugHelper.print("Failed to parse: " + file.getName());
} catch (AppInstallException e) {
DebugHelper.print("Failed to install: " + parsedApp.getAppName());
}
}
@Override
public void onFileChange(File file) {
}
});
setupKarafDeployMonitor(fileAlterationMonitor);
try {
//installAlterationObserver.initialize();
//fileAlterationMonitor.addObserver(installAlterationObserver);
fileAlterationMonitor.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setupKarafDeployMonitor(FileAlterationMonitor fileAlterationMonitor) {
// Set up the FileAlterationMonitor to install/uninstall bundle apps when they are moved
// to the Karaf deploy directory
File karafDeployPath = new File(getKarafDeployDirectory());
FileAlterationObserver karafDeployObserver = new FileAlterationObserver(
karafDeployPath, new SingleLevelFileFilter(karafDeployPath), IOCase.SYSTEM);
karafDeployObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileDelete(File file) {
for (App app : getApps()) {
if (app.getAppTemporaryInstallFile().equals(file)) {
try {
uninstallApp(app);
} catch (AppUninstallException e) {
logger.warn("Failed to uninstall app that was removed from Karaf deploy directory: " + app.getAppName());
}
}
}
}
@Override
public void onFileCreate(File file) {
//System.out.println("File found: " + file);
if (checkIfCytoscapeApp(file)) {
//System.out.println("File was app: " + file);
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
if (parsedApp instanceof SimpleApp) {
logger.warn("A simple app " + file.getName() + " was moved to the "
+ "framework/deploy directory. It should be installed via the "
+ "app manager. Installing anyway..");
}
//System.out.println("App was parsed: " + file);
installApp(parsedApp);
//System.out.println("App was installed: " + file);
} catch (AppParsingException e) {
logger.error("Failed to parse app that was moved to Karaf deploy directory: " + file.getName()
+ ". The error was: " + e.getMessage());
} catch (AppInstallException e) {
logger.error("Failed to register app with app manager: " + file.getName()
+ ". The error was:" + e.getMessage());
}
}
}
});
try {
//karafDeployObserver.initialize();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileAlterationMonitor.addObserver(karafDeployObserver);
}
public CySwingAppAdapter getSwingAppAdapter() {
return swingAppAdapter;
}
public AppParser getAppParser() {
return appParser;
}
public WebQuerier getWebQuerier() {
return webQuerier;
}
/**
* Registers an app to this app manager.
* @param app The app to register to this manager.
*/
public void addApp(App app) {
apps.add(app);
/*
// Let the listeners know that an app has changed
for (AppsChangedListener appListener : appListeners) {
AppsChangedEvent appEvent = new AppsChangedEvent(this);
appListener.appsChanged(appEvent);
}
*/
}
/**
* Removes an app from this app manager.
* @param app The app to remove
*/
public void removeApp(App app) {
apps.remove(app);
}
/**
* Attempts to install an app. Makes a copy of the app file and places it in the directory
* used to hold all installed and uninstalled apps, if it was not already present there. Then, the
* app is created by instancing its class that extends {@link AbstractCyApp}.
*
* Before the app is installed, it is checked if it contains valid packaging by its isAppValidated() method.
* Apps that have not been validated are ignored. Also, apps that are already installed are left alone.
*
* @param app The {@link App} object representing and providing information about the app to install
* @throws AppInstallException If there was an error while attempting to install the app such as being
* unable to copy the app to the installed apps directory or to instance the app's entry point class
*/
public void installApp(App app) throws AppInstallException {
try {
app.install(this);
} catch (AppInstallException e) {
if (app.getAppFile() != null) {
app.getAppFile().delete();
}
throw new AppInstallException(e.getMessage());
}
// For bundle apps, remove temporary files from Karaf deploy directory on exit
if (app instanceof BundleApp) {
File temporaryInstallFile = ((BundleApp) app).getAppTemporaryInstallFile();
if (temporaryInstallFile != null) {
// temporaryInstallFile.deleteOnExit();
}
}
// Let the listeners know that an app has been installed
fireAppsChangedEvent();
}
/**
* Uninstalls an app. If it was located in the subdirectory containing currently installed apps in the
* local storage directory, it will be moved to the subdirectory containing currently uninstalled apps.
*
* The app will only be uninstalled if it is currently installed.
*
* @param app The app to be uninstalled.
* @throws AppUninstallException If there was an error while attempting to uninstall the app such as
* attempting to uninstall an app that isn't installed, or being unable to move the app to the uninstalled
* apps directory
*/
public void uninstallApp(App app) throws AppUninstallException {
app.uninstall(this);
// Let the listeners know that an app has been uninstalled
fireAppsChangedEvent();
}
public void disableApp(App app) {
// Let the listeners know that an app has been disabled
fireAppsChangedEvent();
}
private void fireAppsChangedEvent() {
AppsChangedEvent appEvent = new AppsChangedEvent(this);
for (AppsChangedListener appListener : appListeners) {
appListener.appsChanged(appEvent);
}
}
/**
* Return the set of all apps registered to this app manager.
* @return The set of all apps registered to this app manager.
*/
public Set<App> getApps() {
return apps;
}
/**
* Return the path of the directory used to contain all apps.
* @return The path of the root directory containing all installed and uninstalled apps.
*/
private File getBaseAppPath() {
File baseAppPath = null;
// TODO: At time of writing, CyApplicationConfiguration always returns the home directory for directory location.
try {
baseAppPath = new File(applicationConfiguration.getConfigurationDirectoryLocation().getCanonicalPath()
+ File.separator + APPS_DIRECTORY_NAME);
} catch (IOException e) {
throw new RuntimeException("Unabled to obtain canonical path for Cytoscape local storage directory: " + e.getMessage());
}
return baseAppPath;
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing installed apps.
* @return The canonical path of the subdirectory in the local storage directory containing currently installed apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getInstalledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + INSTALLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to installed apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing disabled apps.
* @return The canonical path of the subdirectory in the local storage directory containing disabled apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getDisabledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + DISABLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to disabled apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the temporary directory in the local storage directory used to contain apps that
* are currently loaded.
* @return The canonical path of the temporary directory containing apps with classes that are loaded.
*/
public String getTemporaryInstallPath() {
File path = new File(getBaseAppPath() + File.separator + TEMPORARY_LOADED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain canonical path to the temporary installed apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing uninstalled apps.
* @return The canonical path of the subdirectory in the local storage directory containing uninstalled apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getUninstalledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + UNINSTALLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to uninstalled apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory used to temporarily store
* apps downloaded from the app store.
* @return The canonical path of the subdirectory in the local storage directory temporarily
* storing apps downloaded from the app store.
*/
public String getDownloadedAppsPath() {
File path = new File(getBaseAppPath() + File.separator + DOWNLOADED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to downloaded apps directory");
return path.getAbsolutePath();
}
}
public String getKarafDeployDirectory() {
String current = System.getProperties().get("cytoscape.home").toString();
String deployDirectoryPath = current + File.separator + "framework"
+ File.separator + "deploy";
return deployDirectoryPath;
}
public void cleanKarafDeployDirectory() {
String[] bundleAppExtensions = new String[]{"kar"};
File karafDeployDirectory = new File(getKarafDeployDirectory());
Collection<File> files = FileUtils.listFiles(karafDeployDirectory, bundleAppExtensions, false);
for (File potentialApp : files) {
if (checkIfCytoscapeApp(potentialApp)) {
DebugHelper.print("Cleaning: " + potentialApp.getName());
potentialApp.delete();
}
}
}
private boolean checkIfCytoscapeApp(File file) {
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
// Check the manifest file
if (manifest != null) {
if (manifest.getMainAttributes().getValue("Cytoscape-App-Name") != null) {
jarFile.close();
return true;
}
}
jarFile.close();
} catch (ZipException e) {
// Do nothing; skip file
// e.printStackTrace();
} catch (IOException e) {
// Do nothing; skip file
// e.printStackTrace();
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
}
}
}
return false;
}
/**
* Removes the temporary app download directory and the directory used to store uninstalled apps.
*/
public void purgeTemporaryDirectories() {
File downloaded = new File(getDownloadedAppsPath());
File uninstalled = new File(getUninstalledAppsPath());
File temporaryInstall = new File(getTemporaryInstallPath());
try {
FileUtils.deleteDirectory(downloaded);
FileUtils.deleteDirectory(uninstalled);
FileUtils.deleteDirectory(temporaryInstall);
} catch (IOException e) {
logger.warn("Unable to completely remove temporary directories for downloaded, loaded, and uninstalled apps.");
}
}
private void installAppsInDirectory(File directory, boolean ignoreDuplicateBundleApps) {
// Temporary fix to get the App Manager working--this should be removed later (Samad)
if (!directory.exists()) {
logger.error("Attempting to load from a directory that does not exist: " + directory.getAbsolutePath());
return;
}
// Parse App objects from the given directory
Set<App> parsedApps = obtainAppsFromDirectory(directory, ignoreDuplicateBundleApps);
// Install each app
for (App parsedApp : parsedApps) {
try {
installApp(parsedApp);
} catch (AppInstallException e) {
logger.warn("Unable to install app from installed apps directory: " + e.getMessage());
}
}
DebugHelper.print("Number of apps installed from directory: " + parsedApps.size());
}
/**
* Obtain a set of {@link App} objects through attempting to parse files found in the first level of the given directory.
* @param directory The directory used to parse {@link App} objects
* @return A set of all {@link App} objects that were successfully parsed from files in the given directory
*/
private Set<App> obtainAppsFromDirectory(File directory, boolean ignoreDuplicateBundleApps) {
// Obtain all files in the given directory with supported extensions, perform a non-recursive search
Collection<File> files = FileUtils.listFiles(directory, APP_EXTENSIONS, false);
Set<App> parsedApps = new HashSet<App>();
String karafDeployDirectory = getKarafDeployDirectory();
App app;
for (File potentialApp : files) {
if (ignoreDuplicateBundleApps
&& (new File(karafDeployDirectory + File.separator + potentialApp.getName())).exists()) {
// Skip file
} else {
app = null;
try {
app = appParser.parseApp(potentialApp);
} catch (AppParsingException e) {
DebugHelper.print("Failed to parse " + potentialApp + ", error: " + e.getMessage());
} finally {
if (app != null) {
parsedApps.add(app);
DebugHelper.print("App parsed: " + app);
}
}
}
}
return parsedApps;
}
/**
* Create app storage directories if they don't already exist.
*/
private void initializeAppsDirectories() {
boolean created = true;
File appDirectory = getBaseAppPath();
if (!appDirectory.exists()) {
created = created && appDirectory.mkdirs();
logger.info("Creating " + appDirectory + ". Success? " + created);
}
File installedDirectory = new File(getInstalledAppsPath());
if (!installedDirectory.exists()) {
created = created && installedDirectory.mkdirs();
logger.info("Creating " + installedDirectory + ". Success? " + created);
}
File disabledDirectory = new File(getDisabledAppsPath());
if (!disabledDirectory.exists()) {
created = created && disabledDirectory.mkdirs();
logger.info("Creating " + disabledDirectory + ". Success? " + created);
}
File temporaryInstallDirectory = new File(getTemporaryInstallPath());
if (!temporaryInstallDirectory.exists()) {
created = created && temporaryInstallDirectory.mkdirs();
logger.info("Creating " + temporaryInstallDirectory + ". Success? " + created);
}
File uninstalledDirectory = new File(getUninstalledAppsPath());
if (!uninstalledDirectory.exists()) {
created = created && uninstalledDirectory.mkdirs();
logger.info("Creating " + uninstalledDirectory + ". Success? " + created);
}
File downloadedDirectory = new File(getDownloadedAppsPath());
if (!downloadedDirectory.exists()) {
created = created && downloadedDirectory.mkdirs();
}
if (!created) {
logger.error("Failed to create local app storage directories.");
}
}
public void addAppListener(AppsChangedListener appListener) {
appListeners.add(appListener);
}
public void removeAppListener(AppsChangedListener appListener) {
appListeners.remove(appListener);
}
/**
* Install apps from the local storage directory containing previously installed apps.
*/
public void installAppsFromDirectory() {
installAppsInDirectory(new File(getInstalledAppsPath()), false);
}
}
| app-impl/src/main/java/org/cytoscape/app/internal/manager/AppManager.java | package org.cytoscape.app.internal.manager;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService;
import org.cytoscape.app.AbstractCyApp;
import org.cytoscape.app.CyAppAdapter;
import org.cytoscape.app.internal.event.AppsChangedEvent;
import org.cytoscape.app.internal.event.AppsChangedListener;
import org.cytoscape.app.internal.exception.AppInstallException;
import org.cytoscape.app.internal.exception.AppParsingException;
import org.cytoscape.app.internal.exception.AppUninstallException;
import org.cytoscape.app.internal.manager.App.AppStatus;
import org.cytoscape.app.internal.net.WebQuerier;
import org.cytoscape.application.CyApplicationConfiguration;
import org.cytoscape.app.internal.net.server.LocalHttpServer;
import org.cytoscape.app.internal.util.DebugHelper;
import org.cytoscape.app.swing.CySwingAppAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents an App Manager, which is capable of maintaining a list of all currently installed and available apps. The class
* also provides functionalities for installing and uninstalling apps.
*/
public class AppManager {
private static final Logger logger = LoggerFactory.getLogger(AppManager.class);
/** Only files with these extensions are checked when looking for apps in a given subdirectory.
*/
private static final String[] APP_EXTENSIONS = {"jar", "kar"};
/** Installed apps are moved to this subdirectory under the local app storage directory. */
private static final String INSTALLED_APPS_DIRECTORY_NAME = "installed";
/** Uninstalled apps are moved to this subdirectory under the local app storage directory. */
private static final String UNINSTALLED_APPS_DIRECTORY_NAME = "uninstalled";
/** Disabled apps are moved to this subdirectory under the local app storage directory. */
private static final String DISABLED_APPS_DIRECTORY_NAME = "disabled";
/** Apps are downloaded from the web store to this subdirectory under local app storage directory. */
private static final String DOWNLOADED_APPS_DIRECTORY_NAME = "download-temp";
/** Apps that are loaded are stored in this temporary directory. */
private static final String TEMPORARY_LOADED_APPS_DIRECTORY_NAME = ".temp-installed";
/** This subdirectory in the local Cytoscape storage directory is used to store app data, as
* well as installed and uninstalled apps. */
private static final String APPS_DIRECTORY_NAME = "3.0/apps";
/** The set of all apps, represented by {@link App} objects, registered to this App Manager. */
private Set<App> apps;
private Set<AppsChangedListener> appListeners;
/** An {@link AppParser} object used to parse File objects and possibly URLs into {@link App} objects
* into a format we can more easily work with
*/
private AppParser appParser;
/**
* A reference to the {@link WebQuerier} object used to make queries to the app store website.
*/
private WebQuerier webQuerier;
/**
* The {@link FeaturesService} used to communicate with Apache Karaf to manage OSGi bundle based apps
*/
private FeaturesService featuresService;
// private KarService karService;
/**
* {@link CyApplicationConfiguration} service used to obtain the directories used to store the apps.
*/
private CyApplicationConfiguration applicationConfiguration;
/**
* The {@link CySwingAppAdapter} service reference provided to the constructor of the app's {@link AbstractCyApp}-implementing class.
*/
private CySwingAppAdapter swingAppAdapter;
private FileAlterationMonitor fileAlterationMonitor;
/**
* A {@link FileFilter} that accepts only files in the first depth level of a given directory
*/
private class SingleLevelFileFilter implements FileFilter {
private File parentDirectory;
public SingleLevelFileFilter(File parentDirectory) {
this.parentDirectory = parentDirectory;
}
@Override
public boolean accept(File pathName) {
if (!pathName.getParentFile().equals(parentDirectory)) {
return false;
} else if (pathName.isDirectory()) {
return false;
}
return true;
}
}
public AppManager(CySwingAppAdapter swingAppAdapter, CyApplicationConfiguration applicationConfiguration,
final WebQuerier webQuerier, FeaturesService featuresService) {
this.applicationConfiguration = applicationConfiguration;
this.swingAppAdapter = swingAppAdapter;
this.webQuerier = webQuerier;
this.featuresService = featuresService;
apps = new HashSet<App>();
appParser = new AppParser();
// cleanKarafDeployDirectory();
purgeTemporaryDirectories();
initializeAppsDirectories();
setupAlterationMonitor();
this.appListeners = new HashSet<AppsChangedListener>();
// Install previously enabled apps
installAppsInDirectory(new File(getKarafDeployDirectory()), false);
installAppsInDirectory(new File(getInstalledAppsPath()), true);
// Load apps from the "uninstalled apps" directory
Set<App> uninstalledApps = obtainAppsFromDirectory(new File(getUninstalledAppsPath()), true);
apps.addAll(uninstalledApps);
DebugHelper.print(this, "config dir: " + applicationConfiguration.getConfigurationDirectoryLocation());
}
public FeaturesService getFeaturesService() {
return this.featuresService;
}
public void setFeaturesService(FeaturesService featuresService) {
this.featuresService = featuresService;
}
private void setupAlterationMonitor() {
// Set up the FileAlterationMonitor to install/uninstall apps when apps are moved in/out of the
// installed/uninstalled app directories
fileAlterationMonitor = new FileAlterationMonitor(30000L);
File installedAppsPath = new File(getInstalledAppsPath());
FileAlterationObserver installAlterationObserver = new FileAlterationObserver(
installedAppsPath, new SingleLevelFileFilter(installedAppsPath), IOCase.SYSTEM);
// Listen for events on the "installed apps" folder
installAlterationObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileDelete(File file) {
DebugHelper.print("Install directory file deleted");
try {
String canonicalPath = file.getCanonicalPath();
for (App app : apps) {
File appFile = app.getAppFile();
if (appFile != null
&& appFile.getCanonicalPath().equals(canonicalPath)) {
app.setAppFile(new File(getUninstalledAppsPath() + File.separator + appFile.getName()));
try {
uninstallApp(app);
} catch (AppUninstallException e) {
logger.warn("Failed to uninstall app " + app.getAppName() + " when it was removed from the local install directory.");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFileCreate(File file) {
DebugHelper.print("Install directory file created");
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
installApp(parsedApp);
DebugHelper.print("Installed: " + parsedApp.getAppName());
} catch (AppParsingException e) {
DebugHelper.print("Failed to parse: " + file.getName());
} catch (AppInstallException e) {
DebugHelper.print("Failed to install: " + parsedApp.getAppName());
}
}
@Override
public void onFileChange(File file) {
}
});
setupKarafDeployMonitor(fileAlterationMonitor);
try {
//installAlterationObserver.initialize();
//fileAlterationMonitor.addObserver(installAlterationObserver);
fileAlterationMonitor.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setupKarafDeployMonitor(FileAlterationMonitor fileAlterationMonitor) {
// Set up the FileAlterationMonitor to install/uninstall bundle apps when they are moved
// to the Karaf deploy directory
File karafDeployPath = new File(getKarafDeployDirectory());
FileAlterationObserver karafDeployObserver = new FileAlterationObserver(
karafDeployPath, new SingleLevelFileFilter(karafDeployPath), IOCase.SYSTEM);
karafDeployObserver.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileDelete(File file) {
for (App app : getApps()) {
if (app.getAppTemporaryInstallFile().equals(file)) {
try {
uninstallApp(app);
} catch (AppUninstallException e) {
logger.warn("Failed to uninstall app that was removed from Karaf deploy directory: " + app.getAppName());
}
}
}
}
@Override
public void onFileCreate(File file) {
//System.out.println("File found: " + file);
if (checkIfCytoscapeApp(file)) {
//System.out.println("File was app: " + file);
App parsedApp = null;
try {
parsedApp = appParser.parseApp(file);
if (parsedApp instanceof SimpleApp) {
logger.warn("A simple app " + file.getName() + " was moved to the "
+ "framework/deploy directory. It should be installed via the "
+ "app manager. Installing anyway..");
}
//System.out.println("App was parsed: " + file);
installApp(parsedApp);
//System.out.println("App was installed: " + file);
} catch (AppParsingException e) {
logger.error("Failed to parse app that was moved to Karaf deploy directory: " + file.getName()
+ ". The error was: " + e.getMessage());
} catch (AppInstallException e) {
logger.error("Failed to register app with app manager: " + file.getName()
+ ". The error was:" + e.getMessage());
}
}
}
});
try {
//karafDeployObserver.initialize();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileAlterationMonitor.addObserver(karafDeployObserver);
}
public CySwingAppAdapter getSwingAppAdapter() {
return swingAppAdapter;
}
public AppParser getAppParser() {
return appParser;
}
public WebQuerier getWebQuerier() {
return webQuerier;
}
/**
* Registers an app to this app manager.
* @param app The app to register to this manager.
*/
public void addApp(App app) {
apps.add(app);
/*
// Let the listeners know that an app has changed
for (AppsChangedListener appListener : appListeners) {
AppsChangedEvent appEvent = new AppsChangedEvent(this);
appListener.appsChanged(appEvent);
}
*/
}
/**
* Removes an app from this app manager.
* @param app The app to remove
*/
public void removeApp(App app) {
apps.remove(app);
}
/**
* Attempts to install an app. Makes a copy of the app file and places it in the directory
* used to hold all installed and uninstalled apps, if it was not already present there. Then, the
* app is created by instancing its class that extends {@link AbstractCyApp}.
*
* Before the app is installed, it is checked if it contains valid packaging by its isAppValidated() method.
* Apps that have not been validated are ignored. Also, apps that are already installed are left alone.
*
* @param app The {@link App} object representing and providing information about the app to install
* @throws AppInstallException If there was an error while attempting to install the app such as being
* unable to copy the app to the installed apps directory or to instance the app's entry point class
*/
public void installApp(App app) throws AppInstallException {
try {
app.install(this);
} catch (AppInstallException e) {
if (app.getAppFile() != null) {
app.getAppFile().delete();
}
throw new AppInstallException(e.getMessage());
}
// For bundle apps, remove temporary files from Karaf deploy directory on exit
if (app instanceof BundleApp) {
File temporaryInstallFile = ((BundleApp) app).getAppTemporaryInstallFile();
if (temporaryInstallFile != null) {
// temporaryInstallFile.deleteOnExit();
}
}
// Let the listeners know that an app has been installed
fireAppsChangedEvent();
}
/**
* Uninstalls an app. If it was located in the subdirectory containing currently installed apps in the
* local storage directory, it will be moved to the subdirectory containing currently uninstalled apps.
*
* The app will only be uninstalled if it is currently installed.
*
* @param app The app to be uninstalled.
* @throws AppUninstallException If there was an error while attempting to uninstall the app such as
* attempting to uninstall an app that isn't installed, or being unable to move the app to the uninstalled
* apps directory
*/
public void uninstallApp(App app) throws AppUninstallException {
app.uninstall(this);
// Let the listeners know that an app has been uninstalled
fireAppsChangedEvent();
}
public void disableApp(App app) {
// Let the listeners know that an app has been disabled
fireAppsChangedEvent();
}
private void fireAppsChangedEvent() {
AppsChangedEvent appEvent = new AppsChangedEvent(this);
for (AppsChangedListener appListener : appListeners) {
appListener.appsChanged(appEvent);
}
}
/**
* Return the set of all apps registered to this app manager.
* @return The set of all apps registered to this app manager.
*/
public Set<App> getApps() {
return apps;
}
/**
* Return the path of the directory used to contain all apps.
* @return The path of the root directory containing all installed and uninstalled apps.
*/
private File getBaseAppPath() {
File baseAppPath = null;
// TODO: At time of writing, CyApplicationConfiguration always returns the home directory for directory location.
try {
baseAppPath = new File(applicationConfiguration.getConfigurationDirectoryLocation().getCanonicalPath()
+ File.separator + APPS_DIRECTORY_NAME);
} catch (IOException e) {
throw new RuntimeException("Unabled to obtain canonical path for Cytoscape local storage directory: " + e.getMessage());
}
return baseAppPath;
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing installed apps.
* @return The canonical path of the subdirectory in the local storage directory containing currently installed apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getInstalledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + INSTALLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to installed apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing disabled apps.
* @return The canonical path of the subdirectory in the local storage directory containing disabled apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getDisabledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + DISABLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to disabled apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the temporary directory in the local storage directory used to contain apps that
* are currently loaded.
* @return The canonical path of the temporary directory containing apps with classes that are loaded.
*/
public String getTemporaryInstallPath() {
File path = new File(getBaseAppPath() + File.separator + TEMPORARY_LOADED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain canonical path to the temporary installed apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory containing uninstalled apps.
* @return The canonical path of the subdirectory in the local storage directory containing uninstalled apps,
* or <code>null</code> if there was an error obtaining the canonical path.
*/
public String getUninstalledAppsPath() {
File path = new File(getBaseAppPath() + File.separator + UNINSTALLED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to uninstalled apps directory");
return path.getAbsolutePath();
}
}
/**
* Return the canonical path of the subdirectory in the local storage directory used to temporarily store
* apps downloaded from the app store.
* @return The canonical path of the subdirectory in the local storage directory temporarily
* storing apps downloaded from the app store.
*/
public String getDownloadedAppsPath() {
File path = new File(getBaseAppPath() + File.separator + DOWNLOADED_APPS_DIRECTORY_NAME);
try {
// Create the directory if it doesn't exist
if (!path.exists()) {
path.mkdirs();
}
return path.getCanonicalPath();
} catch (IOException e) {
logger.warn("Failed to obtain path to downloaded apps directory");
return path.getAbsolutePath();
}
}
public String getKarafDeployDirectory() {
String current = System.getProperties().get("user.dir").toString();
String deployDirectoryPath = current + File.separator + "framework"
+ File.separator + "deploy";
return deployDirectoryPath;
}
public void cleanKarafDeployDirectory() {
String[] bundleAppExtensions = new String[]{"kar"};
File karafDeployDirectory = new File(getKarafDeployDirectory());
Collection<File> files = FileUtils.listFiles(karafDeployDirectory, bundleAppExtensions, false);
for (File potentialApp : files) {
if (checkIfCytoscapeApp(potentialApp)) {
DebugHelper.print("Cleaning: " + potentialApp.getName());
potentialApp.delete();
}
}
}
private boolean checkIfCytoscapeApp(File file) {
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
// Check the manifest file
if (manifest != null) {
if (manifest.getMainAttributes().getValue("Cytoscape-App-Name") != null) {
jarFile.close();
return true;
}
}
jarFile.close();
} catch (ZipException e) {
// Do nothing; skip file
// e.printStackTrace();
} catch (IOException e) {
// Do nothing; skip file
// e.printStackTrace();
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
}
}
}
return false;
}
/**
* Removes the temporary app download directory and the directory used to store uninstalled apps.
*/
public void purgeTemporaryDirectories() {
File downloaded = new File(getDownloadedAppsPath());
File uninstalled = new File(getUninstalledAppsPath());
File temporaryInstall = new File(getTemporaryInstallPath());
try {
FileUtils.deleteDirectory(downloaded);
FileUtils.deleteDirectory(uninstalled);
FileUtils.deleteDirectory(temporaryInstall);
} catch (IOException e) {
logger.warn("Unable to completely remove temporary directories for downloaded, loaded, and uninstalled apps.");
}
}
private void installAppsInDirectory(File directory, boolean ignoreDuplicateBundleApps) {
// Temporary fix to get the App Manager working--this should be removed later (Samad)
if (!directory.exists()) {
logger.error("Attempting to load from a directory that does not exist: " + directory.getAbsolutePath());
return;
}
// Parse App objects from the given directory
Set<App> parsedApps = obtainAppsFromDirectory(directory, ignoreDuplicateBundleApps);
// Install each app
for (App parsedApp : parsedApps) {
try {
installApp(parsedApp);
} catch (AppInstallException e) {
logger.warn("Unable to install app from installed apps directory: " + e.getMessage());
}
}
DebugHelper.print("Number of apps installed from directory: " + parsedApps.size());
}
/**
* Obtain a set of {@link App} objects through attempting to parse files found in the first level of the given directory.
* @param directory The directory used to parse {@link App} objects
* @return A set of all {@link App} objects that were successfully parsed from files in the given directory
*/
private Set<App> obtainAppsFromDirectory(File directory, boolean ignoreDuplicateBundleApps) {
// Obtain all files in the given directory with supported extensions, perform a non-recursive search
Collection<File> files = FileUtils.listFiles(directory, APP_EXTENSIONS, false);
Set<App> parsedApps = new HashSet<App>();
String karafDeployDirectory = getKarafDeployDirectory();
App app;
for (File potentialApp : files) {
if (ignoreDuplicateBundleApps
&& (new File(karafDeployDirectory + File.separator + potentialApp.getName())).exists()) {
// Skip file
} else {
app = null;
try {
app = appParser.parseApp(potentialApp);
} catch (AppParsingException e) {
DebugHelper.print("Failed to parse " + potentialApp + ", error: " + e.getMessage());
} finally {
if (app != null) {
parsedApps.add(app);
DebugHelper.print("App parsed: " + app);
}
}
}
}
return parsedApps;
}
/**
* Create app storage directories if they don't already exist.
*/
private void initializeAppsDirectories() {
boolean created = true;
File appDirectory = getBaseAppPath();
if (!appDirectory.exists()) {
created = created && appDirectory.mkdirs();
logger.info("Creating " + appDirectory + ". Success? " + created);
}
File installedDirectory = new File(getInstalledAppsPath());
if (!installedDirectory.exists()) {
created = created && installedDirectory.mkdirs();
logger.info("Creating " + installedDirectory + ". Success? " + created);
}
File disabledDirectory = new File(getDisabledAppsPath());
if (!disabledDirectory.exists()) {
created = created && disabledDirectory.mkdirs();
logger.info("Creating " + disabledDirectory + ". Success? " + created);
}
File temporaryInstallDirectory = new File(getTemporaryInstallPath());
if (!temporaryInstallDirectory.exists()) {
created = created && temporaryInstallDirectory.mkdirs();
logger.info("Creating " + temporaryInstallDirectory + ". Success? " + created);
}
File uninstalledDirectory = new File(getUninstalledAppsPath());
if (!uninstalledDirectory.exists()) {
created = created && uninstalledDirectory.mkdirs();
logger.info("Creating " + uninstalledDirectory + ". Success? " + created);
}
File downloadedDirectory = new File(getDownloadedAppsPath());
if (!downloadedDirectory.exists()) {
created = created && downloadedDirectory.mkdirs();
}
if (!created) {
logger.error("Failed to create local app storage directories.");
}
}
public void addAppListener(AppsChangedListener appListener) {
appListeners.add(appListener);
}
public void removeAppListener(AppsChangedListener appListener) {
appListeners.remove(appListener);
}
/**
* Install apps from the local storage directory containing previously installed apps.
*/
public void installAppsFromDirectory() {
installAppsInDirectory(new File(getInstalledAppsPath()), false);
}
}
| Gets the deploy directory based off the cytoscape.home system property
| app-impl/src/main/java/org/cytoscape/app/internal/manager/AppManager.java | Gets the deploy directory based off the cytoscape.home system property | <ide><path>pp-impl/src/main/java/org/cytoscape/app/internal/manager/AppManager.java
<ide>
<ide>
<ide> public String getKarafDeployDirectory() {
<del> String current = System.getProperties().get("user.dir").toString();
<add> String current = System.getProperties().get("cytoscape.home").toString();
<ide>
<ide> String deployDirectoryPath = current + File.separator + "framework"
<ide> + File.separator + "deploy"; |
|
JavaScript | mit | 6f966ba7bc931e45fdf62e452c9d9a2ed2f441ba | 0 | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | angular.module('materialscommons').component('mcAccountSettingsApikey', {
template: require('./mc-account-settings-apikey.html'),
controller: MCAccountSettingsApikeyComponentController
});
/*@ngInect*/
function MCAccountSettingsApikeyComponentController(mcapi, User, Restangular) {
const ctrl = this;
ctrl.showKey = false;
ctrl.showHideButtonText = "Show API Key";
ctrl.apikey = User.apikey();
ctrl.showAPIKey = showAPIKey;
ctrl.resetAPIKey = resetAPIKey;
//////////////////
function showAPIKey() {
ctrl.showKey = !ctrl.showKey;
if (!ctrl.showKey) {
ctrl.showHideButtonText = "Show API Key";
} else {
ctrl.showHideButtonText = "Hide API Key";
}
}
function resetAPIKey() {
mcapi('/user/%/apikey/reset', User.u())
.success(function(data) {
User.reset_apikey(data.apikey);
ctrl.apikey = data.apikey;
Restangular.setDefaultRequestParams({apikey: User.apikey()});
}).put();
}
}
| website/src/app/components/accounts/mc-account-settings/mc-account-settings-apikey.component.js | angular.module('materialscommons').component('mcAccountSettingsApikey', {
template: require('./mc-account-settings-apikey.html'),
controller: MCAccountSettingsApikeyComponentController
});
/*@ngInect*/
function MCAccountSettingsApikeyComponentController(mcapi, User) {
const ctrl = this;
ctrl.showKey = false;
ctrl.showHideButtonText = "Show API Key";
ctrl.apikey = User.apikey();
ctrl.showAPIKey = showAPIKey;
ctrl.resetAPIKey = resetAPIKey;
//////////////////
function showAPIKey() {
ctrl.showKey = !ctrl.showKey;
if (!ctrl.showKey) {
ctrl.showHideButtonText = "Show API Key";
} else {
ctrl.showHideButtonText = "Hide API Key";
}
}
function resetAPIKey() {
mcapi('/user/%/apikey/reset', User.u())
.success(function(data) {
User.reset_apikey(data.apikey);
}).put();
}
}
| Update state of component when changing the apikey and also reset default params for Restangular to the new apikey
| website/src/app/components/accounts/mc-account-settings/mc-account-settings-apikey.component.js | Update state of component when changing the apikey and also reset default params for Restangular to the new apikey | <ide><path>ebsite/src/app/components/accounts/mc-account-settings/mc-account-settings-apikey.component.js
<ide> });
<ide>
<ide> /*@ngInect*/
<del>function MCAccountSettingsApikeyComponentController(mcapi, User) {
<add>function MCAccountSettingsApikeyComponentController(mcapi, User, Restangular) {
<ide> const ctrl = this;
<ide>
<ide> ctrl.showKey = false;
<ide> mcapi('/user/%/apikey/reset', User.u())
<ide> .success(function(data) {
<ide> User.reset_apikey(data.apikey);
<add> ctrl.apikey = data.apikey;
<add> Restangular.setDefaultRequestParams({apikey: User.apikey()});
<ide> }).put();
<ide> }
<ide> } |
|
Java | mit | ada189832e1f2bd6a4e569bc14a6d7d58a382cf9 | 0 | RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017,RobotCasserole1736/RobotCasserole2017 | package org.usfirst.frc.team1736.lib.CasserolePID;
import java.util.Timer;
import java.util.TimerTask;
import org.usfirst.frc.team1736.lib.SignalMath.DerivativeCalculator;
import org.usfirst.frc.team1736.lib.SignalMath.IntegralCalculator;
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) FRC Team 1736 2016. See the License file.
//
// Can you use this code? Sure! We're releasing this under GNUV3, which
// basically says you can take, modify, share, publish this as much as you
// want, as long as you don't make it closed source.
//
// If you do find it useful, we'd love to hear about it! Check us out at
// http://robotcasserole.org/ and leave us a message!
///////////////////////////////////////////////////////////////////////////////
/**
* DESCRIPTION: <br>
* PID Controller algorithm designed by FRC1736 Robot Casserole. The WPIlib PID library is pretty
* darn good, but we had some things we wanted done differently. Therefore, we did it ourselves.
* <br>
* This controller implements a "PIDFdFP2" controller, with a few selectable options. Execution runs
* at 10ms (2x speed of *periodic() loops from FRC), this will be made adjustable in the future.
* Output each loop is simply the sum of each term, with not memory of previous outputs (except in
* the integral term). Output can be capped to a specific range, and the integral term can turn
* itself off when the error is too big (prevents windup). More features to be added in the future!
* <br>
* TERMS IN CALCULATION:
* <ul>
* <li><b>Proportional</b> - The error, equal to "setpoint - actual", multiplied by a gain. The
* simplest form of feedback, should push a system toward the setpoint.</li>
* <li><b>Integral</b> - The integral of the error over time, multiplied by a gain. Helps with
* correcting for small errors that exist over longer periods of time, when the P term alone is not
* sufficient.</li>
* <li><b>Derivative</b> - The derivative of the error, or of the actual value(user selects),
* multiplied by a gain. Helps to rate-limit the P term's action to reduce overshoot and increase
* stability (to a point).</li>
* <li><b>Feed-Forward</b> - The setpoint, multiplied by a gain. Helps get the system to a zero
* error state for systems where there is a linear relationship between setpoint and "ideal system"
* control value (Think shooter wheel - more motor command means more speed. For a speed-based
* setpoint, there is a linear relationship between control effort (motor command) and setpoint)
* </li>
* <li><b>Feed-Forward</b> - The setpoint's derivative, multiplied by a gain. Helps in scenarios
* where when the setpoint changes, it's useful to give the system a single "knock". Think using a
* motor to control to a certain angle - you'll need lots of effort when the setpoint first changes,
* but ideally no effort once you've gotten to the right place.</li>
* <li><b>Proportional Squared</b> - The error squared but with sign preserved, multiplied by a
* gain. Helpful in non-linear systems, and when you can afford to be very aggressive when error is
* large.</li>
* </ul>
* USAGE:
* <ol>
* <li>Create new class as a super of this one</li>
* <li>Override methods to set PID output and return feedback to the algorithm.</li>
* <li>Call start() method to begin background execution of algorithm.</li>
* </ol>
*
*
*/
public abstract class CasserolePID {
// PID Gain constants
protected double Kp; // Proportional
protected double Ki; // Integral
protected double Kd; // Derivative
protected double Kf; // Setpoint Feed-Forward
protected double Kdf; // Setpoint Derivative Feed-Forward
protected double Kp2; // Proportional Squared
protected boolean useErrForDerivTerm; // If true, derivative term is calculated using the error
// signal. Otherwise, use the "actual" value from the PID
// system.
// Things for doing math
DerivativeCalculator dTermDeriv;
DerivativeCalculator setpointDeriv;
IntegralCalculator iTermIntegral;
public volatile double setpoint;
// Value limiters
protected double outputMin; // output limit
protected double outputMax;
protected double integratorDisableThresh; // If the abs val of the error goes above this,
// disable and reset the integrator to prevent windup
// PID Thread
private Timer timerThread;
// Thread frequency
private final long pidSamplePeriod_ms = 10;
// Watchdog Counter - counts up every time we run a periodic loop.
// An external obesrver can check this for positive verification the
// PID loop is still alive.
protected volatile long watchdogCounter;
/**
* Simple Constructor
*
* @param Kp_in Proportional Term Gain
* @param Ki_in Integral Term Gain
* @param Kd_in Derivative Term Gain
*/
protected CasserolePID(double Kp_in, double Ki_in, double Kd_in) {
Kp = Kp_in;
Ki = Ki_in;
Kd = Kd_in;
Kf = 0.0;
Kdf = 0.0;
Kp2 = 0.0;
commonConstructor();
}
/**
* More-Complex Constructor
*
* @param Kp_in Proportional Term Gain
* @param Ki_in Integral Term Gain
* @param Kd_in Derivative Term Gain
* @param Kf_in Setpoint Feed-Forward Term Gain
* @param Kdf_in Setpoint Derivative Feed-Forward Term Gain
* @param Kp2_in Proportional Squared Term Gain
*/
protected CasserolePID(double Kp_in, double Ki_in, double Kd_in, double Kf_in, double Kdf_in, double Kp2_in) {
Kp = Kp_in;
Ki = Ki_in;
Kd = Kd_in;
Kf = Kf_in;
Kdf = Kdf_in;
Kp2 = Kp2_in;
commonConstructor();
}
// Do the rest of the construction things, like setting defaults
private void commonConstructor() {
dTermDeriv = new DerivativeCalculator();
setpointDeriv = new DerivativeCalculator();
iTermIntegral = new IntegralCalculator(1);
useErrForDerivTerm = true;
outputMin = Double.NEGATIVE_INFINITY;
outputMax = Double.POSITIVE_INFINITY;
integratorDisableThresh = Double.POSITIVE_INFINITY;
setpoint = 0;
timerThread = new java.util.Timer();
}
/**
* Start the PID thread running. Will begin to call the returnPIDInput and usePIDOutput methods
* asynchronously.
*/
public void start() {
resetIntegrators();
watchdogCounter = 0;
// Kick off the multi-threaded stuff.
// Will start calling the periodic update function at an interval of pidSamplePeriod_ms,
// asynchronously from any other code.
// Java magic here, don't touch!
timerThread.scheduleAtFixedRate(new PIDTask(this), 0L, (long) (pidSamplePeriod_ms));
}
/**
* Stop whatever thread may or may not be running. Will finish the current calculation loop, so
* returnPIDInput and usePIDOutput might get called one more time after this function gets
* called.
*/
public void stop() {
timerThread.cancel();
}
/**
* Reset all internal integrators back to zero. Useful for returning to init-state conditions.
*/
public void resetIntegrators() {
iTermIntegral.resetIntegral();
}
/**
* Assign a new setpoint for the algorithm to control to.
*/
public void setSetpoint(double setpoint_in) {
setpoint = setpoint_in;
}
/**
* Override this method! This function must be implemented to return the present "actual" value
* of the system under control. For example, when controlling a motor to turn a certain number
* of rotations, this should return the encoder count or number of degrees or something like
* that. You must implement this! Expect it to be called frequently and asynchronously by the
* underlying PID algorithm. Make sure it runs fast!
*
* @return The sensor feedback value for the PID algorithm to use.
*/
protected abstract double returnPIDInput();
/**
* Override this method! This function will return the value calculated from the PID. Expect it
* to be called frequently and asynchronously by the underlying PID algorithm. When it is
* called, you should utilize the value given to do something useful. For example, when
* controlling a motor to turn a certain number of rotations, your implementation of this
* function should send the output of the PID to one of the motor controllers. Make sure it runs
* fast!
*
* @param pidOutput The control effort output calculated by the PID algorithm
*/
protected abstract void usePIDOutput(double pidOutput);
// The big kahuna. This is where the magic happens.
protected void periodicUpdate() {
double curInput = returnPIDInput();
double curOutput = 0.0;
double curSetpoint = setpoint; // latch the setpoint at start of loop
double curError = curSetpoint - curInput;
// Calculate P term
if (Kp != 0.0) { // speed optimization when terms are turned off
curOutput = curOutput + curError * Kp;
}
// Calculate I term
if (Ki != 0.0) {
if (Math.abs(curError) > integratorDisableThresh) {
iTermIntegral.resetIntegral();
} else {
curOutput = curOutput + iTermIntegral.calcIntegral(curError) * Ki;
}
}
// Calculate D term
if (Kd != 0.0) {
if (useErrForDerivTerm) {
curOutput = curOutput + dTermDeriv.calcDeriv(curError) * Kd;
} else {
curOutput = curOutput + dTermDeriv.calcDeriv(curInput) * Kd;
}
}
// Calculate FF term
if (Kf != 0.0) {
curOutput = curOutput + curSetpoint * Kf;
}
// Calculate derivative FF term
if (Kdf != 0.0) {
curOutput = curOutput + setpointDeriv.calcDeriv(curSetpoint) * Kdf;
}
// Calculate P^2 term
if (Kp2 != 0.0) {
if (curError >= 0) {
curOutput = curOutput + curError * curError * Kp;
} else {
curOutput = curOutput - curError * curError * Kp;
}
}
// Assign output
if (curOutput > outputMax) {
usePIDOutput(outputMax);
} else if (curOutput < outputMin) {
usePIDOutput(outputMin);
} else {
usePIDOutput(curOutput);
}
// Indicate we are still doing stuff with the watchdog
watchdogCounter = watchdogCounter + 1;
}
// Java multithreading magic. Do not touch.
// Touching will incour the wrath of Cthulhu, god of java and PID.
// May the oceans of 1's and 0's rise to praise him.
private class PIDTask extends TimerTask {
private CasserolePID m_pid;
public PIDTask(CasserolePID pid) {
if (pid == null) {
throw new NullPointerException("Given PIDController was null");
}
m_pid = pid;
}
@Override
public void run() {
m_pid.periodicUpdate();
}
}
/**
* Call this method to set up the algorithm to utilize the error between setpoint and actual for
* the derivative term calculation.
*/
public void setErrorAsDerivTermSrc() {
useErrForDerivTerm = true;
}
/**
* Call this method to set up the algorithm to utilize only the actual (sensor feedback) value
* for the derivative term calculation.
*/
public void setActualAsDerivTermSrc() {
useErrForDerivTerm = false;
}
/**
* @return The present Proportional term gain
*/
public double getKp() {
return Kp;
}
/**
* @param kp the kp to set
*/
public void setKp(double kp) {
Kp = kp;
}
/**
* @return The present Integral term gain
*/
public double getKi() {
return Ki;
}
/**
* @param ki the ki to set
*/
public void setKi(double ki) {
Ki = ki;
}
/**
* @return The present Derivative term gain
*/
public double getKd() {
return Kd;
}
/**
* @param kd the kd to set
*/
public void setKd(double kd) {
Kd = kd;
}
/**
* @return The present feed-forward term gain
*/
public double getKf() {
return Kf;
}
/**
* @param kf the kf to set
*/
public void setKf(double kf) {
Kf = kf;
}
/**
* @return The present derivative feed-forward term gain
*/
public double getKdf() {
return Kdf;
}
/**
* @param kdf the kdf to set
*/
public void setKdf(double kdf) {
Kdf = kdf;
}
/**
* @return The present Proportional-squared term gain
*/
public double getKp2() {
return Kp2;
}
/**
* @param kp2 the kp2 to set
*/
public void setKp2(double kp2) {
Kp2 = kp2;
}
/**
* Set limits on what the control effort (output) can be commanded to.
*
* @param min Smallest allowed control effort
* @param max Largest allowed control effort
*/
public void setOutputRange(double min, double max) {
outputMin = min;
outputMax = max;
}
/**
* @return The present setpoint
*/
public double getSetpoint() {
return setpoint;
}
/**
* Set the Integral term disable threshold. If the absolute value of the error goes above this
* threshold, the integral term will be set to zero AND the integrators will internally reset
* their accumulators to zero. Once the error gets below this threshold, the integrators will
* resume integrating and contributing to the control effort. This is a mechanism to help
* prevent integrator windup in high-error conditions. By default it is disabled (threshold =
* positive infinity).
*
* @param integratorDisableThresh_in The new threshold to use.
*/
public void setintegratorDisableThresh(double integratorDisableThresh_in) {
integratorDisableThresh = integratorDisableThresh_in;
}
}
| EclipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/lib/CasserolePID/CasserolePID.java | package org.usfirst.frc.team1736.lib.CasserolePID;
import java.util.Timer;
import java.util.TimerTask;
import org.usfirst.frc.team1736.lib.SignalMath.DerivativeCalculator;
import org.usfirst.frc.team1736.lib.SignalMath.IntegralCalculator;
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) FRC Team 1736 2016. See the License file.
//
// Can you use this code? Sure! We're releasing this under GNUV3, which
// basically says you can take, modify, share, publish this as much as you
// want, as long as you don't make it closed source.
//
// If you do find it useful, we'd love to hear about it! Check us out at
// http://robotcasserole.org/ and leave us a message!
///////////////////////////////////////////////////////////////////////////////
/**
* DESCRIPTION: <br>
* PID Controller algorithm designed by FRC1736 Robot Casserole. The WPIlib PID library is pretty
* darn good, but we had some things we wanted done differently. Therefore, we did it ourselves.
* <br>
* This controller implements a "PIDFdFP2" controller, with a few selectable options. Execution runs
* at 10ms (2x speed of *periodic() loops from FRC), this will be made adjustable in the future.
* Output each loop is simply the sum of each term, with not memory of previous outputs (except in
* the integral term). Output can be capped to a specific range, and the integral term can turn
* itself off when the error is too big (prevents windup). More features to be added in the future!
* <br>
* TERMS IN CALCULATION:
* <ul>
* <li><b>Proportional</b> - The error, equal to "setpoint - actual", multiplied by a gain. The
* simplest form of feedback, should push a system toward the setpoint.</li>
* <li><b>Integral</b> - The integral of the error over time, multiplied by a gain. Helps with
* correcting for small errors that exist over longer periods of time, when the P term alone is not
* sufficient.</li>
* <li><b>Derivative</b> - The derivative of the error, or of the actual value(user selects),
* multiplied by a gain. Helps to rate-limit the P term's action to reduce overshoot and increase
* stability (to a point).</li>
* <li><b>Feed-Forward</b> - The setpoint, multiplied by a gain. Helps get the system to a zero
* error state for systems where there is a linear relationship between setpoint and "ideal system"
* control value (Think shooter wheel - more motor command means more speed. For a speed-based
* setpoint, there is a linear relationship between control effort (motor command) and setpoint)
* </li>
* <li><b>Feed-Forward</b> - The setpoint's derivative, multiplied by a gain. Helps in scenarios
* where when the setpoint changes, it's useful to give the system a single "knock". Think using a
* motor to control to a certain angle - you'll need lots of effort when the setpoint first changes,
* but ideally no effort once you've gotten to the right place.</li>
* <li><b>Proportional Squared</b> - The error squared but with sign preserved, multiplied by a
* gain. Helpful in non-linear systems, and when you can afford to be very aggressive when error is
* large.</li>
* </ul>
* USAGE:
* <ol>
* <li>Create new class as a super of this one</li>
* <li>Override methods to set PID output and return feedback to the algorithm.</li>
* <li>Call start() method to begin background execution of algorithm.</li>
* </ol>
*
*
*/
public abstract class CasserolePID {
// PID Gain constants
protected double Kp; // Proportional
protected double Ki; // Integral
protected double Kd; // Derivative
protected double Kf; // Setpoint Feed-Forward
protected double Kdf; // Setpoint Derivative Feed-Forward
protected double Kp2; // Proportional Squared
protected boolean useErrForDerivTerm; // If true, derivative term is calculated using the error
// signal. Otherwise, use the "actual" value from the PID
// system.
// Things for doing math
DerivativeCalculator dTermDeriv;
DerivativeCalculator setpointDeriv;
IntegralCalculator iTermIntegral;
public volatile double setpoint;
// Value limiters
protected double outputMin; // output limit
protected double outputMax;
protected double integratorDisableThresh; // If the abs val of the error goes above this,
// disable and reset the integrator to prevent windup
// PID Thread
private Timer timerThread;
// Thread frequency
private final long pidSamplePeriod_ms = 10;
// Watchdog Counter - counts up every time we run a periodic loop.
// An external obesrver can check this for positive verification the
// PID loop is still alive.
protected volatile long watchdogCounter;
/**
* Simple Constructor
*
* @param Kp_in Proportional Term Gain
* @param Ki_in Integral Term Gain
* @param Kd_in Derivative Term Gain
*/
CasserolePID(double Kp_in, double Ki_in, double Kd_in) {
Kp = Kp_in;
Ki = Ki_in;
Kd = Kd_in;
Kf = 0.0;
Kdf = 0.0;
Kp2 = 0.0;
commonConstructor();
}
/**
* More-Complex Constructor
*
* @param Kp_in Proportional Term Gain
* @param Ki_in Integral Term Gain
* @param Kd_in Derivative Term Gain
* @param Kf_in Setpoint Feed-Forward Term Gain
* @param Kdf_in Setpoint Derivative Feed-Forward Term Gain
* @param Kp2_in Proportional Squared Term Gain
*/
CasserolePID(double Kp_in, double Ki_in, double Kd_in, double Kf_in, double Kdf_in, double Kp2_in) {
Kp = Kp_in;
Ki = Ki_in;
Kd = Kd_in;
Kf = Kf_in;
Kdf = Kdf_in;
Kp2 = Kp2_in;
commonConstructor();
}
// Do the rest of the construction things, like setting defaults
private void commonConstructor() {
dTermDeriv = new DerivativeCalculator();
setpointDeriv = new DerivativeCalculator();
iTermIntegral = new IntegralCalculator(1);
useErrForDerivTerm = true;
outputMin = Double.NEGATIVE_INFINITY;
outputMax = Double.POSITIVE_INFINITY;
integratorDisableThresh = Double.POSITIVE_INFINITY;
setpoint = 0;
timerThread = new java.util.Timer();
}
/**
* Start the PID thread running. Will begin to call the returnPIDInput and usePIDOutput methods
* asynchronously.
*/
public void start() {
resetIntegrators();
watchdogCounter = 0;
// Kick off the multi-threaded stuff.
// Will start calling the periodic update function at an interval of pidSamplePeriod_ms,
// asynchronously from any other code.
// Java magic here, don't touch!
timerThread.scheduleAtFixedRate(new PIDTask(this), 0L, (long) (pidSamplePeriod_ms));
}
/**
* Stop whatever thread may or may not be running. Will finish the current calculation loop, so
* returnPIDInput and usePIDOutput might get called one more time after this function gets
* called.
*/
public void stop() {
timerThread.cancel();
}
/**
* Reset all internal integrators back to zero. Useful for returning to init-state conditions.
*/
public void resetIntegrators() {
iTermIntegral.resetIntegral();
}
/**
* Assign a new setpoint for the algorithm to control to.
*/
public void setSetpoint(double setpoint_in) {
setpoint = setpoint_in;
}
/**
* Override this method! This function must be implemented to return the present "actual" value
* of the system under control. For example, when controlling a motor to turn a certain number
* of rotations, this should return the encoder count or number of degrees or something like
* that. You must implement this! Expect it to be called frequently and asynchronously by the
* underlying PID algorithm. Make sure it runs fast!
*
* @return The sensor feedback value for the PID algorithm to use.
*/
protected abstract double returnPIDInput();
/**
* Override this method! This function will return the value calculated from the PID. Expect it
* to be called frequently and asynchronously by the underlying PID algorithm. When it is
* called, you should utilize the value given to do something useful. For example, when
* controlling a motor to turn a certain number of rotations, your implementation of this
* function should send the output of the PID to one of the motor controllers. Make sure it runs
* fast!
*
* @param pidOutput The control effort output calculated by the PID algorithm
*/
protected abstract void usePIDOutput(double pidOutput);
// The big kahuna. This is where the magic happens.
protected void periodicUpdate() {
double curInput = returnPIDInput();
double curOutput = 0.0;
double curSetpoint = setpoint; // latch the setpoint at start of loop
double curError = curSetpoint - curInput;
// Calculate P term
if (Kp != 0.0) { // speed optimization when terms are turned off
curOutput = curOutput + curError * Kp;
}
// Calculate I term
if (Ki != 0.0) {
if (Math.abs(curError) > integratorDisableThresh) {
iTermIntegral.resetIntegral();
} else {
curOutput = curOutput + iTermIntegral.calcIntegral(curError) * Ki;
}
}
// Calculate D term
if (Kd != 0.0) {
if (useErrForDerivTerm) {
curOutput = curOutput + dTermDeriv.calcDeriv(curError) * Kd;
} else {
curOutput = curOutput + dTermDeriv.calcDeriv(curInput) * Kd;
}
}
// Calculate FF term
if (Kf != 0.0) {
curOutput = curOutput + curSetpoint * Kf;
}
// Calculate derivative FF term
if (Kdf != 0.0) {
curOutput = curOutput + setpointDeriv.calcDeriv(curSetpoint) * Kdf;
}
// Calculate P^2 term
if (Kp2 != 0.0) {
if (curError >= 0) {
curOutput = curOutput + curError * curError * Kp;
} else {
curOutput = curOutput - curError * curError * Kp;
}
}
// Assign output
if (curOutput > outputMax) {
usePIDOutput(outputMax);
} else if (curOutput < outputMin) {
usePIDOutput(outputMin);
} else {
usePIDOutput(curOutput);
}
// Indicate we are still doing stuff with the watchdog
watchdogCounter = watchdogCounter + 1;
}
// Java multithreading magic. Do not touch.
// Touching will incour the wrath of Cthulhu, god of java and PID.
// May the oceans of 1's and 0's rise to praise him.
private class PIDTask extends TimerTask {
private CasserolePID m_pid;
public PIDTask(CasserolePID pid) {
if (pid == null) {
throw new NullPointerException("Given PIDController was null");
}
m_pid = pid;
}
@Override
public void run() {
m_pid.periodicUpdate();
}
}
/**
* Call this method to set up the algorithm to utilize the error between setpoint and actual for
* the derivative term calculation.
*/
public void setErrorAsDerivTermSrc() {
useErrForDerivTerm = true;
}
/**
* Call this method to set up the algorithm to utilize only the actual (sensor feedback) value
* for the derivative term calculation.
*/
public void setActualAsDerivTermSrc() {
useErrForDerivTerm = false;
}
/**
* @return The present Proportional term gain
*/
public double getKp() {
return Kp;
}
/**
* @param kp the kp to set
*/
public void setKp(double kp) {
Kp = kp;
}
/**
* @return The present Integral term gain
*/
public double getKi() {
return Ki;
}
/**
* @param ki the ki to set
*/
public void setKi(double ki) {
Ki = ki;
}
/**
* @return The present Derivative term gain
*/
public double getKd() {
return Kd;
}
/**
* @param kd the kd to set
*/
public void setKd(double kd) {
Kd = kd;
}
/**
* @return The present feed-forward term gain
*/
public double getKf() {
return Kf;
}
/**
* @param kf the kf to set
*/
public void setKf(double kf) {
Kf = kf;
}
/**
* @return The present derivative feed-forward term gain
*/
public double getKdf() {
return Kdf;
}
/**
* @param kdf the kdf to set
*/
public void setKdf(double kdf) {
Kdf = kdf;
}
/**
* @return The present Proportional-squared term gain
*/
public double getKp2() {
return Kp2;
}
/**
* @param kp2 the kp2 to set
*/
public void setKp2(double kp2) {
Kp2 = kp2;
}
/**
* Set limits on what the control effort (output) can be commanded to.
*
* @param min Smallest allowed control effort
* @param max Largest allowed control effort
*/
public void setOutputRange(double min, double max) {
outputMin = min;
outputMax = max;
}
/**
* @return The present setpoint
*/
public double getSetpoint() {
return setpoint;
}
/**
* Set the Integral term disable threshold. If the absolute value of the error goes above this
* threshold, the integral term will be set to zero AND the integrators will internally reset
* their accumulators to zero. Once the error gets below this threshold, the integrators will
* resume integrating and contributing to the control effort. This is a mechanism to help
* prevent integrator windup in high-error conditions. By default it is disabled (threshold =
* positive infinity).
*
* @param integratorDisableThresh_in The new threshold to use.
*/
public void setintegratorDisableThresh(double integratorDisableThresh_in) {
integratorDisableThresh = integratorDisableThresh_in;
}
}
| Fix the CasserolePID class
| EclipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/lib/CasserolePID/CasserolePID.java | Fix the CasserolePID class | <ide><path>clipseProject/RobotCasserole2017/src/org/usfirst/frc/team1736/lib/CasserolePID/CasserolePID.java
<ide> * @param Ki_in Integral Term Gain
<ide> * @param Kd_in Derivative Term Gain
<ide> */
<del> CasserolePID(double Kp_in, double Ki_in, double Kd_in) {
<add> protected CasserolePID(double Kp_in, double Ki_in, double Kd_in) {
<ide> Kp = Kp_in;
<ide> Ki = Ki_in;
<ide> Kd = Kd_in;
<ide> * @param Kdf_in Setpoint Derivative Feed-Forward Term Gain
<ide> * @param Kp2_in Proportional Squared Term Gain
<ide> */
<del> CasserolePID(double Kp_in, double Ki_in, double Kd_in, double Kf_in, double Kdf_in, double Kp2_in) {
<add> protected CasserolePID(double Kp_in, double Ki_in, double Kd_in, double Kf_in, double Kdf_in, double Kp2_in) {
<ide> Kp = Kp_in;
<ide> Ki = Ki_in;
<ide> Kd = Kd_in; |
|
Java | bsd-3-clause | 3a2ff38d92e74d1bd362c347cd1ce4f6292c0a88 | 0 | eoinsha/JavaPhoenixChannels,eoinsha/JavaPhoenixChannels | package org.phoenixframework.channels;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
// To fix UnrecognizedPropertyException.
@JsonIgnoreProperties(ignoreUnknown = true)
public class Envelope {
@JsonProperty
private String topic;
@JsonProperty
private String event;
@JsonProperty(value = "payload")
private JsonNode payload;
@JsonProperty
private String ref;
@SuppressWarnings("unused")
public Envelope() {
}
public Envelope(final String topic, final String event, final JsonNode payload, final String ref) {
this.topic = topic;
this.event = event;
this.payload = payload;
this.ref = ref;
}
public String getTopic() {
return topic;
}
public String getEvent() {
return event;
}
public JsonNode getPayload() {
return payload;
}
/**
* Helper to retrieve the value of "ref" from the payload
*
* @return The ref string or null if not found
*/
public String getRef() {
if (ref != null) return ref;
final JsonNode refNode = payload.get("ref");
return refNode != null ? refNode.textValue() : null;
}
/**
* Helper to retrieve the value of "status" from the payload
*
* @return The status string or null if not found
*/
public String getResponseStatus() {
final JsonNode statusNode = payload.get("status");
return statusNode == null ? null : statusNode.textValue();
}
/**
* Helper to retrieve the value of "reason" from the payload
*
* @return The reason string or null if not found
*/
public String getReason() {
final JsonNode reasonNode = payload.get("reason");
return reasonNode == null ? null : reasonNode.textValue();
}
@Override
public String toString() {
return "Envelope{" +
"topic='" + topic + '\'' +
", event='" + event + '\'' +
", payload=" + payload +
'}';
}
}
| src/main/java/org/phoenixframework/channels/Envelope.java | package org.phoenixframework.channels;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
public class Envelope {
@JsonProperty
private String topic;
@JsonProperty
private String event;
@JsonProperty(value = "payload")
private JsonNode payload;
@JsonProperty
private String ref;
@SuppressWarnings("unused")
public Envelope() {
}
public Envelope(final String topic, final String event, final JsonNode payload, final String ref) {
this.topic = topic;
this.event = event;
this.payload = payload;
this.ref = ref;
}
public String getTopic() {
return topic;
}
public String getEvent() {
return event;
}
public JsonNode getPayload() {
return payload;
}
/**
* Helper to retrieve the value of "ref" from the payload
*
* @return The ref string or null if not found
*/
public String getRef() {
if (ref != null) return ref;
final JsonNode refNode = payload.get("ref");
return refNode != null ? refNode.textValue() : null;
}
/**
* Helper to retrieve the value of "status" from the payload
*
* @return The status string or null if not found
*/
public String getResponseStatus() {
final JsonNode statusNode = payload.get("status");
return statusNode == null ? null : statusNode.textValue();
}
/**
* Helper to retrieve the value of "reason" from the payload
*
* @return The reason string or null if not found
*/
public String getReason() {
final JsonNode reasonNode = payload.get("reason");
return reasonNode == null ? null : reasonNode.textValue();
}
@Override
public String toString() {
return "Envelope{" +
"topic='" + topic + '\'' +
", event='" + event + '\'' +
", payload=" + payload +
'}';
}
}
| Update Envelope.java | src/main/java/org/phoenixframework/channels/Envelope.java | Update Envelope.java | <ide><path>rc/main/java/org/phoenixframework/channels/Envelope.java
<ide> import com.fasterxml.jackson.annotation.JsonProperty;
<ide> import com.fasterxml.jackson.databind.JsonNode;
<ide>
<add>// To fix UnrecognizedPropertyException.
<add>@JsonIgnoreProperties(ignoreUnknown = true)
<ide> public class Envelope {
<ide> @JsonProperty
<ide> private String topic; |
|
Java | lgpl-2.1 | b393f7515fd85a28c961e727124e291d3e0619d1 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-04 David Pavlis <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;
import java.util.ListIterator;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DateDataField;
import org.jetel.data.IntegerDataField;
import org.jetel.data.NumericDataField;
import org.jetel.data.LongDataField;
import org.jetel.data.StringDataField;
import org.jetel.exception.JetelException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
/**
* Class for creating mappings between CloverETL's DataRecords and JDBC's
* ResultSets.<br>
* It also contains inner classes for translating various CloverETL's DataField
* types onto JDBC types.
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
public abstract class CopySQLData {
/**
* Description of the Field
*
* @since October 7, 2002
*/
protected int fieldSQL,fieldJetel;
/**
* Description of the Field
*
* @since October 7, 2002
*/
protected DataField field;
/**
* Constructor for the CopySQLData object
*
* @param record Clover record which will be source or target
* @param fieldSQL index of the field in SQL statement
* @param fieldJetel index of the field in Clover record
* @since October 7, 2002
*/
CopySQLData(DataRecord record, int fieldSQL, int fieldJetel) {
this.fieldSQL = fieldSQL + 1;
// fields in ResultSet start with index 1
this.fieldJetel=fieldJetel;
field = record.getField(fieldJetel);
}
/**
* Assigns different DataField than the original used when creating
* copy object
*
* @param field New DataField
*/
public void setCloverField(DataField field){
this.field=field;
}
/**
* Assings different DataField (DataRecord). The proper field
* is taken from DataRecord based on previously saved field number.
*
* @param record New DataRecord
*/
public void setCloverRecord(DataRecord record){
this.field=record.getField(fieldJetel);
}
/**
* Sets value of Jetel/Clover data field based on value from SQL ResultSet
*
* @param resultSet Description of Parameter
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
public void sql2jetel(ResultSet resultSet) throws SQLException {
try {
setJetel(resultSet);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
} catch (ClassCastException ex){
throw new SQLException("Incompatible Clover & JDBC field types - field "+field.getMetadata().getName()+
" Clover type: "+SQLUtil.jetelType2Str(field.getMetadata().getType()));
}
}
/**
* Sets value of SQL field in PreparedStatement based on Jetel/Clover data
* field's value
*
* @param pStatement Description of Parameter
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
public void jetel2sql(PreparedStatement pStatement) throws SQLException {
try {
setSQL(pStatement);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
}catch (ClassCastException ex){
throw new SQLException("Incompatible Clover & JDBC field types - field "+field.getMetadata().getName()+
" Clover type: "+SQLUtil.jetelType2Str(field.getMetadata().getType()));
}
}
/**
* Sets the Jetel attribute of the CopySQLData object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
abstract void setJetel(ResultSet resultSet) throws SQLException;
/**
* Sets the SQL attribute of the CopySQLData object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
abstract void setSQL(PreparedStatement pStatement) throws SQLException;
/**
* Assigns new instance of DataRecord to existing CopySQLData structure (array).
* Useful when CopySQLData (aka transmap) was created using some other
* DataRecord and new one needs to be used
*
* @param transMap Array of CopySQLData object - the transmap
* @param record New DataRecord object to be used within transmap
*/
public static void resetDataRecord(CopySQLData[] transMap,DataRecord record){
for(int i=0;i<transMap.length;transMap[i++].setCloverRecord(record));
}
/**
* Creates translation array for copying data from Database record into Jetel
* record
*
* @param metadata Metadata describing Jetel data record
* @param record Jetel data record
* @param fieldTypes Description of the Parameter
* @return Array of CopySQLData objects which can be used when getting
* data from DB into Jetel record
* @since September 26, 2002
*/
public static CopySQLData[] sql2JetelTransMap(List fieldTypes, DataRecordMetadata metadata, DataRecord record) {
/* test that both sides have at least the same number of fields, less
* fields on DB side is O.K. (some of Clover fields won't get assigned value).
*/
if (fieldTypes.size()>metadata.getNumFields()){
throw new RuntimeException("CloverETL data record "+metadata.getName()+
" contains less fields than source JDBC record !");
}
CopySQLData[] transMap = new CopySQLData[metadata.getNumFields()];
int i = 0;
for (ListIterator iterator = fieldTypes.listIterator(); iterator.hasNext(); ) {
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(),
record.getMetadata().getFieldType(i),
record, i, i);
i++;
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record
*
* @param fieldTypes Description of Parameter
* @param record Description of Parameter
* @return Description of the Returned Value
* @exception SQLException Description of Exception
* @since October 4, 2002
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record) throws SQLException {
int i = 0;
/* test that both sides have at least the same number of fields, less
* fields on DB side is O.K. (some of Clover fields won't be assigned to JDBC).
*/
if (fieldTypes.size()>record.getMetadata().getNumFields()){
throw new RuntimeException("CloverETL data record "+record.getMetadata().getName()+
" contains less fields than target JDBC record !");
}
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(),
record.getMetadata().getFieldType(i),
record, i, i);
i++;
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record. It allows only certain (specified) Clover fields to be considered
*
* @param fieldTypes Description of the Parameter
* @param record Description of the Parameter
* @param cloverFields array of DataRecord record's field names which should be considered for mapping
* @return Description of the Return Value
* @exception SQLException Description of the Exception
* @exception JetelException Description of the Exception
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record, String[] cloverFields)
throws SQLException, JetelException {
int i = 0;
int fromIndex = 0;
int toIndex = 0;
short jdbcType;
char jetelFieldType;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
jdbcType = ((Integer) iterator.next()).shortValue();
// from index is index of specified cloverField in the Clover record
fromIndex = record.getMetadata().getFieldPosition(cloverFields[i]);
jetelFieldType = record.getMetadata().getFieldType(fromIndex);
if (fromIndex == -1) {
throw new JetelException(" Field \"" + cloverFields[i] + "\" does not exist in DataRecord !");
}
// we copy from Clover's field to JDBC - toIndex/fromIndex is switched here
transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record, toIndex, fromIndex);
toIndex++;// we go one by one - order defined by insert/update statement
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record. It allows only certain (specified) Clover fields to be considered
*
* @param fieldTypes Description of the Parameter
* @param record Description of the Parameter
* @param cloverFields array of DataRecord record's field numbers which should be considered for mapping
* @return Description of the Return Value
* @exception SQLException Description of the Exception
* @exception JetelException Description of the Exception
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes,
DataRecord record, int[] cloverFields) throws SQLException,
JetelException {
int i = 0;
int fromIndex = 0;
int toIndex = 0;
short jdbcType;
char jetelFieldType;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
jdbcType = ((Integer) iterator.next()).shortValue();
// from index is index of specified cloverField in the Clover record
fromIndex = cloverFields[i];
jetelFieldType = record.getMetadata().getFieldType(fromIndex);
if (fromIndex == -1) {
throw new JetelException(" Field \"" + cloverFields[i]
+ "\" does not exist in DataRecord !");
}
// we copy from Clover's field to JDBC - toIndex/fromIndex is
// switched here
transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record,
toIndex, fromIndex);
toIndex++;// we go one by one - order defined by insert/update statement
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record. It allows only certain (specified) Clover fields to be considered.<br>
* <i>Note:</i> the target (JDBC) data types are guessed from Jetel field types - so use this
* method only as the last resort.
*
* @param record
* @param cloverFields
* @return
* @throws JetelException
*/
public static CopySQLData[] jetel2sqlTransMap(DataRecord record, int[] cloverFields) throws JetelException {
int fromIndex;
int toIndex;
int jdbcType;
char jetelFieldType;
CopySQLData[] transMap = new CopySQLData[cloverFields.length];
for(int i=0;i<cloverFields.length;i++) {
jetelFieldType=record.getField(cloverFields[i]).getType();
jdbcType = SQLUtil.jetelType2sql(jetelFieldType);
// from index is index of specified cloverField in the Clover record
fromIndex = cloverFields[i];
toIndex=i;
// we copy from Clover's field to JDBC - toIndex/fromIndex is
// switched here
transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record,
toIndex, fromIndex);
}
return transMap;
}
/**
* Creates copy object - bridge between JDBC data types and Clover data types
*
* @param SQLType Description of the Parameter
* @param jetelFieldType Description of the Parameter
* @param record Description of the Parameter
* @param fromIndex Description of the Parameter
* @param toIndex Description of the Parameter
* @return Description of the Return Value
*/
private static CopySQLData createCopyObject(int SQLType, char jetelFieldType, DataRecord record, int fromIndex, int toIndex) {
switch (SQLType) {
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
return new CopyString(record, fromIndex, toIndex);
case Types.INTEGER:
case Types.SMALLINT:
return new CopyInteger(record, fromIndex, toIndex);
case Types.BIGINT:
return new CopyLong(record,fromIndex,toIndex);
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.NUMERIC:
case Types.REAL:
// fix for copying when target is numeric and
// clover source is integer - no precision can be
// lost so we can use CopyInteger
if (jetelFieldType == DataFieldMetadata.INTEGER_FIELD) {
return new CopyInteger(record, fromIndex, toIndex);
} else {
return new CopyNumeric(record, fromIndex, toIndex);
}
case Types.DATE:
case Types.TIME:
return new CopyDate(record, fromIndex, toIndex);
case Types.TIMESTAMP:
return new CopyTimestamp(record, fromIndex, toIndex);
case Types.BOOLEAN:
case Types.BIT:
if (jetelFieldType == DataFieldMetadata.STRING_FIELD) {
return new CopyBoolean(record, fromIndex, toIndex);
}
// when Types.OTHER or unknown, try to copy it as STRING
// this works for most of the NCHAR/NVARCHAR types on Oracle, MSSQL, etc.
default:
//case Types.OTHER:// When other, try to copy it as STRING - should work for NCHAR/NVARCHAR
return new CopyString(record, fromIndex, toIndex);
//default:
// throw new RuntimeException("SQL data type not supported: " + SQLType);
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyDate extends CopySQLData {
java.sql.Date dateValue;
/**
* Constructor for the CopyDate object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyDate(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
dateValue = new java.sql.Date(0);
}
/**
* Sets the Jetel attribute of the CopyDate object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getDate(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyDate object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
dateValue.setTime(((DateDataField) field).getDate().getTime());
pStatement.setDate(fieldSQL, dateValue);
} else {
pStatement.setNull(fieldSQL, java.sql.Types.DATE);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyNumeric extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyNumeric(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
double i = resultSet.getDouble(fieldSQL);
if (resultSet.wasNull()) {
((NumericDataField) field).setValue(null);
} else {
((NumericDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setDouble(fieldSQL, ((NumericDataField) field).getDouble());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.NUMERIC);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since 2. bezen 2004
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyInteger extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyInteger(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
int i = resultSet.getInt(fieldSQL);
if (resultSet.wasNull()) {
((IntegerDataField) field).setValue(null);
} else {
((IntegerDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setInt(fieldSQL, ((IntegerDataField) field).getInt());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.INTEGER);
}
}
}
static class CopyLong extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyLong(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
long i = resultSet.getLong(fieldSQL);
if (resultSet.wasNull()) {
((LongDataField) field).setValue(null);
} else {
((LongDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setLong(fieldSQL, ((LongDataField) field).getLong());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.BIGINT);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyString extends CopySQLData {
/**
* Constructor for the CopyString object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyString(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
String fieldVal = resultSet.getString(fieldSQL);
if (resultSet.wasNull()) {
field.fromString(null);
} else {
field.fromString(fieldVal);
}
}
/**
* Sets the SQL attribute of the CopyString object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setString(fieldSQL, field.toString());
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyTimestamp extends CopySQLData {
Timestamp timeValue;
/**
* Constructor for the CopyTimestamp object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyTimestamp(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
timeValue = new Timestamp(0);
timeValue.setNanos(0);// we don't count with nanos!
}
/**
* Sets the Jetel attribute of the CopyTimestamp object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getTimestamp(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyTimestamp object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
timeValue.setTime(((DateDataField) field).getDate().getTime());
pStatement.setTimestamp(fieldSQL, timeValue);
} else {
pStatement.setNull(fieldSQL, java.sql.Types.TIMESTAMP);
}
}
}
/**
* Copy object for boolean/bit type fields. Expects String data
* representation on Clover's side
* for logical
*
* @author dpavlis
* @since November 27, 2003
* @revision $Revision$
*/
static class CopyBoolean extends CopySQLData {
private static String _TRUE_ = "T";
private static String _FALSE_ = "F";
private static char _TRUE_CHAR_ = 'T';
private static char _TRUE_SMCHAR_ = 't';
/**
* Constructor for the CopyString object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyBoolean(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
field.fromString(resultSet.getBoolean(fieldSQL) ? _TRUE_ : _FALSE_);
}
/**
* Sets the SQL attribute of the CopyString object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
char value = ((StringDataField) field).getCharSequence().charAt(0);
pStatement.setBoolean(fieldSQL, ((value == _TRUE_CHAR_) || (value == _TRUE_SMCHAR_)));
}
}
}
| cloveretl.engine/src/org/jetel/database/CopySQLData.java | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-04 David Pavlis <[email protected]>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;
import java.util.ListIterator;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DateDataField;
import org.jetel.data.IntegerDataField;
import org.jetel.data.NumericDataField;
import org.jetel.data.LongDataField;
import org.jetel.data.StringDataField;
import org.jetel.exception.JetelException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
/**
* Class for creating mappings between CloverETL's DataRecords and JDBC's
* ResultSets.<br>
* It also contains inner classes for translating various CloverETL's DataField
* types onto JDBC types.
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
public abstract class CopySQLData {
/**
* Description of the Field
*
* @since October 7, 2002
*/
protected int fieldSQL,fieldJetel;
/**
* Description of the Field
*
* @since October 7, 2002
*/
protected DataField field;
/**
* Constructor for the CopySQLData object
*
* @param record Clover record which will be source or target
* @param fieldSQL index of the field in SQL statement
* @param fieldJetel index of the field in Clover record
* @since October 7, 2002
*/
CopySQLData(DataRecord record, int fieldSQL, int fieldJetel) {
this.fieldSQL = fieldSQL + 1;
// fields in ResultSet start with index 1
this.fieldJetel=fieldJetel;
field = record.getField(fieldJetel);
}
/**
* Assigns different DataField than the original used when creating
* copy object
*
* @param field New DataField
*/
public void setCloverField(DataField field){
this.field=field;
}
/**
* Assings different DataField (DataRecord). The proper field
* is taken from DataRecord based on previously saved field number.
*
* @param record New DataRecord
*/
public void setCloverRecord(DataRecord record){
this.field=record.getField(fieldJetel);
}
/**
* Sets value of Jetel/Clover data field based on value from SQL ResultSet
*
* @param resultSet Description of Parameter
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
public void sql2jetel(ResultSet resultSet) throws SQLException {
try {
setJetel(resultSet);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
} catch (ClassCastException ex){
throw new SQLException("Incompatible Clover & JDBC field types - field "+field.getMetadata().getName()+
" Clover type: "+SQLUtil.jetelType2Str(field.getMetadata().getType()));
}
}
/**
* Sets value of SQL field in PreparedStatement based on Jetel/Clover data
* field's value
*
* @param pStatement Description of Parameter
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
public void jetel2sql(PreparedStatement pStatement) throws SQLException {
try {
setSQL(pStatement);
} catch (SQLException ex) {
throw new SQLException(ex.getMessage() + " with field " + field.getMetadata().getName());
}catch (ClassCastException ex){
throw new SQLException("Incompatible Clover & JDBC field types - field "+field.getMetadata().getName()+
" Clover type: "+SQLUtil.jetelType2Str(field.getMetadata().getType()));
}
}
/**
* Sets the Jetel attribute of the CopySQLData object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
abstract void setJetel(ResultSet resultSet) throws SQLException;
/**
* Sets the SQL attribute of the CopySQLData object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
abstract void setSQL(PreparedStatement pStatement) throws SQLException;
/**
* Assigns new instance of DataRecord to existing CopySQLData structure (array).
* Useful when CopySQLData (aka transmap) was created using some other
* DataRecord and new one needs to be used
*
* @param transMap Array of CopySQLData object - the transmap
* @param record New DataRecord object to be used within transmap
*/
public static void resetDataRecord(CopySQLData[] transMap,DataRecord record){
for(int i=0;i<transMap.length;transMap[i++].setCloverRecord(record));
}
/**
* Creates translation array for copying data from Database record into Jetel
* record
*
* @param metadata Metadata describing Jetel data record
* @param record Jetel data record
* @param fieldTypes Description of the Parameter
* @return Array of CopySQLData objects which can be used when getting
* data from DB into Jetel record
* @since September 26, 2002
*/
public static CopySQLData[] sql2JetelTransMap(List fieldTypes, DataRecordMetadata metadata, DataRecord record) {
/* test that both sides have at least the same number of fields, less
* fields on DB side is O.K. (some of Clover fields won't get assigned value).
*/
if (fieldTypes.size()>metadata.getNumFields()){
throw new RuntimeException("CloverETL data record "+metadata.getName()+
" contains less fields than source JDBC record !");
}
CopySQLData[] transMap = new CopySQLData[metadata.getNumFields()];
int i = 0;
for (ListIterator iterator = fieldTypes.listIterator(); iterator.hasNext(); ) {
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(),
record.getMetadata().getFieldType(i),
record, i, i);
i++;
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record
*
* @param fieldTypes Description of Parameter
* @param record Description of Parameter
* @return Description of the Returned Value
* @exception SQLException Description of Exception
* @since October 4, 2002
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record) throws SQLException {
int i = 0;
/* test that both sides have at least the same number of fields, less
* fields on DB side is O.K. (some of Clover fields won't be assigned to JDBC).
*/
if (fieldTypes.size()>record.getMetadata().getNumFields()){
throw new RuntimeException("CloverETL data record "+record.getMetadata().getName()+
" contains less fields than target JDBC record !");
}
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
transMap[i] = createCopyObject(((Integer) iterator.next()).shortValue(),
record.getMetadata().getFieldType(i),
record, i, i);
i++;
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record. It allows only certain (specified) Clover fields to be considered
*
* @param fieldTypes Description of the Parameter
* @param record Description of the Parameter
* @param cloverFields array of DataRecord record's field names which should be considered for mapping
* @return Description of the Return Value
* @exception SQLException Description of the Exception
* @exception JetelException Description of the Exception
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes, DataRecord record, String[] cloverFields)
throws SQLException, JetelException {
int i = 0;
int fromIndex = 0;
int toIndex = 0;
short jdbcType;
char jetelFieldType;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
jdbcType = ((Integer) iterator.next()).shortValue();
// from index is index of specified cloverField in the Clover record
fromIndex = record.getMetadata().getFieldPosition(cloverFields[i]);
jetelFieldType = record.getMetadata().getFieldType(fromIndex);
if (fromIndex == -1) {
throw new JetelException(" Field \"" + cloverFields[i] + "\" does not exist in DataRecord !");
}
// we copy from Clover's field to JDBC - toIndex/fromIndex is switched here
transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record, toIndex, fromIndex);
toIndex++;// we go one by one - order defined by insert/update statement
}
return transMap;
}
/**
* Creates translation array for copying data from Jetel record into Database
* record. It allows only certain (specified) Clover fields to be considered
*
* @param fieldTypes Description of the Parameter
* @param record Description of the Parameter
* @param cloverFields array of DataRecord record's field numbers which should be considered for mapping
* @return Description of the Return Value
* @exception SQLException Description of the Exception
* @exception JetelException Description of the Exception
*/
public static CopySQLData[] jetel2sqlTransMap(List fieldTypes,
DataRecord record, int[] cloverFields) throws SQLException,
JetelException {
int i = 0;
int fromIndex = 0;
int toIndex = 0;
short jdbcType;
char jetelFieldType;
CopySQLData[] transMap = new CopySQLData[fieldTypes.size()];
ListIterator iterator = fieldTypes.listIterator();
while (iterator.hasNext()) {
jdbcType = ((Integer) iterator.next()).shortValue();
// from index is index of specified cloverField in the Clover record
fromIndex = cloverFields[i];
jetelFieldType = record.getMetadata().getFieldType(fromIndex);
if (fromIndex == -1) {
throw new JetelException(" Field \"" + cloverFields[i]
+ "\" does not exist in DataRecord !");
}
// we copy from Clover's field to JDBC - toIndex/fromIndex is
// switched here
transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record,
toIndex, fromIndex);
toIndex++;// we go one by one - order defined by insert/update statement
}
return transMap;
}
/**
* Creates copy object - bridge between JDBC data types and Clover data types
*
* @param SQLType Description of the Parameter
* @param jetelFieldType Description of the Parameter
* @param record Description of the Parameter
* @param fromIndex Description of the Parameter
* @param toIndex Description of the Parameter
* @return Description of the Return Value
*/
private static CopySQLData createCopyObject(int SQLType, char jetelFieldType, DataRecord record, int fromIndex, int toIndex) {
switch (SQLType) {
case Types.CHAR:
case Types.LONGVARCHAR:
case Types.VARCHAR:
return new CopyString(record, fromIndex, toIndex);
case Types.INTEGER:
case Types.SMALLINT:
return new CopyInteger(record, fromIndex, toIndex);
case Types.BIGINT:
return new CopyLong(record,fromIndex,toIndex);
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.NUMERIC:
case Types.REAL:
// fix for copying when target is numeric and
// clover source is integer - no precision can be
// lost so we can use CopyInteger
if (jetelFieldType == DataFieldMetadata.INTEGER_FIELD) {
return new CopyInteger(record, fromIndex, toIndex);
} else {
return new CopyNumeric(record, fromIndex, toIndex);
}
case Types.DATE:
case Types.TIME:
return new CopyDate(record, fromIndex, toIndex);
case Types.TIMESTAMP:
return new CopyTimestamp(record, fromIndex, toIndex);
case Types.BOOLEAN:
case Types.BIT:
if (jetelFieldType == DataFieldMetadata.STRING_FIELD) {
return new CopyBoolean(record, fromIndex, toIndex);
}
// when Types.OTHER or unknown, try to copy it as STRING
// this works for most of the NCHAR/NVARCHAR types on Oracle, MSSQL, etc.
default:
//case Types.OTHER:// When other, try to copy it as STRING - should work for NCHAR/NVARCHAR
return new CopyString(record, fromIndex, toIndex);
//default:
// throw new RuntimeException("SQL data type not supported: " + SQLType);
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyDate extends CopySQLData {
java.sql.Date dateValue;
/**
* Constructor for the CopyDate object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyDate(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
dateValue = new java.sql.Date(0);
}
/**
* Sets the Jetel attribute of the CopyDate object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getDate(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyDate object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
dateValue.setTime(((DateDataField) field).getDate().getTime());
pStatement.setDate(fieldSQL, dateValue);
} else {
pStatement.setNull(fieldSQL, java.sql.Types.DATE);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyNumeric extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyNumeric(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
double i = resultSet.getDouble(fieldSQL);
if (resultSet.wasNull()) {
((NumericDataField) field).setValue(null);
} else {
((NumericDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setDouble(fieldSQL, ((NumericDataField) field).getDouble());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.NUMERIC);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since 2. bezen 2004
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyInteger extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyInteger(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
int i = resultSet.getInt(fieldSQL);
if (resultSet.wasNull()) {
((IntegerDataField) field).setValue(null);
} else {
((IntegerDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setInt(fieldSQL, ((IntegerDataField) field).getInt());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.INTEGER);
}
}
}
static class CopyLong extends CopySQLData {
/**
* Constructor for the CopyNumeric object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyLong(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyNumeric object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
long i = resultSet.getLong(fieldSQL);
if (resultSet.wasNull()) {
((LongDataField) field).setValue(null);
} else {
((LongDataField) field).setValue(i);
}
}
/**
* Sets the SQL attribute of the CopyNumeric object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
pStatement.setLong(fieldSQL, ((LongDataField) field).getLong());
} else {
pStatement.setNull(fieldSQL, java.sql.Types.BIGINT);
}
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyString extends CopySQLData {
/**
* Constructor for the CopyString object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyString(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
String fieldVal = resultSet.getString(fieldSQL);
if (resultSet.wasNull()) {
field.fromString(null);
} else {
field.fromString(fieldVal);
}
}
/**
* Sets the SQL attribute of the CopyString object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
pStatement.setString(fieldSQL, field.toString());
}
}
/**
* Description of the Class
*
* @author dpavlis
* @since October 7, 2002
* @revision $Revision$
* @created 8. ervenec 2003
*/
static class CopyTimestamp extends CopySQLData {
Timestamp timeValue;
/**
* Constructor for the CopyTimestamp object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyTimestamp(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
timeValue = new Timestamp(0);
timeValue.setNanos(0);// we don't count with nanos!
}
/**
* Sets the Jetel attribute of the CopyTimestamp object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
((DateDataField) field).setValue(resultSet.getTimestamp(fieldSQL));
}
/**
* Sets the SQL attribute of the CopyTimestamp object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
if (!field.isNull()) {
timeValue.setTime(((DateDataField) field).getDate().getTime());
pStatement.setTimestamp(fieldSQL, timeValue);
} else {
pStatement.setNull(fieldSQL, java.sql.Types.TIMESTAMP);
}
}
}
/**
* Copy object for boolean/bit type fields. Expects String data
* representation on Clover's side
* for logical
*
* @author dpavlis
* @since November 27, 2003
* @revision $Revision$
*/
static class CopyBoolean extends CopySQLData {
private static String _TRUE_ = "T";
private static String _FALSE_ = "F";
private static char _TRUE_CHAR_ = 'T';
private static char _TRUE_SMCHAR_ = 't';
/**
* Constructor for the CopyString object
*
* @param record Description of Parameter
* @param fieldSQL Description of Parameter
* @param fieldJetel Description of Parameter
* @since October 7, 2002
*/
CopyBoolean(DataRecord record, int fieldSQL, int fieldJetel) {
super(record, fieldSQL, fieldJetel);
}
/**
* Sets the Jetel attribute of the CopyString object
*
* @param resultSet The new Jetel value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setJetel(ResultSet resultSet) throws SQLException {
field.fromString(resultSet.getBoolean(fieldSQL) ? _TRUE_ : _FALSE_);
}
/**
* Sets the SQL attribute of the CopyString object
*
* @param pStatement The new SQL value
* @exception SQLException Description of Exception
* @since October 7, 2002
*/
void setSQL(PreparedStatement pStatement) throws SQLException {
char value = ((StringDataField) field).getCharSequence().charAt(0);
pStatement.setBoolean(fieldSQL, ((value == _TRUE_CHAR_) || (value == _TRUE_SMCHAR_)));
}
}
}
| added new variant of jetel2sqlTransMap
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@508 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/database/CopySQLData.java | added new variant of jetel2sqlTransMap | <ide><path>loveretl.engine/src/org/jetel/database/CopySQLData.java
<ide> return transMap;
<ide> }
<ide>
<add> /**
<add> * Creates translation array for copying data from Jetel record into Database
<add> * record. It allows only certain (specified) Clover fields to be considered.<br>
<add> * <i>Note:</i> the target (JDBC) data types are guessed from Jetel field types - so use this
<add> * method only as the last resort.
<add> *
<add> * @param record
<add> * @param cloverFields
<add> * @return
<add> * @throws JetelException
<add> */
<add> public static CopySQLData[] jetel2sqlTransMap(DataRecord record, int[] cloverFields) throws JetelException {
<add> int fromIndex;
<add> int toIndex;
<add> int jdbcType;
<add> char jetelFieldType;
<add>
<add> CopySQLData[] transMap = new CopySQLData[cloverFields.length];
<add>
<add> for(int i=0;i<cloverFields.length;i++) {
<add> jetelFieldType=record.getField(cloverFields[i]).getType();
<add> jdbcType = SQLUtil.jetelType2sql(jetelFieldType);
<add>
<add> // from index is index of specified cloverField in the Clover record
<add> fromIndex = cloverFields[i];
<add> toIndex=i;
<add> // we copy from Clover's field to JDBC - toIndex/fromIndex is
<add> // switched here
<add> transMap[i++] = createCopyObject(jdbcType, jetelFieldType, record,
<add> toIndex, fromIndex);
<add> }
<add> return transMap;
<add> }
<ide>
<ide> /**
<ide> * Creates copy object - bridge between JDBC data types and Clover data types |
|
JavaScript | bsd-3-clause | f79b7264aa73900dc8da59ec0317a3af0be3c340 | 0 | juxtapos/Rain,juxtapos/Rain,juxtapos/Rain,juxtapos/Rain,juxtapos/Rain | "use strict";
/**
* Here be dragons.
*
* Todos:
* Fix circular dependencies.
*/
module.exports = function (modcontainer) {
if (!modcontainer) { throw new Error('dependencies missing'); }
var c = console.log
, mod_util = require('util')
, mod_events = require('events')
, mod_path = require('path')
, mod_mu = require('mu')
, mod_resources = require('./resources.js')
, Resource = mod_resources.Resource
, mod_sys = require('sys')
, modulecontainer = modcontainer
, logger = require('./logger.js').getLogger(mod_path.basename(module.filename))
var uuid = 0;
function Renderer(resource, moduleconf, parser, tagmanager, resmgr, outputMode) {
if (!resource || !moduleconf || !parser || !tagmanager || !resmgr) throw new Error('parameter missing');
this.uuid = ++uuid;
this._state = Renderer.STATES.INIT;
this.resource = resource;
this.moduleconf = moduleconf;
this.modulepath = moduleconf.url;
this.parser = parser;
this.tagmanager = tagmanager;
this.resourcemanager = resmgr;
this.outputMode = outputMode;
this._childRenderer = [];
this.parseResult = null; // return value of HTMLParser promise
this.rendererToElementMap = {};
this.instanceResources = {}; // from instanceids to data resources (somewhat hacky currently)
this.preRenderResult = '';
this.renderResult = '';
logger.debug('Renderer() ' + this.uuid + ' created');
}
mod_util.inherits(Renderer, mod_events.EventEmitter);
Object.defineProperty(Renderer.prototype, 'state', {
get : function () {
return this._state;
},
set : function (val) {
if ('number' !== typeof val) { throw Error('expected number ' + val); }
//if (val !== this._state) {
//logger.debug('renderer ' + this.uuid + ' set state to ' + val);
this._state = val;
this.emit('stateChanged', this);
//}
}
});
Renderer.STATES = {
INIT : 1,
LOADING : 5,
LOADED : 10,
PARSING : 15,
PARSED : 20,
PRERENDERING : 30,
PRERENDERED : 35,
POSTRENDERING : 40,
COMPLETE : 50
}
Renderer.prototype.render = function () {
logger.debug('render ' + this.uuid);
this.state = Renderer.STATES.INIT;
this._load();
this.childRenderer = [];
}
Renderer.prototype._load = function () {
logger.debug('load resource ' + this.resource.uuid + '(url:' + this.resource.url + ') of renderer ' + this.uuid);
var r = this.resource;
if (this.resource.state == Resource.STATES.LOADING) {
logger.debug('already loading, add listener');
(function (self) {
r.once('load', function (resource) {
logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
self._parse();
});
})(this);
} else if (this.resource.state >= Resource.STATES.LOADED) {
this._parse();
} else {
logger.debug('renderer ' + this.uuid + ' load resource ' + r.uuid);
this.state = Renderer.STATES.LOADING;
r.load();
(function (self) {
r.once('load', function (resource) {
logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
self._parse();
});
})(this);
}
}
Renderer.prototype._parse = function () {
if (this.outputMode == 'json') {
this.outputJson();
this.state = Renderer.STATES.COMPLETE;
} else {
logger.debug('parse resource ' + this.resource.uuid + " at renderer " + this.uuid);
this.state = Renderer.STATES.PARSING;
var self = this;
var d = this.resource.data.toString();
this.parser(d, this.resource.url, this.tagmanager).then(function (result) {
logger.debug('parsed renderer ' + self.uuid);
self.parseResult = result;
// rewrite URLs received from view template
self.parseResult.controller = self.resolveUrl(self.parseResult.controller, self.modulePath, 'controllers/js');
self.parseResult.dependencies.css = self.parseResult.dependencies.css.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.parseResult.dependencies.script = self.parseResult.dependencies.script.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.parseResult.dependencies.locale = self.parseResult.dependencies.locale.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.handleDependencies();
self.state = Renderer.STATES.PARSED;
});
}
}
Renderer.prototype.outputJson = function () {
var data = {
};
this.renderResult = JSON.stringify(data);
this.state = Renderer.STATES.COMPLETE;
}
Renderer.prototype.handleDepEvent = function (renderer) {
var self = this;
//logger.debug('handle child renderer event at renderer ' + this.uuid + ', renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
if (this.allChildsRendered()) {
logger.debug('all child renderers of ' + this.uuid + ' prerendered or rendered');
if (this.state >= Renderer.STATES.PRERENDERED) {
this.postRender();
}
}
}
Renderer.prototype.allChildsRendered = function () {
var allRendered = true
, renderer;
for (var i = 0; i < this.childRenderer.length; i++) {
renderer = this.childRenderer[i];
if (renderer.state < Renderer.STATES.COMPLETE) {
allRendered = false;
return;
}
}
return allRendered;
}
Renderer.prototype.handleDependencies = function () {
logger.debug('loadDependencies at renderer ' + this.uuid + ' for resource ' + this.resource.uuid);
var self = this
, renderat
, deps = this.parseResult.elements
, resource
, hasInstances = false
, cnt = deps.length;
if (cnt > 0) {
deps.forEach(function (dep) {
var config = modulecontainer.getConfiguration(dep.tag.module);
resource = self.resourcemanager.getResourceByUrl(modulecontainer.getViewUrl(config, dep.view, self.tagmanager));
logger.debug('adding ' + resource.uuid + ' as dependency to resource ' + self.resource.uuid + ' for renderer ' + self.uuid);
renderat = 'server';
for (var i = 0; i < dep.attrs.length; i++) {
if (dep.attrs[i][0] == 'renderat') {
renderat = dep.attrs[i][1];
}
}
dep.renderat = renderat;
if (dep.renderat == 'server' && dep.instanceid) {
var hasInstances = true;
var dataurl = 'file://' + mod_path.join(__dirname, '..', 'instances', dep.instanceid);
var instanceresource = self.resourcemanager.loadResourceByUrl(dataurl);
logger.debug('new instance resource ' + instanceresource.url)
resource.addDependency(instanceresource);
}
// [TBD] do the same for locales...
resource.load();
c('++++++++++++++++++++++ ' + dep.tag.module);
//var modulepath = modulecontainer.getModulePath(dep.tag.module);
var modulepath = modulecontainer.getConfiguration(dep.tag.module);
c('the modulepath ' + modulepath);
var childrenderer = new Renderer(resource, modulepath, self.parser, self.tagmanager, self.resourcemanager);
if (dep.instanceid) {
childrenderer.instanceResources[dep.instanceid] = instanceresource;
}
childrenderer.parent = this;
childrenderer.render();
self.childRenderer.push(childrenderer);
self.rendererToElementMap[childrenderer.uuid] = dep;
childrenderer.addListener('stateChanged', function (event) {
self.handleDepEvent(event);
});
});
if (!hasInstances) {
this.preRender();
}
} else {
logger.debug('no dependencies for ' + this.uuid + ', only render self');
this.parseResult = {
// [TBD] ugly!
'document' : this.parseResult.document ? this.parseResult.document : this.resource.data,
'controller' : this.parseResult.controller,
'dependencies' : {
'css' : this.parseResult.dependencies.css,
'script' : this.parseResult.dependencies.script,
'locale' : this.parseResult.dependencies.locale
}
}
this.preRender();
}
}
Renderer.prototype.preRender = function () {
logger.debug('preRender ' + this.resource.uuid + ' at renderer ' + this.uuid);
this.state = Renderer.STATES.PRERENDERING;
var self = this
, tmplText = this.parseResult.document
, out = []
, data = {};
//this.resolveUrls();
// 1. preserve the mustache markers that were added to the view source during the parse process
this.childRenderer.forEach(function (renderer) {
var id = self.rendererToElementMap[renderer.uuid].id;
data['thing' + id] = '{{{thing' + id + '}}}'
});
// 2. [TBD] add data
data.city = 'Test' + new Date().getTime();
data.name = 'Rain'
for (var instanceid in this.instanceResources) {
var resource = this.instanceResources[instanceid];
try {
var instanceobj = JSON.parse(resource.data.toString());
for (var identifier in instanceobj) {
if (data[identifier]) { throw new Error('name clash, baby!'); }
data[identifier] = instanceobj[identifier];
}
} catch (ex) {
//throw new Error('');
logger.debug('instance data could not be loaded; ' + ex);
}
}
// 3. Do templating
mod_mu.compileText('template', tmplText);
var stream = mod_mu.render('template', data)
.on('data', function (data) {
out.push(data);
})
.on('end' , function () {
self.preRenderResult = out.join('');
self.state = Renderer.STATES.PRERENDERED;
if (self.childRenderer.length == 0) {
self.postRender();
}
});
}
var RESOURCE_LOADER_URLPATH = "/resources?files";
Renderer.prototype.postRender = function (data) {
logger.debug('postRender ' + this.uuid);
var self = this
, data = {}
, depmarkup = [] // markup for requesting script and css resources via the Resource Service
, alldeps = null // all dependencies object
, cssurls = [], scripturls = [], localeurls = [] // unique URLs to required resources
, out = [] // temp. for output data
// fills the data object for mustache with the pre-rendering results of the child renderers.
this.childRenderer.forEach(function (renderer) {
var id = self.rendererToElementMap[renderer.uuid].id;
data['thing' + id] = HTMLRenderer.getViewBody(renderer.renderResult);
});
if (this.parent == null) {
logger.debug('rendering dependencies of root renderer');
alldeps = this.getDependencies();
alldeps.css.forEach(function (url) {
cssurls.push(url);
});
alldeps.script.forEach(function (url) {
scripturls.push(url);
});
alldeps.locale.forEach(function (url) {
localeurls.push(url);
});
// add JavaScript and CSS resources required by requested view at client runtime.
// [TBD] the resource service should know how to create links to it, not this module.
if (cssurls.length) {
depmarkup.push('<link rel="stylesheet" type="text/css" href="'
, RESOURCE_LOADER_URLPATH, '=', cssurls.join(';'), '"/>\n');
}
if (scripturls.length) {
depmarkup.push('<script type="application/javascript" src="', RESOURCE_LOADER_URLPATH, '='
, scripturls.join(';'), '"></script>\n');
}
if (localeurls.length) {
logger.debug('TO BE DONE');
}
}
var initmarkup = [];
initmarkup.push('\n<script type="application/javascript">\n');
//if (this.parseResult.controller) {
// var module = 'domains'
// c(this.modulePath)
// initmarkup.push('\nrequire(["' + this.parseResult.controller + '"], function (module) {console.log("loaded domains controller!");} );');
var eid = '000';
initmarkup.push('\nrequire(["' + this.moduleconf.url + '/htdocs/script/client.js' + '"], function (module) { module.init("' + eid + '"); } );');
//}
if (typeof this.parseResult !== 'undefined' && typeof this.parseResult.elements !== 'undefined' && this.parseResult.elements.length > 0) {
this.parseResult.elements.forEach(function (elem) {
var im = elem.renderat == 'client' && elem.instanceid ? ',"text!/instances/' + elem.instanceid + '"' : '';
var l = elem.locale;
var m = elem.tag.module.substring(0, elem.tag.module.indexOf(';'));
initmarkup.push('\nrequire(["/modules/', m, '/htdocs/script/client.js"'
, ', "text!/modules/', elem.tag.module, '/main.html?type=json"'
, im
, ', "text!/modules/', elem.tag.module, '/locales/de_DE.js"'
, '], '
, ' function (module, template, instance, localefile) { \n\tmodule.initView("'
, elem.id, '", template, instance, localefile) } );'
);
});
}
initmarkup.push('\n</script>\n');
depmarkup.push(initmarkup.join(''));
mod_mu.compileText('template2', this.preRenderResult);
var stream = mod_mu.render('template2', data)
.on('data', function (data) {
out.push(data);
})
.on('end' , function () {
self.renderResult = out.join('');
// [TBD] yea, ugly, but works for now
// this is to preserve the cascading rules for included stylesheets that have a lower
// precedence than inline stylesheets.
if (self.renderResult.indexOf('<style') > -1) {
self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('<style')) + depmarkup.join('')
+ self.renderResult.substring(self.renderResult.indexOf('<style'));
} else {
self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('</head>')) + depmarkup.join('')
+ self.renderResult.substring(self.renderResult.indexOf('</head>'));
}
logger.debug('renderer ' + self.uuid + ' postRender complete');
self.state = Renderer.STATES.COMPLETE;
});
}
Renderer.prototype.getDependencies = function () {
var css = []
, script = []
, locale = []
, collected = {}
collect(this);
return {
'css' : css
, 'script' : script
, 'locale' : locale
}
function collect(renderer) {
if (renderer.parseResult) {
foreach(renderer.parseResult.dependencies.css, css);
foreach(renderer.parseResult.dependencies.script, script);
foreach(renderer.parseResult.dependencies.locale, locale);
renderer.childRenderer.forEach(function (renderer) {
collect(renderer)
});
}
}
function foreach (obj, target) {
obj.forEach(function (url) {
if (!collected[url]) {
target.push(url);
collected[url] = true;
}
});
}
}
/**
* From the module-relative URLs used in view templates, host-relative URLs are created.
*/
Renderer.prototype.resolveUrls = function () {
this.parseResult.dependencies.css = this.parseResult.dependencies.css.map(function (url) {
return self.resolveUrl(url, true);
});
this.parseResult.dependencies.script = this.parseResult.dependencies.script.map(function (url) {
return self.resolveUrl(url, true);
});
this.parseResult.dependencies.locale = this.parseResult.dependencies.locale.map(function (url) {
return self.resolveUrl(url, true);
});
}
Renderer.prototype.resolveUrl = function (url, folder, specialDir) {
if (!url) return null;
if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
var moduleId = url.substring(modulecontainer.COMPONENT_PROTOCOL.length
, url.indexOf('/', modulecontainer.COMPONENT_PROTOCOL.length + 1));
var path = url.substring(modulecontainer.COMPONENT_PROTOCOL.length + moduleId.length);
var modulepath = modulecontainer.getModulePath(moduleId);
var prefix = '';
var specialDir = specialDir ? specialDir : '';
path = mod_path.join(modulepath, specialDir, path);
return path;
} else if (url.indexOf('http://') === 0) {
return url;
} else {
var np = mod_path.join(folder, url);
return np;
}
return url;
}
Renderer.prototype.resolveToHost = function () {
}
function HTMLRenderer () {
}
HTMLRenderer.getViewBody = function (doc) {
return doc.match(/<body[^>]*>([\s\S]*)<\/body>/mi)[1];
}
return {
Renderer : Renderer
}
} | lib/renderer.js | "use strict";
/**
* Here be dragons.
*
* Todos:
* Fix circular dependencies.
*/
var c = console.log
, mod_util = require('util')
, mod_events = require('events')
, mod_path = require('path')
, mod_mu = require('mu')
, mod_resources = require('./resources.js')
, Resource = mod_resources.Resource
, mod_sys = require('sys')
, modulecontainer = require('./modulecontainer.js')
, logger = require('./logger.js').getLogger(mod_path.basename(module.filename))
var uuid = 0;
function Renderer(resource, modulepath, parser, tagmanager, resmgr) {
if (!resource || !modulepath || !parser || !tagmanager || !resmgr) throw new Error('parameter missing');
this.uuid = ++uuid;
this._state = Renderer.STATES.INIT;
this.resource = resource;
this.modulepath = modulepath;
this.parser = parser;
this.tagmanager = tagmanager;
this.resourcemanager = resmgr;
this._childRenderer = [];
this.parseResult = null; // return value of HTMLParser promise
this.rendererToElementMap = {};
this.instanceResources = {}; // from instanceids to data resources (somewhat hacky currently)
this.preRenderResult = '';
this.renderResult = '';
logger.debug('Renderer() ' + this.uuid + ' created');
}
mod_util.inherits(Renderer, mod_events.EventEmitter);
Object.defineProperty(Renderer.prototype, 'state', {
get : function () {
return this._state;
},
set : function (val) {
if ('number' !== typeof val) { throw Error('expected number ' + val); }
//if (val !== this._state) {
logger.debug('renderer ' + this.uuid + ' set state to ' + val);
this._state = val;
this.emit('stateChanged', this);
//}
}
});
Renderer.STATES = {
INIT : 1,
LOADING : 5,
LOADED : 10,
PARSING : 15,
PARSED : 20,
PRERENDERING : 30,
PRERENDERED : 35,
POSTRENDERING : 40,
COMPLETE : 50
}
Renderer.prototype.render = function () {
logger.debug('render ' + this.uuid);
this.state = Renderer.STATES.INIT;
this._load();
this.childRenderer = [];
}
Renderer.prototype._load = function () {
logger.debug('load resource ' + this.resource.uuid + '(url:' + this.resource.url + ') of renderer ' + this.uuid);
var r = this.resource;
if (this.resource.state == Resource.STATES.LOADING) {
logger.debug('already loading, add listener');
(function (self) {
r.once('load', function (resource) {
logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
self._parse();
});
})(this);
} else if (this.resource.state >= Resource.STATES.LOADED) {
this._parse();
} else {
logger.debug('renderer ' + this.uuid + ' load resource ' + r.uuid);
this.state = Renderer.STATES.LOADING;
r.load();
(function (self) {
r.once('load', function (resource) {
logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
self._parse();
});
})(this);
}
}
Renderer.prototype._parse = function () {
logger.debug('parse resource ' + this.resource.uuid + " at renderer " + this.uuid);
this.state = Renderer.STATES.PARSING;
var self = this;
var d = this.resource.data.toString();
this.parser(d, this.resource.url, this.tagmanager).then(function (result) {
logger.debug('parsed renderer ' + self.uuid);
self.parseResult = result;
// rewrite URLs received from view template
self.parseResult.controller = self.resolveUrl(self.parseResult.controller, self.modulePath, 'controllers/js');
self.parseResult.dependencies.css = self.parseResult.dependencies.css.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.parseResult.dependencies.script = self.parseResult.dependencies.script.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.parseResult.dependencies.locale = self.parseResult.dependencies.locale.map(function (url) {
return self.resolveUrl(url, self.modulepath);
});
self.handleDependencies();
self.state = Renderer.STATES.PARSED;
});
}
Renderer.prototype.handleDepEvent = function (renderer) {
var self = this;
logger.debug('handle child renderer event at renderer ' + this.uuid + ', renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
if (this.allChildsRendered()) {
logger.debug('all child renderers of ' + this.uuid + ' prerendered or rendered');
if (this.state >= Renderer.STATES.PRERENDERED) {
this.postRender();
}
}
}
Renderer.prototype.allChildsRendered = function () {
var allRendered = true
, renderer;
for (var i = 0; i < this.childRenderer.length; i++) {
renderer = this.childRenderer[i];
if (renderer.state < Renderer.STATES.COMPLETE) {
allRendered = false;
return;
}
}
return allRendered;
}
Renderer.prototype.handleDependencies = function () {
logger.debug('loadDependencies at renderer ' + this.uuid + ' for resource ' + this.resource.uuid);
var self = this
, renderat
, deps = this.parseResult.elements
, resource
, hasInstances = false
, cnt = deps.length;
if (cnt > 0) {
deps.forEach(function (dep) {
resource = self.resourcemanager.getResourceByUrl(modulecontainer.getViewUrl(dep.tag.module, dep.view, self.tagmanager));
logger.debug('adding ' + resource.uuid + ' as dependency to resource ' + self.resource.uuid + ' for renderer ' + self.uuid);
renderat = 'server';
for (var i = 0; i < dep.attrs.length; i++) {
if (dep.attrs[i][0] == 'renderat') {
renderat = dep.attrs[i][1];
}
}
dep.renderat = renderat;
if (dep.renderat == 'server' && dep.instanceid) {
var hasInstances = true;
var dataurl = 'file://' + mod_path.join(__dirname, '..', 'instances', dep.instanceid);
var instanceresource = self.resourcemanager.loadResourceByUrl(dataurl);
logger.debug('new instance resource ' + instanceresource.url)
resource.addDependency(instanceresource);
}
// [TBD] do the same for locales...
resource.load();
var modulepath = modulecontainer.getModulePath(dep.tag.module);
c('the modulepath ' + modulepath);
var childrenderer = new Renderer(resource, modulepath, self.parser, self.tagmanager, self.resourcemanager);
if (dep.instanceid) {
childrenderer.instanceResources[dep.instanceid] = instanceresource;
}
childrenderer.parent = this;
childrenderer.render();
self.childRenderer.push(childrenderer);
self.rendererToElementMap[childrenderer.uuid] = dep;
childrenderer.addListener('stateChanged', function (event) {
self.handleDepEvent(event);
});
});
if (!hasInstances) {
this.preRender();
}
} else {
logger.debug('no dependencies for ' + this.uuid + ', only render self');
this.parseResult = {
// [TBD] ugly!
'document' : this.parseResult.document ? this.parseResult.document : this.resource.data,
'controller' : this.parseResult.controller,
'dependencies' : {
'css' : this.parseResult.dependencies.css,
'script' : this.parseResult.dependencies.script,
'locale' : this.parseResult.dependencies.locale
}
}
this.preRender();
}
}
Renderer.prototype.preRender = function () {
logger.debug('preRender ' + this.resource.uuid + ' at renderer ' + this.uuid);
this.state = Renderer.STATES.PRERENDERING;
var self = this
, tmplText = this.parseResult.document
, out = []
, data = {};
//this.resolveUrls();
// 1. preserve the mustache markers that were added to the view source during the parse process
this.childRenderer.forEach(function (renderer) {
var id = self.rendererToElementMap[renderer.uuid].id;
data['thing' + id] = '{{{thing' + id + '}}}'
});
// 2. [TBD] add data
data.city = 'Test' + new Date().getTime();
data.name = 'Rain'
for (var instanceid in this.instanceResources) {
var resource = this.instanceResources[instanceid];
try {
var instanceobj = JSON.parse(resource.data.toString());
for (var identifier in instanceobj) {
if (data[identifier]) { throw new Error('name clash, baby!'); }
data[identifier] = instanceobj[identifier];
}
} catch (ex) {
//throw new Error('');
logger.debug('instance data could not be loaded; ' + ex);
}
}
// 3. Do templating
mod_mu.compileText('template', tmplText);
var stream = mod_mu.render('template', data)
.on('data', function (data) {
out.push(data);
})
.on('end' , function () {
self.preRenderResult = out.join('');
self.state = Renderer.STATES.PRERENDERED;
if (self.childRenderer.length == 0) {
self.postRender();
}
});
}
var RESOURCE_LOADER_URLPATH = "/resources?files";
Renderer.prototype.postRender = function (data) {
logger.debug('postRender ' + this.uuid);
var self = this
, data = {}
, depmarkup = [] // markup for requesting script and css resources via the Resource Service
, alldeps = null // all dependencies object
, cssurls = [], scripturls = [], localeurls = [] // unique URLs to required resources
, out = [] // temp. for output data
// fills the data object for mustache with the pre-rendering results of the child renderers.
this.childRenderer.forEach(function (renderer) {
var id = self.rendererToElementMap[renderer.uuid].id;
data['thing' + id] = HTMLRenderer.getViewBody(renderer.renderResult);
});
if (this.parent == null) {
logger.debug('rendering dependencies of root renderer');
alldeps = this.getDependencies();
alldeps.css.forEach(function (url) {
cssurls.push(url);
});
alldeps.script.forEach(function (url) {
scripturls.push(url);
});
alldeps.locale.forEach(function (url) {
localeurls.push(url);
});
// add JavaScript and CSS resources required by requested view at client runtime.
// [TBD] the resource service should know how to create links to it, not this module.
if (cssurls.length) {
depmarkup.push('<link rel="stylesheet" type="text/css" href="'
, RESOURCE_LOADER_URLPATH, '=', cssurls.join(';'), '"/>\n');
}
if (scripturls.length) {
depmarkup.push('<script type="application/javascript" src="', RESOURCE_LOADER_URLPATH, '='
, scripturls.join(';'), '"></script>\n');
}
if (localeurls.length) {
logger.debug('TO BE DONE');
}
}
var initmarkup = [];
initmarkup.push('\n<script type="application/javascript">\n');
if (this.parseResult.controller) {
var module = 'domains'
initmarkup.push('\nrequire(["' + this.parseResult.controller + '"], function (module) {console.log("loaded domains controller!");} );');
}
if (typeof this.parseResult !== 'undefined' && typeof this.parseResult.elements !== 'undefined' && this.parseResult.elements.length > 0) {
this.parseResult.elements.forEach(function (elem) {
var im = elem.renderat == 'client' && elem.instanceid ? ',"text!/instances/' + elem.instanceid + '"' : '';
var l = elem.locale
initmarkup.push('\nrequire(["/modules/', elem.tag.module, '/client.js"'
, ', "text!/modules/', elem.tag.module, '/main.html?type=json"'
, im
, ', "text!/modules/', elem.tag.module, '/locales/de_DE.js"'
, '], '
, ' function (module, template, instance, localefile) { \n\tmodule.initView("'
, elem.id, '", template, instance, localefile) } );'
);
});
}
initmarkup.push('\n</script>\n');
depmarkup.push(initmarkup.join(''));
mod_mu.compileText('template2', this.preRenderResult);
var stream = mod_mu.render('template2', data)
.on('data', function (data) {
out.push(data);
})
.on('end' , function () {
self.renderResult = out.join('');
// [TBD] yea, ugly, but works for now
self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('</head>')) + depmarkup.join('')
+ self.renderResult.substring(self.renderResult.indexOf('</head>'));
logger.debug('renderer ' + self.uuid + ' postRender complete');
self.state = Renderer.STATES.COMPLETE;
});
}
Renderer.prototype.getDependencies = function () {
var css = []
, script = []
, locale = []
, collected = {}
collect(this);
return {
'css' : css
, 'script' : script
, 'locale' : locale
}
function collect(renderer) {
if (renderer.parseResult) {
foreach(renderer.parseResult.dependencies.css, css);
foreach(renderer.parseResult.dependencies.script, script);
foreach(renderer.parseResult.dependencies.locale, locale);
renderer.childRenderer.forEach(function (renderer) {
collect(renderer)
});
}
}
function foreach (obj, target) {
obj.forEach(function (url) {
if (!collected[url]) {
target.push(url);
collected[url] = true;
}
});
}
}
/**
* From the module-relative URLs used in view templates, host-relative URLs are created.
*/
Renderer.prototype.resolveUrls = function () {
this.parseResult.dependencies.css = this.parseResult.dependencies.css.map(function (url) {
return self.resolveUrl(url, true);
});
this.parseResult.dependencies.script = this.parseResult.dependencies.script.map(function (url) {
return self.resolveUrl(url, true);
});
this.parseResult.dependencies.locale = this.parseResult.dependencies.locale.map(function (url) {
return path + url;
});
}
Renderer.prototype.resolveUrl = function (url, folder, specialDir) {
if (!url) return null;
if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
var moduleId = url.substring(modulecontainer.COMPONENT_PROTOCOL.length
, url.indexOf('/', modulecontainer.COMPONENT_PROTOCOL.length + 1));
var path = url.substring(modulecontainer.COMPONENT_PROTOCOL.length + moduleId.length);
var modulepath = modulecontainer.getModulePath(moduleId);
var prefix = '';
var specialDir = specialDir ? specialDir : '';
path = mod_path.join(modulepath, specialDir, path);
c('transformed ' + path)
return path;
} else if (url.indexOf('http://') === 0) {
return url;
} else {
var np = mod_path.join(folder, url);
c('local url, transformed ' + np);
return np;
}
return url;
}
Renderer.prototype.resolveToHost = function () {
}
exports.Renderer = Renderer;
function HTMLRenderer () {
}
HTMLRenderer.getViewBody = function (doc) {
return doc.match(/<body[^>]*>([\s\S]*)<\/body>/mi)[1];
} | depinjection pattern
| lib/renderer.js | depinjection pattern | <ide><path>ib/renderer.js
<ide> * Todos:
<ide> * Fix circular dependencies.
<ide> */
<del>
<del>var c = console.log
<del> , mod_util = require('util')
<del> , mod_events = require('events')
<del> , mod_path = require('path')
<del> , mod_mu = require('mu')
<del> , mod_resources = require('./resources.js')
<del> , Resource = mod_resources.Resource
<del> , mod_sys = require('sys')
<del> , modulecontainer = require('./modulecontainer.js')
<del> , logger = require('./logger.js').getLogger(mod_path.basename(module.filename))
<del>
<del>var uuid = 0;
<del>function Renderer(resource, modulepath, parser, tagmanager, resmgr) {
<del> if (!resource || !modulepath || !parser || !tagmanager || !resmgr) throw new Error('parameter missing');
<del>
<del> this.uuid = ++uuid;
<del> this._state = Renderer.STATES.INIT;
<del> this.resource = resource;
<del> this.modulepath = modulepath;
<del>
<del> this.parser = parser;
<del> this.tagmanager = tagmanager;
<del> this.resourcemanager = resmgr;
<del>
<del> this._childRenderer = [];
<del> this.parseResult = null; // return value of HTMLParser promise
<del> this.rendererToElementMap = {};
<del> this.instanceResources = {}; // from instanceids to data resources (somewhat hacky currently)
<del>
<del> this.preRenderResult = '';
<del> this.renderResult = '';
<del>
<del> logger.debug('Renderer() ' + this.uuid + ' created');
<add>module.exports = function (modcontainer) {
<add> if (!modcontainer) { throw new Error('dependencies missing'); }
<add> var c = console.log
<add> , mod_util = require('util')
<add> , mod_events = require('events')
<add> , mod_path = require('path')
<add> , mod_mu = require('mu')
<add> , mod_resources = require('./resources.js')
<add> , Resource = mod_resources.Resource
<add> , mod_sys = require('sys')
<add> , modulecontainer = modcontainer
<add> , logger = require('./logger.js').getLogger(mod_path.basename(module.filename))
<add>
<add> var uuid = 0;
<add> function Renderer(resource, moduleconf, parser, tagmanager, resmgr, outputMode) {
<add> if (!resource || !moduleconf || !parser || !tagmanager || !resmgr) throw new Error('parameter missing');
<add>
<add> this.uuid = ++uuid;
<add> this._state = Renderer.STATES.INIT;
<add> this.resource = resource;
<add> this.moduleconf = moduleconf;
<add> this.modulepath = moduleconf.url;
<add>
<add> this.parser = parser;
<add> this.tagmanager = tagmanager;
<add> this.resourcemanager = resmgr;
<add>
<add> this.outputMode = outputMode;
<add> this._childRenderer = [];
<add> this.parseResult = null; // return value of HTMLParser promise
<add> this.rendererToElementMap = {};
<add> this.instanceResources = {}; // from instanceids to data resources (somewhat hacky currently)
<add>
<add> this.preRenderResult = '';
<add> this.renderResult = '';
<add>
<add> logger.debug('Renderer() ' + this.uuid + ' created');
<add> }
<add>
<add> mod_util.inherits(Renderer, mod_events.EventEmitter);
<add>
<add> Object.defineProperty(Renderer.prototype, 'state', {
<add> get : function () {
<add> return this._state;
<add> },
<add> set : function (val) {
<add> if ('number' !== typeof val) { throw Error('expected number ' + val); }
<add> //if (val !== this._state) {
<add> //logger.debug('renderer ' + this.uuid + ' set state to ' + val);
<add> this._state = val;
<add>
<add> this.emit('stateChanged', this);
<add> //}
<add> }
<add> });
<add>
<add> Renderer.STATES = {
<add> INIT : 1,
<add> LOADING : 5,
<add> LOADED : 10,
<add> PARSING : 15,
<add> PARSED : 20,
<add> PRERENDERING : 30,
<add> PRERENDERED : 35,
<add> POSTRENDERING : 40,
<add> COMPLETE : 50
<add> }
<add>
<add> Renderer.prototype.render = function () {
<add> logger.debug('render ' + this.uuid);
<add> this.state = Renderer.STATES.INIT;
<add> this._load();
<add> this.childRenderer = [];
<add> }
<add>
<add> Renderer.prototype._load = function () {
<add> logger.debug('load resource ' + this.resource.uuid + '(url:' + this.resource.url + ') of renderer ' + this.uuid);
<add> var r = this.resource;
<add> if (this.resource.state == Resource.STATES.LOADING) {
<add> logger.debug('already loading, add listener');
<add> (function (self) {
<add> r.once('load', function (resource) {
<add> logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
<add> self._parse();
<add> });
<add> })(this);
<add> } else if (this.resource.state >= Resource.STATES.LOADED) {
<add> this._parse();
<add> } else {
<add> logger.debug('renderer ' + this.uuid + ' load resource ' + r.uuid);
<add> this.state = Renderer.STATES.LOADING;
<add> r.load();
<add> (function (self) {
<add> r.once('load', function (resource) {
<add> logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
<add> self._parse();
<add> });
<add> })(this);
<add> }
<add> }
<add>
<add> Renderer.prototype._parse = function () {
<add> if (this.outputMode == 'json') {
<add> this.outputJson();
<add> this.state = Renderer.STATES.COMPLETE;
<add> } else {
<add> logger.debug('parse resource ' + this.resource.uuid + " at renderer " + this.uuid);
<add> this.state = Renderer.STATES.PARSING;
<add> var self = this;
<add> var d = this.resource.data.toString();
<add> this.parser(d, this.resource.url, this.tagmanager).then(function (result) {
<add> logger.debug('parsed renderer ' + self.uuid);
<add>
<add> self.parseResult = result;
<add>
<add> // rewrite URLs received from view template
<add> self.parseResult.controller = self.resolveUrl(self.parseResult.controller, self.modulePath, 'controllers/js');
<add> self.parseResult.dependencies.css = self.parseResult.dependencies.css.map(function (url) {
<add> return self.resolveUrl(url, self.modulepath);
<add> });
<add> self.parseResult.dependencies.script = self.parseResult.dependencies.script.map(function (url) {
<add> return self.resolveUrl(url, self.modulepath);
<add> });
<add> self.parseResult.dependencies.locale = self.parseResult.dependencies.locale.map(function (url) {
<add> return self.resolveUrl(url, self.modulepath);
<add> });
<add>
<add> self.handleDependencies();
<add> self.state = Renderer.STATES.PARSED;
<add> });
<add> }
<add> }
<add>
<add> Renderer.prototype.outputJson = function () {
<add> var data = {
<add> };
<add> this.renderResult = JSON.stringify(data);
<add> this.state = Renderer.STATES.COMPLETE;
<add> }
<add>
<add> Renderer.prototype.handleDepEvent = function (renderer) {
<add> var self = this;
<add> //logger.debug('handle child renderer event at renderer ' + this.uuid + ', renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
<add> if (this.allChildsRendered()) {
<add> logger.debug('all child renderers of ' + this.uuid + ' prerendered or rendered');
<add> if (this.state >= Renderer.STATES.PRERENDERED) {
<add> this.postRender();
<add> }
<add> }
<add> }
<add>
<add> Renderer.prototype.allChildsRendered = function () {
<add> var allRendered = true
<add> , renderer;
<add> for (var i = 0; i < this.childRenderer.length; i++) {
<add> renderer = this.childRenderer[i];
<add> if (renderer.state < Renderer.STATES.COMPLETE) {
<add> allRendered = false;
<add> return;
<add> }
<add> }
<add> return allRendered;
<add> }
<add>
<add> Renderer.prototype.handleDependencies = function () {
<add> logger.debug('loadDependencies at renderer ' + this.uuid + ' for resource ' + this.resource.uuid);
<add> var self = this
<add> , renderat
<add> , deps = this.parseResult.elements
<add> , resource
<add> , hasInstances = false
<add> , cnt = deps.length;
<add>
<add> if (cnt > 0) {
<add> deps.forEach(function (dep) {
<add>
<add> var config = modulecontainer.getConfiguration(dep.tag.module);
<add> resource = self.resourcemanager.getResourceByUrl(modulecontainer.getViewUrl(config, dep.view, self.tagmanager));
<add>
<add> logger.debug('adding ' + resource.uuid + ' as dependency to resource ' + self.resource.uuid + ' for renderer ' + self.uuid);
<add>
<add> renderat = 'server';
<add> for (var i = 0; i < dep.attrs.length; i++) {
<add> if (dep.attrs[i][0] == 'renderat') {
<add> renderat = dep.attrs[i][1];
<add> }
<add> }
<add> dep.renderat = renderat;
<add>
<add> if (dep.renderat == 'server' && dep.instanceid) {
<add> var hasInstances = true;
<add> var dataurl = 'file://' + mod_path.join(__dirname, '..', 'instances', dep.instanceid);
<add> var instanceresource = self.resourcemanager.loadResourceByUrl(dataurl);
<add> logger.debug('new instance resource ' + instanceresource.url)
<add> resource.addDependency(instanceresource);
<add> }
<add> // [TBD] do the same for locales...
<add> resource.load();
<add>
<add> c('++++++++++++++++++++++ ' + dep.tag.module);
<add> //var modulepath = modulecontainer.getModulePath(dep.tag.module);
<add> var modulepath = modulecontainer.getConfiguration(dep.tag.module);
<add> c('the modulepath ' + modulepath);
<add>
<add> var childrenderer = new Renderer(resource, modulepath, self.parser, self.tagmanager, self.resourcemanager);
<add> if (dep.instanceid) {
<add> childrenderer.instanceResources[dep.instanceid] = instanceresource;
<add> }
<add> childrenderer.parent = this;
<add> childrenderer.render();
<add> self.childRenderer.push(childrenderer);
<add> self.rendererToElementMap[childrenderer.uuid] = dep;
<add> childrenderer.addListener('stateChanged', function (event) {
<add> self.handleDepEvent(event);
<add> });
<add> });
<add>
<add> if (!hasInstances) {
<add> this.preRender();
<add> }
<add> } else {
<add> logger.debug('no dependencies for ' + this.uuid + ', only render self');
<add> this.parseResult = {
<add> // [TBD] ugly!
<add> 'document' : this.parseResult.document ? this.parseResult.document : this.resource.data,
<add> 'controller' : this.parseResult.controller,
<add> 'dependencies' : {
<add> 'css' : this.parseResult.dependencies.css,
<add> 'script' : this.parseResult.dependencies.script,
<add> 'locale' : this.parseResult.dependencies.locale
<add> }
<add> }
<add> this.preRender();
<add> }
<add> }
<add>
<add> Renderer.prototype.preRender = function () {
<add> logger.debug('preRender ' + this.resource.uuid + ' at renderer ' + this.uuid);
<add> this.state = Renderer.STATES.PRERENDERING;
<add>
<add> var self = this
<add> , tmplText = this.parseResult.document
<add> , out = []
<add> , data = {};
<add>
<add> //this.resolveUrls();
<add>
<add> // 1. preserve the mustache markers that were added to the view source during the parse process
<add> this.childRenderer.forEach(function (renderer) {
<add> var id = self.rendererToElementMap[renderer.uuid].id;
<add> data['thing' + id] = '{{{thing' + id + '}}}'
<add> });
<add>
<add> // 2. [TBD] add data
<add> data.city = 'Test' + new Date().getTime();
<add> data.name = 'Rain'
<add>
<add> for (var instanceid in this.instanceResources) {
<add> var resource = this.instanceResources[instanceid];
<add> try {
<add> var instanceobj = JSON.parse(resource.data.toString());
<add> for (var identifier in instanceobj) {
<add> if (data[identifier]) { throw new Error('name clash, baby!'); }
<add> data[identifier] = instanceobj[identifier];
<add> }
<add> } catch (ex) {
<add> //throw new Error('');
<add> logger.debug('instance data could not be loaded; ' + ex);
<add> }
<add> }
<add>
<add> // 3. Do templating
<add> mod_mu.compileText('template', tmplText);
<add> var stream = mod_mu.render('template', data)
<add> .on('data', function (data) {
<add> out.push(data);
<add> })
<add> .on('end' , function () {
<add> self.preRenderResult = out.join('');
<add> self.state = Renderer.STATES.PRERENDERED;
<add> if (self.childRenderer.length == 0) {
<add> self.postRender();
<add> }
<add> });
<add> }
<add>
<add> var RESOURCE_LOADER_URLPATH = "/resources?files";
<add>
<add> Renderer.prototype.postRender = function (data) {
<add> logger.debug('postRender ' + this.uuid);
<add> var self = this
<add> , data = {}
<add> , depmarkup = [] // markup for requesting script and css resources via the Resource Service
<add> , alldeps = null // all dependencies object
<add> , cssurls = [], scripturls = [], localeurls = [] // unique URLs to required resources
<add> , out = [] // temp. for output data
<add>
<add> // fills the data object for mustache with the pre-rendering results of the child renderers.
<add> this.childRenderer.forEach(function (renderer) {
<add> var id = self.rendererToElementMap[renderer.uuid].id;
<add> data['thing' + id] = HTMLRenderer.getViewBody(renderer.renderResult);
<add> });
<add>
<add> if (this.parent == null) {
<add> logger.debug('rendering dependencies of root renderer');
<add> alldeps = this.getDependencies();
<add> alldeps.css.forEach(function (url) {
<add> cssurls.push(url);
<add> });
<add> alldeps.script.forEach(function (url) {
<add> scripturls.push(url);
<add> });
<add> alldeps.locale.forEach(function (url) {
<add> localeurls.push(url);
<add> });
<add>
<add> // add JavaScript and CSS resources required by requested view at client runtime.
<add> // [TBD] the resource service should know how to create links to it, not this module.
<add> if (cssurls.length) {
<add> depmarkup.push('<link rel="stylesheet" type="text/css" href="'
<add> , RESOURCE_LOADER_URLPATH, '=', cssurls.join(';'), '"/>\n');
<add> }
<add> if (scripturls.length) {
<add> depmarkup.push('<script type="application/javascript" src="', RESOURCE_LOADER_URLPATH, '='
<add> , scripturls.join(';'), '"></script>\n');
<add> }
<add> if (localeurls.length) {
<add> logger.debug('TO BE DONE');
<add> }
<add> }
<add>
<add> var initmarkup = [];
<add> initmarkup.push('\n<script type="application/javascript">\n');
<add>
<add> //if (this.parseResult.controller) {
<add> // var module = 'domains'
<add>
<add> // c(this.modulePath)
<add>
<add> // initmarkup.push('\nrequire(["' + this.parseResult.controller + '"], function (module) {console.log("loaded domains controller!");} );');
<add> var eid = '000';
<add> initmarkup.push('\nrequire(["' + this.moduleconf.url + '/htdocs/script/client.js' + '"], function (module) { module.init("' + eid + '"); } );');
<add> //}
<add>
<add> if (typeof this.parseResult !== 'undefined' && typeof this.parseResult.elements !== 'undefined' && this.parseResult.elements.length > 0) {
<add>
<add> this.parseResult.elements.forEach(function (elem) {
<add> var im = elem.renderat == 'client' && elem.instanceid ? ',"text!/instances/' + elem.instanceid + '"' : '';
<add> var l = elem.locale;
<add> var m = elem.tag.module.substring(0, elem.tag.module.indexOf(';'));
<add> initmarkup.push('\nrequire(["/modules/', m, '/htdocs/script/client.js"'
<add> , ', "text!/modules/', elem.tag.module, '/main.html?type=json"'
<add> , im
<add> , ', "text!/modules/', elem.tag.module, '/locales/de_DE.js"'
<add> , '], '
<add> , ' function (module, template, instance, localefile) { \n\tmodule.initView("'
<add> , elem.id, '", template, instance, localefile) } );'
<add> );
<add> });
<add>
<add> }
<add>
<add> initmarkup.push('\n</script>\n');
<add> depmarkup.push(initmarkup.join(''));
<add>
<add> mod_mu.compileText('template2', this.preRenderResult);
<add> var stream = mod_mu.render('template2', data)
<add> .on('data', function (data) {
<add> out.push(data);
<add> })
<add> .on('end' , function () {
<add> self.renderResult = out.join('');
<add> // [TBD] yea, ugly, but works for now
<add> // this is to preserve the cascading rules for included stylesheets that have a lower
<add> // precedence than inline stylesheets.
<add> if (self.renderResult.indexOf('<style') > -1) {
<add> self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('<style')) + depmarkup.join('')
<add> + self.renderResult.substring(self.renderResult.indexOf('<style'));
<add> } else {
<add> self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('</head>')) + depmarkup.join('')
<add> + self.renderResult.substring(self.renderResult.indexOf('</head>'));
<add> }
<add>
<add> logger.debug('renderer ' + self.uuid + ' postRender complete');
<add> self.state = Renderer.STATES.COMPLETE;
<add> });
<add> }
<add>
<add> Renderer.prototype.getDependencies = function () {
<add> var css = []
<add> , script = []
<add> , locale = []
<add> , collected = {}
<add>
<add> collect(this);
<add> return {
<add> 'css' : css
<add> , 'script' : script
<add> , 'locale' : locale
<add> }
<add>
<add> function collect(renderer) {
<add> if (renderer.parseResult) {
<add> foreach(renderer.parseResult.dependencies.css, css);
<add> foreach(renderer.parseResult.dependencies.script, script);
<add> foreach(renderer.parseResult.dependencies.locale, locale);
<add> renderer.childRenderer.forEach(function (renderer) {
<add> collect(renderer)
<add> });
<add> }
<add> }
<add>
<add> function foreach (obj, target) {
<add> obj.forEach(function (url) {
<add> if (!collected[url]) {
<add> target.push(url);
<add> collected[url] = true;
<add> }
<add> });
<add> }
<add> }
<add>
<add> /**
<add> * From the module-relative URLs used in view templates, host-relative URLs are created.
<add> */
<add> Renderer.prototype.resolveUrls = function () {
<add> this.parseResult.dependencies.css = this.parseResult.dependencies.css.map(function (url) {
<add> return self.resolveUrl(url, true);
<add> });
<add> this.parseResult.dependencies.script = this.parseResult.dependencies.script.map(function (url) {
<add> return self.resolveUrl(url, true);
<add> });
<add> this.parseResult.dependencies.locale = this.parseResult.dependencies.locale.map(function (url) {
<add> return self.resolveUrl(url, true);
<add> });
<add> }
<add>
<add> Renderer.prototype.resolveUrl = function (url, folder, specialDir) {
<add> if (!url) return null;
<add> if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
<add> var moduleId = url.substring(modulecontainer.COMPONENT_PROTOCOL.length
<add> , url.indexOf('/', modulecontainer.COMPONENT_PROTOCOL.length + 1));
<add> var path = url.substring(modulecontainer.COMPONENT_PROTOCOL.length + moduleId.length);
<add> var modulepath = modulecontainer.getModulePath(moduleId);
<add> var prefix = '';
<add> var specialDir = specialDir ? specialDir : '';
<add> path = mod_path.join(modulepath, specialDir, path);
<add> return path;
<add> } else if (url.indexOf('http://') === 0) {
<add> return url;
<add> } else {
<add> var np = mod_path.join(folder, url);
<add> return np;
<add> }
<add> return url;
<add> }
<add>
<add> Renderer.prototype.resolveToHost = function () {
<add>
<add> }
<add>
<add> function HTMLRenderer () {
<add>
<add> }
<add> HTMLRenderer.getViewBody = function (doc) {
<add> return doc.match(/<body[^>]*>([\s\S]*)<\/body>/mi)[1];
<add> }
<add>
<add> return {
<add> Renderer : Renderer
<add> }
<ide> }
<del>
<del>mod_util.inherits(Renderer, mod_events.EventEmitter);
<del>
<del>Object.defineProperty(Renderer.prototype, 'state', {
<del> get : function () {
<del> return this._state;
<del> },
<del> set : function (val) {
<del> if ('number' !== typeof val) { throw Error('expected number ' + val); }
<del> //if (val !== this._state) {
<del> logger.debug('renderer ' + this.uuid + ' set state to ' + val);
<del> this._state = val;
<del>
<del> this.emit('stateChanged', this);
<del> //}
<del> }
<del>});
<del>
<del>Renderer.STATES = {
<del> INIT : 1,
<del> LOADING : 5,
<del> LOADED : 10,
<del> PARSING : 15,
<del> PARSED : 20,
<del> PRERENDERING : 30,
<del> PRERENDERED : 35,
<del> POSTRENDERING : 40,
<del> COMPLETE : 50
<del>}
<del>
<del>Renderer.prototype.render = function () {
<del> logger.debug('render ' + this.uuid);
<del> this.state = Renderer.STATES.INIT;
<del> this._load();
<del> this.childRenderer = [];
<del>}
<del>
<del>Renderer.prototype._load = function () {
<del> logger.debug('load resource ' + this.resource.uuid + '(url:' + this.resource.url + ') of renderer ' + this.uuid);
<del> var r = this.resource;
<del> if (this.resource.state == Resource.STATES.LOADING) {
<del> logger.debug('already loading, add listener');
<del> (function (self) {
<del> r.once('load', function (resource) {
<del> logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
<del> self._parse();
<del> });
<del> })(this);
<del> } else if (this.resource.state >= Resource.STATES.LOADED) {
<del> this._parse();
<del> } else {
<del> logger.debug('renderer ' + this.uuid + ' load resource ' + r.uuid);
<del> this.state = Renderer.STATES.LOADING;
<del> r.load();
<del> (function (self) {
<del> r.once('load', function (resource) {
<del> logger.debug('resource ' + resource.uuid + " at renderer " + self.uuid + ' set state to ' + resource.state);
<del> self._parse();
<del> });
<del> })(this);
<del> }
<del>}
<del>
<del>Renderer.prototype._parse = function () {
<del> logger.debug('parse resource ' + this.resource.uuid + " at renderer " + this.uuid);
<del> this.state = Renderer.STATES.PARSING;
<del> var self = this;
<del> var d = this.resource.data.toString();
<del> this.parser(d, this.resource.url, this.tagmanager).then(function (result) {
<del> logger.debug('parsed renderer ' + self.uuid);
<del>
<del> self.parseResult = result;
<del>
<del> // rewrite URLs received from view template
<del> self.parseResult.controller = self.resolveUrl(self.parseResult.controller, self.modulePath, 'controllers/js');
<del> self.parseResult.dependencies.css = self.parseResult.dependencies.css.map(function (url) {
<del> return self.resolveUrl(url, self.modulepath);
<del> });
<del> self.parseResult.dependencies.script = self.parseResult.dependencies.script.map(function (url) {
<del> return self.resolveUrl(url, self.modulepath);
<del> });
<del> self.parseResult.dependencies.locale = self.parseResult.dependencies.locale.map(function (url) {
<del> return self.resolveUrl(url, self.modulepath);
<del> });
<del>
<del> self.handleDependencies();
<del> self.state = Renderer.STATES.PARSED;
<del> });
<del>}
<del>
<del>Renderer.prototype.handleDepEvent = function (renderer) {
<del> var self = this;
<del> logger.debug('handle child renderer event at renderer ' + this.uuid + ', renderer ' + renderer.uuid + ' changed state to ' + renderer.state);
<del> if (this.allChildsRendered()) {
<del> logger.debug('all child renderers of ' + this.uuid + ' prerendered or rendered');
<del> if (this.state >= Renderer.STATES.PRERENDERED) {
<del> this.postRender();
<del> }
<del> }
<del>}
<del>
<del>Renderer.prototype.allChildsRendered = function () {
<del> var allRendered = true
<del> , renderer;
<del> for (var i = 0; i < this.childRenderer.length; i++) {
<del> renderer = this.childRenderer[i];
<del> if (renderer.state < Renderer.STATES.COMPLETE) {
<del> allRendered = false;
<del> return;
<del> }
<del> }
<del> return allRendered;
<del>}
<del>
<del>Renderer.prototype.handleDependencies = function () {
<del> logger.debug('loadDependencies at renderer ' + this.uuid + ' for resource ' + this.resource.uuid);
<del> var self = this
<del> , renderat
<del> , deps = this.parseResult.elements
<del> , resource
<del> , hasInstances = false
<del> , cnt = deps.length;
<del>
<del> if (cnt > 0) {
<del> deps.forEach(function (dep) {
<del> resource = self.resourcemanager.getResourceByUrl(modulecontainer.getViewUrl(dep.tag.module, dep.view, self.tagmanager));
<del> logger.debug('adding ' + resource.uuid + ' as dependency to resource ' + self.resource.uuid + ' for renderer ' + self.uuid);
<del>
<del> renderat = 'server';
<del> for (var i = 0; i < dep.attrs.length; i++) {
<del> if (dep.attrs[i][0] == 'renderat') {
<del> renderat = dep.attrs[i][1];
<del> }
<del> }
<del> dep.renderat = renderat;
<del>
<del> if (dep.renderat == 'server' && dep.instanceid) {
<del> var hasInstances = true;
<del> var dataurl = 'file://' + mod_path.join(__dirname, '..', 'instances', dep.instanceid);
<del> var instanceresource = self.resourcemanager.loadResourceByUrl(dataurl);
<del> logger.debug('new instance resource ' + instanceresource.url)
<del> resource.addDependency(instanceresource);
<del> }
<del> // [TBD] do the same for locales...
<del> resource.load();
<del>
<del> var modulepath = modulecontainer.getModulePath(dep.tag.module);
<del> c('the modulepath ' + modulepath);
<del>
<del> var childrenderer = new Renderer(resource, modulepath, self.parser, self.tagmanager, self.resourcemanager);
<del> if (dep.instanceid) {
<del> childrenderer.instanceResources[dep.instanceid] = instanceresource;
<del> }
<del> childrenderer.parent = this;
<del> childrenderer.render();
<del> self.childRenderer.push(childrenderer);
<del> self.rendererToElementMap[childrenderer.uuid] = dep;
<del> childrenderer.addListener('stateChanged', function (event) {
<del> self.handleDepEvent(event);
<del> });
<del> });
<del>
<del> if (!hasInstances) {
<del> this.preRender();
<del> }
<del> } else {
<del> logger.debug('no dependencies for ' + this.uuid + ', only render self');
<del> this.parseResult = {
<del> // [TBD] ugly!
<del> 'document' : this.parseResult.document ? this.parseResult.document : this.resource.data,
<del> 'controller' : this.parseResult.controller,
<del> 'dependencies' : {
<del> 'css' : this.parseResult.dependencies.css,
<del> 'script' : this.parseResult.dependencies.script,
<del> 'locale' : this.parseResult.dependencies.locale
<del> }
<del> }
<del> this.preRender();
<del> }
<del>}
<del>
<del>Renderer.prototype.preRender = function () {
<del> logger.debug('preRender ' + this.resource.uuid + ' at renderer ' + this.uuid);
<del> this.state = Renderer.STATES.PRERENDERING;
<del>
<del> var self = this
<del> , tmplText = this.parseResult.document
<del> , out = []
<del> , data = {};
<del>
<del> //this.resolveUrls();
<del>
<del> // 1. preserve the mustache markers that were added to the view source during the parse process
<del> this.childRenderer.forEach(function (renderer) {
<del> var id = self.rendererToElementMap[renderer.uuid].id;
<del> data['thing' + id] = '{{{thing' + id + '}}}'
<del> });
<del>
<del> // 2. [TBD] add data
<del> data.city = 'Test' + new Date().getTime();
<del> data.name = 'Rain'
<del>
<del> for (var instanceid in this.instanceResources) {
<del> var resource = this.instanceResources[instanceid];
<del> try {
<del> var instanceobj = JSON.parse(resource.data.toString());
<del> for (var identifier in instanceobj) {
<del> if (data[identifier]) { throw new Error('name clash, baby!'); }
<del> data[identifier] = instanceobj[identifier];
<del> }
<del> } catch (ex) {
<del> //throw new Error('');
<del> logger.debug('instance data could not be loaded; ' + ex);
<del> }
<del> }
<del>
<del> // 3. Do templating
<del> mod_mu.compileText('template', tmplText);
<del> var stream = mod_mu.render('template', data)
<del> .on('data', function (data) {
<del> out.push(data);
<del> })
<del> .on('end' , function () {
<del> self.preRenderResult = out.join('');
<del> self.state = Renderer.STATES.PRERENDERED;
<del> if (self.childRenderer.length == 0) {
<del> self.postRender();
<del> }
<del> });
<del>}
<del>
<del>var RESOURCE_LOADER_URLPATH = "/resources?files";
<del>
<del>Renderer.prototype.postRender = function (data) {
<del> logger.debug('postRender ' + this.uuid);
<del> var self = this
<del> , data = {}
<del> , depmarkup = [] // markup for requesting script and css resources via the Resource Service
<del> , alldeps = null // all dependencies object
<del> , cssurls = [], scripturls = [], localeurls = [] // unique URLs to required resources
<del> , out = [] // temp. for output data
<del>
<del> // fills the data object for mustache with the pre-rendering results of the child renderers.
<del> this.childRenderer.forEach(function (renderer) {
<del> var id = self.rendererToElementMap[renderer.uuid].id;
<del> data['thing' + id] = HTMLRenderer.getViewBody(renderer.renderResult);
<del> });
<del>
<del> if (this.parent == null) {
<del> logger.debug('rendering dependencies of root renderer');
<del> alldeps = this.getDependencies();
<del> alldeps.css.forEach(function (url) {
<del> cssurls.push(url);
<del> });
<del> alldeps.script.forEach(function (url) {
<del> scripturls.push(url);
<del> });
<del> alldeps.locale.forEach(function (url) {
<del> localeurls.push(url);
<del> });
<del>
<del> // add JavaScript and CSS resources required by requested view at client runtime.
<del> // [TBD] the resource service should know how to create links to it, not this module.
<del> if (cssurls.length) {
<del> depmarkup.push('<link rel="stylesheet" type="text/css" href="'
<del> , RESOURCE_LOADER_URLPATH, '=', cssurls.join(';'), '"/>\n');
<del> }
<del> if (scripturls.length) {
<del> depmarkup.push('<script type="application/javascript" src="', RESOURCE_LOADER_URLPATH, '='
<del> , scripturls.join(';'), '"></script>\n');
<del> }
<del> if (localeurls.length) {
<del> logger.debug('TO BE DONE');
<del> }
<del> }
<del>
<del> var initmarkup = [];
<del> initmarkup.push('\n<script type="application/javascript">\n');
<del>
<del> if (this.parseResult.controller) {
<del> var module = 'domains'
<del> initmarkup.push('\nrequire(["' + this.parseResult.controller + '"], function (module) {console.log("loaded domains controller!");} );');
<del> }
<del>
<del> if (typeof this.parseResult !== 'undefined' && typeof this.parseResult.elements !== 'undefined' && this.parseResult.elements.length > 0) {
<del>
<del> this.parseResult.elements.forEach(function (elem) {
<del> var im = elem.renderat == 'client' && elem.instanceid ? ',"text!/instances/' + elem.instanceid + '"' : '';
<del> var l = elem.locale
<del> initmarkup.push('\nrequire(["/modules/', elem.tag.module, '/client.js"'
<del> , ', "text!/modules/', elem.tag.module, '/main.html?type=json"'
<del> , im
<del> , ', "text!/modules/', elem.tag.module, '/locales/de_DE.js"'
<del> , '], '
<del> , ' function (module, template, instance, localefile) { \n\tmodule.initView("'
<del> , elem.id, '", template, instance, localefile) } );'
<del> );
<del> });
<del>
<del> }
<del>
<del> initmarkup.push('\n</script>\n');
<del> depmarkup.push(initmarkup.join(''));
<del>
<del> mod_mu.compileText('template2', this.preRenderResult);
<del> var stream = mod_mu.render('template2', data)
<del> .on('data', function (data) {
<del> out.push(data);
<del> })
<del> .on('end' , function () {
<del> self.renderResult = out.join('');
<del> // [TBD] yea, ugly, but works for now
<del> self.renderResult = self.renderResult.substring(0, self.renderResult.indexOf('</head>')) + depmarkup.join('')
<del> + self.renderResult.substring(self.renderResult.indexOf('</head>'));
<del> logger.debug('renderer ' + self.uuid + ' postRender complete');
<del> self.state = Renderer.STATES.COMPLETE;
<del> });
<del>}
<del>
<del>Renderer.prototype.getDependencies = function () {
<del> var css = []
<del> , script = []
<del> , locale = []
<del> , collected = {}
<del>
<del> collect(this);
<del> return {
<del> 'css' : css
<del> , 'script' : script
<del> , 'locale' : locale
<del> }
<del>
<del> function collect(renderer) {
<del> if (renderer.parseResult) {
<del> foreach(renderer.parseResult.dependencies.css, css);
<del> foreach(renderer.parseResult.dependencies.script, script);
<del> foreach(renderer.parseResult.dependencies.locale, locale);
<del> renderer.childRenderer.forEach(function (renderer) {
<del> collect(renderer)
<del> });
<del> }
<del> }
<del>
<del> function foreach (obj, target) {
<del> obj.forEach(function (url) {
<del> if (!collected[url]) {
<del> target.push(url);
<del> collected[url] = true;
<del> }
<del> });
<del> }
<del>}
<del>
<del>/**
<del> * From the module-relative URLs used in view templates, host-relative URLs are created.
<del> */
<del>Renderer.prototype.resolveUrls = function () {
<del> this.parseResult.dependencies.css = this.parseResult.dependencies.css.map(function (url) {
<del> return self.resolveUrl(url, true);
<del> });
<del> this.parseResult.dependencies.script = this.parseResult.dependencies.script.map(function (url) {
<del> return self.resolveUrl(url, true);
<del> });
<del> this.parseResult.dependencies.locale = this.parseResult.dependencies.locale.map(function (url) {
<del> return path + url;
<del> });
<del>}
<del>
<del>Renderer.prototype.resolveUrl = function (url, folder, specialDir) {
<del> if (!url) return null;
<del> if (url.indexOf(modulecontainer.COMPONENT_PROTOCOL) == 0) {
<del> var moduleId = url.substring(modulecontainer.COMPONENT_PROTOCOL.length
<del> , url.indexOf('/', modulecontainer.COMPONENT_PROTOCOL.length + 1));
<del> var path = url.substring(modulecontainer.COMPONENT_PROTOCOL.length + moduleId.length);
<del> var modulepath = modulecontainer.getModulePath(moduleId);
<del> var prefix = '';
<del> var specialDir = specialDir ? specialDir : '';
<del> path = mod_path.join(modulepath, specialDir, path);
<del> c('transformed ' + path)
<del> return path;
<del> } else if (url.indexOf('http://') === 0) {
<del> return url;
<del> } else {
<del> var np = mod_path.join(folder, url);
<del> c('local url, transformed ' + np);
<del> return np;
<del> }
<del> return url;
<del>}
<del>
<del>Renderer.prototype.resolveToHost = function () {
<del>
<del>}
<del>
<del>exports.Renderer = Renderer;
<del>
<del>
<del>
<del>
<del>
<del>
<del>function HTMLRenderer () {
<del>
<del>}
<del>HTMLRenderer.getViewBody = function (doc) {
<del> return doc.match(/<body[^>]*>([\s\S]*)<\/body>/mi)[1];
<del>} |
|
Java | apache-2.0 | d463daa025d9123feae42d63390487549bc24cbf | 0 | wildfly-swarm/wildfly-config-api,wildfly-swarm/wildfly-config-api | package org.wildfly.swarm.config.generator.generator;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bob McWhirter
*/
public class NameFixer {
public interface Fix {
String fix(String input);
}
public static class SimpleFix implements Fix {
private final String key;
public SimpleFix(String key) {
this.key = key;
}
@Override
public String fix(String input) {
StringBuffer output = new StringBuffer();
int cur = 0;
while ( cur < input.length() ) {
int loc = input.indexOf( this.key, cur );
if ( loc < 0 ) {
output.append( input.substring( cur ) );
break;
} else {
output.append(input.substring(cur, loc));
int nextCharLoc = loc + this.key.length();
if ( nextCharLoc < input.length() && Character.isUpperCase(input.charAt( nextCharLoc )) ) {
output.append(this.key.toUpperCase());
} else {
output.append(this.key);
}
cur = loc + this.key.length();
}
}
return output.toString();
}
}
public static class CustomFix implements Fix {
private final String key;
private final String replacement;
public CustomFix(String key, String replacement) {
this.key = key;
this.replacement = replacement;
}
@Override
public String fix(String input) {
return input.replace(this.key, this.replacement);
}
}
private static List<Fix> FIXES = new ArrayList<Fix>();
private static void simpleFix(String s) {
FIXES.add(new SimpleFix(s));
}
private static void customFix(String s, String r) {
FIXES.add(new CustomFix(s, r));
}
static {
customFix("Activemq", "ActiveMQ");
simpleFix("Acl");
simpleFix("Ajp");
simpleFix("Ee");
simpleFix("Ejb");
simpleFix("Ha");
simpleFix("Http");
simpleFix("Io");
simpleFix("Iiop");
simpleFix("Imap");
customFix("InVm", "InVM");
simpleFix("Jaxrs");
simpleFix("Jca");
simpleFix("Jdbc");
customFix("Jgroups", "JGroups");
simpleFix("Jms");
simpleFix("Jmx");
simpleFix("Jpa");
simpleFix("Jsf");
simpleFix("Jsp");
simpleFix("Jsse");
simpleFix("Mdb");
simpleFix("Msc");
simpleFix("Pop3");
simpleFix("Sasl");
simpleFix("Smtp");
simpleFix("Xa");
}
public static String fix(String input) {
for (Fix s : FIXES) {
input = s.fix(input);
}
return input;
}
}
| generator/src/main/java/org/wildfly/swarm/config/generator/generator/NameFixer.java | package org.wildfly.swarm.config.generator.generator;
import java.util.ArrayList;
import java.util.List;
/**
* @author Bob McWhirter
*/
public class NameFixer {
public interface Fix {
String fix(String input);
}
public static class SimpleFix implements Fix {
private final String key;
public SimpleFix(String key) {
this.key = key;
}
@Override
public String fix(String input) {
StringBuffer output = new StringBuffer();
int cur = 0;
while ( cur < input.length() ) {
int loc = input.indexOf( this.key, cur );
if ( loc < 0 ) {
System.err.println( "did not find: " + this.key );
output.append( input.substring( cur ) );
break;
} else {
output.append(input.substring(cur, loc));
int nextCharLoc = loc + this.key.length();
if ( nextCharLoc < input.length() && Character.isUpperCase(input.charAt( nextCharLoc )) ) {
System.err.println("found " + this.key + " at " + loc);
output.append(this.key.toUpperCase());
} else {
output.append(this.key);
}
cur = loc + this.key.length();
}
}
/*
return input.replace(this.key, this.key.toUpperCase());
int loc = input.indexOf( this.key );
int nextCharLoc = loc + this.key.length() + 1;
if ( input.length() > nextCharLoc ) {
char nextChar = input.charAt( nextCharLoc );
} else {
}
*/
System.err.println( input + " to " + output );
return output.toString();
}
}
public static class CustomFix implements Fix {
private final String key;
private final String replacement;
public CustomFix(String key, String replacement) {
this.key = key;
this.replacement = replacement;
}
@Override
public String fix(String input) {
return input.replace(this.key, this.replacement);
}
}
private static List<Fix> FIXES = new ArrayList<Fix>();
private static void simpleFix(String s) {
FIXES.add(new SimpleFix(s));
}
private static void customFix(String s, String r) {
FIXES.add(new CustomFix(s, r));
}
static {
customFix("Activemq", "ActiveMQ");
simpleFix("Acl");
simpleFix("Ajp");
simpleFix("Ee");
simpleFix("Ejb");
simpleFix("Ha");
simpleFix("Http");
simpleFix("Io");
simpleFix("Iiop");
simpleFix("Imap");
customFix("InVm", "InVM");
simpleFix("Jaxrs");
simpleFix("Jca");
simpleFix("Jdbc");
customFix("Jgroups", "JGroups");
simpleFix("Jms");
simpleFix("Jmx");
simpleFix("Jpa");
simpleFix("Jsf");
simpleFix("Jsp");
simpleFix("Jsse");
simpleFix("Mdb");
simpleFix("Msc");
simpleFix("Pop3");
simpleFix("Sasl");
simpleFix("Smtp");
simpleFix("Xa");
}
public static String fix(String input) {
for (Fix s : FIXES) {
input = s.fix(input);
}
return input;
}
}
| Remove debug printlns.
| generator/src/main/java/org/wildfly/swarm/config/generator/generator/NameFixer.java | Remove debug printlns. | <ide><path>enerator/src/main/java/org/wildfly/swarm/config/generator/generator/NameFixer.java
<ide> while ( cur < input.length() ) {
<ide> int loc = input.indexOf( this.key, cur );
<ide> if ( loc < 0 ) {
<del> System.err.println( "did not find: " + this.key );
<ide> output.append( input.substring( cur ) );
<ide> break;
<ide> } else {
<ide>
<ide> int nextCharLoc = loc + this.key.length();
<ide> if ( nextCharLoc < input.length() && Character.isUpperCase(input.charAt( nextCharLoc )) ) {
<del> System.err.println("found " + this.key + " at " + loc);
<ide> output.append(this.key.toUpperCase());
<ide> } else {
<ide> output.append(this.key);
<ide>
<ide> }
<ide> }
<del> /*
<del> return input.replace(this.key, this.key.toUpperCase());
<del> int loc = input.indexOf( this.key );
<del> int nextCharLoc = loc + this.key.length() + 1;
<del> if ( input.length() > nextCharLoc ) {
<del> char nextChar = input.charAt( nextCharLoc );
<del> } else {
<del>
<del> }
<del> */
<del>
<del> System.err.println( input + " to " + output );
<ide>
<ide> return output.toString();
<ide> } |
|
Java | bsd-3-clause | c42b2192c4153f3685d9d99c1148d9ba1616d7a3 | 0 | spakzad/ocs,fnussber/ocs,fnussber/ocs,arturog8m/ocs,spakzad/ocs,fnussber/ocs,arturog8m/ocs,arturog8m/ocs,spakzad/ocs,arturog8m/ocs,fnussber/ocs,spakzad/ocs | package edu.gemini.qpt.shared.sp;
import edu.gemini.pot.sp.SPComponentType;
import edu.gemini.spModel.core.Site;
import edu.gemini.spModel.data.PreImagingType;
import edu.gemini.spModel.gemini.acqcam.InstAcqCam;
import edu.gemini.spModel.gemini.altair.AltairAowfsGuider;
import edu.gemini.spModel.gemini.altair.AltairParams;
import edu.gemini.spModel.gemini.altair.InstAltair;
import edu.gemini.spModel.gemini.bhros.InstBHROS;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2OiwfsGuideProbe;
import edu.gemini.spModel.gemini.gems.Canopus;
import edu.gemini.spModel.gemini.gmos.*;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.DisperserNorth;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.FPUnitNorth;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.FilterNorth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.DisperserSouth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.FPUnitSouth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.FilterSouth;
import edu.gemini.spModel.gemini.gnirs.GNIRSParams;
import edu.gemini.spModel.gemini.gnirs.GnirsOiwfsGuideProbe;
import edu.gemini.spModel.gemini.gnirs.InstGNIRS;
import edu.gemini.spModel.gemini.gpi.Gpi;
import edu.gemini.spModel.gemini.gsaoi.Gsaoi;
import edu.gemini.spModel.gemini.gsaoi.GsaoiOdgw;
import edu.gemini.spModel.gemini.michelle.InstMichelle;
import edu.gemini.spModel.gemini.nici.InstNICI;
import edu.gemini.spModel.gemini.nici.NICIParams;
import edu.gemini.spModel.gemini.nici.NiciOiwfsGuideProbe;
import edu.gemini.spModel.gemini.nifs.InstNIFS;
import edu.gemini.spModel.gemini.nifs.NIFSParams;
import edu.gemini.spModel.gemini.nifs.NifsOiwfsGuideProbe;
import edu.gemini.spModel.gemini.niri.InstNIRI;
import edu.gemini.spModel.gemini.niri.Niri;
import edu.gemini.spModel.gemini.niri.NiriOiwfsGuideProbe;
import edu.gemini.spModel.gemini.phoenix.InstPhoenix;
import edu.gemini.spModel.gemini.texes.InstTexes;
import edu.gemini.spModel.gemini.texes.TexesParams;
import edu.gemini.spModel.gemini.trecs.InstTReCS;
import edu.gemini.spModel.gemini.trecs.TReCSParams;
import edu.gemini.spModel.guide.GuideProbe;
import edu.gemini.spModel.target.obsComp.PwfsGuideProbe;
import java.util.*;
@SuppressWarnings("unchecked")
public enum Inst {
// Note: alphabetical order: REL-293
ACQUISITION_CAMERA(InstAcqCam.SP_TYPE, true, true, true),
// REL-293: Combine Altair component and AOWFS to one item with NGS and LGS children
// (AOWFS child is needed as well, but is hidden)
ALTAIR(InstAltair.SP_TYPE, true, false, true,
AltairParams.GuideStarType.values(),
arrayOf(AltairParams.GuideStarType.NGS),
arrayOf(AltairAowfsGuider.instance)),
// Not currently in use
BHROS(InstBHROS.SP_TYPE, false, false, false),
CANOPUS(SPComponentType.QPT_CANOPUS, // new SPInstComponentType(SPInstComponentType.INST_BROAD_TYPE, "Canopus", "Canopus"),
false, true, true, Canopus.Wfs.values(), Canopus.Wfs.values()),
FLAMINGOS2(Flamingos2.SP_TYPE, false, true, false,
join(Flamingos2.FPUnit.values(), new Enum[]{Flamingos2OiwfsGuideProbe.instance}),
join(arrayOf(Flamingos2.FPUnit.FPU_NONE, Flamingos2.FPUnit.CUSTOM_MASK), new Enum[]{Flamingos2OiwfsGuideProbe.instance}),
join(Flamingos2.Disperser.values(), Flamingos2.Filter.values(), PreImagingType.values())),
GMOS_NORTH(InstGmosNorth.SP_TYPE, true, false, true,
join(FPUnitNorth.values(),
DisperserNorth.values(),
FilterNorth.values(),
GmosCommonType.DetectorManufacturer.values(),
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(new Enum[]{FPUnitNorth.FPU_NONE, FPUnitNorth.CUSTOM_MASK, DisperserNorth.MIRROR},
FilterNorth.values(),
new Enum[]{GmosCommonType.DetectorManufacturer.E2V},
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(GmosCommonType.UseNS.values(), PreImagingType.values())),
GMOS_SOUTH(InstGmosSouth.SP_TYPE, false, true, true,
join(FPUnitSouth.values(),
DisperserSouth.values(),
FilterSouth.values(),
GmosCommonType.DetectorManufacturer.values(),
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(new Enum[] { FPUnitSouth.FPU_NONE, FPUnitSouth.CUSTOM_MASK, DisperserSouth.MIRROR },
FilterSouth.values(),
new Enum[]{GmosCommonType.DetectorManufacturer.HAMAMATSU},
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(GmosCommonType.UseNS.values(), PreImagingType.values())),
GNIRS(InstGNIRS.SP_TYPE, true, false, false,
join(GNIRSParams.Disperser.values(), GNIRSParams.SlitWidth.values(), new Enum[]{GnirsOiwfsGuideProbe.instance}),
join(GNIRSParams.Disperser.values(), GNIRSParams.SlitWidth.values(), new Enum[]{GnirsOiwfsGuideProbe.instance}),
join(GNIRSParams.CrossDispersed.values(), GNIRSParams.Filter.values(), GNIRSParams.Camera.values())),
GPI(Gpi.SP_TYPE, false, true, false,
new Enum[0],
new Enum[0],
join(Gpi.Disperser.values(), Gpi.Filter.values())),
GSAOI(Gsaoi.SP_TYPE, false, true, true,
GsaoiOdgw.values(), GsaoiOdgw.values(), Gsaoi.Filter.values()),
MICHELLE(InstMichelle.SP_TYPE, true, false, false),
NICI(InstNICI.SP_TYPE, false, true, false,
new Enum[]{NiciOiwfsGuideProbe.instance},
new Enum[]{NiciOiwfsGuideProbe.instance},
join(NICIParams.FocalPlaneMask.values(), NICIParams.DichroicWheel.values(), NICIParams.Channel1FW.values(), NICIParams.Channel2FW.values())),
NIFS(InstNIFS.SP_TYPE, true, false, false,
new Enum[]{NifsOiwfsGuideProbe.instance},
new Enum[]{NifsOiwfsGuideProbe.instance},
join(NIFSParams.Disperser.values(), NIFSParams.Filter.values(), NIFSParams.Mask.values())),
NIRI(InstNIRI.SP_TYPE, true, false, false,
join(new Enum[]{NiriOiwfsGuideProbe.instance}, Niri.Filter.values()),
join(new Enum[]{NiriOiwfsGuideProbe.instance}),
join(Niri.Mask.values(), Niri.Disperser.values(), Niri.Camera.values())),
// Not currently in use
PHOENIX(InstPhoenix.SP_TYPE, false, false, false),
PWFS(SPComponentType.QPT_PWFS, // new SPInstComponentType(SPInstComponentType.INST_BROAD_TYPE, "PWFS", "PWFS"),
true, true, true, PwfsGuideProbe.values(), PwfsGuideProbe.values()),
// Not currently in use
TEXES(InstTexes.SP_TYPE, false, false, false,
new Enum[0], new Enum[0], TexesParams.Disperser.values()),
TRECS(InstTReCS.SP_TYPE, false, true, false,
join(TReCSParams.Disperser.values(), TReCSParams.Mask.values()),
join(TReCSParams.Disperser.values(), TReCSParams.Mask.values())),
VISITOR(SPComponentType.INSTRUMENT_VISITOR, true, true, false)
;
// Some instruments have different categories of options. This map allows
// us to assign a label to each type. If an option's class isn't in this map
// the category will be null (which is ok).
private static final Map<Class<? extends Enum>, String> CATEGORY_MAP = new HashMap<Class<? extends Enum>, String>();
static {
// GMOS-N
CATEGORY_MAP.put(FPUnitNorth.class, "Focal Plane Units");
CATEGORY_MAP.put(DisperserNorth.class, "Dispersers");
CATEGORY_MAP.put(FilterNorth.class, "Filters");
// GMOS-S
CATEGORY_MAP.put(FPUnitSouth.class, "Focal Plane Units");
CATEGORY_MAP.put(DisperserSouth.class, "Dispersers");
CATEGORY_MAP.put(FilterSouth.class, "Filters");
// GMOS-N/S
CATEGORY_MAP.put(GmosCommonType.DetectorManufacturer.class, "CCD Manufacturer");
// GNIRS
CATEGORY_MAP.put(GNIRSParams.Disperser.class, "Dispersers");
CATEGORY_MAP.put(GNIRSParams.SlitWidth.class, "Slits");
// TRECS
CATEGORY_MAP.put(TReCSParams.Disperser.class, "Dispersers");
CATEGORY_MAP.put(TReCSParams.Mask.class, "Slits");
}
// Some enum types represent custom masks
private static final Set<Enum> CUSTOM_MASKS = new HashSet<Enum>();
static {
CUSTOM_MASKS.add(FPUnitNorth.CUSTOM_MASK);
CUSTOM_MASKS.add(FPUnitSouth.CUSTOM_MASK);
}
private final SPComponentType spType;
private final boolean north, south;
private final boolean normallyAvailable;
private final Enum[] options, normallyAvailableOptions, hiddenOptions;
private final GuideProbe guideProbe;
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable) {
this(spType, north, south, normallyAvailable, new Enum[0], new Enum[0]);
}
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable,
Enum[] options, Enum[] normallyAvailableOptions) {
this(spType, north, south, normallyAvailable, options, normallyAvailableOptions, new Enum[0]);
};
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable,
Enum[] options, Enum[] normallyAvailableOptions, Enum[] hiddenOptions) {
assert spType != null;
this.spType = spType;
this.north = north;
this.south = south;
this.normallyAvailable = normallyAvailable;
this.options = options;
this.normallyAvailableOptions = normallyAvailableOptions;
this.hiddenOptions = hiddenOptions;
this.guideProbe = null;
}
public boolean isNormallyAvailable() {
return normallyAvailable;
}
public boolean isNormallyAvailable(Enum option) {
for (Enum o: normallyAvailableOptions)
if (o.equals(option)) return true;
return false;
}
public SPComponentType getSpType() {
return spType;
}
public GuideProbe getGuideProbe() {
return guideProbe;
}
public boolean existsAtSite(Site site) {
return
(Site.GS.equals(site) && south) ||
(Site.GN.equals(site) && north);
}
/**
* Returns this for instruments, or guideProbe for WFS
*/
public Enum getValue() {
if (getGuideProbe() instanceof Enum) return (Enum) getGuideProbe();
return this;
}
public Enum[] getOptions() {
return options;
}
/**
* Hidden options are options that should be treated as always selected, but are not shown for filtering.
* @return
*/
public Enum[] getHiddenOptions() {
return hiddenOptions;
}
public static String getCategory(Enum e) {
for (Class c = e.getClass(); c != null; c = c.getSuperclass()) {
String cat = CATEGORY_MAP.get(c);
if (cat != null)
return cat;
}
return null;
}
public static Inst forSpType(SPComponentType type) {
for (Inst f: values())
if (type.equals(f.getSpType())) return f;
throw new NoSuchElementException("Unknown " + Inst.class.getSimpleName() + ": " + type);
}
public static boolean isCustomMask(Enum e) {
return CUSTOM_MASKS.contains(e);
}
public static Enum[] join(Enum[]... arrays) {
int length = 0;
for (Enum[] array: arrays) length += array.length;
Enum[] ret = new Enum[length];
int i = 0;
for (Enum[] array: arrays)
for (Enum e: array)
ret[i++] = e;
return ret;
}
public static Enum[] arrayOf(Enum... arrays) {
return arrays;
}
@Override
public String toString() {
if (getSpType() != null) {
if (getSpType() == InstAltair.SP_TYPE) {
return "Altair"; // REL-293
}
return getSpType().readableStr;
}
if (getGuideProbe() != null) {
return getGuideProbe().toString();
}
return super.toString(); // should not happen
}
}
| bundle/edu.gemini.qpt.shared/src/main/java/edu/gemini/qpt/shared/sp/Inst.java | package edu.gemini.qpt.shared.sp;
import edu.gemini.pot.sp.SPComponentType;
import edu.gemini.spModel.core.Site;
import edu.gemini.spModel.data.PreImagingType;
import edu.gemini.spModel.gemini.acqcam.InstAcqCam;
import edu.gemini.spModel.gemini.altair.AltairAowfsGuider;
import edu.gemini.spModel.gemini.altair.AltairParams;
import edu.gemini.spModel.gemini.altair.InstAltair;
import edu.gemini.spModel.gemini.bhros.InstBHROS;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2OiwfsGuideProbe;
import edu.gemini.spModel.gemini.gems.Canopus;
import edu.gemini.spModel.gemini.gmos.*;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.DisperserNorth;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.FPUnitNorth;
import edu.gemini.spModel.gemini.gmos.GmosNorthType.FilterNorth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.DisperserSouth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.FPUnitSouth;
import edu.gemini.spModel.gemini.gmos.GmosSouthType.FilterSouth;
import edu.gemini.spModel.gemini.gnirs.GNIRSParams;
import edu.gemini.spModel.gemini.gnirs.GnirsOiwfsGuideProbe;
import edu.gemini.spModel.gemini.gnirs.InstGNIRS;
import edu.gemini.spModel.gemini.gpi.Gpi;
import edu.gemini.spModel.gemini.gsaoi.Gsaoi;
import edu.gemini.spModel.gemini.gsaoi.GsaoiOdgw;
import edu.gemini.spModel.gemini.michelle.InstMichelle;
import edu.gemini.spModel.gemini.nici.InstNICI;
import edu.gemini.spModel.gemini.nici.NICIParams;
import edu.gemini.spModel.gemini.nici.NiciOiwfsGuideProbe;
import edu.gemini.spModel.gemini.nifs.InstNIFS;
import edu.gemini.spModel.gemini.nifs.NIFSParams;
import edu.gemini.spModel.gemini.nifs.NifsOiwfsGuideProbe;
import edu.gemini.spModel.gemini.niri.InstNIRI;
import edu.gemini.spModel.gemini.niri.Niri;
import edu.gemini.spModel.gemini.niri.NiriOiwfsGuideProbe;
import edu.gemini.spModel.gemini.phoenix.InstPhoenix;
import edu.gemini.spModel.gemini.texes.InstTexes;
import edu.gemini.spModel.gemini.texes.TexesParams;
import edu.gemini.spModel.gemini.trecs.InstTReCS;
import edu.gemini.spModel.gemini.trecs.TReCSParams;
import edu.gemini.spModel.guide.GuideProbe;
import edu.gemini.spModel.target.obsComp.PwfsGuideProbe;
import java.util.*;
@SuppressWarnings("unchecked")
public enum Inst {
// Note: alphabetical order: REL-293
ACQUISITION_CAMERA(InstAcqCam.SP_TYPE, true, true, true),
// REL-293: Combine Altair component and AOWFS to one item with NGS and LGS children
// (AOWFS child is needed as well, but is hidden)
ALTAIR(InstAltair.SP_TYPE, true, false, true,
AltairParams.GuideStarType.values(),
arrayOf(AltairParams.GuideStarType.NGS),
arrayOf(AltairAowfsGuider.instance)),
// Not currently in use
BHROS(InstBHROS.SP_TYPE, false, false, false),
CANOPUS(SPComponentType.QPT_CANOPUS, // new SPInstComponentType(SPInstComponentType.INST_BROAD_TYPE, "Canopus", "Canopus"),
false, true, true, Canopus.Wfs.values(), Canopus.Wfs.values()),
FLAMINGOS2(Flamingos2.SP_TYPE, false, true, false,
join(Flamingos2.FPUnit.values(), new Enum[]{Flamingos2OiwfsGuideProbe.instance}),
join(arrayOf(Flamingos2.FPUnit.FPU_NONE, Flamingos2.FPUnit.CUSTOM_MASK), new Enum[]{Flamingos2OiwfsGuideProbe.instance}),
join(Flamingos2.Disperser.values(), Flamingos2.Filter.values(), PreImagingType.values())),
GMOS_NORTH(InstGmosNorth.SP_TYPE, true, false, true,
join(FPUnitNorth.values(),
DisperserNorth.values(),
FilterNorth.values(),
GmosCommonType.DetectorManufacturer.values(),
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(new Enum[]{FPUnitNorth.FPU_NONE, FPUnitNorth.CUSTOM_MASK, DisperserNorth.MIRROR},
FilterNorth.values(),
new Enum[]{GmosCommonType.DetectorManufacturer.E2V},
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(GmosCommonType.UseNS.values(), PreImagingType.values())),
GMOS_SOUTH(InstGmosSouth.SP_TYPE, false, true, true,
join(FPUnitSouth.values(),
DisperserSouth.values(),
FilterSouth.values(),
GmosCommonType.DetectorManufacturer.values(),
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(new Enum[] { FPUnitSouth.FPU_NONE, FPUnitSouth.CUSTOM_MASK, DisperserSouth.MIRROR },
FilterSouth.values(),
new Enum[]{GmosCommonType.DetectorManufacturer.E2V},
new Enum[]{GmosOiwfsGuideProbe.instance}),
join(GmosCommonType.UseNS.values(), PreImagingType.values())),
GNIRS(InstGNIRS.SP_TYPE, true, false, false,
join(GNIRSParams.Disperser.values(), GNIRSParams.SlitWidth.values(), new Enum[]{GnirsOiwfsGuideProbe.instance}),
join(GNIRSParams.Disperser.values(), GNIRSParams.SlitWidth.values(), new Enum[]{GnirsOiwfsGuideProbe.instance}),
join(GNIRSParams.CrossDispersed.values(), GNIRSParams.Filter.values(), GNIRSParams.Camera.values())),
GPI(Gpi.SP_TYPE, false, true, false,
new Enum[0],
new Enum[0],
join(Gpi.Disperser.values(), Gpi.Filter.values())),
GSAOI(Gsaoi.SP_TYPE, false, true, true,
GsaoiOdgw.values(), GsaoiOdgw.values(), Gsaoi.Filter.values()),
MICHELLE(InstMichelle.SP_TYPE, true, false, false),
NICI(InstNICI.SP_TYPE, false, true, false,
new Enum[]{NiciOiwfsGuideProbe.instance},
new Enum[]{NiciOiwfsGuideProbe.instance},
join(NICIParams.FocalPlaneMask.values(), NICIParams.DichroicWheel.values(), NICIParams.Channel1FW.values(), NICIParams.Channel2FW.values())),
NIFS(InstNIFS.SP_TYPE, true, false, false,
new Enum[]{NifsOiwfsGuideProbe.instance},
new Enum[]{NifsOiwfsGuideProbe.instance},
join(NIFSParams.Disperser.values(), NIFSParams.Filter.values(), NIFSParams.Mask.values())),
NIRI(InstNIRI.SP_TYPE, true, false, false,
join(new Enum[]{NiriOiwfsGuideProbe.instance}, Niri.Filter.values()),
join(new Enum[]{NiriOiwfsGuideProbe.instance}),
join(Niri.Mask.values(), Niri.Disperser.values(), Niri.Camera.values())),
// Not currently in use
PHOENIX(InstPhoenix.SP_TYPE, false, false, false),
PWFS(SPComponentType.QPT_PWFS, // new SPInstComponentType(SPInstComponentType.INST_BROAD_TYPE, "PWFS", "PWFS"),
true, true, true, PwfsGuideProbe.values(), PwfsGuideProbe.values()),
// Not currently in use
TEXES(InstTexes.SP_TYPE, false, false, false,
new Enum[0], new Enum[0], TexesParams.Disperser.values()),
TRECS(InstTReCS.SP_TYPE, false, true, false,
join(TReCSParams.Disperser.values(), TReCSParams.Mask.values()),
join(TReCSParams.Disperser.values(), TReCSParams.Mask.values())),
VISITOR(SPComponentType.INSTRUMENT_VISITOR, true, true, false)
;
// Some instruments have different categories of options. This map allows
// us to assign a label to each type. If an option's class isn't in this map
// the category will be null (which is ok).
private static final Map<Class<? extends Enum>, String> CATEGORY_MAP = new HashMap<Class<? extends Enum>, String>();
static {
// GMOS-N
CATEGORY_MAP.put(FPUnitNorth.class, "Focal Plane Units");
CATEGORY_MAP.put(DisperserNorth.class, "Dispersers");
CATEGORY_MAP.put(FilterNorth.class, "Filters");
// GMOS-S
CATEGORY_MAP.put(FPUnitSouth.class, "Focal Plane Units");
CATEGORY_MAP.put(DisperserSouth.class, "Dispersers");
CATEGORY_MAP.put(FilterSouth.class, "Filters");
// GMOS-N/S
CATEGORY_MAP.put(GmosCommonType.DetectorManufacturer.class, "CCD Manufacturer");
// GNIRS
CATEGORY_MAP.put(GNIRSParams.Disperser.class, "Dispersers");
CATEGORY_MAP.put(GNIRSParams.SlitWidth.class, "Slits");
// TRECS
CATEGORY_MAP.put(TReCSParams.Disperser.class, "Dispersers");
CATEGORY_MAP.put(TReCSParams.Mask.class, "Slits");
}
// Some enum types represent custom masks
private static final Set<Enum> CUSTOM_MASKS = new HashSet<Enum>();
static {
CUSTOM_MASKS.add(FPUnitNorth.CUSTOM_MASK);
CUSTOM_MASKS.add(FPUnitSouth.CUSTOM_MASK);
}
private final SPComponentType spType;
private final boolean north, south;
private final boolean normallyAvailable;
private final Enum[] options, normallyAvailableOptions, hiddenOptions;
private final GuideProbe guideProbe;
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable) {
this(spType, north, south, normallyAvailable, new Enum[0], new Enum[0]);
}
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable,
Enum[] options, Enum[] normallyAvailableOptions) {
this(spType, north, south, normallyAvailable, options, normallyAvailableOptions, new Enum[0]);
};
Inst(SPComponentType spType, boolean north, boolean south, boolean normallyAvailable,
Enum[] options, Enum[] normallyAvailableOptions, Enum[] hiddenOptions) {
assert spType != null;
this.spType = spType;
this.north = north;
this.south = south;
this.normallyAvailable = normallyAvailable;
this.options = options;
this.normallyAvailableOptions = normallyAvailableOptions;
this.hiddenOptions = hiddenOptions;
this.guideProbe = null;
}
public boolean isNormallyAvailable() {
return normallyAvailable;
}
public boolean isNormallyAvailable(Enum option) {
for (Enum o: normallyAvailableOptions)
if (o.equals(option)) return true;
return false;
}
public SPComponentType getSpType() {
return spType;
}
public GuideProbe getGuideProbe() {
return guideProbe;
}
public boolean existsAtSite(Site site) {
return
(Site.GS.equals(site) && south) ||
(Site.GN.equals(site) && north);
}
/**
* Returns this for instruments, or guideProbe for WFS
*/
public Enum getValue() {
if (getGuideProbe() instanceof Enum) return (Enum) getGuideProbe();
return this;
}
public Enum[] getOptions() {
return options;
}
/**
* Hidden options are options that should be treated as always selected, but are not shown for filtering.
* @return
*/
public Enum[] getHiddenOptions() {
return hiddenOptions;
}
public static String getCategory(Enum e) {
for (Class c = e.getClass(); c != null; c = c.getSuperclass()) {
String cat = CATEGORY_MAP.get(c);
if (cat != null)
return cat;
}
return null;
}
public static Inst forSpType(SPComponentType type) {
for (Inst f: values())
if (type.equals(f.getSpType())) return f;
throw new NoSuchElementException("Unknown " + Inst.class.getSimpleName() + ": " + type);
}
public static boolean isCustomMask(Enum e) {
return CUSTOM_MASKS.contains(e);
}
public static Enum[] join(Enum[]... arrays) {
int length = 0;
for (Enum[] array: arrays) length += array.length;
Enum[] ret = new Enum[length];
int i = 0;
for (Enum[] array: arrays)
for (Enum e: array)
ret[i++] = e;
return ret;
}
public static Enum[] arrayOf(Enum... arrays) {
return arrays;
}
@Override
public String toString() {
if (getSpType() != null) {
if (getSpType() == InstAltair.SP_TYPE) {
return "Altair"; // REL-293
}
return getSpType().readableStr;
}
if (getGuideProbe() != null) {
return getGuideProbe().toString();
}
return super.toString(); // should not happen
}
}
| REL-2148: make hamamatsu default GMOS-S option
| bundle/edu.gemini.qpt.shared/src/main/java/edu/gemini/qpt/shared/sp/Inst.java | REL-2148: make hamamatsu default GMOS-S option | <ide><path>undle/edu.gemini.qpt.shared/src/main/java/edu/gemini/qpt/shared/sp/Inst.java
<ide> new Enum[]{GmosOiwfsGuideProbe.instance}),
<ide> join(new Enum[] { FPUnitSouth.FPU_NONE, FPUnitSouth.CUSTOM_MASK, DisperserSouth.MIRROR },
<ide> FilterSouth.values(),
<del> new Enum[]{GmosCommonType.DetectorManufacturer.E2V},
<add> new Enum[]{GmosCommonType.DetectorManufacturer.HAMAMATSU},
<ide> new Enum[]{GmosOiwfsGuideProbe.instance}),
<ide> join(GmosCommonType.UseNS.values(), PreImagingType.values())),
<ide> |
|
JavaScript | bsd-3-clause | e04d91f69b9954a7a9b1e4d171852c9afa102442 | 0 | Gapminder/vizabi,Gapminder/vizabi,vizabi/vizabi,vizabi/vizabi,Gapminder/vizabi | import * as utils from "base/utils";
import DataConnected from "models/dataconnected";
/*!
* VIZABI Entities Model
*/
const EntitiesModel = DataConnected.extend({
/**
* Default values for this model
*/
getClassDefaults() {
const defaults = {
show: {},
showFallback: {},
showItemsMaxCount: null,
filter: {},
dim: null,
skipFilter: false
};
return utils.deepExtend(this._super(), defaults);
},
objectLeafs: ["show", "showFallback", "filter", "autoconfig"],
dataConnectedChildren: ["show", "dim", "grouping"],
/**
* Initializes the entities model.
* @param {Object} values The initial values of this model
* @param parent A reference to the parent model
* @param {Object} bind Initial events to bind
*/
init(name, values, parent, bind) {
this._type = "entities";
this._super(name, values, parent, bind);
},
preloadData() {
this.dataSource = this.getClosestModel(this.data || "data");
return this._super();
},
afterPreload() {
this.autoconfigureModel();
},
autoconfigureModel() {
if (!this.dim && this.autoconfig) {
const concept = this.dataSource.getConcept(this.autoconfig);
if (concept) this.dim = concept.concept;
utils.printAutoconfigResult(this);
}
},
setInterModelListeners() {
this.getClosestModel("locale").on("dataConnectedChange", this.handleDataConnectedChange.bind(this));
},
validate() {
this._super();
if (!this.showFallback[this.dim] && !this.showItemsMaxCount) return;
const dimShowFilter = this.show[this.dim] || (this.show.$and && this.show.$and.filter(f => f[this.dim])[0]);
if (!dimShowFilter) {
if (this.showFallback[this.dim]) {
this.show = { [this.dim]: utils.deepClone(this.showFallback[this.dim]) };
}
} else if (dimShowFilter.$in && this.showItemsMaxCount && dimShowFilter.$in.length > this.showItemsMaxCount) {
dimShowFilter.$in.splice(0, dimShowFilter.$in.length - this.showItemsMaxCount);
this.show = utils.deepClone(this.show);
}
},
handleDataConnectedChange(evt) {
//defer is necessary because other events might be queued.
//load right after such events
utils.defer(() => {
this.startLoading()
.catch(utils.warn);
});
},
_isLoading() {
return (!this._loadedOnce || this._loadCall);
},
loadData() {
this.setReady(false);
this._loadCall = true;
const _this = this;
if (!this.dim) {
this._entitySets = {};
this._entitySetsData = {};
this._entitySetsValues = {};
return Promise.resolve();
}
const dim = this.dim;
this._entitySets = { [dim]: this._root.dataManager.getAvailableDataForKey(dim, null, "entities")
.filter(d => d.value !== dim && ["entity_set", "entity_domain"].includes(this._root.dataManager.getConceptProperty(d.value, "concept_type")))
.map(d => d.value) };
if (!this._entitySets[dim].length) {
this._entitySetsValues = { [dim]: [] };
this._entitySetsData = { [dim]: {} };
return Promise.resolve();
}
const queryAddition = { "language": this.getClosestModel("locale").id };
const loadPromises = [this._root.dataManager.getDimensionValues(dim, this._entitySets[dim], queryAddition)]
.concat(this._entitySets[dim].map(entitySetName => this._root.dataManager.getDimensionValues(entitySetName, ["name"], queryAddition)));
return Promise.all(loadPromises).then(data => {
_this._entitySetsValues = { [dim]: data[0] };
_this._entitySetsData = { [dim]: {} };
_this._entitySets[dim].forEach((key, index) => {
_this._entitySetsData[dim][key] = data[index + 1];
});
});
},
getEntitySets(type = "") {
return this["_entitySets" + utils.capitalize(type)][this.dim];
},
/**
* Gets the dimensions in this entities
* @returns {String} String with dimension
*/
getDimension() {
return this.dim;
},
setDimension(dim) {
if (this.dim === dim) return;
const props = {};
props.show = {};
props.dim = dim;
this.set(props);
},
/**
* Gets the filter in this entities
* @returns {Array} Array of unique values
*/
getFilter({ entityTypeRequest } = {}) {
const filter = utils.deepClone(this.filter[this.dim] || {});
if (entityTypeRequest || this.skipFilter) return filter;
const show = utils.deepClone(this.show);
if (show[this.dim] && utils.isEmpty(show[this.dim])) {
delete show[this.dim];
}
const $and = [];
if (!utils.isEmpty(filter)) $and.push(filter);
if (!utils.isEmpty(show)) $and.push(show);
if ($and.length > 1) {
return { $and };
}
return $and[0] || {};
},
/**
* Shows or unshows an entity from the set
*/
showEntity(d) {
//clear selected countries when showing something new
const newShow = utils.deepClone(this.show);
const dimension = this.getDimension();
let _d;
if (!utils.isArray(d)) {
_d = [d];
} else {
_d = d;
}
const showFilter = newShow[dimension] || (newShow.$and || []).filter(f => f[dimension])[0] || { $in: [] };
utils.forEach(_d, d => {
const value = d[dimension];
if (this.isShown(d)) {
showFilter["$in"] = showFilter["$in"].filter(d => d !== value);
} else {
showFilter["$in"] = showFilter["$in"].concat(value);
}
});
if (showFilter["$in"].length === 0) {
if (newShow.$and) {
newShow.$and = newShow.$and.filter(f => !f[dimension]);
} else {
delete newShow[dimension];
}
} else {
if (newShow.$and) {
newShow.$and.push({ [dimension]: showFilter });
} else {
newShow[dimension] = showFilter;
}
}
this.show = newShow;
},
/**
* Selects an entity from the set
* @returns {Boolean} whether the item is shown or not
*/
isShown(d) {
const dimension = this.getDimension();
const { $in = [] } = this.show[dimension] || (this.show.$and || []).filter(f => f[dimension])[0] || {};
return $in.includes(d[dimension]);
},
isInShowFilter(d, category) {
const dim = this.getDimension();
const key = d[dim];
const filter = (this.show.$and || [this.show]).filter(f => f[category])[0] || {};
return utils.getProp(filter, [category, "$in"], []).includes(d[category]);
},
/**
* Clears showing of items
*/
clearShow() {
const dimension = this.getDimension();
const show = utils.deepClone(this.show);
delete show[dimension];
this.show = show;
},
getFilteredEntities() {
const dimension = this.getDimension();
const { $in = [] } = this.show[dimension] || {};
return $in.map(m => ({ [dimension]: m }));
},
isEntities() {
return true;
}
});
export default EntitiesModel;
| src/models/entities.js | import * as utils from "base/utils";
import DataConnected from "models/dataconnected";
/*!
* VIZABI Entities Model
*/
const EntitiesModel = DataConnected.extend({
/**
* Default values for this model
*/
getClassDefaults() {
const defaults = {
show: {},
showFallback: {},
showItemsMaxCount: null,
filter: {},
dim: null,
skipFilter: false
};
return utils.deepExtend(this._super(), defaults);
},
objectLeafs: ["show", "showFallback", "filter", "autoconfig"],
dataConnectedChildren: ["show", "dim", "grouping"],
/**
* Initializes the entities model.
* @param {Object} values The initial values of this model
* @param parent A reference to the parent model
* @param {Object} bind Initial events to bind
*/
init(name, values, parent, bind) {
this._type = "entities";
this._super(name, values, parent, bind);
},
preloadData() {
this.dataSource = this.getClosestModel(this.data || "data");
return this._super();
},
afterPreload() {
this.autoconfigureModel();
},
autoconfigureModel() {
if (!this.dim && this.autoconfig) {
const concept = this.dataSource.getConcept(this.autoconfig);
if (concept) this.dim = concept.concept;
utils.printAutoconfigResult(this);
}
},
setInterModelListeners() {
this.getClosestModel("locale").on("dataConnectedChange", this.loadData.bind(this));
},
validate() {
this._super();
if (!this.showFallback[this.dim] && !this.showItemsMaxCount) return;
const dimShowFilter = this.show[this.dim] || (this.show.$and && this.show.$and.filter(f => f[this.dim])[0]);
if (!dimShowFilter) {
if (this.showFallback[this.dim]) {
this.show = { [this.dim]: utils.deepClone(this.showFallback[this.dim]) };
}
} else if (dimShowFilter.$in && this.showItemsMaxCount && dimShowFilter.$in.length > this.showItemsMaxCount) {
dimShowFilter.$in.splice(0, dimShowFilter.$in.length - this.showItemsMaxCount);
this.show = utils.deepClone(this.show);
}
},
_isLoading() {
return (!this._loadedOnce || this._loadCall);
},
loadData() {
this.setReady(false);
this._loadCall = true;
const _this = this;
if (!this.dim) {
this._entitySets = {};
this._entitySetsData = {};
this._entitySetsValues = {};
return Promise.resolve();
}
const dim = this.dim;
this._entitySets = { [dim]: this._root.dataManager.getAvailableDataForKey(dim, null, "entities")
.filter(d => d.value !== dim && ["entity_set", "entity_domain"].includes(this._root.dataManager.getConceptProperty(d.value, "concept_type")))
.map(d => d.value) };
if (!this._entitySets[dim].length) {
this._entitySetsValues = { [dim]: [] };
this._entitySetsData = { [dim]: {} };
return Promise.resolve();
}
const queryAddition = { "language": this.getClosestModel("locale").id };
const loadPromises = [this._root.dataManager.getDimensionValues(dim, this._entitySets[dim], queryAddition)]
.concat(this._entitySets[dim].map(entitySetName => this._root.dataManager.getDimensionValues(entitySetName, ["name"], queryAddition)));
return Promise.all(loadPromises).then(data => {
_this._entitySetsValues = { [dim]: data[0] };
_this._entitySetsData = { [dim]: {} };
_this._entitySets[dim].forEach((key, index) => {
_this._entitySetsData[dim][key] = data[index + 1];
});
});
},
getEntitySets(type = "") {
return this["_entitySets" + utils.capitalize(type)][this.dim];
},
/**
* Gets the dimensions in this entities
* @returns {String} String with dimension
*/
getDimension() {
return this.dim;
},
setDimension(dim) {
if (this.dim === dim) return;
const props = {};
props.show = {};
props.dim = dim;
this.set(props);
},
/**
* Gets the filter in this entities
* @returns {Array} Array of unique values
*/
getFilter({ entityTypeRequest } = {}) {
const filter = utils.deepClone(this.filter[this.dim] || {});
if (entityTypeRequest || this.skipFilter) return filter;
const show = utils.deepClone(this.show);
if (show[this.dim] && utils.isEmpty(show[this.dim])) {
delete show[this.dim];
}
const $and = [];
if (!utils.isEmpty(filter)) $and.push(filter);
if (!utils.isEmpty(show)) $and.push(show);
if ($and.length > 1) {
return { $and };
}
return $and[0] || {};
},
/**
* Shows or unshows an entity from the set
*/
showEntity(d) {
//clear selected countries when showing something new
const newShow = utils.deepClone(this.show);
const dimension = this.getDimension();
let _d;
if (!utils.isArray(d)) {
_d = [d];
} else {
_d = d;
}
const showFilter = newShow[dimension] || (newShow.$and || []).filter(f => f[dimension])[0] || { $in: [] };
utils.forEach(_d, d => {
const value = d[dimension];
if (this.isShown(d)) {
showFilter["$in"] = showFilter["$in"].filter(d => d !== value);
} else {
showFilter["$in"] = showFilter["$in"].concat(value);
}
});
if (showFilter["$in"].length === 0) {
if (newShow.$and) {
newShow.$and = newShow.$and.filter(f => !f[dimension]);
} else {
delete newShow[dimension];
}
} else {
if (newShow.$and) {
newShow.$and.push({ [dimension]: showFilter });
} else {
newShow[dimension] = showFilter;
}
}
this.show = newShow;
},
/**
* Selects an entity from the set
* @returns {Boolean} whether the item is shown or not
*/
isShown(d) {
const dimension = this.getDimension();
const { $in = [] } = this.show[dimension] || (this.show.$and || []).filter(f => f[dimension])[0] || {};
return $in.includes(d[dimension]);
},
isInShowFilter(d, category) {
const dim = this.getDimension();
const key = d[dim];
const filter = (this.show.$and || [this.show]).filter(f => f[category])[0] || {};
return utils.getProp(filter, [category, "$in"], []).includes(d[category]);
},
/**
* Clears showing of items
*/
clearShow() {
const dimension = this.getDimension();
const show = utils.deepClone(this.show);
delete show[dimension];
this.show = show;
},
getFilteredEntities() {
const dimension = this.getDimension();
const { $in = [] } = this.show[dimension] || {};
return $in.map(m => ({ [dimension]: m }));
},
isEntities() {
return true;
}
});
export default EntitiesModel;
| fix hang on language change
| src/models/entities.js | fix hang on language change | <ide><path>rc/models/entities.js
<ide> },
<ide>
<ide> setInterModelListeners() {
<del> this.getClosestModel("locale").on("dataConnectedChange", this.loadData.bind(this));
<add> this.getClosestModel("locale").on("dataConnectedChange", this.handleDataConnectedChange.bind(this));
<ide> },
<ide>
<ide> validate() {
<ide> dimShowFilter.$in.splice(0, dimShowFilter.$in.length - this.showItemsMaxCount);
<ide> this.show = utils.deepClone(this.show);
<ide> }
<add> },
<add>
<add> handleDataConnectedChange(evt) {
<add> //defer is necessary because other events might be queued.
<add> //load right after such events
<add> utils.defer(() => {
<add> this.startLoading()
<add> .catch(utils.warn);
<add> });
<ide> },
<ide>
<ide> _isLoading() { |
|
Java | apache-2.0 | d93a098ced317979e91746382a0bc539ca449164 | 0 | fhieber/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,gwenniger/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,kpu/joshua,fhieber/incubator-joshua,kpu/joshua,gwenniger/joshua,gwenniger/joshua,lukeorland/joshua,lukeorland/joshua,fhieber/incubator-joshua,kpu/joshua,thammegowda/incubator-joshua,lukeorland/joshua,kpu/joshua,fhieber/incubator-joshua,lukeorland/joshua,gwenniger/joshua,thammegowda/incubator-joshua,gwenniger/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,kpu/joshua,lukeorland/joshua,thammegowda/incubator-joshua,thammegowda/incubator-joshua,kpu/joshua,gwenniger/joshua,fhieber/incubator-joshua,lukeorland/joshua | /* This file is part of the Joshua Machine Translation System.
*
* Joshua 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.jhu.sa.util.suffix_array;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import joshua.decoder.ff.tm.Rule;
import joshua.util.CommandLineParser;
import joshua.util.CommandLineParser.Option;
import joshua.util.lexprob.LexicalProbabilities;
import joshua.util.sentence.Vocabulary;
/**
*
* @author Lane Schwartz
* @version $LastChangedDate$
*/
public class ExtractRules {
/** Logger for this class. */
private static final Logger logger = Logger.getLogger(ExtractRules.class.getName());
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try {
CommandLineParser commandLine = new CommandLineParser();
Option<String> source = commandLine.addStringOption('f',"source","SOURCE_FILE","Source language training file");
Option<String> target = commandLine.addStringOption('e',"target","TARGET_FILE","Target language training file");
Option<String> alignment = commandLine.addStringOption('a',"alignments","ALIGNMENTS_FILE","Source-target alignments training file");
Option<String> test = commandLine.addStringOption('t',"test","TEST_FILE","Source language test file");
Option<String> output = commandLine.addStringOption('o',"output","OUTPUT_FILE","-","Output file");
Option<String> encoding = commandLine.addStringOption("encoding","ENCODING","UTF-8","File encoding format");
Option<Integer> lexSampleSize = commandLine.addIntegerOption("lexSampleSize","LEX_SAMPLE_SIZE",100, "Size to use when sampling for lexical probability calculations");
Option<Integer> ruleSampleSize = commandLine.addIntegerOption("ruleSampleSize","RULE_SAMPLE_SIZE",100, "Maximum number of rules to store at each node in the prefix tree");
Option<Integer> maxPhraseSpan = commandLine.addIntegerOption("maxPhraseSpan","MAX_PHRASE_SPAN",10, "Max phrase span");
Option<Integer> maxPhraseLength = commandLine.addIntegerOption("maxPhraseLength","MAX_PHRASE_LENGTH",10, "Max phrase length");
Option<Integer> maxNonterminals = commandLine.addIntegerOption("maxNonterminals","MAX_NONTERMINALS",2, "Max nonterminals");
// Option<String> target_given_source_counts = commandLine.addStringOption("target-given-source-counts","FILENAME","file containing co-occurence counts of source and target word pairs, sorted by source words");
// Option<String> source_given_target_counts = commandLine.addStringOption("source-given-target-counts","FILENAME","file containing co-occurence counts of target and source word pairs, sorted by target words");
Option<Boolean> output_gz = commandLine.addBooleanOption("output-gzipped",false,"snould the outpu file be gzipped");
// Option<Boolean> target_given_source_gz = commandLine.addBooleanOption("target-given-source-gzipped",false,"is the target given source word pair counts file gzipped");
// Option<Boolean> source_given_target_gz = commandLine.addBooleanOption("source-given-target-gzipped",false,"is the source given target word pair counts file gzipped");
commandLine.parse(args);
// Set System.out and System.err to use the provided character encoding
try {
System.setOut(new PrintStream(System.out, true, commandLine.getValue(encoding)));
System.setErr(new PrintStream(System.err, true, commandLine.getValue(encoding)));
} catch (UnsupportedEncodingException e1) {
System.err.println(commandLine.getValue(encoding) + " is not a valid encoding; using system default encoding for System.out and System.err.");
} catch (SecurityException e2) {
System.err.println("Security manager is configured to disallow changes to System.out or System.err; using system default encoding.");
}
// Lane - TODO -
//SuffixArray.INVERTED_INDEX_PRECOMPUTATION_MIN_FREQ = commandLine.getValue("CACHE_PRECOMPUTATION_FREQUENCY_THRESHOLD");
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language vocabulary.");
String sourceFileName = commandLine.getValue(source);
Vocabulary sourceVocab = new Vocabulary();
int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language corpus array.");
CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language suffix arra.");
SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language vocabulary.");
String targetFileName = commandLine.getValue(target);
Vocabulary targetVocab = new Vocabulary();
int[] targetWordsSentences = SuffixArrayFactory.createVocabulary(commandLine.getValue(target), targetVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language corpus array.");
CorpusArray targetCorpusArray = SuffixArrayFactory.createCorpusArray(targetFileName, targetVocab, targetWordsSentences[0], targetWordsSentences[1]);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language suffix array.");
SuffixArray targetSuffixArray = SuffixArrayFactory.createSuffixArray(targetCorpusArray);
if (logger.isLoggable(Level.FINE)) logger.fine("Reading alignment data.");
String alignmentFileName = commandLine.getValue(alignment);
AlignmentArray alignmentArray = SuffixArrayFactory.createAlignmentArray(alignmentFileName, sourceSuffixArray, targetSuffixArray);
// Set up the source text for reading
// Scanner target_given_source;
// if (commandLine.getValue(target_given_source_counts).endsWith(".gz") || commandLine.getValue(target_given_source_gz))
// target_given_source = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(target_given_source_counts))),commandLine.getValue(encoding))));
// else
// target_given_source = new Scanner( new File(commandLine.getValue(target_given_source_counts)), commandLine.getValue(encoding));
// // Set up the target text for reading
// Scanner source_given_target;
// if (commandLine.getValue(source_given_target_counts).endsWith(".gz") || commandLine.getValue(source_given_target_gz))
// source_given_target = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(source_given_target_counts))),commandLine.getValue(encoding))));
// else
// source_given_target = new Scanner( new File(commandLine.getValue(source_given_target_counts)), commandLine.getValue(encoding));
PrintStream out;
if ("-".equals(commandLine.getValue(output))) {
out = System.out;
} else if (commandLine.getValue(output).endsWith(".gz") || commandLine.getValue(output_gz)) {
//XXX This currently doesn't work
out = new PrintStream(new GZIPOutputStream(new FileOutputStream(commandLine.getValue(output))));
System.err.println("GZIP output not currently working properly");
System.exit(-1);
} else {
out = new PrintStream(commandLine.getValue(output));
}
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing lexical probabilities table");
LexicalProbabilities lexProbs =
new SampledLexProbs(commandLine.getValue(lexSampleSize), sourceSuffixArray, targetSuffixArray, alignmentArray, false);
//new LexProbs(source_given_target, target_given_source, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Done constructing lexical probabilities table");
if (logger.isLoggable(Level.FINE)) logger.fine("Should store a max of " + commandLine.getValue(ruleSampleSize) + " rules at each node in a prefix tree.");
Map<Integer,String> ntVocab = new HashMap<Integer,String>();
ntVocab.put(PrefixTree.X, "X");
Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
int lineNumber = 0;
SuffixArray.CACHE_CAPACITY = 1000;
while (testFileScanner.hasNextLine()) {
String line = testFileScanner.nextLine();
lineNumber++;
int[] words = sourceVocab.getIDs(line);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing prefix tree for source line " + lineNumber + ": " + line);
PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignmentArray, lexProbs, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(ruleSampleSize));
if (logger.isLoggable(Level.FINER)) logger.finer("Outputting rules for source line: " + line);
for (Rule rule : prefixTree.getAllRules()) {
String ruleString = rule.toString(ntVocab, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINEST)) logger.finest("Rule: " + ruleString);
out.println(ruleString);
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (logger.isLoggable(Level.FINE)) logger.fine("Done extracting rules");
}
}
}
| src/edu/jhu/sa/util/suffix_array/ExtractRules.java | /* This file is part of the Joshua Machine Translation System.
*
* Joshua 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.jhu.sa.util.suffix_array;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import joshua.decoder.ff.tm.Rule;
import joshua.util.CommandLineParser;
import joshua.util.CommandLineParser.Option;
import joshua.util.lexprob.LexicalProbabilities;
import joshua.util.sentence.Vocabulary;
/**
*
* @author Lane Schwartz
* @version $LastChangedDate$
*/
public class ExtractRules {
/** Logger for this class. */
private static final Logger logger = Logger.getLogger(ExtractRules.class.getName());
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try {
CommandLineParser commandLine = new CommandLineParser();
Option<String> source = commandLine.addStringOption('f',"source","SOURCE_FILE","Source language training file");
Option<String> target = commandLine.addStringOption('e',"target","TARGET_FILE","Target language training file");
Option<String> alignment = commandLine.addStringOption('a',"alignments","ALIGNMENTS_FILE","Source-target alignments training file");
Option<String> test = commandLine.addStringOption('t',"test","TEST_FILE","Source language test file");
Option<String> output = commandLine.addStringOption('o',"output","OUTPUT_FILE","-","Output file");
Option<String> encoding = commandLine.addStringOption("encoding","ENCODING","UTF-8","File encoding format");
Option<Integer> lexSampleSize = commandLine.addIntegerOption("lexSampleSize","LEX_SAMPLE_SIZE",100, "Size to use when sampling for lexical probability calculations");
Option<Integer> ruleSampleSize = commandLine.addIntegerOption("ruleSampleSize","RULE_SAMPLE_SIZE",100, "Maximum number of rules to store at each node in the prefix tree");
Option<Integer> maxPhraseSpan = commandLine.addIntegerOption("maxPhraseSpan","MAX_PHRASE_SPAN",10, "Max phrase span");
Option<Integer> maxPhraseLength = commandLine.addIntegerOption("maxPhraseLength","MAX_PHRASE_LENGTH",10, "Max phrase length");
Option<Integer> maxNonterminals = commandLine.addIntegerOption("maxNonterminals","MAX_NONTERMINALS",2, "Max nonterminals");
// Option<String> target_given_source_counts = commandLine.addStringOption("target-given-source-counts","FILENAME","file containing co-occurence counts of source and target word pairs, sorted by source words");
// Option<String> source_given_target_counts = commandLine.addStringOption("source-given-target-counts","FILENAME","file containing co-occurence counts of target and source word pairs, sorted by target words");
Option<Boolean> output_gz = commandLine.addBooleanOption("output-gzipped",false,"snould the outpu file be gzipped");
// Option<Boolean> target_given_source_gz = commandLine.addBooleanOption("target-given-source-gzipped",false,"is the target given source word pair counts file gzipped");
// Option<Boolean> source_given_target_gz = commandLine.addBooleanOption("source-given-target-gzipped",false,"is the source given target word pair counts file gzipped");
commandLine.parse(args);
// Set System.out and System.err to use the provided character encoding
try {
System.setOut(new PrintStream(System.out, true, commandLine.getValue(encoding)));
System.setErr(new PrintStream(System.err, true, commandLine.getValue(encoding)));
} catch (UnsupportedEncodingException e1) {
System.err.println(commandLine.getValue(encoding) + " is not a valid encoding; using system default encoding for System.out and System.err.");
} catch (SecurityException e2) {
System.err.println("Security manager is configured to disallow changes to System.out or System.err; using system default encoding.");
}
// Lane - TODO -
//SuffixArray.INVERTED_INDEX_PRECOMPUTATION_MIN_FREQ = commandLine.getValue("CACHE_PRECOMPUTATION_FREQUENCY_THRESHOLD");
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language vocabulary.");
String sourceFileName = commandLine.getValue(source);
Vocabulary sourceVocab = new Vocabulary();
int[] sourceWordsSentences = SuffixArrayFactory.createVocabulary(sourceFileName, sourceVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language corpus array.");
CorpusArray sourceCorpusArray = SuffixArrayFactory.createCorpusArray(sourceFileName, sourceVocab, sourceWordsSentences[0], sourceWordsSentences[1]);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing source language suffix arra.");
SuffixArray sourceSuffixArray = SuffixArrayFactory.createSuffixArray(sourceCorpusArray);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language vocabulary.");
String targetFileName = commandLine.getValue(target);
Vocabulary targetVocab = new Vocabulary();
int[] targetWordsSentences = SuffixArrayFactory.createVocabulary(commandLine.getValue(target), targetVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language corpus array.");
CorpusArray targetCorpusArray = SuffixArrayFactory.createCorpusArray(targetFileName, targetVocab, targetWordsSentences[0], targetWordsSentences[1]);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing target language suffix array.");
SuffixArray targetSuffixArray = SuffixArrayFactory.createSuffixArray(targetCorpusArray);
if (logger.isLoggable(Level.FINE)) logger.fine("Reading alignment data.");
String alignmentFileName = commandLine.getValue(alignment);
AlignmentArray alignmentArray = SuffixArrayFactory.createAlignmentArray(alignmentFileName, sourceSuffixArray, targetSuffixArray);
// Set up the source text for reading
// Scanner target_given_source;
// if (commandLine.getValue(target_given_source_counts).endsWith(".gz") || commandLine.getValue(target_given_source_gz))
// target_given_source = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(target_given_source_counts))),commandLine.getValue(encoding))));
// else
// target_given_source = new Scanner( new File(commandLine.getValue(target_given_source_counts)), commandLine.getValue(encoding));
// // Set up the target text for reading
// Scanner source_given_target;
// if (commandLine.getValue(source_given_target_counts).endsWith(".gz") || commandLine.getValue(source_given_target_gz))
// source_given_target = new Scanner(new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(commandLine.getValue(source_given_target_counts))),commandLine.getValue(encoding))));
// else
// source_given_target = new Scanner( new File(commandLine.getValue(source_given_target_counts)), commandLine.getValue(encoding));
PrintStream out;
if ("-".equals(commandLine.getValue(output))) {
out = System.out;
} else if (commandLine.getValue(output).endsWith(".gz") || commandLine.getValue(output_gz)) {
//XXX This currently doesn't work
out = new PrintStream(new GZIPOutputStream(new FileOutputStream(commandLine.getValue(output))));
System.err.println("GZIP output not currently working properly");
System.exit(-1);
} else {
out = new PrintStream(commandLine.getValue(output));
}
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing lexical probabilities table");
LexicalProbabilities lexProbs =
new SampledLexProbs(commandLine.getValue(lexSampleSize), sourceSuffixArray, targetSuffixArray, alignmentArray, false);
//new LexProbs(source_given_target, target_given_source, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINE)) logger.fine("Done constructing lexical probabilities table");
if (logger.isLoggable(Level.FINE)) logger.fine("Should store a max of " + commandLine.getValue(ruleSampleSize) + " rules at each node in a prefix tree.");
Map<Integer,String> ntVocab = new HashMap<Integer,String>();
ntVocab.put(PrefixTree.X, "X");
Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
while (testFileScanner.hasNextLine()) {
String line = testFileScanner.nextLine();
int[] words = sourceVocab.getIDs(line);
if (logger.isLoggable(Level.FINE)) logger.fine("Constructing prefix tree for source line: " + line);
PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignmentArray, lexProbs, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(ruleSampleSize));
if (logger.isLoggable(Level.FINER)) logger.finer("Outputting rules for source line: " + line);
for (Rule rule : prefixTree.getAllRules()) {
String ruleString = rule.toString(ntVocab, sourceVocab, targetVocab);
if (logger.isLoggable(Level.FINEST)) logger.finest("Rule: " + ruleString);
out.println(ruleString);
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (logger.isLoggable(Level.FINE)) logger.fine("Done extracting rules");
}
}
}
| Attempting to debug OutOfMemory problems during prefix tree creation.
git-svn-id: 113d22c177a5f4646d60eedc1d71f196641d30ff@284 0ae5e6b2-d358-4f09-a895-f82f13dd62a4
| src/edu/jhu/sa/util/suffix_array/ExtractRules.java | Attempting to debug OutOfMemory problems during prefix tree creation. | <ide><path>rc/edu/jhu/sa/util/suffix_array/ExtractRules.java
<ide>
<ide> Scanner testFileScanner = new Scanner(new File(commandLine.getValue(test)), commandLine.getValue(encoding));
<ide>
<add> int lineNumber = 0;
<add>
<add> SuffixArray.CACHE_CAPACITY = 1000;
<add>
<ide> while (testFileScanner.hasNextLine()) {
<ide> String line = testFileScanner.nextLine();
<add> lineNumber++;
<ide> int[] words = sourceVocab.getIDs(line);
<ide>
<del> if (logger.isLoggable(Level.FINE)) logger.fine("Constructing prefix tree for source line: " + line);
<add> if (logger.isLoggable(Level.FINE)) logger.fine("Constructing prefix tree for source line " + lineNumber + ": " + line);
<ide>
<ide> PrefixTree prefixTree = new PrefixTree(sourceSuffixArray, targetCorpusArray, alignmentArray, lexProbs, words, commandLine.getValue(maxPhraseSpan), commandLine.getValue(maxPhraseLength), commandLine.getValue(maxNonterminals), commandLine.getValue(ruleSampleSize));
<ide> |
|
Java | apache-2.0 | ff93846bc946036657d1919bb4d473e9b59dc60f | 0 | jasenmoloy/wirelesscontrol | package jasenmoloy.wirelesscontrol.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import junit.framework.Assert;
import jasenmoloy.wirelesscontrol.R;
import jasenmoloy.wirelesscontrol.data.GeofenceData;
import jasenmoloy.wirelesscontrol.debug.Debug;
import jasenmoloy.wirelesscontrol.mvp.AddGeofencePresenter;
import jasenmoloy.wirelesscontrol.mvp.AddGeofencePresenterImpl;
import jasenmoloy.wirelesscontrol.mvp.AddGeofenceView;
/**
* Created by jasenmoloy on 2/17/16.
*/
public class AddGeofenceActivity extends AppCompatActivity implements AddGeofenceView, GoogleMap.SnapshotReadyCallback {
/// ----------------------
/// Class Fields
/// ----------------------
private static final String TAG = "AddGeofenceActivity";
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
/// ----------------------
/// Object Fields
/// ----------------------
private GoogleMap mMap;
private LocationManager mLocationManager;
private Location mLocation;
private GeofenceMarker mGeofence;
private EditText mGeofenceName;
private AddGeofencePresenter mPresenter;
private GeofenceData mGeofenceSaveData;
/// ----------------------
/// Public Methods
/// ----------------------
/// ----------------------
/// Callback Methods
/// ----------------------
public void onCameraChange(CameraPosition cameraPos) {
UpdateGeofenceMarker(cameraPos.target);
}
public void onSaveButtonClick(View view) {
mGeofenceSaveData = new GeofenceData(
mGeofenceName.getText().toString(),
mGeofence.getPosition(),
mGeofence.getRadius()
);
//JAM TODO: Verify data is correct before attempting to save
//JAM Clean and format the map before taking a snapshot
try {
mMap.setMyLocationEnabled(false);
mMap.moveCamera(CameraUpdateFactory.zoomTo(mMap.getMaxZoomLevel() * 0.5f));
}
catch(SecurityException secEx) {
Debug.logError(TAG, secEx.getMessage());
}
//JAM Grab screenshot of the map
mMap.snapshot(this);
}
public void onGeofenceSaveSuccess() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //Prevents reinstantiation if the activity already exists
startActivity(intent);
}
public void onGeofenceSaveError() {
Debug.logWarn(TAG, "onGeofenceSaveError() - Called but not implemented!");
//Notify the user that an error has occurred
Debug.showDebugOkDialog(this, "Save Error", "An error occurred while saving. Please try again.");
//JAM TODO: Depending on the error, stay on the current screen and attempt to have the user save again (if possible).
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize map to begin in Los Angeles to start.
mMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(34.0500, -118.2500), mMap.getMaxZoomLevel() * 0.6f)
);
//Initialize new geofence marker that will be placed
initGeofenceMarker(mMap.getCameraPosition().target);
//Check and/or request permission if the app can use the user's location.
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
else {
initMyLocationOnMap();
}
}
public void onSnapshotReady(Bitmap map) {
if(map == null) {
//JAM Enable your location again
try {
mMap.setMyLocationEnabled(true);
}
catch(SecurityException secEx) {
Debug.logError(TAG, secEx.getMessage());
}
onGeofenceSaveError();
return;
}
//Add bitmap to geofence save data
mGeofenceSaveData.addBitmap(map);
//Let presenter know we're ready to save the data
mPresenter.saveGeofence(mGeofenceSaveData);
mGeofenceSaveData = null;
}
/// ----------------------
/// Protected Methods
/// ----------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set up the activity's view
setContentView(R.layout.activity_addgeofence);
//Initialize any viewGroup related fields
mGeofenceName = (EditText) findViewById(R.id.addgeofence_name);
//Set the toolbar according to the activity layout
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(myChildToolbar);
//Enable the "Up" button to go back to the parent activity
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.addgeofence_geofencemap);
mapFragment.getMapAsync(this);
mPresenter = new AddGeofencePresenterImpl(this, this);
mPresenter.onCreate();
mPresenter.registerReceiver(LocalBroadcastManager.getInstance(this));
}
@Override
protected void onStart() {
//Stubbed
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
//Stubbed
}
@Override
protected void onPause() {
//Stubbed
super.onPause();
}
@Override
protected void onStop() {
//Stubbed
super.onStop();
}
@Override
protected void onDestroy() {
mPresenter.onDestroy();
super.onDestroy();
}
/// ----------------------
/// Private Methods
/// ----------------------
private void initMyLocationOnMap()
{
try {
mMap.setMyLocationEnabled(true);
if( mLocationManager == null ) {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
//Get the user's current position
LatLng currentPos = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentPos, mMap.getMaxZoomLevel() * 0.8f);
//Update the marker to that position before the users see the map animation
UpdateGeofenceMarker(currentPos);
//Update the camera to point to where the user is located and zoom in a bit.
mMap.animateCamera(cameraUpdate);
}
catch(SecurityException secEx) {
//TODO Request permissions to access the user's location.
}
catch(Exception ex) {
//TODO Print out a log.
}
}
private void initGeofenceMarker(LatLng position) {
//Set the listener for our map.
mMap.setOnCameraChangeListener(this);
mGeofence = new GeofenceMarker(position, 60.0); //JAM TODO: Move this to resources file.
mGeofence.addToMap(mMap);
}
private void UpdateGeofenceMarker(LatLng position) {
Assert.assertNotNull(position);
//JAM TODO Check for null
mGeofence.updateMarker(position, 60.0); //JAM TODO: Move this to resources file.
}
}
| app/src/main/java/jasenmoloy/wirelesscontrol/ui/AddGeofenceActivity.java | package jasenmoloy.wirelesscontrol.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import junit.framework.Assert;
import jasenmoloy.wirelesscontrol.R;
import jasenmoloy.wirelesscontrol.data.GeofenceData;
import jasenmoloy.wirelesscontrol.debug.Debug;
import jasenmoloy.wirelesscontrol.mvp.AddGeofencePresenter;
import jasenmoloy.wirelesscontrol.mvp.AddGeofencePresenterImpl;
import jasenmoloy.wirelesscontrol.mvp.AddGeofenceView;
/**
* Created by jasenmoloy on 2/17/16.
*/
public class AddGeofenceActivity extends AppCompatActivity implements AddGeofenceView, GoogleMap.SnapshotReadyCallback {
/// ----------------------
/// Class Fields
/// ----------------------
private static final String TAG = "AddGeofenceActivity";
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;
/// ----------------------
/// Object Fields
/// ----------------------
private GoogleMap mMap;
private LocationManager mLocationManager;
private Location mLocation;
private GeofenceMarker mGeofence;
private EditText mGeofenceName;
private AddGeofencePresenter mPresenter;
private GeofenceData mGeofenceSaveData;
/// ----------------------
/// Public Methods
/// ----------------------
/// ----------------------
/// Callback Methods
/// ----------------------
public void onCameraChange(CameraPosition cameraPos) {
UpdateGeofenceMarker(cameraPos.target);
}
public void onSaveButtonClick(View view) {
mGeofenceSaveData = new GeofenceData(
mGeofenceName.getText().toString(),
mGeofence.getPosition(),
mGeofence.getRadius()
);
//JAM TODO: Verify data is correct before attempting to save
//JAM Grab screenshot of the map
mMap.snapshot(this);
}
public void onGeofenceSaveSuccess() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //Prevents reinstantiation if the activity already exists
startActivity(intent);
}
public void onGeofenceSaveError() {
Debug.logWarn(TAG, "onGeofenceSaveError() - Called but not implemented!");
//Notify the user that an error has occurred
Debug.showDebugOkDialog(this, "Save Error", "An error occurred while saving. Please try again.");
//JAM TODO: Depending on the error, stay on the current screen and attempt to have the user save again (if possible).
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize map to begin in Los Angeles to start.
mMap.animateCamera(
CameraUpdateFactory.newLatLngZoom(
new LatLng(34.0500, -118.2500), mMap.getMaxZoomLevel() * 0.6f)
);
//Initialize new geofence marker that will be placed
initGeofenceMarker(mMap.getCameraPosition().target);
//Check and/or request permission if the app can use the user's location.
if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
else {
initMyLocationOnMap();
}
}
public void onSnapshotReady(Bitmap map) {
if(map == null) {
onGeofenceSaveError();
return;
}
//Add bitmap to geofence save data
mGeofenceSaveData.addBitmap(map);
//Let presenter know we're ready to save the data
mPresenter.saveGeofence(mGeofenceSaveData);
mGeofenceSaveData = null;
}
/// ----------------------
/// Protected Methods
/// ----------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set up the activity's view
setContentView(R.layout.activity_addgeofence);
//Initialize any viewGroup related fields
mGeofenceName = (EditText) findViewById(R.id.addgeofence_name);
//Set the toolbar according to the activity layout
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(myChildToolbar);
//Enable the "Up" button to go back to the parent activity
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.addgeofence_geofencemap);
mapFragment.getMapAsync(this);
mPresenter = new AddGeofencePresenterImpl(this, this);
mPresenter.onCreate();
mPresenter.registerReceiver(LocalBroadcastManager.getInstance(this));
}
@Override
protected void onStart() {
//Stubbed
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
//Stubbed
}
@Override
protected void onPause() {
//Stubbed
super.onPause();
}
@Override
protected void onStop() {
//Stubbed
super.onStop();
}
@Override
protected void onDestroy() {
mPresenter.onDestroy();
super.onDestroy();
}
/// ----------------------
/// Private Methods
/// ----------------------
private void initMyLocationOnMap()
{
try {
mMap.setMyLocationEnabled(true);
if( mLocationManager == null ) {
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
//Get the user's current position
LatLng currentPos = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentPos, mMap.getMaxZoomLevel() * 0.8f);
//Update the marker to that position before the users see the map animation
UpdateGeofenceMarker(currentPos);
//Update the camera to point to where the user is located and zoom in a bit.
mMap.animateCamera(cameraUpdate);
}
catch(SecurityException secEx) {
//TODO Request permissions to access the user's location.
}
catch(Exception ex) {
//TODO Print out a log.
}
}
private void initGeofenceMarker(LatLng position) {
//Set the listener for our map.
mMap.setOnCameraChangeListener(this);
mGeofence = new GeofenceMarker(position, 60.0); //JAM TODO: Move this to resources file.
mGeofence.addToMap(mMap);
}
private void UpdateGeofenceMarker(LatLng position) {
Assert.assertNotNull(position);
//JAM TODO Check for null
mGeofence.updateMarker(position, 60.0); //JAM TODO: Move this to resources file.
}
}
| Hide your location and set an appropriate zoom when taking a snapshot of the map.
| app/src/main/java/jasenmoloy/wirelesscontrol/ui/AddGeofenceActivity.java | Hide your location and set an appropriate zoom when taking a snapshot of the map. | <ide><path>pp/src/main/java/jasenmoloy/wirelesscontrol/ui/AddGeofenceActivity.java
<ide>
<ide> //JAM TODO: Verify data is correct before attempting to save
<ide>
<add> //JAM Clean and format the map before taking a snapshot
<add> try {
<add> mMap.setMyLocationEnabled(false);
<add> mMap.moveCamera(CameraUpdateFactory.zoomTo(mMap.getMaxZoomLevel() * 0.5f));
<add> }
<add> catch(SecurityException secEx) {
<add> Debug.logError(TAG, secEx.getMessage());
<add> }
<add>
<ide> //JAM Grab screenshot of the map
<ide> mMap.snapshot(this);
<ide> }
<ide>
<ide> public void onSnapshotReady(Bitmap map) {
<ide> if(map == null) {
<add> //JAM Enable your location again
<add> try {
<add> mMap.setMyLocationEnabled(true);
<add> }
<add> catch(SecurityException secEx) {
<add> Debug.logError(TAG, secEx.getMessage());
<add> }
<add>
<ide> onGeofenceSaveError();
<ide> return;
<ide> } |
|
Java | apache-2.0 | 4e28be5cb5e2d692679cb380d53c389cc6859d50 | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr | package org.apache.lucene.search;
/**
* 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.
*/
import java.io.IOException;
import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
/** The abstract base class for queries.
<p>Instantiable subclasses are:
<ul>
<li> {@link TermQuery}
<li> {@link MultiTermQuery}
<li> {@link BooleanQuery}
<li> {@link WildcardQuery}
<li> {@link PhraseQuery}
<li> {@link PrefixQuery}
<li> {@link MultiPhraseQuery}
<li> {@link FuzzyQuery}
<li> {@link TermRangeQuery}
<li> {@link NumericRangeQuery}
<li> {@link org.apache.lucene.search.spans.SpanQuery}
</ul>
<p>A parser for queries is contained in:
<ul>
<li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
</ul>
*/
public abstract class Query implements Cloneable {
private float boost = 1.0f; // query boost factor
/** Sets the boost for this query clause to <code>b</code>. Documents
* matching this clause will (in addition to the normal weightings) have
* their score multiplied by <code>b</code>.
*/
public void setBoost(float b) { boost = b; }
/** Gets the boost for this clause. Documents matching
* this clause will (in addition to the normal weightings) have their score
* multiplied by <code>b</code>. The boost is 1.0 by default.
*/
public float getBoost() { return boost; }
/** Prints a query to a string, with <code>field</code> assumed to be the
* default field and omitted.
* <p>The representation used is one that is supposed to be readable
* by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
* there are the following limitations:
* <ul>
* <li>If the query was created by the parser, the printed
* representation may not be exactly what was parsed. For example,
* characters that need to be escaped will be represented without
* the required backslash.</li>
* <li>Some of the more complicated queries (e.g. span queries)
* don't have a representation that can be parsed by QueryParser.</li>
* </ul>
*/
public abstract String toString(String field);
/** Prints a query to a string. */
@Override
public String toString() {
return toString("");
}
/**
* Expert: Constructs an appropriate Weight implementation for this query.
*
* <p>
* Only implemented by primitive queries, which re-write to themselves.
*/
public Weight createWeight(IndexSearcher searcher) throws IOException {
throw new UnsupportedOperationException("Query " + this + " does not implement createWeight");
}
/** Expert: called to re-write queries into primitive queries. For example,
* a PrefixQuery will be rewritten into a BooleanQuery that consists
* of TermQuerys.
*/
public Query rewrite(IndexReader reader) throws IOException {
return this;
}
/**
* Expert: adds all terms occurring in this query to the terms set. Only
* works if this query is in its {@link #rewrite rewritten} form.
*
* @throws UnsupportedOperationException if this query is not yet rewritten
*/
public void extractTerms(Set<Term> terms) {
// needs to be implemented by query subclasses
throw new UnsupportedOperationException();
}
/** Returns a clone of this query. */
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone not supported: " + e.getMessage());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(boost);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Query other = (Query) obj;
if (Float.floatToIntBits(boost) != Float.floatToIntBits(other.boost))
return false;
return true;
}
}
| lucene/src/java/org/apache/lucene/search/Query.java | package org.apache.lucene.search;
/**
* 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.
*/
import java.io.IOException;
import java.util.Set;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
/** The abstract base class for queries.
<p>Instantiable subclasses are:
<ul>
<li> {@link TermQuery}
<li> {@link MultiTermQuery}
<li> {@link BooleanQuery}
<li> {@link WildcardQuery}
<li> {@link PhraseQuery}
<li> {@link PrefixQuery}
<li> {@link MultiPhraseQuery}
<li> {@link FuzzyQuery}
<li> {@link TermRangeQuery}
<li> {@link NumericRangeQuery}
<li> {@link org.apache.lucene.search.spans.SpanQuery}
</ul>
<p>A parser for queries is contained in:
<ul>
<li>{@link org.apache.lucene.queryParser.QueryParser QueryParser}
</ul>
*/
public abstract class Query implements Cloneable {
private float boost = 1.0f; // query boost factor
/** Sets the boost for this query clause to <code>b</code>. Documents
* matching this clause will (in addition to the normal weightings) have
* their score multiplied by <code>b</code>.
*/
public void setBoost(float b) { boost = b; }
/** Gets the boost for this clause. Documents matching
* this clause will (in addition to the normal weightings) have their score
* multiplied by <code>b</code>. The boost is 1.0 by default.
*/
public float getBoost() { return boost; }
/** Prints a query to a string, with <code>field</code> assumed to be the
* default field and omitted.
* <p>The representation used is one that is supposed to be readable
* by {@link org.apache.lucene.queryParser.QueryParser QueryParser}. However,
* there are the following limitations:
* <ul>
* <li>If the query was created by the parser, the printed
* representation may not be exactly what was parsed. For example,
* characters that need to be escaped will be represented without
* the required backslash.</li>
* <li>Some of the more complicated queries (e.g. span queries)
* don't have a representation that can be parsed by QueryParser.</li>
* </ul>
*/
public abstract String toString(String field);
/** Prints a query to a string. */
@Override
public String toString() {
return toString("");
}
/**
* Expert: Constructs an appropriate Weight implementation for this query.
*
* <p>
* Only implemented by primitive queries, which re-write to themselves.
*/
public Weight createWeight(IndexSearcher searcher) throws IOException {
throw new UnsupportedOperationException();
}
/** Expert: called to re-write queries into primitive queries. For example,
* a PrefixQuery will be rewritten into a BooleanQuery that consists
* of TermQuerys.
*/
public Query rewrite(IndexReader reader) throws IOException {
return this;
}
/**
* Expert: adds all terms occurring in this query to the terms set. Only
* works if this query is in its {@link #rewrite rewritten} form.
*
* @throws UnsupportedOperationException if this query is not yet rewritten
*/
public void extractTerms(Set<Term> terms) {
// needs to be implemented by query subclasses
throw new UnsupportedOperationException();
}
/** Returns a clone of this query. */
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone not supported: " + e.getMessage());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(boost);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Query other = (Query) obj;
if (Float.floatToIntBits(boost) != Float.floatToIntBits(other.boost))
return false;
return true;
}
}
| fix UOE exc in base Query.createWeight to include this.toString in its message
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1141167 13f79535-47bb-0310-9956-ffa450edef68
| lucene/src/java/org/apache/lucene/search/Query.java | fix UOE exc in base Query.createWeight to include this.toString in its message | <ide><path>ucene/src/java/org/apache/lucene/search/Query.java
<ide> * Only implemented by primitive queries, which re-write to themselves.
<ide> */
<ide> public Weight createWeight(IndexSearcher searcher) throws IOException {
<del> throw new UnsupportedOperationException();
<add> throw new UnsupportedOperationException("Query " + this + " does not implement createWeight");
<ide> }
<ide>
<ide> /** Expert: called to re-write queries into primitive queries. For example, |
|
JavaScript | mit | 47ac1b27dbb176ae390c835a3c92b4e1fd21cf97 | 0 | basarevych/secure-proxy,basarevych/secure-proxy,basarevych/secure-proxy | 'use strict'
var readline = require('readline');
function Console(serviceLocator) {
this.sl = serviceLocator;
this.sl.set('console', this);
};
module.exports = Console;
Console.prototype.getDatabase = function () {
if (typeof this.db != 'undefined')
return this.db;
var db = this.sl.get('database');
this.db = db;
return db;
};
Console.prototype.getReadline = function () {
if (typeof this.rl != 'undefined')
return this.rl;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
this.rl = rl;
return rl;
};
Console.prototype.listUsers = function (email) {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write(email ? "==> User list (" + email + ")\n" : "==> User list\n");
var params = {};
if (email)
params['email'] = email;
db.selectUsers(params)
.then(function (users) {
for (var i = 0; i < users.length; i++) {
rl.write(
"\nID:\t\t" + users[i]['id']
+ "\nLogin:\t\t" + users[i]['login']
+ "\nPassword:\t" + users[i]['password']
+ "\nEmail:\t\t" + users[i]['email']
+ "\nSecret:\t\t" + users[i]['secret']
+ "\nOTP Key:\t" + users[i]['otp_key']
+ "\nOTP Confirmed:\t" + (users[i]['otp_confirmed'] ? 'true' : 'false')
+ "\n"
);
}
rl.close();
});
};
Console.prototype.updateUser = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Update user\n");
rl.question('-> Username? ', function (username) {
rl.question('-> Password? ', function (password) {
rl.question('-> Email? ', function (email) {
db.userExists(username)
.then(function (exists) {
if (exists) {
db.setUserPassword(username, password)
.then(function () { return db.setUserEmail(username, email); })
.then(function () {
rl.write("==> User exists, password and email changed\n");
rl.close();
});
} else {
db.createUser(username, password, email)
.then(function () {
rl.write("==> User created\n");
rl.close();
});
}
});
});
});
});
};
Console.prototype.deleteUser = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Delete user\n");
rl.question('-> Username? ', function (username) {
db.userExists(username)
.then(function (exists) {
if (exists) {
db.deleteUser(username)
.then(function () {
rl.write("==> User deleted\n");
rl.close();
});
} else {
rl.write("==> User does not exists\n");
rl.close();
}
});
});
};
Console.prototype.listSessions = function (login) {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write(login ? "==> Session list (" + login + ")\n" : "==> Session list\n");
var params = {};
if (login)
params['login'] = login;
db.selectSessions(params)
.then(function (sessions) {
for (var i = 0; i < sessions.length; i++) {
var date = new Date(sessions[i]['last']);
rl.write(
"\nID:\t\t\t" + sessions[i]['id']
+ "\nLogin:\t\t\t" + sessions[i]['login']
+ "\nSID:\t\t\t" + sessions[i]['sid']
+ "\nLast seen:\t\t" + date.toString()
+ "\nProvided password:\t" + (sessions[i]['auth_password'] ? 'true' : 'false')
+ "\nProvided OTP:\t\t" + (sessions[i]['auth_otp'] ? 'true' : 'false')
+ "\n"
);
}
rl.close();
});
};
Console.prototype.deleteSession = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Delete session\n");
rl.question('-> SID? ', function (sid) {
db.sessionExists(sid)
.then(function (exists) {
if (exists) {
db.deleteSession(sid)
.then(function () {
rl.write("==> Session deleted\n");
rl.close();
});
} else {
rl.write("==> Session does not exists\n");
rl.close();
}
});
});
};
| src/console.js | 'use strict'
var readline = require('readline');
function Console(serviceLocator) {
this.sl = serviceLocator;
this.sl.set('console', this);
};
module.exports = Console;
Console.prototype.getDatabase = function () {
if (typeof this.db != 'undefined')
return this.db;
var db = this.sl.get('database');
this.db = db;
return db;
};
Console.prototype.getReadline = function () {
if (typeof this.rl != 'undefined')
return this.rl;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
this.rl = rl;
return rl;
};
Console.prototype.listUsers = function (email) {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write(email ? "==> User list (" + email + ")\n" : "==> User list\n");
var params = {};
if (email)
params['email'] = email;
db.selectUsers(params)
.then(function (users) {
for (var i = 0; i < users.length; i++) {
rl.write(
"\nID:\t\t" + users[i]['id']
+ "\nLogin:\t\t" + users[i]['login']
+ "\nPassword:\t" + users[i]['password']
+ "\nEmail:\t\t" + users[i]['email']
+ "\nOTP Key:\t" + users[i]['otp_key']
+ "\nOTP Confirmed:\t" + (users[i]['otp_confirmed'] ? 'true' : 'false')
+ "\n"
);
}
rl.close();
});
};
Console.prototype.updateUser = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Update user\n");
rl.question('-> Username? ', function (username) {
rl.question('-> Password? ', function (password) {
rl.question('-> Email? ', function (email) {
db.userExists(username)
.then(function (exists) {
if (exists) {
db.setUserPassword(username, password)
.then(function () { return db.setUserEmail(username, email); })
.then(function () {
rl.write("==> User exists, password and email changed\n");
rl.close();
});
} else {
db.createUser(username, password, email)
.then(function () {
rl.write("==> User created\n");
rl.close();
});
}
});
});
});
});
};
Console.prototype.deleteUser = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Delete user\n");
rl.question('-> Username? ', function (username) {
db.userExists(username)
.then(function (exists) {
if (exists) {
db.deleteUser(username)
.then(function () {
rl.write("==> User deleted\n");
rl.close();
});
} else {
rl.write("==> User does not exists\n");
rl.close();
}
});
});
};
Console.prototype.listSessions = function (login) {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write(login ? "==> Session list (" + login + ")\n" : "==> Session list\n");
var params = {};
if (login)
params['login'] = login;
db.selectSessions(params)
.then(function (sessions) {
for (var i = 0; i < sessions.length; i++) {
var date = new Date(sessions[i]['last']);
rl.write(
"\nID:\t\t\t" + sessions[i]['id']
+ "\nLogin:\t\t\t" + sessions[i]['login']
+ "\nSID:\t\t\t" + sessions[i]['sid']
+ "\nLast seen:\t\t" + date.toString()
+ "\nProvided password:\t" + (sessions[i]['auth_password'] ? 'true' : 'false')
+ "\nProvided OTP:\t\t" + (sessions[i]['auth_otp'] ? 'true' : 'false')
+ "\n"
);
}
rl.close();
});
};
Console.prototype.deleteSession = function () {
var db = this.getDatabase(),
rl = this.getReadline();
rl.write("==> Delete session\n");
rl.question('-> SID? ', function (sid) {
db.sessionExists(sid)
.then(function (exists) {
if (exists) {
db.deleteSession(sid)
.then(function () {
rl.write("==> Session deleted\n");
rl.close();
});
} else {
rl.write("==> Session does not exists\n");
rl.close();
}
});
});
};
| List-users update
| src/console.js | List-users update | <ide><path>rc/console.js
<ide> + "\nLogin:\t\t" + users[i]['login']
<ide> + "\nPassword:\t" + users[i]['password']
<ide> + "\nEmail:\t\t" + users[i]['email']
<add> + "\nSecret:\t\t" + users[i]['secret']
<ide> + "\nOTP Key:\t" + users[i]['otp_key']
<ide> + "\nOTP Confirmed:\t" + (users[i]['otp_confirmed'] ? 'true' : 'false')
<ide> + "\n" |
|
Java | apache-2.0 | 5a8ad43d0bdaffe3e1e5004a0eb8258057803a16 | 0 | amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak | /*
* 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.jackrabbit.mk.api;
import java.io.InputStream;
import javax.annotation.Nonnull;
/**
* The MicroKernel <b>Design Goals and Principles</b>:
* <ul>
* <li>manage huge trees of nodes and properties efficiently</li>
* <li>MVCC-based concurrency control
* (writers don't interfere with readers, snapshot isolation)</li>
* <li>GIT/SVN-inspired DAG-based versioning model</li>
* <li>highly scalable concurrent read & write operations</li>
* <li>session-less API (there's no concept of sessions; an implementation doesn't need to track/manage session state)</li>
* <li>easily portable to C</li>
* <li>easy to remote</li>
* <li>efficient support for large number of child nodes</li>
* <li>integrated API for efficiently storing/retrieving large binaries</li>
* <li>human-readable data serialization (JSON)</li>
* </ul>
* <p>
* The MicroKernel <b>Data Model</b>:
* </p>
* <ul>
* <li>simple JSON-inspired data model: just nodes and properties</li>
* <li>a node consists of an unordered set of name -> item mappings. each
* property and child node is uniquely named and a single name can only
* refer to a property or a child node, not both at the same time.
* <li>properties are represented as name/value pairs</li>
* <li>supported property types: string, number, boolean, array</li>
* <li>a property value is stored and used as an opaque, unparsed character sequence</li>
* </ul>
* <p>
* The <b>Retention Policy for Revisions</b>:
* <p>
* TODO specify retention policy for old revisions, i.e. minimal guaranteed retention period (OAK-114)
* </p>
* <p>
* The <b>Retention Policy for Binaries</b>:
* </p>
* <p>
* The MicroKernel implementation is free to remove binaries if both of the
* following conditions are met:
* </p>
* <ul>
* <li>If the binary is not references as a property value of the
* format ":blobId:<blobId>" where <blobId> is the id returned by
* {@link #write(InputStream in)}. This includes simple property values such as
* {"bin": ":blobId:1234"} as well as array property values such as
* {"array": [":blobId:1234", ":blobId:5678"]}.</li>
* <li>If the binary was stored before the last retained revision (this is to
* keep temporary binaries, and binaries that are not yet referenced).</li>
* </ul>
*/
public interface MicroKernel {
public static final String CONFLICT = ":conflict";
//---------------------------------------------------------< REVISION ops >
/**
* Return the id of the current head revision, i.e. the most recent <i>public</i>
* trunk revision. <i>Private</i> branch revisions are ignored.
*
* @return the id of the head revision
* @throws MicroKernelException if an error occurs
*/
String getHeadRevision() throws MicroKernelException;
/**
* Creates a new checkpoint of the latest head revision. The checkpoint
* guarantees that revision to remain valid and accessible for at least
* as long as requested.
*
* @param lifetime time (in milliseconds) that the checkpoint should
* remain available
* @return revision id of the created checkpoint
* @throws MicroKernelException if the checkpoint could not be created
*/
@Nonnull
String checkpoint(long lifetime) throws MicroKernelException;
/**
* Returns a list of all currently available (historical) head revisions in
* chronological order since a specific point in time. <i>Private</i> branch
* revisions won't be included in the result.
* <p>
* Format:
* <pre>
* [
* {
* "id" : "<revisionId>",
* "ts" : <revisionTimestamp>,
* "msg" : "<commitMessage>"
* },
* ...
* ]
* </pre>
* The {@code path} parameter allows to filter the revisions by path, i.e.
* only those revisions that affected the subtree rooted at {@code path}
* will be included.
* <p>
* The {@code maxEntries} parameter allows to limit the number of revisions
* returned. if {@code maxEntries < 0} no limit will be applied. otherwise,
* if the number of revisions satisfying the specified {@code since} and
* {@code path} criteria exceeds {@code maxEntries}, only {@code maxEntries}
* entries will be returned (in chronological order, starting with the oldest).
*
* @param since timestamp (number of milliseconds since midnight, January 1, 1970 UTC) of earliest revision to be returned
* @param maxEntries maximum #entries to be returned;
* if < 0, no limit will be applied.
* @param path optional path filter; if {@code null} or {@code ""} the
* default ({@code "/"}) will be assumed, i.e. no filter
* will be applied
* @return a list of revisions in chronological order in JSON format.
* @throws MicroKernelException if an error occurs
*/
String /* jsonArray */ getRevisionHistory(long since, int maxEntries, String path)
throws MicroKernelException;
/**
* Waits for a commit to occur that is more recent than {@code oldHeadRevisionId}.
* <p>
* This method allows for efficient polling for new revisions. The method
* will return the id of the current head revision if it is more recent than
* {@code oldHeadRevisionId}, or waits if either the specified amount of time
* has elapsed or a new head revision has become available.
* <p>
* if a zero or negative {@code timeout} value has been specified the method
* will return immediately, i.e. calling {@code waitForCommit(oldHeadRevisionId, 0)} is
* equivalent to calling {@code getHeadRevision()}.
* <p>
* Note that commits on a <i>private</i> branch will be ignored.
*
* @param oldHeadRevisionId id of earlier head revision
* @param timeout the maximum time to wait in milliseconds
* @return the id of the head revision
* @throws MicroKernelException if an error occurs
* @throws InterruptedException if the thread was interrupted
*/
String waitForCommit(String oldHeadRevisionId, long timeout)
throws MicroKernelException, InterruptedException;
/**
* Returns a revision journal, starting with {@code fromRevisionId}
* and ending with {@code toRevisionId} in chronological order.
* <p>
* Format:
* <pre>
* [
* {
* "id" : "<revisionId>",
* "ts" : <revisionTimestamp>,
* "msg" : "<commitMessage>",
* "changes" : "<JSON diff>"
* },
* ...
* ]
* </pre>
* If {@code fromRevisionId} and {@code toRevisionId} are not in chronological
* order the returned journal will be empty (i.e. {@code []})
* <p>
* The {@code path} parameter allows to filter the revisions by path, i.e.
* only those revisions that affected the subtree rooted at {@code path}
* will be included. The filter will also be applied to the JSON diff, i.e.
* the diff will include only those changes that affected the subtree rooted
* at {@code path}.
* <p>
* A {@code MicroKernelException} is thrown if either {@code fromRevisionId}
* or {@code toRevisionId} doesn't exist, if {@code fromRevisionId} denotes
* a <i>private</i> branch revision <i>and</i> {@code toRevisionId} denotes
* either a head revision or a revision on a different <i>private</i> branch,
* or if another error occurs.
* <p>
* If the journal includes <i>private</i> branch revisions, those entries
* will include a {@code "branchRootId"} denoting the head revision the
* <i>private</i> branch is based on.
*
* @param fromRevisionId id of first revision to be returned in journal
* @param toRevisionId id of last revision to be returned in journal,
* if {@code null} the current head revision is assumed
* @param path optional path filter; if {@code null} or {@code ""}
* the default ({@code "/"}) will be assumed, i.e. no
* filter will be applied
* @return a chronological list of revisions in JSON format
* @throws MicroKernelException if any of the specified revisions doesn't exist or if another error occurs
*/
String /* jsonArray */ getJournal(String fromRevisionId, String toRevisionId,
String path)
throws MicroKernelException;
/**
* Returns the JSON diff representation of the changes between the specified
* revisions. The changes will be consolidated if the specified range
* covers intermediary revisions. {@code fromRevisionId} and {@code toRevisionId}
* don't need not be in a specific chronological order.
* <p>
* The {@code path} parameter allows to filter the changes included in the
* JSON diff, i.e. only those changes that affected the subtree rooted at
* {@code path} will be included.
* <p>
* The {@code depth} limit applies to the subtree rooted at {@code path}.
* It allows to limit the depth of the diff, i.e. only changes up to the
* specified depth will be included in full detail. changes at paths exceeding
* the specified depth limit will be reported as {@code ^"/some/path" : {}},
* indicating that there are unspecified changes below that path.
* <table border="1">
* <tr>
* <th>{@code depth} value</th><th>scope of detailed diff</th>
* </tr>
* <tr>
* <td>-1</td><td>no limit will be applied</td>
* </tr>
* <tr>
* <td>0</td><td>changes affecting the properties and child node names of the node at {@code path}</td>
* </tr>
* <tr>
* <td>1</td><td>changes affecting the properties and child node names of the node at {@code path} and its direct descendants</td>
* </tr>
* <tr>
* <td>...</td><td>...</td>
* </tr>
* </table>
*
* @param fromRevisionId a revision id, if {@code null} the current head revision is assumed
* @param toRevisionId another revision id, if {@code null} the current head revision is assumed
* @param path optional path filter; if {@code null} or {@code ""}
* the default ({@code "/"}) will be assumed, i.e. no
* filter will be applied
* @param depth depth limit; if {@code -1} no limit will be applied
* @return JSON diff representation of the changes
* @throws MicroKernelException if any of the specified revisions doesn't exist or if another error occurs
*/
String /* JSON diff */ diff(String fromRevisionId, String toRevisionId,
String path, int depth)
throws MicroKernelException;
//-------------------------------------------------------------< READ ops >
/**
* Determines whether the specified node exists.
*
* @param path path denoting node
* @param revisionId revision id, if {@code null} the current head revision is assumed
* @return {@code true} if the specified node exists, otherwise {@code false}
* @throws MicroKernelException if the specified revision does not exist or if another error occurs
*/
boolean nodeExists(String path, String revisionId) throws MicroKernelException;
/**
* Returns the number of child nodes of the specified node.
* <p>
* This is a convenience method since the number of child nodes can be also
* determined by calling {@code getNodes(path, revisionId, 0, 0, 0, null)}
* and evaluating the {@code :childNodeCount} property.
*
* @param path path denoting node
* @param revisionId revision id, if {@code null} the current head revision is assumed
* @return the number of child nodes
* @throws MicroKernelException if the specified node or revision does not exist or if another error occurs
*/
long getChildNodeCount(String path, String revisionId) throws MicroKernelException;
/**
* Returns the node tree rooted at the specified parent node with the
* specified depth, maximum child node maxChildNodes and offset. The depth of the
* returned tree is governed by the {@code depth} parameter:
* <table>
* <tr>
* <td>depth = 0</td>
* <td>properties, including {@code :childNodeCount} and
* child node names (i.e. empty child node objects)</td>
* </tr>
* <tr>
* <td>depth = 1</td>
* <td>properties, child nodes and their properties (including
* {@code :childNodeCount}) and their child node names
* (i.e. empty child node objects)</td>
* </tr>
* <tr>
* <td>depth = 2</td>
* <td>[and so on...]</td>
* </tr>
* </table>
* <p>
* Example (depth=0):
* <pre>
* {
* "someprop" : "someval",
* ":childNodeCount" : 2,
* "child1" : {},
* "child2" : {}
* }
* </pre>
* Example (depth=1):
* <pre>
* {
* "someprop" : "someval",
* ":childNodeCount" : 2,
* "child1" : {
* "prop1" : 123,
* ":childNodeCount" : 2,
* "grandchild1" : {},
* "grandchild2" : {}
* },
* "child2" : {
* "prop1" : "bar",
* ":childNodeCount" : 0
* }
* }
* </pre>
* Remarks:
* <ul>
* <li>If the property {@code :childNodeCount} equals 0, then the
* node does not have any child nodes.
* <li>If the value of {@code :childNodeCount} is larger than the number
* of returned child nodes, then the node has more child nodes than those
* included in the returned tree.</li>
* </ul>
* The {@code offset} parameter is only applied to the direct child nodes
* of the root of the returned node tree. {@code maxChildNodes} however
* is applied on all hierarchy levels.
* <p>
* An {@code IllegalArgumentException} is thrown if both an {@code offset}
* greater than zero and a {@code filter} on node names (see below) have been
* specified.
* <p>
* The order of the child nodes is stable for any given {@code revisionId},
* i.e. calling {@code getNodes} repeatedly with the same {@code revisionId}
* is guaranteed to return the child nodes in the same order, but the
* specific order used is implementation-dependent and may change across
* different revisions of the same node.
* <p>
* The optional {@code filter} parameter allows to specify glob patterns for names of
* nodes and/or properties to be included or excluded.
* <p>
* Example:
* <pre>
* {
* "nodes": [ "foo*", "-foo1" ],
* "properties": [ "*", "-:childNodeCount" ]
* }
* </pre>
* In the above example all child nodes with names starting with "foo" will
* be included, except for nodes named "foo1"; similarly, all properties will
* be included except for the ":childNodeCount" metadata property (see below).
* <p>
* Glob Syntax:
* <ul>
* <li>a {@code nodes} or {@code properties} filter consists of one or more <i>globs</i>.</li>
* <li>a <i>glob</i> prefixed by {@code -} (dash) is treated as an exclusion pattern;
* all others are considered inclusion patterns.</li>
* <li>a leading {@code -} (dash) must be escaped by prepending {@code \} (backslash)
* if it should be interpreted as a literal.</li>
* <li>{@code *} (asterisk) serves as a <i>wildcard</i>, i.e. it matches any
* substring in the target name.</li>
* <li>{@code *} (asterisk) occurrences within the glob to be interpreted as
* literals must be escaped by prepending {@code \} (backslash).</li>
* <li>a filter matches a target name if any of the inclusion patterns match but
* none of the exclusion patterns.</li>
* </ul>
* If no filter is specified the implicit default filter is assumed:
* {@code {"nodes":["*"],"properties":["*"]}}
* <p>
* System-provided metadata properties:
* <ul>
* <li>{@code :childNodeCount} provides the actual number of direct child nodes; this property
* is included by the implicit default filter. it can be excluded by specifying a filter such
* as {@code {properties:["*", "-:childNodeCount"]}}</li>
* <li>{@code :hash} provides a content-based identifier for the subtree
* rooted at the {@code :hash} property's parent node. {@code :hash} values
* are similar to fingerprints. they can be compared to quickly determine
* if two subtrees are identical. if the {@code :hash} values are different
* the respective subtrees are different with regard to structure and/or properties.
* if on the other hand the {@code :hash} values are identical the respective
* subtrees are identical with regard to structure and properties.
* {@code :hash} is <i>not</i> included by the implicit default filter.
* it can be included by specifying a filter such as {@code {properties:["*", ":hash"]}}.
* <p>Returning the {@code :hash} property is optional. Some implementations
* might only return it on specific nodes or might not support it at all.
* If however a {@code :hash} property is returned it has to obey the contract
* described above.</p>
* <p>Implementations that keep track of the child hash along with
* the child node name can return the {@code :hash} value also as
* a property of the child node objects, even if they'd otherwise
* be empty, for example due to a depth limit. If such child hashes
* are returned, the client can use them as an alternative to child
* paths when accessing those nodes.</li>
* <li>{@code :id} provides an implementation-specific identifier
* of a node. Identifiers are like content hashes as described above,
* except for the fact that two different identifiers may refer to
* identical subtrees. Also {@code :id} values may be returned for
* child nodes, in which case the client can use them for accessing
* those nodes.
* </li>
* </ul>
*
* @param path path denoting root of node tree to be retrieved,
* or alternatively a previously returned
* {@code :hash} or {@code :id} value; in the latter case
* the {@code revisionId} parameter is ignored.
* @param revisionId revision id, if {@code null} the current head revision is assumed;
* the {@code revisionId} parameter is ignored if {@code path}
* is an identifier (i.e. a {@code :hash} or {@code :id} value).
* @param depth maximum depth of returned tree
* @param offset start position in the iteration order of child nodes (0 to start at the
* beginning)
* @param maxChildNodes maximum number of sibling child nodes to retrieve (-1 for all)
* @param filter optional filter on property and/or node names; if {@code null} or
* {@code ""} the default filter will be assumed
* @return node tree in JSON format or {@code null} if the specified node does not exist
* @throws MicroKernelException if the specified revision does not exist or if another error occurs
* @throws IllegalArgumentException if both an {@code offset > 0} and a {@code filter} on node names have been specified
*/
String /* jsonTree */ getNodes(String path, String revisionId, int depth,
long offset, int maxChildNodes, String filter)
throws MicroKernelException;
//------------------------------------------------------------< WRITE ops >
/**
* Applies the specified changes on the specified target node.
* <p>
* If {@code path.length() == 0} the paths specified in the
* {@code jsonDiff} are expected to be absolute.
* <p>
* The implementation tries to merge changes if the revision id of the
* commit is set accordingly. As an example, deleting a node is allowed if
* the node existed in the given revision, even if it was deleted in the
* meantime.
*
* @param path path denoting target node
* @param jsonDiff changes to be applied in JSON diff format.
* @param revisionId id of revision the changes are based on,
* if {@code null} the current head revision is assumed
* @param message commit message
* @return id of newly created revision
* @throws MicroKernelException if the specified revision doesn't exist or if another error occurs
*/
String /* revisionId */ commit(String path, String jsonDiff,
String revisionId, String message)
throws MicroKernelException;
/**
* Creates a <i>private</i> branch revision off the specified <i>public</i>
* trunk revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code trunkRevisionId} doesn't
* exist, if it's not a <i>trunk</i> revision (i.e. it's not reachable
* by traversing the revision history in reverse chronological order starting
* from the current head revision) or if another error occurs.
*
* @param trunkRevisionId id of public trunk revision to base branch on,
* if {@code null} the current head revision is assumed
* @return id of newly created private branch revision
* @throws MicroKernelException if {@code trunkRevisionId} doesn't exist,
* if it's not a <i>trunk</i> revision
* or if another error occurs
* @see #merge(String, String)
*/
String /* revisionId */ branch(String trunkRevisionId)
throws MicroKernelException;
/**
* Merges the specified <i>private</i> branch revision with the current
* head revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code branchRevisionId} doesn't
* exist, if it's not a branch revision, if the merge fails because of
* conflicting changes or if another error occurs.
*
* @param branchRevisionId id of private branch revision
* @param message commit message
* @return id of newly created head revision
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if the merge
* fails because of conflicting changes or if
* another error occurs.
* @see #branch(String)
*/
String /* revisionId */ merge(String branchRevisionId, String message)
throws MicroKernelException;
/**
* Rebases the specified <i>private</i> branch revision on top of specified new base
* revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code branchRevisionId} doesn't
* exist, if it's not a branch revision, if {@code newBaseRevisionId} doesn't exist,
* if it's a branch revision or if another error occurs.
* <p>
* If rebasing results in a conflict, conflicting nodes are annotated with a conflict
* marker denoting the type of the conflict and the value(s) before the rebase operation.
* The conflict marker is an internal node with the name {@link #CONFLICT} and is added
* to the node whose properties or child nodes are in conflict.
* <p>
* type of conflicts:
* <dl>
* <dt>addExistingProperty:</dt>
* <dd>A property has been added that has a different value than a property with the same name
* that has been added in trunk.</dd>
* <dt>deleteDeletedProperty:</dt>
* <dd>A property has been removed while a property of the same name has been removed in trunk.</dd>
* <dt>deleteChangedProperty:</dt>
* <dd>A property has been removed while a property of the same name has been changed in trunk.</dd>
* <dt>changeDeletedProperty:</dt>
* <dd>A property has been changed while a property of the same name has been removed in trunk. </dd>
* <dt>changeChangedProperty:</dt>
* <dd>A property has been changed while a property of the same name has been changed to a
* different value in trunk.</dd>
* <dt>addExistingNode:</dt>
* <dd>A node has been added that can't be merged with a node of them same name that has
* been added to the trunk. How and whether merging takes place is up to the
* implementation. Merging must not cause data to be lost however.</dd>
* <dt>deleteDeletedNode:</dt>
* <dd>A node has been removed while a node of the same name has been removed in trunk.</dd>
* <dt>deleteChangedNode:</dt>
* <dd>A node has been removed while a node of the same name has been changed in trunk.</dd>
* <dt>changeDeletedNode:</dt>
* <dd>A node has been changed while a node of the same name has been removed in trunk.</dd>
* </dl>
* In this context a node is regarded as changed if a property was added, a property was removed,
* a property was set to a different value, a child node was added, a child node was removed or
* a child node was changed.
* <p>
* On conflict the conflict marker node carries the conflicting value of the branch while the rebased
* value in the branch itself will be set to the conflicting value of the trunk. In the case of conflicting
* properties, the conflicting value is the property value from the branch. In the case of conflicting
* node, the conflicting value is the node from the branch.
*
* @param branchRevisionId id of private branch revision
* @param newBaseRevisionId id of new base revision
* @return id of the rebased branch revision
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if {@code newBaseRevisionId}
* doesn't exist, if it's a branch revision, or if another error occurs.
*/
@Nonnull
String /*revisionId */ rebase(@Nonnull String branchRevisionId, String newBaseRevisionId)
throws MicroKernelException;
/**
* Resets the branch identified by {@code branchRevisionId} to an ancestor
* branch commit identified by {@code ancestorRevisionId}.
*
* @param branchRevisionId id of the private branch revision
* @param ancestorRevisionId id of the ancestor commit to reset the branch to.
* @return the id of the new head of the branch. This may not necessarily
* be the same as {@code ancestorRevisionId}. An implementation is
* free to create a new id for the reset branch.
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if {@code ancestorRevisionId}
* is not a revision on that branch or if another error occurs.
*/
@Nonnull
String /* revisionId */ reset(@Nonnull String branchRevisionId,
@Nonnull String ancestorRevisionId)
throws MicroKernelException;
//--------------------------------------------------< BLOB READ/WRITE ops >
/**
* Returns the length of the specified blob.
*
* @param blobId blob identifier
* @return length of the specified blob
* @throws MicroKernelException if the specified blob does not exist or if another error occurs
*/
long getLength(String blobId) throws MicroKernelException;
/**
* Reads up to {@code length} bytes of data from the specified blob into
* the given array of bytes where the actual number of bytes read is
* {@code min(length, max(0, blobLength - pos))}.
* <p>
* If the returned value is smaller than {@code length}, no more data is available.
* This method never returns negative values.
*
* @param blobId blob identifier
* @param pos the offset within the blob
* @param buff the buffer into which the data is read.
* @param off the start offset in array {@code buff}
* at which the data is written.
* @param length the maximum number of bytes to read
* @return the total number of bytes read into the buffer.
* @throws MicroKernelException if the specified blob does not exist or if another error occurs
*/
int /* count */ read(String blobId, long pos, byte[] buff, int off, int length)
throws MicroKernelException;
/**
* Stores the content of the given stream and returns an associated
* identifier for later retrieval.
* <p>
* If identical stream content has been stored previously, then the existing
* identifier will be returned instead of storing a redundant copy.
* <p>
* The stream is closed by this method.
*
* @param in InputStream providing the blob content
* @return blob identifier associated with the given content
* @throws MicroKernelException if an error occurs
*/
String /* blobId */ write(InputStream in) throws MicroKernelException;
}
| oak-mk-api/src/main/java/org/apache/jackrabbit/mk/api/MicroKernel.java | /*
* 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.jackrabbit.mk.api;
import java.io.InputStream;
import javax.annotation.Nonnull;
/**
* The MicroKernel <b>Design Goals and Principles</b>:
* <ul>
* <li>manage huge trees of nodes and properties efficiently</li>
* <li>MVCC-based concurrency control
* (writers don't interfere with readers, snapshot isolation)</li>
* <li>GIT/SVN-inspired DAG-based versioning model</li>
* <li>highly scalable concurrent read & write operations</li>
* <li>session-less API (there's no concept of sessions; an implementation doesn't need to track/manage session state)</li>
* <li>easily portable to C</li>
* <li>easy to remote</li>
* <li>efficient support for large number of child nodes</li>
* <li>integrated API for efficiently storing/retrieving large binaries</li>
* <li>human-readable data serialization (JSON)</li>
* </ul>
* <p>
* The MicroKernel <b>Data Model</b>:
* </p>
* <ul>
* <li>simple JSON-inspired data model: just nodes and properties</li>
* <li>a node consists of an unordered set of name -> item mappings. each
* property and child node is uniquely named and a single name can only
* refer to a property or a child node, not both at the same time.
* <li>properties are represented as name/value pairs</li>
* <li>supported property types: string, number, boolean, array</li>
* <li>a property value is stored and used as an opaque, unparsed character sequence</li>
* </ul>
* <p>
* The <b>Retention Policy for Revisions</b>:
* <p>
* TODO specify retention policy for old revisions, i.e. minimal guaranteed retention period (OAK-114)
* </p>
* <p>
* The <b>Retention Policy for Binaries</b>:
* </p>
* <p>
* The MicroKernel implementation is free to remove binaries if both of the
* following conditions are met:
* </p>
* <ul>
* <li>If the binary is not references as a property value of the
* format ":blobId:<blobId>" where <blobId> is the id returned by
* {@link #write(InputStream in)}. This includes simple property values such as
* {"bin": ":blobId:1234"} as well as array property values such as
* {"array": [":blobId:1234", ":blobId:5678"]}.</li>
* <li>If the binary was stored before the last retained revision (this is to
* keep temporary binaries, and binaries that are not yet referenced).</li>
* </ul>
*/
public interface MicroKernel {
public static final String CONFLICT = ":conflict";
//---------------------------------------------------------< REVISION ops >
/**
* Return the id of the current head revision, i.e. the most recent <i>public</i>
* trunk revision. <i>Private</i> branch revisions are ignored.
*
* @return the id of the head revision
* @throws MicroKernelException if an error occurs
*/
String getHeadRevision() throws MicroKernelException;
/**
* Creates a new checkpoint of the latest head revision. The checkpoint
* guarantees that revision to remain valid and accessible for at least
* as long as requested.
*
* @param lifetime time (in milliseconds) that the checkpoint should
* remain available
* @return revision id of the created checkpoint
* @throws MicroKernelException if the checkpoint could not be created
*/
@Nonnull
String checkpoint(long lifetime) throws MicroKernelException;
/**
* Returns a list of all currently available (historical) head revisions in
* chronological order since a specific point. <i>Private</i> branch
* revisions won't be included in the result.
* <p>
* Format:
* <pre>
* [
* {
* "id" : "<revisionId>",
* "ts" : <revisionTimestamp>,
* "msg" : "<commitMessage>"
* },
* ...
* ]
* </pre>
* The {@code path} parameter allows to filter the revisions by path, i.e.
* only those revisions that affected the subtree rooted at {@code path}
* will be included.
* <p>
* The {@code maxEntries} parameter allows to limit the number of revisions
* returned. if {@code maxEntries < 0} no limit will be applied. otherwise,
* if the number of revisions satisfying the specified {@code since} and
* {@code path} criteria exceeds {@code maxEntries}, only {@code maxEntries}
* entries will be returned (in chronological order, starting with the oldest).
*
* @param since timestamp (ms) of earliest revision to be returned
* @param maxEntries maximum #entries to be returned;
* if < 0, no limit will be applied.
* @param path optional path filter; if {@code null} or {@code ""} the
* default ({@code "/"}) will be assumed, i.e. no filter
* will be applied
* @return a list of revisions in chronological order in JSON format.
* @throws MicroKernelException if an error occurs
*/
String /* jsonArray */ getRevisionHistory(long since, int maxEntries, String path)
throws MicroKernelException;
/**
* Waits for a commit to occur that is more recent than {@code oldHeadRevisionId}.
* <p>
* This method allows for efficient polling for new revisions. The method
* will return the id of the current head revision if it is more recent than
* {@code oldHeadRevisionId}, or waits if either the specified amount of time
* has elapsed or a new head revision has become available.
* <p>
* if a zero or negative {@code timeout} value has been specified the method
* will return immediately, i.e. calling {@code waitForCommit(oldHeadRevisionId, 0)} is
* equivalent to calling {@code getHeadRevision()}.
* <p>
* Note that commits on a <i>private</i> branch will be ignored.
*
* @param oldHeadRevisionId id of earlier head revision
* @param timeout the maximum time to wait in milliseconds
* @return the id of the head revision
* @throws MicroKernelException if an error occurs
* @throws InterruptedException if the thread was interrupted
*/
String waitForCommit(String oldHeadRevisionId, long timeout)
throws MicroKernelException, InterruptedException;
/**
* Returns a revision journal, starting with {@code fromRevisionId}
* and ending with {@code toRevisionId} in chronological order.
* <p>
* Format:
* <pre>
* [
* {
* "id" : "<revisionId>",
* "ts" : <revisionTimestamp>,
* "msg" : "<commitMessage>",
* "changes" : "<JSON diff>"
* },
* ...
* ]
* </pre>
* If {@code fromRevisionId} and {@code toRevisionId} are not in chronological
* order the returned journal will be empty (i.e. {@code []})
* <p>
* The {@code path} parameter allows to filter the revisions by path, i.e.
* only those revisions that affected the subtree rooted at {@code path}
* will be included. The filter will also be applied to the JSON diff, i.e.
* the diff will include only those changes that affected the subtree rooted
* at {@code path}.
* <p>
* A {@code MicroKernelException} is thrown if either {@code fromRevisionId}
* or {@code toRevisionId} doesn't exist, if {@code fromRevisionId} denotes
* a <i>private</i> branch revision <i>and</i> {@code toRevisionId} denotes
* either a head revision or a revision on a different <i>private</i> branch,
* or if another error occurs.
* <p>
* If the journal includes <i>private</i> branch revisions, those entries
* will include a {@code "branchRootId"} denoting the head revision the
* <i>private</i> branch is based on.
*
* @param fromRevisionId id of first revision to be returned in journal
* @param toRevisionId id of last revision to be returned in journal,
* if {@code null} the current head revision is assumed
* @param path optional path filter; if {@code null} or {@code ""}
* the default ({@code "/"}) will be assumed, i.e. no
* filter will be applied
* @return a chronological list of revisions in JSON format
* @throws MicroKernelException if any of the specified revisions doesn't exist or if another error occurs
*/
String /* jsonArray */ getJournal(String fromRevisionId, String toRevisionId,
String path)
throws MicroKernelException;
/**
* Returns the JSON diff representation of the changes between the specified
* revisions. The changes will be consolidated if the specified range
* covers intermediary revisions. {@code fromRevisionId} and {@code toRevisionId}
* don't need not be in a specific chronological order.
* <p>
* The {@code path} parameter allows to filter the changes included in the
* JSON diff, i.e. only those changes that affected the subtree rooted at
* {@code path} will be included.
* <p>
* The {@code depth} limit applies to the subtree rooted at {@code path}.
* It allows to limit the depth of the diff, i.e. only changes up to the
* specified depth will be included in full detail. changes at paths exceeding
* the specified depth limit will be reported as {@code ^"/some/path" : {}},
* indicating that there are unspecified changes below that path.
* <table border="1">
* <tr>
* <th>{@code depth} value</th><th>scope of detailed diff</th>
* </tr>
* <tr>
* <td>-1</td><td>no limit will be applied</td>
* </tr>
* <tr>
* <td>0</td><td>changes affecting the properties and child node names of the node at {@code path}</td>
* </tr>
* <tr>
* <td>1</td><td>changes affecting the properties and child node names of the node at {@code path} and its direct descendants</td>
* </tr>
* <tr>
* <td>...</td><td>...</td>
* </tr>
* </table>
*
* @param fromRevisionId a revision id, if {@code null} the current head revision is assumed
* @param toRevisionId another revision id, if {@code null} the current head revision is assumed
* @param path optional path filter; if {@code null} or {@code ""}
* the default ({@code "/"}) will be assumed, i.e. no
* filter will be applied
* @param depth depth limit; if {@code -1} no limit will be applied
* @return JSON diff representation of the changes
* @throws MicroKernelException if any of the specified revisions doesn't exist or if another error occurs
*/
String /* JSON diff */ diff(String fromRevisionId, String toRevisionId,
String path, int depth)
throws MicroKernelException;
//-------------------------------------------------------------< READ ops >
/**
* Determines whether the specified node exists.
*
* @param path path denoting node
* @param revisionId revision id, if {@code null} the current head revision is assumed
* @return {@code true} if the specified node exists, otherwise {@code false}
* @throws MicroKernelException if the specified revision does not exist or if another error occurs
*/
boolean nodeExists(String path, String revisionId) throws MicroKernelException;
/**
* Returns the number of child nodes of the specified node.
* <p>
* This is a convenience method since the number of child nodes can be also
* determined by calling {@code getNodes(path, revisionId, 0, 0, 0, null)}
* and evaluating the {@code :childNodeCount} property.
*
* @param path path denoting node
* @param revisionId revision id, if {@code null} the current head revision is assumed
* @return the number of child nodes
* @throws MicroKernelException if the specified node or revision does not exist or if another error occurs
*/
long getChildNodeCount(String path, String revisionId) throws MicroKernelException;
/**
* Returns the node tree rooted at the specified parent node with the
* specified depth, maximum child node maxChildNodes and offset. The depth of the
* returned tree is governed by the {@code depth} parameter:
* <table>
* <tr>
* <td>depth = 0</td>
* <td>properties, including {@code :childNodeCount} and
* child node names (i.e. empty child node objects)</td>
* </tr>
* <tr>
* <td>depth = 1</td>
* <td>properties, child nodes and their properties (including
* {@code :childNodeCount}) and their child node names
* (i.e. empty child node objects)</td>
* </tr>
* <tr>
* <td>depth = 2</td>
* <td>[and so on...]</td>
* </tr>
* </table>
* <p>
* Example (depth=0):
* <pre>
* {
* "someprop" : "someval",
* ":childNodeCount" : 2,
* "child1" : {},
* "child2" : {}
* }
* </pre>
* Example (depth=1):
* <pre>
* {
* "someprop" : "someval",
* ":childNodeCount" : 2,
* "child1" : {
* "prop1" : 123,
* ":childNodeCount" : 2,
* "grandchild1" : {},
* "grandchild2" : {}
* },
* "child2" : {
* "prop1" : "bar",
* ":childNodeCount" : 0
* }
* }
* </pre>
* Remarks:
* <ul>
* <li>If the property {@code :childNodeCount} equals 0, then the
* node does not have any child nodes.
* <li>If the value of {@code :childNodeCount} is larger than the number
* of returned child nodes, then the node has more child nodes than those
* included in the returned tree.</li>
* </ul>
* The {@code offset} parameter is only applied to the direct child nodes
* of the root of the returned node tree. {@code maxChildNodes} however
* is applied on all hierarchy levels.
* <p>
* An {@code IllegalArgumentException} is thrown if both an {@code offset}
* greater than zero and a {@code filter} on node names (see below) have been
* specified.
* <p>
* The order of the child nodes is stable for any given {@code revisionId},
* i.e. calling {@code getNodes} repeatedly with the same {@code revisionId}
* is guaranteed to return the child nodes in the same order, but the
* specific order used is implementation-dependent and may change across
* different revisions of the same node.
* <p>
* The optional {@code filter} parameter allows to specify glob patterns for names of
* nodes and/or properties to be included or excluded.
* <p>
* Example:
* <pre>
* {
* "nodes": [ "foo*", "-foo1" ],
* "properties": [ "*", "-:childNodeCount" ]
* }
* </pre>
* In the above example all child nodes with names starting with "foo" will
* be included, except for nodes named "foo1"; similarly, all properties will
* be included except for the ":childNodeCount" metadata property (see below).
* <p>
* Glob Syntax:
* <ul>
* <li>a {@code nodes} or {@code properties} filter consists of one or more <i>globs</i>.</li>
* <li>a <i>glob</i> prefixed by {@code -} (dash) is treated as an exclusion pattern;
* all others are considered inclusion patterns.</li>
* <li>a leading {@code -} (dash) must be escaped by prepending {@code \} (backslash)
* if it should be interpreted as a literal.</li>
* <li>{@code *} (asterisk) serves as a <i>wildcard</i>, i.e. it matches any
* substring in the target name.</li>
* <li>{@code *} (asterisk) occurrences within the glob to be interpreted as
* literals must be escaped by prepending {@code \} (backslash).</li>
* <li>a filter matches a target name if any of the inclusion patterns match but
* none of the exclusion patterns.</li>
* </ul>
* If no filter is specified the implicit default filter is assumed:
* {@code {"nodes":["*"],"properties":["*"]}}
* <p>
* System-provided metadata properties:
* <ul>
* <li>{@code :childNodeCount} provides the actual number of direct child nodes; this property
* is included by the implicit default filter. it can be excluded by specifying a filter such
* as {@code {properties:["*", "-:childNodeCount"]}}</li>
* <li>{@code :hash} provides a content-based identifier for the subtree
* rooted at the {@code :hash} property's parent node. {@code :hash} values
* are similar to fingerprints. they can be compared to quickly determine
* if two subtrees are identical. if the {@code :hash} values are different
* the respective subtrees are different with regard to structure and/or properties.
* if on the other hand the {@code :hash} values are identical the respective
* subtrees are identical with regard to structure and properties.
* {@code :hash} is <i>not</i> included by the implicit default filter.
* it can be included by specifying a filter such as {@code {properties:["*", ":hash"]}}.
* <p>Returning the {@code :hash} property is optional. Some implementations
* might only return it on specific nodes or might not support it at all.
* If however a {@code :hash} property is returned it has to obey the contract
* described above.</p>
* <p>Implementations that keep track of the child hash along with
* the child node name can return the {@code :hash} value also as
* a property of the child node objects, even if they'd otherwise
* be empty, for example due to a depth limit. If such child hashes
* are returned, the client can use them as an alternative to child
* paths when accessing those nodes.</li>
* <li>{@code :id} provides an implementation-specific identifier
* of a node. Identifiers are like content hashes as described above,
* except for the fact that two different identifiers may refer to
* identical subtrees. Also {@code :id} values may be returned for
* child nodes, in which case the client can use them for accessing
* those nodes.
* </li>
* </ul>
*
* @param path path denoting root of node tree to be retrieved,
* or alternatively a previously returned
* {@code :hash} or {@code :id} value; in the latter case
* the {@code revisionId} parameter is ignored.
* @param revisionId revision id, if {@code null} the current head revision is assumed;
* the {@code revisionId} parameter is ignored if {@code path}
* is an identifier (i.e. a {@code :hash} or {@code :id} value).
* @param depth maximum depth of returned tree
* @param offset start position in the iteration order of child nodes (0 to start at the
* beginning)
* @param maxChildNodes maximum number of sibling child nodes to retrieve (-1 for all)
* @param filter optional filter on property and/or node names; if {@code null} or
* {@code ""} the default filter will be assumed
* @return node tree in JSON format or {@code null} if the specified node does not exist
* @throws MicroKernelException if the specified revision does not exist or if another error occurs
* @throws IllegalArgumentException if both an {@code offset > 0} and a {@code filter} on node names have been specified
*/
String /* jsonTree */ getNodes(String path, String revisionId, int depth,
long offset, int maxChildNodes, String filter)
throws MicroKernelException;
//------------------------------------------------------------< WRITE ops >
/**
* Applies the specified changes on the specified target node.
* <p>
* If {@code path.length() == 0} the paths specified in the
* {@code jsonDiff} are expected to be absolute.
* <p>
* The implementation tries to merge changes if the revision id of the
* commit is set accordingly. As an example, deleting a node is allowed if
* the node existed in the given revision, even if it was deleted in the
* meantime.
*
* @param path path denoting target node
* @param jsonDiff changes to be applied in JSON diff format.
* @param revisionId id of revision the changes are based on,
* if {@code null} the current head revision is assumed
* @param message commit message
* @return id of newly created revision
* @throws MicroKernelException if the specified revision doesn't exist or if another error occurs
*/
String /* revisionId */ commit(String path, String jsonDiff,
String revisionId, String message)
throws MicroKernelException;
/**
* Creates a <i>private</i> branch revision off the specified <i>public</i>
* trunk revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code trunkRevisionId} doesn't
* exist, if it's not a <i>trunk</i> revision (i.e. it's not reachable
* by traversing the revision history in reverse chronological order starting
* from the current head revision) or if another error occurs.
*
* @param trunkRevisionId id of public trunk revision to base branch on,
* if {@code null} the current head revision is assumed
* @return id of newly created private branch revision
* @throws MicroKernelException if {@code trunkRevisionId} doesn't exist,
* if it's not a <i>trunk</i> revision
* or if another error occurs
* @see #merge(String, String)
*/
String /* revisionId */ branch(String trunkRevisionId)
throws MicroKernelException;
/**
* Merges the specified <i>private</i> branch revision with the current
* head revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code branchRevisionId} doesn't
* exist, if it's not a branch revision, if the merge fails because of
* conflicting changes or if another error occurs.
*
* @param branchRevisionId id of private branch revision
* @param message commit message
* @return id of newly created head revision
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if the merge
* fails because of conflicting changes or if
* another error occurs.
* @see #branch(String)
*/
String /* revisionId */ merge(String branchRevisionId, String message)
throws MicroKernelException;
/**
* Rebases the specified <i>private</i> branch revision on top of specified new base
* revision.
* <p>
* A {@code MicroKernelException} is thrown if {@code branchRevisionId} doesn't
* exist, if it's not a branch revision, if {@code newBaseRevisionId} doesn't exist,
* if it's a branch revision or if another error occurs.
* <p>
* If rebasing results in a conflict, conflicting nodes are annotated with a conflict
* marker denoting the type of the conflict and the value(s) before the rebase operation.
* The conflict marker is an internal node with the name {@link #CONFLICT} and is added
* to the node whose properties or child nodes are in conflict.
* <p>
* type of conflicts:
* <dl>
* <dt>addExistingProperty:</dt>
* <dd>A property has been added that has a different value than a property with the same name
* that has been added in trunk.</dd>
* <dt>deleteDeletedProperty:</dt>
* <dd>A property has been removed while a property of the same name has been removed in trunk.</dd>
* <dt>deleteChangedProperty:</dt>
* <dd>A property has been removed while a property of the same name has been changed in trunk.</dd>
* <dt>changeDeletedProperty:</dt>
* <dd>A property has been changed while a property of the same name has been removed in trunk. </dd>
* <dt>changeChangedProperty:</dt>
* <dd>A property has been changed while a property of the same name has been changed to a
* different value in trunk.</dd>
* <dt>addExistingNode:</dt>
* <dd>A node has been added that can't be merged with a node of them same name that has
* been added to the trunk. How and whether merging takes place is up to the
* implementation. Merging must not cause data to be lost however.</dd>
* <dt>deleteDeletedNode:</dt>
* <dd>A node has been removed while a node of the same name has been removed in trunk.</dd>
* <dt>deleteChangedNode:</dt>
* <dd>A node has been removed while a node of the same name has been changed in trunk.</dd>
* <dt>changeDeletedNode:</dt>
* <dd>A node has been changed while a node of the same name has been removed in trunk.</dd>
* </dl>
* In this context a node is regarded as changed if a property was added, a property was removed,
* a property was set to a different value, a child node was added, a child node was removed or
* a child node was changed.
* <p>
* On conflict the conflict marker node carries the conflicting value of the branch while the rebased
* value in the branch itself will be set to the conflicting value of the trunk. In the case of conflicting
* properties, the conflicting value is the property value from the branch. In the case of conflicting
* node, the conflicting value is the node from the branch.
*
* @param branchRevisionId id of private branch revision
* @param newBaseRevisionId id of new base revision
* @return id of the rebased branch revision
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if {@code newBaseRevisionId}
* doesn't exist, if it's a branch revision, or if another error occurs.
*/
@Nonnull
String /*revisionId */ rebase(@Nonnull String branchRevisionId, String newBaseRevisionId)
throws MicroKernelException;
/**
* Resets the branch identified by {@code branchRevisionId} to an ancestor
* branch commit identified by {@code ancestorRevisionId}.
*
* @param branchRevisionId id of the private branch revision
* @param ancestorRevisionId id of the ancestor commit to reset the branch to.
* @return the id of the new head of the branch. This may not necessarily
* be the same as {@code ancestorRevisionId}. An implementation is
* free to create a new id for the reset branch.
* @throws MicroKernelException if {@code branchRevisionId} doesn't exist,
* if it's not a branch revision, if {@code ancestorRevisionId}
* is not a revision on that branch or if another error occurs.
*/
@Nonnull
String /* revisionId */ reset(@Nonnull String branchRevisionId,
@Nonnull String ancestorRevisionId)
throws MicroKernelException;
//--------------------------------------------------< BLOB READ/WRITE ops >
/**
* Returns the length of the specified blob.
*
* @param blobId blob identifier
* @return length of the specified blob
* @throws MicroKernelException if the specified blob does not exist or if another error occurs
*/
long getLength(String blobId) throws MicroKernelException;
/**
* Reads up to {@code length} bytes of data from the specified blob into
* the given array of bytes where the actual number of bytes read is
* {@code min(length, max(0, blobLength - pos))}.
* <p>
* If the returned value is smaller than {@code length}, no more data is available.
* This method never returns negative values.
*
* @param blobId blob identifier
* @param pos the offset within the blob
* @param buff the buffer into which the data is read.
* @param off the start offset in array {@code buff}
* at which the data is written.
* @param length the maximum number of bytes to read
* @return the total number of bytes read into the buffer.
* @throws MicroKernelException if the specified blob does not exist or if another error occurs
*/
int /* count */ read(String blobId, long pos, byte[] buff, int off, int length)
throws MicroKernelException;
/**
* Stores the content of the given stream and returns an associated
* identifier for later retrieval.
* <p>
* If identical stream content has been stored previously, then the existing
* identifier will be returned instead of storing a redundant copy.
* <p>
* The stream is closed by this method.
*
* @param in InputStream providing the blob content
* @return blob identifier associated with the given content
* @throws MicroKernelException if an error occurs
*/
String /* blobId */ write(InputStream in) throws MicroKernelException;
}
| OAK-2160: mk.getRevisionHistory: clarify since parameter
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1629148 13f79535-47bb-0310-9956-ffa450edef68
| oak-mk-api/src/main/java/org/apache/jackrabbit/mk/api/MicroKernel.java | OAK-2160: mk.getRevisionHistory: clarify since parameter | <ide><path>ak-mk-api/src/main/java/org/apache/jackrabbit/mk/api/MicroKernel.java
<ide>
<ide> /**
<ide> * Returns a list of all currently available (historical) head revisions in
<del> * chronological order since a specific point. <i>Private</i> branch
<add> * chronological order since a specific point in time. <i>Private</i> branch
<ide> * revisions won't be included in the result.
<ide> * <p>
<ide> * Format:
<ide> * {@code path} criteria exceeds {@code maxEntries}, only {@code maxEntries}
<ide> * entries will be returned (in chronological order, starting with the oldest).
<ide> *
<del> * @param since timestamp (ms) of earliest revision to be returned
<add> * @param since timestamp (number of milliseconds since midnight, January 1, 1970 UTC) of earliest revision to be returned
<ide> * @param maxEntries maximum #entries to be returned;
<ide> * if < 0, no limit will be applied.
<ide> * @param path optional path filter; if {@code null} or {@code ""} the |
|
Java | apache-2.0 | 027c8a26923f05b4c739ff1902e2a720a4ca418c | 0 | ejlchina/bean-searcher,ejlchina/bean-searcher,ejlchina/bean-searcher,ejlchina/bean-searcher | package com.ejlchina.searcher.implement;
import com.ejlchina.searcher.FieldMeta;
import com.ejlchina.searcher.BeanMeta;
import com.ejlchina.searcher.ParamFilter;
import com.ejlchina.searcher.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
/**
* Bool 值过滤器
* @author Troy.Zhou @ 2021-11-01
* @since v3.0.0
* */
public class BoolValueFilter implements ParamFilter {
/**
* 参数名分割符
* v1.2.0之前默认值是下划线:"_",自 v1.2.0之后默认值更新为中划线:"-"
*/
private String separator = "-";
/**
* Boolean true 值参数后缀
*/
private String trueSuffix = "true";
/**
* Boolean false 值参数后缀
*/
private String falseSuffix = "false";
/**
* 忽略大小写参数名后缀
*/
private String ignoreCaseSuffix = "ic";
/**
* False 参数值
*/
private String[] falseValues = new String[] { "0", "OFF", "FALSE", "N", "NO", "F" };
@Override
public <T> Map<String, Object> doFilter(BeanMeta<T> beanMeta, Map<String, Object> paraMap) {
String[] fields = getBoolFieldList(beanMeta);
String icSuffix = separator + ignoreCaseSuffix;
Map<String, Object> map = new HashMap<>();
for (Entry<String, Object> entry : paraMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.endsWith(icSuffix)) {
map.put(key, toBoolean(value));
continue;
}
String field = findField(fields, key);
if (field == null) {
// 不是 Bool 字段
map.put(key, value);
continue;
}
// 是 Bool 字段
if (key.length() == field.length()) {
map.put(field, toBoolean(value));
continue;
}
map.put(field, key.endsWith(trueSuffix));
}
return map;
}
protected String[] getBoolFieldList(BeanMeta<?> beanMeta) {
return beanMeta.getFieldMetas().stream()
.filter(meta -> {
Class<?> type = meta.getType();
return type == boolean.class || type == Boolean.class;
})
.map(FieldMeta::getName)
.toArray(String[]::new);
}
protected String findField(String[] fields, String key) {
for (String field: fields) {
if (key.startsWith(field)) {
int fLen = field.length();
if (key.length() == fLen) {
return field;
}
String suffix = key.substring(fLen);
if (!suffix.startsWith(separator)) {
continue;
}
int len = suffix.length() - separator.length();
if (len == falseSuffix.length() && suffix.endsWith(falseSuffix)
|| len == trueSuffix.length() && suffix.endsWith(trueSuffix)) {
return field;
}
}
}
return null;
}
protected Boolean toBoolean(Object value) {
if (value == null) {
return null;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
String tv = ((String) value).trim();
if (StringUtils.isBlank(tv)) {
return null;
}
for (String fv: falseValues) {
if (tv.equalsIgnoreCase(fv)) {
return Boolean.FALSE;
}
}
}
if (value instanceof Number) {
return ((Number) value).intValue() != 0;
}
return Boolean.TRUE;
}
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
this.separator = Objects.requireNonNull(separator);
}
public String getTrueSuffix() {
return trueSuffix;
}
public void setTrueSuffix(String trueSuffix) {
this.trueSuffix = Objects.requireNonNull(trueSuffix);
}
public String getFalseSuffix() {
return falseSuffix;
}
public void setFalseSuffix(String falseSuffix) {
this.falseSuffix = Objects.requireNonNull(falseSuffix);
}
public String getIgnoreCaseSuffix() {
return ignoreCaseSuffix;
}
public void setIgnoreCaseSuffix(String ignoreCaseSuffix) {
this.ignoreCaseSuffix = Objects.requireNonNull(ignoreCaseSuffix);
}
public String[] getFalseValues() {
return falseValues;
}
public void setFalseValues(String[] falseValues) {
this.falseValues = Objects.requireNonNull(falseValues);
}
}
| bean-searcher/src/main/java/com/ejlchina/searcher/implement/BoolValueFilter.java | package com.ejlchina.searcher.implement;
import com.ejlchina.searcher.FieldMeta;
import com.ejlchina.searcher.BeanMeta;
import com.ejlchina.searcher.ParamFilter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
/**
* Bool 值过滤器
* @author Troy.Zhou @ 2021-11-01
* @since v3.0.0
* */
public class BoolValueFilter implements ParamFilter {
/**
* 参数名分割符
* v1.2.0之前默认值是下划线:"_",自 v1.2.0之后默认值更新为中划线:"-"
*/
private String separator = "-";
/**
* Boolean true 值参数后缀
*/
private String trueSuffix = "true";
/**
* Boolean false 值参数后缀
*/
private String falseSuffix = "false";
/**
* 忽略大小写参数名后缀
*/
private String ignoreCaseSuffix = "ic";
/**
* False 参数值
*/
private String[] falseValues = new String[] { "0", "OFF", "FALSE", "N", "NO", "F" };
@Override
public <T> Map<String, Object> doFilter(BeanMeta<T> beanMeta, Map<String, Object> paraMap) {
String[] fields = getBoolFieldList(beanMeta);
String icSuffix = separator + ignoreCaseSuffix;
Map<String, Object> map = new HashMap<>();
for (Entry<String, Object> entry : paraMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.endsWith(icSuffix)) {
map.put(key, toBoolean(value));
continue;
}
String field = findField(fields, key);
if (field == null) {
// 不是 Bool 字段
map.put(key, value);
continue;
}
// 是 Bool 字段
if (key.length() == field.length()) {
map.put(field, toBoolean(value));
continue;
}
map.put(field, key.endsWith(trueSuffix));
}
return map;
}
protected String[] getBoolFieldList(BeanMeta<?> beanMeta) {
return beanMeta.getFieldMetas().stream()
.filter(meta -> {
Class<?> type = meta.getType();
return type == boolean.class || type == Boolean.class;
})
.map(FieldMeta::getName)
.toArray(String[]::new);
}
protected String findField(String[] fields, String key) {
for (String field: fields) {
if (key.startsWith(field)) {
int fLen = field.length();
if (key.length() == fLen) {
return field;
}
String suffix = key.substring(fLen);
if (!suffix.startsWith(separator)) {
continue;
}
int len = suffix.length() - separator.length();
if (len == falseSuffix.length() && suffix.endsWith(falseSuffix)
|| len == trueSuffix.length() && suffix.endsWith(trueSuffix)) {
return field;
}
}
}
return null;
}
protected Boolean toBoolean(Object value) {
if (value == null) {
return null;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
for (String v: falseValues) {
if (((String) value).equalsIgnoreCase(v)) {
return Boolean.FALSE;
}
}
}
if (value instanceof Number) {
return ((Number) value).intValue() != 0;
}
return Boolean.TRUE;
}
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
this.separator = Objects.requireNonNull(separator);
}
public String getTrueSuffix() {
return trueSuffix;
}
public void setTrueSuffix(String trueSuffix) {
this.trueSuffix = Objects.requireNonNull(trueSuffix);
}
public String getFalseSuffix() {
return falseSuffix;
}
public void setFalseSuffix(String falseSuffix) {
this.falseSuffix = Objects.requireNonNull(falseSuffix);
}
public String getIgnoreCaseSuffix() {
return ignoreCaseSuffix;
}
public void setIgnoreCaseSuffix(String ignoreCaseSuffix) {
this.ignoreCaseSuffix = Objects.requireNonNull(ignoreCaseSuffix);
}
public String[] getFalseValues() {
return falseValues;
}
public void setFalseValues(String[] falseValues) {
this.falseValues = Objects.requireNonNull(falseValues);
}
}
| 修复:BoolValueFilter 可能将 空串 的 boolean 类型字段值 转换为 true 的问题
| bean-searcher/src/main/java/com/ejlchina/searcher/implement/BoolValueFilter.java | 修复:BoolValueFilter 可能将 空串 的 boolean 类型字段值 转换为 true 的问题 | <ide><path>ean-searcher/src/main/java/com/ejlchina/searcher/implement/BoolValueFilter.java
<ide> import com.ejlchina.searcher.FieldMeta;
<ide> import com.ejlchina.searcher.BeanMeta;
<ide> import com.ejlchina.searcher.ParamFilter;
<add>import com.ejlchina.searcher.util.StringUtils;
<ide>
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> return (Boolean) value;
<ide> }
<ide> if (value instanceof String) {
<del> for (String v: falseValues) {
<del> if (((String) value).equalsIgnoreCase(v)) {
<add> String tv = ((String) value).trim();
<add> if (StringUtils.isBlank(tv)) {
<add> return null;
<add> }
<add> for (String fv: falseValues) {
<add> if (tv.equalsIgnoreCase(fv)) {
<ide> return Boolean.FALSE;
<ide> }
<ide> } |
|
Java | apache-2.0 | 5d0b554c9bb0b7a8f9ced838f8056d790dd72dfe | 0 | Pardus-Engerek/engerek,Pardus-Engerek/engerek,Pardus-Engerek/engerek,Pardus-Engerek/engerek | /*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.workflow;
import com.evolveum.midpoint.model.api.WorkflowService;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.wf.WorkItemsPanel;
import com.evolveum.midpoint.web.page.admin.workflow.dto.WorkItemDto;
import com.evolveum.midpoint.web.page.admin.workflow.dto.WorkItemDtoProvider;
import com.evolveum.midpoint.web.session.UserProfileStorage;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import java.util.List;
/**
* @author lazyman
*/
public abstract class PageWorkItems extends PageAdminWorkItems {
//private static final Trace LOGGER = TraceManager.getTrace(PageWorkItems.class);
private static final String DOT_CLASS = PageWorkItems.class.getName() + ".";
private static final String OPERATION_APPROVE_OR_REJECT_ITEMS = DOT_CLASS + "approveOrRejectItems";
private static final String OPERATION_APPROVE_OR_REJECT_ITEM = DOT_CLASS + "approveOrRejectItem";
private static final String OPERATION_CLAIM_ITEMS = DOT_CLASS + "claimItems";
private static final String OPERATION_CLAIM_ITEM = DOT_CLASS + "claimItem";
private static final String OPERATION_RELEASE_ITEMS = DOT_CLASS + "releaseItems";
private static final String OPERATION_RELEASE_ITEM = DOT_CLASS + "releaseItem";
private static final String ID_WORK_ITEMS_PANEL = "workItemsPanel";
private static final String ID_MAIN_FORM = "mainForm";
private boolean claimable;
private boolean all;
public PageWorkItems(boolean claimable, boolean all) {
this.claimable = claimable;
this.all = all;
initLayout();
}
private void initLayout() {
Form mainForm = new Form(ID_MAIN_FORM);
add(mainForm);
WorkItemsPanel panel = new WorkItemsPanel(ID_WORK_ITEMS_PANEL, new WorkItemDtoProvider(PageWorkItems.this, claimable, all),
UserProfileStorage.TableId.PAGE_WORK_ITEMS, (int) getItemsPerPage(UserProfileStorage.TableId.PAGE_WORK_ITEMS),
WorkItemsPanel.View.FULL_LIST);
panel.setOutputMarkupId(true);
mainForm.add(panel);
initItemButtons(mainForm);
}
private void initItemButtons(Form mainForm) {
AjaxButton claim = new AjaxButton("claim", createStringResource("pageWorkItems.button.claim")) {
@Override
public void onClick(AjaxRequestTarget target) {
claimWorkItemsPerformed(target);
}
};
claim.setVisible(!all && claimable);
mainForm.add(claim);
AjaxButton release = new AjaxButton("release", createStringResource("pageWorkItems.button.release")) {
@Override
public void onClick(AjaxRequestTarget target) {
releaseWorkItemsPerformed(target);
}
};
release.setVisible(!all && !claimable);
mainForm.add(release);
// the following are shown irrespectively of whether the work item is assigned or not
AjaxButton approve = new AjaxButton("approve",
createStringResource("pageWorkItems.button.approve")) {
@Override
public void onClick(AjaxRequestTarget target) {
approveOrRejectWorkItemsPerformed(target, true);
}
};
mainForm.add(approve);
AjaxButton reject = new AjaxButton("reject",
createStringResource("pageWorkItems.button.reject")) {
@Override
public void onClick(AjaxRequestTarget target) {
approveOrRejectWorkItemsPerformed(target, false);
}
};
mainForm.add(reject);
}
private boolean isSomeItemSelected(List<WorkItemDto> items, AjaxRequestTarget target) {
if (!items.isEmpty()) {
return true;
}
warn(getString("pageWorkItems.message.noItemSelected"));
target.add(getFeedbackPanel());
return false;
}
private WorkItemsPanel getWorkItemsPanel() {
return (WorkItemsPanel) get(ID_MAIN_FORM).get(ID_WORK_ITEMS_PANEL);
}
private void approveOrRejectWorkItemsPerformed(AjaxRequestTarget target, boolean approve) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_APPROVE_OR_REJECT_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_APPROVE_OR_REJECT_ITEM);
try {
workflowService.completeWorkItem(workItemDto.getWorkItemId(), approve, null, null, result);
result.computeStatus();
} catch (Exception e) {
result.recordPartialError("Beklenmeyen hata sonucu iş akışı öğesi onay/ret işlemi gerçekleştirilemedi.", e);
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğeleri başarıyla " + (approve ? "onaylandı." : "reddedildi."));
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
private void claimWorkItemsPerformed(AjaxRequestTarget target) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_CLAIM_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_CLAIM_ITEM);
try {
workflowService.claimWorkItem(workItemDto.getWorkItemId(), result);
result.computeStatusIfUnknown();
} catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
result.recordPartialError("Beklenmeyen hata yüzünden iş akışı öğesi talep edilemedi.", e);
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğesi başarıyla talep edildi.");
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
private void releaseWorkItemsPerformed(AjaxRequestTarget target) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_RELEASE_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_RELEASE_ITEM);
try {
workflowService.releaseWorkItem(workItemDto.getWorkItemId(), result);
result.computeStatusIfUnknown();
} catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
result.recordPartialError("İş akışı öğesi beklenmeyen hata sonucu serbest bırakılamadı.", e);
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğeleri başarıyla serbest bırakıldı.");
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
}
| gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/PageWorkItems.java | /*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.workflow;
import com.evolveum.midpoint.model.api.WorkflowService;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.wf.WorkItemsPanel;
import com.evolveum.midpoint.web.page.admin.workflow.dto.WorkItemDto;
import com.evolveum.midpoint.web.page.admin.workflow.dto.WorkItemDtoProvider;
import com.evolveum.midpoint.web.session.UserProfileStorage;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import java.util.List;
/**
* @author lazyman
*/
public abstract class PageWorkItems extends PageAdminWorkItems {
//private static final Trace LOGGER = TraceManager.getTrace(PageWorkItems.class);
private static final String DOT_CLASS = PageWorkItems.class.getName() + ".";
private static final String OPERATION_APPROVE_OR_REJECT_ITEMS = DOT_CLASS + "approveOrRejectItems";
private static final String OPERATION_APPROVE_OR_REJECT_ITEM = DOT_CLASS + "approveOrRejectItem";
private static final String OPERATION_CLAIM_ITEMS = DOT_CLASS + "claimItems";
private static final String OPERATION_CLAIM_ITEM = DOT_CLASS + "claimItem";
private static final String OPERATION_RELEASE_ITEMS = DOT_CLASS + "releaseItems";
private static final String OPERATION_RELEASE_ITEM = DOT_CLASS + "releaseItem";
private static final String ID_WORK_ITEMS_PANEL = "workItemsPanel";
private static final String ID_MAIN_FORM = "mainForm";
private boolean claimable;
private boolean all;
public PageWorkItems(boolean claimable, boolean all) {
this.claimable = claimable;
this.all = all;
initLayout();
}
private void initLayout() {
Form mainForm = new Form(ID_MAIN_FORM);
add(mainForm);
WorkItemsPanel panel = new WorkItemsPanel(ID_WORK_ITEMS_PANEL, new WorkItemDtoProvider(PageWorkItems.this, claimable, all),
UserProfileStorage.TableId.PAGE_WORK_ITEMS, (int) getItemsPerPage(UserProfileStorage.TableId.PAGE_WORK_ITEMS),
WorkItemsPanel.View.FULL_LIST);
panel.setOutputMarkupId(true);
mainForm.add(panel);
initItemButtons(mainForm);
}
private void initItemButtons(Form mainForm) {
AjaxButton claim = new AjaxButton("claim", createStringResource("pageWorkItems.button.claim")) {
@Override
public void onClick(AjaxRequestTarget target) {
claimWorkItemsPerformed(target);
}
};
claim.setVisible(!all && claimable);
mainForm.add(claim);
AjaxButton release = new AjaxButton("release", createStringResource("pageWorkItems.button.release")) {
@Override
public void onClick(AjaxRequestTarget target) {
releaseWorkItemsPerformed(target);
}
};
release.setVisible(!all && !claimable);
mainForm.add(release);
// the following are shown irrespectively of whether the work item is assigned or not
AjaxButton approve = new AjaxButton("approve",
createStringResource("pageWorkItems.button.approve")) {
@Override
public void onClick(AjaxRequestTarget target) {
approveOrRejectWorkItemsPerformed(target, true);
}
};
mainForm.add(approve);
AjaxButton reject = new AjaxButton("reject",
createStringResource("pageWorkItems.button.reject")) {
@Override
public void onClick(AjaxRequestTarget target) {
approveOrRejectWorkItemsPerformed(target, false);
}
};
mainForm.add(reject);
}
private boolean isSomeItemSelected(List<WorkItemDto> items, AjaxRequestTarget target) {
if (!items.isEmpty()) {
return true;
}
warn(getString("pageWorkItems.message.noItemSelected"));
target.add(getFeedbackPanel());
return false;
}
private WorkItemsPanel getWorkItemsPanel() {
return (WorkItemsPanel) get(ID_MAIN_FORM).get(ID_WORK_ITEMS_PANEL);
}
private void approveOrRejectWorkItemsPerformed(AjaxRequestTarget target, boolean approve) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_APPROVE_OR_REJECT_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_APPROVE_OR_REJECT_ITEM);
try {
workflowService.completeWorkItem(workItemDto.getWorkItemId(), approve, null, null, result);
result.computeStatus();
} catch (Exception e) {
result.recordPartialError("Beklenmeyen hata sonucu iş akışı öğesi onay/ret işlemi gerçekleştirilemedi.", e);
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğeleri başarıyla " + (approve ? "onaylandı." : "reddedildi."));
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
private void claimWorkItemsPerformed(AjaxRequestTarget target) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_CLAIM_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_CLAIM_ITEM);
try {
workflowService.claimWorkItem(workItemDto.getWorkItemId(), result);
result.computeStatusIfUnknown();
<<<<<<< HEAD
} catch (RuntimeException e) {
result.recordPartialError("Beklenmeyen hata yüzünden iş akışı öğesi talep edilemedi.", e);
=======
} catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
result.recordPartialError("Couldn't claim work item due to an unexpected exception.", e);
>>>>>>> midpoint/master
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğesi başarıyla talep edildi.");
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
private void releaseWorkItemsPerformed(AjaxRequestTarget target) {
List<WorkItemDto> workItemDtoList = getWorkItemsPanel().getSelectedWorkItems();
if (!isSomeItemSelected(workItemDtoList, target)) {
return;
}
OperationResult mainResult = new OperationResult(OPERATION_RELEASE_ITEMS);
WorkflowService workflowService = getWorkflowService();
for (WorkItemDto workItemDto : workItemDtoList) {
OperationResult result = mainResult.createSubresult(OPERATION_RELEASE_ITEM);
try {
workflowService.releaseWorkItem(workItemDto.getWorkItemId(), result);
result.computeStatusIfUnknown();
<<<<<<< HEAD
} catch (RuntimeException e) {
result.recordPartialError("İş akışı öğesi beklenmeyen hata sonucu serbest bırakılamadı.", e);
=======
} catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
result.recordPartialError("Couldn't release work item due to an unexpected exception.", e);
>>>>>>> midpoint/master
}
}
if (mainResult.isUnknown()) {
mainResult.recomputeStatus();
}
if (mainResult.isSuccess()) {
mainResult.recordStatus(OperationResultStatus.SUCCESS, "İş akışı öğeleri başarıyla serbest bırakıldı.");
}
showResult(mainResult);
resetWorkItemCountModel();
target.add(this);
}
}
| Update PageWorkItems.java | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/PageWorkItems.java | Update PageWorkItems.java | <ide><path>ui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/PageWorkItems.java
<ide> try {
<ide> workflowService.claimWorkItem(workItemDto.getWorkItemId(), result);
<ide> result.computeStatusIfUnknown();
<del><<<<<<< HEAD
<del> } catch (RuntimeException e) {
<add> } catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
<ide> result.recordPartialError("Beklenmeyen hata yüzünden iş akışı öğesi talep edilemedi.", e);
<del>=======
<del> } catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
<del> result.recordPartialError("Couldn't claim work item due to an unexpected exception.", e);
<del>>>>>>>> midpoint/master
<ide> }
<ide> }
<ide> if (mainResult.isUnknown()) {
<ide> try {
<ide> workflowService.releaseWorkItem(workItemDto.getWorkItemId(), result);
<ide> result.computeStatusIfUnknown();
<del><<<<<<< HEAD
<del> } catch (RuntimeException e) {
<add> } catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
<ide> result.recordPartialError("İş akışı öğesi beklenmeyen hata sonucu serbest bırakılamadı.", e);
<del>=======
<del> } catch (ObjectNotFoundException | SecurityViolationException | RuntimeException e) {
<del> result.recordPartialError("Couldn't release work item due to an unexpected exception.", e);
<del>>>>>>>> midpoint/master
<ide> }
<ide> }
<ide> if (mainResult.isUnknown()) { |
|
Java | mit | 83ed0655bff0578ce8e9fb31c454c676dab59dc8 | 0 | jsedlak/Kikkit | package core;
import java.io.File;
import java.util.Timer;
import java.util.logging.Logger;
import java.util.Date;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import core.economy.*;
import core.listeners.*;
import core.players.PlayerManager;
/*
* Kikkit
* Description: A basic hMod plugin that employs a temporary whitelist
* and stops lava and fire use.
* Author: John Sedlak
* Created: 2011-01-04
*/
@SuppressWarnings("deprecation")
public class Kikkit extends JavaPlugin {
public static Kikkit Current = null;
public static Logger MinecraftLog = null; // Used to log stuff
public static boolean IsDebugging = false;
public static int DEGRIEF_ITEM_ID = 280;
public static int MAX_IGNITE_ATTEMPTS = 5;
public static final int DAY = 0;
public static final int NIGHT = 13500;
public static String getPluginName(){
return Current.getDescription().getName() + " v" + Current.getDescription().getVersion();
}
public static String getTimeStampString(Date datetime){
return datetime.getHours() + ":" + datetime.getMinutes() + ":" + datetime.getSeconds();
}
public static World getCurrentWorld(){
return Current.getServer().getWorlds().get(0);
}
private KickCounter igniteKickCounter = new KickCounter();
private KikkitPlayerListener playerListener; // Used to handle server events
private KikkitBlockListener blockListener;
private KikkitEntityListener entityListener;
@SuppressWarnings("unused")
private KikkitWorldListener worldListener;
private boolean isEnabled = true; // Whether or not the plugin is enabled
private Whitelist fireWhitelist; // Who can ignite stuff
private TemporaryWhitelist tempWhitelist;
private GenericConfig genConfig; // Generic configuration loading
private WarpList secretWarpList;
private WarpList homeWarpList;
private WarpList hModWarpList;
private SecurityManager securityManager;
private PlayerManager playerManager;
private Market currentMarket;
private String messageOfTheDay = "";
private CommandListenerCollection listeners = new CommandListenerCollection();
private String[] enabledCommands = new String[] { "*" };
Timer updateTimer;
public Kikkit(
PluginLoader pluginLoader, Server instance,
PluginDescriptionFile desc,
File folder, File plugin,
ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
Current = this;
// Instantiate our listener object
playerListener = new KikkitPlayerListener(this);
blockListener = new KikkitBlockListener(this);
entityListener = new KikkitEntityListener(this);
worldListener = new KikkitWorldListener(this);
// Get the logging device
if(MinecraftLog == null)
MinecraftLog = Logger.getLogger("Minecraft");
}
public void onEnable(){
MinecraftLog.info(getPluginName() + " has been enabled.");
isEnabled = true;
initialize();
}
public void onDisable(){
MinecraftLog.info(getPluginName() + " has been disabled.");
isEnabled = false;
if(updateTimer != null){
updateTimer.cancel();
updateTimer = null;
}
}
protected void initialize(){
// Tell the console that we have started loading the plugin
MinecraftLog.info(getPluginName() + " (Kr1sc) has been initialized.");
// Load the configuration, and the whitelist files.
securityManager = new SecurityManager();
genConfig = new GenericConfig("config/kikkit.config");
tempWhitelist = new TemporaryWhitelist("config/kikkit-whitelist.txt", genConfig, "wl-");
fireWhitelist = new Whitelist("config/kikkit-fire.txt");
secretWarpList = new WarpList("secret-warps.txt");
homeWarpList = new WarpList("player-homes.txt");
hModWarpList = new WarpList("warps.txt");
playerManager = new PlayerManager(this);
currentMarket = new Market(this);
listeners.add(new AdminCommandsListener(this));
listeners.add(new GeneralCommandsListener(this));
listeners.add(new ItemCommandsListener(this));
listeners.add(new PersonalWarpCommandsListener(this));
listeners.add(new PublicWarpCommandsListener(this));
listeners.add(new TeleportCommandsListener(this));
listeners.add(new WhitelistCommandsListener(this));
listeners.add(new EconomyCommandsListener(this));
listeners.add(new ChatCommandsListener(this));
loadConfiguration();
// HOOK! Wasn't that a movie? Anyways, attach some event handlers (I'm a C#er, okay?)
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_COMMAND, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_CANBUILD, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, new KikkitUpdater(this), Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGEDBY_BLOCK, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGEDBY_ENTITY, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGED, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_COMBUST, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this);
//pm.registerEvent(Event.Type.ITEM_SPAWN, worldListener, Priority.Normal, this);
// Setup a timer so that the update method gets called (and call it)
//updateTimer = new Timer();
//updateTimer.schedule(new KikkitUpdater(this), 0, UPDATE_INTERVAL);
broadcast(ChatColor.DARK_PURPLE + getPluginName() + " has been initialized.");
}
protected void loadConfiguration(){
try{
if(genConfig.hasKey("max-ignites")){
MAX_IGNITE_ATTEMPTS = Parser.TryParseInt(genConfig.getValue("max-ignites"), 5);
MinecraftLog.info("MAX_IGNITE_ATTEMPTS has been set to " + MAX_IGNITE_ATTEMPTS);
}
if(genConfig.hasKey("motd")){
messageOfTheDay = genConfig.getValue("motd");
}
if(genConfig.hasKey("enabledCommands")){
enabledCommands = genConfig.getValue("enabledCommands").split(",");
}
} catch(Exception ex){
MinecraftLog.info(ex.getMessage() + "\n" + ex.getStackTrace());
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
// Get the command name
String cmdName = command.getName().toLowerCase();
if(enabledCommands != null && enabledCommands.length > 0){
boolean isCmdEnabled = false;
for(int i = 0; i < enabledCommands.length; i++){
if(enabledCommands[i].equalsIgnoreCase("*") || enabledCommands[i].equalsIgnoreCase(cmdName)){
isCmdEnabled = true;
break;
}
// If the command isn't enabled, just return
if(!isCmdEnabled) return false;
}
}
CommandWrapper commandWrapper = new CommandWrapper();
commandWrapper.Sender = sender;
commandWrapper.Name = cmdName;
commandWrapper.Command = command;
commandWrapper.Label = commandLabel;
commandWrapper.Args = args;
commandWrapper.IsCancelled = false;
if(args == null) commandWrapper.Args = new String[0];
if(Kikkit.IsDebugging) {
MinecraftLog.info("onCommand: " + commandWrapper.Name);
String argStr = "";
for(String a : commandWrapper.Args){
argStr += a + " ";
}
MinecraftLog.info(" Args: " + argStr);
}
// Loop through all the command listeners
for(CommandListener listener : listeners){
boolean result = listener.onCommand(commandWrapper);
if(commandWrapper.IsCancelled || result) return true;
if(result) break;
}
return false;
}
public boolean canUseCommand(CommandSender cmdSender, String command){
if(cmdSender.isOp()) return true;
if(cmdSender instanceof Player) return canUseCommand((Player)cmdSender, command);
return false;
}
public boolean canUseCommand(Player player, String command){
return canUseCommand(player.getName(), command);
}
public boolean canUseCommand(String player, String command){
boolean returnValue = securityManager.canUseCommand(player, command);
if(Kikkit.IsDebugging) MinecraftLog.info(player + " is trying to use " + command + " and result is " + returnValue);
return returnValue;
}
public void broadcast(String msg){
for(Player player : getServer().getOnlinePlayers()){
player.sendMessage(msg);
}
}
/*
* Updates the plugin periodically.
*/
public void update(){
//MinecraftLog.info("UPDATED KIKKIT");
boolean current = tempWhitelist.getIsEnabled();
tempWhitelist.update();
if(current != tempWhitelist.getIsEnabled()){
if(tempWhitelist.getIsEnabled()){
MinecraftLog.info("Enabling whitelist temporarily.");
broadcast(ChatColor.DARK_PURPLE + "Server entered a whiteout until (at least) " + getTimeStampString(tempWhitelist.getCurrentPeriod().End) + ".");
}
else {
MinecraftLog.info("Disabling whitelist temporarily.");
broadcast(ChatColor.DARK_PURPLE + "The server has exited a whiteout.");
}
}
}
public boolean canPlayerLogin(Player player){
return tempWhitelist.isOnList(player.getName()) ||
securityManager.isInGroup(player, Groups.Vip) ||
securityManager.isInGroup(player, Groups.Moderator) ||
securityManager.isInGroup(player, Groups.Admin);
}
public boolean canPlayerIgnite(Player player){
return fireWhitelist.isOnList(player.getName()) ||
securityManager.isInGroup(player, Groups.Vip) ||
securityManager.isInGroup(player, Groups.Moderator) ||
securityManager.isInGroup(player, Groups.Admin);
}
public String getMotd(){
return messageOfTheDay;
}
// Gets whether or not the plugin is enabled
public boolean getIsEnabled(){
return isEnabled;
}
public TemporaryWhitelist getTemporaryWhitelist(){
return tempWhitelist;
}
public Whitelist getFireWhitelist(){
return fireWhitelist;
}
public WarpList getSecretWarpList(){
return secretWarpList;
}
public WarpList getHomeWarpList(){
return homeWarpList;
}
public WarpList getServerModWarps(){
return hModWarpList;
}
public GenericConfig getConfig(){
return genConfig;
}
public KickCounter getIgnitionKickCounter(){
return igniteKickCounter;
}
public SecurityManager getSecurityManager(){
return securityManager;
}
public PlayerManager getPlayerManager(){
return playerManager;
}
public Market getMarket(){ return currentMarket; }
/*
public boolean getIsWhitelistEnabled(){
return tempWhitelist.getIsEnabled();
}
public void setWhitelistOverride(boolean value){
//whitelistDisableOverride = value;
tempWhitelist.setIsOverriden(value);
MinecraftLog.info("Whitelist Override has been set to " + tempWhitelist.getIsOverriden());
}
public boolean getFireListOverride(){
//return firelistOverride;
return fireWhitelist.getIsOverriden();
}
public void setFireListOverride(boolean value){
//firelistOverride = value;
fireWhitelist.setIsOverriden(value);
}*/
}
| src/core/Kikkit.java | package core;
import java.io.File;
import java.util.Timer;
import java.util.logging.Logger;
import java.util.Date;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import core.economy.*;
import core.listeners.*;
import core.players.PlayerManager;
/*
* Kikkit
* Description: A basic hMod plugin that employs a temporary whitelist
* and stops lava and fire use.
* Author: John Sedlak
* Created: 2011-01-04
*/
@SuppressWarnings("deprecation")
public class Kikkit extends JavaPlugin {
public static Kikkit Current = null;
public static Logger MinecraftLog = null; // Used to log stuff
public static boolean IsDebugging = false;
public static int DEGRIEF_ITEM_ID = 280;
public static int MAX_IGNITE_ATTEMPTS = 5;
public static final int DAY = 0;
public static final int NIGHT = 13500;
public static String getPluginName(){
return Current.getDescription().getName() + " v" + Current.getDescription().getVersion();
}
public static String getTimeStampString(Date datetime){
return datetime.getHours() + ":" + datetime.getMinutes() + ":" + datetime.getSeconds();
}
public static World getCurrentWorld(){
return Current.getServer().getWorlds().get(0);
}
private KickCounter igniteKickCounter = new KickCounter();
private KikkitPlayerListener playerListener; // Used to handle server events
private KikkitBlockListener blockListener;
private KikkitEntityListener entityListener;
@SuppressWarnings("unused")
private KikkitWorldListener worldListener;
private boolean isEnabled = true; // Whether or not the plugin is enabled
private Whitelist fireWhitelist; // Who can ignite stuff
private TemporaryWhitelist tempWhitelist;
private GenericConfig genConfig; // Generic configuration loading
private WarpList secretWarpList;
private WarpList homeWarpList;
private WarpList hModWarpList;
private SecurityManager securityManager;
private PlayerManager playerManager;
private Market currentMarket;
private String messageOfTheDay = "";
private CommandListenerCollection listeners = new CommandListenerCollection();
Timer updateTimer;
public Kikkit(
PluginLoader pluginLoader, Server instance,
PluginDescriptionFile desc,
File folder, File plugin,
ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
Current = this;
// Instantiate our listener object
playerListener = new KikkitPlayerListener(this);
blockListener = new KikkitBlockListener(this);
entityListener = new KikkitEntityListener(this);
worldListener = new KikkitWorldListener(this);
// Get the logging device
if(MinecraftLog == null)
MinecraftLog = Logger.getLogger("Minecraft");
}
public void onEnable(){
MinecraftLog.info(getPluginName() + " has been enabled.");
isEnabled = true;
initialize();
}
public void onDisable(){
MinecraftLog.info(getPluginName() + " has been disabled.");
isEnabled = false;
if(updateTimer != null){
updateTimer.cancel();
updateTimer = null;
}
}
protected void initialize(){
// Tell the console that we have started loading the plugin
MinecraftLog.info(getPluginName() + " (Kr1sc) has been initialized.");
// Load the configuration, and the whitelist files.
securityManager = new SecurityManager();
genConfig = new GenericConfig("config/kikkit.config");
tempWhitelist = new TemporaryWhitelist("config/kikkit-whitelist.txt", genConfig, "wl-");
fireWhitelist = new Whitelist("config/kikkit-fire.txt");
secretWarpList = new WarpList("secret-warps.txt");
homeWarpList = new WarpList("player-homes.txt");
hModWarpList = new WarpList("warps.txt");
playerManager = new PlayerManager(this);
currentMarket = new Market(this);
listeners.add(new AdminCommandsListener(this));
listeners.add(new GeneralCommandsListener(this));
listeners.add(new ItemCommandsListener(this));
listeners.add(new PersonalWarpCommandsListener(this));
listeners.add(new PublicWarpCommandsListener(this));
listeners.add(new TeleportCommandsListener(this));
listeners.add(new WhitelistCommandsListener(this));
listeners.add(new EconomyCommandsListener(this));
listeners.add(new ChatCommandsListener(this));
loadConfiguration();
// HOOK! Wasn't that a movie? Anyways, attach some event handlers (I'm a C#er, okay?)
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_COMMAND, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_CANBUILD, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_RIGHTCLICKED, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, blockListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, new KikkitUpdater(this), Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGEDBY_BLOCK, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGEDBY_ENTITY, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGED, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_COMBUST, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this);
//pm.registerEvent(Event.Type.ITEM_SPAWN, worldListener, Priority.Normal, this);
// Setup a timer so that the update method gets called (and call it)
//updateTimer = new Timer();
//updateTimer.schedule(new KikkitUpdater(this), 0, UPDATE_INTERVAL);
broadcast(ChatColor.DARK_PURPLE + getPluginName() + " has been initialized.");
}
protected void loadConfiguration(){
try{
if(genConfig.hasKey("max-ignites")){
MAX_IGNITE_ATTEMPTS = Parser.TryParseInt(genConfig.getValue("max-ignites"), 5);
MinecraftLog.info("MAX_IGNITE_ATTEMPTS has been set to " + MAX_IGNITE_ATTEMPTS);
}
if(genConfig.hasKey("motd")){
messageOfTheDay = genConfig.getValue("motd");
}
} catch(Exception ex){
MinecraftLog.info(ex.getMessage() + "\n" + ex.getStackTrace());
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
//String[] split = event.getMessage().split(" ");
//Player player = event.getPlayer();
CommandWrapper commandWrapper = new CommandWrapper();
commandWrapper.Sender = sender;
commandWrapper.Name = command.getName();
commandWrapper.Command = command;
commandWrapper.Label = commandLabel;
commandWrapper.Args = args;
commandWrapper.IsCancelled = false;
if(args == null) commandWrapper.Args = new String[0];
if(Kikkit.IsDebugging) {
MinecraftLog.info("onCommand: " + commandWrapper.Name);
String argStr = "";
for(String a : commandWrapper.Args){
argStr += a + " ";
}
MinecraftLog.info(" Args: " + argStr);
}
// Loop through all the command listeners
for(CommandListener listener : listeners){
boolean result = listener.onCommand(commandWrapper);
if(commandWrapper.IsCancelled || result) return true;
if(result) break;
}
return false;
}
public boolean canUseCommand(CommandSender cmdSender, String command){
if(cmdSender.isOp()) return true;
if(cmdSender instanceof Player) return canUseCommand((Player)cmdSender, command);
return false;
}
public boolean canUseCommand(Player player, String command){
return canUseCommand(player.getName(), command);
}
public boolean canUseCommand(String player, String command){
boolean returnValue = securityManager.canUseCommand(player, command);
if(Kikkit.IsDebugging) MinecraftLog.info(player + " is trying to use " + command + " and result is " + returnValue);
return returnValue;
}
public void broadcast(String msg){
for(Player player : getServer().getOnlinePlayers()){
player.sendMessage(msg);
}
}
/*
* Updates the plugin periodically.
*/
public void update(){
//MinecraftLog.info("UPDATED KIKKIT");
boolean current = tempWhitelist.getIsEnabled();
tempWhitelist.update();
if(current != tempWhitelist.getIsEnabled()){
if(tempWhitelist.getIsEnabled()){
MinecraftLog.info("Enabling whitelist temporarily.");
broadcast(ChatColor.DARK_PURPLE + "Server entered a whiteout until (at least) " + getTimeStampString(tempWhitelist.getCurrentPeriod().End) + ".");
}
else {
MinecraftLog.info("Disabling whitelist temporarily.");
broadcast(ChatColor.DARK_PURPLE + "The server has exited a whiteout.");
}
}
}
public boolean canPlayerLogin(Player player){
return tempWhitelist.isOnList(player.getName()) ||
securityManager.isInGroup(player, Groups.Vip) ||
securityManager.isInGroup(player, Groups.Moderator) ||
securityManager.isInGroup(player, Groups.Admin);
}
public boolean canPlayerIgnite(Player player){
return fireWhitelist.isOnList(player.getName()) ||
securityManager.isInGroup(player, Groups.Vip) ||
securityManager.isInGroup(player, Groups.Moderator) ||
securityManager.isInGroup(player, Groups.Admin);
}
public String getMotd(){
return messageOfTheDay;
}
// Gets whether or not the plugin is enabled
public boolean getIsEnabled(){
return isEnabled;
}
public TemporaryWhitelist getTemporaryWhitelist(){
return tempWhitelist;
}
public Whitelist getFireWhitelist(){
return fireWhitelist;
}
public WarpList getSecretWarpList(){
return secretWarpList;
}
public WarpList getHomeWarpList(){
return homeWarpList;
}
public WarpList getServerModWarps(){
return hModWarpList;
}
public GenericConfig getConfig(){
return genConfig;
}
public KickCounter getIgnitionKickCounter(){
return igniteKickCounter;
}
public SecurityManager getSecurityManager(){
return securityManager;
}
public PlayerManager getPlayerManager(){
return playerManager;
}
public Market getMarket(){ return currentMarket; }
/*
public boolean getIsWhitelistEnabled(){
return tempWhitelist.getIsEnabled();
}
public void setWhitelistOverride(boolean value){
//whitelistDisableOverride = value;
tempWhitelist.setIsOverriden(value);
MinecraftLog.info("Whitelist Override has been set to " + tempWhitelist.getIsOverriden());
}
public boolean getFireListOverride(){
//return firelistOverride;
return fireWhitelist.getIsOverriden();
}
public void setFireListOverride(boolean value){
//firelistOverride = value;
fireWhitelist.setIsOverriden(value);
}*/
}
| Added support for enabling/disabling commands.
| src/core/Kikkit.java | Added support for enabling/disabling commands. | <ide><path>rc/core/Kikkit.java
<ide> private String messageOfTheDay = "";
<ide>
<ide> private CommandListenerCollection listeners = new CommandListenerCollection();
<add> private String[] enabledCommands = new String[] { "*" };
<ide>
<ide> Timer updateTimer;
<ide>
<ide> if(genConfig.hasKey("motd")){
<ide> messageOfTheDay = genConfig.getValue("motd");
<ide> }
<add>
<add> if(genConfig.hasKey("enabledCommands")){
<add> enabledCommands = genConfig.getValue("enabledCommands").split(",");
<add> }
<ide> } catch(Exception ex){
<ide> MinecraftLog.info(ex.getMessage() + "\n" + ex.getStackTrace());
<ide> }
<ide>
<ide> @Override
<ide> public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args){
<del> //String[] split = event.getMessage().split(" ");
<del> //Player player = event.getPlayer();
<add> // Get the command name
<add> String cmdName = command.getName().toLowerCase();
<add>
<add> if(enabledCommands != null && enabledCommands.length > 0){
<add> boolean isCmdEnabled = false;
<add> for(int i = 0; i < enabledCommands.length; i++){
<add> if(enabledCommands[i].equalsIgnoreCase("*") || enabledCommands[i].equalsIgnoreCase(cmdName)){
<add> isCmdEnabled = true;
<add> break;
<add> }
<add>
<add> // If the command isn't enabled, just return
<add> if(!isCmdEnabled) return false;
<add> }
<add> }
<ide>
<ide> CommandWrapper commandWrapper = new CommandWrapper();
<ide> commandWrapper.Sender = sender;
<del> commandWrapper.Name = command.getName();
<add> commandWrapper.Name = cmdName;
<ide> commandWrapper.Command = command;
<ide> commandWrapper.Label = commandLabel;
<ide> commandWrapper.Args = args; |
|
Java | agpl-3.0 | f5ee16bd1dd6b75a23cd9a226ae45eca4f7e05e9 | 0 | geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt2 | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.example.gwt.client.samples.layer;
import org.geomajas.example.gwt.client.samples.base.SamplePanel;
import org.geomajas.example.gwt.client.samples.base.SamplePanelFactory;
import org.geomajas.example.gwt.client.samples.i18n.I18nProvider;
import org.geomajas.gwt.client.controller.PanController;
import org.geomajas.gwt.client.gfx.paintable.mapaddon.GoogleAddon;
import org.geomajas.gwt.client.widget.MapWidget;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.layout.VLayout;
/**
* Sample that shows two Google maps, one with normal, one satellite, one with terrain.
*
* @author Joachim Van der Auwera
* @author Oliver May
*/
public class GoogleSample extends SamplePanel {
public static final String TITLE = "GoogleLayer";
public static final SamplePanelFactory FACTORY = new SamplePanelFactory() {
public SamplePanel createPanel() {
return new GoogleSample();
}
};
private MapWidget googleMap;
private MapWidget googleSatMap;
private MapWidget googleTerrainMap;
public Canvas getViewPanel() {
VLayout layout = new VLayout();
layout.setWidth100();
layout.setHeight100();
layout.setMembersMargin(10);
// Create map with Google layer, and add a PanController to it:
VLayout mapLayout1 = new VLayout();
mapLayout1.setShowEdges(true);
googleMap = new MapWidget("mapGoogle", "gwt-samples");
googleMap.setController(new PanController(googleMap));
mapLayout1.addMember(googleMap);
// Create map with Google layer (satellite), and add a PanController to it:
// VLayout mapLayout2 = new VLayout();
// mapLayout2.setShowEdges(true);
// googleSatMap = new MapWidget("mapGoogleSat", "gwt-samples");
// googleSatMap.setController(new PanController(googleSatMap));
// mapLayout2.addMember(googleSatMap);
//
// // Create map with Google layer (terrain), and add a PanController to it:
// VLayout mapLayout3 = new VLayout();
// mapLayout3.setShowEdges(true);
// googleTerrainMap = new MapWidget("mapGoogleTerrain", "gwt-samples");
// googleTerrainMap.setController(new PanController(googleTerrainMap));
// mapLayout3.addMember(googleTerrainMap);
// Place all three in the layout:
layout.addMember(mapLayout1);
// layout.addMember(mapLayout2);
// layout.addMember(mapLayout3);
return layout;
}
public String getDescription() {
return I18nProvider.getSampleMessages().googleDescription();
}
public String getSourceFileName() {
return "classpath:org/geomajas/example/gwt/client/samples/layer/GoogleSample.txt";
}
public String[] getConfigurationFiles() {
return new String[] { "WEB-INF/mapGoogle.xml", "WEB-INF/mapGoogleSat.xml",
"WEB-INF/mapGoogleTerrain.xml", "WEB-INF/layerGoogle.xml", "WEB-INF/layerGoogleSat.xml",
"WEB-INF/layerGoogleTerrain.xml" };
}
public String ensureUserLoggedIn() {
return "luc";
}
// @extract-start GoogleSample, GoogleSample
protected void onDraw2() {
googleMap.registerMapAddon(new GoogleAddon("google", googleMap, GoogleAddon.MapType.NORMAL, false));
googleSatMap.registerMapAddon(new GoogleAddon("google", googleSatMap, GoogleAddon.MapType.SATELLITE, false));
googleTerrainMap.registerMapAddon(new GoogleAddon("google", googleTerrainMap, GoogleAddon.MapType.PHYSICAL,
false));
MapSynchronizer synchronizer = new MapSynchronizer(googleMap.getMapModel().getMapView(), googleSatMap
.getMapModel().getMapView());
MapSynchronizer synchronizer2 = new MapSynchronizer(googleMap.getMapModel().getMapView(), googleTerrainMap
.getMapModel().getMapView());
synchronizer.setEnabled(true);
synchronizer2.setEnabled(true);
}
// @extract-end
}
| application/geomajas-gwt-example/src/main/java/org/geomajas/example/gwt/client/samples/layer/GoogleSample.java | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.example.gwt.client.samples.layer;
import org.geomajas.example.gwt.client.samples.base.SamplePanel;
import org.geomajas.example.gwt.client.samples.base.SamplePanelFactory;
import org.geomajas.example.gwt.client.samples.i18n.I18nProvider;
import org.geomajas.gwt.client.controller.PanController;
import org.geomajas.gwt.client.gfx.paintable.mapaddon.GoogleAddon;
import org.geomajas.gwt.client.widget.MapWidget;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.layout.VLayout;
/**
* Sample that shows two Google maps, one with normal, one satellite, one with terrain.
*
* @author Joachim Van der Auwera
* @author Oliver May
*/
public class GoogleSample extends SamplePanel {
public static final String TITLE = "GoogleLayer";
public static final SamplePanelFactory FACTORY = new SamplePanelFactory() {
public SamplePanel createPanel() {
return new GoogleSample();
}
};
private MapWidget googleMap;
private MapWidget googleSatMap;
private MapWidget googleTerrainMap;
public Canvas getViewPanel() {
VLayout layout = new VLayout();
layout.setWidth100();
layout.setHeight100();
layout.setMembersMargin(10);
// Create map with Google layer, and add a PanController to it:
VLayout mapLayout1 = new VLayout();
mapLayout1.setShowEdges(true);
googleMap = new MapWidget("mapGoogle", "gwt-samples");
googleMap.setController(new PanController(googleMap));
mapLayout1.addMember(googleMap);
// Create map with Google layer (satellite), and add a PanController to it:
VLayout mapLayout2 = new VLayout();
mapLayout2.setShowEdges(true);
// googleSatMap = new MapWidget("mapGoogleSat", "gwt-samples");
// googleSatMap.setController(new PanController(googleSatMap));
// mapLayout2.addMember(googleSatMap);
//
// // Create map with Google layer (terrain), and add a PanController to it:
// VLayout mapLayout3 = new VLayout();
// mapLayout3.setShowEdges(true);
// googleTerrainMap = new MapWidget("mapGoogleTerrain", "gwt-samples");
// googleTerrainMap.setController(new PanController(googleTerrainMap));
// mapLayout3.addMember(googleTerrainMap);
// Place all three in the layout:
layout.addMember(mapLayout1);
// layout.addMember(mapLayout2);
// layout.addMember(mapLayout3);
return layout;
}
public String getDescription() {
return I18nProvider.getSampleMessages().googleDescription();
}
public String getSourceFileName() {
return "classpath:org/geomajas/example/gwt/client/samples/layer/GoogleSample.txt";
}
public String[] getConfigurationFiles() {
return new String[] { "WEB-INF/mapGoogle.xml", "WEB-INF/mapGoogleSat.xml",
"WEB-INF/mapGoogleTerrain.xml", "WEB-INF/layerGoogle.xml", "WEB-INF/layerGoogleSat.xml",
"WEB-INF/layerGoogleTerrain.xml" };
}
public String ensureUserLoggedIn() {
return "luc";
}
// @extract-start GoogleSample, GoogleSample
protected void _onDraw() {
googleMap.registerMapAddon(new GoogleAddon("google", googleMap, GoogleAddon.MapType.NORMAL, false));
googleSatMap.registerMapAddon(new GoogleAddon("google", googleSatMap, GoogleAddon.MapType.SATELLITE, false));
googleTerrainMap.registerMapAddon(new GoogleAddon("google", googleTerrainMap, GoogleAddon.MapType.PHYSICAL,
false));
MapSynchronizer synchronizer = new MapSynchronizer(googleMap.getMapModel().getMapView(), googleSatMap
.getMapModel().getMapView());
MapSynchronizer synchronizer2 = new MapSynchronizer(googleMap.getMapModel().getMapView(), googleTerrainMap
.getMapModel().getMapView());
synchronizer.setEnabled(true);
synchronizer2.setEnabled(true);
}
// @extract-end
}
| Fix checkstyle
| application/geomajas-gwt-example/src/main/java/org/geomajas/example/gwt/client/samples/layer/GoogleSample.java | Fix checkstyle | <ide><path>pplication/geomajas-gwt-example/src/main/java/org/geomajas/example/gwt/client/samples/layer/GoogleSample.java
<ide> mapLayout1.addMember(googleMap);
<ide>
<ide> // Create map with Google layer (satellite), and add a PanController to it:
<del> VLayout mapLayout2 = new VLayout();
<del> mapLayout2.setShowEdges(true);
<add>// VLayout mapLayout2 = new VLayout();
<add>// mapLayout2.setShowEdges(true);
<ide> // googleSatMap = new MapWidget("mapGoogleSat", "gwt-samples");
<ide> // googleSatMap.setController(new PanController(googleSatMap));
<ide> // mapLayout2.addMember(googleSatMap);
<ide> }
<ide>
<ide> // @extract-start GoogleSample, GoogleSample
<del> protected void _onDraw() {
<add> protected void onDraw2() {
<ide> googleMap.registerMapAddon(new GoogleAddon("google", googleMap, GoogleAddon.MapType.NORMAL, false));
<ide> googleSatMap.registerMapAddon(new GoogleAddon("google", googleSatMap, GoogleAddon.MapType.SATELLITE, false));
<ide> googleTerrainMap.registerMapAddon(new GoogleAddon("google", googleTerrainMap, GoogleAddon.MapType.PHYSICAL, |
|
Java | apache-2.0 | dfe76d3fea32958dffbc49c7a64c6bc4d8ba99be | 0 | Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck | /*
* Copyright (C) 2004 EBI, GRL
*
* 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., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.variation;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
//import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that allele frequencies add up to 1
*/
public class AlleleFrequencies extends SingleDatabaseTestCase {
/**
* Creates a new instance of Check Allele Frequencies
*/
public AlleleFrequencies() {
addToGroup("variation");
setDescription("Check that the allele frequencies add up to 1");
}
/**
* Check that all allele/genotype frequencies add up to 1 for the same variation/subsnp and sample.
* @param dbre
* The database to use.
* @return Result.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] tables = new String[] {
"population_genotype",
"allele"
};
// Tolerance for the deviation from 1.0
float tol = 0.005f;
// Get the results in batches (determined by the variation_id)
int chunk = 1000000;
try {
Statement stmt = con.createStatement();
// Get variations with allele/genotype frequencies that don't add up to 1 for the same variation_id, subsnp_id and sample_id
for (int i=0; i<tables.length; i++) {
// The query to get the data
String sql = "SELECT s.variation_id, s.subsnp_id, s.sample_id, s.frequency FROM " + tables[i] + " s USE INDEX (variation_idx,subsnp_idx) ORDER BY s.variation_id, s.subsnp_id, s.sample_id LIMIT ";
int offset = 0;
int leftover = 1;
boolean noFail = true;
// Loop until we've reached the maximum variation_id or hit a fail condition
while (leftover > 0 && noFail) {
ResultSet rs = stmt.executeQuery(sql + new String(String.valueOf(offset) + "," + String.valueOf(chunk)));
offset += chunk;
int lastVid = 0;
int lastSSid = 0;
int lastSid = 0;
int curVid;
int curSSid;
int curSid;
float freq;
float sum = 1.f;
leftover = 0;
while (rs.next()) {
curVid = rs.getInt(1);
curSSid = rs.getInt(2);
curSid = rs.getInt(3);
freq = rs.getFloat(4);
// If any of the values was NULL, skip processing the row
if (curVid != 0 && curSSid != 0 && curSid != 0 && !rs.wasNull()) {
// If any of the ids is different from the last one, stop summing and check the sum of the latest variation
if (curVid != lastVid || curSSid != lastSSid || curSid != lastSid) {
if (Math.abs(1.f - sum) > tol) {
ReportManager.problem(this, con, "There are variations in " + tables[i] + " where the frequencies don't add up to 1 (e.g. variation_id = " + String.valueOf(lastVid) + ", subsnp_id = " + String.valueOf(lastSSid) + ", sample_id = " + String.valueOf(lastSid) + ", sum is " + String.valueOf(sum));
noFail = false;
result = false;
break;
}
// Set the last ids to this one and reset the sum
lastVid = curVid;
lastSSid = curSSid;
lastSid = curSid;
sum = 0.f;
// The previous variation is completely processed so reset the leftover counter
leftover = 0;
}
// Add the frequency to the sum
sum += freq;
}
leftover++;
}
// Roll back the offset with the leftover count so that we don't skip any variations (will also take care of the very last variation)
offset -= leftover;
rs.close();
}
if (noFail) {
ReportManager.correct(this,con,"Frequencies in " + tables[i] + " all add up to 1");
}
}
stmt.close();
} catch (Exception e) {
result = false;
e.printStackTrace();
}
if ( result ){
ReportManager.correct(this,con,"Allele/Genotype frequency healthcheck passed without any problem");
}
return result;
} // run
} // AlleleFrequencies
| src/org/ensembl/healthcheck/testcase/variation/AlleleFrequencies.java | /*
* Copyright (C) 2004 EBI, GRL
*
* 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., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.variation;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
//import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that allele frequencies add up to 1
*/
public class AlleleFrequencies extends SingleDatabaseTestCase {
/**
* Creates a new instance of Check Allele Frequencies
*/
public AlleleFrequencies() {
addToGroup("variation");
setDescription("Check that the allele frequencies add up to 1");
}
/**
* Check that all allele/genotype frequencies add up to 1 for the same variation/subsnp and sample.
* @param dbre
* The database to use.
* @return Result.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] tables = new String[] {
"population_genotype",
"allele"
};
// Get variations with allele/genotype frequencies that don't add up to 1 for the same variation_id, subsnp_id and sample_id
for (int i=0; i<tables.length; i++) {
String stmt = "SELECT q.problem FROM (SELECT CONCAT('variation_id = ',a.variation_id,', subsnp_id = ',a.subsnp_id,', sample_id = ',a.sample_id,', sum is: ',ROUND(SUM(a.frequency),2)) AS problem, ROUND(SUM(a.frequency),2) AS sum FROM " + tables[i] + " a WHERE a.frequency IS NOT NULL GROUP BY a.variation_id, a.subsnp_id, a.sample_id) AS q WHERE q.sum != 1 LIMIT 1";
String vfId = getRowColumnValue(con,stmt);
if (vfId != null && vfId.length() > 0) {
ReportManager.problem(this, con, "There are variations in " + tables[i] + " where the frequencies don't add up to 1 (e.g. " + vfId + ")");
result = false;
}
}
if ( result ){
ReportManager.correct(this,con,"Allele/Genotype frequency healthcheck passed without any problem");
}
return result;
} // run
} // AlleleFrequencies
| Perform most operations in Java to speed up processing
| src/org/ensembl/healthcheck/testcase/variation/AlleleFrequencies.java | Perform most operations in Java to speed up processing | <ide><path>rc/org/ensembl/healthcheck/testcase/variation/AlleleFrequencies.java
<ide> package org.ensembl.healthcheck.testcase.variation;
<ide>
<ide> import java.sql.Connection;
<add>import java.sql.ResultSet;
<add>import java.sql.Statement;
<ide>
<ide> import org.ensembl.healthcheck.DatabaseRegistryEntry;
<ide> //import org.ensembl.healthcheck.DatabaseType;
<ide> "population_genotype",
<ide> "allele"
<ide> };
<del> // Get variations with allele/genotype frequencies that don't add up to 1 for the same variation_id, subsnp_id and sample_id
<del> for (int i=0; i<tables.length; i++) {
<del> String stmt = "SELECT q.problem FROM (SELECT CONCAT('variation_id = ',a.variation_id,', subsnp_id = ',a.subsnp_id,', sample_id = ',a.sample_id,', sum is: ',ROUND(SUM(a.frequency),2)) AS problem, ROUND(SUM(a.frequency),2) AS sum FROM " + tables[i] + " a WHERE a.frequency IS NOT NULL GROUP BY a.variation_id, a.subsnp_id, a.sample_id) AS q WHERE q.sum != 1 LIMIT 1";
<del> String vfId = getRowColumnValue(con,stmt);
<del> if (vfId != null && vfId.length() > 0) {
<del> ReportManager.problem(this, con, "There are variations in " + tables[i] + " where the frequencies don't add up to 1 (e.g. " + vfId + ")");
<del> result = false;
<add> // Tolerance for the deviation from 1.0
<add> float tol = 0.005f;
<add> // Get the results in batches (determined by the variation_id)
<add> int chunk = 1000000;
<add>
<add> try {
<add>
<add> Statement stmt = con.createStatement();
<add>
<add> // Get variations with allele/genotype frequencies that don't add up to 1 for the same variation_id, subsnp_id and sample_id
<add> for (int i=0; i<tables.length; i++) {
<add> // The query to get the data
<add> String sql = "SELECT s.variation_id, s.subsnp_id, s.sample_id, s.frequency FROM " + tables[i] + " s USE INDEX (variation_idx,subsnp_idx) ORDER BY s.variation_id, s.subsnp_id, s.sample_id LIMIT ";
<add> int offset = 0;
<add> int leftover = 1;
<add> boolean noFail = true;
<add> // Loop until we've reached the maximum variation_id or hit a fail condition
<add> while (leftover > 0 && noFail) {
<add> ResultSet rs = stmt.executeQuery(sql + new String(String.valueOf(offset) + "," + String.valueOf(chunk)));
<add> offset += chunk;
<add>
<add> int lastVid = 0;
<add> int lastSSid = 0;
<add> int lastSid = 0;
<add> int curVid;
<add> int curSSid;
<add> int curSid;
<add> float freq;
<add> float sum = 1.f;
<add> leftover = 0;
<add>
<add> while (rs.next()) {
<add> curVid = rs.getInt(1);
<add> curSSid = rs.getInt(2);
<add> curSid = rs.getInt(3);
<add> freq = rs.getFloat(4);
<add>
<add> // If any of the values was NULL, skip processing the row
<add> if (curVid != 0 && curSSid != 0 && curSid != 0 && !rs.wasNull()) {
<add> // If any of the ids is different from the last one, stop summing and check the sum of the latest variation
<add> if (curVid != lastVid || curSSid != lastSSid || curSid != lastSid) {
<add> if (Math.abs(1.f - sum) > tol) {
<add> ReportManager.problem(this, con, "There are variations in " + tables[i] + " where the frequencies don't add up to 1 (e.g. variation_id = " + String.valueOf(lastVid) + ", subsnp_id = " + String.valueOf(lastSSid) + ", sample_id = " + String.valueOf(lastSid) + ", sum is " + String.valueOf(sum));
<add> noFail = false;
<add> result = false;
<add> break;
<add> }
<add> // Set the last ids to this one and reset the sum
<add> lastVid = curVid;
<add> lastSSid = curSSid;
<add> lastSid = curSid;
<add> sum = 0.f;
<add> // The previous variation is completely processed so reset the leftover counter
<add> leftover = 0;
<add> }
<add> // Add the frequency to the sum
<add> sum += freq;
<add> }
<add> leftover++;
<add> }
<add>
<add> // Roll back the offset with the leftover count so that we don't skip any variations (will also take care of the very last variation)
<add> offset -= leftover;
<add>
<add> rs.close();
<add> }
<add> if (noFail) {
<add> ReportManager.correct(this,con,"Frequencies in " + tables[i] + " all add up to 1");
<add> }
<ide> }
<add> stmt.close();
<add> } catch (Exception e) {
<add> result = false;
<add> e.printStackTrace();
<ide> }
<ide> if ( result ){
<ide> ReportManager.correct(this,con,"Allele/Genotype frequency healthcheck passed without any problem"); |
|
Java | lgpl-2.1 | 64ef97d3efb123570476ab130373af4686cf85d9 | 0 | benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc,benb/beast-mcmc | package test.dr.evomodel.treelikelihood;
import dr.evolution.alignment.SimpleAlignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.Units;
import dr.evomodel.sitemodel.GammaSiteModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.HKY;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treelikelihood.TreeLikelihood;
import dr.evomodelxml.sitemodel.GammaSiteModelParser;
import dr.evomodelxml.substmodel.HKYParser;
import dr.inference.model.Parameter;
import test.dr.inference.trace.TraceCorrelationAssert;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* @author Marc A. Suchard
*/
public class SequenceLikelihoodTest extends TraceCorrelationAssert {
protected NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
protected TreeModel treeModel;
protected static double tolerance = 1E-8;
public SequenceLikelihoodTest(String name) {
super(name);
}
private void recursivelyAddCharacter(String[] sequences, List<Integer> pattern,
DataType dataType) {
final int nTaxa = sequences.length;
if (pattern.size() == nTaxa) {
// Add pattern
for (int i = 0; i < nTaxa; i++) {
sequences[i] = sequences[i] + dataType.getCode(pattern.get(i));
}
} else {
// Continue recursion
final int stateCount = dataType.getStateCount();
for (int i = 0; i < stateCount; i++) {
List<Integer> newPattern = new ArrayList<Integer>();
newPattern.addAll(pattern);
newPattern.add(i);
recursivelyAddCharacter(sequences, newPattern, dataType);
}
}
}
public void testNull() {
// Do nothing; completely abstract JUnitTests are not allowed?
}
private String[] createAllUniquePatterns(int nTaxa, DataType dataType) {
String[] result = new String[nTaxa];
for (int i = 0; i < nTaxa; i++) {
result[i] = "";
}
List<Integer> pattern = new ArrayList<Integer>();
recursivelyAddCharacter(result, pattern, dataType);
return result;
}
protected void createAlignmentWithAllUniquePatterns(Object[][] taxa_sequence, DataType dataType) {
alignment = new SimpleAlignment();
alignment.setDataType(dataType);
int nTaxa = taxa_sequence[0].length;
String[] allUniquePatterns = createAllUniquePatterns(nTaxa, dataType);
taxa_sequence[1] = allUniquePatterns;
taxa = new Taxon[nTaxa]; // 6, 17
System.out.println("Taxon len = " + taxa_sequence[0].length);
System.out.println("Alignment len = " + taxa_sequence[1].length);
if (taxa_sequence.length > 2) System.out.println("Date len = " + taxa_sequence[2].length);
for (int i=0; i < taxa_sequence[0].length; i++) {
taxa[i] = new Taxon(taxa_sequence[0][i].toString());
if (taxa_sequence.length > 2) {
Date date = new Date((Double) taxa_sequence[2][i], Units.Type.YEARS, (Boolean) taxa_sequence[3][0]);
taxa[i].setDate(date);
}
//taxonList.addTaxon(taxon);
Sequence sequence = new Sequence(taxa_sequence[1][i].toString());
sequence.setTaxon(taxa[i]);
sequence.setDataType(dataType);
alignment.addSequence(sequence);
}
System.out.println("Sequence pattern count = " + alignment.getPatternCount());
}
protected double[] computeSitePatternLikelihoods(SitePatterns patterns) {
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 29.739445, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
GammaSiteModel siteModel = new GammaSiteModel(hky);
Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
siteModel.setMutationRateParameter(mu);
//treeLikelihood
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
return treeLikelihood.getPatternLogLikelihoods();
}
protected double computeSumOfPatterns(SitePatterns patterns) {
double[] patternLogLikelihoods = computeSitePatternLikelihoods(patterns);
double total = 0;
for (double x: patternLogLikelihoods) {
total += Math.exp(x);
}
return total;
}
}
| src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java | package test.dr.evomodel.treelikelihood;
import dr.evolution.alignment.SimpleAlignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.Units;
import dr.evomodel.sitemodel.GammaSiteModel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.HKY;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.treelikelihood.TreeLikelihood;
import dr.evomodelxml.sitemodel.GammaSiteModelParser;
import dr.evomodelxml.substmodel.HKYParser;
import dr.inference.model.Parameter;
import test.dr.inference.trace.TraceCorrelationAssert;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by IntelliJ IDEA.
* User: msuchard
* Date: Jul 12, 2010
* Time: 7:32:56 AM
* To change this template use File | Settings | File Templates.
*/
public class SequenceLikelihoodTest extends TraceCorrelationAssert {
protected NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
protected TreeModel treeModel;
protected static double tolerance = 1E-8;
public SequenceLikelihoodTest(String name) {
super(name);
}
private void recursivelyAddCharacter(String[] sequences, List<Integer> pattern,
DataType dataType) {
final int nTaxa = sequences.length;
if (pattern.size() == nTaxa) {
// Add pattern
for (int i = 0; i < nTaxa; i++) {
sequences[i] = sequences[i] + dataType.getCode(pattern.get(i));
}
} else {
// Continue recursion
final int stateCount = dataType.getStateCount();
for (int i = 0; i < stateCount; i++) {
List<Integer> newPattern = new ArrayList<Integer>();
newPattern.addAll(pattern);
newPattern.add(i);
recursivelyAddCharacter(sequences, newPattern, dataType);
}
}
}
private String[] createAllUniquePatterns(int nTaxa, DataType dataType) {
String[] result = new String[nTaxa];
for (int i = 0; i < nTaxa; i++) {
result[i] = "";
}
List<Integer> pattern = new ArrayList<Integer>();
recursivelyAddCharacter(result, pattern, dataType);
return result;
}
protected void createAlignmentWithAllUniquePatterns(Object[][] taxa_sequence, DataType dataType) {
alignment = new SimpleAlignment();
alignment.setDataType(dataType);
int nTaxa = taxa_sequence[0].length;
String[] allUniquePatterns = createAllUniquePatterns(nTaxa, dataType);
taxa_sequence[1] = allUniquePatterns;
taxa = new Taxon[nTaxa]; // 6, 17
System.out.println("Taxon len = " + taxa_sequence[0].length);
System.out.println("Alignment len = " + taxa_sequence[1].length);
if (taxa_sequence.length > 2) System.out.println("Date len = " + taxa_sequence[2].length);
for (int i=0; i < taxa_sequence[0].length; i++) {
taxa[i] = new Taxon(taxa_sequence[0][i].toString());
if (taxa_sequence.length > 2) {
Date date = new Date((Double) taxa_sequence[2][i], Units.Type.YEARS, (Boolean) taxa_sequence[3][0]);
taxa[i].setDate(date);
}
//taxonList.addTaxon(taxon);
Sequence sequence = new Sequence(taxa_sequence[1][i].toString());
sequence.setTaxon(taxa[i]);
sequence.setDataType(dataType);
alignment.addSequence(sequence);
}
System.out.println("Sequence pattern count = " + alignment.getPatternCount());
}
protected double[] computeSitePatternLikelihoods(SitePatterns patterns) {
// Sub model
Parameter freqs = new Parameter.Default(alignment.getStateFrequencies());
Parameter kappa = new Parameter.Default(HKYParser.KAPPA, 29.739445, 0, 100);
FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
HKY hky = new HKY(kappa, f);
//siteModel
GammaSiteModel siteModel = new GammaSiteModel(hky);
Parameter mu = new Parameter.Default(GammaSiteModelParser.MUTATION_RATE, 1.0, 0, Double.POSITIVE_INFINITY);
siteModel.setMutationRateParameter(mu);
//treeLikelihood
TreeLikelihood treeLikelihood = new TreeLikelihood(patterns, treeModel, siteModel, null, null,
false, false, true, false, false);
return treeLikelihood.getPatternLogLikelihoods();
}
protected double computeSumOfPatterns(SitePatterns patterns) {
double[] patternLogLikelihoods = computeSitePatternLikelihoods(patterns);
double total = 0;
for (double x: patternLogLikelihoods) {
total += Math.exp(x);
}
return total;
}
}
| Pacifying Hudson.
| src/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java | Pacifying Hudson. | <ide><path>rc/test/dr/evomodel/treelikelihood/SequenceLikelihoodTest.java
<ide> import java.util.Locale;
<ide>
<ide> /**
<del> * Created by IntelliJ IDEA.
<del> * User: msuchard
<del> * Date: Jul 12, 2010
<del> * Time: 7:32:56 AM
<del> * To change this template use File | Settings | File Templates.
<add> * @author Marc A. Suchard
<ide> */
<ide> public class SequenceLikelihoodTest extends TraceCorrelationAssert {
<ide> protected NumberFormat format = NumberFormat.getNumberInstance(Locale.ENGLISH);
<ide> recursivelyAddCharacter(sequences, newPattern, dataType);
<ide> }
<ide> }
<add> }
<add>
<add> public void testNull() {
<add> // Do nothing; completely abstract JUnitTests are not allowed?
<ide> }
<ide>
<ide> private String[] createAllUniquePatterns(int nTaxa, DataType dataType) { |
|
Java | apache-2.0 | dd018146fe456015ed2476aa0fb6416200c47fd6 | 0 | Jukkorsis/Hadrian,Jukkorsis/Hadrian,Jukkorsis/Hadrian | /*
* Copyright 2014 Richard Thurston.
*
* 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.northernwall.hadrian.service;
import com.northernwall.hadrian.service.helper.InfoHelper;
import com.northernwall.hadrian.maven.MavenHelper;
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;
import com.northernwall.hadrian.ConfigHelper;
import com.northernwall.hadrian.Const;
import com.northernwall.hadrian.Util;
import com.northernwall.hadrian.access.AccessException;
import com.northernwall.hadrian.access.AccessHelper;
import com.northernwall.hadrian.db.DataAccess;
import com.northernwall.hadrian.domain.Audit;
import com.northernwall.hadrian.domain.CustomFunction;
import com.northernwall.hadrian.domain.DataStore;
import com.northernwall.hadrian.domain.GitMode;
import com.northernwall.hadrian.domain.Vip;
import com.northernwall.hadrian.domain.VipRef;
import com.northernwall.hadrian.domain.Service;
import com.northernwall.hadrian.domain.Host;
import com.northernwall.hadrian.domain.Module;
import com.northernwall.hadrian.domain.Operation;
import com.northernwall.hadrian.domain.ServiceRef;
import com.northernwall.hadrian.domain.Type;
import com.northernwall.hadrian.domain.User;
import com.northernwall.hadrian.workItem.WorkItemProcessor;
import com.northernwall.hadrian.service.dao.GetAuditData;
import com.northernwall.hadrian.service.dao.GetCustomFunctionData;
import com.northernwall.hadrian.service.dao.GetDataStoreData;
import com.northernwall.hadrian.service.dao.GetHostData;
import com.northernwall.hadrian.service.dao.GetModuleData;
import com.northernwall.hadrian.service.dao.GetNotUsesData;
import com.northernwall.hadrian.service.dao.GetServiceData;
import com.northernwall.hadrian.service.dao.GetServiceRefData;
import com.northernwall.hadrian.service.dao.GetServicesData;
import com.northernwall.hadrian.service.dao.GetVipData;
import com.northernwall.hadrian.service.dao.GetVipRefData;
import com.northernwall.hadrian.service.dao.PostServiceData;
import com.northernwall.hadrian.service.dao.PostServiceRefData;
import com.northernwall.hadrian.service.dao.PutServiceData;
import com.northernwall.hadrian.service.helper.ReadAvailabilityRunnable;
import com.northernwall.hadrian.service.helper.ReadMavenVersionsRunnable;
import com.northernwall.hadrian.service.helper.ReadVersionRunnable;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Richard Thurston
*/
public class ServiceHandler extends AbstractHandler {
private final static Logger logger = LoggerFactory.getLogger(ServiceHandler.class);
private final AccessHelper accessHelper;
private final DataAccess dataAccess;
private final WorkItemProcessor workItemProcess;
private final ConfigHelper configHelper;
private final MavenHelper mavenHelper;
private final InfoHelper infoHelper;
private final Gson gson;
private final ExecutorService executorService;
private final DateFormat format;
public ServiceHandler(AccessHelper accessHelper, DataAccess dataAccess, WorkItemProcessor workItemProcess, ConfigHelper configHelper, MavenHelper mavenHelper, InfoHelper infoHelper) {
this.accessHelper = accessHelper;
this.dataAccess = dataAccess;
this.workItemProcess = workItemProcess;
this.configHelper = configHelper;
this.mavenHelper = mavenHelper;
this.infoHelper = infoHelper;
gson = new Gson();
executorService = Executors.newFixedThreadPool(20);
format = new SimpleDateFormat("MM/dd/yyyy");
}
@Override
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response) throws IOException, ServletException {
try {
if (target.startsWith("/v1/service")) {
switch (request.getMethod()) {
case Const.HTTP_GET:
if (target.matches("/v1/service")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getServices(response);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/notuses")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getServiceNotUses(response, target.substring(12, target.length() - 8));
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/audit")) {
String start = request.getParameter("start");
String end = request.getParameter("end");
logger.info("Handling {} request {} start {} end {}", request.getMethod(), target, start, end);
getServiceAudit(response, target.substring(12, target.length() - 6), start, end);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getService(request, response, target.substring(12, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_POST:
if (target.matches("/v1/service/service")) {
logger.info("Handling {} request {}", request.getMethod(), target);
createService(request);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/ref")) {
logger.info("Handling {} request {}", request.getMethod(), target);
createServiceRef(request, target.substring(12, target.length() - 4));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_PUT:
if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
updateService(request, target.substring(12, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_DELETE:
if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/uses/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
deleteServiceRef(request, target.substring(12, target.length() - 42), target.substring(54, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
}
}
} catch (AccessException e) {
logger.error("Exception {} while handling request for {}", e.getMessage(), target);
response.setStatus(401);
request.setHandled(true);
} catch (Exception e) {
logger.error("Exception {} while handling request for {}", e.getMessage(), target, e);
response.setStatus(400);
request.setHandled(true);
}
}
private void getServices(HttpServletResponse response) throws IOException {
response.setContentType(Const.JSON);
List<Service> services = dataAccess.getServices();
GetServicesData getServicesData = new GetServicesData();
for (Service service : services) {
getServicesData.services.add(GetServiceData.create(service));
}
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(getServicesData, GetServicesData.class, jw);
}
}
private void getService(Request request, HttpServletResponse response, String id) throws IOException {
response.setContentType(Const.JSON);
Service service = dataAccess.getService(id);
if (service == null) {
throw new RuntimeException("Could not find service with id '" + id + "'");
}
GetServiceData getServiceData = GetServiceData.create(service);
getServiceData.canModify = accessHelper.canUserModify(request, service.getTeamId());
List<Future> futures = new LinkedList<>();
List<Module> modules = dataAccess.getModules(id);
Collections.sort(modules);
for (Module module : modules) {
GetModuleData getModuleData = GetModuleData.create(module, configHelper.getConfig());
futures.add(executorService.submit(new ReadMavenVersionsRunnable(getModuleData, mavenHelper)));
getServiceData.modules.add(getModuleData);
}
List<Vip> vips = dataAccess.getVips(id);
Collections.sort(vips);
for (Vip vip : vips) {
GetModuleData getModuleData = null;
for (GetModuleData temp : getServiceData.modules) {
if (vip.getModuleId().equals(temp.moduleId)) {
getModuleData = temp;
}
}
if (getModuleData != null) {
GetVipData getVipData = GetVipData.create(vip);
getModuleData.addVip(getVipData);
}
}
List<Host> hosts = dataAccess.getHosts(id);
Collections.sort(hosts);
for (Host host : hosts) {
GetModuleData getModuleData = null;
for (GetModuleData temp : getServiceData.modules) {
if (host.getModuleId().equals(temp.moduleId)) {
getModuleData = temp;
}
}
if (getModuleData != null) {
GetHostData getHostData = GetHostData.create(host);
futures.add(executorService.submit(new ReadVersionRunnable(getHostData, getModuleData, infoHelper)));
futures.add(executorService.submit(new ReadAvailabilityRunnable(getHostData, getModuleData, infoHelper)));
for (VipRef vipRef : dataAccess.getVipRefsByHost(getHostData.hostId)) {
GetVipRefData getVipRefData = GetVipRefData.create(vipRef);
for (GetVipData vip : getModuleData.getVips(host.getNetwork())) {
if (vip.vipId.equals(getVipRefData.vipId)) {
getVipRefData.vipName = vip.vipName;
}
}
getHostData.vipRefs.add(getVipRefData);
}
getModuleData.addHost(getHostData);
}
}
List<DataStore> dataStores = dataAccess.getDataStores(id);
Collections.sort(dataStores);
for (DataStore dataStore : dataStores) {
GetDataStoreData getDataStoreData = GetDataStoreData.create(dataStore);
getServiceData.dataStores.add(getDataStoreData);
}
for (ServiceRef ref : dataAccess.getServiceRefsByClient(id)) {
GetServiceRefData tempRef = GetServiceRefData.create(ref);
tempRef.serviceName = dataAccess.getService(ref.getServerServiceId()).getServiceName();
getServiceData.uses.add(tempRef);
}
for (ServiceRef ref : dataAccess.getServiceRefsByServer(id)) {
GetServiceRefData tempRef = GetServiceRefData.create(ref);
tempRef.serviceName = dataAccess.getService(ref.getClientServiceId()).getServiceName();
getServiceData.usedBy.add(tempRef);
}
List<CustomFunction> customFunctions = dataAccess.getCustomFunctions(id);
Collections.sort(customFunctions);
for (CustomFunction customFunction : customFunctions) {
for (GetModuleData temp : getServiceData.modules) {
if (customFunction.getModuleId().equals(temp.moduleId)) {
GetCustomFunctionData getCustomFunctionData = GetCustomFunctionData.create(customFunction);
temp.customFunctions.add(getCustomFunctionData);
}
}
}
waitForFutures(futures);
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(getServiceData, GetServiceData.class, jw);
}
}
private void waitForFutures(List<Future> futures) {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
}
futures.removeIf(new Predicate<Future>() {
@Override
public boolean test(Future t) {
return t.isDone();
}
});
if (futures.isEmpty()) {
return;
}
}
}
private void getServiceNotUses(HttpServletResponse response, String id) throws IOException {
logger.info("got here {}", id);
List<Service> services = dataAccess.getServices();
List<ServiceRef> refs = dataAccess.getServiceRefsByClient(id);
GetNotUsesData notUses = new GetNotUsesData();
for (Service service : services) {
if (!service.getServiceId().equals(id)) {
boolean found = false;
for (ServiceRef ref : refs) {
if (service.getServiceId().equals(ref.getServerServiceId())) {
found = true;
}
}
if (!found) {
GetServiceRefData ref = new GetServiceRefData();
ref.clientServiceId = id;
ref.serverServiceId = service.getServiceId();
ref.serviceName = service.getServiceName();
notUses.refs.add(ref);
}
}
}
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(notUses, GetNotUsesData.class, jw);
}
}
private void getServiceAudit(HttpServletResponse response, String id, String start, String end) throws IOException {
GetAuditData auditData = new GetAuditData();
Date startDate = null;
try {
startDate = format.parse(start);
} catch (ParseException ex) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -15);
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
startDate = now.getTime();
}
Date endDate = null;
try {
endDate = format.parse(end);
} catch (ParseException ex) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, 1);
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
endDate = now.getTime();
}
logger.info("Audit search from {} to {} on service {}", startDate.toString(), endDate.toString(), id);
auditData.audits = dataAccess.getAudit(id, startDate, endDate);
Collections.sort(auditData.audits);
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(auditData, GetAuditData.class, jw);
}
}
private void createService(Request request) throws IOException {
PostServiceData postServiceData = Util.fromJson(request, PostServiceData.class);
User user = accessHelper.checkIfUserCanModify(request, postServiceData.teamId, "create a service");
postServiceData.serviceAbbr = postServiceData.serviceAbbr.toLowerCase();
for (Service temp : dataAccess.getServices(postServiceData.teamId)) {
if (temp.getServiceAbbr().equals(postServiceData.serviceAbbr)) {
logger.warn("A service already exists with that abbreviation, {}", postServiceData.serviceAbbr);
return;
}
}
if (postServiceData.serviceType.equals(Const.SERVICE_TYPE_SHARED_LIBRARY)) {
postServiceData.gitMode = GitMode.Flat;
}
Service service = new Service(
postServiceData.serviceAbbr.toUpperCase(),
postServiceData.serviceName,
postServiceData.teamId,
postServiceData.description,
postServiceData.serviceType,
postServiceData.gitMode,
postServiceData.gitProject);
dataAccess.saveService(service);
Map<String, String> notes = new HashMap<>();
notes.put("name", service.getServiceName());
notes.put("abbr", service.getServiceAbbr());
createAudit(service.getServiceId(), user.getUsername(), Type.service, Operation.create, notes);
}
private void updateService(Request request, String id) throws IOException {
PutServiceData putServiceData = Util.fromJson(request, PutServiceData.class);
Service service = dataAccess.getService(id);
if (service == null) {
throw new RuntimeException("Could not find service");
}
accessHelper.checkIfUserCanModify(request, service.getTeamId(), "modify a service");
service.setServiceAbbr(putServiceData.serviceAbbr.toUpperCase());
service.setServiceName(putServiceData.serviceName);
service.setDescription(putServiceData.description);
dataAccess.updateService(service);
}
private void createServiceRef(Request request, String clientId) throws IOException {
PostServiceRefData postServiceRefData = Util.fromJson(request, PostServiceRefData.class);
Service clientService = dataAccess.getService(clientId);
if (clientService == null) {
throw new RuntimeException("Could not find service");
}
User user = accessHelper.checkIfUserCanModify(request, clientService.getTeamId(), "add a service ref");
for (Entry<String, String> entry : postServiceRefData.uses.entrySet()) {
if (entry.getValue().equalsIgnoreCase("true")) {
String serverId = entry.getKey();
Service serverService = dataAccess.getService(serverId);
if (serverService != null) {
ServiceRef ref = new ServiceRef(clientId, serverId);
dataAccess.saveServiceRef(ref);
Map<String, String> notes = new HashMap<>();
notes.put("uses", serverService.getServiceAbbr());
createAudit(clientId, user.getUsername(), Type.serviceRef, Operation.create, notes);
notes = new HashMap<>();
notes.put("use_by", clientService.getServiceAbbr());
createAudit(serverId, user.getUsername(), Type.serviceRef, Operation.create, notes);
}
}
}
}
private void deleteServiceRef(Request request, String clientId, String serverId) {
Service clientService = dataAccess.getService(clientId);
if (clientService == null) {
return;
}
Service serverService = dataAccess.getService(serverId);
if (serverService == null) {
return;
}
User user = accessHelper.checkIfUserCanModify(request, clientService.getTeamId(), "delete a service ref");
dataAccess.deleteServiceRef(clientId, serverId);
Map<String, String> notes = new HashMap<>();
notes.put("uses", serverService.getServiceAbbr());
createAudit(clientId, user.getUsername(), Type.serviceRef, Operation.delete, notes);
notes = new HashMap<>();
notes.put("use_by", clientService.getServiceAbbr());
createAudit(serverId, user.getUsername(), Type.serviceRef, Operation.delete, notes);
}
private void createAudit(String serviceId, String requestor, Type type, Operation operation, Map<String, String> notes) {
Audit audit = new Audit();
audit.serviceId = serviceId;
audit.timePerformed = new Date();
audit.timeRequested = new Date();
audit.requestor = requestor;
audit.type = type;
audit.operation = operation;
audit.notes = gson.toJson(notes);
dataAccess.saveAudit(audit, " ");
}
}
| src/main/java/com/northernwall/hadrian/service/ServiceHandler.java | /*
* Copyright 2014 Richard Thurston.
*
* 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.northernwall.hadrian.service;
import com.northernwall.hadrian.service.helper.InfoHelper;
import com.northernwall.hadrian.maven.MavenHelper;
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;
import com.northernwall.hadrian.ConfigHelper;
import com.northernwall.hadrian.Const;
import com.northernwall.hadrian.Util;
import com.northernwall.hadrian.access.AccessException;
import com.northernwall.hadrian.access.AccessHelper;
import com.northernwall.hadrian.db.DataAccess;
import com.northernwall.hadrian.domain.Audit;
import com.northernwall.hadrian.domain.Config;
import com.northernwall.hadrian.domain.CustomFunction;
import com.northernwall.hadrian.domain.DataStore;
import com.northernwall.hadrian.domain.GitMode;
import com.northernwall.hadrian.domain.Vip;
import com.northernwall.hadrian.domain.VipRef;
import com.northernwall.hadrian.domain.Service;
import com.northernwall.hadrian.domain.Host;
import com.northernwall.hadrian.domain.Module;
import com.northernwall.hadrian.domain.Operation;
import com.northernwall.hadrian.domain.ServiceRef;
import com.northernwall.hadrian.domain.Type;
import com.northernwall.hadrian.domain.User;
import com.northernwall.hadrian.workItem.WorkItemProcessor;
import com.northernwall.hadrian.service.dao.GetAuditData;
import com.northernwall.hadrian.service.dao.GetCustomFunctionData;
import com.northernwall.hadrian.service.dao.GetDataStoreData;
import com.northernwall.hadrian.service.dao.GetHostData;
import com.northernwall.hadrian.service.dao.GetModuleData;
import com.northernwall.hadrian.service.dao.GetNotUsesData;
import com.northernwall.hadrian.service.dao.GetServiceData;
import com.northernwall.hadrian.service.dao.GetServiceRefData;
import com.northernwall.hadrian.service.dao.GetServicesData;
import com.northernwall.hadrian.service.dao.GetVipData;
import com.northernwall.hadrian.service.dao.GetVipRefData;
import com.northernwall.hadrian.service.dao.PostServiceData;
import com.northernwall.hadrian.service.dao.PostServiceRefData;
import com.northernwall.hadrian.service.dao.PutServiceData;
import com.northernwall.hadrian.service.helper.ReadAvailabilityRunnable;
import com.northernwall.hadrian.service.helper.ReadMavenVersionsRunnable;
import com.northernwall.hadrian.service.helper.ReadVersionRunnable;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Richard Thurston
*/
public class ServiceHandler extends AbstractHandler {
private final static Logger logger = LoggerFactory.getLogger(ServiceHandler.class);
private final AccessHelper accessHelper;
private final DataAccess dataAccess;
private final WorkItemProcessor workItemProcess;
private final ConfigHelper configHelper;
private final MavenHelper mavenHelper;
private final InfoHelper infoHelper;
private final Gson gson;
private final ExecutorService executorService;
private final DateFormat format;
public ServiceHandler(AccessHelper accessHelper, DataAccess dataAccess, WorkItemProcessor workItemProcess, ConfigHelper configHelper, MavenHelper mavenHelper, InfoHelper infoHelper) {
this.accessHelper = accessHelper;
this.dataAccess = dataAccess;
this.workItemProcess = workItemProcess;
this.configHelper = configHelper;
this.mavenHelper = mavenHelper;
this.infoHelper = infoHelper;
gson = new Gson();
executorService = Executors.newFixedThreadPool(20);
format = new SimpleDateFormat("MM/dd/yyyy");
}
@Override
public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response) throws IOException, ServletException {
try {
if (target.startsWith("/v1/service")) {
switch (request.getMethod()) {
case Const.HTTP_GET:
if (target.matches("/v1/service")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getServices(response);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/notuses")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getServiceNotUses(response, target.substring(12, target.length() - 8));
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/audit")) {
String start = request.getParameter("start");
String end = request.getParameter("end");
logger.info("Handling {} request {} start {} end {}", request.getMethod(), target, start, end);
getServiceAudit(response, target.substring(12, target.length() - 6), start, end);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
getService(request, response, target.substring(12, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_POST:
if (target.matches("/v1/service/service")) {
logger.info("Handling {} request {}", request.getMethod(), target);
createService(request);
response.setStatus(200);
request.setHandled(true);
} else if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/ref")) {
logger.info("Handling {} request {}", request.getMethod(), target);
createServiceRef(request, target.substring(12, target.length() - 4));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_PUT:
if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
updateService(request, target.substring(12, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
case Const.HTTP_DELETE:
if (target.matches("/v1/service/\\w+-\\w+-\\w+-\\w+-\\w+/uses/\\w+-\\w+-\\w+-\\w+-\\w+")) {
logger.info("Handling {} request {}", request.getMethod(), target);
deleteServiceRef(request, target.substring(12, target.length() - 42), target.substring(54, target.length()));
response.setStatus(200);
request.setHandled(true);
}
break;
}
}
} catch (AccessException e) {
logger.error("Exception {} while handling request for {}", e.getMessage(), target);
response.setStatus(401);
request.setHandled(true);
} catch (Exception e) {
logger.error("Exception {} while handling request for {}", e.getMessage(), target, e);
response.setStatus(400);
request.setHandled(true);
}
}
private void getServices(HttpServletResponse response) throws IOException {
response.setContentType(Const.JSON);
List<Service> services = dataAccess.getServices();
GetServicesData getServicesData = new GetServicesData();
for (Service service : services) {
getServicesData.services.add(GetServiceData.create(service));
}
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(getServicesData, GetServicesData.class, jw);
}
}
private void getService(Request request, HttpServletResponse response, String id) throws IOException {
response.setContentType(Const.JSON);
Service service = dataAccess.getService(id);
if (service == null) {
throw new RuntimeException("Could not find service with id '" + id + "'");
}
GetServiceData getServiceData = GetServiceData.create(service);
getServiceData.canModify = accessHelper.canUserModify(request, service.getTeamId());
List<Future> futures = new LinkedList<>();
List<Module> modules = dataAccess.getModules(id);
Collections.sort(modules);
for (Module module : modules) {
GetModuleData getModuleData = GetModuleData.create(module, configHelper.getConfig());
futures.add(executorService.submit(new ReadMavenVersionsRunnable(getModuleData, mavenHelper)));
getServiceData.modules.add(getModuleData);
}
List<Vip> vips = dataAccess.getVips(id);
Collections.sort(vips);
for (Vip vip : vips) {
GetModuleData getModuleData = null;
for (GetModuleData temp : getServiceData.modules) {
if (vip.getModuleId().equals(temp.moduleId)) {
getModuleData = temp;
}
}
if (getModuleData != null) {
GetVipData getVipData = GetVipData.create(vip);
getModuleData.addVip(getVipData);
}
}
List<Host> hosts = dataAccess.getHosts(id);
Collections.sort(hosts);
for (Host host : hosts) {
GetModuleData getModuleData = null;
for (GetModuleData temp : getServiceData.modules) {
if (host.getModuleId().equals(temp.moduleId)) {
getModuleData = temp;
}
}
if (getModuleData != null) {
GetHostData getHostData = GetHostData.create(host);
futures.add(executorService.submit(new ReadVersionRunnable(getHostData, getModuleData, infoHelper)));
futures.add(executorService.submit(new ReadAvailabilityRunnable(getHostData, getModuleData, infoHelper)));
for (VipRef vipRef : dataAccess.getVipRefsByHost(getHostData.hostId)) {
GetVipRefData getVipRefData = GetVipRefData.create(vipRef);
for (GetVipData vip : getModuleData.getVips(host.getNetwork())) {
if (vip.vipId.equals(getVipRefData.vipId)) {
getVipRefData.vipName = vip.vipName;
}
}
getHostData.vipRefs.add(getVipRefData);
}
getModuleData.addHost(getHostData);
}
}
List<DataStore> dataStores = dataAccess.getDataStores(id);
Collections.sort(dataStores);
for (DataStore dataStore : dataStores) {
GetDataStoreData getDataStoreData = GetDataStoreData.create(dataStore);
getServiceData.dataStores.add(getDataStoreData);
}
for (ServiceRef ref : dataAccess.getServiceRefsByClient(id)) {
GetServiceRefData tempRef = GetServiceRefData.create(ref);
tempRef.serviceName = dataAccess.getService(ref.getServerServiceId()).getServiceName();
getServiceData.uses.add(tempRef);
}
for (ServiceRef ref : dataAccess.getServiceRefsByServer(id)) {
GetServiceRefData tempRef = GetServiceRefData.create(ref);
tempRef.serviceName = dataAccess.getService(ref.getClientServiceId()).getServiceName();
getServiceData.usedBy.add(tempRef);
}
List<CustomFunction> customFunctions = dataAccess.getCustomFunctions(id);
Collections.sort(customFunctions);
for (CustomFunction customFunction : customFunctions) {
for (GetModuleData temp : getServiceData.modules) {
if (customFunction.getModuleId().equals(temp.moduleId)) {
GetCustomFunctionData getCustomFunctionData = GetCustomFunctionData.create(customFunction);
temp.customFunctions.add(getCustomFunctionData);
}
}
}
waitForFutures(futures);
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(getServiceData, GetServiceData.class, jw);
}
}
private void waitForFutures(List<Future> futures) {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(250);
} catch (InterruptedException ex) {
}
futures.removeIf(new Predicate<Future>() {
@Override
public boolean test(Future t) {
return t.isDone();
}
});
if (futures.isEmpty()) {
return;
}
}
}
private void getServiceNotUses(HttpServletResponse response, String id) throws IOException {
logger.info("got here {}", id);
List<Service> services = dataAccess.getServices();
List<ServiceRef> refs = dataAccess.getServiceRefsByClient(id);
GetNotUsesData notUses = new GetNotUsesData();
for (Service service : services) {
if (!service.getServiceId().equals(id)) {
boolean found = false;
for (ServiceRef ref : refs) {
if (service.getServiceId().equals(ref.getServerServiceId())) {
found = true;
}
}
if (!found) {
GetServiceRefData ref = new GetServiceRefData();
ref.clientServiceId = id;
ref.serverServiceId = service.getServiceId();
ref.serviceName = service.getServiceName();
notUses.refs.add(ref);
}
}
}
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(notUses, GetNotUsesData.class, jw);
}
}
private void getServiceAudit(HttpServletResponse response, String id, String start, String end) throws IOException {
GetAuditData auditData = new GetAuditData();
Date startDate = null;
try {
startDate = format.parse(start);
} catch (ParseException ex) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -15);
startDate = now.getTime();
}
Date endDate = null;
try {
endDate = format.parse(end);
} catch (ParseException ex) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, 1);
endDate = now.getTime();
}
auditData.audits = dataAccess.getAudit(id, startDate, endDate);
Collections.sort(auditData.audits);
try (JsonWriter jw = new JsonWriter(new OutputStreamWriter(response.getOutputStream()))) {
gson.toJson(auditData, GetAuditData.class, jw);
}
}
private void createService(Request request) throws IOException {
PostServiceData postServiceData = Util.fromJson(request, PostServiceData.class);
User user = accessHelper.checkIfUserCanModify(request, postServiceData.teamId, "create a service");
postServiceData.serviceAbbr = postServiceData.serviceAbbr.toLowerCase();
for (Service temp : dataAccess.getServices(postServiceData.teamId)) {
if (temp.getServiceAbbr().equals(postServiceData.serviceAbbr)) {
logger.warn("A service already exists with that abbreviation, {}", postServiceData.serviceAbbr);
return;
}
}
if (postServiceData.serviceType.equals(Const.SERVICE_TYPE_SHARED_LIBRARY)) {
postServiceData.gitMode = GitMode.Flat;
}
Service service = new Service(
postServiceData.serviceAbbr.toUpperCase(),
postServiceData.serviceName,
postServiceData.teamId,
postServiceData.description,
postServiceData.serviceType,
postServiceData.gitMode,
postServiceData.gitProject);
dataAccess.saveService(service);
Map<String, String> notes = new HashMap<>();
notes.put("name", service.getServiceName());
notes.put("abbr", service.getServiceAbbr());
createAudit(service.getServiceId(), user.getUsername(), Type.service, Operation.create, notes);
}
private void updateService(Request request, String id) throws IOException {
PutServiceData putServiceData = Util.fromJson(request, PutServiceData.class);
Service service = dataAccess.getService(id);
if (service == null) {
throw new RuntimeException("Could not find service");
}
accessHelper.checkIfUserCanModify(request, service.getTeamId(), "modify a service");
service.setServiceAbbr(putServiceData.serviceAbbr.toUpperCase());
service.setServiceName(putServiceData.serviceName);
service.setDescription(putServiceData.description);
dataAccess.updateService(service);
}
private void createServiceRef(Request request, String clientId) throws IOException {
PostServiceRefData postServiceRefData = Util.fromJson(request, PostServiceRefData.class);
Service clientService = dataAccess.getService(clientId);
if (clientService == null) {
throw new RuntimeException("Could not find service");
}
User user = accessHelper.checkIfUserCanModify(request, clientService.getTeamId(), "add a service ref");
for (Entry<String, String> entry : postServiceRefData.uses.entrySet()) {
if (entry.getValue().equalsIgnoreCase("true")) {
String serverId = entry.getKey();
Service serverService = dataAccess.getService(serverId);
if (serverService != null) {
ServiceRef ref = new ServiceRef(clientId, serverId);
dataAccess.saveServiceRef(ref);
Map<String, String> notes = new HashMap<>();
notes.put("uses", serverService.getServiceAbbr());
createAudit(clientId, user.getUsername(), Type.serviceRef, Operation.create, notes);
notes = new HashMap<>();
notes.put("use_by", clientService.getServiceAbbr());
createAudit(serverId, user.getUsername(), Type.serviceRef, Operation.create, notes);
}
}
}
}
private void deleteServiceRef(Request request, String clientId, String serverId) {
Service clientService = dataAccess.getService(clientId);
if (clientService == null) {
return;
}
Service serverService = dataAccess.getService(serverId);
if (serverService == null) {
return;
}
User user = accessHelper.checkIfUserCanModify(request, clientService.getTeamId(), "delete a service ref");
dataAccess.deleteServiceRef(clientId, serverId);
Map<String, String> notes = new HashMap<>();
notes.put("uses", serverService.getServiceAbbr());
createAudit(clientId, user.getUsername(), Type.serviceRef, Operation.delete, notes);
notes = new HashMap<>();
notes.put("use_by", clientService.getServiceAbbr());
createAudit(serverId, user.getUsername(), Type.serviceRef, Operation.delete, notes);
}
private void createAudit(String serviceId, String requestor, Type type, Operation operation, Map<String, String> notes) {
Audit audit = new Audit();
audit.serviceId = serviceId;
audit.timePerformed = new Date();
audit.timeRequested = new Date();
audit.requestor = requestor;
audit.type = type;
audit.operation = operation;
audit.notes = gson.toJson(notes);
dataAccess.saveAudit(audit, " ");
}
}
| Minor Search Audit improvements | src/main/java/com/northernwall/hadrian/service/ServiceHandler.java | Minor Search Audit improvements | <ide><path>rc/main/java/com/northernwall/hadrian/service/ServiceHandler.java
<ide> import com.northernwall.hadrian.access.AccessHelper;
<ide> import com.northernwall.hadrian.db.DataAccess;
<ide> import com.northernwall.hadrian.domain.Audit;
<del>import com.northernwall.hadrian.domain.Config;
<ide> import com.northernwall.hadrian.domain.CustomFunction;
<ide> import com.northernwall.hadrian.domain.DataStore;
<ide> import com.northernwall.hadrian.domain.GitMode;
<ide> } catch (ParseException ex) {
<ide> Calendar now = Calendar.getInstance();
<ide> now.add(Calendar.DATE, -15);
<add> now.clear(Calendar.HOUR);
<add> now.clear(Calendar.MINUTE);
<add> now.clear(Calendar.SECOND);
<ide> startDate = now.getTime();
<ide> }
<ide> Date endDate = null;
<ide> } catch (ParseException ex) {
<ide> Calendar now = Calendar.getInstance();
<ide> now.add(Calendar.DATE, 1);
<add> now.clear(Calendar.HOUR);
<add> now.clear(Calendar.MINUTE);
<add> now.clear(Calendar.SECOND);
<ide> endDate = now.getTime();
<ide> }
<add> logger.info("Audit search from {} to {} on service {}", startDate.toString(), endDate.toString(), id);
<ide> auditData.audits = dataAccess.getAudit(id, startDate, endDate);
<ide> Collections.sort(auditData.audits);
<ide> |
|
Java | mit | error: pathspec 'TemplateMethod/Java/Main.java' did not match any file(s) known to git
| 86db4ea0a578e17225e0a2d82eeff1749d1537fc | 1 | wrymax/design-pattern-examples | // 检测汽车质量的抽象模板类
abstract class AbstractQualityChecker {
/* 一组抽象方法,让子类重写 */
// 检测启动
abstract void startup();
// 检车加速
abstract void speedup();
// 检测制动
abstract void brake();
// 检测停止
abstract void stop();
// 控制检测流程,声明为final,防止子类重写
public final void checkQuality() {
startup();
speedup();
brake();
stop();
System.out.println("--- 检测完成!---\n");
}
}
// 实现1. 保时捷911的质量检测
class QualityChecker911 extends AbstractQualityChecker {
void startup() {
System.out.println("检测保时捷911的启动性能...");
}
void speedup() {
System.out.println("检测保时捷911的加速性能...");
}
void brake() {
System.out.println("检测保时捷911的制动性能...");
}
void stop() {
System.out.println("检测保时捷911的停止性能...");
}
}
// 实现2. 保时捷Cayma的质量检测
class QualityCheckerCayma extends AbstractQualityChecker {
void startup() {
System.out.println("检测保时捷Cayma的启动性能...");
}
void speedup() {
System.out.println("检测保时捷Cayma的加速性能...");
}
void brake() {
System.out.println("检测保时捷Cayma的制动性能...");
}
void stop() {
System.out.println("检测保时捷Cayma的停止性能...");
}
}
public class Main {
public static void main(String[] args) {
// 911 checker
QualityChecker911 checker911 = new QualityChecker911();
// Cayma checker
QualityCheckerCayma checkerCayma = new QualityCheckerCayma();
checker911.checkQuality();
checkerCayma.checkQuality();
}
}
| TemplateMethod/Java/Main.java | add TemplateMethod pattern
| TemplateMethod/Java/Main.java | add TemplateMethod pattern | <ide><path>emplateMethod/Java/Main.java
<add>// 检测汽车质量的抽象模板类
<add>abstract class AbstractQualityChecker {
<add> /* 一组抽象方法,让子类重写 */
<add> // 检测启动
<add> abstract void startup();
<add> // 检车加速
<add> abstract void speedup();
<add> // 检测制动
<add> abstract void brake();
<add> // 检测停止
<add> abstract void stop();
<add>
<add> // 控制检测流程,声明为final,防止子类重写
<add> public final void checkQuality() {
<add> startup();
<add> speedup();
<add> brake();
<add> stop();
<add> System.out.println("--- 检测完成!---\n");
<add> }
<add>}
<add>
<add>// 实现1. 保时捷911的质量检测
<add>class QualityChecker911 extends AbstractQualityChecker {
<add> void startup() {
<add> System.out.println("检测保时捷911的启动性能...");
<add> }
<add> void speedup() {
<add> System.out.println("检测保时捷911的加速性能...");
<add> }
<add> void brake() {
<add> System.out.println("检测保时捷911的制动性能...");
<add> }
<add> void stop() {
<add> System.out.println("检测保时捷911的停止性能...");
<add> }
<add>}
<add>
<add>// 实现2. 保时捷Cayma的质量检测
<add>class QualityCheckerCayma extends AbstractQualityChecker {
<add> void startup() {
<add> System.out.println("检测保时捷Cayma的启动性能...");
<add> }
<add> void speedup() {
<add> System.out.println("检测保时捷Cayma的加速性能...");
<add> }
<add> void brake() {
<add> System.out.println("检测保时捷Cayma的制动性能...");
<add> }
<add> void stop() {
<add> System.out.println("检测保时捷Cayma的停止性能...");
<add> }
<add>}
<add>
<add>public class Main {
<add> public static void main(String[] args) {
<add> // 911 checker
<add> QualityChecker911 checker911 = new QualityChecker911();
<add> // Cayma checker
<add> QualityCheckerCayma checkerCayma = new QualityCheckerCayma();
<add>
<add> checker911.checkQuality();
<add> checkerCayma.checkQuality();
<add> }
<add>} |
|
Java | apache-2.0 | 17f4aa050db1c35650adedbdb5f1729a8bc7d624 | 0 | Xyanid/bindableFX | /*
* Copyright 2015 - 2016 Xyanid
*
* 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 de.saxsys.bindablefx;
import javafx.beans.WeakListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Optional;
/**
* This class represents the basic binding class, it simply hold the {@link ObjectProperty} and a {@link ChangeListener}, which will be invoked each time the
* observedProperty is changed. Every time the {@link #observedProperty} is changed the class extending from this class will be informed and can react to the
* new state of the observedProperty according to its own needs.
*
* @author xyanid on 30.03.2016.
*/
//TODO maybe caching of events that happened during creation of the instance in a sub class need to be cached so they are not lost and
//TODO invoked when the sub class activates the listener ?
public abstract class BaseBinding<TPropertyValue> extends ReferenceQueue implements ChangeListener<TPropertyValue>, WeakListener {
//region Fields
/**
* Determines the {@link ObjectProperty} which is watched by this binding.
*/
@Nullable
private WeakReference<ObjectProperty<TPropertyValue>> observedProperty;
//endregion
// region Getter
/**
* Returns the current value of the {@link #observedProperty}.
*
* @return {@link Optional#empty()} if the {@link #observedProperty} is null or an {@link Optional} of the current value of the {@link #observedProperty}.
*/
public Optional<TPropertyValue> getCurrentObservedValue() {
if (observedProperty == null) {
return Optional.empty();
}
ObjectProperty<TPropertyValue> property = observedProperty.get();
if (property != null) {
return Optional.ofNullable(property.get());
} else {
return Optional.empty();
}
}
// endregion
// region Package Private
/**
* Removes this binding as the listener from the {@link #observedProperty}, invokes a call to {@link #changed(ObservableValue, Object, Object)} with the oldValue and then
* sets the {@link #observedProperty} to null.
*/
void destroyObservedProperty() {
if (observedProperty != null) {
ObjectProperty<TPropertyValue> property = observedProperty.get();
if (property != null) {
property.removeListener(this);
changed(property, property.get(), null);
}
observedProperty = null;
}
}
/**
* Sets the {@link #observedProperty} and adds the this binding as the listener.
*
* @param observedProperty the {@link ObjectProperty} which will be used as the {@link #observedProperty}
*/
void createObservedProperty(@NotNull final ObjectProperty<TPropertyValue> observedProperty) {
// set the property that is being observe and invoke a change so that the implementation can bind the property correctly
this.observedProperty = new WeakReference<>(observedProperty);
observedProperty.addListener(this);
changed(observedProperty, null, observedProperty.get());
}
// endregion
// region Public
/**
* Removes this binding as the listener from the {@link #observedProperty}, invokes a call to {@link #changed(ObservableValue, Object, Object)} with the oldValue and then
* sets the {@link #observedProperty} to null. After the call, this {@link BaseBinding} will not longer work and the {@link #observedProperty} needs to be reset using
* {@link #createObservedProperty(ObjectProperty)}.
*/
public void dispose() {
destroyObservedProperty();
}
// endregion
// region Implement WeakListener
/**
* Returns true if the {@link #observedProperty} is no longer set.
*
* @return true if the {@link #observedProperty} is no longer set, otherwise false.
*/
public boolean wasGarbageCollected() {
return observedProperty != null && observedProperty.get() == null;
}
// endregion
} | src/main/java/de/saxsys/bindablefx/BaseBinding.java | /*
* Copyright 2015 - 2016 Xyanid
*
* 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 de.saxsys.bindablefx;
import com.sun.istack.internal.Nullable;
import javafx.beans.WeakListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Optional;
/**
* This class represents the basic binding class, it simply hold the {@link ObjectProperty} and a {@link ChangeListener}, which will be invoked each time the
* observedProperty is changed. Every time the {@link #observedProperty} is changed the class extending from this class will be informed and can react to the
* new state of the observedProperty according to its own needs.
*
* @author xyanid on 30.03.2016.
*/
//TODO maybe caching of events that happened during creation of the instance in a sub class need to be cached so they are not lost and
//TODO invoked when the sub class activates the listener ?
public abstract class BaseBinding<TPropertyValue> extends ReferenceQueue implements ChangeListener<TPropertyValue>, WeakListener {
//region Fields
/**
* Determines the {@link ObjectProperty} which is watched by this binding.
*/
@Nullable
private WeakReference<ObjectProperty<TPropertyValue>> observedProperty;
//endregion
// region Getter
/**
* Returns the current value of the {@link #observedProperty}.
*
* @return {@link Optional#empty()} if the {@link #observedProperty} is null or an {@link Optional} of the current value of the {@link #observedProperty}.
*/
public Optional<TPropertyValue> getCurrentObservedValue() {
if (observedProperty == null) {
return Optional.empty();
}
ObjectProperty<TPropertyValue> property = observedProperty.get();
if (property != null) {
return Optional.ofNullable(property.get());
} else {
return Optional.empty();
}
}
// endregion
// region Package Private
/**
* Removes this binding as the listener from the {@link #observedProperty}, invokes a call to {@link #changed(ObservableValue, Object, Object)} with the oldValue and then
* sets the {@link #observedProperty} to null.
*/
void destroyObservedProperty() {
if (observedProperty != null) {
ObjectProperty<TPropertyValue> property = observedProperty.get();
if (property != null) {
property.removeListener(this);
changed(property, property.get(), null);
}
observedProperty = null;
}
}
/**
* Sets the {@link #observedProperty} and adds the this binding as the listener.
*
* @param observedProperty the {@link ObjectProperty} which will be used as the {@link #observedProperty}
*/
void createObservedProperty(@NotNull final ObjectProperty<TPropertyValue> observedProperty) {
// set the property that is being observe and invoke a change so that the implementation can bind the property correctly
this.observedProperty = new WeakReference<>(observedProperty);
observedProperty.addListener(this);
changed(observedProperty, null, observedProperty.get());
}
// endregion
// region Public
/**
* Removes this binding as the listener from the {@link #observedProperty}, invokes a call to {@link #changed(ObservableValue, Object, Object)} with the oldValue and then
* sets the {@link #observedProperty} to null. After the call, this {@link BaseBinding} will not longer work and the {@link #observedProperty} needs to be reset using
* {@link #createObservedProperty(ObjectProperty)}.
*/
public void dispose() {
destroyObservedProperty();
}
// endregion
// region Implement WeakListener
/**
* Returns true if the {@link #observedProperty} is no longer set.
*
* @return true if the {@link #observedProperty} is no longer set, otherwise false.
*/
public boolean wasGarbageCollected() {
return observedProperty != null && observedProperty.get() == null;
}
// endregion
} | - removed wrong package in base binding
| src/main/java/de/saxsys/bindablefx/BaseBinding.java | - removed wrong package in base binding | <ide><path>rc/main/java/de/saxsys/bindablefx/BaseBinding.java
<ide>
<ide> package de.saxsys.bindablefx;
<ide>
<del>import com.sun.istack.internal.Nullable;
<ide> import javafx.beans.WeakListener;
<ide> import javafx.beans.property.ObjectProperty;
<ide> import javafx.beans.value.ChangeListener;
<ide> import javafx.beans.value.ObservableValue;
<ide> import org.jetbrains.annotations.NotNull;
<add>import org.jetbrains.annotations.Nullable;
<ide>
<ide> import java.lang.ref.ReferenceQueue;
<ide> import java.lang.ref.WeakReference; |
|
Java | apache-2.0 | 62e2898e5501c78480d742041c39cb719a5032e4 | 0 | qos-ch/reload4j,qos-ch/reload4j,smathieu/librarian_sample_repo_java,MuShiiii/log4j,prmsheriff/log4j,sreekanthpulagam/log4j,prmsheriff/log4j,MuShiiii/log4j,prmsheriff/log4j,smathieu/librarian_sample_repo_java,sreekanthpulagam/log4j,qos-ch/reload4j,prmsheriff/log4j,sreekanthpulagam/log4j,sreekanthpulagam/log4j,prmsheriff/log4j,MuShiiii/log4j,MuShiiii/log4j,MuShiiii/log4j,sreekanthpulagam/log4j | /*
* Copyright 1999,2004 The Apache Software 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.apache.log4j.concurrent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.OptionConverter;
// Contibutors: Jens Uwe Pipka <[email protected]>
// Ben Sandee
/**
* FileAppender appends log events to a file.
*
* <p>Support for <code>java.io.Writer</code> and console appending
* has been deprecated and then removed. See the replacement
* solutions: {@link WriterAppender} and {@link ConsoleAppender}.
*
* @author Ceki Gülcü
* */
public class FileAppender extends WriterAppender {
public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
/**
* Controls whether to append to or truncate an existing file.
* The default value for this variable is
* <code>true</code>, meaning that by default a <code>FileAppender</code> will
* append to an existing file and not truncate it.
*
* <p>This option is meaningful only if the FileAppender opens the file.
*/
protected boolean fileAppend = true;
/**
The name of the log file. */
protected String fileName = null;
/**
Do we do bufferedIO? */
protected boolean bufferedIO = true;
/**
The size of the IO buffer. Default is 8K. */
protected int bufferSize = DEFAULT_BUFFER_SIZE;
/**
The default constructor does not do anything.
*/
public FileAppender() {
}
/**
Instantiate a <code>FileAppender</code> and open the file
designated by <code>filename</code>. The opened filename will
become the output destination for this appender.
<p>If the <code>append</code> parameter is true, the file will be
appended to. Otherwise, the file designated by
<code>filename</code> will be truncated before being opened.
<p>If the <code>bufferedIO</code> parameter is <code>true</code>,
then buffered IO will be used to write to the output file.
*/
public FileAppender(
Layout layout, String filename, boolean append, boolean bufferedIO,
int bufferSize) throws IOException {
setLayout(layout);
this.setFile(filename, append, bufferedIO, bufferSize);
activateOptions();
}
/**
Instantiate a FileAppender and open the file designated by
<code>filename</code>. The opened filename will become the output
destination for this appender.
<p>If the <code>append</code> parameter is true, the file will be
appended to. Otherwise, the file designated by
<code>filename</code> will be truncated before being opened.
*/
public FileAppender(Layout layout, String filename, boolean append)
throws IOException {
this(layout, filename, append, false, DEFAULT_BUFFER_SIZE);
}
/**
Instantiate a FileAppender and open the file designated by
<code>filename</code>. The opened filename will become the output
destination for this appender.
<p>The file will be appended to. */
public FileAppender(Layout layout, String filename) throws IOException {
this(layout, filename, true);
activateOptions();
}
/**
The <b>File</b> property takes a string value which should be the
name of the file to append to.
<p><font color="#DD0044"><b>Note that the special values
"System.out" or "System.err" are no longer honored.</b></font>
<p>Note: Actual opening of the file is made when {@link
#activateOptions} is called, not when the options are set. */
public void setFile(String file) {
// Trim spaces from both ends. The users probably does not want
// trailing spaces in file names.
String val = file.trim();
fileName = OptionConverter.stripDuplicateBackslashes(val);
}
/**
Returns the value of the <b>Append</b> option.
*/
public boolean getAppend() {
return fileAppend;
}
/** Returns the value of the <b>File</b> option. */
public String getFile() {
return fileName;
}
/**
If the value of <b>File</b> is not <code>null</code>, then {@link
#setFile} is called with the values of <b>File</b> and
<b>Append</b> properties.
@since 0.8.1 */
public void activateOptions() {
if (fileName != null) {
try {
setFile(fileName, fileAppend, bufferedIO, bufferSize);
super.activateOptions();
} catch (java.io.IOException e) {
getLogger().error(
"setFile(" + fileName + "," + fileAppend + ") call failed.", e);
}
} else {
getLogger().error("File option not set for appender [{}].", name);
getLogger().warn("Are you using FileAppender instead of ConsoleAppender?");
}
}
/**
* Closes the previously opened file.
*
* @deprecated Use the super class' {@link #closeWriter} method instead.
*/
protected void closeFile() {
closeWriter();
}
/**
Get the value of the <b>BufferedIO</b> option.
<p>BufferedIO will significantly increase performance on heavily
loaded systems.
*/
public boolean getBufferedIO() {
return this.bufferedIO;
}
/**
Get the size of the IO buffer.
*/
public int getBufferSize() {
return this.bufferSize;
}
/**
The <b>Append</b> option takes a boolean value. It is set to
<code>true</code> by default. If true, then <code>File</code>
will be opened in append mode by {@link #setFile setFile} (see
above). Otherwise, {@link #setFile setFile} will open
<code>File</code> in truncate mode.
<p>Note: Actual opening of the file is made when {@link
#activateOptions} is called, not when the options are set.
*/
public void setAppend(boolean flag) {
fileAppend = flag;
}
/**
The <b>BufferedIO</b> option takes a boolean value. It is set to
<code>false</code> by default. If true, then <code>File</code>
will be opened and the resulting {@link java.io.Writer} wrapped
around a {@link BufferedWriter}.
BufferedIO will significantly increase performance on heavily
loaded systems.
*/
public void setBufferedIO(boolean bufferedIO) {
this.bufferedIO = bufferedIO;
}
/**
Set the size of the IO buffer.
*/
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
/**
<p>Sets and <i>opens</i> the file where the log output will
go. The specified file must be writable.
<p>If there was already an opened file, then the previous file
is closed first.
<p><b>Do not use this method directly. To configure a FileAppender
or one of its subclasses, set its properties one by one and then
call activateOptions.</b>
@param filename The path to the log file.
@param append If true will append to fileName. Otherwise will
truncate fileName.
@param bufferedIO
@param bufferSize
@throws IOException
*/
public void setFile(
String filename, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
getLogger().debug("setFile called: {}, {}", filename, append ? Boolean.TRUE : Boolean.FALSE);
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.fileName = filename;
this.bufferSize = bufferSize;
FileOutputStream ostream = createOutputStream();
Writer writer = createWriter(ostream);
if (bufferedIO) {
writer = new BufferedWriter(writer, bufferSize);
}
setWriter(writer);
getLogger().debug("setFile ended");
}
protected FileOutputStream createOutputStream()
throws IOException
{
try {
//
// attempt to create file
//
return new FileOutputStream(fileName, fileAppend);
} catch(FileNotFoundException ex) {
//
// if parent directory does not exist then
// attempt to create it and try to create file
// see bug 9150
//
File parentDir = new File(new File(fileName).getParent());
if (!parentDir.exists() && parentDir.mkdirs()) {
return new FileOutputStream(fileName, fileAppend);
} else {
throw ex;
}
}
}
}
| src/java/org/apache/log4j/concurrent/FileAppender.java | /*
* Copyright 1999,2004 The Apache Software 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.apache.log4j.concurrent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.OptionConverter;
// Contibutors: Jens Uwe Pipka <[email protected]>
// Ben Sandee
/**
* FileAppender appends log events to a file.
*
* <p>Support for <code>java.io.Writer</code> and console appending
* has been deprecated and then removed. See the replacement
* solutions: {@link WriterAppender} and {@link ConsoleAppender}.
*
* @author Ceki Gülcü
* */
public class FileAppender extends WriterAppender {
public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;
/**
* Controls whether to append to or truncate an existing file.
* The default value for this variable is
* <code>true</code>, meaning that by default a <code>FileAppender</code> will
* append to an existing file and not truncate it.
*
* <p>This option is meaningful only if the FileAppender opens the file.
*/
protected boolean fileAppend = true;
/**
The name of the log file. */
protected String fileName = null;
/**
Do we do bufferedIO? */
protected boolean bufferedIO = true;
/**
The size of the IO buffer. Default is 8K. */
protected int bufferSize = DEFAULT_BUFFER_SIZE;
/**
The default constructor does not do anything.
*/
public FileAppender() {
}
/**
Instantiate a <code>FileAppender</code> and open the file
designated by <code>filename</code>. The opened filename will
become the output destination for this appender.
<p>If the <code>append</code> parameter is true, the file will be
appended to. Otherwise, the file designated by
<code>filename</code> will be truncated before being opened.
<p>If the <code>bufferedIO</code> parameter is <code>true</code>,
then buffered IO will be used to write to the output file.
*/
public FileAppender(
Layout layout, String filename, boolean append, boolean bufferedIO,
int bufferSize) throws IOException {
setLayout(layout);
this.setFile(filename, append, bufferedIO, bufferSize);
activateOptions();
}
/**
Instantiate a FileAppender and open the file designated by
<code>filename</code>. The opened filename will become the output
destination for this appender.
<p>If the <code>append</code> parameter is true, the file will be
appended to. Otherwise, the file designated by
<code>filename</code> will be truncated before being opened.
*/
public FileAppender(Layout layout, String filename, boolean append)
throws IOException {
this(layout, filename, append, false, DEFAULT_BUFFER_SIZE);
}
/**
Instantiate a FileAppender and open the file designated by
<code>filename</code>. The opened filename will become the output
destination for this appender.
<p>The file will be appended to. */
public FileAppender(Layout layout, String filename) throws IOException {
this(layout, filename, true);
activateOptions();
}
/**
The <b>File</b> property takes a string value which should be the
name of the file to append to.
<p><font color="#DD0044"><b>Note that the special values
"System.out" or "System.err" are no longer honored.</b></font>
<p>Note: Actual opening of the file is made when {@link
#activateOptions} is called, not when the options are set. */
public void setFile(String file) {
// Trim spaces from both ends. The users probably does not want
// trailing spaces in file names.
String val = file.trim();
fileName = OptionConverter.stripDuplicateBackslashes(val);
}
/**
Returns the value of the <b>Append</b> option.
*/
public boolean getAppend() {
return fileAppend;
}
/** Returns the value of the <b>File</b> option. */
public String getFile() {
return fileName;
}
/**
If the value of <b>File</b> is not <code>null</code>, then {@link
#setFile} is called with the values of <b>File</b> and
<b>Append</b> properties.
@since 0.8.1 */
public void activateOptions() {
if (fileName != null) {
try {
setFile(fileName, fileAppend, bufferedIO, bufferSize);
super.activateOptions();
} catch (java.io.IOException e) {
getLogger().error(
"setFile(" + fileName + "," + fileAppend + ") call failed.", e);
}
} else {
getLogger().error("File option not set for appender [{}].", name);
getLogger().warn("Are you using FileAppender instead of ConsoleAppender?");
}
}
/**
* Closes the previously opened file.
*
* @deprecated Use the super class' {@link #closeWriter} method instead.
*/
protected void closeFile() {
closeWriter();
}
/**
Get the value of the <b>BufferedIO</b> option.
<p>BufferedIO will significantly increase performance on heavily
loaded systems.
*/
public boolean getBufferedIO() {
return this.bufferedIO;
}
/**
Get the size of the IO buffer.
*/
public int getBufferSize() {
return this.bufferSize;
}
/**
The <b>Append</b> option takes a boolean value. It is set to
<code>true</code> by default. If true, then <code>File</code>
will be opened in append mode by {@link #setFile setFile} (see
above). Otherwise, {@link #setFile setFile} will open
<code>File</code> in truncate mode.
<p>Note: Actual opening of the file is made when {@link
#activateOptions} is called, not when the options are set.
*/
public void setAppend(boolean flag) {
fileAppend = flag;
}
/**
The <b>BufferedIO</b> option takes a boolean value. It is set to
<code>false</code> by default. If true, then <code>File</code>
will be opened and the resulting {@link java.io.Writer} wrapped
around a {@link BufferedWriter}.
BufferedIO will significantly increase performance on heavily
loaded systems.
*/
public void setBufferedIO(boolean bufferedIO) {
this.bufferedIO = bufferedIO;
}
/**
Set the size of the IO buffer.
*/
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
/**
<p>Sets and <i>opens</i> the file where the log output will
go. The specified file must be writable.
<p>If there was already an opened file, then the previous file
is closed first.
<p><b>Do not use this method directly. To configure a FileAppender
or one of its subclasses, set its properties one by one and then
call activateOptions.</b>
@param filename The path to the log file.
@param append If true will append to fileName. Otherwise will
truncate fileName.
@param bufferedIO
@param bufferSize
@throws IOException
*/
public void setFile(
String filename, boolean append, boolean bufferedIO, int bufferSize)
throws IOException {
getLogger().debug("setFile called: {}, {}", filename, Boolean.valueOf(append));
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.fileName = filename;
this.bufferSize = bufferSize;
FileOutputStream ostream = createOutputStream();
Writer writer = createWriter(ostream);
if (bufferedIO) {
writer = new BufferedWriter(writer, bufferSize);
}
setWriter(writer);
getLogger().debug("setFile ended");
}
protected FileOutputStream createOutputStream()
throws IOException
{
try {
//
// attempt to create file
//
return new FileOutputStream(fileName, fileAppend);
} catch(FileNotFoundException ex) {
//
// if parent directory does not exist then
// attempt to create it and try to create file
// see bug 9150
//
File parentDir = new File(new File(fileName).getParent());
if (!parentDir.exists() && parentDir.mkdirs()) {
return new FileOutputStream(fileName, fileAppend);
} else {
throw ex;
}
}
}
}
| Bug 19004: Remove use of JDK 1.4 method Boolean.valueOf(boolean)
git-svn-id: a7be136288eb2cd985a15786d66ec039c800a993@502386 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/log4j/concurrent/FileAppender.java | Bug 19004: Remove use of JDK 1.4 method Boolean.valueOf(boolean) | <ide><path>rc/java/org/apache/log4j/concurrent/FileAppender.java
<ide> public void setFile(
<ide> String filename, boolean append, boolean bufferedIO, int bufferSize)
<ide> throws IOException {
<del> getLogger().debug("setFile called: {}, {}", filename, Boolean.valueOf(append));
<add> getLogger().debug("setFile called: {}, {}", filename, append ? Boolean.TRUE : Boolean.FALSE);
<ide>
<ide> this.fileAppend = append;
<ide> this.bufferedIO = bufferedIO; |
|
Java | apache-2.0 | 4c69bd0cfe28db393495a7a504aa22e41147c81d | 0 | DorsetProject/dorset-framework,DorsetProject/dorset_framework,davidpatrone/dorset-framework | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* 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 edu.jhuapl.dorset.record;
import java.util.Date;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.Response;
import edu.jhuapl.dorset.agent.Agent;
/**
* A record of handling a request
*/
public class Record {
private Date timestamp;
private long routeTime;
private long agentTime;
private String requestText;
private String[] agentNames;
private String selectedAgentName;
private String responseText;
/**
* Default zero argument constructor to support usage as bean
*
* For bean usage only
*/
public Record() {
}
/**
* Record of handling a request
* @param request Request object
*/
public Record(Request request) {
timestamp = new Date();
requestText = request.getText();
routeTime = 0;
agentTime = 0;
agentNames = new String[0];
selectedAgentName = "";
responseText = "";
}
/**
* Set the text of the request
*
* For bean usage only
*
* @param text request text
*/
public void setRequestText(String text) {
requestText = text;
}
/**
* Get the text of the request
* @return text of the request
*/
public String getRequestText() {
return requestText;
}
/**
* Set the length of time that the routing took
*
* Use System.nanoTime() to get the start and stop times.
*
* @param start The time the routing started
* @param stop The time the routing stopped
*/
public void setRouteTime(long start, long stop) {
routeTime = stop - start;
}
/**
* Set the length of time that the routing took
* @param time The length of time for the routing
*/
public void setRouteTime(long time) {
routeTime = time;
}
/**
* Get the length of time that the routing took
* @return time in nano-seconds
*/
public long getRouteTime() {
return routeTime;
}
/**
* Set the length of time the agent took to handle the request
*
* Use System.nanoTime() to get the start and stop times.
*
* @param start The time the agent started
* @param stop The time the agent stopped
*/
public void setAgentTime(long start, long stop) {
agentTime = stop - start;
}
/**
* Set the length of time that the agent took
* @param time The length of time for agent processing
*/
public void setAgentTime(long time) {
agentTime = time;
}
/**
* Get the length of time the agent took to handle the request
* @return time in nano-seconds
*/
public long getAgentTime() {
return agentTime;
}
/**
* Set the agents the router nominated to handle the request
* @param agents Array of Agent objects
*/
public void setAgents(Agent[] agents) {
agentNames = new String[agents.length];
for (int i = 0; i < agents.length; i++) {
agentNames[i] = agents[i].getName();
}
}
/**
* Set the agent that handled the request
* @param agent Agent object
*/
public void setSelectedAgent(Agent agent) {
selectedAgentName = agent.getName();
}
/**
* Set the agent name that handled the request
* @param name the name of the agent
*/
public void setSelectedAgentName(String name) {
selectedAgentName = name;
}
/**
* Get the agent that handled the request
* @return name of the agent
*/
public String getSelectedAgentName() {
return selectedAgentName;
}
/**
* Set the text of the response
* @param response Response object
*/
public void setResponse(Response response) {
responseText = response.getText();
}
/**
* Set the text of the response
* @param text Text of the response
*/
public void setResponseText(String text) {
responseText = text;
}
/**
* Get the text of the response
* @return text of the response
*/
public String getResponseText() {
return responseText;
}
/**
* Set the timestamp of the record
*
* For bean usage only
*
* @param timestamp time of the request being received
*/
public void setTimestamp(Date ts) {
timestamp = ts;
}
/**
* Get the timestamp of the record
* @return Date of the record
*/
public Date getTimestamp() {
return timestamp;
}
}
| core/src/main/java/edu/jhuapl/dorset/record/Record.java | /*
* Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
* 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 edu.jhuapl.dorset.record;
import java.util.Date;
import edu.jhuapl.dorset.Request;
import edu.jhuapl.dorset.Response;
import edu.jhuapl.dorset.agent.Agent;
/**
* A record of handling a request
*/
public class Record {
private Date timestamp;
private long routeTime;
private long agentTime;
private String requestText;
private String[] agentNames;
private String selectedAgentName;
private String responseText;
/**
* Default zero argument constructor to support usage as bean
*
* For bean usage only
*/
public Record() {
}
/**
* Record of handling a request
* @param request Request object
*/
public Record(Request request) {
timestamp = new Date();
requestText = request.getText();
routeTime = 0;
agentTime = 0;
agentNames = new String[0];
selectedAgentName = "";
responseText = "";
}
/**
* Set the text of the request
*
* For bean usage only
*
* @param text request text
*/
public void setRequestText(String text) {
requestText = text;
}
/**
* Get the text of the request
* @return text of the request
*/
public String getRequestText() {
return requestText;
}
/**
* Set the length of time that the routing took
*
* Use System.nanoTime() to get the start and stop times.
*
* @param start The time the routing started
* @param stop The time the routing stopped
*/
public void setRouteTime(long start, long stop) {
routeTime = stop - start;
}
/**
* Set the length of time that the routing took
* @param time The length of time for the routing
*/
public void setRouteTime(long time) {
routeTime = time;
}
/**
* Get the length of time that the routing took
* @return time in nano-seconds
*/
public long getRouteTime() {
return routeTime;
}
/**
* Set the length of time the agent took to handle the request
*
* Use System.nanoTime() to get the start and stop times.
*
* @param start The time the agent started
* @param stop The time the agent stopped
*/
public void setAgentTime(long start, long stop) {
agentTime = stop - start;
}
/**
* Set the length of time that the agent took
* @param time The length of time for agent processing
*/
public void setAgentTime(long time) {
agentTime = time;
}
/**
* Get the length of time the agent took to handle the request
* @return time in nano-seconds
*/
public long getAgentTime() {
return agentTime;
}
/**
* Set the agents the router nominated to handle the request
* @param agents Array of Agent objects
*/
public void setAgents(Agent[] agents) {
agentNames = new String[agents.length];
for (int i = 0; i < agents.length; i++) {
agentNames[i] = agents[i].getName();
}
}
/**
* Set the agent that handled the request
* @param agent Agent object
*/
public void setSelectedAgent(Agent agent) {
selectedAgentName = agent.getName();
}
/**
* Set the agent name that handled the request
* @param name the name of the agent
*/
public void setSelectedAgent(String name) {
selectedAgentName = name;
}
/**
* Get the agent that handled the request
* @return name of the agent
*/
public String getSelectedAgentName() {
return selectedAgentName;
}
/**
* Set the text of the response
* @param response Response object
*/
public void setResponse(Response response) {
responseText = response.getText();
}
/**
* Set the text of the response
* @param text Text of the response
*/
public void setResponseText(String text) {
responseText = text;
}
/**
* Get the text of the response
* @return text of the response
*/
public String getResponseText() {
return responseText;
}
/**
* Set the timestamp of the record
*
* For bean usage only
*
* @param timestamp time of the request being received
*/
public void setTimestamp(Date ts) {
timestamp = ts;
}
/**
* Get the timestamp of the record
* @return Date of the record
*/
public Date getTimestamp() {
return timestamp;
}
}
| fixed typo of method name
| core/src/main/java/edu/jhuapl/dorset/record/Record.java | fixed typo of method name | <ide><path>ore/src/main/java/edu/jhuapl/dorset/record/Record.java
<ide> * Set the agent name that handled the request
<ide> * @param name the name of the agent
<ide> */
<del> public void setSelectedAgent(String name) {
<add> public void setSelectedAgentName(String name) {
<ide> selectedAgentName = name;
<ide> }
<ide> |
|
Java | apache-2.0 | 574d437d13718495f778a1d39d550b80032344ea | 0 | MarcMeszaros/papyrus | /**
* Copyright 2011 Marc Meszaros
*
* 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 ca.marcmeszaros.papyrus.browser;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import ca.marcmeszaros.papyrus.AlarmReceiver;
import ca.marcmeszaros.papyrus.R;
import ca.marcmeszaros.papyrus.Settings;
import ca.marcmeszaros.papyrus.database.AddBook;
import ca.marcmeszaros.papyrus.database.AddLibrary;
import ca.marcmeszaros.papyrus.database.Book;
import ca.marcmeszaros.papyrus.database.Loan;
import ca.marcmeszaros.papyrus.database.sqlite.DBHelper;
public class BooksBrowser extends ListActivity implements
OnItemSelectedListener, OnItemClickListener, OnItemLongClickListener,
DialogInterface.OnClickListener, OnDateSetListener {
private static final String TAG = "BooksBrowser";
// class variables
private long selectedBookID;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
private Intent loanData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_browser);
// set listeners for list clicks and long clicks to this activity
getListView().setOnItemClickListener(this);
getListView().setOnItemLongClickListener(this);
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// run a query on the DB and get a Cursor (aka result)
Cursor result = db.query(DBHelper.BOOK_TABLE_NAME, null, null, null, null, null, DBHelper.BOOK_FIELD_TITLE);
startManagingCursor(result);
// create our custom adapter with our result and
// set the adapter to the ListView to display the books
setListAdapter(new BookAdapter(this, result));
// get the library spinner
Spinner spinner = (Spinner) findViewById(R.id.BooksBrowser_spinner_library);
// get all the libraries
Cursor library = db.query(DBHelper.LIBRARY_TABLE_NAME, null, null,
null, null, null, DBHelper.LIBRARY_FIELD_NAME);
startManagingCursor(library);
// close the db connection
db.close();
// specify what fields to map to what views
String[] from = { DBHelper.LIBRARY_FIELD_NAME };
int[] to = { android.R.id.text1 };
// create a cursor adapter and set it to the list
SimpleCursorAdapter adp = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, library, from, to);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(this);
}
/**
* Handles a Click from an item in the list.
*/
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// set the item id to a class variable
this.selectedBookID = id;
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { DBHelper.BOOK_FIELD_ISBN10,
DBHelper.BOOK_FIELD_ISBN13, DBHelper.BOOK_FIELD_TITLE,
DBHelper.BOOK_FIELD_AUTHOR, DBHelper.BOOK_FIELD_PUBLISHER,
DBHelper.BOOK_FIELD_QUANTITY, DBHelper.BOOK_FIELD_ID,
DBHelper.BOOK_FIELD_LIBRARY_ID };
// delete the entry in the database
Cursor bookCursor = db.query(DBHelper.BOOK_TABLE_NAME, columns,
DBHelper.BOOK_FIELD_ID + "=" + selectedBookID, null, null,
null, null);
startManagingCursor(bookCursor);
bookCursor.moveToFirst();
Book book = new Book(bookCursor.getString(0), bookCursor.getString(1),
bookCursor.getString(2), bookCursor.getString(3));
book.setPublisher(bookCursor.getString(4));
book.setQuantity(bookCursor.getInt(5));
book.setBookID(bookCursor.getInt(6));
book.setLibraryID(bookCursor.getInt(7));
Intent intent = new Intent(this, BookDetails.class);
intent.putExtra("book", book);
db.close();
startActivity(intent);
}
/**
* Handles a LongClick from an item in the list (create a dialog).
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int position, final long id) {
// set the item id to a class variable
this.selectedBookID = id;
// setup the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.BooksBrowser_LongClickDialog_title));
// create the dialog items
final CharSequence[] items = {
// getString(R.string.BooksBrowser_LongClickDialog_edit),
getString(R.string.BooksBrowser_LongClickDialog_delete),
getString(R.string.BooksBrowser_LongClickDialog_lendTo) };
// set the items and the click listener
builder.setItems(items, this);
// create the dialog box and show it
AlertDialog alert = builder.create();
alert.show();
return true;
}
/**
* Handles a click event from the LongClickDialog.
*/
@Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
// edit
// case 0:
// Toast.makeText(getApplicationContext(),
// "Feature not implemented yet.", Toast.LENGTH_SHORT).show();
// break;
// delete
case 0:
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// delete the entry in the database
db.delete(DBHelper.BOOK_TABLE_NAME, DBHelper.BOOK_FIELD_ID + "=" + selectedBookID, null);
db.close();
// requery the database
((BookAdapter) getListAdapter()).getCursor().requery();
// tell the list we have new data
((BookAdapter) getListAdapter()).notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
getString(R.string.BooksBrowser_toast_bookDeleted),
Toast.LENGTH_SHORT).show();
break;
// lend book to someone
case 1:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1001);
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
// LOAN A BOOK
case 1001:
// there are sufficient copies of the book to lend
if (canLoanBook()) {
loanData = data;
// set default due date
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis()+ (1000 * 60 * 60 * 24 * 14));
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Box
showDialog(DATE_DIALOG_ID);
}
// there are no more copies left in the library
else {
Toast.makeText(this, getString(R.string.BooksBrowser_toast_allCopiesLentOut), Toast.LENGTH_LONG).show();
}
break;
}
} else {
// gracefully handle failure
// Log.w(DEBUG_TAG, "resultWarning: activity result not ok");
}
}
/**
* Creates the menu when the "menu" button is pressed.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.books_browser, menu);
return true;
}
/**
* Handles the event when an option is selected from the option menu.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.BooksBrowser_menu_addBook:
SQLiteDatabase db = new DBHelper(getApplicationContext())
.getReadableDatabase();
Cursor result = db.query(DBHelper.LIBRARY_TABLE_NAME, null, null,
null, null, null, null, null);
startManagingCursor(result);
if (result.getCount() > 0) {
startActivity(new Intent(this, AddBook.class));
} else {
startActivity(new Intent(this, AddLibrary.class));
}
db.close();
break;
case R.id.BooksBrowser_Settings_menu:
startActivity(new Intent(this, Settings.class));
break;
}
return false;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long id) {
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
Log.i(TAG, "Item select ID: " + id);
String selection = DBHelper.BOOK_TABLE_NAME + "."
+ DBHelper.BOOK_FIELD_LIBRARY_ID + "=" + id;
// run a query on the DB and get a Cursor (aka result)
Cursor result = db.query(DBHelper.BOOK_TABLE_NAME, null, selection,
null, null, null, DBHelper.BOOK_FIELD_TITLE);
startManagingCursor(result);
setListAdapter(new BookAdapter(this, result));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
/**
* Date Picking
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
}
return null;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
}
/**
* the callback received when the user "sets" the date in the dialog
*/
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
loanBook();
}
};
/**
* Executes the query to loan out the book
*/
private void loanBook() {
// set the due date
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth, mDay);
// gets the uri path to the user selected
Uri user = loanData.getData();
// gets the user id
String id = user.getLastPathSegment();
// get a reference to the database
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// prepare the query
ContentValues values = new ContentValues();
values.put(DBHelper.LOAN_FIELD_BOOK_ID, selectedBookID);
values.put(DBHelper.LOAN_FIELD_CONTACT_ID, id);
values.put(DBHelper.LOAN_FIELD_LEND_DATE, System.currentTimeMillis());
values.put(DBHelper.LOAN_FIELD_DUE_DATE, c.getTimeInMillis());
// insert the entry in the database
db.insert(DBHelper.LOAN_TABLE_NAME, "", values);
// loan the new id
String tables = DBHelper.LOAN_TABLE_NAME;
String selection = DBHelper.LOAN_TABLE_NAME + "."
+ DBHelper.LOAN_FIELD_BOOK_ID + " = " + selectedBookID
+ " AND " +
DBHelper.LOAN_TABLE_NAME + "." + DBHelper.LOAN_FIELD_CONTACT_ID + " = " + id;
String[] columns = {
DBHelper.LOAN_FIELD_ID
};
Cursor cursor = db.query(tables, columns, selection, null, null, null, DBHelper.LOAN_FIELD_ID+" DESC");
cursor.moveToFirst();
int loanID = cursor.getInt(0);
cursor.close();
// close the db
db.close();
//Book book = new Book(isbn10, title, author);
Loan loan = new Loan(
loanID,
values.getAsInteger(DBHelper.LOAN_FIELD_BOOK_ID),
values.getAsInteger(DBHelper.LOAN_FIELD_CONTACT_ID),
values.getAsLong(DBHelper.LOAN_FIELD_LEND_DATE),
values.getAsLong(DBHelper.LOAN_FIELD_DUE_DATE)
);
// get an alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// create the intent for the alarm
Intent intent = new Intent(this, AlarmReceiver.class);
// put the loan object into the alarm receiver
intent.putExtra("loan", loan);
// create the pendingIntent to run when the alarm goes off and be handled by a receiver
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set the repeating alarm
am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);
Toast.makeText(this, getString(R.string.BooksBrowser_toast_loanSuccessful), Toast.LENGTH_LONG).show();
}
/**
* Checks that there are enough books to loan out this copy
*/
public boolean canLoanBook() {
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
// Get the quantity of books stored
String tables = DBHelper.BOOK_TABLE_NAME;
String selection = DBHelper.BOOK_TABLE_NAME + "."
+ DBHelper.BOOK_FIELD_ID + " = " + selectedBookID;
String[] columns = { DBHelper.BOOK_FIELD_QUANTITY };
// store result of query
Cursor result = db.query(tables, columns, selection, null, null, null,
null);
result.moveToFirst();
int qty = result.getShort(0);
tables = DBHelper.LOAN_TABLE_NAME;
selection = DBHelper.LOAN_TABLE_NAME + "."
+ DBHelper.LOAN_FIELD_BOOK_ID + " = " + selectedBookID;
columns[0] = DBHelper.LOAN_FIELD_ID;
// store result of query
result = db.query(tables, columns, selection, null, null, null, null);
// determine the number of books on loan
int onLoan = 0;
while (result.moveToNext())
onLoan++;
if (onLoan < qty)
return true;
return false;
}
}
| papyrus/src/ca/marcmeszaros/papyrus/browser/BooksBrowser.java | /**
* Copyright 2011 Marc Meszaros
*
* 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 ca.marcmeszaros.papyrus.browser;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import ca.marcmeszaros.papyrus.AlarmReceiver;
import ca.marcmeszaros.papyrus.R;
import ca.marcmeszaros.papyrus.Settings;
import ca.marcmeszaros.papyrus.database.AddBook;
import ca.marcmeszaros.papyrus.database.AddLibrary;
import ca.marcmeszaros.papyrus.database.Book;
import ca.marcmeszaros.papyrus.database.Loan;
import ca.marcmeszaros.papyrus.database.sqlite.DBHelper;
public class BooksBrowser extends ListActivity implements
OnItemSelectedListener, OnItemClickListener, OnItemLongClickListener,
DialogInterface.OnClickListener, OnDateSetListener {
private static final String TAG = "BooksBrowser";
// class variables
private long selectedBookID;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
private Intent loanData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books_browser);
// set listeners for list clicks and long clicks to this activity
getListView().setOnItemClickListener(this);
getListView().setOnItemLongClickListener(this);
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// run a query on the DB and get a Cursor (aka result)
Cursor result = db.query(DBHelper.BOOK_TABLE_NAME, null, null, null, null, null, DBHelper.BOOK_FIELD_TITLE);
startManagingCursor(result);
// create our custom adapter with our result and
// set the adapter to the ListView to display the books
setListAdapter(new BookAdapter(this, result));
// get the library spinner
Spinner spinner = (Spinner) findViewById(R.id.BooksBrowser_spinner_library);
// get all the libraries
Cursor library = db.query(DBHelper.LIBRARY_TABLE_NAME, null, null,
null, null, null, DBHelper.LIBRARY_FIELD_NAME);
startManagingCursor(library);
// specify what fields to map to what views
String[] from = { DBHelper.LIBRARY_FIELD_NAME };
int[] to = { android.R.id.text1 };
// create a cursor adapter and set it to the list
SimpleCursorAdapter adp = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, library, from, to);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(this);
}
/**
* Handles a Click from an item in the list.
*/
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// set the item id to a class variable
this.selectedBookID = id;
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { DBHelper.BOOK_FIELD_ISBN10,
DBHelper.BOOK_FIELD_ISBN13, DBHelper.BOOK_FIELD_TITLE,
DBHelper.BOOK_FIELD_AUTHOR, DBHelper.BOOK_FIELD_PUBLISHER,
DBHelper.BOOK_FIELD_QUANTITY, DBHelper.BOOK_FIELD_ID,
DBHelper.BOOK_FIELD_LIBRARY_ID };
// delete the entry in the database
Cursor bookCursor = db.query(DBHelper.BOOK_TABLE_NAME, columns,
DBHelper.BOOK_FIELD_ID + "=" + selectedBookID, null, null,
null, null);
startManagingCursor(bookCursor);
bookCursor.moveToFirst();
Book book = new Book(bookCursor.getString(0), bookCursor.getString(1),
bookCursor.getString(2), bookCursor.getString(3));
book.setPublisher(bookCursor.getString(4));
book.setQuantity(bookCursor.getInt(5));
book.setBookID(bookCursor.getInt(6));
book.setLibraryID(bookCursor.getInt(7));
Intent intent = new Intent(this, BookDetails.class);
intent.putExtra("book", book);
db.close();
startActivity(intent);
}
/**
* Handles a LongClick from an item in the list (create a dialog).
*/
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int position, final long id) {
// set the item id to a class variable
this.selectedBookID = id;
// setup the dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.BooksBrowser_LongClickDialog_title));
// create the dialog items
final CharSequence[] items = {
// getString(R.string.BooksBrowser_LongClickDialog_edit),
getString(R.string.BooksBrowser_LongClickDialog_delete),
getString(R.string.BooksBrowser_LongClickDialog_lendTo) };
// set the items and the click listener
builder.setItems(items, this);
// create the dialog box and show it
AlertDialog alert = builder.create();
alert.show();
return true;
}
/**
* Handles a click event from the LongClickDialog.
*/
@Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
// edit
// case 0:
// Toast.makeText(getApplicationContext(),
// "Feature not implemented yet.", Toast.LENGTH_SHORT).show();
// break;
// delete
case 0:
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// delete the entry in the database
db.delete(DBHelper.BOOK_TABLE_NAME, DBHelper.BOOK_FIELD_ID + "=" + selectedBookID, null);
db.close();
// requery the database
((BookAdapter) getListAdapter()).getCursor().requery();
// tell the list we have new data
((BookAdapter) getListAdapter()).notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
getString(R.string.BooksBrowser_toast_bookDeleted),
Toast.LENGTH_SHORT).show();
break;
// lend book to someone
case 1:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1001);
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
// LOAN A BOOK
case 1001:
// there are sufficient copies of the book to lend
if (canLoanBook()) {
loanData = data;
// set default due date
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis()+ (1000 * 60 * 60 * 24 * 14));
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// Launch Date Picker Box
showDialog(DATE_DIALOG_ID);
}
// there are no more copies left in the library
else {
Toast.makeText(this, getString(R.string.BooksBrowser_toast_allCopiesLentOut), Toast.LENGTH_LONG).show();
}
break;
}
} else {
// gracefully handle failure
// Log.w(DEBUG_TAG, "resultWarning: activity result not ok");
}
}
/**
* Creates the menu when the "menu" button is pressed.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.books_browser, menu);
return true;
}
/**
* Handles the event when an option is selected from the option menu.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.BooksBrowser_menu_addBook:
SQLiteDatabase db = new DBHelper(getApplicationContext())
.getReadableDatabase();
Cursor result = db.query(DBHelper.LIBRARY_TABLE_NAME, null, null,
null, null, null, null, null);
startManagingCursor(result);
if (result.getCount() > 0) {
startActivity(new Intent(this, AddBook.class));
} else {
startActivity(new Intent(this, AddLibrary.class));
}
db.close();
break;
case R.id.BooksBrowser_Settings_menu:
startActivity(new Intent(this, Settings.class));
break;
}
return false;
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long id) {
// create an instance of the db helper class
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
Log.i(TAG, "Item select ID: " + id);
String selection = DBHelper.BOOK_TABLE_NAME + "."
+ DBHelper.BOOK_FIELD_LIBRARY_ID + "=" + id;
// run a query on the DB and get a Cursor (aka result)
Cursor result = db.query(DBHelper.BOOK_TABLE_NAME, null, selection,
null, null, null, DBHelper.BOOK_FIELD_TITLE);
startManagingCursor(result);
setListAdapter(new BookAdapter(this, result));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
/**
* Date Picking
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
mDay);
}
return null;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
}
/**
* the callback received when the user "sets" the date in the dialog
*/
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
loanBook();
}
};
/**
* Executes the query to loan out the book
*/
private void loanBook() {
// set the due date
Calendar c = Calendar.getInstance();
c.set(mYear, mMonth, mDay);
// gets the uri path to the user selected
Uri user = loanData.getData();
// gets the user id
String id = user.getLastPathSegment();
// get a reference to the database
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
// prepare the query
ContentValues values = new ContentValues();
values.put(DBHelper.LOAN_FIELD_BOOK_ID, selectedBookID);
values.put(DBHelper.LOAN_FIELD_CONTACT_ID, id);
values.put(DBHelper.LOAN_FIELD_LEND_DATE, System.currentTimeMillis());
values.put(DBHelper.LOAN_FIELD_DUE_DATE, c.getTimeInMillis());
// insert the entry in the database
db.insert(DBHelper.LOAN_TABLE_NAME, "", values);
// loan the new id
String tables = DBHelper.LOAN_TABLE_NAME;
String selection = DBHelper.LOAN_TABLE_NAME + "."
+ DBHelper.LOAN_FIELD_BOOK_ID + " = " + selectedBookID
+ " AND " +
DBHelper.LOAN_TABLE_NAME + "." + DBHelper.LOAN_FIELD_CONTACT_ID + " = " + id;
String[] columns = {
DBHelper.LOAN_FIELD_ID
};
Cursor cursor = db.query(tables, columns, selection, null, null, null, DBHelper.LOAN_FIELD_ID+" DESC");
cursor.moveToFirst();
int loanID = cursor.getInt(0);
cursor.close();
// close the db
db.close();
//Book book = new Book(isbn10, title, author);
Loan loan = new Loan(
loanID,
values.getAsInteger(DBHelper.LOAN_FIELD_BOOK_ID),
values.getAsInteger(DBHelper.LOAN_FIELD_CONTACT_ID),
values.getAsLong(DBHelper.LOAN_FIELD_LEND_DATE),
values.getAsLong(DBHelper.LOAN_FIELD_DUE_DATE)
);
// get an alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// create the intent for the alarm
Intent intent = new Intent(this, AlarmReceiver.class);
// put the loan object into the alarm receiver
intent.putExtra("loan", loan);
// create the pendingIntent to run when the alarm goes off and be handled by a receiver
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set the repeating alarm
am.set(AlarmManager.RTC, c.getTimeInMillis(), pendingIntent);
Toast.makeText(this, getString(R.string.BooksBrowser_toast_loanSuccessful), Toast.LENGTH_LONG).show();
}
/**
* Checks that there are enough books to loan out this copy
*/
public boolean canLoanBook() {
DBHelper helper = new DBHelper(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
// Get the quantity of books stored
String tables = DBHelper.BOOK_TABLE_NAME;
String selection = DBHelper.BOOK_TABLE_NAME + "."
+ DBHelper.BOOK_FIELD_ID + " = " + selectedBookID;
String[] columns = { DBHelper.BOOK_FIELD_QUANTITY };
// store result of query
Cursor result = db.query(tables, columns, selection, null, null, null,
null);
result.moveToFirst();
int qty = result.getShort(0);
tables = DBHelper.LOAN_TABLE_NAME;
selection = DBHelper.LOAN_TABLE_NAME + "."
+ DBHelper.LOAN_FIELD_BOOK_ID + " = " + selectedBookID;
columns[0] = DBHelper.LOAN_FIELD_ID;
// store result of query
result = db.query(tables, columns, selection, null, null, null, null);
// determine the number of books on loan
int onLoan = 0;
while (result.moveToNext())
onLoan++;
if (onLoan < qty)
return true;
return false;
}
}
| closes a memory leak
| papyrus/src/ca/marcmeszaros/papyrus/browser/BooksBrowser.java | closes a memory leak | <ide><path>apyrus/src/ca/marcmeszaros/papyrus/browser/BooksBrowser.java
<ide> Cursor library = db.query(DBHelper.LIBRARY_TABLE_NAME, null, null,
<ide> null, null, null, DBHelper.LIBRARY_FIELD_NAME);
<ide> startManagingCursor(library);
<add>
<add> // close the db connection
<add> db.close();
<ide>
<ide> // specify what fields to map to what views
<ide> String[] from = { DBHelper.LIBRARY_FIELD_NAME };
<ide> startManagingCursor(result);
<ide>
<ide> setListAdapter(new BookAdapter(this, result));
<del>
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mpl-2.0 | b3b841cf1e9d2c3d186236b8fef2eac53996f37b | 0 | nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,nth10sd/funfuzz | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is jsfunfuzz.
*
* The Initial Developer of the Original Code is
* Jesse Ruderman.
* Portions created by the Initial Developer are Copyright (C) 2006-2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gary Kwong
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//"use strict";
var jsStrictMode = false;
/********************
* ENGINE DETECTION *
********************/
// jsfunfuzz is best run in a command-line shell. It can also run in
// a web browser, but you might have trouble reproducing bugs that way.
var ENGINE_UNKNOWN = 0;
var ENGINE_SPIDERMONKEY_TRUNK = 1; // also 1.9.1 and tracemonkey branch
var ENGINE_SPIDERMONKEY_MOZ_1_9_0 = 2;
var ENGINE_JAVASCRIPTCORE = 4;
var engine = ENGINE_UNKNOWN;
var jsshell = (typeof window == "undefined");
var dump;
var dumpln;
var printImportant;
if (jsshell) {
dumpln = print;
printImportant = function(s) { dumpln("***"); dumpln(s); }
if (typeof line2pc == "function") {
if (typeof snarf == "function")
engine = ENGINE_SPIDERMONKEY_TRUNK;
else if (typeof countHeap == "function")
engine = ENGINE_SPIDERMONKEY_MOZ_1_9_0
version(180); // 170: make "yield" and "let" work. 180: sane for..in.
options("anonfunfix");
} else if (typeof XPCNativeWrapper == "function") {
engine = ENGINE_SPIDERMONKEY_TRUNK;
} else if (typeof debug == "function") {
engine = ENGINE_JAVASCRIPTCORE;
}
} else {
if (navigator.userAgent.indexOf("WebKit") != -1) {
engine = ENGINE_JAVASCRIPTCORE;
// This worked in Safari 3.0, but it might not work in Safari 3.1.
dump = function(s) { console.log(s); }
} else if (navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("rv:1.9.0") != -1) {
engine = ENGINE_SPIDERMONKEY_MOZ_1_9_0;
} else if (navigator.userAgent.indexOf("Gecko") != -1) {
engine = ENGINE_SPIDERMONKEY_TRUNK;
} else if (typeof dump != "function") {
// In other browsers, jsfunfuzz does not know how to log anything.
dump = function() { };
}
dumpln = function(s) { dump(s + "\n"); }
printImportant = function(s) {
dumpln(s);
var p = document.createElement("pre");
p.appendChild(document.createTextNode(s));
document.body.appendChild(p);
}
}
if (typeof gc == "undefined")
gc = function(){};
var haveUsefulDis = engine == ENGINE_SPIDERMONKEY_TRUNK && typeof dis == "function" && typeof dis(function(){}) == "string";
var haveE4X = (typeof XML == "function");
if (haveE4X)
XML.ignoreComments = false; // to make uneval saner -- see bug 465908
function simpleSource(s)
{
function hexify(c)
{
var code = c.charCodeAt(0);
var hex = code.toString(16);
while (hex.length < 4)
hex = "0" + hex;
return "\\u" + hex;
}
if (typeof s == "string")
return "\"" + s.replace(/\\/g, "\\\\")
.replace(/\"/g, "\\\"")
.replace(/\0/g, "\\0")
.replace(/\n/g, "\\n")
.replace(/[^ -~]/g, hexify) // not space (32) through tilde (126)
+ "\"";
else
return "" + s; // hope this is right ;) should work for numbers.
}
var haveRealUneval = (typeof uneval == "function");
if (!haveRealUneval)
uneval = simpleSource;
if (engine == ENGINE_UNKNOWN)
printImportant("Targeting an unknown JavaScript engine!");
else if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0)
printImportant("Targeting SpiderMonkey / Gecko (Mozilla 1.9.0 branch).");
else if (engine == ENGINE_SPIDERMONKEY_TRUNK)
printImportant("Targeting SpiderMonkey / Gecko (trunk).");
else if (engine == ENGINE_JAVASCRIPTCORE)
printImportant("Targeting JavaScriptCore / WebKit.");
function printAndStop(s)
{
printImportant(s)
if (jsshell) {
print("jsfunfuzz stopping due to above error!"); // Magic string that jsunhappy.py looks for
quit();
}
}
function errorToString(e)
{
try {
return ("" + e);
} catch (e2) {
return "Can't toString the error!!";
}
}
var jitEnabled = (engine == ENGINE_SPIDERMONKEY_TRUNK) && jsshell && options().indexOf("jit") != -1;
/***********************
* AVOIDING KNOWN BUGS *
***********************/
function whatToTestSpidermonkeyTrunk(code)
{
return {
allowParse: true,
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true,
// Exclude things here if decompiling returns something bogus that won't compile.
checkRecompiling: true
&& !( code.match( /\..*\@.*(this|null|false|true).*\:\:/ )) // avoid bug 381197
&& !( code.match( /arguments.*\:\:/ )) // avoid bug 355506
&& !( code.match( /\:.*for.*\(.*var.*\)/ )) // avoid bug 352921
&& !( code.match( /\:.*for.*\(.*let.*\)/ )) // avoid bug 352921
&& !( code.match( /for.*let.*\).*function/ )) // avoid bug 352735 (more rebracing stuff)
&& !( code.match( /for.*\(.*\(.*in.*;.*;.*\)/ )) // avoid bug 353255
&& !( code.match( /const.*arguments/ )) // avoid bug 355480
&& !( code.match( /var.*arguments/ )) // avoid bug 355480
&& !( code.match( /let.*arguments/ )) // avoid bug 355480
&& !( code.match( /let/ )) // avoid bug 462309 :( :( :(
&& !( code.match( /function.*\:.*arguments/ )) // avoid bug 496985
&& !( code.match( /\{.*\:.*\}.*\=.*/ ) && code.indexOf("const") != -1) // avoid bug 492010
&& !( code.match( /\{.*\:.*\}.*\=.*/ ) && code.indexOf("function") != -1) // avoid bug 492010
&& !( code.match( /if.*function/ ) && code.indexOf("const") != -1) // avoid bug 355980 *errors*
&& !( code.match( /switch.*default.*xml.*namespace/ )) // avoid bug 566616
&& !( code.match( /\#.*=/ )) // avoid bug 568734
,
// Exclude things here if decompiling returns something incorrect or non-canonical, but that will compile.
checkForMismatch: false // bug 539819
&& !( code.match( /const.*if/ )) // avoid bug 352985
&& !( code.match( /if.*const/ )) // avoid bug 352985
&& !( code.match( /with.*try.*function/ )) // avoid bug 418285
&& !( code.match( /if.*try.*function/ )) // avoid bug 418285
&& !( code.match( /\?.*\?/ )) // avoid bug 475895
&& !( code.match( /if.*function/ )) // avoid bug 355980 *changes*
&& !( code.match( /\=.*\:\:/ )) // avoid bug 504957
&& (code.indexOf("-0") == -1) // constant folding isn't perfect
&& (code.indexOf("-1") == -1) // constant folding isn't perfect
&& (code.indexOf("default") == -1) // avoid bug 355509
&& (code.indexOf("delete") == -1) // avoid bug 352027, which won't be fixed for a while :(
&& (code.indexOf("const") == -1) // avoid bug 352985 and bug 355480 :(
&& (code.indexOf("&&") == -1) // ignore bug 461226 with a hatchet
&& (code.indexOf("||") == -1) // ignore bug 461226 with a hatchet
// avoid bug 352085: keep operators that coerce to number (or integer)
// at constant-folding time (?) away from strings
&&
(
(code.indexOf("\"") == -1 && code.indexOf("\'") == -1)
||
(
(code.indexOf("%") == -1)
&& (code.indexOf("/") == -1)
&& (code.indexOf("*") == -1)
&& (code.indexOf("-") == -1)
&& (code.indexOf(">>") == -1)
&& (code.indexOf("<<") == -1)
)
)
,
// Exclude things here if the decompilation doesn't match what the function actually does
checkDisassembly: true
&& !( code.match( /\@.*\:\:/ )) // avoid bug 381197 harder than above
&& !( code.match( /for.*in.*for.*in/ )) // avoid bug 475985
,
checkForExtraParens: true
&& !code.match( /\(.*for.*\(.*in.*\).*\)/ ) // ignore bug 381213, and unfortunately anything with genexps
&& !code.match( /if.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /while.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /\?.*\=/) // ignore bug 475893
,
allowExec: unlikelyToHang(code)
&& code.indexOf("<>") == -1 // avoid bug 334628, hopefully
&& (jsshell || code.indexOf("nogeckoex") == -1)
,
allowIter: true,
checkUneval: false // bug 539819
// exclusions won't be perfect, since functions can return things they don't
// appear to contain, e.g. with "return x;"
&& (code.indexOf("<") == -1 || code.indexOf(".") == -1) // avoid bug 379525
&& (code.indexOf("<>") == -1) // avoid bug 334628
};
}
function whatToTestSpidermonkey190Branch(code)
{
return {
allowParse: true,
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true,
// Exclude things here if decompiling returns something bogus that won't compile.
checkRecompiling: true
&& (code.indexOf("#") == -1) // avoid bug 367731 (branch)
&& !( code.match( /\..*\@.*(this|null|false|true).*\:\:/ )) // avoid bug 381197 (branch)
&& !( code.match( /arguments.*\:\:/ )) // avoid bug 355506 (branch)
&& !( code.match( /\:.*for.*\(.*var.*\)/ )) // avoid bug 352921 (branch)
&& !( code.match( /\:.*for.*\(.*let.*\)/ )) // avoid bug 352921 (branch)
&& !( code.match( /for.*let.*\).*function/ )) // avoid bug 352735 (branch) (more rebracing stuff)
&& !( code.match( /for.*\(.*\(.*in.*;.*;.*\)/ )) // avoid bug 353255 (branch)
&& !( code.match( /while.*for.*in/ )) // avoid bug 381963 (branch)
&& !( code.match( /const.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /var.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /let.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /let/ )) // avoid bug 462309 (branch) :( :( :(
,
// Exclude things here if decompiling returns something incorrect or non-canonical, but that will compile.
checkForMismatch: true
&& !( code.match( /const.*if/ )) // avoid bug 352985 (branch)
&& !( code.match( /if.*const/ )) // avoid bug 352985 (branch)
&& !( code.match( /\{.*\}.*=.*\[.*=.*\]/ )) // avoid bug 376558 (branch)
&& !( code.match( /\[.*\].*=.*\[.*=.*\]/ )) // avoid bug 376558 (branch)
&& !( code.match( /with.*try.*function/ )) // avoid bug 418285 (branch)
&& !( code.match( /if.*try.*function/ )) // avoid bug 418285 (branch)
&& !( code.match( /\[.*\].*\=.*\[.*\,/ )) // avoid bug 355051 (branch)
&& !( code.match( /\{.*\}.*\=.*\[.*\,/ )) // avoid bug 355051 (branch) where empty {} becomes []
&& !( code.match( /\?.*\?/ )) // avoid bug 475895 (branch)
&& !( code.match( /for.*;.*;/ )) // avoid wackiness related to bug 461269 (branch)
&& !( code.match( /new.*\?/ )) // avoid bug 476210 (branch)
&& !( code.match( /\=.*\:\:/ )) // avoid bug 504957 (branch)
&& (code.indexOf("-0") == -1) // constant folding isn't perfect
&& (code.indexOf("-1") == -1) // constant folding isn't perfect
&& (code.indexOf("default") == -1) // avoid bug 355509 (branch)
&& (code.indexOf("delete") == -1) // avoid bug 352027 (branch), which won't be fixed for a while :(
&& (code.indexOf("const") == -1) // avoid bug 352985 (branch), bug 353020 (branch), and bug 355480 (branch) :(
&& (code.indexOf("&&") == -1) // ignore bug 461226 (branch) with a hatchet
&& (code.indexOf("||") == -1) // ignore bug 461226 (branch) with a hatchet
// avoid bug 352085 (branch): keep operators that coerce to number (or integer)
// at constant-folding time (?) away from strings
&&
(
(code.indexOf("\"") == -1 && code.indexOf("\'") == -1)
||
(
(code.indexOf("%") == -1)
&& (code.indexOf("/") == -1)
&& (code.indexOf("*") == -1)
&& (code.indexOf("-") == -1)
&& (code.indexOf(">>") == -1)
&& (code.indexOf("<<") == -1)
)
)
,
// Exclude things here if the decompilation doesn't match what the function actually does
checkDisassembly: true
&& !( code.match( /\@.*\:\:/ )) // avoid bug 381197 (branch) harder than above
&& !( code.match( /\(.*\?.*\:.*\).*\(.*\)/ )) // avoid bug 475899 (branch)
&& !( code.match( /for.*in.*for.*in/ )) // avoid bug 475985 (branch)
,
checkForExtraParens: true
&& !code.match( /\(.*for.*\(.*in.*\).*\)/ ) // ignore bug 381213 (branch), and unfortunately anything with genexps
&& !code.match( /if.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /while.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /\?.*\=/) // ignore bug 475893 (branch)
,
allowExec: unlikelyToHang(code)
&& code.indexOf("finally") == -1 // avoid bug 380018 (branch) and bug 381107 (branch) :(
&& code.indexOf("<>") == -1 // avoid bug 334628 (branch), hopefully
&& (jsshell || code.indexOf("nogeckoex") == -1)
&& !( code.match( /function.*::.*=/ )) // avoid ????
,
allowIter: true,
checkUneval: true
// exclusions won't be perfect, since functions can return things they don't
// appear to contain, e.g. with "return x;"
&& (code.indexOf("<") == -1 || code.indexOf(".") == -1) // avoid bug 379525 (branch)
&& (code.indexOf("<>") == -1) // avoid bug 334628 (branch)
};
}
function whatToTestJavaScriptCore(code)
{
return {
allowParse: true,
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true
,
checkForExtraParens: false, // ?
allowExec: unlikelyToHang(code)
,
allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
checkUneval: false // JavaScriptCore does not support |uneval|
};
}
function whatToTestGeneric(code)
{
return {
allowParse: true,
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true,
checkForExtraParens: false, // most js engines don't try to guarantee lack of extra parens
allowExec: unlikelyToHang(code),
allowIter: ("Iterator" in this),
checkUneval: haveRealUneval
};
}
var whatToTest;
if (engine == ENGINE_SPIDERMONKEY_TRUNK)
whatToTest = whatToTestSpidermonkeyTrunk;
else if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0)
whatToTest = whatToTestSpidermonkey190Branch;
else if (engine == ENGINE_JAVASCRIPTCORE)
whatToTest = whatToTestJavaScriptCore;
else
whatToTest = whatToTestGeneric;
function unlikelyToHang(code)
{
// Things that are likely to hang in all JavaScript engines
return true
&& code.indexOf("infloop") == -1
&& !( code.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
&& !( code.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
&& !( code.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
&& !( code.match( /for.*for.*for/ )) // nested for loops (including for..in, array comprehensions, etc) can take a while
&& !( code.match( /for.*for.*gc/ ))
;
}
/*************************
* DRIVING & BASIC TESTS *
*************************/
var allMakers = [];
function totallyRandom(d, b) {
d = d + (rnd(5) - 2); // can increase!!
return (rndElt(allMakers))(d, b);
}
function init()
{
for (var f in this)
if (f.indexOf("make") == 0 && typeof this[f] == "function")
allMakers.push(this[f]);
}
function testEachMaker()
{
for each (var f in allMakers) {
dumpln("");
dumpln(f.name);
dumpln("==========");
dumpln("");
for (var i = 0; i < 100; ++i) {
try {
dumpln(f(8, ["A", "B"]));
} catch(e) {
dumpln("");
dumpln(uneval(e));
dumpln(e.stack);
dumpln("");
}
}
dumpln("");
}
}
function start()
{
init();
count = 0;
if (jsshell) {
// If another script specified a "maxRunTime" argument, use it; otherwise, run forever
var MAX_TOTAL_TIME = (this.maxRunTime) || (Infinity);
var startTime = new Date();
do {
testOne();
var elapsed1 = new Date() - lastTime;
if (elapsed1 > 1000) {
print("That took " + elapsed1 + "ms!");
}
var lastTime = new Date();
} while(lastTime - startTime < MAX_TOTAL_TIME);
} else {
setTimeout(testStuffForAWhile, 200);
}
}
function testStuffForAWhile()
{
for (var j = 0; j < 100; ++j)
testOne();
if (count % 10000 < 100)
printImportant("Iterations: " + count);
setTimeout(testStuffForAWhile, 30);
}
function testOne()
{
var dumpEachSeed = false; // Can be set to true if makeStatement has side effects, such as crashing, so you have to reduce "the hard way".
++count;
// Split this string across two source strings to ensure that if a
// generated function manages to output the entire jsfunfuzz source,
// that output won't match the grep command.
var grepforme = "/*F";
grepforme += "RC*/"
// Sometimes it makes sense to start with simpler functions:
//var depth = (~~(count / 1000)) & 16;
var depth = 10;
if (dumpEachSeed) {
// More complicated, but results in a much shorter script, making SpiderMonkey happier.
var MTA = uneval(rnd.fuzzMT.export_mta());
var MTI = rnd.fuzzMT.export_mti();
if (MTA != rnd.lastDumpedMTA) {
dumpln(grepforme + "rnd.fuzzMT.import_mta(" + MTA + ");");
rnd.lastDumpedMTA = MTA;
}
dumpln(grepforme + "rnd.fuzzMT.import_mti(" + MTI + "); void (makeStatement(" + depth + "), ['x']);");
}
var code = makeStatement(depth, ["x"]);
// if (rnd(10) == 1) {
// var dp = "/*infloop-deParen*/" + rndElt(deParen(code));
// if (dp)
// code = dp;
// }
dumpln(grepforme + "count=" + count + "; tryItOut(" + uneval(code) + ");");
tryItOut(code);
}
function tryItOut(code)
{
var c; // a harmless variable for closure fun
// Accidentally leaving gczeal enabled for a long time would make jsfunfuzz really slow.
if ("gczeal" in this)
gczeal(0);
// SpiderMonkey shell does not schedule GC on its own. Help it not use too much memory.
if (count % 1000 == 0) {
dumpln("Paranoid GC (count=" + count + ")!");
realGC();
}
// regexps can't match across lines, so replace whitespace with spaces.
var wtt = whatToTest(code.replace(/\s/g, " "));
code = code.replace(/\/\*DUPTRY\d+\*\//, function(k) { var n = parseInt(k.substr(8), 10); dumpln(n); return strTimes("try{}catch(e){}", n); })
if (!wtt.allowParse)
return;
try {
Reflect.parse(code);
} catch(e) {
}
if (count % 20 == 1) {
if (wtt.allowExec) {
try {
print("Plain eval");
eval(code);
} catch(e) {
print(errorToString(e));
}
tryEnsureSanity();
}
return;
}
var f = tryCompiling(code, wtt.allowExec);
optionalTests(f, code, wtt);
if (f && wtt.allowDecompile) {
tryRoundTripStuff(f, code, wtt);
if (haveUsefulDis && wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkDisassembly)
checkRoundTripDisassembly(f, code, wtt);
}
if (f && wtt.allowExec) {
if (code.indexOf("\n") == -1 && code.indexOf("\r") == -1 && code.indexOf("\f") == -1 && code.indexOf("\0") == -1 && code.indexOf("\u2028") == -1 && code.indexOf("\u2029") == -1 && code.indexOf("<--") == -1 && code.indexOf("-->") == -1 && code.indexOf("//") == -1) {
if (code.indexOf("Error") == -1 // avoid bug 525518
&& code.indexOf("too_much_recursion") == -1 // recursion limits may differ (at least between execution modes). see bug 584594 (wontfix).
&& code.indexOf("getOwnPropertyNames") == -1 // Object.getOwnPropertyNames(this) contains "jitstats" and "tracemonkey" exist only with -j
&& code.indexOf("--") == -1 // avoid bug 584603
&& code.indexOf("++") == -1 // avoid bug 584603
&& code.indexOf("gc") == -1 // gc is noisy
&& code.indexOf(".(") == -1 // this e4x operator can get itself into infinite-recursion, and recursion limits are nondeterministic
&& code.indexOf("with") == -1 // avoid bug 593556
) {
// FCM cookie
var cookie1 = "/*F";
var cookie2 = "CM*/";
var nCode = code;
// Avoid compile-time errors because those are no fun.
// But leave some things out of function(){} because some bugs are only detectable at top-level, and
// pure jsfunfuzz doesn't test top-level at all.
// (This is a good reason to use compareJIT even if I'm not interested in finding JIT bugs!)
function failsToCompileInTry(code) {
// Why would this happen? One way is "let x, x"
try {
new Function(" try { " + code + " } catch(e) { }");
return false;
} catch(e) {
return true;
}
}
if (nCode.indexOf("return") != -1 || nCode.indexOf("yield") != -1 || nCode.indexOf("const") != -1 || failsToCompileInTry(nCode))
nCode = "(function(){" + nCode + "})()"
dumpln(cookie1 + cookie2 + " try { " + nCode + " } catch(e) { }");
}
}
}
var rv = null;
if (wtt.allowExec && f) {
rv = tryRunning(f, code);
tryEnsureSanity();
}
if (wtt.allowIter && rv && typeof rv == "object") {
tryIteration(rv);
tryEnsureSanity();
}
// "checkRecompiling && checkForMismatch" here to catch returned functions
if (wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkUneval && rv && typeof rv == "object") {
testUneval(rv);
}
if (verbose)
dumpln("Done trying out that function!");
dumpln("");
}
function tryCompiling(code, allowExec)
{
var c; // harmless local variable for closure fun
try {
// Try two methods of creating functions, just in case there are differences.
if (count % 2 == 0 && allowExec) {
if (verbose)
dumpln("About to compile, using eval hack.")
return eval("(function(){" + code + "});"); // Disadvantage: "}" can "escape", allowing code to *execute* that we only intended to compile. Hence the allowExec check.
}
else {
if (verbose)
dumpln("About to compile, using new Function.")
if (jsStrictMode)
code = "'use strict'; " + code; // ES5 10.1.1: new Function does not inherit strict mode
return new Function(code);
}
} catch(compileError) {
dumpln("Compiling threw: " + errorToString(compileError));
return null;
}
}
function tryRunning(f, code)
{
try {
if (verbose)
dumpln("About to run it!");
var rv = f();
if (verbose)
dumpln("It ran!");
return rv;
} catch(runError) {
if(verbose)
dumpln("Running threw! About to toString to error.");
var err = errorToString(runError);
dumpln("Running threw: " + err);
tryEnsureSanity();
// bug 465908 and other e4x uneval nonsense make this show lots of false positives
// checkErrorMessage(err, code);
return null;
}
}
// Store things now so we can restore sanity later.
var realEval = eval;
var realMath = Math;
var realFunction = Function;
var realGC = gc;
var realUneval = uneval;
var realToString = toString;
var realToSource = this.toSource; // "this." because it only exists in spidermonkey
function tryEnsureSanity()
{
try {
// The script might have turned on gczeal. Turn it back off right away to avoid slowness.
if ("gczeal" in this)
gczeal(0);
// At least one bug in the past has put exceptions in strange places. This also catches "eval getter" issues.
try { eval("") } catch(e) { dumpln("That really shouldn't have thrown: " + errorToString(e)); }
// Try to get rid of any fake 'unwatch' functions.
delete this.unwatch;
// Restore important stuff that might have been broken as soon as possible :)
if ('unwatch' in this) {
this.unwatch("eval")
this.unwatch("Function")
this.unwatch("gc")
this.unwatch("uneval")
this.unwatch("toSource")
this.unwatch("toString")
}
if ('__defineSetter__' in this) {
// The only way to get rid of getters/setters is to delete the property.
if (!jsStrictMode)
delete this.eval;
delete this.Math;
delete this.Function;
delete this.gc;
delete this.uneval;
delete this.toSource;
delete this.toString;
}
this.Math = realMath;
this.eval = realEval;
this.Function = realFunction;
this.gc = realGC;
this.uneval = realUneval;
this.toSource = realToSource;
this.toString = realToString;
} catch(e) {
printImportant("tryEnsureSanity failed: " + e);
}
// These can fail if the page creates a getter for "eval", for example.
if (!this.eval)
printImportant("WTF did my |eval| go?");
if (this.eval != realEval)
printImportant("WTF did my |eval| get replaced by?")
if (Function != realFunction)
printImportant("WTF did my |Function| get replaced by?")
}
function tryIteration(rv)
{
try {
if (!(Iterator(rv) === rv))
return; // not an iterator
}
catch(e) {
// Is it a bug that it's possible to end up here? Probably not!
dumpln("Error while trying to determine whether it's an iterator!");
dumpln("The error was: " + e);
return;
}
dumpln("It's an iterator!");
try {
var iterCount = 0;
var iterValue;
// To keep Safari-compatibility, don't use "let", "each", etc.
for /* each */ ( /* let */ iterValue in rv)
++iterCount;
dumpln("Iterating succeeded, iterCount == " + iterCount);
} catch (iterError) {
dumpln("Iterating threw!");
dumpln("Iterating threw: " + errorToString(iterError));
}
}
/***********************************
* WHOLE-FUNCTION DECOMPILER TESTS *
***********************************/
function tryRoundTripStuff(f, code, wtt)
{
if (verbose)
dumpln("About to do the 'toString' round-trip test");
// Functions are prettier with line breaks, so test toString before uneval.
checkRoundTripToString(f, code, wtt);
if (wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkForExtraParens) {
try {
testForExtraParens(f, code);
} catch(e) { /* bug 355667 is annoying here too */ }
}
if (haveRealUneval) {
if (verbose)
dumpln("About to do the 'uneval' round-trip test");
checkRoundTripUneval(f, code, wtt);
}
}
// Function round-trip with implicit toString
function checkRoundTripToString(f, code, wtt)
{
var fs, g;
try {
fs = "" + f;
} catch(e) { reportRoundTripIssue("Round-trip with implicit toString: can't toString", code, null, null, errorToString(e)); return; }
checkForCookies(fs);
if (wtt.checkRecompiling) {
try {
g = eval("(" + fs + ")");
var gs = "" + g;
if (wtt.checkForMismatch && fs != gs) {
reportRoundTripIssue("Round-trip with implicit toString", code, fs, gs, "mismatch");
wtt.checkForMismatch = false;
}
} catch(e) {
reportRoundTripIssue("Round-trip with implicit toString: error", code, fs, gs, errorToString(e));
}
}
}
// Function round-trip with uneval
function checkRoundTripUneval(f, code, wtt)
{
var g, uf, ug;
try {
uf = uneval(f);
} catch(e) { reportRoundTripIssue("Round-trip with uneval: can't uneval", code, null, null, errorToString(e)); return; }
checkForCookies(uf);
if (wtt.checkRecompiling) {
try {
g = eval("(" + uf + ")");
ug = uneval(g);
if (wtt.checkForMismatch && ug != uf) {
reportRoundTripIssue("Round-trip with uneval: mismatch", code, uf, ug, "mismatch");
wtt.checkForMismatch = false;
}
} catch(e) { reportRoundTripIssue("Round-trip with uneval: error", code, uf, ug, errorToString(e)); }
}
}
function checkForCookies(code)
{
// http://lxr.mozilla.org/seamonkey/source/js/src/jsopcode.c#1613
// These are things that shouldn't appear in decompilations.
if (code.indexOf("/*EXCEPTION") != -1
|| code.indexOf("/*RETSUB") != -1
|| code.indexOf("/*FORELEM") != -1
|| code.indexOf("/*WITH") != -1)
printAndStop(code)
}
function reportRoundTripIssue(issue, code, fs, gs, e)
{
if (e.indexOf("missing variable name") != -1) {
dumpln("Bug 355667 sure is annoying!");
return;
}
if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0 && e.indexOf("invalid object initializer") != -1) {
dumpln("Ignoring bug 452561 (branch).");
return;
}
if (e.indexOf("illegal XML character") != -1) {
dumpln("Ignoring bug 355674.");
return;
}
if (e.indexOf("illegal character") != -1) {
dumpln("Ignoring bug 566661.");
return;
}
if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0 && e.indexOf("missing ; after for-loop condition") != -1) {
dumpln("Looks like bug 460504 (branch).");
return;
}
if (fs && gs && fs.replace(/'/g, "\"") == gs.replace(/'/g, "\"")) {
dumpln("Ignoring quote mismatch (bug 346898 (wontfix)).");
return;
}
var message = issue + "\n\n" +
"Code: " + uneval(code) + "\n\n" +
"fs: " + fs + "\n\n" +
"gs: " + gs + "\n\n" +
"error: " + e;
printAndStop(message);
}
/*************************************************
* EXPRESSION DECOMPILATION & VALUE UNEVAL TESTS *
*************************************************/
function testUneval(o)
{
// If it happens to return an object, especially an array or hash,
// let's test uneval. Note that this is a different code path than decompiling
// an array literal within a function, although the two code paths often have
// similar bugs!
var uo, euo, ueuo;
try {
uo = uneval(o);
} catch(e) {
if (errorToString(e).indexOf("called on incompatible") != -1) {
dumpln("Ignoring bug 379528!".toUpperCase());
return;
}
else
throw e;
}
if (uo == "({})") {
// ?
return;
}
if (testUnevalString(uo)) {
// count=946; tryItOut("return (({ set x x (x) { yield /x/g } , x setter: ({}).hasOwnProperty }));");
uo = uo.replace(/\[native code\]/g, "");
if (uo.charAt(0) == "/")
return; // ignore bug 362582
try {
euo = eval(uo); // if this throws, something's wrong with uneval, probably
} catch(e) {
dumpln("The string returned by uneval failed to eval!");
dumpln("The string was: " + uo);
printAndStop(e);
return;
}
ueuo = uneval(euo);
if (ueuo != uo) {
printAndStop("Mismatch with uneval/eval on the function's return value! " + "\n" + uo + "\n" + ueuo);
}
} else {
dumpln("Skipping re-eval test");
}
}
function testUnevalString(uo)
{
var uowlb = uo.replace(/\n/g, " ").replace(/\r/g, " ");
return true
&& uo.indexOf("[native code]") == -1 // ignore bug 384756
&& (uo.indexOf("#") == -1) // ignore bug 328745 (ugh)
&& (uo.indexOf("{") == -1 || uo.indexOf(":") == -1) // ignore bug 379525 hard (ugh!)
&& uo.indexOf("NaN") == -1 // ignore bug 379521
&& uo.indexOf("Infinity") == -1 // ignore bug 379521
&& uo.indexOf(",]") == -1 // avoid bug 334628 / bug 379525?
&& uo.indexOf("[function") == -1 // avoid bug 380379?
&& uo.indexOf("[(function") == -1 // avoid bug 380379?
&& !uowlb.match(/new.*Error/) // ignore bug 380578
&& !uowlb.match(/<.*\/.*>.*<.*\/.*>/) // ignore bug 334628
&& !uowlb.match(/\\0\d/) // ignore bug 537849
;
}
function checkErrorMessage(err, code)
{
// Checking to make sure DVG is behaving (and not, say, playing with uninitialized memory)
if (engine == ENGINE_SPIDERMONKEY_TRUNK) {
checkErrorMessage2(err, "TypeError: ", " is not a function");
checkErrorMessage2(err, "TypeError: ", " is not a constructor");
checkErrorMessage2(err, "TypeError: ", " is undefined");
}
// These should probably be tested too:XML.ignoreComments
// XML filter is applied to non-XML value ...
// invalid 'instanceof' operand ...
// invalid 'in' operand ...
// missing argument 0 when calling function ...
// ... has invalid __iterator__ value ... (two of them!!)
}
function checkErrorMessage2(err, prefix, suffix)
{
var P = prefix.length;
var S = suffix.length;
if (err.substr(0, P) == prefix) {
if (err.substr(-S, S) == suffix) {
var dvg = err.substr(11, err.length - P - S);
print("Testing an expression in a recent error message: " + dvg);
// These error messages can involve decompilation of expressions (DVG),
// but in some situations they can just be uneval of a value. In those
// cases, we don't want to complain about known uneval bugs.
if (!testUnevalString(dvg)) {
print("Ignoring error message string because it looks like a known-bogus uneval");
return;
}
if (dvg == "") {
print("Ignoring E4X uneval bogosity");
// e.g. the error message from (<x/>.(false))()
// bug 465908, etc.
return;
}
try {
eval("(function() { return (" + dvg + "); })");
} catch(e) {
printAndStop("DVG has apparently failed us: " + e);
}
}
}
}
/**************************
* PARENTHESIZATION TESTS *
**************************/
// Returns an array of strings of length (code.length-2),
// each having one pair of matching parens removed.
// Assumes all parens in code are significant. This assumption fails
// for strings or regexps, but whatever.
function deParen(code)
{
// Get a list of locations of parens.
var parenPairs = []; // array of { left : int, right : int } (indices into code string)
var unmatched = []; // stack of indices into parenPairs
var i, c;
for (i = 0; i < code.length; ++i) {
c = code.charCodeAt(i);
if (c == 40) {
// left paren
unmatched.push(parenPairs.length);
parenPairs.push({ left: i });
} else if (c == 41) {
// right paren
if (unmatched.length == 0)
return []; // eep! unmatched rparen!
parenPairs[unmatched.pop()].right = i;
}
}
if (unmatched.length > 0)
return []; // eep! unmatched lparen!
var rs = [];
// Don't add spaces in place of the parens, because we don't
// want to detect things like (5).x as being unnecessary use
// of parens.
for (i = 0; i < parenPairs.length; ++i) {
var left = parenPairs[i].left, right = parenPairs[i].right;
rs.push(
code.substr(0, left)
+ code.substr(left + 1, right - (left + 1))
+ code.substr(right + 1)
);
}
return rs;
}
// print(uneval(deParen("for (i = 0; (false); ++i) { x(); }")));
// print(uneval(deParen("[]")));
function testForExtraParens(f, code)
{
code = code.replace(/\n/g, " ").replace(/\r/g, " "); // regexps can't match across lines
var uf = "" + f;
// numbers get more parens than they need
if (uf.match(/\(\d/)) return;
if (uf.indexOf("(<") != -1) return; // bug 381204
if (uf.indexOf(".(") != -1) return; // bug 381207
if (code.indexOf("new") != -1) return; // "new" is weird. what can i say?
if (code.indexOf("let") != -1) return; // reasonable to overparenthesize "let" (see expclo#c33)
if (code.match(/for.*in.*=/)) return; // bug 381213
if (code.match(/\:.*function/)) return; // why?
if (uf.indexOf("(function") != -1) return; // expression closures over-parenthesize
if (code.match(/for.*yield/)) return; // why?
if (uf.indexOf("= (yield") != -1) return;
if (uf.indexOf(":(yield") != -1) return;
if (uf.indexOf(": (yield") != -1) return;
if (uf.indexOf(", (yield") != -1) return;
if (uf.indexOf("[(yield") != -1) return;
if (uf.indexOf("yield") != -1) return; // i give up on yield
// Sanity check
var euf = eval("(" + uf + ")");
var ueuf = "" + euf;
if (ueuf != uf)
printAndStop("Shouldn't the earlier round-trip test have caught this?");
var dps = deParen(uf);
// skip the first, which is the function's formal params.
for (var i = 1; i < dps.length; ++i) {
var uf2 = dps[i];
try {
var euf2 = eval("(" + uf2 + ")");
} catch(e) { /* print("The latter did not compile. That's fine."); */ continue; }
var ueuf2 = "" + euf2
if (ueuf2 == ueuf) {
print(uf);
print(" vs ");
print(uf2);
print("Both decompile as:");
print(ueuf);
printAndStop("Unexpected match!!! Extra parens!?");
}
}
}
/*********************************
* SPIDERMONKEY DISASSEMBLY TEST *
*********************************/
// Finds decompiler bugs and bytecode inefficiencies by complaining when a round trip
// through the decompiler changes the bytecode.
function checkRoundTripDisassembly(f, code, wtt)
{
if (code.indexOf("[@") != -1 || code.indexOf("*::") != -1 || code.indexOf("::*") != -1 || code.match(/\[.*\*/)) {
dumpln("checkRoundTripDisassembly: ignoring bug 475859");
return;
}
if (code.indexOf("=") != -1 && code.indexOf("const") != -1) {
dumpln("checkRoundTripDisassembly: ignoring function with const and assignment, because that's boring.");
return;
}
var uf = uneval(f);
if (uf.indexOf("switch") != -1) {
// Bug 355509 :(
return;
}
if (code.indexOf("new") != code.lastIndexOf("new")) {
dumpln("checkRoundTripDisassembly: ignoring function with two 'new' operators (bug 475848)");
return;
}
if (code.indexOf("&&") != code.lastIndexOf("&&")) {
dumpln("checkRoundTripDisassembly: ignoring && associativity issues (bug 475863)");
return;
}
if (code.indexOf("||") != code.lastIndexOf("||")) {
dumpln("checkRoundTripDisassembly: ignoring || associativity issues (bug 475863)");
return;
}
if (code.match(/for.*\(.*in.*\).*if/)) {
print("checkRoundTripDisassembly: ignoring array comprehension with 'if' (bug 475882)");
return;
}
try { var g = eval(uf); } catch(e) { return; /* separate uneval test will catch this */ }
var df = dis(f);
if (df.indexOf("newline") != -1)
return;
if (df.indexOf("lineno") != -1)
return;
if (df.indexOf("trap") != -1) {
print("checkRoundTripDisassembly: trapped");
return;
}
var dg = dis(g);
if (df == dg) {
// Happy!
if (wtt.allowExec)
trapCorrectnessTest(f);
return;
}
if (dg.indexOf("newline") != -1) {
// Really should just ignore these lines, instead of bailing...
return;
}
var dfl = df.split("\n");
var dgl = dg.split("\n");
for (var i = 0; i < dfl.length && i < dgl.length; ++i) {
if (dfl[i] != dgl[i]) {
if (dfl[i] == "00000: generator") {
print("checkRoundTripDisassembly: ignoring loss of generator (bug 350743)");
return;
}
if (dfl[i].indexOf("goto") != -1 && dgl[i].indexOf("stop") != -1 && uf.indexOf("switch") != -1) {
// Actually, this might just be bug 355509.
print("checkRoundTripDisassembly: ignoring extra 'goto' in switch (bug 475838)");
return;
}
if (dfl[i].indexOf("regexp null") != -1) {
print("checkRoundTripDisassembly: ignoring 475844 / regexp");
return;
}
if (dfl[i].indexOf("namedfunobj null") != -1 || dfl[i].indexOf("anonfunobj null") != -1) {
print("checkRoundTripDisassembly: ignoring 475844 / function");
return;
}
if (dfl[i].indexOf("string") != -1 && (dfl[i+1].indexOf("toxml") != -1 || dfl[i+1].indexOf("startxml") != -1)) {
print("checkRoundTripDisassembly: ignoring e4x-string mismatch (likely bug 355674)");
return;
}
if (dfl[i].indexOf("string") != -1 && df.indexOf("startxmlexpr") != -1) {
print("checkRoundTripDisassembly: ignoring complicated e4x-string mismatch (likely bug 355674)");
return;
}
if (dfl[i].indexOf("newinit") != -1 && dgl[i].indexOf("newarray 0") != -1) {
print("checkRoundTripDisassembly: ignoring array comprehension disappearance (bug 475847)");
return;
}
if (i == 0 && dfl[i].indexOf("HEAVYWEIGHT") != -1 && dgl[i].indexOf("HEAVYWEIGHT") == -1) {
print("checkRoundTripDisassembly: ignoring unnecessarily HEAVYWEIGHT function (bug 475854)");
return;
}
if (i == 0 && dfl[i].indexOf("HEAVYWEIGHT") == -1 && dgl[i].indexOf("HEAVYWEIGHT") != -1) {
// The other direction
// var __proto__ hoisting, for example
print("checkRoundTripDisassembly: ignoring unnecessarily HEAVYWEIGHT function (bug 475854 comment 1)");
return;
}
if (dfl[i].indexOf("pcdelta") != -1 && dgl[i].indexOf("pcdelta") != -1) {
print("checkRoundTripDisassembly: pcdelta changed, who cares? (bug 475908)");
return;
}
print("First line that does not match:");
print(dfl[i]);
print(dgl[i]);
break;
}
}
print("Function from original code:");
print(code);
print(df);
print("Function from recompiling:");
print(uf);
print(dg);
printAndStop("Disassembly was not stable through decompilation");
}
/*****************************
* SPIDERMONKEY TRAP TESTING *
*****************************/
function getBytecodeOffsets(f)
{
var disassembly = dis(f);
var lines = disassembly.split("\n");
var i;
offsets = [];
for (i = 0; i < lines.length; ++i) {
if (lines[i] == "main:")
break;
if (i + 1 == lines.length)
printAndStop("disassembly -- no main?");
}
for (++i; i < lines.length; ++i) {
if (lines[i] == "")
break;
if (i + 1 == lines.length)
printAndStop("disassembly -- ended suddenly?")
// The opcodes |tableswitch| and |lookupswitch| add indented lists,
// which we want to ignore.
var c = lines[i].charCodeAt(0);
if (!(0x30 <= c && c <= 0x39))
continue;
var op = lines[i].substr(8).split(" ")[0]; // used only for avoiding known bugs
var offset = parseInt(lines[i], 10);
offsets.push({ offset: offset, op: op });
if (op == "getter" || op == "setter") {
++i; // skip the next opcode per bug 476073 comment 4
}
}
return offsets;
}
function trapCorrectnessTest(f)
{
var uf = uneval(f);
print("trapCorrectnessTest...");
var offsets = getBytecodeOffsets(f);
var prefix = "var fff = " + f + "; ";
var r1 = sandboxResult(prefix + "fff();");
for (var i = 0; i < offsets.length; ++i) {
var offset = offsets[i].offset;
var op = offsets[i].op;
// print(offset + " " + op);
var trapStr = "trap(fff, " + offset + ", ''); ";
var r2 = sandboxResult(prefix + trapStr + " fff();");
if (r1 != r2) {
if (r1.indexOf("TypeError") != -1 && r2.indexOf("TypeError") != -1) {
// Why does this get printed multiple times???
// count=6544; tIO("var x; x.y;");
print("A TypeError changed. Might be bug 476088.");
continue;
}
print("Adding a trap changed the result!");
print(f);
print(r1);
print(trapStr);
print(r2);
printAndStop(":(");
}
}
//print("Happy: " + f + r1);
}
function sandboxResult(code)
{
// Use sandbox to isolate side-effects.
// This might be wrong in cases where the sandbox manages to return objects with getters and stuff!
var result;
try {
// result = evalcx(code, {trap:trap, print:print}); // WRONG
var sandbox = evalcx("");
sandbox.trap = trap;
sandbox.print = print;
sandbox.dis = dis;
result = evalcx(code, sandbox);
} catch(e) {
result = "Error: " + errorToString(e);
}
return "" + result;
}
// This tests two aspects of trap:
// 1) put a trap in a random place; does decompilation get horked?
// 2) traps that do things
// These should probably be split into different tests.
function spiderMonkeyTrapTest(f, code, wtt)
{
var offsets = getBytecodeOffsets(f);
if ("trap" in this) {
// Save for trap
//if (wtt.allowExec && count % 2 == 0) {
//nextTrapCode = code;
// return;
//}
// Use trap
if (verbose)
dumpln("About to try the trap test.");
var ode;
if (wtt.allowDecompile)
ode = "" + f;
//if (nextTrapCode) {
// trapCode = nextTrapCode;
// nextTrapCode = null;
// print("trapCode = " + simpleSource(trapCode));
//} else {
trapCode = "print('Trap hit!')";
//}
trapOffset = offsets[count % offsets.length].offset;
print("trapOffset: " + trapOffset);
if (!(trapOffset > -1)) {
print(dis(f));
print(count);
print(uneval(offsets));
print(offsets.length);
printAndStop("WTF");
}
trap(f, trapOffset, trapCode);
if (wtt.allowDecompile) {
nde = "" + f;
if (ode != nde) {
print(ode);
print(nde);
printAndStop("Trap decompilation mismatch");
}
}
}
}
/*********************
* SPECIALIZED TESTS *
*********************/
function simpleDVGTest(code)
{
var fullCode = "(function() { try { \n" + code + "\n; throw 1; } catch(exx) { this.nnn.nnn } })()";
try {
eval(fullCode);
} catch(e) {
if (e.message != "this.nnn is undefined" && e.message.indexOf("redeclaration of") == -1) {
printAndStop("Wrong error message: " + e);
}
}
}
function optionalTests(f, code, wtt)
{
if (0) {
tryHalves(code);
}
if (0 && engine == ENGINE_SPIDERMONKEY_TRUNK) {
if (wtt.allowExec && ('sandbox' in this)) {
f = null;
if (trySandboxEval(code, false)) {
dumpln("Trying it again to see if it's a 'real leak' (???)")
trySandboxEval(code, true);
}
}
return;
}
if (0 && f && haveUsefulDis) {
spiderMonkeyTrapTest(f, code, wtt);
}
if (0 && f && wtt.allowExec && engine == ENGINE_SPIDERMONKEY_TRUNK) {
simpleDVGTest(code);
tryEnsureSanity();
}
}
function trySandboxEval(code, isRetry)
{
// (function(){})() wrapping allows "return" when it's allowed outside.
// The line breaks are to allow single-line comments within code ("//" and "<!--").
if (!sandbox) {
sandbox = evalcx("");
}
var rv = null;
try {
rv = evalcx("(function(){\n" + code + "\n})();", sandbox);
} catch(e) {
rv = "Error from sandbox: " + errorToString(e);
}
try {
if (typeof rv != "undefined")
dumpln(rv);
} catch(e) {
dumpln("Sandbox error printing: " + errorToString(e));
}
rv = null;
if (1 || count % 100 == 0) { // count % 100 *here* is sketchy.
dumpln("Done with this sandbox.");
sandbox = null;
gc();
var currentHeapCount = countHeap()
dumpln("countHeap: " + currentHeapCount);
if (currentHeapCount > maxHeapCount) {
if (maxHeapCount != 0)
dumpln("A new record by " + (currentHeapCount - maxHeapCount) + "!");
if (isRetry)
throw new Error("Found a leak!");
maxHeapCount = currentHeapCount;
return true;
}
}
return false;
}
function tryHalves(code)
{
// See if there are any especially horrible bugs that appear when the parser has to start/stop in the middle of something. this is kinda evil.
// Stray "}"s are likely in secondHalf, so use new Function rather than eval. "}" can't escape from new Function :)
var f, firstHalf, secondHalf;
try {
firstHalf = code.substr(0, code.length / 2);
if (verbose)
dumpln("First half: " + firstHalf);
f = new Function(firstHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("First half compilation error: " + e);
}
try {
secondHalf = code.substr(code.length / 2, code.length);
if (verbose)
dumpln("Second half: " + secondHalf);
f = new Function(secondHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("Second half compilation error: " + e);
}
}
/***************************
* REPRODUCIBLE RANDOMNESS *
***************************/
// this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class,
// an almost straight conversion from the original program, mt19937ar.c,
// translated by y. okada on July 17, 2006.
// Changes by Jesse Ruderman: added "var" keyword in a few spots; added export_mta etc; pasted into fuzz.js.
// in this program, procedure descriptions and comments of original source code were not removed.
// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.
// lines commented with /* and */ are original comments.
// lines commented with // are additional comments in this JavaScript version.
// before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances.
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
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 names of its contributors may not 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.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
function MersenneTwister19937()
{
/* Period parameters */
//c//#define N 624
//c//#define M 397
//c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */
//c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
//c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
var N = 624;
var M = 397;
var MATRIX_A = 0x9908b0df; /* constant vector a */
var UPPER_MASK = 0x80000000; /* most significant w-r bits */
var LOWER_MASK = 0x7fffffff; /* least significant r bits */
//c//static unsigned long mt[N]; /* the array for the state vector */
//c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
var mt = new Array(N); /* the array for the state vector */
var mti = N+1; /* mti==N+1 means mt[N] is not initialized */
function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.
{
return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;
}
function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;
}
function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return unsigned32((n1 + n2) & 0xffffffff)
}
function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
var sum = 0;
for (var i = 0; i < 32; ++i){
if ((n1 >>> i) & 0x1){
sum = addition32(sum, unsigned32(n2 << i));
}
}
return sum;
}
/* initializes mt[N] with a seed */
//c//void init_genrand(unsigned long s)
this.init_genrand = function (s)
{
//c//mt[0]= s & 0xffffffff;
mt[0]= unsigned32(s & 0xffffffff);
for (mti=1; mti<N; mti++) {
mt[mti] =
//c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//c//mt[mti] &= 0xffffffff;
mt[mti] = unsigned32(mt[mti] & 0xffffffff);
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//c//void init_by_array(unsigned long init_key[], int key_length)
this.init_by_array = function (init_key, key_length)
{
//c//int i, j, k;
var i, j, k;
//c//init_genrand(19650218);
this.init_genrand(19650218);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))
//c// + init_key[j] + j; /* non linear */
mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);
mt[i] =
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
unsigned32(mt[i] & 0xffffffff);
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))
//c//- i; /* non linear */
mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
mt[i] = unsigned32(mt[i] & 0xffffffff);
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
this.export_state = function() { return [mt, mti]; };
this.import_state = function(s) { mt = s[0]; mti = s[1]; };
this.export_mta = function() { return mt; };
this.import_mta = function(_mta) { mt = _mta };
this.export_mti = function() { return mti; };
this.import_mti = function(_mti) { mti = _mti; }
/* generates a random number on [0,0xffffffff]-interval */
//c//unsigned long genrand_int32(void)
this.genrand_int32 = function ()
{
//c//unsigned long y;
//c//static unsigned long mag01[2]={0x0UL, MATRIX_A};
var y;
var mag01 = new Array(0x0, MATRIX_A);
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
//c//int kk;
var kk;
if (mti == N+1) /* if init_genrand() has not been called, */
//c//init_genrand(5489); /* a default initial seed is used */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
for (;kk<N-1;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
//c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
//c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));
mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
//c//y ^= (y >> 11);
//c//y ^= (y << 7) & 0x9d2c5680;
//c//y ^= (y << 15) & 0xefc60000;
//c//y ^= (y >> 18);
y = unsigned32(y ^ (y >>> 11));
y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));
y = unsigned32(y ^ ((y << 15) & 0xefc60000));
y = unsigned32(y ^ (y >>> 18));
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
//c//long genrand_int31(void)
this.genrand_int31 = function ()
{
//c//return (genrand_int32()>>1);
return (this.genrand_int32()>>>1);
}
/* generates a random number on [0,1]-real-interval */
//c//double genrand_real1(void)
this.genrand_real1 = function ()
{
//c//return genrand_int32()*(1.0/4294967295.0);
return this.genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
//c//double genrand_real2(void)
this.genrand_real2 = function ()
{
//c//return genrand_int32()*(1.0/4294967296.0);
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//c//double genrand_real3(void)
this.genrand_real3 = function ()
{
//c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);
return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
//c//double genrand_res53(void)
this.genrand_res53 = function ()
{
//c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
var rnd;
if (1) {
// Mersenne twister: I get to set the seed, great distribution of random numbers, but pretty slow
// (spidermonkey trunk 2008-10-08 with JIT on, makes jsfunfuzz 20% slower overall!)
(function() {
var fuzzMT = new MersenneTwister19937;
var fuzzSeed = Math.floor(Math.random() * Math.pow(2,28));
dumpln("fuzzSeed: " + fuzzSeed);
fuzzMT.init_genrand(fuzzSeed);
rnd = function (n) { return Math.floor(fuzzMT.genrand_real2() * n); };
rnd.rndReal = function() { return fuzzMT.genrand_real2(); };
rnd.fuzzMT = fuzzMT;
})();
} else {
// Math.random(): ok distribution of random numbers, fast
rnd = function (n) { return Math.floor(Math.random() * n); };
}
function errorstack()
{
print("EEE");
try { [].qwerty.qwerty } catch(e) { print(e.stack) }
}
function rndElt(a)
{
if (typeof a == "string") {
dumpln("String passed to rndElt: " + a);
errorstack();
}
if (typeof a == "function")
dumpln("Function passed to rndElt: " + a);
if (a == null)
dumpln("Null passed to rndElt");
if (!a.length) {
dumpln("Empty thing passed to rndElt");
return null;
}
return a[rnd(a.length)];
}
/**************************
* TOKEN-LEVEL GENERATION *
**************************/
// Each input to |cat| should be a token or so, OR a bigger logical piece (such as a call to makeExpr). Smaller than a token is ok too ;)
// When "torture" is true, it may do any of the following:
// * skip a token
// * skip all the tokens to the left
// * skip all the tokens to the right
// * insert unterminated comments
// * insert line breaks
// * insert entire expressions
// * insert any token
// Even when not in "torture" mode, it may sneak in extra line breaks.
// Why did I decide to toString at every step, instead of making larger and larger arrays (or more and more deeply nested arrays?). no particular reason...
function cat(toks)
{
if (rnd(1700) == 0)
return totallyRandom(2, []);
var torture = (rnd(1700) == 57);
if (torture)
dumpln("Torture!!!");
var s = maybeLineBreak();
for (var i = 0; i < toks.length; ++i) {
// Catch bugs in the fuzzer. An easy mistake is
// return /*foo*/ + ...
// instead of
// return "/*foo*/" + ...
// Unary plus in the first one coerces the string that follows to number!
if(typeof(toks[i]) != "string") {
dumpln("Strange item in the array passed to cat: toks[" + i + "] == " + toks[i]);
dumpln(cat.caller)
dumpln(cat.caller.caller)
printAndStop('yarr')
}
if (!(torture && rnd(12) == 0))
s += toks[i];
s += maybeLineBreak();
if (torture) switch(rnd(120)) {
case 0:
case 1:
case 2:
case 3:
case 4:
s += maybeSpace() + totallyRandom(2, []) + maybeSpace();
break;
case 5:
s = "(" + s + ")"; // randomly parenthesize some *prefix* of it.
break;
case 6:
s = ""; // throw away everything before this point
break;
case 7:
return s; // throw away everything after this point
case 8:
s += UNTERMINATED_COMMENT;
break;
case 9:
s += UNTERMINATED_STRING_LITERAL;
break;
case 10:
if (rnd(2))
s += "(";
s += UNTERMINATED_REGEXP_LITERAL;
break;
default:
}
}
return s;
}
// For reference and debugging.
/*
function catNice(toks)
{
var s = ""
var i;
for (i=0; i<toks.length; ++i) {
if(typeof(toks[i]) != "string")
printAndStop("Strange toks[i]: " + toks[i]);
s += toks[i];
}
return s;
}
*/
var UNTERMINATED_COMMENT = "/*"; /* this comment is here so my text editor won't get confused */
var UNTERMINATED_STRING_LITERAL = "'";
var UNTERMINATED_REGEXP_LITERAL = "/";
function maybeLineBreak()
{
if (rnd(900) == 3)
return rndElt(["\r", "\n", "//h\n", "/*\n*/"]); // line break to trigger semicolon insertion and stuff
else if (rnd(400) == 3)
return rnd(2) ? "\u000C" : "\t"; // weird space-like characters
else
return "";
}
function maybeSpace()
{
if (rnd(2) == 0)
return " ";
else
return "";
}
function stripSemicolon(c)
{
var len = c.length;
if (c.charAt(len - 1) == ";")
return c.substr(0, len - 1);
else
return c;
}
/*************************
* HIGH-LEVEL GENERATION *
*************************/
var TOTALLY_RANDOM = 500;
function makeStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d < 6 && rnd(3) == 0)
return makePrintStatement(d, b);
if (d < rnd(8)) // frequently for small depth, infrequently for large depth
return makeLittleStatement(d, b);
d = rnd(d); // !
return (rndElt(statementMakers))(d, b)
}
var varBinder = ["var ", "let ", "const ", ""];
var varBinderFor = ["var ", "let ", ""]; // const is a syntax error in for loops
// The reason there are several types of loops here is to create different
// types of scripts without introducing infinite loops.
function makeOpaqueIdiomaticLoop(d, b)
{
var reps = 1 + rnd(7);
var vHidden = uniqueVarName();
return ("/*oLoop*/for (" + rndElt(varBinderFor) + "x = 0; x < " + reps + "; ++x) ").replace(/x/g, vHidden) +
makeStatement(d - 2, b);
}
function makeTransparentIdiomaticLoop(d, b)
{
var reps = 1 + rnd(7);
var vHidden = uniqueVarName();
var vVisible = makeNewId(d, b);
return ("/*vLoop*/for (" + rndElt(varBinderFor) + "x = 0; x < " + reps + "; ++x)").replace(/x/g, vHidden) +
" { " +
rndElt(varBinder) + vVisible + " = " + vHidden + "; " +
makeStatement(d - 2, b.concat([vVisible])) +
" } "
}
function makeBranchUnstableLoop(d, b)
{
var reps = 1 + rnd(24);
var v = uniqueVarName();
var mod = rnd(5) + 2;
var target = rnd(mod);
var loopHead = ("/*bLoop*/for (var x = 0; x < " + reps + "; ++x)").replace(/x/g, v);
return loopHead + " { " +
"if (" + v + " % " + mod + " == " + target + ") { " + makeStatement(d - 2, b) + " } " +
"else { " + makeStatement(d - 2, b) + " } " +
" } "
}
function makeTypeUnstableLoop(d, b) {
var a = makeMixedTypeArray(d, b);
var v = makeNewId(d, b);
var bv = b.concat([v]);
return "/*tLoop*/for each (let " + v + " in " + a + ") { " + makeStatement(d - 2, bv) + " }";
}
function weighted(wa)
{
var a = [];
for (var i = 0; i < wa.length; ++i) {
for (var j = 0; j < wa[i].w; ++j) {
a.push(wa[i].fun);
}
}
return a;
}
var statementMakers = weighted([
// Any two statements in sequence
{ w: 15, fun: function(d, b) { return cat([makeStatement(d - 1, b), makeStatement(d - 1, b) ]); } },
{ w: 15, fun: function(d, b) { return cat([makeStatement(d - 1, b), "\n", makeStatement(d - 1, b), "\n"]); } },
// Stripping semilcolons. What happens if semicolons are missing? Especially with line breaks used in place of semicolons (semicolon insertion).
{ w: 1, fun: function(d, b) { return cat([stripSemicolon(makeStatement(d, b)), "\n", makeStatement(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([stripSemicolon(makeStatement(d, b)), "\n" ]); } },
{ w: 1, fun: function(d, b) { return stripSemicolon(makeStatement(d, b)); } }, // usually invalid, but can be ok e.g. at the end of a block with curly braces
// Simple variable declarations, followed (or preceded) by statements using those variables
{ w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([rndElt(varBinder), v, " = ", makeExpr(d, b), ";", makeStatement(d - 1, b.concat([v]))]); } },
{ w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([makeStatement(d - 1, b.concat([v])), rndElt(varBinder), v, " = ", makeExpr(d, b), ";"]); } },
// Complex variable declarations, e.g. "const [a,b] = [3,4];" or "var a,b,c,d=4,e;"
{ w: 10, fun: function(d, b) { return cat([rndElt(varBinder), makeLetHead(d, b), ";", makeStatement(d - 1, b)]); } },
// Blocks
{ w: 2, fun: function(d, b) { return cat(["{", makeStatement(d, b), " }"]); } },
{ w: 2, fun: function(d, b) { return cat(["{", makeStatement(d - 1, b), makeStatement(d - 1, b), " }"]); } },
// "with" blocks
{ w: 2, fun: function(d, b) { return cat([maybeLabel(), "with", "(", makeExpr(d, b), ")", makeStatementOrBlock(d, b)]); } },
{ w: 2, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "with", "(", "{", v, ": ", makeExpr(d, b), "}", ")", makeStatementOrBlock(d, b.concat([v]))]); } },
// C-style "for" loops
// Two kinds of "for" loops: one with an expression as the first part, one with a var or let binding 'statement' as the first part.
// I'm not sure if arbitrary statements are allowed there; I think not.
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " = ", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeDestructuringLValue(d, b), " = ", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
// Various types of "for" loops, specially set up to test tracing, carefully avoiding infinite loops
{ w: 6, fun: makeTransparentIdiomaticLoop },
{ w: 6, fun: makeOpaqueIdiomaticLoop },
{ w: 6, fun: makeBranchUnstableLoop },
{ w: 8, fun: makeTypeUnstableLoop },
// "for..in" loops
// arbitrary-LHS marked as infloop because
// -- for (key in obj)
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeForInLHS(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
// -- for (key in generator())
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeForInLHS(d, b), " in ", "(", "(", makeFunction(d, b), ")", "(", makeExpr(d, b), ")", ")", ")", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " in ", "(", "(", makeFunction(d, b), ")", "(", makeExpr(d, b), ")", ")", ")", makeStatementOrBlock(d, b.concat([v]))]); } },
// -- for each (value in obj)
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), " for ", " each", "(", rndElt(varBinderFor), makeLValue(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), " for ", " each", "(", rndElt(varBinderFor), v, " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
// Modify something during a loop -- perhaps the thing being looped over
// Since we use "let" to bind the for-variables, and only do wacky stuff once, I *think* this is unlikely to hang.
// function(d, b) { return "let forCount = 0; for (let " + makeId(d, b) + " in " + makeExpr(d, b) + ") { if (forCount++ == " + rnd(3) + ") { " + makeStatement(d - 1, b) + " } }"; },
// Hoisty "for..in" loops. I don't know why this construct exists, but it does, and it hoists the initial-value expression above the loop.
// With "var" or "const", the entire thing is hoisted.
// With "let", only the value is hoisted, and it can be elim'ed as a useless statement.
// The first form could be an infinite loop because of "for (x.y in x)" with e4x.
// The last form is specific to JavaScript 1.7 (only).
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeId(d, b), " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b), w = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), "[", v, ", ", w, "]", " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v, w]))]); } },
// do..while
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "while((", makeExpr(d, b), ") && 0)" /*don't split this, it's needed to avoid marking as infloop*/, makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "while", "(", makeExpr(d, b), ")", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "do ", makeStatementOrBlock(d, b), " while((", makeExpr(d, b), ") && 0)" /*don't split this, it's needed to avoid marking as infloop*/, ";"]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "do ", makeStatementOrBlock(d, b), " while", "(", makeExpr(d, b), ");"]); } },
// Switch statement
{ w: 3, fun: function(d, b) { return cat([maybeLabel(), "switch", "(", makeExpr(d, b), ")", " { ", makeSwitchBody(d, b), " }"]); } },
// "let" blocks, with bound variable used inside the block
{ w: 2, fun: function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, ")", " { ", makeStatement(d, b.concat([v])), " }"]); } },
// "let" blocks, with and without multiple bindings, with and without initial values
{ w: 2, fun: function(d, b) { return cat(["let ", "(", makeLetHead(d, b), ")", " { ", makeStatement(d, b), " }"]); } },
// Conditionals, perhaps with 'else if' / 'else'
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b)]); } },
// A tricky pair of if/else cases.
// In the SECOND case, braces must be preserved to keep the final "else" associated with the first "if".
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", "{", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b), "}"]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", "{", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), "}", " else ", makeStatementOrBlock(d - 1, b)]); } },
// Expression statements
{ w: 5, fun: function(d, b) { return cat([makeExpr(d, b), ";"]); } },
{ w: 5, fun: function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); } },
// Exception-related statements :)
{ w: 6, fun: function(d, b) { return makeExceptionyStatement(d - 1, b) + makeExceptionyStatement(d - 1, b); } },
{ w: 7, fun: function(d, b) { return makeExceptionyStatement(d, b); } },
// Labels. (JavaScript does not have goto, but it does have break-to-label and continue-to-label).
{ w: 1, fun: function(d, b) { return cat(["L", ": ", makeStatementOrBlock(d, b)]); } },
// Function-declaration-statements with shared names
{ w: 10, fun: function(d, b) { return cat([makeStatement(d-2, b), "function ", makeId(d, b), "(", makeFormalArgList(d, b), ")", "{", "/*jjj*/", "}", makeStatement(d-2, b)]); } },
// Function-declaration-statements with unique names, along with calls to those functions
{ w: 8, fun: makeNamedFunctionAndUse },
// Long script -- can confuse Spidermonkey's short vs long jmp or something like that.
// Spidermonkey's regexp engine is so slow for long strings that we have to bypass whatToTest :(
//{ w: 1, fun: function(d, b) { return strTimes("try{}catch(e){}", rnd(10000)); } },
{ w: 1, fun: function(d, b) { if (rnd(200)==0) return "/*DUPTRY" + rnd(10000) + "*/" + makeStatement(d - 1, b); return ";"; } },
// E4X "default xml namespace"
{ w: 1, fun: function(d, b) { return cat(["default ", "xml ", "namespace ", " = ", makeExpr(d, b), ";"]); } },
{ w: 1, fun: function(d, b) { return makeShapeyConstructorLoop(d, b); } },
// Replace a variable with a long linked list pointing to it. (Forces SpiderMonkey's GC marker into a stackless mode.)
{ w: 1, fun: function(d, b) { var x = makeId(d, b); return x + " = linkedList(" + x + ", " + (rnd(100) * rnd(100)) + ");"; } },
]);
function linkedList(x, n)
{
for (var i = 0; i < n; ++i)
x = {a: x};
return x;
}
function makeNamedFunctionAndUse(d, b) {
// Use a unique function name to make it less likely that we'll accidentally make a recursive call
var funcName = uniqueVarName();
var formalArgList = makeFormalArgList(d, b);
var bv = formalArgList.length == 1 ? b.concat(formalArgList) : b;
var declStatement = cat(["/*hhh*/function ", funcName, "(", formalArgList, ")", "{", makeStatement(d - 1, bv), "}"]);
var useStatement;
if (rnd(2)) {
// Direct call
useStatement = cat([funcName, "(", makeActualArgList(d, b), ")", ";"]);
} else {
// Any statement, allowed to use the name of the function
useStatement = "/*iii*/" + makeStatement(d - 1, b.concat([funcName]));
}
if (rnd(2)) {
return declStatement + useStatement;
} else {
return useStatement + declStatement;
}
}
function makePrintStatement(d, b)
{
if (rnd(2) && b.length)
return "print(" + rndElt(b) + ");";
else
return "print(" + makeExpr(d, b) + ");";
}
function maybeLabel()
{
if (rnd(4) == 1)
return cat([rndElt(["L", "M"]), ":"]);
else
return "";
}
function uniqueVarName()
{
// Make a random variable name.
var i, s = "";
for (i = 0; i < 6; ++i)
s += String.fromCharCode(97 + rnd(26)); // a lowercase english letter
return s;
}
function makeSwitchBody(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var haveSomething = false;
var haveDefault = false;
var output = "";
do {
if (!haveSomething || rnd(2)) {
// Want a case/default (or, if this is the beginning, "need").
if (!haveDefault && rnd(2)) {
output += "default: ";
haveDefault = true;
}
else {
// cases with numbers (integers?) have special optimizations that affect order when decompiling,
// so be sure to test those well in addition to testing complicated expressions.
output += "case " + (rnd(2) ? rnd(10) : makeExpr(d, b)) + ": ";
}
haveSomething = true;
}
// Might want a statement.
if (rnd(2))
output += makeStatement(d, b)
// Might want to break, or might want to fall through.
if (rnd(2))
output += "break; ";
if (rnd(2))
--d;
} while (d && rnd(5));
return output;
}
function makeLittleStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (rnd(4) == 1)
return makeStatement(d, b);
return (rndElt(littleStatementMakers))(d, b);
}
var littleStatementMakers =
[
// Tiny
function(d, b) { return cat([";"]); }, // e.g. empty "if" block
function(d, b) { return cat(["{", "}"]); }, // e.g. empty "if" block
function(d, b) { return cat([""]); },
// Force garbage collection
function(d, b) { return "gc()"; },
// Throw stuff.
function(d, b) { return cat(["throw ", makeExpr(d, b), ";"]); },
// Break/continue [to label].
function(d, b) { return cat([rndElt(["continue", "break"]), " ", rndElt(["L", "M", "", ""]), ";"]); },
// Named and unnamed functions (which have different behaviors in different places: both can be expressions,
// but unnamed functions "want" to be expressions and named functions "want" to be special statements)
function(d, b) { return makeFunction(d, b); },
// Return, yield
function(d, b) { return cat(["return ", makeExpr(d, b), ";"]); },
function(d, b) { return "return;"; }, // return without a value is allowed in generators; return with a value is not.
function(d, b) { return cat(["yield ", makeExpr(d, b), ";"]); }, // note: yield can also be a left-unary operator, or something like that
function(d, b) { return "yield;"; },
// Expression statements
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
// Turn on gczeal in the middle of something
function(d, b) { return "gczeal(" + makeZealLevel() + ")" + ";"; }
];
// makeStatementOrBlock exists because often, things have different behaviors depending on where there are braces.
// for example, if braces are added or removed, the meaning of "let" can change.
function makeStatementOrBlock(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return (rndElt(statementBlockMakers))(d - 1, b);
}
var statementBlockMakers = [
function(d, b) { return makeStatement(d, b); },
function(d, b) { return makeStatement(d, b); },
function(d, b) { return cat(["{", makeStatement(d, b), " }"]); },
function(d, b) { return cat(["{", makeStatement(d - 1, b), makeStatement(d - 1, b), " }"]); },
]
// Extra-hard testing for try/catch/finally and related things.
function makeExceptionyStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (d < 1)
return makeLittleStatement(d, b);
return (rndElt(exceptionyStatementMakers))(d, b);
}
var exceptionyStatementMakers = [
function(d, b) { return makeTryBlock(d, b); },
function(d, b) { return makeStatement(d, b); },
function(d, b) { return makeLittleStatement(d, b); },
function(d, b) { return "return;" }, // return without a value can be mixed with yield
function(d, b) { return cat(["return ", makeExpr(d, b), ";"]); },
function(d, b) { return cat(["yield ", makeExpr(d, b), ";"]); },
function(d, b) { return cat(["throw ", makeId(d, b), ";"]); },
function(d, b) { return "throw StopIteration;"; },
function(d, b) { return "this.zzz.zzz;"; }, // throws; also tests js_DecompileValueGenerator in various locations
function(d, b) { return cat([makeId(d, b), " = ", makeId(d, b), ";"]); },
function(d, b) { return cat([makeLValue(d, b), " = ", makeId(d, b), ";"]); },
// Iteration uses StopIteration internally.
// Iteration is also useful to test because it asserts that there is no pending exception.
function(d, b) { var v = makeNewId(d, b); return "for(let " + v + " in []);"; },
function(d, b) { var v = makeNewId(d, b); return "for(let " + v + " in " + makeMixedTypeArray(d, b) + ") " + makeExceptionyStatement(d, b.concat([v])); },
// Brendan says these are scary places to throw: with, let block, lambda called immediately in let expr.
// And I think he was right.
function(d, b) { return "with({}) " + makeExceptionyStatement(d, b); },
function(d, b) { return "with({}) { " + makeExceptionyStatement(d, b) + " } "; },
function(d, b) { var v = makeNewId(d, b); return "let(" + v + ") { " + makeExceptionyStatement(d, b.concat([v])) + "}"; },
function(d, b) { var v = makeNewId(d, b); return "let(" + v + ") ((function(){" + makeExceptionyStatement(d, b.concat([v])) + "})());" },
function(d, b) { return "let(" + makeLetHead(d, b) + ") { " + makeExceptionyStatement(d, b) + "}"; },
function(d, b) { return "let(" + makeLetHead(d, b) + ") ((function(){" + makeExceptionyStatement(d, b) + "})());" },
// Commented out due to causing too much noise on stderr and causing a nonzero exit code :/
/*
// Generator close hooks: called during GC in this case!!!
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })().next()"; },
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })()"; },
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })"; },
function(d, b) {
return "function gen() { try { yield 1; } finally { " + makeStatement(d, b) + " } } var i = gen(); i.next(); i = null;";
}
*/
];
function makeTryBlock(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// Catches: 1/6 chance of having none
// Catches: maybe 2 + 1/2
// So approximately 4 recursions into makeExceptionyStatement on average!
// Therefore we want to keep the chance of recursing too much down...
d = d - rnd(3);
var s = cat(["try", " { ", makeExceptionyStatement(d, b), " } "]);
var numCatches = 0;
while(rnd(3) == 0) {
// Add a guarded catch, using an expression or a function call.
++numCatches;
if (rnd(2))
s += cat(["catch", "(", makeId(d, b), " if ", makeExpr(d, b), ")", " { ", makeExceptionyStatement(d, b), " } "]);
else
s += cat(["catch", "(", makeId(d, b), " if ", "(function(){", makeExceptionyStatement(d, b), "})())", " { ", makeExceptionyStatement(d, b), " } "]);
}
if (rnd(2)) {
// Add an unguarded catch.
++numCatches;
s += cat(["catch", "(", makeId(d, b), ")", " { ", makeExceptionyStatement(d, b), " } "]);
}
if (numCatches == 0 || rnd(2) == 1) {
// Add a finally.
s += cat(["finally", " { ", makeExceptionyStatement(d, b), " } "]);
}
return s;
}
// Creates a string that sorta makes sense as an expression
function makeExpr(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0 || (rnd(7) == 1))
return makeTerm(d - 1, b);
if (rnd(6) == 1 && b.length)
return rndElt(b);
if (rnd(10) == 1)
return makeImmediateRecursiveCall(d, b);
d = rnd(d); // !
var expr = (rndElt(exprMakers))(d, b);
if (rnd(4) == 1)
return "(" + expr + ")";
else
return expr;
}
var binaryOps = [
// Long-standing JavaScript operators, roughly in order from http://www.codehouse.com/javascript/precedence/
" * ", " / ", " % ", " + ", " - ", " << ", " >> ", " >>> ", " < ", " > ", " <= ", " >= ", " instanceof ", " in ", " == ", " != ", " === ", " !== ",
" & ", " | ", " ^ ", " && ", " || ", " = ", " *= ", " /= ", " %= ", " += ", " -= ", " <<= ", " >>= ", " >>>= ", " &= ", " ^= ", " |= ", " , ",
// . is special, so test it as a group of right-unary ops, a special exprMaker for property access, and a special exprMaker for the xml filtering predicate operator
// " . ",
];
if (haveE4X) {
binaryOps = binaryOps.concat([
// Binary operators added by E4X
" :: ", " .. ", " @ ",
// Frequent combinations of E4X things (and "*" namespace, which isn't produced by this fuzzer otherwise)
" .@ ", " .@*:: ", " .@x:: ",
]);
}
var leftUnaryOps = [
"--", "++",
"!", "+", "-", "~",
"void ", "typeof ", "delete ",
"new ", // but note that "new" can also be a very strange left-binary operator
"yield " // see http://www.python.org/dev/peps/pep-0342/ . Often needs to be parenthesized, so there's also a special exprMaker for it.
];
var rightUnaryOps = [
"++", "--",
];
if (haveE4X)
rightUnaryOps = rightUnaryOps.concat([".*", ".@foo", ".@*"]);
var specialProperties = [
"x", "y",
"__iterator__", "__count__",
"__noSuchMethod__",
"__parent__", "__proto__", "constructor", "prototype",
"wrappedJSObject",
"length",
// Typed arraays
"buffer", "byteLength", "byteOffset",
// E4X
"ignoreComments", "ignoreProcessingInstructions", "ignoreWhitespace",
"prettyPrinting", "prettyIndent"
]
function makeSpecialProperty(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return rndElt(specialProperties);
}
function makeNamespacePrefix(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch (rnd(7)) {
case 0: return "function::";
case 1: return makeId(d, b) + "::";
default: return "";
}
}
// An incomplete list of builtin methods for various data types.
var objectMethods = [
// String
"fromCharCode",
// Strings
"charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "localeCompare",
"match", "quote", "replace", "search", "slice", "split", "substr", "substring",
"toLocaleUpperCase", "toLocaleLowerCase", "toLowerCase", "toUpperCase",
// String methods added in ES5
"trim", "trimLeft", "trimRight",
// Regular expressions
"test", "exec",
// Arrays
"splice", "shift", "sort", "pop", "push", "reverse", "unshift",
"concat", "join", "slice",
// Array extras in JavaScript 1.6
"map", "forEach", "filter", "some", "every", "indexOf", "lastIndexOf",
// Array extras in JavaScript 1.8
"reduce", "reduceRight",
// Functions
"call", "apply",
// Date
"now", "parse", "UTC",
// Date instances
"getDate", "setDay", // many more not listed
// Number
"toExponential", "toFixed", "toLocaleString", "toPrecision",
// General -- defined on each type of object, but wit a different implementation
"toSource", "toString", "valueOf", "constructor", "prototype", "__proto__",
// General -- same implementation inherited from Object.prototype
"__defineGetter__", "__defineSetter__", "hasOwnProperty", "isPrototypeOf", "__lookupGetter__", "__lookupSetter__", "__noSuchMethod__", "propertyIsEnumerable", "unwatch", "watch",
// Things that are only built-in on Object itself
"defineProperty", "defineProperties", "create", "getOwnPropertyDescriptor", "getPrototypeOf",
// E4X functions on XML objects
"addNamespace", "appendChild", "attribute", "attributes", "child", "childIndex", "children", "comments", "contains", "copy", "descendants", "elements", "hasOwnProperty", "hasComplexContent", "hasSimpleContent", "isScopeNamespace", "insertChildAfter", "insertChildBefore", "length", "localName", "name", "namespace", "namespaceDeclarations", "nodeKind", "normalize", "parent", "processingInstructions", "prependChild", "propertyIsEnumerable", "removeNamespace", "replace", "setChildren", "setLocalName", "setName", "setNamespace", "text", "toString", "toXMLString", "valueOf",
// E4X functions on the XML constructor
"settings", "setSettings", "defaultSettings",
// E4X functions on the global object
"isXMLName",
];
var exprMakers =
[
// Left-unary operators
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
// Right-unary operators
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
// Special properties: we love to set them!
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeFunction(d, b)]); },
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeExpr(d, b)]); },
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeFunction(d, b)]); },
// Methods
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), rndElt(objectMethods)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), rndElt(objectMethods), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), "valueOf", "(", uneval("number"), ")"]); },
// Binary operators
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
// Ternary operator
function(d, b) { return cat([makeExpr(d, b), " ? ", makeExpr(d, b), " : ", makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), " ? ", makeExpr(d, b), " : ", makeExpr(d, b)]); },
// In most contexts, yield expressions must be parenthesized, so including explicitly parenthesized yields makes actually-compiling yields appear more often.
function(d, b) { return cat(["yield ", makeExpr(d, b)]); },
function(d, b) { return cat(["(", "yield ", makeExpr(d, b), ")"]); },
// Array functions (including extras). The most interesting are map and filter, I think.
// These are mostly interesting to fuzzers in the sense of "what happens if i do strange things from a filter function?" e.g. modify the array.. :)
// This fuzzer isn't the best for attacking this kind of thing, since it's unlikely that the code in the function will attempt to modify the array or make it go away.
// The second parameter to "map" is used as the "this" for the function.
function(d, b) { return cat(["[11,12,13,14]", ".", rndElt(["map", "filter", "some", "sort"]) ]); },
function(d, b) { return cat(["[15,16,17,18]", ".", rndElt(["map", "filter", "some", "sort"]), "(", makeFunction(d, b), ", ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["[", makeExpr(d, b), "]", ".", rndElt(["map", "filter", "some", "sort"]), "(", makeFunction(d, b), ")"]); },
// RegExp replace. This is interesting for the same reason as array extras. Also, in SpiderMonkey, the "this" argument is weird (obj.__parent__?)
function(d, b) { return cat(["'fafafa'", ".", "replace", "(", "/", "a", "/", "g", ", ", makeFunction(d, b), ")"]); },
// Dot (property access)
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeId(d, b)]); },
// Index into array
function(d, b) { return cat([ makeExpr(d, b), "[", makeExpr(d, b), "]"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "[", makeExpr(d, b), "]"]); },
// Containment in an array or object (or, if this happens to end up on the LHS of an assignment, destructuring)
function(d, b) { return cat([maybeSharpDecl(), "[", makeExpr(d, b), "]"]); },
function(d, b) { return cat([maybeSharpDecl(), "(", "{", makeId(d, b), ": ", makeExpr(d, b), "}", ")"]); },
// Sharps on random stuff?
function(d, b) { return cat([maybeSharpDecl(), makeExpr(d, b)]); },
// Functions: called immediately/not
function(d, b) { return makeFunction(d, b); },
function(d, b) { return makeFunction(d, b) + ".prototype"; },
function(d, b) { return cat(["(", makeFunction(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
// Try to call things that may or may not be functions.
function(d, b) { return cat([ makeExpr(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat([ makeFunction(d, b), "(", makeActualArgList(d, b), ")"]); },
// Try to test function.call heavily.
function(d, b) { return cat(["(", makeFunction(d, b), ")", ".", "call", "(", makeExpr(d, b), ", ", makeActualArgList(d, b), ")"]); },
// Binary "new", with and without clarifying parentheses, with expressions or functions
function(d, b) { return cat(["new ", makeExpr(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", "(", makeExpr(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", makeFunction(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", "(", makeFunction(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
// Sometimes we do crazy stuff, like putting a statement where an expression should go. This frequently causes a syntax error.
function(d, b) { return stripSemicolon(makeLittleStatement(d, b)); },
function(d, b) { return ""; },
// Let expressions -- note the lack of curly braces.
function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, ") ", makeExpr(d - 1, b.concat([v]))]); },
function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, " = ", makeExpr(d - 1, b), ") ", makeExpr(d - 1, b.concat([v]))]); },
function(d, b) { return cat(["let ", "(", makeLetHead(d, b), ") ", makeExpr(d, b)]); },
// Array comprehensions (JavaScript 1.7)
function(d, b) { return cat(["[", makeExpr(d, b), makeComprehension(d, b), "]"]); },
// Generator expressions (JavaScript 1.8)
function(d, b) { return cat([ makeExpr(d, b), makeComprehension(d, b) ]); },
function(d, b) { return cat(["(", makeExpr(d, b), makeComprehension(d, b), ")"]); },
// Comments and whitespace
function(d, b) { return cat([" /* Comment */", makeExpr(d, b)]); },
function(d, b) { return cat(["\n", makeExpr(d, b)]); }, // perhaps trigger semicolon insertion and stuff
function(d, b) { return cat([makeExpr(d, b), "\n"]); },
// LValue as an expression
function(d, b) { return cat([makeLValue(d, b)]); },
// Assignment (can be destructuring)
function(d, b) { return cat([ makeLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat([ makeLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat(["(", makeLValue(d, b), " = ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeLValue(d, b), ")", " = ", makeExpr(d, b) ]); },
// Destructuring assignment
function(d, b) { return cat([ makeDestructuringLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat([ makeDestructuringLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat(["(", makeDestructuringLValue(d, b), " = ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeDestructuringLValue(d, b), ")", " = ", makeExpr(d, b) ]); },
// Destructuring assignment with lots of group assignment
function(d, b) { return cat([makeDestructuringLValue(d, b), " = ", makeDestructuringLValue(d, b)]); },
// Modifying assignment, with operators that do various coercions
function(d, b) { return cat([makeLValue(d, b), rndElt(["|=", "%=", "+=", "-="]), makeExpr(d, b)]); },
// Watchpoints (similar to setters)
function(d, b) { return cat([makeExpr(d, b), ".", "watch", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "unwatch", "(", uneval(makeId(d, b)), ")"]); },
// ES5 getter/setter syntax, imperative (added in Gecko 1.9.3?)
function(d, b) { return cat(["Object.defineProperty", "(", makeId(d, b), ", ", simpleSource(makeId(d, b)), ", ", makePropertyDescriptor(d, b), ")"]); },
// Old getter/setter syntax, imperative
function(d, b) { return cat([makeExpr(d, b), ".", "__defineGetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "__defineSetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat(["this", ".", "__defineGetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat(["this", ".", "__defineSetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
// Very old getter/setter syntax, imperative (removed in Gecko 1.9.3)
function(d, b) { return cat([makeId(d, b), ".", makeId(d, b), " ", rndElt(["getter", "setter"]), "= ", makeFunction(d, b)]); },
// Object literal
function(d, b) { return cat(["(", "{", makeObjLiteralPart(d, b), " }", ")"]); },
function(d, b) { return cat(["(", "{", makeObjLiteralPart(d, b), ", ", makeObjLiteralPart(d, b), " }", ")"]); },
// Test js_ReportIsNotFunction heavily.
function(d, b) { return "(p={}, (p.z = " + makeExpr(d, b) + ")())"; },
// Test js_ReportIsNotFunction heavily.
// Test decompilation for ".keyword" a bit.
// Test throwing-into-generator sometimes.
function(d, b) { return cat([makeExpr(d, b), ".", "throw", "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "yoyo", "(", makeExpr(d, b), ")"]); },
// Throws, but more importantly, tests js_DecompileValueGenerator in various contexts.
function(d, b) { return "this.zzz.zzz"; },
// Test eval in various contexts. (but avoid clobbering eval)
// Test the special "obj.eval" and "eval(..., obj)" forms.
function(d, b) { return makeExpr(d, b) + ".eval(" + makeExpr(d, b) + ")"; },
function(d, b) { return "eval(" + uneval(makeExpr(d, b)) + ")"; },
function(d, b) { return "eval(" + uneval(makeExpr(d, b)) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return "eval(" + uneval(makeStatement(d, b)) + ")"; },
function(d, b) { return "eval(" + uneval(makeStatement(d, b)) + ", " + makeExpr(d, b) + ")"; },
// Test evalcx: sandbox creation
function(d, b) { return "evalcx('')"; },
function(d, b) { return "evalcx('lazy')"; },
// Test evalcx: sandbox use
function(d, b) { return "evalcx(" + uneval(makeExpr(d, b)) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return "evalcx(" + uneval(makeStatement(d, b)) + ", " + makeExpr(d, b) + ")"; },
// Uneval needs more testing than it will get accidentally. No cat() because I don't want uneval clobbered (assigned to) accidentally.
function(d, b) { return "(uneval(" + makeExpr(d, b) + "))"; },
// Constructors. No cat() because I don't want to screw with the constructors themselves, just call them.
function(d, b) { return "new " + rndElt(constructors) + "(" + makeActualArgList(d, b) + ")"; },
function(d, b) { return rndElt(constructors) + "(" + makeActualArgList(d, b) + ")"; },
// Turn on gczeal in the middle of something
function(d, b) { return "gczeal(" + makeZealLevel() + ")"; },
// Unary Math functions
function (d, b) { return "Math." + rndElt(["abs", "acos", "asin", "atan", "ceil", "cos", "exp", "floor", "log", "round", "sin", "sqrt", "tan"]) + "(" + makeExpr(d, b) + ")"; },
// Binary Math functions
function (d, b) { return "Math." + rndElt(["atan2", "max", "min", "pow"]) + "(" + makeExpr(d, b) + ", " + makeExpr(d, b) + ")"; },
// Gecko wrappers
function(d, b) { return "new XPCNativeWrapper(" + makeExpr(d, b) + ")"; },
function(d, b) { return "new XPCSafeJSObjectWrapper(" + makeExpr(d, b) + ")"; },
// Harmony proxy creation: object, function without constructTrap, function with constructTrap
function(d, b) { return makeId(d, b) + " = " + "Proxy.create(" + makeProxyHandler(d, b) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return makeId(d, b) + " = " + "Proxy.createFunction(" + makeProxyHandler(d, b) + ", " + makeFunction(d, b) + ")"; },
function(d, b) { return makeId(d, b) + " = " + "Proxy.createFunction(" + makeProxyHandler(d, b) + ", " + makeFunction(d, b) + ", " + makeFunction(d, b) + ")"; },
function(d, b) { return cat(["delete", " ", makeId(d, b), ".", makeId(d, b)]); },
];
// In addition, can always use "undefined" or makeFunction
// Forwarding proxy code based on http://wiki.ecmascript.org/doku.php?id=harmony:proxies "Example: a no-op forwarding proxy"
// The letter 'x' is special.
var proxyHandlerProperties = {
getOwnPropertyDescriptor: {
empty: "function(){}",
forward: "function(name) { var desc = Object.getOwnPropertyDescriptor(x); desc.configurable = true; return desc; }"
},
getPropertyDescriptor: {
empty: "function(){}",
forward: "function(name) { var desc = Object.getPropertyDescriptor(x); desc.configurable = true; return desc; }"
},
defineProperty: {
empty: "function(){}",
forward: "function(name, desc) { Object.defineProperty(x, name, desc); }"
},
getOwnPropertyNames: {
empty: "function() { return []; }",
forward: "function() { return Object.getOwnPropertyNames(x); }"
},
delete: {
empty: "function() { return true; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return delete x[name]; }"
},
fix: {
empty: "function() { return []; }",
yes: "function() { return []; }",
no: "function() { }",
forward: "function() { if (Object.isFrozen(x)) { return Object.getOwnProperties(x); } }"
},
has: {
empty: "function() { return false; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return name in x; }"
},
hasOwn: {
empty: "function() { return false; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return Object.prototype.hasOwnProperty.call(x, name); }"
},
get: {
empty: "function() { return undefined }",
forward: "function(receiver, name) { return x[name]; }",
bind: "function(receiver, name) { var prop = x[name]; return (typeof prop) === 'function' ? prop.bind(x) : prop; }"
},
set: {
empty: "function() { return true; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(receiver, name, val) { x[name] = val; return true; }"
},
iterate: {
empty: "function() { return (function() { throw StopIteration; }); }",
forward: "function() { return (function() { for (var name in x) { yield name; } })(); }"
},
enumerate: {
empty: "function() { return []; }",
forward: "function() { var result = []; for (var name in x) { result.push(name); }; return result; }"
},
enumerateOwn: {
empty: "function() { return []; }",
forward: "function() { return Object.keys(x); }"
}
}
function makeProxyHandlerFactory(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
try { // in case we screwed Object.prototype, breaking proxyHandlerProperties
var preferred = rndElt(["empty", "forward", "yes", "no", "bind"]);
var fallback = rndElt(["empty", "forward"]);
var fidelity = 1; // Math.random();
var handlerFactoryText = "(function handlerFactory(x) {";
handlerFactoryText += "return {"
if (rnd(2)) {
// handlerFactory has an argument 'x'
bp = b.concat(['x']);
} else {
// handlerFactory has no argument
handlerFactoryText = handlerFactoryText.replace(/x/, "");
bp = b;
}
for (var p in proxyHandlerProperties) {
var funText;
if (preferred[p] && Math.random() < fidelity) {
funText = proxyMunge(proxyHandlerProperties[p][preferred], p);
} else {
switch(rnd(7)) {
case 0: funText = makeFunction(d - 3, bp); break;
case 1: funText = "undefined"; break;
default: funText = proxyMunge(proxyHandlerProperties[p][fallback], p);
}
}
handlerFactoryText += p + ": " + funText + ", ";
}
handlerFactoryText += "}; })"
return handlerFactoryText;
} catch(e) {
return "({/* :( */})";
}
}
function proxyMunge(funText, p)
{
funText = funText.replace(/\{/, "{ var yum = 'PCAL'; dumpln(yum + 'LED: " + p + "');");
return funText;
}
function makeProxyHandler(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return makeProxyHandlerFactory(d, b) + "(" + makeExpr(d - 1, b) + ")"
}
function makeShapeyConstructor(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var argName = uniqueVarName();
var t = rnd(4) ? "this" : argName;
var funText = "function shapeyConstructor(" + argName + "){";
var bp = b.concat([argName]);
var nPropNames = rnd(6) + 1;
var propNames = [];
for (var i = 0; i < nPropNames; ++i) {
propNames[i] = makeNewId(d, b);
}
var nStatements = rnd(11);
for (var i = 0; i < nStatements; ++i) {
var propName = rndElt(propNames);
if (rnd(5) == 0) {
funText += "if (" + (rnd(2) ? argName : makeExpr(d, bp)) + ") ";
}
switch(rnd(7)) {
case 0: funText += "delete " + t + "." + propName + ";"; break;
case 1: funText += "Object.defineProperty(" + t + ", " + uneval(propName) + ", " + makePropertyDescriptor(d, bp) + ");"; break;
case 2: funText += "{ " + makeStatement(d, bp) + " } "; break;
case 3: funText += t + "." + propName + " = " + makeExpr(d, bp) + ";"; break;
case 4: funText += t + "." + propName + " = " + makeFunction(d, bp) + ";"; break;
case 5: funText += "for (var ytq" + uniqueVarName() + " in " + t + ") { }"; break;
default: funText += t + "." + propName + " = " + makeShapeyValue(d, bp) + ";"; break;
}
}
funText += "return " + t + "; }";
return funText;
}
function makeShapeyConstructorLoop(d, b)
{
var a = makeMixedTypeArray(d, b);
var v = makeNewId(d, b);
var v2 = uniqueVarName(d, b);
var bvv = b.concat([v, v2]);
return makeShapeyConstructor(d - 1, b) +
"/*tLoopC*/for each (let " + v + " in " + a + ") { " +
"try{" +
"let " + v2 + " = " + rndElt(["new ", ""]) + "shapeyConstructor(" + v + "); print('EETT'); " +
//"print(uneval(" + v2 + "));" +
makeStatement(d - 2, bvv) +
"}catch(e){print('TTEE ' + e); }" +
" }";
}
function makePropertyDescriptor(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var s = "({"
switch(rnd(3)) {
case 0:
// Data descriptor. Can have 'value' and 'writable'.
if (rnd(2)) s += "value: " + makeExpr(d, b) + ", ";
if (rnd(2)) s += "writable: " + makeBoolean(d, b) + ", ";
break;
case 1:
// Accessor descriptor. Can have 'get' and 'set'.
if (rnd(2)) s += "get: " + makeFunction(d, b) + ", ";
if (rnd(2)) s += "set: " + makeFunction(d, b) + ", ";
break;
default:
}
if (rnd(2)) s += "configurable: " + makeBoolean(d, b) + ", ";
if (rnd(2)) s += "enumerable: " + makeBoolean(d, b) + ", ";
// remove trailing comma
if (s.length > 2)
s = s.substr(0, s.length - 2)
s += "})";
return s;
}
function makeBoolean(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(10) == 0) return makeExpr(d - 2, b);
return rndElt(["true", "false"]);
}
function makeZealLevel()
{
// gczeal is really slow, so only turn it on very occasionally.
switch(rnd(100)) {
case 0:
return "2";
case 1:
return "1";
default:
return "0";
}
}
if (haveE4X) {
exprMakers = exprMakers.concat([
// XML filtering predicate operator! It isn't lexed specially; there can be a space between the dot and the lparen.
function(d, b) { return cat([makeId(d, b), ".", "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat([makeE4X(d, b), ".", "(", makeExpr(d, b), ")"]); },
]);
}
var constructors = [
"Error", "RangeError", "Exception",
"Function", "RegExp", "String", "Array", "Object", "Number", "Boolean",
// "Date", // commented out due to appearing "random, but XXX want to use it sometimes...
"Iterator",
// E4X
"Namespace", "QName", "XML", "XMLList",
"AttributeName" // not listed as a constructor in e4x spec, but exists!
];
function maybeSharpDecl()
{
if (rnd(3) == 0)
return cat(["#", "" + (rnd(3)), "="]);
else
return "";
}
function makeObjLiteralPart(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(8))
{
// Old-style literal getter/setter
case 0: return cat([makeId(d, b), " getter: ", makeFunction(d, b)]);
case 1: return cat([makeId(d, b), " setter: ", makeFunction(d, b)]);
// New-style literal getter/setter
case 2: return cat([" get ", makeId(d, b), maybeName(d, b), "(", makeFormalArgList(d - 1, b), ")", makeFunctionBody(d, b)]);
case 3: return cat([" set ", makeId(d, b), maybeName(d, b), "(", makeFormalArgList(d - 1, b), ")", makeFunctionBody(d, b)]);
/*
case 3: return cat(["toString: ", makeFunction(d, b), "}", ")"]);
case 4: return cat(["toString: function() { return this; } }", ")"]); }, // bwahaha
case 5: return cat(["toString: function() { return " + makeExpr(d, b) + "; } }", ")"]); },
case 6: return cat(["valueOf: ", makeFunction(d, b), "}", ")"]); },
case 7: return cat(["valueOf: function() { return " + makeExpr(d, b) + "; } }", ")"]); },
*/
// Note that string literals, integer literals, and float literals are also good!
// (See https://bugzilla.mozilla.org/show_bug.cgi?id=520696.)
default: return cat([makeId(d, b), ": ", makeExpr(d, b)]);
}
}
function makeFunction(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if(rnd(5) == 1)
return makeExpr(d, b);
return (rndElt(functionMakers))(d, b);
}
function makeFunPrefix(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(20)) {
// Leaving this stuff out until bug 381203 is fixed.
// Eventually this stuff should be moved from functionMakers to somewhere
// like statementMakers, right?
// case 0: return "getter ";
// case 1: return "setter ";
default: return "";
}
}
function maybeName(d, b)
{
if (rnd(2) == 0)
return " " + makeId(d, b) + " ";
else
return "";
}
function makeFunctionBody(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(4)) {
case 0: return cat([" { ", makeStatement(d - 1, b), " } "]);
case 1: return cat([" { ", "return ", makeExpr(d, b), " } "]);
case 2: return cat([" { ", "yield ", makeExpr(d, b), " } "]);
default: return makeExpr(d, b); // make an "expression closure"
}
}
var functionMakers = [
// Note that a function with a name is sometimes considered a statement rather than an expression.
// Functions and expression closures
function(d, b) { var v = makeNewId(d, b); return cat([makeFunPrefix(d, b), "function", " ", maybeName(d, b), "(", v, ")", makeFunctionBody(d, b.concat([v]))]); },
function(d, b) { return cat([makeFunPrefix(d, b), "function", " ", maybeName(d, b), "(", makeFormalArgList(d, b), ")", makeFunctionBody(d, b)]); },
// Methods
function(d, b) { return cat([makeExpr(d, b), ".", rndElt(objectMethods)]); },
// The identity function
function(d, b) { return "function(q) { return q; }" },
// A function that does something
function(d, b) { return "function(y) { " + makeStatement(d, b.concat(["y"])) + " }" },
// A function that computes something
function(d, b) { return "function(y) { return " + makeExpr(d, b.concat(["y"])) + " }" },
// A generator that does something
function(d, b) { return "function(y) { yield y; " + makeStatement(d, b.concat(["y"])) + "; yield y; }" },
// A generator expression -- kinda a function??
function(d, b) { return "(1 for (x in []))"; },
// A simple wrapping pattern
function(d, b) { return "/*wrap1*/(function(){ " + makeStatement(d, b) + "return " + makeFunction(d, b) + "})()" },
// Wrapping with upvar: escaping, may or may not be modified
function(d, b) { var v1 = uniqueVarName(); var v2 = uniqueVarName(); return "/*wrap2*/(function(){ var " + v1 + " = " + makeExpr(d, b) + "; var " + v2 + " = " + makeFunction(d, b.concat([v1])) + "; return " + v2 + ";})()"; },
// Wrapping with upvar: non-escaping
function(d, b) { var v1 = uniqueVarName(); var v2 = uniqueVarName(); return "/*wrap3*/(function(){ var " + v1 + " = " + makeExpr(d, b) + "; (" + makeFunction(d, b.concat([v1])) + ")(); })"; },
// Bind
function(d, b) { return "Function.prototype.bind" },
function(d, b) { return "(" + makeFunction(d-1, b) + ").bind" },
function(d, b) { return "(" + makeFunction(d-1, b) + ").bind(" + makeActualArgList(d, b) + ")" },
// Special functions that might have interesting results, especially when called "directly" by things like string.replace or array.map.
function(d, b) { return "eval" }, // eval is interesting both for its "no indirect calls" feature and for the way it's implemented in spidermonkey (a special bytecode).
function(d, b) { return "(let (e=eval) e)" },
function(d, b) { return "new Function" }, // this won't be interpreted the same way for each caller of makeFunction, but that's ok
function(d, b) { return "(new Function(" + uneval(makeStatement(d, b)) + "))"; },
function(d, b) { return "Function" }, // without "new"! it does seem to work...
function(d, b) { return "gc" },
function(d, b) { return "Object.defineProperty" },
function(d, b) { return "Object.defineProperties" },
function(d, b) { return "Object.create" },
function(d, b) { return "Object.getOwnPropertyDescriptor" },
function(d, b) { return "Object.getOwnPropertyNames" },
function(d, b) { return "Object.getPrototypeOf" },
function(d, b) { return "Object.keys" },
function(d, b) { return "Object.preventExtensions" },
function(d, b) { return "Object.seal" },
function(d, b) { return "Object.freeze" },
function(d, b) { return "decodeURI" },
function(d, b) { return "decodeURIComponent" },
function(d, b) { return "encodeURI" },
function(d, b) { return "encodeURIComponent" },
function(d, b) { return "Array.reduce" }, // also known as Array.prototype.reduce
function(d, b) { return "Array.isArray" },
function(d, b) { return "JSON.parse" },
function(d, b) { return "JSON.stringify" }, // has interesting arguments...
function(d, b) { return "Math.sin" },
function(d, b) { return "Math.pow" },
function(d, b) { return "/a/gi" }, // in Firefox, at least, regular expressions can be used as functions: e.g. "hahaa".replace(/a+/g, /aa/g) is "hnullhaa"!
function(d, b) { return "XPCNativeWrapper" },
function(d, b) { return "XPCSafeJSObjectWrapper" },
function(d, b) { return "WebGLIntArray" },
function(d, b) { return "WebGLFloatArray" },
function(d, b) { return "Int8Array" },
function(d, b) { return "Uint8Array" },
function(d, b) { return "Int16Array" },
function(d, b) { return "Uint16Array" },
function(d, b) { return "Int32Array" },
function(d, b) { return "Uint32Array" },
function(d, b) { return "Float32Array" },
function(d, b) { return "Float64Array" },
function(d, b) { return "Uint8ClampedArray" },
function(d, b) { return "ArrayBuffer" },
function(d, b) { return "Proxy.isTrapping" },
function(d, b) { return "Proxy.create" },
function(d, b) { return "Proxy.createFunction" },
function(d, b) { return "wrap" }, // spidermonkey shell shortcut for a native forwarding proxy
function(d, b) { return makeProxyHandlerFactory(d, b); },
function(d, b) { return makeShapeyConstructor(d, b); },
];
/*
David Anderson suggested creating the following recursive structures:
- recurse down an array of mixed types, car cdr kinda thing
- multiple recursive calls in a function, like binary search left/right, sometimes calls neither and sometimes calls both
the recursion support in spidermonkey only works with self-recursion.
that is, two functions that call each other recursively will not be traced.
two trees are formed, going down and going up.
type instability matters on both sides.
so the values returned from the function calls matter.
so far, what i've thought of means recursing from the top of a function and if..else.
but i'd probably also want to recurse from other points, e.g. loops.
special code for tail recursion likely coming soon, but possibly as a separate patch, because it requires changes to the interpreter.
*/
// "@" indicates a point at which a statement can be inserted. XXX allow use of variables, as consts
// variable names will be replaced, and should be uppercase to reduce the chance of matching things they shouldn't.
// take care to ensure infinite recursion never occurs unexpectedly, especially with doubly-recursive functions.
var recursiveFunctions = [
{
// Unless the recursive call is in the tail position, this will throw.
text: "(function too_much_recursion(depth) { @; if (depth > 0) { @; too_much_recursion(depth - 1); } @ })",
vars: ["depth"],
args: function(d, b) { return rnd(10000); },
test: function(f) { try { f(5000); } catch(e) { } return true; }
},
{
text: "(function factorial(N) { @; if (N == 0) return 1; @; return N * factorial(N - 1); @ })",
vars: ["N"],
args: function(d, b) { return "" + rnd(20); },
test: function(f) { return f(10) == 3628800; }
},
{
text: "(function factorial_tail(N, Acc) { @; if (N == 0) { @; return Acc; } @; return factorial_tail(N - 1, Acc * N); @ })",
vars: ["N", "Acc"],
args: function(d, b) { return rnd(20) + ", 1"; },
test: function(f) { return f(10, 1) == 3628800; }
},
{
// two recursive calls
text: "(function fibonacci(N) { @; if (N <= 1) { @; return 1; } @; return fibonacci(N - 1) + fibonacci(N - 2); @ })",
vars: ["N"],
args: function(d, b) { return "" + rnd(8); },
test: function(f) { return f(6) == 13; }
},
{
// do *anything* while indexing over mixed-type arrays
text: "(function a_indexing(array, start) { @; if (array.length == start) { @; return EXPR1; } var thisitem = array[start]; var recval = a_indexing(array, start + 1); STATEMENT1 })",
vars: ["array", "start", "thisitem", "recval"],
args: function(d, b) { return makeMixedTypeArray(d-1, b) + ", 0"; },
testSub: function(text) { return text.replace(/EXPR1/, "0").replace(/STATEMENT1/, "return thisitem + recval;"); },
randSub: function(text, varMap, d, b) {
var expr1 = makeExpr(d, b.concat([varMap["array"], varMap["start"]]));
var statement1 = rnd(2) ?
makeStatement(d, b.concat([varMap["thisitem"], varMap["recval"]])) :
"return " + makeExpr(d, b.concat([varMap["thisitem"], varMap["recval"]])) + ";";
return (text.replace(/EXPR1/, expr1)
.replace(/STATEMENT1/, statement1)
); },
test: function(f) { return f([1,2,3,"4",5,6,7], 0) == "123418"; }
},
{
// this lets us play a little with mixed-type arrays
text: "(function sum_indexing(array, start) { @; return array.length == start ? 0 : array[start] + sum_indexing(array, start + 1); })",
vars: ["array", "start"],
args: function(d, b) { return makeMixedTypeArray(d-1, b) + ", 0"; },
test: function(f) { return f([1,2,3,"4",5,6,7], 0) == "123418"; }
},
{
text: "(function sum_slicing(array) { @; return array.length == 0 ? 0 : array[0] + sum_slicing(array.slice(1)); })",
vars: ["array"],
args: function(d, b) { return makeMixedTypeArray(d-1, b); },
test: function(f) { return f([1,2,3,"4",5,6,7]) == "123418"; }
}
];
(function testAllRecursiveFunctions() {
for (var i = 0; i < recursiveFunctions.length; ++i) {
var a = recursiveFunctions[i];
var text = a.text;
if (a.testSub) text = a.testSub(text);
var f = eval(text.replace(/@/g, ""))
if (!a.test(f))
throw "Failed test of: " + a.text;
}
})();
function makeImmediateRecursiveCall(d, b, cheat1, cheat2)
{
if (rnd(10) != 0)
return "(4277)";
var a = (cheat1 == null) ? rndElt(recursiveFunctions) : recursiveFunctions[cheat1];
var s = a.text;
var varMap = {};
for (var i = 0; i < a.vars.length; ++i) {
var prettyName = a.vars[i];
varMap[prettyName] = uniqueVarName();
s = s.replace(new RegExp(prettyName, "g"), varMap[prettyName]);
}
var actualArgs = cheat2 == null ? a.args(d, b) : cheat2;
s = s + "(" + actualArgs + ")";
s = s.replace(/@/g, function() { if (rnd(4) == 0) return makeStatement(d-2, b); return ""; });
if (a.randSub) s = a.randSub(s, varMap, d, b);
s = "(" + s + ")";
return s;
}
function makeLetHead(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var items = (d > 0 || rnd(2) == 0) ? rnd(10) + 1 : 1;
var result = "";
for (var i = 0; i < items; ++i) {
if (i > 0)
result += ", ";
result += makeLetHeadItem(d - i, b);
}
return result;
}
function makeLetHeadItem(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (d < 0 || rnd(2) == 0)
return rnd(2) ? uniqueVarName() : makeId(d, b);
else if (rnd(5) == 0)
return makeDestructuringLValue(d, b) + " = " + makeExpr(d, b);
else
return makeId(d, b) + " = " + makeExpr(d, b);
}
function makeActualArgList(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var nArgs = rnd(3);
if (nArgs == 0)
return "";
var argList = makeExpr(d, b);
for (var i = 1; i < nArgs; ++i)
argList += ", " + makeExpr(d - i, b);
return argList;
}
function makeFormalArgList(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var nArgs = rnd(3);
if (nArgs == 0)
return "";
var argList = makeFormalArg(d, b)
for (var i = 1; i < nArgs; ++i)
argList += ", " + makeFormalArg(d - i, b);
return argList;
}
function makeFormalArg(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(4) == 1)
return makeDestructuringLValue(d, b);
return makeId(d, b);
}
function makeNewId(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return rndElt(["a", "b", "c", "d", "e", "w", "x", "y", "z"]);
}
function makeId(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(3) == 1 && b.length)
return rndElt(b);
switch(rnd(200))
{
case 0:
return makeTerm(d, b);
case 1:
return makeExpr(d, b);
case 2: case 3: case 4: case 5:
return makeLValue(d, b);
case 6: case 7:
return makeDestructuringLValue(d, b);
case 8: case 9: case 10:
// some keywords that can be used as identifiers in some contexts (e.g. variables, function names, argument names)
// but that's annoying, and some of these cause lots of syntax errors.
return rndElt(["get", "set", "getter", "setter", "delete", "let", "yield", "each", "xml", "namespace"]);
case 11:
return "function::" + makeId(d, b);
case 12: case 13:
return "this." + makeId(d, b);
case 14:
return "x::" + makeId(d, b);
case 15: case 16:
return makeNamespacePrefix(d - 1, b) + makeSpecialProperty(d - 1, b);
case 17: case 18:
return makeNamespacePrefix(d - 1, b) + makeId(d - 1, b);
case 19:
return " "; // [k, v] becomes [, v] -- test how holes are handled in unexpected destructuring
case 20:
return "this";
}
return rndElt(["a", "b", "c", "d", "e", "w", "x", "y", "z",
"window", "eval", "\u3056", "NaN",
// "valueOf", "toString", // e.g. valueOf getter :P // bug 381242, etc
"functional", // perhaps decompiler code looks for "function"?
]);
// window is a const (in the browser), so some attempts to redeclare it will cause errors
// eval is interesting because it cannot be called indirectly. and maybe also because it has its own opcode in jsopcode.tbl.
// but bad things happen if you have "eval setter"... so let's not put eval in this list.
}
function makeComprehension(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d < 0)
return "";
switch(rnd(5)) {
case 0:
return "";
case 1:
return cat([" for ", "(", makeForInLHS(d, b), " in ", makeExpr(d - 2, b), ")"]) + makeComprehension(d - 1, b);
case 2:
return cat([" for ", "each ", "(", makeId(d, b), " in ", makeExpr(d - 2, b), ")"]) + makeComprehension(d - 1, b);
case 3:
return cat([" for ", "each ", "(", makeId(d, b), " in ", makeMixedTypeArray(d - 2, b), ")"]) + makeComprehension(d - 1, b);
default:
return cat([" if ", "(", makeExpr(d - 2, b), ")"]); // this is always last (and must be preceded by a "for", oh well)
}
}
// for..in LHS can be a single variable OR it can be a destructuring array of exactly two elements.
function makeForInLHS(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// JS 1.7 only (removed in JS 1.8)
//
// if (version() == 170 && rnd(4) == 0)
// return cat(["[", makeLValue(d, b), ", ", makeLValue(d, b), "]"]);
return makeLValue(d, b);
}
function makeLValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0 || (rnd(2) == 1))
return makeId(d - 1, b);
d = rnd(d);
return (rndElt(lvalueMakers))(d, b);
}
var lvalueMakers = [
// Simple variable names :)
function(d, b) { return cat([makeId(d, b)]); },
// Destructuring
function(d, b) { return makeDestructuringLValue(d, b); },
function(d, b) { return "(" + makeDestructuringLValue(d, b) + ")"; },
// Properties
function(d, b) { return cat([makeId(d, b), ".", makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), "[", "'", makeId(d, b), "'", "]"]); },
// Special properties
function(d, b) { return cat([makeId(d, b), ".", makeSpecialProperty(d, b)]); },
// Certain functions can act as lvalues! See JS_HAS_LVALUE_RETURN in js engine source.
function(d, b) { return cat([makeId(d, b), "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "(", makeExpr(d, b), ")"]); },
// Parenthesized lvalues can cause problems ;)
function(d, b) { return cat(["(", makeLValue(d, b), ")"]); },
function(d, b) { return makeExpr(d, b); } // intentionally bogus, but not quite garbage.
];
function makeDestructuringLValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (d < 0 || rnd(4) == 1)
return makeId(d, b);
if (rnd(6) == 1)
return makeLValue(d, b);
return (rndElt(destructuringLValueMakers))(d, b);
}
var destructuringLValueMakers = [
// destructuring assignment: arrays
function(d, b)
{
var len = rnd(d, b);
if (len == 0)
return "[]";
var Ti = [];
Ti.push("[");
Ti.push(maybeMakeDestructuringLValue(d, b));
for (var i = 1; i < len; ++i) {
Ti.push(", ");
Ti.push(maybeMakeDestructuringLValue(d, b));
}
Ti.push("]");
return cat(Ti);
},
// destructuring assignment: objects
function(d, b)
{
var len = rnd(d, b);
if (len == 0)
return "{}";
var Ti = [];
Ti.push("{");
for (var i = 0; i < len; ++i) {
if (i > 0)
Ti.push(", ");
Ti.push(makeId(d, b));
if (rnd(3)) {
Ti.push(": ");
Ti.push(makeDestructuringLValue(d, b));
} // else, this is a shorthand destructuring, treated as "id: id".
}
Ti.push("}");
return cat(Ti);
}
];
// Allow "holes".
function maybeMakeDestructuringLValue(d, b)
{
if (rnd(2) == 0)
return ""
return makeDestructuringLValue(d, b)
}
function makeTerm(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return (rndElt(termMakers))(d, b);
}
var termMakers = [
// Variable names
function(d, b) { return makeId(d, b); },
// Simple literals (no recursion required to make them)
function(d, b) { return rndElt([
// Arrays
"[]", "[1]", "[[]]", "[[1]]", "[,]", "[,,]", "[1,,]",
// Objects
"{}", "({})", "({a1:1})",
// Possibly-destructuring arrays
"[z1]", "[z1,,]", "[,,z1]",
// Possibly-destructuring objects
"({a2:z2})",
// Sharp use
"#1#",
// Sharp creation and use
"#1=[#1#]", "#3={a:#3#}",
"function(id) { return id }",
"function ([y]) { }",
"(function ([y]) { })()",
"arguments",
"Math",
"this",
"length"
]);
},
function(d, b) { return rndElt([ "0.1", ".2", "3", "1.3", "4.", "5.0000000000000000000000", "1.2e3", "1e81", "1e+81", "1e-81", "1e4", "0", "-0", "(-0)", "-1", "(-1)", "0x99", "033", (""+Math.PI), "3/0", "-3/0", "0/0"
// these are commented out due to bug 379294
// "0x2D413CCC", "0x5a827999", "0xB504F332", "(0x50505050 >> 1)"
]); },
function(d, b) { return rndElt([ "true", "false", "undefined", "null"]); },
function(d, b) { return rndElt([ "this", "window" ]); },
function(d, b) { return rndElt([" \"\" ", " '' "]) },
randomUnitStringLiteral,
function(d, b) { return rndElt([" /x/ ", " /x/g "]) },
];
function randomUnitStringLiteral()
{
var s = "\"\\u";
var nDigits = rnd(6) + 1;
for (var i = 0; i < nDigits; ++i) {
s += "0123456789ABCDEF".charAt(rnd(16));
}
s += "\""
return s;
}
if (haveE4X) {
// E4X literals
termMakers = termMakers.concat([
function(d, b) { return rndElt([ "<x/>", "<y><z/></y>"]); },
function(d, b) { return rndElt([ "@foo" /* makes sense in filtering predicates, at least... */, "*", "*::*"]); },
function(d, b) { return makeE4X(d, b) }, // xml
function(d, b) { return cat(["<", ">", makeE4X(d, b), "<", "/", ">"]); }, // xml list
]);
}
function maybeMakeTerm(d, b)
{
if (rnd(2))
return makeTerm(d - 1, b);
else
return "";
}
function makeCrazyToken()
{
if (rnd(2) == 0) {
// This can be more aggressive once bug 368694 is fixed.
return String.fromCharCode(32 + rnd(128 - 32));
}
return rndElt([
// Some of this is from reading jsscan.h.
// Comments; comments hiding line breaks.
"//", UNTERMINATED_COMMENT, (UNTERMINATED_COMMENT + "\n"), "/*\n*/",
// groupers (which will usually be unmatched if they come from here ;)
"[", "]",
"{", "}",
"(", ")",
// a few operators
"!", "@", "%", "^", "*", "|", ":", "?", "'", "\"", ",", ".", "/",
"~", "_", "+", "=", "-", "++", "--", "+=", "%=", "|=", "-=",
"#", "#1", "#1=", // usually an "invalid character", but used as sharps too
// most real keywords plus a few reserved keywords
" in ", " instanceof ", " let ", " new ", " get ", " for ", " if ", " else ", " else if ", " try ", " catch ", " finally ", " export ", " import ", " void ", " with ",
" default ", " goto ", " case ", " switch ", " do ", " /*infloop*/while ", " return ", " yield ", " break ", " continue ", " typeof ", " var ", " const ",
// several keywords can be used as identifiers. these are just a few of them.
" enum ", // JS_HAS_RESERVED_ECMA_KEYWORDS
" debugger ", // JS_HAS_DEBUGGER_KEYWORD
" super ", // TOK_PRIMARY!
" this ", // TOK_PRIMARY!
" null ", // TOK_PRIMARY!
" undefined ", // not a keyword, but a default part of the global object
"\n", // trigger semicolon insertion, also acts as whitespace where it might not be expected
"\r",
"\u2028", // LINE_SEPARATOR?
"\u2029", // PARA_SEPARATOR?
"<" + "!" + "--", // beginning of HTML-style to-end-of-line comment (!)
"--" + ">", // end of HTML-style comment
"",
"\0", // confuse anything that tries to guess where a string ends. but note: "illegal character"!
]);
}
function makeE4X(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0)
return cat(["<", "x", ">", "<", "y", "/", ">", "<", "/", "x", ">"]);
d = d - 1;
var y = [
function(d, b) { return '<employee id="1"><name>Joe</name><age>20</age></employee>' },
function(d, b) { return cat(["<", ">", makeSubE4X(d, b), "<", "/", ">"]); }, // xml list
function(d, b) { return cat(["<", ">", makeExpr(d, b), "<", "/", ">"]); }, // bogus or text
function(d, b) { return cat(["<", "zzz", ">", makeExpr(d, b), "<", "/", "zzz", ">"]); }, // bogus or text
// mimic parts of this example at a time, from the e4x spec: <x><{tagname} {attributename}={attributevalue+attributevalue}>{content}</{tagname}></x>;
function(d, b) { var tagId = makeId(d, b); return cat(["<", "{", tagId, "}", ">", makeSubE4X(d, b), "<", "/", "{", tagId, "}", ">"]); },
function(d, b) { var attrId = makeId(d, b); var attrValExpr = makeExpr(d, b); return cat(["<", "yyy", " ", "{", attrId, "}", "=", "{", attrValExpr, "}", " ", "/", ">"]); },
function(d, b) { var contentId = makeId(d, b); return cat(["<", "yyy", ">", "{", contentId, "}", "<", "/", "yyy", ">"]); },
// namespace stuff
function(d, b) { var contentId = makeId(d, b); return cat(['<', 'bbb', ' ', 'xmlns', '=', '"', makeExpr(d, b), '"', '>', makeSubE4X(d, b), '<', '/', 'bbb', '>']); },
function(d, b) { var contentId = makeId(d, b); return cat(['<', 'bbb', ' ', 'xmlns', ':', 'ccc', '=', '"', makeExpr(d, b), '"', '>', '<', 'ccc', ':', 'eee', '>', '<', '/', 'ccc', ':', 'eee', '>', '<', '/', 'bbb', '>']); },
function(d, b) { return makeExpr(d, b); },
function(d, b) { return makeSubE4X(d, b); }, // naked cdata things, etc.
]
return (rndElt(y))(d, b);
}
function makeSubE4X(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// Bug 380431
// if (rnd(8) == 0)
// return "<" + "!" + "[" + "CDATA[" + makeExpr(depth - 1) + "]" + "]" + ">"
if (d < -2)
return "";
var y = [
function(d, b) { return cat(["<", "ccc", ":", "ddd", ">", makeSubE4X(d - 1, b), "<", "/", "ccc", ":", "ddd", ">"]); },
function(d, b) { return makeE4X(d, b) + makeSubE4X(d - 1, b); },
function(d, b) { return "yyy"; },
function(d, b) { return cat(["<", "!", "--", "yy", "--", ">"]); }, // XML comment
// Bug 380431
// function(depth) { return cat(["<", "!", "[", "CDATA", "[", "zz", "]", "]", ">"]); }, // XML cdata section
function(d, b) { return " "; },
function(d, b) { return ""; },
];
return (rndElt(y))(d, b);
}
function makeShapeyValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(10) == 0)
return makeExpr(d, b);
var a = [
// Numbers and number-like things
[
"0", "1", "2", "3", "0.1", ".2", "1.3", "4.", "5.0000000000000000000000",
"1.2e3", "1e81", "1e+81", "1e-81", "1e4", "-0", "(-0)",
"-1", "(-1)", "0x99", "033", "3/0", "-3/0", "0/0",
"Math.PI",
"0x2D413CCC", "0x5a827999", "0xB504F332", "-0x2D413CCC", "-0x5a827999", "-0xB504F332", "0x50505050", "(0x50505050 >> 1)",
// various powers of two, with values near JSVAL_INT_MAX especially tested
"0x10000000", "0x20000000", "0x3FFFFFFE", "0x3FFFFFFF", "0x40000000", "0x40000001", "0x80000000", "-0x80000000",
],
// Special numbers
[ "(1/0)", "(-1/0)", "(0/0)" ],
// String literals
[" \"\" ", " '' ", " 'A' ", " '\\0' "],
// Regular expression literals
[ " /x/ ", " /x/g "],
// Booleans
[ "true", "false" ],
// Undefined and null
[ "(void 0)", "null" ],
// Object literals
[ "[]", "[1]", "[(void 0)]", "{}", "{x:3}", "({})", "({x:3})" ],
// Variables that really should have been constants in the ecmascript spec
[ "NaN", "Infinity", "-Infinity", "undefined"],
// Boxed booleans
[ "new Boolean(true)", "new Boolean(false)" ],
// Boxed numbers
[ "new Number(1)", "new Number(1.5)" ],
// Boxed strings
[ "new String('')", "new String('q')" ],
// Fun stuff
[ "function(){}"],
["{}", "[]", "[1]", "['z']", "[undefined]", "this", "eval", "arguments" ],
// Actual variables (slightly dangerous)
[ b.length ? rndElt(b) : "x" ]
];
return rndElt(rndElt(a));
}
function makeMixedTypeArray(d, b)
{
// Pick two to five of those
var q = rnd(4) + 2;
var picks = [];
for (var j = 0; j < q; ++j)
picks.push(makeShapeyValue(d, b));
// Make an array of up to 39 elements, containing those two to five values
var c = [];
var count = rnd(40);
for (var j = 0; j < count; ++j)
c.push(rndElt(picks));
return "[" + c.join(", ") + "]";
}
function strTimes(s, n)
{
if (n == 0) return "";
if (n == 1) return s;
var s2 = s + s;
var r = n % 2;
var d = (n - r) / 2;
var m = strTimes(s2, d);
return r ? m + s : m;
}
var count = 0;
var verbose = false;
var maxHeapCount = 0;
var sandbox = null;
//var nextTrapCode = null;
// https://bugzilla.mozilla.org/show_bug.cgi?id=394853#c19
//try { eval("/") } catch(e) { }
// Remember the number of countHeap.
tryItOut("");
/*
// Aggressive test for type-unstable arrays
count = 1;
for (var j = 0; j < 20000; ++j) {
x = null;
if (j % 100 == 0) gc();
var a = makeMixedTypeArray();
print(uneval(a));
var s = "for each (let i in " + a + ") { }";
//var s = "[i for each (i in " + a + ") if (i)]";
eval(s);
}
throw 1;
*/
/**************************************
* To reproduce a crash or assertion: *
**************************************/
// 1. grep tryIt LOGFILE | grep -v "function tryIt" | pbcopy
// 2. Paste the result between "ddbegin" and "ddend", replacing "start();"
// 3. Run Lithium to remove unnecessary lines between "ddbegin" and "ddend".
// SPLICE DDBEGIN
start();
// SPLICE DDEND
if (jsshell)
print("It's looking good!"); // Magic string that jsunhappy.py looks for
// 3. Run it.
| jsfunfuzz/jsfunfuzz.js | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is jsfunfuzz.
*
* The Initial Developer of the Original Code is
* Jesse Ruderman.
* Portions created by the Initial Developer are Copyright (C) 2006-2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gary Kwong
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//"use strict";
var jsStrictMode = false;
/********************
* ENGINE DETECTION *
********************/
// jsfunfuzz is best run in a command-line shell. It can also run in
// a web browser, but you might have trouble reproducing bugs that way.
var ENGINE_UNKNOWN = 0;
var ENGINE_SPIDERMONKEY_TRUNK = 1; // also 1.9.1 and tracemonkey branch
var ENGINE_SPIDERMONKEY_MOZ_1_9_0 = 2;
var ENGINE_JAVASCRIPTCORE = 4;
var engine = ENGINE_UNKNOWN;
var jsshell = (typeof window == "undefined");
var dump;
var dumpln;
var printImportant;
if (jsshell) {
dumpln = print;
printImportant = function(s) { dumpln("***"); dumpln(s); }
if (typeof line2pc == "function") {
if (typeof snarf == "function")
engine = ENGINE_SPIDERMONKEY_TRUNK;
else if (typeof countHeap == "function")
engine = ENGINE_SPIDERMONKEY_MOZ_1_9_0
version(180); // 170: make "yield" and "let" work. 180: sane for..in.
options("anonfunfix");
} else if (typeof XPCNativeWrapper == "function") {
engine = ENGINE_SPIDERMONKEY_TRUNK;
} else if (typeof debug == "function") {
engine = ENGINE_JAVASCRIPTCORE;
}
} else {
if (navigator.userAgent.indexOf("WebKit") != -1) {
engine = ENGINE_JAVASCRIPTCORE;
// This worked in Safari 3.0, but it might not work in Safari 3.1.
dump = function(s) { console.log(s); }
} else if (navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("rv:1.9.0") != -1) {
engine = ENGINE_SPIDERMONKEY_MOZ_1_9_0;
} else if (navigator.userAgent.indexOf("Gecko") != -1) {
engine = ENGINE_SPIDERMONKEY_TRUNK;
} else if (typeof dump != "function") {
// In other browsers, jsfunfuzz does not know how to log anything.
dump = function() { };
}
dumpln = function(s) { dump(s + "\n"); }
printImportant = function(s) {
dumpln(s);
var p = document.createElement("pre");
p.appendChild(document.createTextNode(s));
document.body.appendChild(p);
}
}
if (typeof gc == "undefined")
gc = function(){};
var haveUsefulDis = engine == ENGINE_SPIDERMONKEY_TRUNK && typeof dis == "function" && typeof dis(function(){}) == "string";
var haveE4X = (typeof XML == "function");
if (haveE4X)
XML.ignoreComments = false; // to make uneval saner -- see bug 465908
function simpleSource(s)
{
function hexify(c)
{
var code = c.charCodeAt(0);
var hex = code.toString(16);
while (hex.length < 4)
hex = "0" + hex;
return "\\u" + hex;
}
if (typeof s == "string")
return "\"" + s.replace(/\\/g, "\\\\")
.replace(/\"/g, "\\\"")
.replace(/\0/g, "\\0")
.replace(/\n/g, "\\n")
.replace(/[^ -~]/g, hexify) // not space (32) through tilde (126)
+ "\"";
else
return "" + s; // hope this is right ;) should work for numbers.
}
var haveRealUneval = (typeof uneval == "function");
if (!haveRealUneval)
uneval = simpleSource;
if (engine == ENGINE_UNKNOWN)
printImportant("Targeting an unknown JavaScript engine!");
else if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0)
printImportant("Targeting SpiderMonkey / Gecko (Mozilla 1.9.0 branch).");
else if (engine == ENGINE_SPIDERMONKEY_TRUNK)
printImportant("Targeting SpiderMonkey / Gecko (trunk).");
else if (engine == ENGINE_JAVASCRIPTCORE)
printImportant("Targeting JavaScriptCore / WebKit.");
function printAndStop(s)
{
printImportant(s)
if (jsshell) {
print("jsfunfuzz stopping due to above error!"); // Magic string that jsunhappy.py looks for
quit();
}
}
function errorToString(e)
{
try {
return ("" + e);
} catch (e2) {
return "Can't toString the error!!";
}
}
var jitEnabled = (engine == ENGINE_SPIDERMONKEY_TRUNK) && jsshell && options().indexOf("jit") != -1;
/***********************
* AVOIDING KNOWN BUGS *
***********************/
function whatToTestSpidermonkeyTrunk(code)
{
return {
allowParse: true,
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true,
// Exclude things here if decompiling returns something bogus that won't compile.
checkRecompiling: true
&& !( code.match( /\..*\@.*(this|null|false|true).*\:\:/ )) // avoid bug 381197
&& !( code.match( /arguments.*\:\:/ )) // avoid bug 355506
&& !( code.match( /\:.*for.*\(.*var.*\)/ )) // avoid bug 352921
&& !( code.match( /\:.*for.*\(.*let.*\)/ )) // avoid bug 352921
&& !( code.match( /for.*let.*\).*function/ )) // avoid bug 352735 (more rebracing stuff)
&& !( code.match( /for.*\(.*\(.*in.*;.*;.*\)/ )) // avoid bug 353255
&& !( code.match( /const.*arguments/ )) // avoid bug 355480
&& !( code.match( /var.*arguments/ )) // avoid bug 355480
&& !( code.match( /let.*arguments/ )) // avoid bug 355480
&& !( code.match( /let/ )) // avoid bug 462309 :( :( :(
&& !( code.match( /function.*\:.*arguments/ )) // avoid bug 496985
&& !( code.match( /\{.*\:.*\}.*\=.*/ ) && code.indexOf("const") != -1) // avoid bug 492010
&& !( code.match( /\{.*\:.*\}.*\=.*/ ) && code.indexOf("function") != -1) // avoid bug 492010
&& !( code.match( /if.*function/ ) && code.indexOf("const") != -1) // avoid bug 355980 *errors*
&& !( code.match( /switch.*default.*xml.*namespace/ )) // avoid bug 566616
&& !( code.match( /\#.*=/ )) // avoid bug 568734
,
// Exclude things here if decompiling returns something incorrect or non-canonical, but that will compile.
checkForMismatch: false // bug 539819
&& !( code.match( /const.*if/ )) // avoid bug 352985
&& !( code.match( /if.*const/ )) // avoid bug 352985
&& !( code.match( /with.*try.*function/ )) // avoid bug 418285
&& !( code.match( /if.*try.*function/ )) // avoid bug 418285
&& !( code.match( /\?.*\?/ )) // avoid bug 475895
&& !( code.match( /if.*function/ )) // avoid bug 355980 *changes*
&& !( code.match( /\=.*\:\:/ )) // avoid bug 504957
&& (code.indexOf("-0") == -1) // constant folding isn't perfect
&& (code.indexOf("-1") == -1) // constant folding isn't perfect
&& (code.indexOf("default") == -1) // avoid bug 355509
&& (code.indexOf("delete") == -1) // avoid bug 352027, which won't be fixed for a while :(
&& (code.indexOf("const") == -1) // avoid bug 352985 and bug 355480 :(
&& (code.indexOf("&&") == -1) // ignore bug 461226 with a hatchet
&& (code.indexOf("||") == -1) // ignore bug 461226 with a hatchet
// avoid bug 352085: keep operators that coerce to number (or integer)
// at constant-folding time (?) away from strings
&&
(
(code.indexOf("\"") == -1 && code.indexOf("\'") == -1)
||
(
(code.indexOf("%") == -1)
&& (code.indexOf("/") == -1)
&& (code.indexOf("*") == -1)
&& (code.indexOf("-") == -1)
&& (code.indexOf(">>") == -1)
&& (code.indexOf("<<") == -1)
)
)
,
// Exclude things here if the decompilation doesn't match what the function actually does
checkDisassembly: true
&& !( code.match( /\@.*\:\:/ )) // avoid bug 381197 harder than above
&& !( code.match( /for.*in.*for.*in/ )) // avoid bug 475985
,
checkForExtraParens: true
&& !code.match( /\(.*for.*\(.*in.*\).*\)/ ) // ignore bug 381213, and unfortunately anything with genexps
&& !code.match( /if.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /while.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /\?.*\=/) // ignore bug 475893
,
allowExec: unlikelyToHang(code)
&& code.indexOf("<>") == -1 // avoid bug 334628, hopefully
&& (jsshell || code.indexOf("nogeckoex") == -1)
,
allowIter: true,
checkUneval: false // bug 539819
// exclusions won't be perfect, since functions can return things they don't
// appear to contain, e.g. with "return x;"
&& (code.indexOf("<") == -1 || code.indexOf(".") == -1) // avoid bug 379525
&& (code.indexOf("<>") == -1) // avoid bug 334628
};
}
function whatToTestSpidermonkey190Branch(code)
{
return {
allowParse: true,
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true,
// Exclude things here if decompiling returns something bogus that won't compile.
checkRecompiling: true
&& (code.indexOf("#") == -1) // avoid bug 367731 (branch)
&& !( code.match( /\..*\@.*(this|null|false|true).*\:\:/ )) // avoid bug 381197 (branch)
&& !( code.match( /arguments.*\:\:/ )) // avoid bug 355506 (branch)
&& !( code.match( /\:.*for.*\(.*var.*\)/ )) // avoid bug 352921 (branch)
&& !( code.match( /\:.*for.*\(.*let.*\)/ )) // avoid bug 352921 (branch)
&& !( code.match( /for.*let.*\).*function/ )) // avoid bug 352735 (branch) (more rebracing stuff)
&& !( code.match( /for.*\(.*\(.*in.*;.*;.*\)/ )) // avoid bug 353255 (branch)
&& !( code.match( /while.*for.*in/ )) // avoid bug 381963 (branch)
&& !( code.match( /const.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /var.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /let.*arguments/ )) // avoid bug 355480 (branch)
&& !( code.match( /let/ )) // avoid bug 462309 (branch) :( :( :(
,
// Exclude things here if decompiling returns something incorrect or non-canonical, but that will compile.
checkForMismatch: true
&& !( code.match( /const.*if/ )) // avoid bug 352985 (branch)
&& !( code.match( /if.*const/ )) // avoid bug 352985 (branch)
&& !( code.match( /\{.*\}.*=.*\[.*=.*\]/ )) // avoid bug 376558 (branch)
&& !( code.match( /\[.*\].*=.*\[.*=.*\]/ )) // avoid bug 376558 (branch)
&& !( code.match( /with.*try.*function/ )) // avoid bug 418285 (branch)
&& !( code.match( /if.*try.*function/ )) // avoid bug 418285 (branch)
&& !( code.match( /\[.*\].*\=.*\[.*\,/ )) // avoid bug 355051 (branch)
&& !( code.match( /\{.*\}.*\=.*\[.*\,/ )) // avoid bug 355051 (branch) where empty {} becomes []
&& !( code.match( /\?.*\?/ )) // avoid bug 475895 (branch)
&& !( code.match( /for.*;.*;/ )) // avoid wackiness related to bug 461269 (branch)
&& !( code.match( /new.*\?/ )) // avoid bug 476210 (branch)
&& !( code.match( /\=.*\:\:/ )) // avoid bug 504957 (branch)
&& (code.indexOf("-0") == -1) // constant folding isn't perfect
&& (code.indexOf("-1") == -1) // constant folding isn't perfect
&& (code.indexOf("default") == -1) // avoid bug 355509 (branch)
&& (code.indexOf("delete") == -1) // avoid bug 352027 (branch), which won't be fixed for a while :(
&& (code.indexOf("const") == -1) // avoid bug 352985 (branch), bug 353020 (branch), and bug 355480 (branch) :(
&& (code.indexOf("&&") == -1) // ignore bug 461226 (branch) with a hatchet
&& (code.indexOf("||") == -1) // ignore bug 461226 (branch) with a hatchet
// avoid bug 352085 (branch): keep operators that coerce to number (or integer)
// at constant-folding time (?) away from strings
&&
(
(code.indexOf("\"") == -1 && code.indexOf("\'") == -1)
||
(
(code.indexOf("%") == -1)
&& (code.indexOf("/") == -1)
&& (code.indexOf("*") == -1)
&& (code.indexOf("-") == -1)
&& (code.indexOf(">>") == -1)
&& (code.indexOf("<<") == -1)
)
)
,
// Exclude things here if the decompilation doesn't match what the function actually does
checkDisassembly: true
&& !( code.match( /\@.*\:\:/ )) // avoid bug 381197 (branch) harder than above
&& !( code.match( /\(.*\?.*\:.*\).*\(.*\)/ )) // avoid bug 475899 (branch)
&& !( code.match( /for.*in.*for.*in/ )) // avoid bug 475985 (branch)
,
checkForExtraParens: true
&& !code.match( /\(.*for.*\(.*in.*\).*\)/ ) // ignore bug 381213 (branch), and unfortunately anything with genexps
&& !code.match( /if.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /while.*\(.*=.*\)/) // ignore extra parens added to avoid strict warning
&& !code.match( /\?.*\=/) // ignore bug 475893 (branch)
,
allowExec: unlikelyToHang(code)
&& code.indexOf("finally") == -1 // avoid bug 380018 (branch) and bug 381107 (branch) :(
&& code.indexOf("<>") == -1 // avoid bug 334628 (branch), hopefully
&& (jsshell || code.indexOf("nogeckoex") == -1)
&& !( code.match( /function.*::.*=/ )) // avoid ????
,
allowIter: true,
checkUneval: true
// exclusions won't be perfect, since functions can return things they don't
// appear to contain, e.g. with "return x;"
&& (code.indexOf("<") == -1 || code.indexOf(".") == -1) // avoid bug 379525 (branch)
&& (code.indexOf("<>") == -1) // avoid bug 334628 (branch)
};
}
function whatToTestJavaScriptCore(code)
{
return {
allowParse: true,
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true
,
checkForExtraParens: false, // ?
allowExec: unlikelyToHang(code)
,
allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
checkUneval: false // JavaScriptCore does not support |uneval|
};
}
function whatToTestGeneric(code)
{
return {
allowParse: true,
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true,
checkForExtraParens: false, // most js engines don't try to guarantee lack of extra parens
allowExec: unlikelyToHang(code),
allowIter: ("Iterator" in this),
checkUneval: haveRealUneval
};
}
var whatToTest;
if (engine == ENGINE_SPIDERMONKEY_TRUNK)
whatToTest = whatToTestSpidermonkeyTrunk;
else if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0)
whatToTest = whatToTestSpidermonkey190Branch;
else if (engine == ENGINE_JAVASCRIPTCORE)
whatToTest = whatToTestJavaScriptCore;
else
whatToTest = whatToTestGeneric;
function unlikelyToHang(code)
{
// Things that are likely to hang in all JavaScript engines
return true
&& code.indexOf("infloop") == -1
&& !( code.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
&& !( code.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
&& !( code.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
&& !( code.match( /for.*for.*for/ )) // nested for loops (including for..in, array comprehensions, etc) can take a while
&& !( code.match( /for.*for.*gc/ ))
;
}
/*************************
* DRIVING & BASIC TESTS *
*************************/
var allMakers = [];
function totallyRandom(d, b) {
d = d + (rnd(5) - 2); // can increase!!
return (rndElt(allMakers))(d, b);
}
function init()
{
for (var f in this)
if (f.indexOf("make") == 0 && typeof this[f] == "function")
allMakers.push(this[f]);
}
function testEachMaker()
{
for each (var f in allMakers) {
dumpln("");
dumpln(f.name);
dumpln("==========");
dumpln("");
for (var i = 0; i < 100; ++i) {
try {
dumpln(f(8, ["A", "B"]));
} catch(e) {
dumpln("");
dumpln(uneval(e));
dumpln(e.stack);
dumpln("");
}
}
dumpln("");
}
}
function start()
{
init();
count = 0;
if (jsshell) {
// If another script specified a "maxRunTime" argument, use it; otherwise, run forever
var MAX_TOTAL_TIME = (this.maxRunTime) || (Infinity);
var startTime = new Date();
do {
testOne();
var elapsed1 = new Date() - lastTime;
if (elapsed1 > 1000) {
print("That took " + elapsed1 + "ms!");
}
var lastTime = new Date();
} while(lastTime - startTime < MAX_TOTAL_TIME);
} else {
setTimeout(testStuffForAWhile, 200);
}
}
function testStuffForAWhile()
{
for (var j = 0; j < 100; ++j)
testOne();
if (count % 10000 < 100)
printImportant("Iterations: " + count);
setTimeout(testStuffForAWhile, 30);
}
function testOne()
{
var dumpEachSeed = false; // Can be set to true if makeStatement has side effects, such as crashing, so you have to reduce "the hard way".
++count;
// Split this string across two source strings to ensure that if a
// generated function manages to output the entire jsfunfuzz source,
// that output won't match the grep command.
var grepforme = "/*F";
grepforme += "RC*/"
// Sometimes it makes sense to start with simpler functions:
//var depth = (~~(count / 1000)) & 16;
var depth = 10;
if (dumpEachSeed) {
// More complicated, but results in a much shorter script, making SpiderMonkey happier.
var MTA = uneval(rnd.fuzzMT.export_mta());
var MTI = rnd.fuzzMT.export_mti();
if (MTA != rnd.lastDumpedMTA) {
dumpln(grepforme + "rnd.fuzzMT.import_mta(" + MTA + ");");
rnd.lastDumpedMTA = MTA;
}
dumpln(grepforme + "rnd.fuzzMT.import_mti(" + MTI + "); void (makeStatement(" + depth + "), ['x']);");
}
var code = makeStatement(depth, ["x"]);
// if (rnd(10) == 1) {
// var dp = "/*infloop-deParen*/" + rndElt(deParen(code));
// if (dp)
// code = dp;
// }
dumpln(grepforme + "count=" + count + "; tryItOut(" + uneval(code) + ");");
tryItOut(code);
}
function tryItOut(code)
{
var c; // a harmless variable for closure fun
// Accidentally leaving gczeal enabled for a long time would make jsfunfuzz really slow.
if ("gczeal" in this)
gczeal(0);
// SpiderMonkey shell does not schedule GC on its own. Help it not use too much memory.
if (count % 1000 == 0) {
dumpln("Paranoid GC (count=" + count + ")!");
realGC();
}
// regexps can't match across lines, so replace whitespace with spaces.
var wtt = whatToTest(code.replace(/\s/g, " "));
code = code.replace(/\/\*DUPTRY\d+\*\//, function(k) { var n = parseInt(k.substr(8), 10); dumpln(n); return strTimes("try{}catch(e){}", n); })
if (!wtt.allowParse)
return;
try {
Reflect.parse(code);
} catch(e) {
}
if (count % 20 == 1) {
if (wtt.allowExec) {
try {
print("Plain eval");
eval(code);
} catch(e) {
print(errorToString(e));
}
tryEnsureSanity();
}
return;
}
var f = tryCompiling(code, wtt.allowExec);
optionalTests(f, code, wtt);
if (f && wtt.allowDecompile) {
tryRoundTripStuff(f, code, wtt);
if (haveUsefulDis && wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkDisassembly)
checkRoundTripDisassembly(f, code, wtt);
}
if (f && wtt.allowExec) {
if (code.indexOf("\n") == -1 && code.indexOf("\r") == -1 && code.indexOf("\f") == -1 && code.indexOf("\0") == -1 && code.indexOf("\u2028") == -1 && code.indexOf("\u2029") == -1 && code.indexOf("<--") == -1 && code.indexOf("-->") == -1 && code.indexOf("//") == -1) {
if (code.indexOf("Error") == -1 // avoid bug 525518
&& code.indexOf("too_much_recursion") == -1 // recursion limits may differ (at least between execution modes). see bug 584594 (wontfix).
&& code.indexOf("getOwnPropertyNames") == -1 // Object.getOwnPropertyNames(this) contains "jitstats" and "tracemonkey" exist only with -j
&& code.indexOf("--") == -1 // avoid bug 584603
&& code.indexOf("++") == -1 // avoid bug 584603
&& code.indexOf("gc") == -1 // gc is noisy
&& code.indexOf(".(") == -1 // this e4x operator can get itself into infinite-recursion, and recursion limits are nondeterministic
&& code.indexOf("with") == -1 // avoid bug 593556
) {
// FCM cookie
var cookie1 = "/*F";
var cookie2 = "CM*/";
var nCode = code;
// Avoid compile-time errors because those are no fun.
// But leave some things out of function(){} because some bugs are only detectable at top-level, and
// pure jsfunfuzz doesn't test top-level at all.
// (This is a good reason to use compareJIT even if I'm not interested in finding JIT bugs!)
function failsToCompileInTry(code) {
// Why would this happen? One way is "let x, x"
try {
new Function(" try { " + code + " } catch(e) { }");
return false;
} catch(e) {
return true;
}
}
if (nCode.indexOf("return") != -1 || nCode.indexOf("yield") != -1 || nCode.indexOf("const") != -1 || failsToCompileInTry(nCode))
nCode = "(function(){" + nCode + "})()"
dumpln(cookie1 + cookie2 + " try { " + nCode + " } catch(e) { }");
}
}
}
var rv = null;
if (wtt.allowExec && f) {
rv = tryRunning(f, code);
tryEnsureSanity();
}
if (wtt.allowIter && rv && typeof rv == "object") {
tryIteration(rv);
tryEnsureSanity();
}
// "checkRecompiling && checkForMismatch" here to catch returned functions
if (wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkUneval && rv && typeof rv == "object") {
testUneval(rv);
}
if (verbose)
dumpln("Done trying out that function!");
dumpln("");
}
function tryCompiling(code, allowExec)
{
var c; // harmless local variable for closure fun
try {
// Try two methods of creating functions, just in case there are differences.
if (count % 2 == 0 && allowExec) {
if (verbose)
dumpln("About to compile, using eval hack.")
return eval("(function(){" + code + "});"); // Disadvantage: "}" can "escape", allowing code to *execute* that we only intended to compile. Hence the allowExec check.
}
else {
if (verbose)
dumpln("About to compile, using new Function.")
if (jsStrictMode)
code = "'use strict'; " + code; // ES5 10.1.1: new Function does not inherit strict mode
return new Function(code);
}
} catch(compileError) {
dumpln("Compiling threw: " + errorToString(compileError));
return null;
}
}
function tryRunning(f, code)
{
try {
if (verbose)
dumpln("About to run it!");
var rv = f();
if (verbose)
dumpln("It ran!");
return rv;
} catch(runError) {
if(verbose)
dumpln("Running threw! About to toString to error.");
var err = errorToString(runError);
dumpln("Running threw: " + err);
tryEnsureSanity();
// bug 465908 and other e4x uneval nonsense make this show lots of false positives
// checkErrorMessage(err, code);
return null;
}
}
// Store things now so we can restore sanity later.
var realEval = eval;
var realMath = Math;
var realFunction = Function;
var realGC = gc;
var realUneval = uneval;
var realToString = toString;
var realToSource = this.toSource; // "this." because it only exists in spidermonkey
function tryEnsureSanity()
{
try {
// The script might have turned on gczeal. Turn it back off right away to avoid slowness.
if ("gczeal" in this)
gczeal(0);
// At least one bug in the past has put exceptions in strange places. This also catches "eval getter" issues.
try { eval("") } catch(e) { dumpln("That really shouldn't have thrown: " + errorToString(e)); }
// Try to get rid of any fake 'unwatch' functions.
delete this.unwatch;
// Restore important stuff that might have been broken as soon as possible :)
if ('unwatch' in this) {
this.unwatch("eval")
this.unwatch("Function")
this.unwatch("gc")
this.unwatch("uneval")
this.unwatch("toSource")
this.unwatch("toString")
}
if ('__defineSetter__' in this) {
// The only way to get rid of getters/setters is to delete the property.
if (!jsStrictMode)
delete this.eval;
delete this.Math;
delete this.Function;
delete this.gc;
delete this.uneval;
delete this.toSource;
delete this.toString;
}
this.Math = realMath;
this.eval = realEval;
this.Function = realFunction;
this.gc = realGC;
this.uneval = realUneval;
this.toSource = realToSource;
this.toString = realToString;
} catch(e) {
printImportant("tryEnsureSanity failed: " + e);
}
// These can fail if the page creates a getter for "eval", for example.
if (!this.eval)
printImportant("WTF did my |eval| go?");
if (this.eval != realEval)
printImportant("WTF did my |eval| get replaced by?")
if (Function != realFunction)
printImportant("WTF did my |Function| get replaced by?")
}
function tryIteration(rv)
{
try {
if (!(Iterator(rv) === rv))
return; // not an iterator
}
catch(e) {
// Is it a bug that it's possible to end up here? Probably not!
dumpln("Error while trying to determine whether it's an iterator!");
dumpln("The error was: " + e);
return;
}
dumpln("It's an iterator!");
try {
var iterCount = 0;
var iterValue;
// To keep Safari-compatibility, don't use "let", "each", etc.
for /* each */ ( /* let */ iterValue in rv)
++iterCount;
dumpln("Iterating succeeded, iterCount == " + iterCount);
} catch (iterError) {
dumpln("Iterating threw!");
dumpln("Iterating threw: " + errorToString(iterError));
}
}
/***********************************
* WHOLE-FUNCTION DECOMPILER TESTS *
***********************************/
function tryRoundTripStuff(f, code, wtt)
{
if (verbose)
dumpln("About to do the 'toString' round-trip test");
// Functions are prettier with line breaks, so test toString before uneval.
checkRoundTripToString(f, code, wtt);
if (wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkForExtraParens) {
try {
testForExtraParens(f, code);
} catch(e) { /* bug 355667 is annoying here too */ }
}
if (haveRealUneval) {
if (verbose)
dumpln("About to do the 'uneval' round-trip test");
checkRoundTripUneval(f, code, wtt);
}
}
// Function round-trip with implicit toString
function checkRoundTripToString(f, code, wtt)
{
var fs, g;
try {
fs = "" + f;
} catch(e) { reportRoundTripIssue("Round-trip with implicit toString: can't toString", code, null, null, errorToString(e)); return; }
checkForCookies(fs);
if (wtt.checkRecompiling) {
try {
g = eval("(" + fs + ")");
var gs = "" + g;
if (wtt.checkForMismatch && fs != gs) {
reportRoundTripIssue("Round-trip with implicit toString", code, fs, gs, "mismatch");
wtt.checkForMismatch = false;
}
} catch(e) {
reportRoundTripIssue("Round-trip with implicit toString: error", code, fs, gs, errorToString(e));
}
}
}
// Function round-trip with uneval
function checkRoundTripUneval(f, code, wtt)
{
var g, uf, ug;
try {
uf = uneval(f);
} catch(e) { reportRoundTripIssue("Round-trip with uneval: can't uneval", code, null, null, errorToString(e)); return; }
checkForCookies(uf);
if (wtt.checkRecompiling) {
try {
g = eval("(" + uf + ")");
ug = uneval(g);
if (wtt.checkForMismatch && ug != uf) {
reportRoundTripIssue("Round-trip with uneval: mismatch", code, uf, ug, "mismatch");
wtt.checkForMismatch = false;
}
} catch(e) { reportRoundTripIssue("Round-trip with uneval: error", code, uf, ug, errorToString(e)); }
}
}
function checkForCookies(code)
{
// http://lxr.mozilla.org/seamonkey/source/js/src/jsopcode.c#1613
// These are things that shouldn't appear in decompilations.
if (code.indexOf("/*EXCEPTION") != -1
|| code.indexOf("/*RETSUB") != -1
|| code.indexOf("/*FORELEM") != -1
|| code.indexOf("/*WITH") != -1)
printAndStop(code)
}
function reportRoundTripIssue(issue, code, fs, gs, e)
{
if (e.indexOf("missing variable name") != -1) {
dumpln("Bug 355667 sure is annoying!");
return;
}
if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0 && e.indexOf("invalid object initializer") != -1) {
dumpln("Ignoring bug 452561 (branch).");
return;
}
if (e.indexOf("illegal XML character") != -1) {
dumpln("Ignoring bug 355674.");
return;
}
if (e.indexOf("illegal character") != -1) {
dumpln("Ignoring bug 566661.");
return;
}
if (engine == ENGINE_SPIDERMONKEY_MOZ_1_9_0 && e.indexOf("missing ; after for-loop condition") != -1) {
dumpln("Looks like bug 460504 (branch).");
return;
}
if (fs && gs && fs.replace(/'/g, "\"") == gs.replace(/'/g, "\"")) {
dumpln("Ignoring quote mismatch (bug 346898 (wontfix)).");
return;
}
var message = issue + "\n\n" +
"Code: " + uneval(code) + "\n\n" +
"fs: " + fs + "\n\n" +
"gs: " + gs + "\n\n" +
"error: " + e;
printAndStop(message);
}
/*************************************************
* EXPRESSION DECOMPILATION & VALUE UNEVAL TESTS *
*************************************************/
function testUneval(o)
{
// If it happens to return an object, especially an array or hash,
// let's test uneval. Note that this is a different code path than decompiling
// an array literal within a function, although the two code paths often have
// similar bugs!
var uo, euo, ueuo;
try {
uo = uneval(o);
} catch(e) {
if (errorToString(e).indexOf("called on incompatible") != -1) {
dumpln("Ignoring bug 379528!".toUpperCase());
return;
}
else
throw e;
}
if (uo == "({})") {
// ?
return;
}
if (testUnevalString(uo)) {
// count=946; tryItOut("return (({ set x x (x) { yield /x/g } , x setter: ({}).hasOwnProperty }));");
uo = uo.replace(/\[native code\]/g, "");
if (uo.charAt(0) == "/")
return; // ignore bug 362582
try {
euo = eval(uo); // if this throws, something's wrong with uneval, probably
} catch(e) {
dumpln("The string returned by uneval failed to eval!");
dumpln("The string was: " + uo);
printAndStop(e);
return;
}
ueuo = uneval(euo);
if (ueuo != uo) {
printAndStop("Mismatch with uneval/eval on the function's return value! " + "\n" + uo + "\n" + ueuo);
}
} else {
dumpln("Skipping re-eval test");
}
}
function testUnevalString(uo)
{
var uowlb = uo.replace(/\n/g, " ").replace(/\r/g, " ");
return true
&& uo.indexOf("[native code]") == -1 // ignore bug 384756
&& (uo.indexOf("#") == -1) // ignore bug 328745 (ugh)
&& (uo.indexOf("{") == -1 || uo.indexOf(":") == -1) // ignore bug 379525 hard (ugh!)
&& uo.indexOf("NaN") == -1 // ignore bug 379521
&& uo.indexOf("Infinity") == -1 // ignore bug 379521
&& uo.indexOf(",]") == -1 // avoid bug 334628 / bug 379525?
&& uo.indexOf("[function") == -1 // avoid bug 380379?
&& uo.indexOf("[(function") == -1 // avoid bug 380379?
&& !uowlb.match(/new.*Error/) // ignore bug 380578
&& !uowlb.match(/<.*\/.*>.*<.*\/.*>/) // ignore bug 334628
&& !uowlb.match(/\\0\d/) // ignore bug 537849
;
}
function checkErrorMessage(err, code)
{
// Checking to make sure DVG is behaving (and not, say, playing with uninitialized memory)
if (engine == ENGINE_SPIDERMONKEY_TRUNK) {
checkErrorMessage2(err, "TypeError: ", " is not a function");
checkErrorMessage2(err, "TypeError: ", " is not a constructor");
checkErrorMessage2(err, "TypeError: ", " is undefined");
}
// These should probably be tested too:XML.ignoreComments
// XML filter is applied to non-XML value ...
// invalid 'instanceof' operand ...
// invalid 'in' operand ...
// missing argument 0 when calling function ...
// ... has invalid __iterator__ value ... (two of them!!)
}
function checkErrorMessage2(err, prefix, suffix)
{
var P = prefix.length;
var S = suffix.length;
if (err.substr(0, P) == prefix) {
if (err.substr(-S, S) == suffix) {
var dvg = err.substr(11, err.length - P - S);
print("Testing an expression in a recent error message: " + dvg);
// These error messages can involve decompilation of expressions (DVG),
// but in some situations they can just be uneval of a value. In those
// cases, we don't want to complain about known uneval bugs.
if (!testUnevalString(dvg)) {
print("Ignoring error message string because it looks like a known-bogus uneval");
return;
}
if (dvg == "") {
print("Ignoring E4X uneval bogosity");
// e.g. the error message from (<x/>.(false))()
// bug 465908, etc.
return;
}
try {
eval("(function() { return (" + dvg + "); })");
} catch(e) {
printAndStop("DVG has apparently failed us: " + e);
}
}
}
}
/**************************
* PARENTHESIZATION TESTS *
**************************/
// Returns an array of strings of length (code.length-2),
// each having one pair of matching parens removed.
// Assumes all parens in code are significant. This assumption fails
// for strings or regexps, but whatever.
function deParen(code)
{
// Get a list of locations of parens.
var parenPairs = []; // array of { left : int, right : int } (indices into code string)
var unmatched = []; // stack of indices into parenPairs
var i, c;
for (i = 0; i < code.length; ++i) {
c = code.charCodeAt(i);
if (c == 40) {
// left paren
unmatched.push(parenPairs.length);
parenPairs.push({ left: i });
} else if (c == 41) {
// right paren
if (unmatched.length == 0)
return []; // eep! unmatched rparen!
parenPairs[unmatched.pop()].right = i;
}
}
if (unmatched.length > 0)
return []; // eep! unmatched lparen!
var rs = [];
// Don't add spaces in place of the parens, because we don't
// want to detect things like (5).x as being unnecessary use
// of parens.
for (i = 0; i < parenPairs.length; ++i) {
var left = parenPairs[i].left, right = parenPairs[i].right;
rs.push(
code.substr(0, left)
+ code.substr(left + 1, right - (left + 1))
+ code.substr(right + 1)
);
}
return rs;
}
// print(uneval(deParen("for (i = 0; (false); ++i) { x(); }")));
// print(uneval(deParen("[]")));
function testForExtraParens(f, code)
{
code = code.replace(/\n/g, " ").replace(/\r/g, " "); // regexps can't match across lines
var uf = "" + f;
// numbers get more parens than they need
if (uf.match(/\(\d/)) return;
if (uf.indexOf("(<") != -1) return; // bug 381204
if (uf.indexOf(".(") != -1) return; // bug 381207
if (code.indexOf("new") != -1) return; // "new" is weird. what can i say?
if (code.indexOf("let") != -1) return; // reasonable to overparenthesize "let" (see expclo#c33)
if (code.match(/for.*in.*=/)) return; // bug 381213
if (code.match(/\:.*function/)) return; // why?
if (uf.indexOf("(function") != -1) return; // expression closures over-parenthesize
if (code.match(/for.*yield/)) return; // why?
if (uf.indexOf("= (yield") != -1) return;
if (uf.indexOf(":(yield") != -1) return;
if (uf.indexOf(": (yield") != -1) return;
if (uf.indexOf(", (yield") != -1) return;
if (uf.indexOf("[(yield") != -1) return;
if (uf.indexOf("yield") != -1) return; // i give up on yield
// Sanity check
var euf = eval("(" + uf + ")");
var ueuf = "" + euf;
if (ueuf != uf)
printAndStop("Shouldn't the earlier round-trip test have caught this?");
var dps = deParen(uf);
// skip the first, which is the function's formal params.
for (var i = 1; i < dps.length; ++i) {
var uf2 = dps[i];
try {
var euf2 = eval("(" + uf2 + ")");
} catch(e) { /* print("The latter did not compile. That's fine."); */ continue; }
var ueuf2 = "" + euf2
if (ueuf2 == ueuf) {
print(uf);
print(" vs ");
print(uf2);
print("Both decompile as:");
print(ueuf);
printAndStop("Unexpected match!!! Extra parens!?");
}
}
}
/*********************************
* SPIDERMONKEY DISASSEMBLY TEST *
*********************************/
// Finds decompiler bugs and bytecode inefficiencies by complaining when a round trip
// through the decompiler changes the bytecode.
function checkRoundTripDisassembly(f, code, wtt)
{
if (code.indexOf("[@") != -1 || code.indexOf("*::") != -1 || code.indexOf("::*") != -1 || code.match(/\[.*\*/)) {
dumpln("checkRoundTripDisassembly: ignoring bug 475859");
return;
}
if (code.indexOf("=") != -1 && code.indexOf("const") != -1) {
dumpln("checkRoundTripDisassembly: ignoring function with const and assignment, because that's boring.");
return;
}
var uf = uneval(f);
if (uf.indexOf("switch") != -1) {
// Bug 355509 :(
return;
}
if (code.indexOf("new") != code.lastIndexOf("new")) {
dumpln("checkRoundTripDisassembly: ignoring function with two 'new' operators (bug 475848)");
return;
}
if (code.indexOf("&&") != code.lastIndexOf("&&")) {
dumpln("checkRoundTripDisassembly: ignoring && associativity issues (bug 475863)");
return;
}
if (code.indexOf("||") != code.lastIndexOf("||")) {
dumpln("checkRoundTripDisassembly: ignoring || associativity issues (bug 475863)");
return;
}
if (code.match(/for.*\(.*in.*\).*if/)) {
print("checkRoundTripDisassembly: ignoring array comprehension with 'if' (bug 475882)");
return;
}
try { var g = eval(uf); } catch(e) { return; /* separate uneval test will catch this */ }
var df = dis(f);
if (df.indexOf("newline") != -1)
return;
if (df.indexOf("lineno") != -1)
return;
if (df.indexOf("trap") != -1) {
print("checkRoundTripDisassembly: trapped");
return;
}
var dg = dis(g);
if (df == dg) {
// Happy!
if (wtt.allowExec)
trapCorrectnessTest(f);
return;
}
if (dg.indexOf("newline") != -1) {
// Really should just ignore these lines, instead of bailing...
return;
}
var dfl = df.split("\n");
var dgl = dg.split("\n");
for (var i = 0; i < dfl.length && i < dgl.length; ++i) {
if (dfl[i] != dgl[i]) {
if (dfl[i] == "00000: generator") {
print("checkRoundTripDisassembly: ignoring loss of generator (bug 350743)");
return;
}
if (dfl[i].indexOf("goto") != -1 && dgl[i].indexOf("stop") != -1 && uf.indexOf("switch") != -1) {
// Actually, this might just be bug 355509.
print("checkRoundTripDisassembly: ignoring extra 'goto' in switch (bug 475838)");
return;
}
if (dfl[i].indexOf("regexp null") != -1) {
print("checkRoundTripDisassembly: ignoring 475844 / regexp");
return;
}
if (dfl[i].indexOf("namedfunobj null") != -1 || dfl[i].indexOf("anonfunobj null") != -1) {
print("checkRoundTripDisassembly: ignoring 475844 / function");
return;
}
if (dfl[i].indexOf("string") != -1 && (dfl[i+1].indexOf("toxml") != -1 || dfl[i+1].indexOf("startxml") != -1)) {
print("checkRoundTripDisassembly: ignoring e4x-string mismatch (likely bug 355674)");
return;
}
if (dfl[i].indexOf("string") != -1 && df.indexOf("startxmlexpr") != -1) {
print("checkRoundTripDisassembly: ignoring complicated e4x-string mismatch (likely bug 355674)");
return;
}
if (dfl[i].indexOf("newinit") != -1 && dgl[i].indexOf("newarray 0") != -1) {
print("checkRoundTripDisassembly: ignoring array comprehension disappearance (bug 475847)");
return;
}
if (i == 0 && dfl[i].indexOf("HEAVYWEIGHT") != -1 && dgl[i].indexOf("HEAVYWEIGHT") == -1) {
print("checkRoundTripDisassembly: ignoring unnecessarily HEAVYWEIGHT function (bug 475854)");
return;
}
if (i == 0 && dfl[i].indexOf("HEAVYWEIGHT") == -1 && dgl[i].indexOf("HEAVYWEIGHT") != -1) {
// The other direction
// var __proto__ hoisting, for example
print("checkRoundTripDisassembly: ignoring unnecessarily HEAVYWEIGHT function (bug 475854 comment 1)");
return;
}
if (dfl[i].indexOf("pcdelta") != -1 && dgl[i].indexOf("pcdelta") != -1) {
print("checkRoundTripDisassembly: pcdelta changed, who cares? (bug 475908)");
return;
}
print("First line that does not match:");
print(dfl[i]);
print(dgl[i]);
break;
}
}
print("Function from original code:");
print(code);
print(df);
print("Function from recompiling:");
print(uf);
print(dg);
printAndStop("Disassembly was not stable through decompilation");
}
/*****************************
* SPIDERMONKEY TRAP TESTING *
*****************************/
function getBytecodeOffsets(f)
{
var disassembly = dis(f);
var lines = disassembly.split("\n");
var i;
offsets = [];
for (i = 0; i < lines.length; ++i) {
if (lines[i] == "main:")
break;
if (i + 1 == lines.length)
printAndStop("disassembly -- no main?");
}
for (++i; i < lines.length; ++i) {
if (lines[i] == "")
break;
if (i + 1 == lines.length)
printAndStop("disassembly -- ended suddenly?")
// The opcodes |tableswitch| and |lookupswitch| add indented lists,
// which we want to ignore.
var c = lines[i].charCodeAt(0);
if (!(0x30 <= c && c <= 0x39))
continue;
var op = lines[i].substr(8).split(" ")[0]; // used only for avoiding known bugs
var offset = parseInt(lines[i], 10);
offsets.push({ offset: offset, op: op });
if (op == "getter" || op == "setter") {
++i; // skip the next opcode per bug 476073 comment 4
}
}
return offsets;
}
function trapCorrectnessTest(f)
{
var uf = uneval(f);
print("trapCorrectnessTest...");
var offsets = getBytecodeOffsets(f);
var prefix = "var fff = " + f + "; ";
var r1 = sandboxResult(prefix + "fff();");
for (var i = 0; i < offsets.length; ++i) {
var offset = offsets[i].offset;
var op = offsets[i].op;
// print(offset + " " + op);
var trapStr = "trap(fff, " + offset + ", ''); ";
var r2 = sandboxResult(prefix + trapStr + " fff();");
if (r1 != r2) {
if (r1.indexOf("TypeError") != -1 && r2.indexOf("TypeError") != -1) {
// Why does this get printed multiple times???
// count=6544; tIO("var x; x.y;");
print("A TypeError changed. Might be bug 476088.");
continue;
}
print("Adding a trap changed the result!");
print(f);
print(r1);
print(trapStr);
print(r2);
printAndStop(":(");
}
}
//print("Happy: " + f + r1);
}
function sandboxResult(code)
{
// Use sandbox to isolate side-effects.
// This might be wrong in cases where the sandbox manages to return objects with getters and stuff!
var result;
try {
// result = evalcx(code, {trap:trap, print:print}); // WRONG
var sandbox = evalcx("");
sandbox.trap = trap;
sandbox.print = print;
sandbox.dis = dis;
result = evalcx(code, sandbox);
} catch(e) {
result = "Error: " + errorToString(e);
}
return "" + result;
}
// This tests two aspects of trap:
// 1) put a trap in a random place; does decompilation get horked?
// 2) traps that do things
// These should probably be split into different tests.
function spiderMonkeyTrapTest(f, code, wtt)
{
var offsets = getBytecodeOffsets(f);
if ("trap" in this) {
// Save for trap
//if (wtt.allowExec && count % 2 == 0) {
//nextTrapCode = code;
// return;
//}
// Use trap
if (verbose)
dumpln("About to try the trap test.");
var ode;
if (wtt.allowDecompile)
ode = "" + f;
//if (nextTrapCode) {
// trapCode = nextTrapCode;
// nextTrapCode = null;
// print("trapCode = " + simpleSource(trapCode));
//} else {
trapCode = "print('Trap hit!')";
//}
trapOffset = offsets[count % offsets.length].offset;
print("trapOffset: " + trapOffset);
if (!(trapOffset > -1)) {
print(dis(f));
print(count);
print(uneval(offsets));
print(offsets.length);
printAndStop("WTF");
}
trap(f, trapOffset, trapCode);
if (wtt.allowDecompile) {
nde = "" + f;
if (ode != nde) {
print(ode);
print(nde);
printAndStop("Trap decompilation mismatch");
}
}
}
}
/*********************
* SPECIALIZED TESTS *
*********************/
function simpleDVGTest(code)
{
var fullCode = "(function() { try { \n" + code + "\n; throw 1; } catch(exx) { this.nnn.nnn } })()";
try {
eval(fullCode);
} catch(e) {
if (e.message != "this.nnn is undefined" && e.message.indexOf("redeclaration of") == -1) {
printAndStop("Wrong error message: " + e);
}
}
}
function optionalTests(f, code, wtt)
{
if (0) {
tryHalves(code);
}
if (0 && engine == ENGINE_SPIDERMONKEY_TRUNK) {
if (wtt.allowExec && ('sandbox' in this)) {
f = null;
if (trySandboxEval(code, false)) {
dumpln("Trying it again to see if it's a 'real leak' (???)")
trySandboxEval(code, true);
}
}
return;
}
if (0 && f && haveUsefulDis) {
spiderMonkeyTrapTest(f, code, wtt);
}
if (0 && f && wtt.allowExec && engine == ENGINE_SPIDERMONKEY_TRUNK) {
simpleDVGTest(code);
tryEnsureSanity();
}
}
function trySandboxEval(code, isRetry)
{
// (function(){})() wrapping allows "return" when it's allowed outside.
// The line breaks are to allow single-line comments within code ("//" and "<!--").
if (!sandbox) {
sandbox = evalcx("");
}
var rv = null;
try {
rv = evalcx("(function(){\n" + code + "\n})();", sandbox);
} catch(e) {
rv = "Error from sandbox: " + errorToString(e);
}
try {
if (typeof rv != "undefined")
dumpln(rv);
} catch(e) {
dumpln("Sandbox error printing: " + errorToString(e));
}
rv = null;
if (1 || count % 100 == 0) { // count % 100 *here* is sketchy.
dumpln("Done with this sandbox.");
sandbox = null;
gc();
var currentHeapCount = countHeap()
dumpln("countHeap: " + currentHeapCount);
if (currentHeapCount > maxHeapCount) {
if (maxHeapCount != 0)
dumpln("A new record by " + (currentHeapCount - maxHeapCount) + "!");
if (isRetry)
throw new Error("Found a leak!");
maxHeapCount = currentHeapCount;
return true;
}
}
return false;
}
function tryHalves(code)
{
// See if there are any especially horrible bugs that appear when the parser has to start/stop in the middle of something. this is kinda evil.
// Stray "}"s are likely in secondHalf, so use new Function rather than eval. "}" can't escape from new Function :)
var f, firstHalf, secondHalf;
try {
firstHalf = code.substr(0, code.length / 2);
if (verbose)
dumpln("First half: " + firstHalf);
f = new Function(firstHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("First half compilation error: " + e);
}
try {
secondHalf = code.substr(code.length / 2, code.length);
if (verbose)
dumpln("Second half: " + secondHalf);
f = new Function(secondHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("Second half compilation error: " + e);
}
}
/***************************
* REPRODUCIBLE RANDOMNESS *
***************************/
// this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class,
// an almost straight conversion from the original program, mt19937ar.c,
// translated by y. okada on July 17, 2006.
// Changes by Jesse Ruderman: added "var" keyword in a few spots; added export_mta etc; pasted into fuzz.js.
// in this program, procedure descriptions and comments of original source code were not removed.
// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.
// lines commented with /* and */ are original comments.
// lines commented with // are additional comments in this JavaScript version.
// before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances.
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
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 names of its contributors may not 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.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
function MersenneTwister19937()
{
/* Period parameters */
//c//#define N 624
//c//#define M 397
//c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */
//c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
//c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
var N = 624;
var M = 397;
var MATRIX_A = 0x9908b0df; /* constant vector a */
var UPPER_MASK = 0x80000000; /* most significant w-r bits */
var LOWER_MASK = 0x7fffffff; /* least significant r bits */
//c//static unsigned long mt[N]; /* the array for the state vector */
//c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
var mt = new Array(N); /* the array for the state vector */
var mti = N+1; /* mti==N+1 means mt[N] is not initialized */
function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.
{
return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;
}
function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;
}
function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return unsigned32((n1 + n2) & 0xffffffff)
}
function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
var sum = 0;
for (var i = 0; i < 32; ++i){
if ((n1 >>> i) & 0x1){
sum = addition32(sum, unsigned32(n2 << i));
}
}
return sum;
}
/* initializes mt[N] with a seed */
//c//void init_genrand(unsigned long s)
this.init_genrand = function (s)
{
//c//mt[0]= s & 0xffffffff;
mt[0]= unsigned32(s & 0xffffffff);
for (mti=1; mti<N; mti++) {
mt[mti] =
//c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//c//mt[mti] &= 0xffffffff;
mt[mti] = unsigned32(mt[mti] & 0xffffffff);
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//c//void init_by_array(unsigned long init_key[], int key_length)
this.init_by_array = function (init_key, key_length)
{
//c//int i, j, k;
var i, j, k;
//c//init_genrand(19650218);
this.init_genrand(19650218);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))
//c// + init_key[j] + j; /* non linear */
mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);
mt[i] =
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
unsigned32(mt[i] & 0xffffffff);
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))
//c//- i; /* non linear */
mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
mt[i] = unsigned32(mt[i] & 0xffffffff);
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
this.export_state = function() { return [mt, mti]; };
this.import_state = function(s) { mt = s[0]; mti = s[1]; };
this.export_mta = function() { return mt; };
this.import_mta = function(_mta) { mt = _mta };
this.export_mti = function() { return mti; };
this.import_mti = function(_mti) { mti = _mti; }
/* generates a random number on [0,0xffffffff]-interval */
//c//unsigned long genrand_int32(void)
this.genrand_int32 = function ()
{
//c//unsigned long y;
//c//static unsigned long mag01[2]={0x0UL, MATRIX_A};
var y;
var mag01 = new Array(0x0, MATRIX_A);
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
//c//int kk;
var kk;
if (mti == N+1) /* if init_genrand() has not been called, */
//c//init_genrand(5489); /* a default initial seed is used */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
for (;kk<N-1;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
//c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
//c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));
mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
//c//y ^= (y >> 11);
//c//y ^= (y << 7) & 0x9d2c5680;
//c//y ^= (y << 15) & 0xefc60000;
//c//y ^= (y >> 18);
y = unsigned32(y ^ (y >>> 11));
y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));
y = unsigned32(y ^ ((y << 15) & 0xefc60000));
y = unsigned32(y ^ (y >>> 18));
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
//c//long genrand_int31(void)
this.genrand_int31 = function ()
{
//c//return (genrand_int32()>>1);
return (this.genrand_int32()>>>1);
}
/* generates a random number on [0,1]-real-interval */
//c//double genrand_real1(void)
this.genrand_real1 = function ()
{
//c//return genrand_int32()*(1.0/4294967295.0);
return this.genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
//c//double genrand_real2(void)
this.genrand_real2 = function ()
{
//c//return genrand_int32()*(1.0/4294967296.0);
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//c//double genrand_real3(void)
this.genrand_real3 = function ()
{
//c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);
return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
//c//double genrand_res53(void)
this.genrand_res53 = function ()
{
//c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
var rnd;
if (1) {
// Mersenne twister: I get to set the seed, great distribution of random numbers, but pretty slow
// (spidermonkey trunk 2008-10-08 with JIT on, makes jsfunfuzz 20% slower overall!)
(function() {
var fuzzMT = new MersenneTwister19937;
var fuzzSeed = Math.floor(Math.random() * Math.pow(2,28));
dumpln("fuzzSeed: " + fuzzSeed);
fuzzMT.init_genrand(fuzzSeed);
rnd = function (n) { return Math.floor(fuzzMT.genrand_real2() * n); };
rnd.rndReal = function() { return fuzzMT.genrand_real2(); };
rnd.fuzzMT = fuzzMT;
})();
} else {
// Math.random(): ok distribution of random numbers, fast
rnd = function (n) { return Math.floor(Math.random() * n); };
}
function errorstack()
{
print("EEE");
try { [].qwerty.qwerty } catch(e) { print(e.stack) }
}
function rndElt(a)
{
if (typeof a == "string") {
dumpln("String passed to rndElt: " + a);
errorstack();
}
if (typeof a == "function")
dumpln("Function passed to rndElt: " + a);
if (a == null)
dumpln("Null passed to rndElt");
if (!a.length) {
dumpln("Empty thing passed to rndElt");
return null;
}
return a[rnd(a.length)];
}
/**************************
* TOKEN-LEVEL GENERATION *
**************************/
// Each input to |cat| should be a token or so, OR a bigger logical piece (such as a call to makeExpr). Smaller than a token is ok too ;)
// When "torture" is true, it may do any of the following:
// * skip a token
// * skip all the tokens to the left
// * skip all the tokens to the right
// * insert unterminated comments
// * insert line breaks
// * insert entire expressions
// * insert any token
// Even when not in "torture" mode, it may sneak in extra line breaks.
// Why did I decide to toString at every step, instead of making larger and larger arrays (or more and more deeply nested arrays?). no particular reason...
function cat(toks)
{
if (rnd(1700) == 0)
return totallyRandom(2, []);
var torture = (rnd(1700) == 57);
if (torture)
dumpln("Torture!!!");
var s = maybeLineBreak();
for (var i = 0; i < toks.length; ++i) {
// Catch bugs in the fuzzer. An easy mistake is
// return /*foo*/ + ...
// instead of
// return "/*foo*/" + ...
// Unary plus in the first one coerces the string that follows to number!
if(typeof(toks[i]) != "string") {
dumpln("Strange item in the array passed to cat: toks[" + i + "] == " + toks[i]);
dumpln(cat.caller)
dumpln(cat.caller.caller)
printAndStop('yarr')
}
if (!(torture && rnd(12) == 0))
s += toks[i];
s += maybeLineBreak();
if (torture) switch(rnd(120)) {
case 0:
case 1:
case 2:
case 3:
case 4:
s += maybeSpace() + totallyRandom(2, []) + maybeSpace();
break;
case 5:
s = "(" + s + ")"; // randomly parenthesize some *prefix* of it.
break;
case 6:
s = ""; // throw away everything before this point
break;
case 7:
return s; // throw away everything after this point
case 8:
s += UNTERMINATED_COMMENT;
break;
case 9:
s += UNTERMINATED_STRING_LITERAL;
break;
case 10:
if (rnd(2))
s += "(";
s += UNTERMINATED_REGEXP_LITERAL;
break;
default:
}
}
return s;
}
// For reference and debugging.
/*
function catNice(toks)
{
var s = ""
var i;
for (i=0; i<toks.length; ++i) {
if(typeof(toks[i]) != "string")
printAndStop("Strange toks[i]: " + toks[i]);
s += toks[i];
}
return s;
}
*/
var UNTERMINATED_COMMENT = "/*"; /* this comment is here so my text editor won't get confused */
var UNTERMINATED_STRING_LITERAL = "'";
var UNTERMINATED_REGEXP_LITERAL = "/";
function maybeLineBreak()
{
if (rnd(900) == 3)
return rndElt(["\r", "\n", "//h\n", "/*\n*/"]); // line break to trigger semicolon insertion and stuff
else if (rnd(400) == 3)
return rnd(2) ? "\u000C" : "\t"; // weird space-like characters
else
return "";
}
function maybeSpace()
{
if (rnd(2) == 0)
return " ";
else
return "";
}
function stripSemicolon(c)
{
var len = c.length;
if (c.charAt(len - 1) == ";")
return c.substr(0, len - 1);
else
return c;
}
/*************************
* HIGH-LEVEL GENERATION *
*************************/
var TOTALLY_RANDOM = 100;
function makeStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d < 6 && rnd(3) == 0)
return makePrintStatement(d, b);
if (d < rnd(8)) // frequently for small depth, infrequently for large depth
return makeLittleStatement(d, b);
d = rnd(d); // !
return (rndElt(statementMakers))(d, b)
}
var varBinder = ["var ", "let ", "const ", ""];
var varBinderFor = ["var ", "let ", ""]; // const is a syntax error in for loops
// The reason there are several types of loops here is to create different
// types of scripts without introducing infinite loops.
function makeOpaqueIdiomaticLoop(d, b)
{
var reps = 1 + rnd(7);
var vHidden = uniqueVarName();
return ("/*oLoop*/for (" + rndElt(varBinderFor) + "x = 0; x < " + reps + "; ++x) ").replace(/x/g, vHidden) +
makeStatement(d - 2, b);
}
function makeTransparentIdiomaticLoop(d, b)
{
var reps = 1 + rnd(7);
var vHidden = uniqueVarName();
var vVisible = makeNewId(d, b);
return ("/*vLoop*/for (" + rndElt(varBinderFor) + "x = 0; x < " + reps + "; ++x)").replace(/x/g, vHidden) +
" { " +
rndElt(varBinder) + vVisible + " = " + vHidden + "; " +
makeStatement(d - 2, b.concat([vVisible])) +
" } "
}
function makeBranchUnstableLoop(d, b)
{
var reps = 1 + rnd(24);
var v = uniqueVarName();
var mod = rnd(5) + 2;
var target = rnd(mod);
var loopHead = ("/*bLoop*/for (var x = 0; x < " + reps + "; ++x)").replace(/x/g, v);
return loopHead + " { " +
"if (" + v + " % " + mod + " == " + target + ") { " + makeStatement(d - 2, b) + " } " +
"else { " + makeStatement(d - 2, b) + " } " +
" } "
}
function makeTypeUnstableLoop(d, b) {
var a = makeMixedTypeArray(d, b);
var v = makeNewId(d, b);
var bv = b.concat([v]);
return "/*tLoop*/for each (let " + v + " in " + a + ") { " + makeStatement(d - 2, bv) + " }";
}
function weighted(wa)
{
var a = [];
for (var i = 0; i < wa.length; ++i) {
for (var j = 0; j < wa[i].w; ++j) {
a.push(wa[i].fun);
}
}
return a;
}
var statementMakers = weighted([
// Any two statements in sequence
{ w: 4, fun: function(d, b) { return cat([makeStatement(d, b), makeStatement(d, b)]); } },
{ w: 4, fun: function(d, b) { return cat([makeStatement(d - 1, b), "\n", makeStatement(d - 1, b), "\n"]); } },
// Stripping semilcolons. What happens if semicolons are missing? Especially with line breaks used in place of semicolons (semicolon insertion).
{ w: 1, fun: function(d, b) { return cat([stripSemicolon(makeStatement(d, b)), "\n", makeStatement(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([stripSemicolon(makeStatement(d, b)), "\n" ]); } },
{ w: 1, fun: function(d, b) { return stripSemicolon(makeStatement(d, b)); } }, // usually invalid, but can be ok e.g. at the end of a block with curly braces
// Simple variable declarations, followed (or preceded) by statements using those variables
{ w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([rndElt(varBinder), v, " = ", makeExpr(d, b), ";", makeStatement(d - 1, b.concat([v]))]); } },
{ w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([makeStatement(d - 1, b.concat([v])), rndElt(varBinder), v, " = ", makeExpr(d, b), ";"]); } },
// Complex variable declarations, e.g. "const [a,b] = [3,4];"
{ w: 1, fun: function(d, b) { return cat([rndElt(varBinder), makeLetHead(d, b), ";", makeStatement(d - 1, b)]); } },
// Blocks
{ w: 2, fun: function(d, b) { return cat(["{", makeStatement(d, b), " }"]); } },
{ w: 2, fun: function(d, b) { return cat(["{", makeStatement(d - 1, b), makeStatement(d - 1, b), " }"]); } },
// "with" blocks
{ w: 2, fun: function(d, b) { return cat([maybeLabel(), "with", "(", makeExpr(d, b), ")", makeStatementOrBlock(d, b)]); } },
{ w: 2, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "with", "(", "{", v, ": ", makeExpr(d, b), "}", ")", makeStatementOrBlock(d, b.concat([v]))]); } },
// C-style "for" loops
// Two kinds of "for" loops: one with an expression as the first part, one with a var or let binding 'statement' as the first part.
// I'm not sure if arbitrary statements are allowed there; I think not.
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " = ", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeDestructuringLValue(d, b), " = ", makeExpr(d, b), "; ", makeExpr(d, b), "; ", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
// Various types of "for" loops, specially set up to test tracing, carefully avoiding infinite loops
{ w: 6, fun: makeTransparentIdiomaticLoop },
{ w: 6, fun: makeOpaqueIdiomaticLoop },
{ w: 6, fun: makeBranchUnstableLoop },
{ w: 8, fun: makeTypeUnstableLoop },
// "for..in" loops
// arbitrary-LHS marked as infloop because
// -- for (key in obj)
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeForInLHS(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
// -- for (key in generator())
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeForInLHS(d, b), " in ", "(", "(", makeFunction(d, b), ")", "(", makeExpr(d, b), ")", ")", ")", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " in ", "(", "(", makeFunction(d, b), ")", "(", makeExpr(d, b), ")", ")", ")", makeStatementOrBlock(d, b.concat([v]))]); } },
// -- for each (value in obj)
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), " for ", " each", "(", rndElt(varBinderFor), makeLValue(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), " for ", " each", "(", rndElt(varBinderFor), v, " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
// Modify something during a loop -- perhaps the thing being looped over
// Since we use "let" to bind the for-variables, and only do wacky stuff once, I *think* this is unlikely to hang.
// function(d, b) { return "let forCount = 0; for (let " + makeId(d, b) + " in " + makeExpr(d, b) + ") { if (forCount++ == " + rnd(3) + ") { " + makeStatement(d - 1, b) + " } }"; },
// Hoisty "for..in" loops. I don't know why this construct exists, but it does, and it hoists the initial-value expression above the loop.
// With "var" or "const", the entire thing is hoisted.
// With "let", only the value is hoisted, and it can be elim'ed as a useless statement.
// The first form could be an infinite loop because of "for (x.y in x)" with e4x.
// The last form is specific to JavaScript 1.7 (only).
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "for", "(", rndElt(varBinderFor), makeId(d, b), " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), v, " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v]))]); } },
{ w: 1, fun: function(d, b) { var v = makeNewId(d, b), w = makeNewId(d, b); return cat([maybeLabel(), "for", "(", rndElt(varBinderFor), "[", v, ", ", w, "]", " = ", makeExpr(d, b), " in ", makeExpr(d - 2, b), ") ", makeStatementOrBlock(d, b.concat([v, w]))]); } },
// do..while
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "while((", makeExpr(d, b), ") && 0)" /*don't split this, it's needed to avoid marking as infloop*/, makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "while", "(", makeExpr(d, b), ")", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "do ", makeStatementOrBlock(d, b), " while((", makeExpr(d, b), ") && 0)" /*don't split this, it's needed to avoid marking as infloop*/, ";"]); } },
{ w: 1, fun: function(d, b) { return "/*infloop*/" + cat([maybeLabel(), "do ", makeStatementOrBlock(d, b), " while", "(", makeExpr(d, b), ");"]); } },
// Switch statement
{ w: 3, fun: function(d, b) { return cat([maybeLabel(), "switch", "(", makeExpr(d, b), ")", " { ", makeSwitchBody(d, b), " }"]); } },
// "let" blocks, with bound variable used inside the block
{ w: 2, fun: function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, ")", " { ", makeStatement(d, b.concat([v])), " }"]); } },
// "let" blocks, with and without multiple bindings, with and without initial values
{ w: 2, fun: function(d, b) { return cat(["let ", "(", makeLetHead(d, b), ")", " { ", makeStatement(d, b), " }"]); } },
// Conditionals, perhaps with 'else if' / 'else'
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b)]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b)]); } },
// A tricky pair of if/else cases.
// In the SECOND case, braces must be preserved to keep the final "else" associated with the first "if".
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", "{", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), " else ", makeStatementOrBlock(d - 1, b), "}"]); } },
{ w: 1, fun: function(d, b) { return cat([maybeLabel(), "if(", makeExpr(d, b), ") ", "{", " if ", "(", makeExpr(d, b), ") ", makeStatementOrBlock(d - 1, b), "}", " else ", makeStatementOrBlock(d - 1, b)]); } },
// Expression statements
{ w: 5, fun: function(d, b) { return cat([makeExpr(d, b), ";"]); } },
{ w: 5, fun: function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); } },
// Exception-related statements :)
{ w: 6, fun: function(d, b) { return makeExceptionyStatement(d - 1, b) + makeExceptionyStatement(d - 1, b); } },
{ w: 7, fun: function(d, b) { return makeExceptionyStatement(d, b); } },
// Labels. (JavaScript does not have goto, but it does have break-to-label and continue-to-label).
{ w: 1, fun: function(d, b) { return cat(["L", ": ", makeStatementOrBlock(d, b)]); } },
// Function-declaration-statements, along with calls to those functions
{ w: 8, fun: makeNamedFunctionAndUse },
// Long script -- can confuse Spidermonkey's short vs long jmp or something like that.
// Spidermonkey's regexp engine is so slow for long strings that we have to bypass whatToTest :(
//{ w: 1, fun: function(d, b) { return strTimes("try{}catch(e){}", rnd(10000)); } },
{ w: 1, fun: function(d, b) { if (rnd(200)==0) return "/*DUPTRY" + rnd(10000) + "*/" + makeStatement(d - 1, b); return ";"; } },
// E4X "default xml namespace"
{ w: 1, fun: function(d, b) { return cat(["default ", "xml ", "namespace ", " = ", makeExpr(d, b), ";"]); } },
{ w: 1, fun: function(d, b) { return makeShapeyConstructorLoop(d, b); } },
// Replace a variable with a long linked list pointing to it. (Forces SpiderMonkey's GC marker into a stackless mode.)
{ w: 1, fun: function(d, b) { var x = makeId(d, b); return x + " = linkedList(" + x + ", " + (rnd(100) * rnd(100)) + ");"; } },
]);
function linkedList(x, n)
{
for (var i = 0; i < n; ++i)
x = {a: x};
return x;
}
function makeNamedFunctionAndUse(d, b) {
// Use a unique function name to make it less likely that we'll accidentally make a recursive call
var funcName = uniqueVarName();
var declStatement = cat(["/*hhh*/function ", funcName, "(", makeFormalArgList(d, b), ")", "{", makeStatement(d - 2, b), "}"]);
var useStatement;
if (rnd(2)) {
// Direct call
useStatement = cat([funcName, "(", makeActualArgList(d, b), ")", ";"]);
} else {
// Any statement, allowed to use the name of the function
useStatement = "/*iii*/" + makeStatement(d - 1, b.concat([funcName]));
}
if (rnd(2)) {
return declStatement + useStatement;
} else {
return useStatement + declStatement;
}
}
function makePrintStatement(d, b)
{
if (rnd(2) && b.length)
return "print(" + rndElt(b) + ");";
else
return "print(" + makeExpr(d, b) + ");";
}
function maybeLabel()
{
if (rnd(4) == 1)
return cat([rndElt(["L", "M"]), ":"]);
else
return "";
}
function uniqueVarName()
{
// Make a random variable name.
var i, s = "";
for (i = 0; i < 6; ++i)
s += String.fromCharCode(97 + rnd(26)); // a lowercase english letter
return s;
}
function makeSwitchBody(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var haveSomething = false;
var haveDefault = false;
var output = "";
do {
if (!haveSomething || rnd(2)) {
// Want a case/default (or, if this is the beginning, "need").
if (!haveDefault && rnd(2)) {
output += "default: ";
haveDefault = true;
}
else {
// cases with numbers (integers?) have special optimizations that affect order when decompiling,
// so be sure to test those well in addition to testing complicated expressions.
output += "case " + (rnd(2) ? rnd(10) : makeExpr(d, b)) + ": ";
}
haveSomething = true;
}
// Might want a statement.
if (rnd(2))
output += makeStatement(d, b)
// Might want to break, or might want to fall through.
if (rnd(2))
output += "break; ";
if (rnd(2))
--d;
} while (d && rnd(5));
return output;
}
function makeLittleStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (rnd(4) == 1)
return makeStatement(d, b);
return (rndElt(littleStatementMakers))(d, b);
}
var littleStatementMakers =
[
// Tiny
function(d, b) { return cat([";"]); }, // e.g. empty "if" block
function(d, b) { return cat(["{", "}"]); }, // e.g. empty "if" block
function(d, b) { return cat([""]); },
// Force garbage collection
function(d, b) { return "gc()"; },
// Throw stuff.
function(d, b) { return cat(["throw ", makeExpr(d, b), ";"]); },
// Break/continue [to label].
function(d, b) { return cat([rndElt(["continue", "break"]), " ", rndElt(["L", "M", "", ""]), ";"]); },
// Named and unnamed functions (which have different behaviors in different places: both can be expressions,
// but unnamed functions "want" to be expressions and named functions "want" to be special statements)
function(d, b) { return makeFunction(d, b); },
// Return, yield
function(d, b) { return cat(["return ", makeExpr(d, b), ";"]); },
function(d, b) { return "return;"; }, // return without a value is allowed in generators; return with a value is not.
function(d, b) { return cat(["yield ", makeExpr(d, b), ";"]); }, // note: yield can also be a left-unary operator, or something like that
function(d, b) { return "yield;"; },
// Expression statements
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat([makeExpr(d, b), ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", ";"]); },
// Turn on gczeal in the middle of something
function(d, b) { return "gczeal(" + makeZealLevel() + ")" + ";"; }
];
// makeStatementOrBlock exists because often, things have different behaviors depending on where there are braces.
// for example, if braces are added or removed, the meaning of "let" can change.
function makeStatementOrBlock(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return (rndElt(statementBlockMakers))(d - 1, b);
}
var statementBlockMakers = [
function(d, b) { return makeStatement(d, b); },
function(d, b) { return makeStatement(d, b); },
function(d, b) { return cat(["{", makeStatement(d, b), " }"]); },
function(d, b) { return cat(["{", makeStatement(d - 1, b), makeStatement(d - 1, b), " }"]); },
]
// Extra-hard testing for try/catch/finally and related things.
function makeExceptionyStatement(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (d < 1)
return makeLittleStatement(d, b);
return (rndElt(exceptionyStatementMakers))(d, b);
}
var exceptionyStatementMakers = [
function(d, b) { return makeTryBlock(d, b); },
function(d, b) { return makeStatement(d, b); },
function(d, b) { return makeLittleStatement(d, b); },
function(d, b) { return "return;" }, // return without a value can be mixed with yield
function(d, b) { return cat(["return ", makeExpr(d, b), ";"]); },
function(d, b) { return cat(["yield ", makeExpr(d, b), ";"]); },
function(d, b) { return cat(["throw ", makeId(d, b), ";"]); },
function(d, b) { return "throw StopIteration;"; },
function(d, b) { return "this.zzz.zzz;"; }, // throws; also tests js_DecompileValueGenerator in various locations
function(d, b) { return cat([makeId(d, b), " = ", makeId(d, b), ";"]); },
function(d, b) { return cat([makeLValue(d, b), " = ", makeId(d, b), ";"]); },
// Iteration uses StopIteration internally.
// Iteration is also useful to test because it asserts that there is no pending exception.
function(d, b) { var v = makeNewId(d, b); return "for(let " + v + " in []);"; },
function(d, b) { var v = makeNewId(d, b); return "for(let " + v + " in " + makeMixedTypeArray(d, b) + ") " + makeExceptionyStatement(d, b.concat([v])); },
// Brendan says these are scary places to throw: with, let block, lambda called immediately in let expr.
// And I think he was right.
function(d, b) { return "with({}) " + makeExceptionyStatement(d, b); },
function(d, b) { return "with({}) { " + makeExceptionyStatement(d, b) + " } "; },
function(d, b) { var v = makeNewId(d, b); return "let(" + v + ") { " + makeExceptionyStatement(d, b.concat([v])) + "}"; },
function(d, b) { var v = makeNewId(d, b); return "let(" + v + ") ((function(){" + makeExceptionyStatement(d, b.concat([v])) + "})());" },
function(d, b) { return "let(" + makeLetHead(d, b) + ") { " + makeExceptionyStatement(d, b) + "}"; },
function(d, b) { return "let(" + makeLetHead(d, b) + ") ((function(){" + makeExceptionyStatement(d, b) + "})());" },
// Commented out due to causing too much noise on stderr and causing a nonzero exit code :/
/*
// Generator close hooks: called during GC in this case!!!
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })().next()"; },
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })()"; },
function(d, b) { return "(function () { try { yield " + makeExpr(d, b) + " } finally { " + makeStatement(d, b) + " } })"; },
function(d, b) {
return "function gen() { try { yield 1; } finally { " + makeStatement(d, b) + " } } var i = gen(); i.next(); i = null;";
}
*/
];
function makeTryBlock(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// Catches: 1/6 chance of having none
// Catches: maybe 2 + 1/2
// So approximately 4 recursions into makeExceptionyStatement on average!
// Therefore we want to keep the chance of recursing too much down...
d = d - rnd(3);
var s = cat(["try", " { ", makeExceptionyStatement(d, b), " } "]);
var numCatches = 0;
while(rnd(3) == 0) {
// Add a guarded catch, using an expression or a function call.
++numCatches;
if (rnd(2))
s += cat(["catch", "(", makeId(d, b), " if ", makeExpr(d, b), ")", " { ", makeExceptionyStatement(d, b), " } "]);
else
s += cat(["catch", "(", makeId(d, b), " if ", "(function(){", makeExceptionyStatement(d, b), "})())", " { ", makeExceptionyStatement(d, b), " } "]);
}
if (rnd(2)) {
// Add an unguarded catch.
++numCatches;
s += cat(["catch", "(", makeId(d, b), ")", " { ", makeExceptionyStatement(d, b), " } "]);
}
if (numCatches == 0 || rnd(2) == 1) {
// Add a finally.
s += cat(["finally", " { ", makeExceptionyStatement(d, b), " } "]);
}
return s;
}
// Creates a string that sorta makes sense as an expression
function makeExpr(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0 || (rnd(7) == 1))
return makeTerm(d - 1, b);
if (rnd(6) == 1 && b.length)
return rndElt(b);
if (rnd(10) == 1)
return makeImmediateRecursiveCall(d, b);
d = rnd(d); // !
var expr = (rndElt(exprMakers))(d, b);
if (rnd(4) == 1)
return "(" + expr + ")";
else
return expr;
}
var binaryOps = [
// Long-standing JavaScript operators, roughly in order from http://www.codehouse.com/javascript/precedence/
" * ", " / ", " % ", " + ", " - ", " << ", " >> ", " >>> ", " < ", " > ", " <= ", " >= ", " instanceof ", " in ", " == ", " != ", " === ", " !== ",
" & ", " | ", " ^ ", " && ", " || ", " = ", " *= ", " /= ", " %= ", " += ", " -= ", " <<= ", " >>= ", " >>>= ", " &= ", " ^= ", " |= ", " , ",
// . is special, so test it as a group of right-unary ops, a special exprMaker for property access, and a special exprMaker for the xml filtering predicate operator
// " . ",
];
if (haveE4X) {
binaryOps = binaryOps.concat([
// Binary operators added by E4X
" :: ", " .. ", " @ ",
// Frequent combinations of E4X things (and "*" namespace, which isn't produced by this fuzzer otherwise)
" .@ ", " .@*:: ", " .@x:: ",
]);
}
var leftUnaryOps = [
"--", "++",
"!", "+", "-", "~",
"void ", "typeof ", "delete ",
"new ", // but note that "new" can also be a very strange left-binary operator
"yield " // see http://www.python.org/dev/peps/pep-0342/ . Often needs to be parenthesized, so there's also a special exprMaker for it.
];
var rightUnaryOps = [
"++", "--",
];
if (haveE4X)
rightUnaryOps = rightUnaryOps.concat([".*", ".@foo", ".@*"]);
var specialProperties = [
"x", "y",
"__iterator__", "__count__",
"__noSuchMethod__",
"__parent__", "__proto__", "constructor", "prototype",
"wrappedJSObject",
"length",
// Typed arraays
"buffer", "byteLength", "byteOffset",
// E4X
"ignoreComments", "ignoreProcessingInstructions", "ignoreWhitespace",
"prettyPrinting", "prettyIndent"
]
function makeSpecialProperty(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return rndElt(specialProperties);
}
function makeNamespacePrefix(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch (rnd(7)) {
case 0: return "function::";
case 1: return makeId(d, b) + "::";
default: return "";
}
}
// An incomplete list of builtin methods for various data types.
var objectMethods = [
// String
"fromCharCode",
// Strings
"charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "localeCompare",
"match", "quote", "replace", "search", "slice", "split", "substr", "substring",
"toLocaleUpperCase", "toLocaleLowerCase", "toLowerCase", "toUpperCase",
// String methods added in ES5
"trim", "trimLeft", "trimRight",
// Regular expressions
"test", "exec",
// Arrays
"splice", "shift", "sort", "pop", "push", "reverse", "unshift",
"concat", "join", "slice",
// Array extras in JavaScript 1.6
"map", "forEach", "filter", "some", "every", "indexOf", "lastIndexOf",
// Array extras in JavaScript 1.8
"reduce", "reduceRight",
// Functions
"call", "apply",
// Date
"now", "parse", "UTC",
// Date instances
"getDate", "setDay", // many more not listed
// Number
"toExponential", "toFixed", "toLocaleString", "toPrecision",
// General -- defined on each type of object, but wit a different implementation
"toSource", "toString", "valueOf", "constructor", "prototype", "__proto__",
// General -- same implementation inherited from Object.prototype
"__defineGetter__", "__defineSetter__", "hasOwnProperty", "isPrototypeOf", "__lookupGetter__", "__lookupSetter__", "__noSuchMethod__", "propertyIsEnumerable", "unwatch", "watch",
// Things that are only built-in on Object itself
"defineProperty", "defineProperties", "create", "getOwnPropertyDescriptor", "getPrototypeOf",
// E4X functions on XML objects
"addNamespace", "appendChild", "attribute", "attributes", "child", "childIndex", "children", "comments", "contains", "copy", "descendants", "elements", "hasOwnProperty", "hasComplexContent", "hasSimpleContent", "isScopeNamespace", "insertChildAfter", "insertChildBefore", "length", "localName", "name", "namespace", "namespaceDeclarations", "nodeKind", "normalize", "parent", "processingInstructions", "prependChild", "propertyIsEnumerable", "removeNamespace", "replace", "setChildren", "setLocalName", "setName", "setNamespace", "text", "toString", "toXMLString", "valueOf",
// E4X functions on the XML constructor
"settings", "setSettings", "defaultSettings",
// E4X functions on the global object
"isXMLName",
];
var exprMakers =
[
// Left-unary operators
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([rndElt(leftUnaryOps), makeExpr(d, b)]); },
// Right-unary operators
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(rightUnaryOps)]); },
// Special properties: we love to set them!
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeFunction(d, b)]); },
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeExpr(d, b)]); },
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeSpecialProperty(d, b), " = ", makeFunction(d, b)]); },
// Methods
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), rndElt(objectMethods)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), rndElt(objectMethods), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), "valueOf", "(", uneval("number"), ")"]); },
// Binary operators
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), rndElt(binaryOps), makeExpr(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
function(d, b) { return cat([makeId(d, b), rndElt(binaryOps), makeId(d, b)]); },
// Ternary operator
function(d, b) { return cat([makeExpr(d, b), " ? ", makeExpr(d, b), " : ", makeExpr(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), " ? ", makeExpr(d, b), " : ", makeExpr(d, b)]); },
// In most contexts, yield expressions must be parenthesized, so including explicitly parenthesized yields makes actually-compiling yields appear more often.
function(d, b) { return cat(["yield ", makeExpr(d, b)]); },
function(d, b) { return cat(["(", "yield ", makeExpr(d, b), ")"]); },
// Array functions (including extras). The most interesting are map and filter, I think.
// These are mostly interesting to fuzzers in the sense of "what happens if i do strange things from a filter function?" e.g. modify the array.. :)
// This fuzzer isn't the best for attacking this kind of thing, since it's unlikely that the code in the function will attempt to modify the array or make it go away.
// The second parameter to "map" is used as the "this" for the function.
function(d, b) { return cat(["[11,12,13,14]", ".", rndElt(["map", "filter", "some", "sort"]) ]); },
function(d, b) { return cat(["[15,16,17,18]", ".", rndElt(["map", "filter", "some", "sort"]), "(", makeFunction(d, b), ", ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["[", makeExpr(d, b), "]", ".", rndElt(["map", "filter", "some", "sort"]), "(", makeFunction(d, b), ")"]); },
// RegExp replace. This is interesting for the same reason as array extras. Also, in SpiderMonkey, the "this" argument is weird (obj.__parent__?)
function(d, b) { return cat(["'fafafa'", ".", "replace", "(", "/", "a", "/", "g", ", ", makeFunction(d, b), ")"]); },
// Dot (property access)
function(d, b) { return cat([makeId(d, b), ".", makeNamespacePrefix(d, b), makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeNamespacePrefix(d, b), makeId(d, b)]); },
// Index into array
function(d, b) { return cat([ makeExpr(d, b), "[", makeExpr(d, b), "]"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "[", makeExpr(d, b), "]"]); },
// Containment in an array or object (or, if this happens to end up on the LHS of an assignment, destructuring)
function(d, b) { return cat([maybeSharpDecl(), "[", makeExpr(d, b), "]"]); },
function(d, b) { return cat([maybeSharpDecl(), "(", "{", makeId(d, b), ": ", makeExpr(d, b), "}", ")"]); },
// Sharps on random stuff?
function(d, b) { return cat([maybeSharpDecl(), makeExpr(d, b)]); },
// Functions: called immediately/not
function(d, b) { return makeFunction(d, b); },
function(d, b) { return makeFunction(d, b) + ".prototype"; },
function(d, b) { return cat(["(", makeFunction(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
// Try to call things that may or may not be functions.
function(d, b) { return cat([ makeExpr(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat([ makeFunction(d, b), "(", makeActualArgList(d, b), ")"]); },
// Try to test function.call heavily.
function(d, b) { return cat(["(", makeFunction(d, b), ")", ".", "call", "(", makeExpr(d, b), ", ", makeActualArgList(d, b), ")"]); },
// Binary "new", with and without clarifying parentheses, with expressions or functions
function(d, b) { return cat(["new ", makeExpr(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", "(", makeExpr(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", makeFunction(d, b), "(", makeActualArgList(d, b), ")"]); },
function(d, b) { return cat(["new ", "(", makeFunction(d, b), ")", "(", makeActualArgList(d, b), ")"]); },
// Sometimes we do crazy stuff, like putting a statement where an expression should go. This frequently causes a syntax error.
function(d, b) { return stripSemicolon(makeLittleStatement(d, b)); },
function(d, b) { return ""; },
// Let expressions -- note the lack of curly braces.
function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, ") ", makeExpr(d - 1, b.concat([v]))]); },
function(d, b) { var v = makeNewId(d, b); return cat(["let ", "(", v, " = ", makeExpr(d - 1, b), ") ", makeExpr(d - 1, b.concat([v]))]); },
function(d, b) { return cat(["let ", "(", makeLetHead(d, b), ") ", makeExpr(d, b)]); },
// Array comprehensions (JavaScript 1.7)
function(d, b) { return cat(["[", makeExpr(d, b), makeComprehension(d, b), "]"]); },
// Generator expressions (JavaScript 1.8)
function(d, b) { return cat([ makeExpr(d, b), makeComprehension(d, b) ]); },
function(d, b) { return cat(["(", makeExpr(d, b), makeComprehension(d, b), ")"]); },
// Comments and whitespace
function(d, b) { return cat([" /* Comment */", makeExpr(d, b)]); },
function(d, b) { return cat(["\n", makeExpr(d, b)]); }, // perhaps trigger semicolon insertion and stuff
function(d, b) { return cat([makeExpr(d, b), "\n"]); },
// LValue as an expression
function(d, b) { return cat([makeLValue(d, b)]); },
// Assignment (can be destructuring)
function(d, b) { return cat([ makeLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat([ makeLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat(["(", makeLValue(d, b), " = ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeLValue(d, b), ")", " = ", makeExpr(d, b) ]); },
// Destructuring assignment
function(d, b) { return cat([ makeDestructuringLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat([ makeDestructuringLValue(d, b), " = ", makeExpr(d, b) ]); },
function(d, b) { return cat(["(", makeDestructuringLValue(d, b), " = ", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeDestructuringLValue(d, b), ")", " = ", makeExpr(d, b) ]); },
// Destructuring assignment with lots of group assignment
function(d, b) { return cat([makeDestructuringLValue(d, b), " = ", makeDestructuringLValue(d, b)]); },
// Modifying assignment, with operators that do various coercions
function(d, b) { return cat([makeLValue(d, b), rndElt(["|=", "%=", "+=", "-="]), makeExpr(d, b)]); },
// Watchpoints (similar to setters)
function(d, b) { return cat([makeExpr(d, b), ".", "watch", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "unwatch", "(", uneval(makeId(d, b)), ")"]); },
// ES5 getter/setter syntax, imperative (added in Gecko 1.9.3?)
function(d, b) { return cat(["Object.defineProperty", "(", makeId(d, b), ", ", simpleSource(makeId(d, b)), ", ", makePropertyDescriptor(d, b), ")"]); },
// Old getter/setter syntax, imperative
function(d, b) { return cat([makeExpr(d, b), ".", "__defineGetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "__defineSetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat(["this", ".", "__defineGetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
function(d, b) { return cat(["this", ".", "__defineSetter__", "(", uneval(makeId(d, b)), ", ", makeFunction(d, b), ")"]); },
// Very old getter/setter syntax, imperative (removed in Gecko 1.9.3)
function(d, b) { return cat([makeId(d, b), ".", makeId(d, b), " ", rndElt(["getter", "setter"]), "= ", makeFunction(d, b)]); },
// Object literal
function(d, b) { return cat(["(", "{", makeObjLiteralPart(d, b), " }", ")"]); },
function(d, b) { return cat(["(", "{", makeObjLiteralPart(d, b), ", ", makeObjLiteralPart(d, b), " }", ")"]); },
// Test js_ReportIsNotFunction heavily.
function(d, b) { return "(p={}, (p.z = " + makeExpr(d, b) + ")())"; },
// Test js_ReportIsNotFunction heavily.
// Test decompilation for ".keyword" a bit.
// Test throwing-into-generator sometimes.
function(d, b) { return cat([makeExpr(d, b), ".", "throw", "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat([makeExpr(d, b), ".", "yoyo", "(", makeExpr(d, b), ")"]); },
// Throws, but more importantly, tests js_DecompileValueGenerator in various contexts.
function(d, b) { return "this.zzz.zzz"; },
// Test eval in various contexts. (but avoid clobbering eval)
// Test the special "obj.eval" and "eval(..., obj)" forms.
function(d, b) { return makeExpr(d, b) + ".eval(" + makeExpr(d, b) + ")"; },
function(d, b) { return "eval(" + uneval(makeExpr(d, b)) + ")"; },
function(d, b) { return "eval(" + uneval(makeExpr(d, b)) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return "eval(" + uneval(makeStatement(d, b)) + ")"; },
function(d, b) { return "eval(" + uneval(makeStatement(d, b)) + ", " + makeExpr(d, b) + ")"; },
// Test evalcx: sandbox creation
function(d, b) { return "evalcx('')"; },
function(d, b) { return "evalcx('lazy')"; },
// Test evalcx: sandbox use
function(d, b) { return "evalcx(" + uneval(makeExpr(d, b)) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return "evalcx(" + uneval(makeStatement(d, b)) + ", " + makeExpr(d, b) + ")"; },
// Uneval needs more testing than it will get accidentally. No cat() because I don't want uneval clobbered (assigned to) accidentally.
function(d, b) { return "(uneval(" + makeExpr(d, b) + "))"; },
// Constructors. No cat() because I don't want to screw with the constructors themselves, just call them.
function(d, b) { return "new " + rndElt(constructors) + "(" + makeActualArgList(d, b) + ")"; },
function(d, b) { return rndElt(constructors) + "(" + makeActualArgList(d, b) + ")"; },
// Turn on gczeal in the middle of something
function(d, b) { return "gczeal(" + makeZealLevel() + ")"; },
// Unary Math functions
function (d, b) { return "Math." + rndElt(["abs", "acos", "asin", "atan", "ceil", "cos", "exp", "floor", "log", "round", "sin", "sqrt", "tan"]) + "(" + makeExpr(d, b) + ")"; },
// Binary Math functions
function (d, b) { return "Math." + rndElt(["atan2", "max", "min", "pow"]) + "(" + makeExpr(d, b) + ", " + makeExpr(d, b) + ")"; },
// Gecko wrappers
function(d, b) { return "new XPCNativeWrapper(" + makeExpr(d, b) + ")"; },
function(d, b) { return "new XPCSafeJSObjectWrapper(" + makeExpr(d, b) + ")"; },
// Harmony proxy creation: object, function without constructTrap, function with constructTrap
function(d, b) { return makeId(d, b) + " = " + "Proxy.create(" + makeProxyHandler(d, b) + ", " + makeExpr(d, b) + ")"; },
function(d, b) { return makeId(d, b) + " = " + "Proxy.createFunction(" + makeProxyHandler(d, b) + ", " + makeFunction(d, b) + ")"; },
function(d, b) { return makeId(d, b) + " = " + "Proxy.createFunction(" + makeProxyHandler(d, b) + ", " + makeFunction(d, b) + ", " + makeFunction(d, b) + ")"; },
function(d, b) { return cat(["delete", " ", makeId(d, b), ".", makeId(d, b)]); },
];
// In addition, can always use "undefined" or makeFunction
// Forwarding proxy code based on http://wiki.ecmascript.org/doku.php?id=harmony:proxies "Example: a no-op forwarding proxy"
// The letter 'x' is special.
var proxyHandlerProperties = {
getOwnPropertyDescriptor: {
empty: "function(){}",
forward: "function(name) { var desc = Object.getOwnPropertyDescriptor(x); desc.configurable = true; return desc; }"
},
getPropertyDescriptor: {
empty: "function(){}",
forward: "function(name) { var desc = Object.getPropertyDescriptor(x); desc.configurable = true; return desc; }"
},
defineProperty: {
empty: "function(){}",
forward: "function(name, desc) { Object.defineProperty(x, name, desc); }"
},
getOwnPropertyNames: {
empty: "function() { return []; }",
forward: "function() { return Object.getOwnPropertyNames(x); }"
},
delete: {
empty: "function() { return true; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return delete x[name]; }"
},
fix: {
empty: "function() { return []; }",
yes: "function() { return []; }",
no: "function() { }",
forward: "function() { if (Object.isFrozen(x)) { return Object.getOwnProperties(x); } }"
},
has: {
empty: "function() { return false; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return name in x; }"
},
hasOwn: {
empty: "function() { return false; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(name) { return Object.prototype.hasOwnProperty.call(x, name); }"
},
get: {
empty: "function() { return undefined }",
forward: "function(receiver, name) { return x[name]; }",
bind: "function(receiver, name) { var prop = x[name]; return (typeof prop) === 'function' ? prop.bind(x) : prop; }"
},
set: {
empty: "function() { return true; }",
yes: "function() { return true; }",
no: "function() { return false; }",
forward: "function(receiver, name, val) { x[name] = val; return true; }"
},
iterate: {
empty: "function() { return (function() { throw StopIteration; }); }",
forward: "function() { return (function() { for (var name in x) { yield name; } })(); }"
},
enumerate: {
empty: "function() { return []; }",
forward: "function() { var result = []; for (var name in x) { result.push(name); }; return result; }"
},
enumerateOwn: {
empty: "function() { return []; }",
forward: "function() { return Object.keys(x); }"
}
}
function makeProxyHandlerFactory(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
try { // in case we screwed Object.prototype, breaking proxyHandlerProperties
var preferred = rndElt(["empty", "forward", "yes", "no", "bind"]);
var fallback = rndElt(["empty", "forward"]);
var fidelity = 1; // Math.random();
var handlerFactoryText = "(function handlerFactory(x) {";
handlerFactoryText += "return {"
if (rnd(2)) {
// handlerFactory has an argument 'x'
bp = b.concat(['x']);
} else {
// handlerFactory has no argument
handlerFactoryText = handlerFactoryText.replace(/x/, "");
bp = b;
}
for (var p in proxyHandlerProperties) {
var funText;
if (preferred[p] && Math.random() < fidelity) {
funText = proxyMunge(proxyHandlerProperties[p][preferred], p);
} else {
switch(rnd(7)) {
case 0: funText = makeFunction(d - 3, bp); break;
case 1: funText = "undefined"; break;
default: funText = proxyMunge(proxyHandlerProperties[p][fallback], p);
}
}
handlerFactoryText += p + ": " + funText + ", ";
}
handlerFactoryText += "}; })"
return handlerFactoryText;
} catch(e) {
return "({/* :( */})";
}
}
function proxyMunge(funText, p)
{
funText = funText.replace(/\{/, "{ var yum = 'PCAL'; dumpln(yum + 'LED: " + p + "');");
return funText;
}
function makeProxyHandler(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return makeProxyHandlerFactory(d, b) + "(" + makeExpr(d - 1, b) + ")"
}
function makeShapeyConstructor(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var argName = uniqueVarName();
var t = rnd(4) ? "this" : argName;
var funText = "function shapeyConstructor(" + argName + "){";
var bp = b.concat([argName]);
var nPropNames = rnd(6) + 1;
var propNames = [];
for (var i = 0; i < nPropNames; ++i) {
propNames[i] = makeNewId(d, b);
}
var nStatements = rnd(11);
for (var i = 0; i < nStatements; ++i) {
var propName = rndElt(propNames);
if (rnd(5) == 0) {
funText += "if (" + (rnd(2) ? argName : makeExpr(d, bp)) + ") ";
}
switch(rnd(7)) {
case 0: funText += "delete " + t + "." + propName + ";"; break;
case 1: funText += "Object.defineProperty(" + t + ", " + uneval(propName) + ", " + makePropertyDescriptor(d, bp) + ");"; break;
case 2: funText += "{ " + makeStatement(d, bp) + " } "; break;
case 3: funText += t + "." + propName + " = " + makeExpr(d, bp) + ";"; break;
case 4: funText += t + "." + propName + " = " + makeFunction(d, bp) + ";"; break;
case 5: funText += "for (var ytq" + uniqueVarName() + " in " + t + ") { }"; break;
default: funText += t + "." + propName + " = " + makeShapeyValue(d, bp) + ";"; break;
}
}
funText += "return " + t + "; }";
return funText;
}
function makeShapeyConstructorLoop(d, b)
{
var a = makeMixedTypeArray(d, b);
var v = makeNewId(d, b);
var v2 = uniqueVarName(d, b);
var bvv = b.concat([v, v2]);
return makeShapeyConstructor(d - 1, b) +
"/*tLoopC*/for each (let " + v + " in " + a + ") { " +
"try{" +
"let " + v2 + " = " + rndElt(["new ", ""]) + "shapeyConstructor(" + v + "); print('EETT'); " +
//"print(uneval(" + v2 + "));" +
makeStatement(d - 2, bvv) +
"}catch(e){print('TTEE ' + e); }" +
" }";
}
function makePropertyDescriptor(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var s = "({"
switch(rnd(3)) {
case 0:
// Data descriptor. Can have 'value' and 'writable'.
if (rnd(2)) s += "value: " + makeExpr(d, b) + ", ";
if (rnd(2)) s += "writable: " + makeBoolean(d, b) + ", ";
break;
case 1:
// Accessor descriptor. Can have 'get' and 'set'.
if (rnd(2)) s += "get: " + makeFunction(d, b) + ", ";
if (rnd(2)) s += "set: " + makeFunction(d, b) + ", ";
break;
default:
}
if (rnd(2)) s += "configurable: " + makeBoolean(d, b) + ", ";
if (rnd(2)) s += "enumerable: " + makeBoolean(d, b) + ", ";
// remove trailing comma
if (s.length > 2)
s = s.substr(0, s.length - 2)
s += "})";
return s;
}
function makeBoolean(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(10) == 0) return makeExpr(d - 2, b);
return rndElt(["true", "false"]);
}
function makeZealLevel()
{
// gczeal is really slow, so only turn it on very occasionally.
switch(rnd(100)) {
case 0:
return "2";
case 1:
return "1";
default:
return "0";
}
}
if (haveE4X) {
exprMakers = exprMakers.concat([
// XML filtering predicate operator! It isn't lexed specially; there can be a space between the dot and the lparen.
function(d, b) { return cat([makeId(d, b), ".", "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat([makeE4X(d, b), ".", "(", makeExpr(d, b), ")"]); },
]);
}
var constructors = [
"Error", "RangeError", "Exception",
"Function", "RegExp", "String", "Array", "Object", "Number", "Boolean",
// "Date", // commented out due to appearing "random, but XXX want to use it sometimes...
"Iterator",
// E4X
"Namespace", "QName", "XML", "XMLList",
"AttributeName" // not listed as a constructor in e4x spec, but exists!
];
function maybeSharpDecl()
{
if (rnd(3) == 0)
return cat(["#", "" + (rnd(3)), "="]);
else
return "";
}
function makeObjLiteralPart(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(8))
{
// Old-style literal getter/setter
case 0: return cat([makeId(d, b), " getter: ", makeFunction(d, b)]);
case 1: return cat([makeId(d, b), " setter: ", makeFunction(d, b)]);
// New-style literal getter/setter
case 2: return cat([" get ", makeId(d, b), maybeName(d, b), "(", makeFormalArgList(d - 1, b), ")", makeFunctionBody(d, b)]);
case 3: return cat([" set ", makeId(d, b), maybeName(d, b), "(", makeFormalArgList(d - 1, b), ")", makeFunctionBody(d, b)]);
/*
case 3: return cat(["toString: ", makeFunction(d, b), "}", ")"]);
case 4: return cat(["toString: function() { return this; } }", ")"]); }, // bwahaha
case 5: return cat(["toString: function() { return " + makeExpr(d, b) + "; } }", ")"]); },
case 6: return cat(["valueOf: ", makeFunction(d, b), "}", ")"]); },
case 7: return cat(["valueOf: function() { return " + makeExpr(d, b) + "; } }", ")"]); },
*/
// Note that string literals, integer literals, and float literals are also good!
// (See https://bugzilla.mozilla.org/show_bug.cgi?id=520696.)
default: return cat([makeId(d, b), ": ", makeExpr(d, b)]);
}
}
function makeFunction(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if(rnd(5) == 1)
return makeExpr(d, b);
return (rndElt(functionMakers))(d, b);
}
function makeFunPrefix(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(20)) {
// Leaving this stuff out until bug 381203 is fixed.
// Eventually this stuff should be moved from functionMakers to somewhere
// like statementMakers, right?
// case 0: return "getter ";
// case 1: return "setter ";
default: return "";
}
}
function maybeName(d, b)
{
if (rnd(2) == 0)
return " " + makeId(d, b) + " ";
else
return "";
}
function makeFunctionBody(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
switch(rnd(4)) {
case 0: return cat([" { ", makeStatement(d - 1, b), " } "]);
case 1: return cat([" { ", "return ", makeExpr(d, b), " } "]);
case 2: return cat([" { ", "yield ", makeExpr(d, b), " } "]);
default: return makeExpr(d, b); // make an "expression closure"
}
}
var functionMakers = [
// Note that a function with a name is sometimes considered a statement rather than an expression.
// Functions and expression closures
function(d, b) { var v = makeNewId(d, b); return cat([makeFunPrefix(d, b), "function", " ", maybeName(d, b), "(", v, ")", makeFunctionBody(d, b.concat([v]))]); },
function(d, b) { return cat([makeFunPrefix(d, b), "function", " ", maybeName(d, b), "(", makeFormalArgList(d, b), ")", makeFunctionBody(d, b)]); },
// Methods
function(d, b) { return cat([makeExpr(d, b), ".", rndElt(objectMethods)]); },
// The identity function
function(d, b) { return "function(q) { return q; }" },
// A function that does something
function(d, b) { return "function(y) { " + makeStatement(d, b.concat(["y"])) + " }" },
// A function that computes something
function(d, b) { return "function(y) { return " + makeExpr(d, b.concat(["y"])) + " }" },
// A generator that does something
function(d, b) { return "function(y) { yield y; " + makeStatement(d, b.concat(["y"])) + "; yield y; }" },
// A generator expression -- kinda a function??
function(d, b) { return "(1 for (x in []))"; },
// A simple wrapping pattern
function(d, b) { return "/*wrap1*/(function(){ " + makeStatement(d, b) + "return " + makeFunction(d, b) + "})()" },
// Wrapping with upvar: escaping, may or may not be modified
function(d, b) { var v1 = uniqueVarName(); var v2 = uniqueVarName(); return "/*wrap2*/(function(){ var " + v1 + " = " + makeExpr(d, b) + "; var " + v2 + " = " + makeFunction(d, b.concat([v1])) + "; return " + v2 + ";})()"; },
// Wrapping with upvar: non-escaping
function(d, b) { var v1 = uniqueVarName(); var v2 = uniqueVarName(); return "/*wrap3*/(function(){ var " + v1 + " = " + makeExpr(d, b) + "; (" + makeFunction(d, b.concat([v1])) + ")(); })"; },
// Bind
function(d, b) { return "Function.prototype.bind" },
function(d, b) { return "(" + makeFunction(d-1, b) + ").bind" },
function(d, b) { return "(" + makeFunction(d-1, b) + ").bind(" + makeActualArgList(d, b) + ")" },
// Special functions that might have interesting results, especially when called "directly" by things like string.replace or array.map.
function(d, b) { return "eval" }, // eval is interesting both for its "no indirect calls" feature and for the way it's implemented in spidermonkey (a special bytecode).
function(d, b) { return "(let (e=eval) e)" },
function(d, b) { return "new Function" }, // this won't be interpreted the same way for each caller of makeFunction, but that's ok
function(d, b) { return "(new Function(" + uneval(makeStatement(d, b)) + "))"; },
function(d, b) { return "Function" }, // without "new"! it does seem to work...
function(d, b) { return "gc" },
function(d, b) { return "Object.defineProperty" },
function(d, b) { return "Object.defineProperties" },
function(d, b) { return "Object.create" },
function(d, b) { return "Object.getOwnPropertyDescriptor" },
function(d, b) { return "Object.getOwnPropertyNames" },
function(d, b) { return "Object.getPrototypeOf" },
function(d, b) { return "Object.keys" },
function(d, b) { return "Object.preventExtensions" },
function(d, b) { return "Object.seal" },
function(d, b) { return "Object.freeze" },
function(d, b) { return "decodeURI" },
function(d, b) { return "decodeURIComponent" },
function(d, b) { return "encodeURI" },
function(d, b) { return "encodeURIComponent" },
function(d, b) { return "Array.reduce" }, // also known as Array.prototype.reduce
function(d, b) { return "Array.isArray" },
function(d, b) { return "JSON.parse" },
function(d, b) { return "JSON.stringify" }, // has interesting arguments...
function(d, b) { return "Math.sin" },
function(d, b) { return "Math.pow" },
function(d, b) { return "/a/gi" }, // in Firefox, at least, regular expressions can be used as functions: e.g. "hahaa".replace(/a+/g, /aa/g) is "hnullhaa"!
function(d, b) { return "XPCNativeWrapper" },
function(d, b) { return "XPCSafeJSObjectWrapper" },
function(d, b) { return "WebGLIntArray" },
function(d, b) { return "WebGLFloatArray" },
function(d, b) { return "Int8Array" },
function(d, b) { return "Uint8Array" },
function(d, b) { return "Int16Array" },
function(d, b) { return "Uint16Array" },
function(d, b) { return "Int32Array" },
function(d, b) { return "Uint32Array" },
function(d, b) { return "Float32Array" },
function(d, b) { return "Float64Array" },
function(d, b) { return "Uint8ClampedArray" },
function(d, b) { return "ArrayBuffer" },
function(d, b) { return "Proxy.isTrapping" },
function(d, b) { return "Proxy.create" },
function(d, b) { return "Proxy.createFunction" },
function(d, b) { return "wrap" }, // spidermonkey shell shortcut for a native forwarding proxy
function(d, b) { return makeProxyHandlerFactory(d, b); },
function(d, b) { return makeShapeyConstructor(d, b); },
];
/*
David Anderson suggested creating the following recursive structures:
- recurse down an array of mixed types, car cdr kinda thing
- multiple recursive calls in a function, like binary search left/right, sometimes calls neither and sometimes calls both
the recursion support in spidermonkey only works with self-recursion.
that is, two functions that call each other recursively will not be traced.
two trees are formed, going down and going up.
type instability matters on both sides.
so the values returned from the function calls matter.
so far, what i've thought of means recursing from the top of a function and if..else.
but i'd probably also want to recurse from other points, e.g. loops.
special code for tail recursion likely coming soon, but possibly as a separate patch, because it requires changes to the interpreter.
*/
// "@" indicates a point at which a statement can be inserted. XXX allow use of variables, as consts
// variable names will be replaced, and should be uppercase to reduce the chance of matching things they shouldn't.
// take care to ensure infinite recursion never occurs unexpectedly, especially with doubly-recursive functions.
var recursiveFunctions = [
{
// Unless the recursive call is in the tail position, this will throw.
text: "(function too_much_recursion(depth) { @; if (depth > 0) { @; too_much_recursion(depth - 1); } @ })",
vars: ["depth"],
args: function(d, b) { return rnd(10000); },
test: function(f) { try { f(5000); } catch(e) { } return true; }
},
{
text: "(function factorial(N) { @; if (N == 0) return 1; @; return N * factorial(N - 1); @ })",
vars: ["N"],
args: function(d, b) { return "" + rnd(20); },
test: function(f) { return f(10) == 3628800; }
},
{
text: "(function factorial_tail(N, Acc) { @; if (N == 0) { @; return Acc; } @; return factorial_tail(N - 1, Acc * N); @ })",
vars: ["N", "Acc"],
args: function(d, b) { return rnd(20) + ", 1"; },
test: function(f) { return f(10, 1) == 3628800; }
},
{
// two recursive calls
text: "(function fibonacci(N) { @; if (N <= 1) { @; return 1; } @; return fibonacci(N - 1) + fibonacci(N - 2); @ })",
vars: ["N"],
args: function(d, b) { return "" + rnd(8); },
test: function(f) { return f(6) == 13; }
},
{
// do *anything* while indexing over mixed-type arrays
text: "(function a_indexing(array, start) { @; if (array.length == start) { @; return EXPR1; } var thisitem = array[start]; var recval = a_indexing(array, start + 1); STATEMENT1 })",
vars: ["array", "start", "thisitem", "recval"],
args: function(d, b) { return makeMixedTypeArray(d-1, b) + ", 0"; },
testSub: function(text) { return text.replace(/EXPR1/, "0").replace(/STATEMENT1/, "return thisitem + recval;"); },
randSub: function(text, varMap, d, b) {
var expr1 = makeExpr(d, b.concat([varMap["array"], varMap["start"]]));
var statement1 = rnd(2) ?
makeStatement(d, b.concat([varMap["thisitem"], varMap["recval"]])) :
"return " + makeExpr(d, b.concat([varMap["thisitem"], varMap["recval"]])) + ";";
return (text.replace(/EXPR1/, expr1)
.replace(/STATEMENT1/, statement1)
); },
test: function(f) { return f([1,2,3,"4",5,6,7], 0) == "123418"; }
},
{
// this lets us play a little with mixed-type arrays
text: "(function sum_indexing(array, start) { @; return array.length == start ? 0 : array[start] + sum_indexing(array, start + 1); })",
vars: ["array", "start"],
args: function(d, b) { return makeMixedTypeArray(d-1, b) + ", 0"; },
test: function(f) { return f([1,2,3,"4",5,6,7], 0) == "123418"; }
},
{
text: "(function sum_slicing(array) { @; return array.length == 0 ? 0 : array[0] + sum_slicing(array.slice(1)); })",
vars: ["array"],
args: function(d, b) { return makeMixedTypeArray(d-1, b); },
test: function(f) { return f([1,2,3,"4",5,6,7]) == "123418"; }
}
];
(function testAllRecursiveFunctions() {
for (var i = 0; i < recursiveFunctions.length; ++i) {
var a = recursiveFunctions[i];
var text = a.text;
if (a.testSub) text = a.testSub(text);
var f = eval(text.replace(/@/g, ""))
if (!a.test(f))
throw "Failed test of: " + a.text;
}
})();
function makeImmediateRecursiveCall(d, b, cheat1, cheat2)
{
if (rnd(10) != 0)
return "(4277)";
var a = (cheat1 == null) ? rndElt(recursiveFunctions) : recursiveFunctions[cheat1];
var s = a.text;
var varMap = {};
for (var i = 0; i < a.vars.length; ++i) {
var prettyName = a.vars[i];
varMap[prettyName] = uniqueVarName();
s = s.replace(new RegExp(prettyName, "g"), varMap[prettyName]);
}
var actualArgs = cheat2 == null ? a.args(d, b) : cheat2;
s = s + "(" + actualArgs + ")";
s = s.replace(/@/g, function() { if (rnd(4) == 0) return makeStatement(d-2, b); return ""; });
if (a.randSub) s = a.randSub(s, varMap, d, b);
s = "(" + s + ")";
return s;
}
function makeLetHead(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(2) == 1)
return makeLetHeadItem(d, b);
else
return makeLetHeadItem(d, b) + ", " + makeLetHeadItem(d - 1, b);
}
function makeLetHeadItem(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
// 0 or more things being declared
var lhs = (rnd(3) == 1) ? makeDestructuringLValue(d, b) : makeId(d, b);
// initial value
var rhs = (rnd(2) == 1) ? (" = " + makeExpr(d, b)) : "";
return lhs + rhs;
}
function makeActualArgList(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var nArgs = rnd(3);
if (nArgs == 0)
return "";
var argList = makeExpr(d, b);
for (var i = 1; i < nArgs; ++i)
argList += ", " + makeExpr(d - i, b);
return argList;
}
function makeFormalArgList(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
var nArgs = rnd(3);
if (nArgs == 0)
return "";
var argList = makeFormalArg(d, b)
for (var i = 1; i < nArgs; ++i)
argList += ", " + makeFormalArg(d - i, b);
return argList;
}
function makeFormalArg(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(4) == 1)
return makeDestructuringLValue(d, b);
return makeId(d, b);
}
function makeNewId(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return rndElt(["a", "b", "c", "d", "e", "w", "x", "y", "z"]);
}
function makeId(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(2) == 1 && b.length)
return rndElt(b);
switch(rnd(200))
{
case 0:
return makeTerm(d, b);
case 1:
return makeExpr(d, b);
case 2: case 3: case 4: case 5:
return makeLValue(d, b);
case 6: case 7:
return makeDestructuringLValue(d, b);
case 8: case 9: case 10:
// some keywords that can be used as identifiers in some contexts (e.g. variables, function names, argument names)
// but that's annoying, and some of these cause lots of syntax errors.
return rndElt(["get", "set", "getter", "setter", "delete", "let", "yield", "each", "xml", "namespace"]);
case 11:
return "function::" + makeId(d, b);
case 12: case 13:
return "this." + makeId(d, b);
case 14:
return "x::" + makeId(d, b);
case 15: case 16:
return makeNamespacePrefix(d - 1, b) + makeSpecialProperty(d - 1, b);
case 17: case 18:
return makeNamespacePrefix(d - 1, b) + makeId(d - 1, b);
}
return rndElt(["a", "b", "c", "d", "e", "w", "x", "y", "z",
"window", "this", "eval", "\u3056", "NaN",
// "valueOf", "toString", // e.g. valueOf getter :P // bug 381242, etc
"functional", // perhaps decompiler code looks for "function"?
" " // [k, v] becomes [, v] -- test how holes are handled in unexpected destructuring
]);
// window is a const (in the browser), so some attempts to redeclare it will cause errors
// eval is interesting because it cannot be called indirectly. and maybe also because it has its own opcode in jsopcode.tbl.
// but bad things happen if you have "eval setter"... so let's not put eval in this list.
}
function makeComprehension(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d < 0)
return "";
switch(rnd(5)) {
case 0:
return "";
case 1:
return cat([" for ", "(", makeForInLHS(d, b), " in ", makeExpr(d - 2, b), ")"]) + makeComprehension(d - 1, b);
case 2:
return cat([" for ", "each ", "(", makeId(d, b), " in ", makeExpr(d - 2, b), ")"]) + makeComprehension(d - 1, b);
case 3:
return cat([" for ", "each ", "(", makeId(d, b), " in ", makeMixedTypeArray(d - 2, b), ")"]) + makeComprehension(d - 1, b);
default:
return cat([" if ", "(", makeExpr(d - 2, b), ")"]); // this is always last (and must be preceded by a "for", oh well)
}
}
// for..in LHS can be a single variable OR it can be a destructuring array of exactly two elements.
function makeForInLHS(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// JS 1.7 only (removed in JS 1.8)
//
// if (version() == 170 && rnd(4) == 0)
// return cat(["[", makeLValue(d, b), ", ", makeLValue(d, b), "]"]);
return makeLValue(d, b);
}
function makeLValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0 || (rnd(2) == 1))
return makeId(d - 1, b);
d = rnd(d);
return (rndElt(lvalueMakers))(d, b);
}
var lvalueMakers = [
// Simple variable names :)
function(d, b) { return cat([makeId(d, b)]); },
// Destructuring
function(d, b) { return makeDestructuringLValue(d, b); },
function(d, b) { return "(" + makeDestructuringLValue(d, b) + ")"; },
// Properties
function(d, b) { return cat([makeId(d, b), ".", makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), ".", makeId(d, b)]); },
function(d, b) { return cat([makeExpr(d, b), "[", "'", makeId(d, b), "'", "]"]); },
// Special properties
function(d, b) { return cat([makeId(d, b), ".", makeSpecialProperty(d, b)]); },
// Certain functions can act as lvalues! See JS_HAS_LVALUE_RETURN in js engine source.
function(d, b) { return cat([makeId(d, b), "(", makeExpr(d, b), ")"]); },
function(d, b) { return cat(["(", makeExpr(d, b), ")", "(", makeExpr(d, b), ")"]); },
// Parenthesized lvalues can cause problems ;)
function(d, b) { return cat(["(", makeLValue(d, b), ")"]); },
function(d, b) { return makeExpr(d, b); } // intentionally bogus, but not quite garbage.
];
function makeDestructuringLValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
d = d - 1;
if (d < 0 || rnd(4) == 1)
return makeId(d, b);
if (rnd(6) == 1)
return makeLValue(d, b);
return (rndElt(destructuringLValueMakers))(d, b);
}
var destructuringLValueMakers = [
// destructuring assignment: arrays
function(d, b)
{
var len = rnd(d, b);
if (len == 0)
return "[]";
var Ti = [];
Ti.push("[");
Ti.push(maybeMakeDestructuringLValue(d, b));
for (var i = 1; i < len; ++i) {
Ti.push(", ");
Ti.push(maybeMakeDestructuringLValue(d, b));
}
Ti.push("]");
return cat(Ti);
},
// destructuring assignment: objects
function(d, b)
{
var len = rnd(d, b);
if (len == 0)
return "{}";
var Ti = [];
Ti.push("{");
for (var i = 0; i < len; ++i) {
if (i > 0)
Ti.push(", ");
Ti.push(makeId(d, b));
if (rnd(3)) {
Ti.push(": ");
Ti.push(makeDestructuringLValue(d, b));
} // else, this is a shorthand destructuring, treated as "id: id".
}
Ti.push("}");
return cat(Ti);
}
];
// Allow "holes".
function maybeMakeDestructuringLValue(d, b)
{
if (rnd(2) == 0)
return ""
return makeDestructuringLValue(d, b)
}
function makeTerm(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
return (rndElt(termMakers))(d, b);
}
var termMakers = [
// Variable names
function(d, b) { return makeId(d, b); },
// Simple literals (no recursion required to make them)
function(d, b) { return rndElt([
// Arrays
"[]", "[1]", "[[]]", "[[1]]", "[,]", "[,,]", "[1,,]",
// Objects
"{}", "({})", "({a1:1})",
// Possibly-destructuring arrays
"[z1]", "[z1,,]", "[,,z1]",
// Possibly-destructuring objects
"({a2:z2})",
// Sharp use
"#1#",
// Sharp creation and use
"#1=[#1#]", "#3={a:#3#}",
"function(id) { return id }",
"function ([y]) { }",
"(function ([y]) { })()",
"arguments",
"Math",
"this",
"length"
]);
},
function(d, b) { return rndElt([ "0.1", ".2", "3", "1.3", "4.", "5.0000000000000000000000", "1.2e3", "1e81", "1e+81", "1e-81", "1e4", "0", "-0", "(-0)", "-1", "(-1)", "0x99", "033", (""+Math.PI), "3/0", "-3/0", "0/0"
// these are commented out due to bug 379294
// "0x2D413CCC", "0x5a827999", "0xB504F332", "(0x50505050 >> 1)"
]); },
function(d, b) { return rndElt([ "true", "false", "undefined", "null"]); },
function(d, b) { return rndElt([ "this", "window" ]); },
function(d, b) { return rndElt([" \"\" ", " '' "]) },
randomUnitStringLiteral,
function(d, b) { return rndElt([" /x/ ", " /x/g "]) },
];
function randomUnitStringLiteral()
{
var s = "\"\\u";
var nDigits = rnd(6) + 1;
for (var i = 0; i < nDigits; ++i) {
s += "0123456789ABCDEF".charAt(rnd(16));
}
s += "\""
return s;
}
if (haveE4X) {
// E4X literals
termMakers = termMakers.concat([
function(d, b) { return rndElt([ "<x/>", "<y><z/></y>"]); },
function(d, b) { return rndElt([ "@foo" /* makes sense in filtering predicates, at least... */, "*", "*::*"]); },
function(d, b) { return makeE4X(d, b) }, // xml
function(d, b) { return cat(["<", ">", makeE4X(d, b), "<", "/", ">"]); }, // xml list
]);
}
function maybeMakeTerm(d, b)
{
if (rnd(2))
return makeTerm(d - 1, b);
else
return "";
}
function makeCrazyToken()
{
if (rnd(2) == 0) {
// This can be more aggressive once bug 368694 is fixed.
return String.fromCharCode(32 + rnd(128 - 32));
}
return rndElt([
// Some of this is from reading jsscan.h.
// Comments; comments hiding line breaks.
"//", UNTERMINATED_COMMENT, (UNTERMINATED_COMMENT + "\n"), "/*\n*/",
// groupers (which will usually be unmatched if they come from here ;)
"[", "]",
"{", "}",
"(", ")",
// a few operators
"!", "@", "%", "^", "*", "|", ":", "?", "'", "\"", ",", ".", "/",
"~", "_", "+", "=", "-", "++", "--", "+=", "%=", "|=", "-=",
"#", "#1", "#1=", // usually an "invalid character", but used as sharps too
// most real keywords plus a few reserved keywords
" in ", " instanceof ", " let ", " new ", " get ", " for ", " if ", " else ", " else if ", " try ", " catch ", " finally ", " export ", " import ", " void ", " with ",
" default ", " goto ", " case ", " switch ", " do ", " /*infloop*/while ", " return ", " yield ", " break ", " continue ", " typeof ", " var ", " const ",
// several keywords can be used as identifiers. these are just a few of them.
" enum ", // JS_HAS_RESERVED_ECMA_KEYWORDS
" debugger ", // JS_HAS_DEBUGGER_KEYWORD
" super ", // TOK_PRIMARY!
" this ", // TOK_PRIMARY!
" null ", // TOK_PRIMARY!
" undefined ", // not a keyword, but a default part of the global object
"\n", // trigger semicolon insertion, also acts as whitespace where it might not be expected
"\r",
"\u2028", // LINE_SEPARATOR?
"\u2029", // PARA_SEPARATOR?
"<" + "!" + "--", // beginning of HTML-style to-end-of-line comment (!)
"--" + ">", // end of HTML-style comment
"",
"\0", // confuse anything that tries to guess where a string ends. but note: "illegal character"!
]);
}
function makeE4X(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (d <= 0)
return cat(["<", "x", ">", "<", "y", "/", ">", "<", "/", "x", ">"]);
d = d - 1;
var y = [
function(d, b) { return '<employee id="1"><name>Joe</name><age>20</age></employee>' },
function(d, b) { return cat(["<", ">", makeSubE4X(d, b), "<", "/", ">"]); }, // xml list
function(d, b) { return cat(["<", ">", makeExpr(d, b), "<", "/", ">"]); }, // bogus or text
function(d, b) { return cat(["<", "zzz", ">", makeExpr(d, b), "<", "/", "zzz", ">"]); }, // bogus or text
// mimic parts of this example at a time, from the e4x spec: <x><{tagname} {attributename}={attributevalue+attributevalue}>{content}</{tagname}></x>;
function(d, b) { var tagId = makeId(d, b); return cat(["<", "{", tagId, "}", ">", makeSubE4X(d, b), "<", "/", "{", tagId, "}", ">"]); },
function(d, b) { var attrId = makeId(d, b); var attrValExpr = makeExpr(d, b); return cat(["<", "yyy", " ", "{", attrId, "}", "=", "{", attrValExpr, "}", " ", "/", ">"]); },
function(d, b) { var contentId = makeId(d, b); return cat(["<", "yyy", ">", "{", contentId, "}", "<", "/", "yyy", ">"]); },
// namespace stuff
function(d, b) { var contentId = makeId(d, b); return cat(['<', 'bbb', ' ', 'xmlns', '=', '"', makeExpr(d, b), '"', '>', makeSubE4X(d, b), '<', '/', 'bbb', '>']); },
function(d, b) { var contentId = makeId(d, b); return cat(['<', 'bbb', ' ', 'xmlns', ':', 'ccc', '=', '"', makeExpr(d, b), '"', '>', '<', 'ccc', ':', 'eee', '>', '<', '/', 'ccc', ':', 'eee', '>', '<', '/', 'bbb', '>']); },
function(d, b) { return makeExpr(d, b); },
function(d, b) { return makeSubE4X(d, b); }, // naked cdata things, etc.
]
return (rndElt(y))(d, b);
}
function makeSubE4X(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
// Bug 380431
// if (rnd(8) == 0)
// return "<" + "!" + "[" + "CDATA[" + makeExpr(depth - 1) + "]" + "]" + ">"
if (d < -2)
return "";
var y = [
function(d, b) { return cat(["<", "ccc", ":", "ddd", ">", makeSubE4X(d - 1, b), "<", "/", "ccc", ":", "ddd", ">"]); },
function(d, b) { return makeE4X(d, b) + makeSubE4X(d - 1, b); },
function(d, b) { return "yyy"; },
function(d, b) { return cat(["<", "!", "--", "yy", "--", ">"]); }, // XML comment
// Bug 380431
// function(depth) { return cat(["<", "!", "[", "CDATA", "[", "zz", "]", "]", ">"]); }, // XML cdata section
function(d, b) { return " "; },
function(d, b) { return ""; },
];
return (rndElt(y))(d, b);
}
function makeShapeyValue(d, b)
{
if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
if (rnd(10) == 0)
return makeExpr(d, b);
var a = [
// Numbers and number-like things
[
"0", "1", "2", "3", "0.1", ".2", "1.3", "4.", "5.0000000000000000000000",
"1.2e3", "1e81", "1e+81", "1e-81", "1e4", "-0", "(-0)",
"-1", "(-1)", "0x99", "033", "3/0", "-3/0", "0/0",
"Math.PI",
"0x2D413CCC", "0x5a827999", "0xB504F332", "-0x2D413CCC", "-0x5a827999", "-0xB504F332", "0x50505050", "(0x50505050 >> 1)",
// various powers of two, with values near JSVAL_INT_MAX especially tested
"0x10000000", "0x20000000", "0x3FFFFFFE", "0x3FFFFFFF", "0x40000000", "0x40000001", "0x80000000", "-0x80000000",
],
// Special numbers
[ "(1/0)", "(-1/0)", "(0/0)" ],
// String literals
[" \"\" ", " '' ", " 'A' ", " '\\0' "],
// Regular expression literals
[ " /x/ ", " /x/g "],
// Booleans
[ "true", "false" ],
// Undefined and null
[ "(void 0)", "null" ],
// Object literals
[ "[]", "[1]", "[(void 0)]", "{}", "{x:3}", "({})", "({x:3})" ],
// Variables that really should have been constants in the ecmascript spec
[ "NaN", "Infinity", "-Infinity", "undefined"],
// Boxed booleans
[ "new Boolean(true)", "new Boolean(false)" ],
// Boxed numbers
[ "new Number(1)", "new Number(1.5)" ],
// Boxed strings
[ "new String('')", "new String('q')" ],
// Fun stuff
[ "function(){}"],
["{}", "[]", "[1]", "['z']", "[undefined]", "this", "eval", "arguments" ],
// Actual variables (slightly dangerous)
[ b.length ? rndElt(b) : "x" ]
];
return rndElt(rndElt(a));
}
function makeMixedTypeArray(d, b)
{
// Pick two to five of those
var q = rnd(4) + 2;
var picks = [];
for (var j = 0; j < q; ++j)
picks.push(makeShapeyValue(d, b));
// Make an array of up to 39 elements, containing those two to five values
var c = [];
var count = rnd(40);
for (var j = 0; j < count; ++j)
c.push(rndElt(picks));
return "[" + c.join(", ") + "]";
}
function strTimes(s, n)
{
if (n == 0) return "";
if (n == 1) return s;
var s2 = s + s;
var r = n % 2;
var d = (n - r) / 2;
var m = strTimes(s2, d);
return r ? m + s : m;
}
var count = 0;
var verbose = false;
var maxHeapCount = 0;
var sandbox = null;
//var nextTrapCode = null;
// https://bugzilla.mozilla.org/show_bug.cgi?id=394853#c19
//try { eval("/") } catch(e) { }
// Remember the number of countHeap.
tryItOut("");
/*
// Aggressive test for type-unstable arrays
count = 1;
for (var j = 0; j < 20000; ++j) {
x = null;
if (j % 100 == 0) gc();
var a = makeMixedTypeArray();
print(uneval(a));
var s = "for each (let i in " + a + ") { }";
//var s = "[i for each (i in " + a + ") if (i)]";
eval(s);
}
throw 1;
*/
/**************************************
* To reproduce a crash or assertion: *
**************************************/
// 1. grep tryIt LOGFILE | grep -v "function tryIt" | pbcopy
// 2. Paste the result between "ddbegin" and "ddend", replacing "start();"
// 3. Run Lithium to remove unnecessary lines between "ddbegin" and "ddend".
// SPLICE DDBEGIN
start();
// SPLICE DDEND
if (jsshell)
print("It's looking good!"); // Magic string that jsunhappy.py looks for
// 3. Run it.
| Tweak jsfunfuzz so it can find bug 600067. The largest changes are creating longer 'var' lists and creating function-declarations with non-unique names.
| jsfunfuzz/jsfunfuzz.js | Tweak jsfunfuzz so it can find bug 600067. The largest changes are creating longer 'var' lists and creating function-declarations with non-unique names. | <ide><path>sfunfuzz/jsfunfuzz.js
<ide> *************************/
<ide>
<ide>
<del>var TOTALLY_RANDOM = 100;
<add>var TOTALLY_RANDOM = 500;
<ide>
<ide> function makeStatement(d, b)
<ide> {
<ide> var statementMakers = weighted([
<ide>
<ide> // Any two statements in sequence
<del> { w: 4, fun: function(d, b) { return cat([makeStatement(d, b), makeStatement(d, b)]); } },
<del> { w: 4, fun: function(d, b) { return cat([makeStatement(d - 1, b), "\n", makeStatement(d - 1, b), "\n"]); } },
<add> { w: 15, fun: function(d, b) { return cat([makeStatement(d - 1, b), makeStatement(d - 1, b) ]); } },
<add> { w: 15, fun: function(d, b) { return cat([makeStatement(d - 1, b), "\n", makeStatement(d - 1, b), "\n"]); } },
<ide>
<ide> // Stripping semilcolons. What happens if semicolons are missing? Especially with line breaks used in place of semicolons (semicolon insertion).
<ide> { w: 1, fun: function(d, b) { return cat([stripSemicolon(makeStatement(d, b)), "\n", makeStatement(d, b)]); } },
<ide> { w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([rndElt(varBinder), v, " = ", makeExpr(d, b), ";", makeStatement(d - 1, b.concat([v]))]); } },
<ide> { w: 4, fun: function(d, b) { var v = makeNewId(d, b); return cat([makeStatement(d - 1, b.concat([v])), rndElt(varBinder), v, " = ", makeExpr(d, b), ";"]); } },
<ide>
<del> // Complex variable declarations, e.g. "const [a,b] = [3,4];"
<del> { w: 1, fun: function(d, b) { return cat([rndElt(varBinder), makeLetHead(d, b), ";", makeStatement(d - 1, b)]); } },
<add> // Complex variable declarations, e.g. "const [a,b] = [3,4];" or "var a,b,c,d=4,e;"
<add> { w: 10, fun: function(d, b) { return cat([rndElt(varBinder), makeLetHead(d, b), ";", makeStatement(d - 1, b)]); } },
<ide>
<ide> // Blocks
<ide> { w: 2, fun: function(d, b) { return cat(["{", makeStatement(d, b), " }"]); } },
<ide> // Labels. (JavaScript does not have goto, but it does have break-to-label and continue-to-label).
<ide> { w: 1, fun: function(d, b) { return cat(["L", ": ", makeStatementOrBlock(d, b)]); } },
<ide>
<del> // Function-declaration-statements, along with calls to those functions
<add> // Function-declaration-statements with shared names
<add> { w: 10, fun: function(d, b) { return cat([makeStatement(d-2, b), "function ", makeId(d, b), "(", makeFormalArgList(d, b), ")", "{", "/*jjj*/", "}", makeStatement(d-2, b)]); } },
<add>
<add> // Function-declaration-statements with unique names, along with calls to those functions
<ide> { w: 8, fun: makeNamedFunctionAndUse },
<ide>
<ide> // Long script -- can confuse Spidermonkey's short vs long jmp or something like that.
<ide> function makeNamedFunctionAndUse(d, b) {
<ide> // Use a unique function name to make it less likely that we'll accidentally make a recursive call
<ide> var funcName = uniqueVarName();
<del> var declStatement = cat(["/*hhh*/function ", funcName, "(", makeFormalArgList(d, b), ")", "{", makeStatement(d - 2, b), "}"]);
<add> var formalArgList = makeFormalArgList(d, b);
<add> var bv = formalArgList.length == 1 ? b.concat(formalArgList) : b;
<add> var declStatement = cat(["/*hhh*/function ", funcName, "(", formalArgList, ")", "{", makeStatement(d - 1, bv), "}"]);
<ide> var useStatement;
<ide> if (rnd(2)) {
<ide> // Direct call
<ide> {
<ide> if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
<ide>
<del> if (rnd(2) == 1)
<del> return makeLetHeadItem(d, b);
<add> var items = (d > 0 || rnd(2) == 0) ? rnd(10) + 1 : 1;
<add> var result = "";
<add>
<add> for (var i = 0; i < items; ++i) {
<add> if (i > 0)
<add> result += ", ";
<add> result += makeLetHeadItem(d - i, b);
<add> }
<add>
<add> return result;
<add>}
<add>
<add>function makeLetHeadItem(d, b)
<add>{
<add> if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
<add>
<add> d = d - 1;
<add>
<add> if (d < 0 || rnd(2) == 0)
<add> return rnd(2) ? uniqueVarName() : makeId(d, b);
<add> else if (rnd(5) == 0)
<add> return makeDestructuringLValue(d, b) + " = " + makeExpr(d, b);
<ide> else
<del> return makeLetHeadItem(d, b) + ", " + makeLetHeadItem(d - 1, b);
<del>}
<del>
<del>function makeLetHeadItem(d, b)
<del>{
<del> if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
<del>
<del> d = d - 1;
<del>
<del> // 0 or more things being declared
<del> var lhs = (rnd(3) == 1) ? makeDestructuringLValue(d, b) : makeId(d, b);
<del>
<del> // initial value
<del> var rhs = (rnd(2) == 1) ? (" = " + makeExpr(d, b)) : "";
<del>
<del> return lhs + rhs;
<add> return makeId(d, b) + " = " + makeExpr(d, b);
<ide> }
<ide>
<ide>
<ide> {
<ide> if (rnd(TOTALLY_RANDOM) == 2) return totallyRandom(d, b);
<ide>
<del> if (rnd(2) == 1 && b.length)
<add> if (rnd(3) == 1 && b.length)
<ide> return rndElt(b);
<ide>
<ide> switch(rnd(200))
<ide> return makeNamespacePrefix(d - 1, b) + makeSpecialProperty(d - 1, b);
<ide> case 17: case 18:
<ide> return makeNamespacePrefix(d - 1, b) + makeId(d - 1, b);
<add> case 19:
<add> return " "; // [k, v] becomes [, v] -- test how holes are handled in unexpected destructuring
<add> case 20:
<add> return "this";
<ide> }
<ide>
<ide> return rndElt(["a", "b", "c", "d", "e", "w", "x", "y", "z",
<del> "window", "this", "eval", "\u3056", "NaN",
<add> "window", "eval", "\u3056", "NaN",
<ide> // "valueOf", "toString", // e.g. valueOf getter :P // bug 381242, etc
<ide> "functional", // perhaps decompiler code looks for "function"?
<del> " " // [k, v] becomes [, v] -- test how holes are handled in unexpected destructuring
<ide> ]);
<ide>
<ide> // window is a const (in the browser), so some attempts to redeclare it will cause errors |
|
Java | mit | ff66023d8328c03f9ad0ec7fd3c9ca3e05d19415 | 0 | iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable | package org.broadinstitute.sting.playground.gatk.walkers.varianteval;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.refdata.*;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.genotype.Variation;
import java.util.ArrayList;
import java.util.List;
/**
* The Broad Institute
* SOFTWARE COPYRIGHT NOTICE AGREEMENT
* This software and its documentation are copyright 2009 by the
* Broad Institute/Massachusetts Institute of Technology. All rights are reserved.
* <p/>
* This software is supplied without any warranty or guaranteed support whatsoever. Neither
* the Broad Institute nor MIT can be responsible for its use, misuse, or functionality.
*/
public class VariantDBCoverage extends BasicVariantAnalysis implements GenotypeAnalysis, PopulationAnalysis {
private String dbName;
private int nDBSNPs = 0;
private int nEvalObs = 0;
private int nSNPsAtdbSNPs = 0;
private int nConcordant = 0;
public VariantDBCoverage(final String name) {
super("db_coverage");
dbName = name;
}
public int nDBSNPs() { return nDBSNPs; }
public int nEvalSites() { return nEvalObs; }
public int nSNPsAtdbSNPs() { return nSNPsAtdbSNPs; }
public int nConcordant() { return nConcordant; }
public int nNovelSites() { return Math.abs(nEvalSites() - nSNPsAtdbSNPs()); }
public boolean discordantP(Variation dbSNP, Variation eval) {
if (eval != null) {
char alt = (eval.isSNP()) ? eval.getAlternativeBaseForSNP() : Utils.stringToChar(eval.getReference());
if (dbSNP != null && dbSNP.isSNP())
return !dbSNP.getAlleleList().contains(String.valueOf(alt));
}
return false;
}
/**
* What fraction of the evaluated site variants were also found in the db?
*
* @return
*/
public double dbSNPRate() {
return nSNPsAtdbSNPs() / (1.0 * nEvalSites());
}
public double concordanceRate() {
return nConcordant() / (1.0 * nSNPsAtdbSNPs());
}
public static Variation getFirstRealSNP(RODRecordList<ReferenceOrderedDatum> dbsnpList) {
if (dbsnpList == null)
return null;
Variation dbsnp = null;
for (ReferenceOrderedDatum d : dbsnpList) {
if (((Variation) d).isSNP() && (! (d instanceof RodVCF) || ! ((RodVCF)d).isFiltered())) {
dbsnp = (Variation)d;
break;
}
}
return dbsnp;
}
public String update(Variation eval, RefMetaDataTracker tracker, char ref, AlignmentContext context) {
Variation dbSNP = getFirstRealSNP(tracker.getTrackData( dbName, null, false ));
String result = null;
if ( dbSNP != null ) nDBSNPs++; // count the number of real dbSNP events
if ( eval != null && eval.isSNP() ) { // ignore indels right now
nEvalObs++; // count the number of eval snps we've seen
if (dbSNP != null) { // both eval and dbSNP have real snps
nSNPsAtdbSNPs++;
if (!discordantP(dbSNP, eval)) // count whether we're concordant or not with the dbSNP value
nConcordant++;
else
result = String.format("Discordant [DBSNP %s] [EVAL %s]", dbSNP, eval);
}
}
// if ( dbSNP != null && dbSNP.isSNP() ) {
// BrokenRODSimulator.attach("dbSNP");
// rodDbSNP dbsnp = (rodDbSNP) BrokenRODSimulator.simulate_lookup("dbSNP", context.getLocation(), tracker);
// if ( ! dbSNP.getRS_ID().equals(dbsnp.getRS_ID()) && dbsnp.isSNP() ) {
// System.out.printf("Discordant site! %n%s%n vs.%n%s%n", dbSNP, dbsnp);
// }
// }
return result;
}
public List<String> done() {
List<String> s = new ArrayList<String>();
s.add(String.format("name %s", dbName));
s.add(String.format("n_db_snps %d", nDBSNPs()));
s.add(String.format("n_eval_sites %d", nEvalSites()));
s.add(String.format("n_overlapping_sites %d", nSNPsAtdbSNPs()));
s.add(String.format("n_concordant %d", nConcordant()));
s.add(String.format("n_novel_sites %d", nNovelSites()));
s.add(String.format("%s_rate %.2f # percent eval snps at dbsnp snps", dbName.toLowerCase(), 100 * dbSNPRate()));
s.add(String.format("concordance_rate %.2f", 100 * concordanceRate()));
return s;
}
} | java/src/org/broadinstitute/sting/playground/gatk/walkers/varianteval/VariantDBCoverage.java | package org.broadinstitute.sting.playground.gatk.walkers.varianteval;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.refdata.*;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.genotype.Variation;
import java.util.ArrayList;
import java.util.List;
/**
* The Broad Institute
* SOFTWARE COPYRIGHT NOTICE AGREEMENT
* This software and its documentation are copyright 2009 by the
* Broad Institute/Massachusetts Institute of Technology. All rights are reserved.
* <p/>
* This software is supplied without any warranty or guaranteed support whatsoever. Neither
* the Broad Institute nor MIT can be responsible for its use, misuse, or functionality.
*/
public class VariantDBCoverage extends BasicVariantAnalysis implements GenotypeAnalysis, PopulationAnalysis {
private String dbName;
private int nDBSNPs = 0;
private int nEvalObs = 0;
private int nSNPsAtdbSNPs = 0;
private int nConcordant = 0;
public VariantDBCoverage(final String name) {
super("db_coverage");
dbName = name;
}
public int nDBSNPs() { return nDBSNPs; }
public int nEvalSites() { return nEvalObs; }
public int nSNPsAtdbSNPs() { return nSNPsAtdbSNPs; }
public int nConcordant() { return nConcordant; }
public int nNovelSites() { return Math.abs(nEvalSites() - nSNPsAtdbSNPs()); }
public boolean discordantP(Variation dbSNP, Variation eval) {
if (eval != null) {
char alt = (eval.isSNP()) ? eval.getAlternativeBaseForSNP() : Utils.stringToChar(eval.getReference());
if (dbSNP != null && dbSNP.isSNP())
return !dbSNP.getAlleleList().contains(String.valueOf(alt));
}
return false;
}
/**
* What fraction of the evaluated site variants were also found in the db?
*
* @return
*/
public double dbSNPRate() {
return nSNPsAtdbSNPs() / (1.0 * nEvalSites());
}
public double concordanceRate() {
return nConcordant() / (1.0 * nSNPsAtdbSNPs());
}
public static Variation getFirstRealSNP(RODRecordList<ReferenceOrderedDatum> dbsnpList) {
if (dbsnpList == null)
return null;
Variation dbsnp = null;
for (ReferenceOrderedDatum d : dbsnpList) {
if (((Variation) d).isSNP()) {
dbsnp = (Variation)d;
break;
}
}
return dbsnp;
}
public String update(Variation eval, RefMetaDataTracker tracker, char ref, AlignmentContext context) {
Variation dbSNP = getFirstRealSNP(tracker.getTrackData( dbName, null, false ));
String result = null;
if ( dbSNP != null ) nDBSNPs++; // count the number of real dbSNP events
if ( eval != null && eval.isSNP() ) { // ignore indels right now
nEvalObs++; // count the number of eval snps we've seen
if (dbSNP != null) { // both eval and dbSNP have real snps
nSNPsAtdbSNPs++;
if (!discordantP(dbSNP, eval)) // count whether we're concordant or not with the dbSNP value
nConcordant++;
else
result = String.format("Discordant [DBSNP %s] [EVAL %s]", dbSNP, eval);
}
}
// if ( dbSNP != null && dbSNP.isSNP() ) {
// BrokenRODSimulator.attach("dbSNP");
// rodDbSNP dbsnp = (rodDbSNP) BrokenRODSimulator.simulate_lookup("dbSNP", context.getLocation(), tracker);
// if ( ! dbSNP.getRS_ID().equals(dbsnp.getRS_ID()) && dbsnp.isSNP() ) {
// System.out.printf("Discordant site! %n%s%n vs.%n%s%n", dbSNP, dbsnp);
// }
// }
return result;
}
public List<String> done() {
List<String> s = new ArrayList<String>();
s.add(String.format("name %s", dbName));
s.add(String.format("n_db_snps %d", nDBSNPs()));
s.add(String.format("n_eval_sites %d", nEvalSites()));
s.add(String.format("n_overlapping_sites %d", nSNPsAtdbSNPs()));
s.add(String.format("n_concordant %d", nConcordant()));
s.add(String.format("n_novel_sites %d", nNovelSites()));
s.add(String.format("%s_rate %.2f # percent eval snps at dbsnp snps", dbName.toLowerCase(), 100 * dbSNPRate()));
s.add(String.format("concordance_rate %.2f", 100 * concordanceRate()));
return s;
}
} | Trivial change to support filter field in VCF
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2636 348d0f76-0448-11de-a6fe-93d51630548a
| java/src/org/broadinstitute/sting/playground/gatk/walkers/varianteval/VariantDBCoverage.java | Trivial change to support filter field in VCF | <ide><path>ava/src/org/broadinstitute/sting/playground/gatk/walkers/varianteval/VariantDBCoverage.java
<ide>
<ide> Variation dbsnp = null;
<ide> for (ReferenceOrderedDatum d : dbsnpList) {
<del> if (((Variation) d).isSNP()) {
<add> if (((Variation) d).isSNP() && (! (d instanceof RodVCF) || ! ((RodVCF)d).isFiltered())) {
<ide> dbsnp = (Variation)d;
<ide> break;
<ide> } |
|
Java | apache-2.0 | 20a950a4638360d9b532d9847f1cc893821f5f94 | 0 | crrlos/MyChess | package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import com.mychess.mychess.Chess.Ubicacion;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
TextView nombreColumnas[] = new TextView[8];
TextView numeroFila[] = new TextView[8];
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
boolean enroqueBlanco = true;
boolean enroqueNegro = true;
boolean jugadaLocal;// sirve para difenciar entre una jugada local y una remota
Chess chess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillasBlanco();
setOnclickListener();
setDefaultColor();
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
tiempoMovimiento.iniciar();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
/*---------------------*/
new SocketServidor().conectar();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(jugadaLocal) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
}else
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCampos(int n){
nombreColumnas[0] = (TextView) findViewById(R.id.columnaa);
nombreColumnas[1] = (TextView) findViewById(R.id.columnab);
nombreColumnas[2] = (TextView) findViewById(R.id.columnac);
nombreColumnas[3] = (TextView) findViewById(R.id.columnad);
nombreColumnas[4] = (TextView) findViewById(R.id.columnae);
nombreColumnas[5] = (TextView) findViewById(R.id.columnaf);
nombreColumnas[6] = (TextView) findViewById(R.id.columnag);
nombreColumnas[7] = (TextView) findViewById(R.id.columnah);
numeroFila[0] = (TextView) findViewById(R.id.fila1);
numeroFila[1]= (TextView) findViewById(R.id.fila2);
numeroFila[2]= (TextView) findViewById(R.id.fila3);
numeroFila[3]= (TextView) findViewById(R.id.fila4);
numeroFila[4]= (TextView) findViewById(R.id.fila5);
numeroFila[5]= (TextView) findViewById(R.id.fila6);
numeroFila[6]= (TextView) findViewById(R.id.fila7);
numeroFila[7]= (TextView) findViewById(R.id.fila8);
nombreColumnas[0].setText("a");
nombreColumnas[1].setText("b");
nombreColumnas[2].setText("c");
nombreColumnas[3].setText("d");
nombreColumnas[4].setText("e");
nombreColumnas[5].setText("f");
nombreColumnas[6].setText("g");
nombreColumnas[7].setText("h");
numeroFila[0].setText("1");
numeroFila[1].setText("2");
numeroFila[2].setText("3");
numeroFila[3].setText("4");
numeroFila[4].setText("5");
numeroFila[5].setText("6");
numeroFila[6].setText("7");
numeroFila[7].setText("8");
if(n == 2)
{
nombreColumnas[0].setText("h");
nombreColumnas[1].setText("g");
nombreColumnas[2].setText("f");
nombreColumnas[3].setText("e");
nombreColumnas[4].setText("d");
nombreColumnas[5].setText("c");
nombreColumnas[6].setText("b");
nombreColumnas[7].setText("a");
numeroFila[0].setText("8");
numeroFila[1].setText("7");
numeroFila[2].setText("6");
numeroFila[3].setText("5");
numeroFila[4].setText("4");
numeroFila[5].setText("3");
numeroFila[6].setText("2");
numeroFila[7].setText("1");
}
}
private void inicializarCasillasBlanco() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
colocarPiezas(1);
inicializarCampos(1);
jugadaLocal = true;
}
private void inicializarCasillasNegro() {
casillas[0][0] = (ImageView) findViewById(R.id.h1);
casillas[0][1] = (ImageView) findViewById(R.id.h2);
casillas[0][2] = (ImageView) findViewById(R.id.h3);
casillas[0][3] = (ImageView) findViewById(R.id.h4);
casillas[0][4] = (ImageView) findViewById(R.id.h5);
casillas[0][5] = (ImageView) findViewById(R.id.h6);
casillas[0][6] = (ImageView) findViewById(R.id.h7);
casillas[0][7] = (ImageView) findViewById(R.id.h8);
casillas[1][0] = (ImageView) findViewById(R.id.g1);
casillas[1][1] = (ImageView) findViewById(R.id.g2);
casillas[1][2] = (ImageView) findViewById(R.id.g3);
casillas[1][3] = (ImageView) findViewById(R.id.g4);
casillas[1][4] = (ImageView) findViewById(R.id.g5);
casillas[1][5] = (ImageView) findViewById(R.id.g6);
casillas[1][6] = (ImageView) findViewById(R.id.g7);
casillas[1][7] = (ImageView) findViewById(R.id.g8);
casillas[2][0] = (ImageView) findViewById(R.id.f1);
casillas[2][1] = (ImageView) findViewById(R.id.f2);
casillas[2][2] = (ImageView) findViewById(R.id.f3);
casillas[2][3] = (ImageView) findViewById(R.id.f4);
casillas[2][4] = (ImageView) findViewById(R.id.f5);
casillas[2][5] = (ImageView) findViewById(R.id.f6);
casillas[2][6] = (ImageView) findViewById(R.id.f7);
casillas[2][7] = (ImageView) findViewById(R.id.f8);
casillas[3][0] = (ImageView) findViewById(R.id.e1);
casillas[3][1] = (ImageView) findViewById(R.id.e2);
casillas[3][2] = (ImageView) findViewById(R.id.e3);
casillas[3][3] = (ImageView) findViewById(R.id.e4);
casillas[3][4] = (ImageView) findViewById(R.id.e5);
casillas[3][5] = (ImageView) findViewById(R.id.e6);
casillas[3][6] = (ImageView) findViewById(R.id.e7);
casillas[3][7] = (ImageView) findViewById(R.id.e8);
casillas[4][0] = (ImageView) findViewById(R.id.d1);
casillas[4][1] = (ImageView) findViewById(R.id.d2);
casillas[4][2] = (ImageView) findViewById(R.id.d3);
casillas[4][3] = (ImageView) findViewById(R.id.d4);
casillas[4][4] = (ImageView) findViewById(R.id.d5);
casillas[4][5] = (ImageView) findViewById(R.id.d6);
casillas[4][6] = (ImageView) findViewById(R.id.d7);
casillas[4][7] = (ImageView) findViewById(R.id.d8);
casillas[5][0] = (ImageView) findViewById(R.id.c1);
casillas[5][1] = (ImageView) findViewById(R.id.c2);
casillas[5][2] = (ImageView) findViewById(R.id.c3);
casillas[5][3] = (ImageView) findViewById(R.id.c4);
casillas[5][4] = (ImageView) findViewById(R.id.c5);
casillas[5][5] = (ImageView) findViewById(R.id.c6);
casillas[5][6] = (ImageView) findViewById(R.id.c7);
casillas[5][7] = (ImageView) findViewById(R.id.c8);
casillas[6][0] = (ImageView) findViewById(R.id.b1);
casillas[6][1] = (ImageView) findViewById(R.id.b2);
casillas[6][2] = (ImageView) findViewById(R.id.b3);
casillas[6][3] = (ImageView) findViewById(R.id.b4);
casillas[6][4] = (ImageView) findViewById(R.id.b5);
casillas[6][5] = (ImageView) findViewById(R.id.b6);
casillas[6][6] = (ImageView) findViewById(R.id.b7);
casillas[6][7] = (ImageView) findViewById(R.id.b8);
casillas[7][0] = (ImageView) findViewById(R.id.a1);
casillas[7][1] = (ImageView) findViewById(R.id.a2);
casillas[7][2] = (ImageView) findViewById(R.id.a3);
casillas[7][3] = (ImageView) findViewById(R.id.a4);
casillas[7][4] = (ImageView) findViewById(R.id.a5);
casillas[7][5] = (ImageView) findViewById(R.id.a6);
casillas[7][6] = (ImageView) findViewById(R.id.a7);
casillas[7][7] = (ImageView) findViewById(R.id.a8);
colocarPiezas(1);
inicializarCampos(2);
jugadaLocal = false;
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundResource(R.color.casillablanca);
else
casillas[i][j].setBackgroundResource(R.color.casillnegra);
dark = !dark;
}
dark = !dark;
}
}
private void colocarPiezas(int bando){
casillas[0][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[7][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[0][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[3][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[4][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[5][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[6][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[7][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[6][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[2][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[5][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[3][7].setImageResource(bando == 1?R.mipmap.alpha_wq:R.mipmap.alpha_bq);
casillas[4][7].setImageResource(bando == 1?R.mipmap.alpha_wk:R.mipmap.alpha_bk);
casillas[7][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[3][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[4][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[5][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[6][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[7][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[6][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[2][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[5][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[3][0].setImageResource(bando == 2 ? R.mipmap.alpha_wq : R.mipmap.alpha_bq);
casillas[4][0].setImageResource(bando == 2 ? R.mipmap.alpha_wk : R.mipmap.alpha_bk);
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};//inicialización del arreglo con valores negativos para indicar que el click no se realizó en una casilla
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
tiempoMovimiento.reiniciar();
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas){
switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4)))
{
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
moverPieza(1,coordenadas);
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 0:
moverPieza(2,coordenadas);
break;
}
}
private void moverPieza(int n,String coordenada){
if(jugadaLocal){
enviarMovimiento(crearCoordenada());
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}else{
validarCoordenadas(coordenada);
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}
jugadaLocal = !jugadaLocal;
if(n == 1){
Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
}
}
private boolean enroque(){
if(enroqueBlanco)
if(cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][7].setImageDrawable(casillas[7][7].getDrawable());
casillas[7][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}else if(cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][7].setImageDrawable(casillas[0][7].getDrawable());
casillas[0][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}
if(enroqueNegro)
if(cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][0].setImageDrawable(casillas[7][0].getDrawable());
casillas[7][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}else if(cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][0].setImageDrawable(casillas[0][0].getDrawable());
casillas[0][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}
return false;
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
if(true) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
casillas[cOrigen][fOrigen].setBackgroundResource(R.color.origen);
for(Ubicacion u:chess.mostrarMovimientos(fOrigen,cOrigen))
{
casillas[u.getCol()][u.getFila()].setBackgroundResource(R.drawable.seleccion);
}
} else {
cDestino = position[0];
fDestino = position[1];
destino = casillas[cDestino][fDestino];
if(!(destino == origen)) {
validarMovimiento(crearCoordenada());
setDefaultColor();
}else
setDefaultColor();
origen = null;
}
}
}else{
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = SocketServidor.getSocket().getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarMovimiento(values[0]);
Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show();
tiempoMovimiento.iniciar();
}
}
}
| app/src/main/java/com/mychess/mychess/Juego.java | package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
TextView nombreColumnas[] = new TextView[8];
TextView numeroFila[] = new TextView[8];
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
boolean enroqueBlanco = true;
boolean enroqueNegro = true;
boolean jugadaLocal;// sirve para difenciar entre una jugada local y una remota
Chess chess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillasNegro();
setOnclickListener();
setDefaultColor();
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
tiempoMovimiento.iniciar();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
/*---------------------*/
new SocketServidor().conectar();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(jugadaLocal) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
}else
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCampos(int n){
nombreColumnas[0] = (TextView) findViewById(R.id.columnaa);
nombreColumnas[1] = (TextView) findViewById(R.id.columnab);
nombreColumnas[2] = (TextView) findViewById(R.id.columnac);
nombreColumnas[3] = (TextView) findViewById(R.id.columnad);
nombreColumnas[4] = (TextView) findViewById(R.id.columnae);
nombreColumnas[5] = (TextView) findViewById(R.id.columnaf);
nombreColumnas[6] = (TextView) findViewById(R.id.columnag);
nombreColumnas[7] = (TextView) findViewById(R.id.columnah);
numeroFila[0] = (TextView) findViewById(R.id.fila1);
numeroFila[1]= (TextView) findViewById(R.id.fila2);
numeroFila[2]= (TextView) findViewById(R.id.fila3);
numeroFila[3]= (TextView) findViewById(R.id.fila4);
numeroFila[4]= (TextView) findViewById(R.id.fila5);
numeroFila[5]= (TextView) findViewById(R.id.fila6);
numeroFila[6]= (TextView) findViewById(R.id.fila7);
numeroFila[7]= (TextView) findViewById(R.id.fila8);
nombreColumnas[0].setText("a");
nombreColumnas[1].setText("b");
nombreColumnas[2].setText("c");
nombreColumnas[3].setText("d");
nombreColumnas[4].setText("e");
nombreColumnas[5].setText("f");
nombreColumnas[6].setText("g");
nombreColumnas[7].setText("h");
numeroFila[0].setText("1");
numeroFila[1].setText("2");
numeroFila[2].setText("3");
numeroFila[3].setText("4");
numeroFila[4].setText("5");
numeroFila[5].setText("6");
numeroFila[6].setText("7");
numeroFila[7].setText("8");
if(n == 2)
{
nombreColumnas[0].setText("h");
nombreColumnas[1].setText("g");
nombreColumnas[2].setText("f");
nombreColumnas[3].setText("e");
nombreColumnas[4].setText("d");
nombreColumnas[5].setText("c");
nombreColumnas[6].setText("b");
nombreColumnas[7].setText("a");
numeroFila[0].setText("8");
numeroFila[1].setText("7");
numeroFila[2].setText("6");
numeroFila[3].setText("5");
numeroFila[4].setText("4");
numeroFila[5].setText("3");
numeroFila[6].setText("2");
numeroFila[7].setText("1");
}
}
private void inicializarCasillasBlanco() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
colocarPiezas(1);
inicializarCampos(1);
jugadaLocal = true;
}
private void inicializarCasillasNegro() {
casillas[0][0] = (ImageView) findViewById(R.id.h1);
casillas[0][1] = (ImageView) findViewById(R.id.h2);
casillas[0][2] = (ImageView) findViewById(R.id.h3);
casillas[0][3] = (ImageView) findViewById(R.id.h4);
casillas[0][4] = (ImageView) findViewById(R.id.h5);
casillas[0][5] = (ImageView) findViewById(R.id.h6);
casillas[0][6] = (ImageView) findViewById(R.id.h7);
casillas[0][7] = (ImageView) findViewById(R.id.h8);
casillas[1][0] = (ImageView) findViewById(R.id.g1);
casillas[1][1] = (ImageView) findViewById(R.id.g2);
casillas[1][2] = (ImageView) findViewById(R.id.g3);
casillas[1][3] = (ImageView) findViewById(R.id.g4);
casillas[1][4] = (ImageView) findViewById(R.id.g5);
casillas[1][5] = (ImageView) findViewById(R.id.g6);
casillas[1][6] = (ImageView) findViewById(R.id.g7);
casillas[1][7] = (ImageView) findViewById(R.id.g8);
casillas[2][0] = (ImageView) findViewById(R.id.f1);
casillas[2][1] = (ImageView) findViewById(R.id.f2);
casillas[2][2] = (ImageView) findViewById(R.id.f3);
casillas[2][3] = (ImageView) findViewById(R.id.f4);
casillas[2][4] = (ImageView) findViewById(R.id.f5);
casillas[2][5] = (ImageView) findViewById(R.id.f6);
casillas[2][6] = (ImageView) findViewById(R.id.f7);
casillas[2][7] = (ImageView) findViewById(R.id.f8);
casillas[3][0] = (ImageView) findViewById(R.id.e1);
casillas[3][1] = (ImageView) findViewById(R.id.e2);
casillas[3][2] = (ImageView) findViewById(R.id.e3);
casillas[3][3] = (ImageView) findViewById(R.id.e4);
casillas[3][4] = (ImageView) findViewById(R.id.e5);
casillas[3][5] = (ImageView) findViewById(R.id.e6);
casillas[3][6] = (ImageView) findViewById(R.id.e7);
casillas[3][7] = (ImageView) findViewById(R.id.e8);
casillas[4][0] = (ImageView) findViewById(R.id.d1);
casillas[4][1] = (ImageView) findViewById(R.id.d2);
casillas[4][2] = (ImageView) findViewById(R.id.d3);
casillas[4][3] = (ImageView) findViewById(R.id.d4);
casillas[4][4] = (ImageView) findViewById(R.id.d5);
casillas[4][5] = (ImageView) findViewById(R.id.d6);
casillas[4][6] = (ImageView) findViewById(R.id.d7);
casillas[4][7] = (ImageView) findViewById(R.id.d8);
casillas[5][0] = (ImageView) findViewById(R.id.c1);
casillas[5][1] = (ImageView) findViewById(R.id.c2);
casillas[5][2] = (ImageView) findViewById(R.id.c3);
casillas[5][3] = (ImageView) findViewById(R.id.c4);
casillas[5][4] = (ImageView) findViewById(R.id.c5);
casillas[5][5] = (ImageView) findViewById(R.id.c6);
casillas[5][6] = (ImageView) findViewById(R.id.c7);
casillas[5][7] = (ImageView) findViewById(R.id.c8);
casillas[6][0] = (ImageView) findViewById(R.id.b1);
casillas[6][1] = (ImageView) findViewById(R.id.b2);
casillas[6][2] = (ImageView) findViewById(R.id.b3);
casillas[6][3] = (ImageView) findViewById(R.id.b4);
casillas[6][4] = (ImageView) findViewById(R.id.b5);
casillas[6][5] = (ImageView) findViewById(R.id.b6);
casillas[6][6] = (ImageView) findViewById(R.id.b7);
casillas[6][7] = (ImageView) findViewById(R.id.b8);
casillas[7][0] = (ImageView) findViewById(R.id.a1);
casillas[7][1] = (ImageView) findViewById(R.id.a2);
casillas[7][2] = (ImageView) findViewById(R.id.a3);
casillas[7][3] = (ImageView) findViewById(R.id.a4);
casillas[7][4] = (ImageView) findViewById(R.id.a5);
casillas[7][5] = (ImageView) findViewById(R.id.a6);
casillas[7][6] = (ImageView) findViewById(R.id.a7);
casillas[7][7] = (ImageView) findViewById(R.id.a8);
colocarPiezas(1);
inicializarCampos(2);
jugadaLocal = false;
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundResource(R.color.casillablanca);
else
casillas[i][j].setBackgroundResource(R.color.casillnegra);
dark = !dark;
}
dark = !dark;
}
}
private void colocarPiezas(int bando){
casillas[0][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[7][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[0][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[3][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[4][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[5][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[6][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[7][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[6][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[2][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[5][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[3][7].setImageResource(bando == 1?R.mipmap.alpha_wq:R.mipmap.alpha_bq);
casillas[4][7].setImageResource(bando == 1?R.mipmap.alpha_wk:R.mipmap.alpha_bk);
casillas[7][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[3][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[4][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[5][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[6][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[7][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[6][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[2][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[5][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[3][0].setImageResource(bando == 2 ? R.mipmap.alpha_wq : R.mipmap.alpha_bq);
casillas[4][0].setImageResource(bando == 2 ? R.mipmap.alpha_wk : R.mipmap.alpha_bk);
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};//inicialización del arreglo con valores negativos para indicar que el click no se realizó en una casilla
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
tiempoMovimiento.reiniciar();
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas){
switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4)))
{
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
moverPieza(1,coordenadas);
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 0:
moverPieza(2,coordenadas);
break;
}
}
private void moverPieza(int n,String coordenada){
if(jugadaLocal){
enviarMovimiento(crearCoordenada());
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}else{
validarCoordenadas(coordenada);
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}
jugadaLocal = !jugadaLocal;
if(n == 1){
Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
}
}
private boolean enroque(){
if(enroqueBlanco)
if(cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][7].setImageDrawable(casillas[7][7].getDrawable());
casillas[7][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}else if(cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][7].setImageDrawable(casillas[0][7].getDrawable());
casillas[0][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}
if(enroqueNegro)
if(cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][0].setImageDrawable(casillas[7][0].getDrawable());
casillas[7][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}else if(cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][0].setImageDrawable(casillas[0][0].getDrawable());
casillas[0][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}
return false;
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
if(jugadaLocal) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
} else {
origen = null;
cDestino = position[0];
fDestino = position[1];
validarMovimiento(crearCoordenada());
}
}
}else{
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = SocketServidor.getSocket().getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarMovimiento(values[0]);
Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show();
tiempoMovimiento.iniciar();
}
}
}
| modificación para mostrar los movimientos posibles de una pieza
| app/src/main/java/com/mychess/mychess/Juego.java | modificación para mostrar los movimientos posibles de una pieza | <ide><path>pp/src/main/java/com/mychess/mychess/Juego.java
<ide> import android.widget.Toast;
<ide>
<ide> import com.mychess.mychess.Chess.Chess;
<add>import com.mychess.mychess.Chess.Ubicacion;
<ide>
<ide> import java.io.DataInputStream;
<ide> import java.io.DataOutputStream;
<ide> setContentView(R.layout.activity_juego);
<ide> Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
<ide> setSupportActionBar(toolbar);
<del> inicializarCasillasNegro();
<add> inicializarCasillasBlanco();
<ide> setOnclickListener();
<ide> setDefaultColor();
<ide>
<ide>
<ide> @Override
<ide> public void onClick(View v) {
<del> if(jugadaLocal) {
<add> if(true) {
<ide> int position[] = getPosition(v.getId());
<ide> if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
<ide> if (origen == null) {
<ide> origen = casillas[position[0]][position[1]];
<ide> cOrigen = position[0];
<ide> fOrigen = position[1];
<add> casillas[cOrigen][fOrigen].setBackgroundResource(R.color.origen);
<add> for(Ubicacion u:chess.mostrarMovimientos(fOrigen,cOrigen))
<add> {
<add> casillas[u.getCol()][u.getFila()].setBackgroundResource(R.drawable.seleccion);
<add> }
<ide> } else {
<del>
<del> origen = null;
<ide> cDestino = position[0];
<ide> fDestino = position[1];
<del> validarMovimiento(crearCoordenada());
<del>
<add> destino = casillas[cDestino][fDestino];
<add> if(!(destino == origen)) {
<add> validarMovimiento(crearCoordenada());
<add> setDefaultColor();
<add> }else
<add> setDefaultColor();
<add> origen = null;
<ide> }
<ide> }
<ide> }else{ |
|
Java | mit | 9caace18b19d7ca51e585e5d52a96d30283f2c3b | 0 | CloudSpiral2015-C4/norakore,CloudSpiral2015-C4/norakore,CloudSpiral2015-C4/norakore,CloudSpiral2015-C4/norakore | package jp.kobe_u.cspiral.norakore;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import jp.kobe_u.cspiral.norakore.model.*;
import jp.kobe_u.cspiral.norakore.util.DBUtils;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.sun.jersey.core.util.Base64;
public class NorakoreController {
private final String NyavatarColl_Name = "nyavatar";
private final String UserColl_Name = "user";
private final String PictureColl_Name = "picture";
private final String IconColl_Name = "icon";
private DBCollection NyavatarColl;
private DBCollection UserColl;
private DBCollection PictureColl;
private DBCollection IconColl;
public NorakoreController() {
this.NyavatarColl = DBUtils.getInstance().getDb().getCollection(NyavatarColl_Name);
this.UserColl = DBUtils.getInstance().getDb().getCollection(UserColl_Name);
this.PictureColl = DBUtils.getInstance().getDb().getCollection(PictureColl_Name);
this.IconColl = DBUtils.getInstance().getDb().getCollection(IconColl_Name);
}
public NyavatarList searchNyavatar(double lon, double lat) {
final double search_area = 10000;
NyavatarList result = new NyavatarList();
List<Nyavatar> list = new ArrayList<Nyavatar>();
DBCursor cursor = NyavatarColl.find();
for (DBObject nya : cursor) {
// TODO: mongoのクエリ書く, 四角形範囲クエリにする
list.add(new Nyavatar(nya));
}
result.setList(list);
return result;
}
public NyavatarList getUsersNyavatar(String userID) throws Exception {
NyavatarList result = new NyavatarList();
try {
// retrieve the specified user's DBObject
// DBObject query = new BasicDBObject("_id", new ObjectId(userID));
DBObject query = new BasicDBObject("_id", userID);
DBObject userdbo = UserColl.findOne(query);
if (userdbo == null) throw new Exception("Specified user is not found.");
// get user's nyavatar list
BasicDBList id_list = (BasicDBList)userdbo.get("nyavatarList");
if (id_list == null) throw new Exception("user's nyavatarList is not found.");
// generate nyavatar list from id list
List<Nyavatar> ny_list = new ArrayList<Nyavatar>();
for(Object id: id_list) {
ObjectId oid = new ObjectId((String)id);
DBObject ny_dbo = NyavatarColl.findOne(new BasicDBObject("_id", oid));
if (ny_dbo == null) throw new Exception("There is lost-nyavatar on db.");
ny_list.add(new Nyavatar(ny_dbo));
}
// generate result object
result.setList(ny_list);
} catch (IllegalArgumentException e) {
throw new Exception(MessageFormat.format("Invalid userID, userID={0}", userID));
}
return result;
}
public NyavatarDetail getNyavatarDetail(String nyavatarID, String userID){
NyavatarDetail result = new NyavatarDetail();
DBObject query = new BasicDBObject("_id",new ObjectId(nyavatarID));
DBObject queryResult = NyavatarColl.findOne(query);
// TODO: likeUsersの中にuserIDが含まれるかのチェック⇒ふくまれていいたら、isLiked=true
result.setNyavatarID(queryResult.get("_id").toString());
result.setName((String)queryResult.get("name"));
result.setType((String)queryResult.get("type"));
result.setPictureID((String)queryResult.get("pictureID"));
result.setIconID((String)queryResult.get("iconID"));
result.setDate((Date)queryResult.get("date"));
result.setLocation(new Location((DBObject)queryResult.get("location")));
// TODO: LostCatIDにネコサーチAPIを投げて類似猫があれば、LostCatsこれくしょんに追加してそのIDを追加
// TODO: 広告文章をsayに追加する話は無視
result.setSay((String)queryResult.get("say"));
return result;
}
public String registerNyavatar(String userID, String name, String type,
String picture, double lon, double lat) throws Exception {
NyavatarDetail nya = new NyavatarDetail();
nya.setName(name);
nya.setType(type);
if (picture == null || picture.length() == 0) throw new Exception(
"Param:picture is not specified.");
String picid = saveImage(picture, "picture");
if (picid == "") throw new Exception("saveImage failed.");
nya.setPictureID(picid);
String iconid = "nullID";
Random rnd = new Random();
int ran = rnd.nextInt(2);
switch(ran){
case 0:
iconid = "563374c731b1b0e407093a9f";
case 1:
iconid = "563374d831b1b0e408093a9f";
}
nya.setIconID(iconid);
Location loc = new Location();
loc.setLon(lon);
loc.setLat(lat);
nya.setLocation(loc);
nya.setSay("お腹すいたにゃぁ~");
nya.determineParams(userID); // 欠落パラメータ補完
// TODO: 重複チェック;名前はともかく、pictureぐらいはチェック必要だろう
DBObject dbo = nya.toDBObject();
NyavatarColl.insert(dbo);
String nya_id = dbo.get("_id").toString();
// 登録するユーザを取得
//DBObject query = new BasicDBObject("_id", new ObjectId(userID));
DBObject query = new BasicDBObject("_id", userID);
DBObject userdbo = UserColl.findOne(query);
if (userdbo == null) throw new Exception("Specified user is not found.");
// ユーザのにゃばたーリストに登録したにゃばたーを追加する
BasicDBList list = (BasicDBList)userdbo.get("nyavatarList");
if (list == null) throw new Exception("user's nyavatarList is not found.");
list.add(nya_id);
// 更新したにゃばたーリストをユーザに適応する
userdbo.put("nyavatarList", list);
UserColl.update(query, userdbo);
return nya_id;
}
public String saveImage(String data, String res) {
DBObject dbo = new BasicDBObject("src", data);
if (res.equals("picture")){
PictureColl.save(dbo);
}else if (res.equals("icon")){
IconColl.save(dbo);
}else return "";
String id = dbo.get("_id").toString();
return id;
}
public ByteArrayOutputStream getImage(String id, String res) {
DBObject query = new BasicDBObject("_id", new ObjectId(id));
String type;
DBObject o;
if (res.equals("picture")){
o = PictureColl.findOne(query);
type = "jpg";
}else if (res.equals("icon")){
o = IconColl.findOne(query);
type = "png";
}else return null;
if (o == null) return null;
String src = (String)o.get("src");
src = src.split(",")[1];
byte[] bytes = Base64.decode(src);
try {
BufferedImage bImage = ImageIO.read(new ByteArrayInputStream(bytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bImage, type, baos);
return baos;
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return null;
}
}
| src/jp/kobe_u/cspiral/norakore/NorakoreController.java | package jp.kobe_u.cspiral.norakore;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import jp.kobe_u.cspiral.norakore.model.*;
import jp.kobe_u.cspiral.norakore.util.DBUtils;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.sun.jersey.core.util.Base64;
public class NorakoreController {
private final String NyavatarColl_Name = "nyavatar";
private final String UserColl_Name = "user";
private final String PictureColl_Name = "picture";
private final String IconColl_Name = "icon";
private DBCollection NyavatarColl;
private DBCollection UserColl;
private DBCollection PictureColl;
private DBCollection IconColl;
public NorakoreController() {
this.NyavatarColl = DBUtils.getInstance().getDb().getCollection(NyavatarColl_Name);
this.UserColl = DBUtils.getInstance().getDb().getCollection(UserColl_Name);
this.PictureColl = DBUtils.getInstance().getDb().getCollection(PictureColl_Name);
this.IconColl = DBUtils.getInstance().getDb().getCollection(IconColl_Name);
}
public NyavatarList searchNyavatar(double lon, double lat) {
final double search_area = 10000;
NyavatarList result = new NyavatarList();
List<Nyavatar> list = new ArrayList<Nyavatar>();
DBCursor cursor = NyavatarColl.find();
for (DBObject nya : cursor) {
// TODO: mongoのクエリ書く, 四角形範囲クエリにする
list.add(new Nyavatar(nya));
}
result.setList(list);
return result;
}
public NyavatarList getUsersNyavatar(String userID) throws Exception {
NyavatarList result = new NyavatarList();
try {
// retrieve the specified user's DBObject
DBObject query = new BasicDBObject("_id", new ObjectId(userID));
DBObject userdbo = UserColl.findOne(query);
if (userdbo == null) throw new Exception("Specified user is not found.");
// get user's nyavatar list
BasicDBList id_list = (BasicDBList)userdbo.get("nyavatarList");
if (id_list == null) throw new Exception("user's user is not found.");
// generate nyavatar list from id list
List<Nyavatar> ny_list = new ArrayList<Nyavatar>();
for(Object id: id_list) {
ObjectId oid = new ObjectId((String)id);
DBObject ny_dbo = NyavatarColl.findOne(new BasicDBObject("_id", oid));
if (ny_dbo == null) throw new Exception("There is lost-nyavatar on db.");
ny_list.add(new Nyavatar(ny_dbo));
}
// generate result object
result.setList(ny_list);
} catch (IllegalArgumentException e) {
throw new Exception(MessageFormat.format("Invalid userID, userID={0}", userID));
}
return result;
}
public NyavatarDetail getNyavatarDetail(String nyavatarID, String userID){
NyavatarDetail result = new NyavatarDetail();
DBObject query = new BasicDBObject("_id",new ObjectId(nyavatarID));
DBObject queryResult = NyavatarColl.findOne(query);
// TODO: likeUsersの中にuserIDが含まれるかのチェック⇒ふくまれていいたら、isLiked=true
result.setNyavatarID(queryResult.get("_id").toString());
result.setName((String)queryResult.get("name"));
result.setType((String)queryResult.get("type"));
result.setPictureID((String)queryResult.get("pictureID"));
result.setIconID((String)queryResult.get("iconID"));
result.setDate((Date)queryResult.get("date"));
result.setLocation(new Location((DBObject)queryResult.get("location")));
// TODO: LostCatIDにネコサーチAPIを投げて類似猫があれば、LostCatsこれくしょんに追加してそのIDを追加
// TODO: 広告文章をsayに追加する話は無視
result.setSay((String)queryResult.get("say"));
return result;
}
public String registerNyavatar(String userID, String name, String type,
String picture, double lon, double lat) throws Exception {
NyavatarDetail nya = new NyavatarDetail();
nya.setName(name);
nya.setType(type);
if (picture == null || picture.length() == 0) throw new Exception(
"Param:picture is not specified.");
String picid = saveImage(picture, "picture");
if (picid == "") throw new Exception("saveImage failed.");
nya.setPictureID(picid);
String iconid = "nullID";
Random rnd = new Random();
int ran = rnd.nextInt(2);
switch(ran){
case 0:
iconid = "563374c731b1b0e407093a9f";
case 1:
iconid = "563374d831b1b0e408093a9f";
}
nya.setIconID(iconid);
Location loc = new Location();
loc.setLon(lon);
loc.setLat(lat);
nya.setLocation(loc);
nya.setSay("お腹すいたにゃぁ~");
nya.determineParams(userID); // 欠落パラメータ補完
// TODO: 重複チェック;名前はともかく、pictureぐらいはチェック必要だろう
DBObject dbo = nya.toDBObject();
NyavatarColl.insert(dbo);
String nya_id = dbo.get("_id").toString();
// 登録するユーザを取得
// TODO: error handling
//DBObject query = new BasicDBObject("_id", new ObjectId(userID));
DBObject query = new BasicDBObject("_id", userID);
DBObject userdbo = UserColl.findOne(query);
if (userdbo == null) return null;
// ユーザのにゃばたーリストに登録したにゃばたーを追加する
BasicDBList list = (BasicDBList)userdbo.get("nyavatarList");
list.add(nya_id);
// 更新したにゃばたーリストをユーザに適応する
userdbo.put("nyavatarList", list);
UserColl.update(query, userdbo);
return nya_id;
}
public String saveImage(String data, String res) {
DBObject dbo = new BasicDBObject("src", data);
if (res.equals("picture")){
PictureColl.save(dbo);
}else if (res.equals("icon")){
IconColl.save(dbo);
}else return "";
String id = dbo.get("_id").toString();
return id;
}
public ByteArrayOutputStream getImage(String id, String res) {
DBObject query = new BasicDBObject("_id", new ObjectId(id));
String type;
DBObject o;
if (res.equals("picture")){
o = PictureColl.findOne(query);
type = "jpg";
}else if (res.equals("icon")){
o = IconColl.findOne(query);
type = "png";
}else return null;
if (o == null) return null;
String src = (String)o.get("src");
src = src.split(",")[1];
byte[] bytes = Base64.decode(src);
try {
BufferedImage bImage = ImageIO.read(new ByteArrayInputStream(bytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bImage, type, baos);
return baos;
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
return null;
}
}
| [add] api/registerにユーザ周りのエラー処理を追加
APIの入力やDBの状態がおかしかった場合のエラーをわかりやすくするため.
また,api/mynyavatarのuserIDをObjectIdでない仕様に合わせた.
| src/jp/kobe_u/cspiral/norakore/NorakoreController.java | [add] api/registerにユーザ周りのエラー処理を追加 | <ide><path>rc/jp/kobe_u/cspiral/norakore/NorakoreController.java
<ide> NyavatarList result = new NyavatarList();
<ide> try {
<ide> // retrieve the specified user's DBObject
<del> DBObject query = new BasicDBObject("_id", new ObjectId(userID));
<add> // DBObject query = new BasicDBObject("_id", new ObjectId(userID));
<add> DBObject query = new BasicDBObject("_id", userID);
<ide> DBObject userdbo = UserColl.findOne(query);
<ide> if (userdbo == null) throw new Exception("Specified user is not found.");
<ide>
<ide> // get user's nyavatar list
<ide> BasicDBList id_list = (BasicDBList)userdbo.get("nyavatarList");
<del> if (id_list == null) throw new Exception("user's user is not found.");
<add> if (id_list == null) throw new Exception("user's nyavatarList is not found.");
<ide>
<ide> // generate nyavatar list from id list
<ide> List<Nyavatar> ny_list = new ArrayList<Nyavatar>();
<ide> String nya_id = dbo.get("_id").toString();
<ide>
<ide> // 登録するユーザを取得
<del> // TODO: error handling
<ide> //DBObject query = new BasicDBObject("_id", new ObjectId(userID));
<ide> DBObject query = new BasicDBObject("_id", userID);
<ide> DBObject userdbo = UserColl.findOne(query);
<del> if (userdbo == null) return null;
<add> if (userdbo == null) throw new Exception("Specified user is not found.");
<ide> // ユーザのにゃばたーリストに登録したにゃばたーを追加する
<ide> BasicDBList list = (BasicDBList)userdbo.get("nyavatarList");
<add> if (list == null) throw new Exception("user's nyavatarList is not found.");
<ide> list.add(nya_id);
<ide> // 更新したにゃばたーリストをユーザに適応する
<ide> userdbo.put("nyavatarList", list); |
|
Java | apache-2.0 | 7877afa7486a20c2e179b74e36daeffda5e5ec05 | 0 | kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss | package com.kickstarter.ui.activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.jakewharton.processphoenix.ProcessPhoenix;
import com.kickstarter.KSApplication;
import com.kickstarter.R;
import com.kickstarter.libs.ApiEndpoint;
import com.kickstarter.libs.BaseActivity;
import com.kickstarter.libs.CurrentUser;
import com.kickstarter.libs.EnumAdapter;
import com.kickstarter.libs.Logout;
import com.kickstarter.libs.Release;
import com.kickstarter.libs.preferences.StringPreferenceType;
import com.kickstarter.libs.qualifiers.ApiEndpointPreference;
import com.kickstarter.libs.qualifiers.RequiresViewModel;
import com.kickstarter.models.User;
import com.kickstarter.ui.viewmodels.InternalToolsViewModel;
import org.joda.time.format.DateTimeFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.BindDrawable;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.kickstarter.libs.utils.TransitionUtils.slideInFromLeft;
@RequiresViewModel(InternalToolsViewModel.class)
public final class InternalToolsActivity extends BaseActivity<InternalToolsViewModel> {
@Inject @ApiEndpointPreference StringPreferenceType apiEndpointPreference;
@Inject Release release;
@Inject CurrentUser currentUser;
@Inject Logout logout;
@Bind(R.id.build_date) TextView buildDate;
@Bind(R.id.endpoint_spinner) Spinner endpointSpinner;
@Bind(R.id.sha) TextView sha;
@Bind(R.id.variant) TextView variant;
@Bind(R.id.version_code) TextView versionCode;
@Bind(R.id.version_name) TextView versionName;
@BindDrawable(android.R.drawable.ic_dialog_alert) Drawable icDialogAlertDrawable;
@Override
protected void onCreate(final @Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internal_tools_layout);
ButterKnife.bind(this);
((KSApplication) getApplicationContext()).component().inject(this);
setupNetworkSection();
setupBuildInformationSection();
}
@OnClick(R.id.playground_button)
public void playgroundClick() {
startActivity(new Intent(this, PlaygroundActivity.class));
}
@OnClick(R.id.push_notifications_button)
public void pushNotificationsButtonClick() {
final View view = LayoutInflater.from(this).inflate(R.layout.debug_push_notifications_layout, null);
new AlertDialog.Builder(this)
.setTitle("Push notifications")
.setView(view)
.show();
}
@OnClick(R.id.submit_bug_report_button)
public void submitBugReportButtonClick() {
currentUser.observable().take(1).subscribe(this::submitBugReport);
}
private void submitBugReport(final @Nullable User user) {
final String email = "***REMOVED***";
final List<String> debugInfo = Arrays.asList(
user != null ? user.name() : "Logged Out",
release.variant(),
release.versionName(),
release.versionCode().toString(),
release.sha(),
Integer.toString(Build.VERSION.SDK_INT),
Build.MANUFACTURER + " " + Build.MODEL,
Locale.getDefault().getLanguage()
);
final String body = new StringBuilder()
.append(TextUtils.join(" | ", debugInfo))
.append("\r\n\r\nDescribe the bug and add a subject. Attach images if it helps!\r\n")
.append("—————————————\r\n")
.toString();
final Intent intent = new Intent(android.content.Intent.ACTION_SEND)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.setType("message/rfc822")
.putExtra(Intent.EXTRA_TEXT, body)
.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
startActivity(Intent.createChooser(intent, getString(R.string.Select_email_application)));
}
private void setupNetworkSection() {
final ApiEndpoint currentApiEndpoint = ApiEndpoint.from(apiEndpointPreference.get());
final EnumAdapter<ApiEndpoint> endpointAdapter =
new EnumAdapter<>(this, ApiEndpoint.class, false, R.layout.black_spinner_item);
endpointSpinner.setAdapter(endpointAdapter);
endpointSpinner.setSelection(currentApiEndpoint.ordinal());
endpointSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(final @NonNull AdapterView<?> adapterView, final @NonNull View view,
final int position, final long id) {
final ApiEndpoint selected = endpointAdapter.getItem(position);
if (selected != currentApiEndpoint) {
if (selected == ApiEndpoint.CUSTOM) {
showCustomEndpointDialog(currentApiEndpoint.ordinal(), "https://");
} else {
setEndpointAndRelaunch(selected.url());
}
}
}
@Override
public void onNothingSelected(final @NonNull AdapterView<?> adapterView) {}
});
}
private void setupBuildInformationSection() {
buildDate.setText(release.dateTime().toString(DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss aa zzz")));
sha.setText(release.sha());
variant.setText(release.variant());
versionCode.setText(release.versionCode().toString());
versionName.setText(release.versionName());
}
private void showCustomEndpointDialog(final int originalSelection, final @NonNull String defaultUrl) {
final View view = LayoutInflater.from(this).inflate(R.layout.api_endpoint_layout, null);
final EditText url = ButterKnife.findById(view, R.id.url);
url.setText(defaultUrl);
url.setSelection(url.length());
new AlertDialog.Builder(this)
.setTitle("Set API Endpoint")
.setView(view)
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
String inputUrl = url.getText().toString();
if (inputUrl.length() > 0) {
// Remove trailing '/'
if (inputUrl.charAt(inputUrl.length() - 1) == '/') {
inputUrl = inputUrl.substring(0, inputUrl.length() - 1);
}
setEndpointAndRelaunch(inputUrl);
} else {
endpointSpinner.setSelection(originalSelection);
}
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
endpointSpinner.setSelection(originalSelection);
dialog.cancel();
})
.setOnCancelListener(dialogInterface -> {
// TODO: Is this redundant?
endpointSpinner.setSelection(originalSelection);
})
.setIcon(icDialogAlertDrawable)
.show();
}
private void setEndpointAndRelaunch(final @NonNull String endpoint) {
apiEndpointPreference.set(endpoint);
logout.execute();
ProcessPhoenix.triggerRebirth(this);
}
protected @Nullable Pair<Integer, Integer> exitTransition() {
return slideInFromLeft();
}
}
| app/src/internal/java/com/kickstarter/ui/activities/InternalToolsActivity.java | package com.kickstarter.ui.activities;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import com.jakewharton.processphoenix.ProcessPhoenix;
import com.kickstarter.KSApplication;
import com.kickstarter.R;
import com.kickstarter.libs.ApiEndpoint;
import com.kickstarter.libs.BaseActivity;
import com.kickstarter.libs.CurrentUser;
import com.kickstarter.libs.EnumAdapter;
import com.kickstarter.libs.Logout;
import com.kickstarter.libs.Release;
import com.kickstarter.libs.preferences.StringPreferenceType;
import com.kickstarter.libs.qualifiers.ApiEndpointPreference;
import com.kickstarter.libs.qualifiers.RequiresViewModel;
import com.kickstarter.models.User;
import com.kickstarter.ui.viewmodels.InternalToolsViewModel;
import org.joda.time.format.DateTimeFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.BindDrawable;
import butterknife.ButterKnife;
import butterknife.OnClick;
import static com.kickstarter.libs.utils.TransitionUtils.slideInFromLeft;
@RequiresViewModel(InternalToolsViewModel.class)
public final class InternalToolsActivity extends BaseActivity<InternalToolsViewModel> {
@Inject @ApiEndpointPreference StringPreferenceType apiEndpointPreference;
@Inject Release release;
@Inject CurrentUser currentUser;
@Inject Logout logout;
@Bind(R.id.build_date) TextView buildDate;
@Bind(R.id.endpoint_spinner) Spinner endpointSpinner;
@Bind(R.id.sha) TextView sha;
@Bind(R.id.variant) TextView variant;
@Bind(R.id.version_code) TextView versionCode;
@Bind(R.id.version_name) TextView versionName;
@BindDrawable(android.R.drawable.ic_dialog_alert) Drawable icDialogAlertDrawable;
@Override
protected void onCreate(final @Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internal_tools_layout);
ButterKnife.bind(this);
((KSApplication) getApplicationContext()).component().inject(this);
setupNetworkSection();
setupBuildInformationSection();
}
@OnClick(R.id.playground_button)
public void playgroundClick() {
startActivity(new Intent(this, PlaygroundActivity.class));
}
@OnClick(R.id.push_notifications_button)
public void pushNotificationsButtonClick() {
final View view = LayoutInflater.from(this).inflate(R.layout.debug_push_notifications_layout, null);
new AlertDialog.Builder(this)
.setTitle("Push notifications")
.setView(view)
.show();
}
@OnClick(R.id.submit_bug_report_button)
public void submitBugReportButtonClick() {
currentUser.observable().take(1).subscribe(this::submitBugReport);
}
private void submitBugReport(final @Nullable User user) {
final String email = "chrstphrwrght+21qbymyz894ttajaomwh@***REMOVED***";
final List<String> debugInfo = Arrays.asList(
user != null ? user.name() : "Logged Out",
release.variant(),
release.versionName(),
release.versionCode().toString(),
release.sha(),
Integer.toString(Build.VERSION.SDK_INT),
Build.MANUFACTURER + " " + Build.MODEL,
Locale.getDefault().getLanguage()
);
final String body = new StringBuilder()
.append(TextUtils.join(" | ", debugInfo))
.append("\r\n\r\nDescribe the bug and add a subject. Attach images if it helps!\r\n")
.append("—————————————\r\n")
.toString();
final Intent intent = new Intent(android.content.Intent.ACTION_SEND)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
.setType("message/rfc822")
.putExtra(Intent.EXTRA_TEXT, body)
.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
startActivity(Intent.createChooser(intent, getString(R.string.Select_email_application)));
}
private void setupNetworkSection() {
final ApiEndpoint currentApiEndpoint = ApiEndpoint.from(apiEndpointPreference.get());
final EnumAdapter<ApiEndpoint> endpointAdapter =
new EnumAdapter<>(this, ApiEndpoint.class, false, R.layout.black_spinner_item);
endpointSpinner.setAdapter(endpointAdapter);
endpointSpinner.setSelection(currentApiEndpoint.ordinal());
endpointSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(final @NonNull AdapterView<?> adapterView, final @NonNull View view,
final int position, final long id) {
final ApiEndpoint selected = endpointAdapter.getItem(position);
if (selected != currentApiEndpoint) {
if (selected == ApiEndpoint.CUSTOM) {
showCustomEndpointDialog(currentApiEndpoint.ordinal(), "https://");
} else {
setEndpointAndRelaunch(selected.url());
}
}
}
@Override
public void onNothingSelected(final @NonNull AdapterView<?> adapterView) {}
});
}
private void setupBuildInformationSection() {
buildDate.setText(release.dateTime().toString(DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss aa zzz")));
sha.setText(release.sha());
variant.setText(release.variant());
versionCode.setText(release.versionCode().toString());
versionName.setText(release.versionName());
}
private void showCustomEndpointDialog(final int originalSelection, final @NonNull String defaultUrl) {
final View view = LayoutInflater.from(this).inflate(R.layout.api_endpoint_layout, null);
final EditText url = ButterKnife.findById(view, R.id.url);
url.setText(defaultUrl);
url.setSelection(url.length());
new AlertDialog.Builder(this)
.setTitle("Set API Endpoint")
.setView(view)
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
String inputUrl = url.getText().toString();
if (inputUrl.length() > 0) {
// Remove trailing '/'
if (inputUrl.charAt(inputUrl.length() - 1) == '/') {
inputUrl = inputUrl.substring(0, inputUrl.length() - 1);
}
setEndpointAndRelaunch(inputUrl);
} else {
endpointSpinner.setSelection(originalSelection);
}
})
.setNegativeButton(android.R.string.cancel, (dialog, which) -> {
endpointSpinner.setSelection(originalSelection);
dialog.cancel();
})
.setOnCancelListener(dialogInterface -> {
// TODO: Is this redundant?
endpointSpinner.setSelection(originalSelection);
})
.setIcon(icDialogAlertDrawable)
.show();
}
private void setEndpointAndRelaunch(final @NonNull String endpoint) {
apiEndpointPreference.set(endpoint);
logout.execute();
ProcessPhoenix.triggerRebirth(this);
}
protected @Nullable Pair<Integer, Integer> exitTransition() {
return slideInFromLeft();
}
}
| Feedback email posts to Native Meta board
| app/src/internal/java/com/kickstarter/ui/activities/InternalToolsActivity.java | Feedback email posts to Native Meta board | <ide><path>pp/src/internal/java/com/kickstarter/ui/activities/InternalToolsActivity.java
<ide> }
<ide>
<ide> private void submitBugReport(final @Nullable User user) {
<del> final String email = "chrstphrwrght+21qbymyz894ttajaomwh@***REMOVED***";
<add> final String email = "***REMOVED***";
<ide>
<ide> final List<String> debugInfo = Arrays.asList(
<ide> user != null ? user.name() : "Logged Out", |
|
Java | mit | 2f4d3183c15d7c0a79c89b8985a9bab7c92aa234 | 0 | CS2103AUG2016-F10-C1/main,CS2103AUG2016-F10-C1/main,CS2103AUG2016-F10-C1/main | package tars.storage;
import tars.commons.exceptions.IllegalValueException;
import tars.model.task.*;
import tars.model.tag.Tag;
import tars.model.tag.UniqueTagList;
import javax.xml.bind.annotation.XmlElement;
import java.util.ArrayList;
import java.util.List;
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String name;
@XmlElement(required = true)
private String priority;
@XmlElement(required = true)
private DateTime dateTime;
@XmlElement(required = true)
private boolean status;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* No-arg constructor for JAXB use.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
name = source.getName().taskName;
priority = source.getPriority().priorityLevel;
dateTime = source.getDateTime();
status = source.getStatus().status;
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
/**
* Converts this jaxb-friendly adapted task object into the model's Task object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted task
*/
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Name name = new Name(this.name);
final Priority priority = new Priority(this.priority);
final DateTime dateTime = new DateTime(this.dateTime.startDateString, this.dateTime.endDateString);
final Status status = new Status(this.status);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(name, dateTime, priority, status, tags);
}
}
| src/main/java/tars/storage/XmlAdaptedTask.java | package tars.storage;
import tars.commons.exceptions.IllegalValueException;
import tars.model.task.*;
import tars.model.tag.Tag;
import tars.model.tag.UniqueTagList;
import javax.xml.bind.annotation.XmlElement;
import java.util.ArrayList;
import java.util.List;
/**
* JAXB-friendly version of the Task.
*/
public class XmlAdaptedTask {
@XmlElement(required = true)
private String name;
@XmlElement
private String priority;
@XmlElement(required = true)
private DateTime dateTime;
@XmlElement(required = true)
private boolean status;
@XmlElement
private List<XmlAdaptedTag> tagged = new ArrayList<>();
/**
* No-arg constructor for JAXB use.
*/
public XmlAdaptedTask() {}
/**
* Converts a given Task into this class for JAXB use.
*
* @param source future changes to this will not affect the created XmlAdaptedTask
*/
public XmlAdaptedTask(ReadOnlyTask source) {
name = source.getName().taskName;
priority = source.getPriority().priorityLevel;
dateTime = source.getDateTime();
status = source.getStatus().status;
tagged = new ArrayList<>();
for (Tag tag : source.getTags()) {
tagged.add(new XmlAdaptedTag(tag));
}
}
/**
* Converts this jaxb-friendly adapted task object into the model's Task object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted task
*/
public Task toModelType() throws IllegalValueException {
final List<Tag> taskTags = new ArrayList<>();
for (XmlAdaptedTag tag : tagged) {
taskTags.add(tag.toModelType());
}
final Name name = new Name(this.name);
final Priority priority = new Priority(this.priority);
final DateTime dateTime = new DateTime(this.dateTime.startDateString, this.dateTime.endDateString);
final Status status = new Status(this.status);
final UniqueTagList tags = new UniqueTagList(taskTags);
return new Task(name, dateTime, priority, status, tags);
}
}
| Add @XmlElement requirement to Priority
| src/main/java/tars/storage/XmlAdaptedTask.java | Add @XmlElement requirement to Priority | <ide><path>rc/main/java/tars/storage/XmlAdaptedTask.java
<ide>
<ide> @XmlElement(required = true)
<ide> private String name;
<del> @XmlElement
<add> @XmlElement(required = true)
<ide> private String priority;
<ide> @XmlElement(required = true)
<ide> private DateTime dateTime; |
|
Java | apache-2.0 | 30489147e622b1e7f6ae15f479abf7daa039b7d8 | 0 | ycaihua/metadata-extractor,drewnoakes/metadata-extractor,Nadahar/metadata-extractor,Widen/metadata-extractor,RoyZeng/metadata-extractor,veggiespam/metadata-extractor,Nadahar/metadata-extractor,veggiespam/metadata-extractor,PaytonGarland/metadata-extractor,rcketscientist/metadata-extractor,wswenyue/metadata-extractor,RoyZeng/metadata-extractor,ycaihua/metadata-extractor,wswenyue/metadata-extractor | /*
* Copyright 2002-2015 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.metadata.jfif;
import com.drew.imaging.jpeg.JpegSegmentMetadataReader;
import com.drew.imaging.jpeg.JpegSegmentType;
import com.drew.lang.ByteArrayReader;
import com.drew.lang.RandomAccessReader;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataReader;
import java.io.IOException;
import java.util.Arrays;
/**
* Reader for JFIF data, found in the APP0 JPEG segment.
* <p>
* More info at:
* <ul>
* <li>http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format</li>
* <li>http://www.w3.org/Graphics/JPEG/jfif3.pdf</li>
* </ul>
*
* @author Yuri Binev, Drew Noakes, Markus Meyer
*/
public class JfifReader implements JpegSegmentMetadataReader, MetadataReader
{
public static final String PREAMBLE = "JFIF";
@NotNull
public Iterable<JpegSegmentType> getSegmentTypes()
{
return Arrays.asList(JpegSegmentType.APP0);
}
public void readJpegSegments(@NotNull Iterable<byte[]> segments, @NotNull Metadata metadata, @NotNull JpegSegmentType segmentType)
{
for (byte[] segmentBytes : segments) {
// Skip segments not starting with the required header
if (segmentBytes.length >= 4 && PREAMBLE.equals(new String(segmentBytes, 0, PREAMBLE.length())))
extract(new ByteArrayReader(segmentBytes), metadata);
}
}
/**
* Performs the Jfif data extraction, adding found values to the specified
* instance of {@link Metadata}.
*/
public void extract(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata)
{
JfifDirectory directory = new JfifDirectory();
metadata.addDirectory(directory);
try {
// For JFIF, the tag number is also the offset into the segment
int ver = reader.getUInt16(JfifDirectory.TAG_VERSION);
directory.setInt(JfifDirectory.TAG_VERSION, ver);
int units = reader.getUInt8(JfifDirectory.TAG_UNITS);
directory.setInt(JfifDirectory.TAG_UNITS, units);
int height = reader.getUInt16(JfifDirectory.TAG_RESX);
directory.setInt(JfifDirectory.TAG_RESX, height);
int width = reader.getUInt16(JfifDirectory.TAG_RESY);
directory.setInt(JfifDirectory.TAG_RESY, width);
} catch (IOException me) {
directory.addError(me.getMessage());
}
}
}
| Source/com/drew/metadata/jfif/JfifReader.java | /*
* Copyright 2002-2015 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.metadata.jfif;
import com.drew.imaging.jpeg.JpegSegmentMetadataReader;
import com.drew.imaging.jpeg.JpegSegmentType;
import com.drew.lang.ByteArrayReader;
import com.drew.lang.RandomAccessReader;
import com.drew.lang.annotations.NotNull;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataReader;
import java.io.IOException;
import java.util.Arrays;
/**
* Reader for JFIF data, found in the APP0 JPEG segment.
* <p>
* More info at: http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
*
* @author Yuri Binev, Drew Noakes, Markus Meyer
*/
public class JfifReader implements JpegSegmentMetadataReader, MetadataReader
{
public static final String PREAMBLE = "JFIF";
@NotNull
public Iterable<JpegSegmentType> getSegmentTypes()
{
return Arrays.asList(JpegSegmentType.APP0);
}
public void readJpegSegments(@NotNull Iterable<byte[]> segments, @NotNull Metadata metadata, @NotNull JpegSegmentType segmentType)
{
for (byte[] segmentBytes : segments) {
// Skip segments not starting with the required header
if (segmentBytes.length >= 4 && PREAMBLE.equals(new String(segmentBytes, 0, PREAMBLE.length())))
extract(new ByteArrayReader(segmentBytes), metadata);
}
}
/**
* Performs the Jfif data extraction, adding found values to the specified
* instance of {@link Metadata}.
*/
public void extract(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata)
{
JfifDirectory directory = new JfifDirectory();
metadata.addDirectory(directory);
try {
// For JFIF, the tag number is also the offset into the segment
int ver = reader.getUInt16(JfifDirectory.TAG_VERSION);
directory.setInt(JfifDirectory.TAG_VERSION, ver);
int units = reader.getUInt8(JfifDirectory.TAG_UNITS);
directory.setInt(JfifDirectory.TAG_UNITS, units);
int height = reader.getUInt16(JfifDirectory.TAG_RESX);
directory.setInt(JfifDirectory.TAG_RESX, height);
int width = reader.getUInt16(JfifDirectory.TAG_RESY);
directory.setInt(JfifDirectory.TAG_RESY, width);
} catch (IOException me) {
directory.addError(me.getMessage());
}
}
}
| Link to JFIF spec PDF.
| Source/com/drew/metadata/jfif/JfifReader.java | Link to JFIF spec PDF. | <ide><path>ource/com/drew/metadata/jfif/JfifReader.java
<ide> /**
<ide> * Reader for JFIF data, found in the APP0 JPEG segment.
<ide> * <p>
<del> * More info at: http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
<add> * More info at:
<add> * <ul>
<add> * <li>http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format</li>
<add> * <li>http://www.w3.org/Graphics/JPEG/jfif3.pdf</li>
<add> * </ul>
<ide> *
<ide> * @author Yuri Binev, Drew Noakes, Markus Meyer
<ide> */ |
|
Java | apache-2.0 | 31af86884d4e6c54dd4b4cfde95a3f821a1f4069 | 0 | Martinfx/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa | package cz.brmlab.yodaqa.provider.rdf;
import java.util.ArrayList;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Literal;
import org.slf4j.Logger;
/** A wrapper around DBpedia "Titles" dataset that maps titles to
* Wikipedia articles. The main point of using this is to find out
* whether an article with the given title (termed also "label")
* exists.
*
* Articles are represented as (label, pageId), where label is the
* article title. The label is included as we pass through redirects. */
public class DBpediaTitles extends CachedJenaLookup {
public class Article {
protected int pageID;
protected String label;
public Article(int pageID_, String label_) {
pageID = pageID_;
label = label_;
}
/** @return the pageID */
public int getPageID() {
return pageID;
}
/** @return the label */
public String getLabel() {
return label;
}
}
/** Query for a given title, returning a set of articles. */
public List<Article> query(String title, Logger logger) {
/* XXX: Case-insensitive search via SPARQL turns out
* to be surprisingly tricky. Cover 90% of all cases
* by force-capitalizing the first letter in the sought
* after title. */
boolean wasCapitalized = Character.toUpperCase(title.charAt(0)) == title.charAt(0);
title = Character.toUpperCase(title.charAt(0)) + title.substring(1);
title = title.replaceAll("\"", "");
String rawQueryStr =
"{\n" +
// (A) fetch resources with @title label
" ?res rdfs:label \"" + title + "\"@en.\n" +
"} UNION {\n" +
// (B) fetch also resources targetted by @title redirect
" ?redir dbo:wikiPageRedirects ?res .\n" +
" ?redir rdfs:label \"" + title + "\"@en .\n" +
"}\n" +
// for (B), we are also getting a redundant (A) entry;
// identify the redundant (A) entry by filling
// ?redirTarget in that case
"OPTIONAL { ?res dbo:wikiPageRedirects ?redirTarget . }\n" +
// set the output variables
"?res dbo:wikiPageID ?pageID .\n" +
"?res rdfs:label ?label .\n" +
// ignore the redundant (A) entries (that are redirects)
"FILTER ( !BOUND(?redirTarget) )\n" +
// weed out categories and other in-namespace junk
"FILTER ( !regex(str(?res), '^http://dbpedia.org/resource/[^_]*:', 'i') )\n" +
// output only english labels, thankyouverymuch
"FILTER ( LANG(?label) = 'en' )\n" +
"";
//logger.debug("executing sparql query: {}", rawQueryStr);
List<Literal[]> rawResults = rawQuery(rawQueryStr,
new String[] { "pageID", "label" });
List<Article> results = new ArrayList<Article>(rawResults.size());
for (Literal[] rawResult : rawResults) {
String label = rawResult[1].getString();
/* Undo capitalization if the label isn't all-caps
* and the original title wasn't capitalized either.
* Otherwise, all our terms will end up all-caps,
* a silly thing. */
if (!wasCapitalized && (label.length() > 1 && Character.toUpperCase(label.charAt(1)) != label.charAt(1)))
label = Character.toLowerCase(label.charAt(0)) + label.substring(1);
logger.debug("DBpedia {}: [[{}]]", title, label);
results.add(new Article(rawResult[0].getInt(), label));
}
return results;
/*
return rawQuery("?res rdfs:label \"" + title + "\"@en.\n" +
"?res dbo:wikiPageID ?pageid\n" +
// weed out categories and other in-namespace junk
"FILTER ( !regex(str(?res), '^http://dbpedia.org/resource/[^_]*:', 'i') )\n",
"pageid");
*/
}
}
| src/main/java/cz/brmlab/yodaqa/provider/rdf/DBpediaTitles.java | package cz.brmlab.yodaqa.provider.rdf;
import java.util.ArrayList;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Literal;
import org.slf4j.Logger;
/** A wrapper around DBpedia "Titles" dataset that maps titles to
* Wikipedia articles. The main point of using this is to find out
* whether an article with the given title (termed also "label")
* exists.
*
* Articles are represented as (label, pageId), where label is the
* article title. The label is included as we pass through redirects. */
public class DBpediaTitles extends CachedJenaLookup {
public class Article {
protected int pageID;
protected String label;
public Article(int pageID_, String label_) {
pageID = pageID_;
label = label_;
}
/** @return the pageID */
public int getPageID() {
return pageID;
}
/** @return the label */
public String getLabel() {
return label;
}
}
/** Query for a given title, returning a set of articles. */
public List<Article> query(String title, Logger logger) {
/* XXX: Case-insensitive search via SPARQL turns out
* to be surprisingly tricky. Cover 90% of all cases
* by force-capitalizing the first letter in the sought
* after title. */
boolean wasCapitalized = Character.toUpperCase(title.charAt(0)) == title.charAt(0);
title = Character.toUpperCase(title.charAt(0)) + title.substring(1);
title = title.replaceAll("\"", "");
String rawQueryStr =
"{\n" +
// (A) fetch resources with @title label
" ?res rdfs:label \"" + title + "\"@en.\n" +
"} UNION {\n" +
// (B) fetch also resources targetted by @title redirect
" ?redir dbo:wikiPageRedirects ?res .\n" +
" ?redir rdfs:label \"" + title + "\"@en .\n" +
"}\n" +
// for (B), we are also getting a redundant (A) entry;
// identify the redundant (A) entry by filling
// ?redirTarget in that case
"OPTIONAL { ?res dbo:wikiPageRedirects ?redirTarget . }\n" +
// set the output variables
"?res dbo:wikiPageID ?pageID .\n" +
"?res rdfs:label ?label .\n" +
// ignore the redundant (A) entries (that are redirects)
"FILTER ( !BOUND(?redirTarget) )\n" +
// weed out categories and other in-namespace junk
"FILTER ( !regex(str(?res), '^http://dbpedia.org/resource/[^_]*:', 'i') )\n" +
// output only english labels, thankyouverymuch
"FILTER ( LANG(?label) = 'en' )\n" +
"";
//logger.debug("executing sparql query: {}", rawQueryStr);
List<Literal[]> rawResults = rawQuery(rawQueryStr,
new String[] { "pageID", "label" });
List<Article> results = new ArrayList<Article>(rawResults.size());
for (Literal[] rawResult : rawResults) {
String label = rawResult[1].getString();
/* Undo capitalization if the label isn't all-caps
* and the original title wasn't capitalized either.
* Otherwise, all our terms will end up all-caps,
* a silly thing. */
if (!wasCapitalized && (Character.toUpperCase(label.charAt(1)) != label.charAt(1)))
label = Character.toLowerCase(label.charAt(0)) + label.substring(1);
logger.debug("DBpedia {}: [[{}]]", title, label);
results.add(new Article(rawResult[0].getInt(), label));
}
return results;
/*
return rawQuery("?res rdfs:label \"" + title + "\"@en.\n" +
"?res dbo:wikiPageID ?pageid\n" +
// weed out categories and other in-namespace junk
"FILTER ( !regex(str(?res), '^http://dbpedia.org/resource/[^_]*:', 'i') )\n",
"pageid");
*/
}
}
| DBpediaTitles: Fix crash on certain single-letter words in question
| src/main/java/cz/brmlab/yodaqa/provider/rdf/DBpediaTitles.java | DBpediaTitles: Fix crash on certain single-letter words in question | <ide><path>rc/main/java/cz/brmlab/yodaqa/provider/rdf/DBpediaTitles.java
<ide> * and the original title wasn't capitalized either.
<ide> * Otherwise, all our terms will end up all-caps,
<ide> * a silly thing. */
<del> if (!wasCapitalized && (Character.toUpperCase(label.charAt(1)) != label.charAt(1)))
<add> if (!wasCapitalized && (label.length() > 1 && Character.toUpperCase(label.charAt(1)) != label.charAt(1)))
<ide> label = Character.toLowerCase(label.charAt(0)) + label.substring(1);
<ide> logger.debug("DBpedia {}: [[{}]]", title, label);
<ide> results.add(new Article(rawResult[0].getInt(), label)); |
|
Java | apache-2.0 | e71fd6948f3307abdfd2eb1f62719c409913ab48 | 0 | apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat | /*
* 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.tomcat.util.net;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyStore;
import java.security.UnrecoverableKeyException;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ObjectName;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.openssl.OpenSSLConf;
import org.apache.tomcat.util.net.openssl.ciphers.Cipher;
import org.apache.tomcat.util.net.openssl.ciphers.OpenSSLCipherConfigurationParser;
import org.apache.tomcat.util.res.StringManager;
/**
* Represents the TLS configuration for a virtual host.
*/
public class SSLHostConfig implements Serializable {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(SSLHostConfig.class);
private static final StringManager sm = StringManager.getManager(SSLHostConfig.class);
protected static final String DEFAULT_SSL_HOST_NAME = "_default_";
protected static final Set<String> SSL_PROTO_ALL_SET = new HashSet<>();
static {
/* Default used if protocols is not configured, also used if
* protocols="All"
*/
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_SSLv2Hello);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_1);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_2);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_3);
}
private Type configType = null;
private Type currentConfigType = null;
private Map<Type, Set<String>> configuredProperties = new EnumMap<>(Type.class);
private String hostName = DEFAULT_SSL_HOST_NAME;
private transient Long openSslConfContext = Long.valueOf(0);
// OpenSSL can handle multiple certs in a single config so the reference to
// the context is here at the virtual host level. JSSE can't so the
// reference is held on the certificate.
private transient Long openSslContext = Long.valueOf(0);
// Configuration properties
// Internal
private String[] enabledCiphers;
private String[] enabledProtocols;
private ObjectName oname;
// Need to know if TLS 1.3 has been explicitly requested as a warning needs
// to generated if it is explicitly requested for a JVM that does not
// support it. Uses a set so it is extensible for TLS 1.4 etc.
private Set<String> explicitlyRequestedProtocols = new HashSet<>();
// Nested
private SSLHostConfigCertificate defaultCertificate = null;
private Set<SSLHostConfigCertificate> certificates = new LinkedHashSet<>(4);
// Common
private String certificateRevocationListFile;
private CertificateVerification certificateVerification = CertificateVerification.NONE;
private int certificateVerificationDepth = 10;
// Used to track if certificateVerificationDepth has been explicitly set
private boolean certificateVerificationDepthConfigured = false;
private String ciphers = "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!kRSA";
private LinkedHashSet<Cipher> cipherList = null;
private List<String> jsseCipherNames = null;
private boolean honorCipherOrder = false;
private Set<String> protocols = new HashSet<>();
// JSSE
private String keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
private boolean revocationEnabled = false;
private int sessionCacheSize = 0;
private int sessionTimeout = 86400;
private String sslProtocol = Constants.SSL_PROTO_TLS;
private String trustManagerClassName;
private String truststoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
private String truststoreFile = System.getProperty("javax.net.ssl.trustStore");
private String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
private String truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
private String truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
private transient KeyStore truststore = null;
// OpenSSL
private String certificateRevocationListPath;
private String caCertificateFile;
private String caCertificatePath;
private boolean disableCompression = true;
private boolean disableSessionTickets = false;
private boolean insecureRenegotiation = false;
private OpenSSLConf openSslConf = null;
public SSLHostConfig() {
// Set defaults that can't be (easily) set when defining the fields.
setProtocols(Constants.SSL_PROTO_ALL);
}
public Long getOpenSslConfContext() {
return openSslConfContext;
}
public void setOpenSslConfContext(Long openSslConfContext) {
this.openSslConfContext = openSslConfContext;
}
public Long getOpenSslContext() {
return openSslContext;
}
public void setOpenSslContext(Long openSslContext) {
this.openSslContext = openSslContext;
}
// Expose in String form for JMX
public String getConfigType() {
return configType.name();
}
public void setConfigType(Type configType) {
this.configType = configType;
if (configType == Type.EITHER) {
if (configuredProperties.remove(Type.JSSE) == null) {
configuredProperties.remove(Type.OPENSSL);
}
} else {
configuredProperties.remove(configType);
}
for (Map.Entry<Type,Set<String>> entry : configuredProperties.entrySet()) {
for (String property : entry.getValue()) {
log.warn(sm.getString("sslHostConfig.mismatch",
property, getHostName(), entry.getKey(), configType));
}
}
}
void setProperty(String name, Type configType) {
if (this.configType == null) {
Set<String> properties = configuredProperties.get(configType);
if (properties == null) {
properties = new HashSet<>();
configuredProperties.put(configType, properties);
}
properties.add(name);
} else if (this.configType == Type.EITHER) {
if (currentConfigType == null) {
currentConfigType = configType;
} else if (currentConfigType != configType) {
log.warn(sm.getString("sslHostConfig.mismatch",
name, getHostName(), configType, currentConfigType));
}
} else {
if (configType != this.configType) {
log.warn(sm.getString("sslHostConfig.mismatch",
name, getHostName(), configType, this.configType));
}
}
}
// ----------------------------------------------------- Internal properties
/**
* @see SSLUtil#getEnabledProtocols()
*
* @return The protocols enabled for this TLS virtual host
*/
public String[] getEnabledProtocols() {
return enabledProtocols;
}
public void setEnabledProtocols(String[] enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
/**
* @see SSLUtil#getEnabledCiphers()
*
* @return The ciphers enabled for this TLS virtual host
*/
public String[] getEnabledCiphers() {
return enabledCiphers;
}
public void setEnabledCiphers(String[] enabledCiphers) {
this.enabledCiphers = enabledCiphers;
}
public ObjectName getObjectName() {
return oname;
}
public void setObjectName(ObjectName oname) {
this.oname = oname;
}
// ------------------------------------------- Nested configuration elements
private void registerDefaultCertificate() {
if (defaultCertificate == null) {
defaultCertificate = new SSLHostConfigCertificate(
this, SSLHostConfigCertificate.Type.UNDEFINED);
certificates.add(defaultCertificate);
}
}
public void addCertificate(SSLHostConfigCertificate certificate) {
// Need to make sure that if there is more than one certificate, none of
// them have a type of undefined.
if (certificates.size() == 0) {
certificates.add(certificate);
return;
}
if (certificates.size() == 1 &&
certificates.iterator().next().getType() == SSLHostConfigCertificate.Type.UNDEFINED ||
certificate.getType() == SSLHostConfigCertificate.Type.UNDEFINED) {
// Invalid config
throw new IllegalArgumentException(sm.getString("sslHostConfig.certificate.notype"));
}
certificates.add(certificate);
}
public OpenSSLConf getOpenSslConf() {
return openSslConf;
}
public void setOpenSslConf(OpenSSLConf conf) {
if (conf == null) {
throw new IllegalArgumentException(sm.getString("sslHostConfig.opensslconf.null"));
} else if (openSslConf != null) {
throw new IllegalArgumentException(sm.getString("sslHostConfig.opensslconf.alreadySet"));
}
setProperty("<OpenSSLConf>", Type.OPENSSL);
openSslConf = conf;
}
public Set<SSLHostConfigCertificate> getCertificates() {
return getCertificates(false);
}
public Set<SSLHostConfigCertificate> getCertificates(boolean createDefaultIfEmpty) {
if (certificates.size() == 0 && createDefaultIfEmpty) {
registerDefaultCertificate();
}
return certificates;
}
// ----------------------------------------- Common configuration properties
// TODO: This certificate setter can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateKeyPassword() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyPassword();
}
public void setCertificateKeyPassword(String certificateKeyPassword) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyPassword(certificateKeyPassword);
}
public void setCertificateRevocationListFile(String certificateRevocationListFile) {
this.certificateRevocationListFile = certificateRevocationListFile;
}
public String getCertificateRevocationListFile() {
return certificateRevocationListFile;
}
public void setCertificateVerification(String certificateVerification) {
try {
this.certificateVerification =
CertificateVerification.fromString(certificateVerification);
} catch (IllegalArgumentException iae) {
// If the specified value is not recognised, default to the
// strictest possible option.
this.certificateVerification = CertificateVerification.REQUIRED;
throw iae;
}
}
public CertificateVerification getCertificateVerification() {
return certificateVerification;
}
public void setCertificateVerificationAsString(String certificateVerification) {
setCertificateVerification(certificateVerification);
}
public String getCertificateVerificationAsString() {
return certificateVerification.toString();
}
public void setCertificateVerificationDepth(int certificateVerificationDepth) {
this.certificateVerificationDepth = certificateVerificationDepth;
certificateVerificationDepthConfigured = true;
}
public int getCertificateVerificationDepth() {
return certificateVerificationDepth;
}
public boolean isCertificateVerificationDepthConfigured() {
return certificateVerificationDepthConfigured;
}
/**
* Set the new cipher configuration. Note: Regardless of the format used to
* set the configuration, it is always stored in OpenSSL format.
*
* @param ciphersList The new cipher configuration in OpenSSL or JSSE format
*/
public void setCiphers(String ciphersList) {
// Ciphers is stored in OpenSSL format. Convert the provided value if
// necessary.
if (ciphersList != null && !ciphersList.contains(":")) {
StringBuilder sb = new StringBuilder();
// Not obviously in OpenSSL format. May be a single OpenSSL or JSSE
// cipher name. May be a comma separated list of cipher names
String ciphers[] = ciphersList.split(",");
for (String cipher : ciphers) {
String trimmed = cipher.trim();
if (trimmed.length() > 0) {
String openSSLName = OpenSSLCipherConfigurationParser.jsseToOpenSSL(trimmed);
if (openSSLName == null) {
// Not a JSSE name. Maybe an OpenSSL name or alias
openSSLName = trimmed;
}
if (sb.length() > 0) {
sb.append(':');
}
sb.append(openSSLName);
}
}
this.ciphers = sb.toString();
} else {
this.ciphers = ciphersList;
}
this.cipherList = null;
this.jsseCipherNames = null;
}
/**
* @return An OpenSSL cipher string for the current configuration.
*/
public String getCiphers() {
return ciphers;
}
public LinkedHashSet<Cipher> getCipherList() {
if (cipherList == null) {
cipherList = OpenSSLCipherConfigurationParser.parse(ciphers);
}
return cipherList;
}
/**
* Obtain the list of JSSE cipher names for the current configuration.
* Ciphers included in the configuration but not supported by JSSE will be
* excluded from this list.
*
* @return A list of the JSSE cipher names
*/
public List<String> getJsseCipherNames() {
if (jsseCipherNames == null) {
jsseCipherNames = OpenSSLCipherConfigurationParser.convertForJSSE(getCipherList());
}
return jsseCipherNames;
}
public void setHonorCipherOrder(boolean honorCipherOrder) {
this.honorCipherOrder = honorCipherOrder;
}
public boolean getHonorCipherOrder() {
return honorCipherOrder;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getHostName() {
return hostName;
}
public void setProtocols(String input) {
protocols.clear();
explicitlyRequestedProtocols.clear();
// List of protocol names, separated by ",", "+" or "-".
// Semantics is adding ("+") or removing ("-") from left
// to right, starting with an empty protocol set.
// Tokens are individual protocol names or "all" for a
// default set of supported protocols.
// Separator "," is only kept for compatibility and has the
// same semantics as "+", except that it warns about a potentially
// missing "+" or "-".
// Split using a positive lookahead to keep the separator in
// the capture so we can check which case it is.
for (String value: input.split("(?=[-+,])")) {
String trimmed = value.trim();
// Ignore token which only consists of prefix character
if (trimmed.length() > 1) {
if (trimmed.charAt(0) == '+') {
trimmed = trimmed.substring(1).trim();
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.addAll(SSL_PROTO_ALL_SET);
} else {
protocols.add(trimmed);
explicitlyRequestedProtocols.add(trimmed);
}
} else if (trimmed.charAt(0) == '-') {
trimmed = trimmed.substring(1).trim();
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.removeAll(SSL_PROTO_ALL_SET);
} else {
protocols.remove(trimmed);
explicitlyRequestedProtocols.remove(trimmed);
}
} else {
if (trimmed.charAt(0) == ',') {
trimmed = trimmed.substring(1).trim();
}
if (!protocols.isEmpty()) {
log.warn(sm.getString("sslHostConfig.prefix_missing",
trimmed, getHostName()));
}
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.addAll(SSL_PROTO_ALL_SET);
} else {
protocols.add(trimmed);
explicitlyRequestedProtocols.add(trimmed);
}
}
}
}
}
public Set<String> getProtocols() {
return protocols;
}
boolean isExplicitlyRequestedProtocol(String protocol) {
return explicitlyRequestedProtocols.contains(protocol);
}
// ---------------------------------- JSSE specific configuration properties
// TODO: These certificate setters can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateKeyAlias() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyAlias();
}
public void setCertificateKeyAlias(String certificateKeyAlias) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyAlias(certificateKeyAlias);
}
public String getCertificateKeystoreFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreFile();
}
public void setCertificateKeystoreFile(String certificateKeystoreFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreFile(certificateKeystoreFile);
}
public String getCertificateKeystorePassword() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystorePassword();
}
public void setCertificateKeystorePassword(String certificateKeystorePassword) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystorePassword(certificateKeystorePassword);
}
public String getCertificateKeystoreProvider() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreProvider();
}
public void setCertificateKeystoreProvider(String certificateKeystoreProvider) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreProvider(certificateKeystoreProvider);
}
public String getCertificateKeystoreType() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreType();
}
public void setCertificateKeystoreType(String certificateKeystoreType) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreType(certificateKeystoreType);
}
public void setKeyManagerAlgorithm(String keyManagerAlgorithm) {
setProperty("keyManagerAlgorithm", Type.JSSE);
this.keyManagerAlgorithm = keyManagerAlgorithm;
}
public String getKeyManagerAlgorithm() {
return keyManagerAlgorithm;
}
public void setRevocationEnabled(boolean revocationEnabled) {
setProperty("revocationEnabled", Type.JSSE);
this.revocationEnabled = revocationEnabled;
}
public boolean getRevocationEnabled() {
return revocationEnabled;
}
public void setSessionCacheSize(int sessionCacheSize) {
setProperty("sessionCacheSize", Type.JSSE);
this.sessionCacheSize = sessionCacheSize;
}
public int getSessionCacheSize() {
return sessionCacheSize;
}
public void setSessionTimeout(int sessionTimeout) {
setProperty("sessionTimeout", Type.JSSE);
this.sessionTimeout = sessionTimeout;
}
public int getSessionTimeout() {
return sessionTimeout;
}
public void setSslProtocol(String sslProtocol) {
setProperty("sslProtocol", Type.JSSE);
this.sslProtocol = sslProtocol;
}
public String getSslProtocol() {
return sslProtocol;
}
public void setTrustManagerClassName(String trustManagerClassName) {
setProperty("trustManagerClassName", Type.JSSE);
this.trustManagerClassName = trustManagerClassName;
}
public String getTrustManagerClassName() {
return trustManagerClassName;
}
public void setTruststoreAlgorithm(String truststoreAlgorithm) {
setProperty("truststoreAlgorithm", Type.JSSE);
this.truststoreAlgorithm = truststoreAlgorithm;
}
public String getTruststoreAlgorithm() {
return truststoreAlgorithm;
}
public void setTruststoreFile(String truststoreFile) {
setProperty("truststoreFile", Type.JSSE);
this.truststoreFile = truststoreFile;
}
public String getTruststoreFile() {
return truststoreFile;
}
public void setTruststorePassword(String truststorePassword) {
setProperty("truststorePassword", Type.JSSE);
this.truststorePassword = truststorePassword;
}
public String getTruststorePassword() {
return truststorePassword;
}
public void setTruststoreProvider(String truststoreProvider) {
setProperty("truststoreProvider", Type.JSSE);
this.truststoreProvider = truststoreProvider;
}
public String getTruststoreProvider() {
if (truststoreProvider == null) {
Set<SSLHostConfigCertificate> certificates = getCertificates();
if (certificates.size() == 1) {
return certificates.iterator().next().getCertificateKeystoreProvider();
}
return SSLHostConfigCertificate.DEFAULT_KEYSTORE_PROVIDER;
} else {
return truststoreProvider;
}
}
public void setTruststoreType(String truststoreType) {
setProperty("truststoreType", Type.JSSE);
this.truststoreType = truststoreType;
}
public String getTruststoreType() {
if (truststoreType == null) {
Set<SSLHostConfigCertificate> certificates = getCertificates();
if (certificates.size() == 1) {
String keystoreType = certificates.iterator().next().getCertificateKeystoreType();
// Don't use keystore type as the default if we know it is not
// going to be used as a trust store type
if (!"PKCS12".equalsIgnoreCase(keystoreType)) {
return keystoreType;
}
}
return SSLHostConfigCertificate.DEFAULT_KEYSTORE_TYPE;
} else {
return truststoreType;
}
}
public void setTrustStore(KeyStore truststore) {
this.truststore = truststore;
}
public KeyStore getTruststore() throws IOException {
KeyStore result = truststore;
if (result == null) {
if (truststoreFile != null){
try {
result = SSLUtilBase.getStore(getTruststoreType(), getTruststoreProvider(),
getTruststoreFile(), getTruststorePassword());
} catch (IOException ioe) {
Throwable cause = ioe.getCause();
if (cause instanceof UnrecoverableKeyException) {
// Log a warning we had a password issue
log.warn(sm.getString("jsse.invalid_truststore_password"),
cause);
// Re-try
result = SSLUtilBase.getStore(getTruststoreType(), getTruststoreProvider(),
getTruststoreFile(), null);
} else {
// Something else went wrong - re-throw
throw ioe;
}
}
}
}
return result;
}
// ------------------------------- OpenSSL specific configuration properties
// TODO: These certificate setters can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateChainFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateChainFile();
}
public void setCertificateChainFile(String certificateChainFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateChainFile(certificateChainFile);
}
public String getCertificateFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateFile();
}
public void setCertificateFile(String certificateFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateFile(certificateFile);
}
public String getCertificateKeyFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyFile();
}
public void setCertificateKeyFile(String certificateKeyFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyFile(certificateKeyFile);
}
public void setCertificateRevocationListPath(String certificateRevocationListPath) {
setProperty("certificateRevocationListPath", Type.OPENSSL);
this.certificateRevocationListPath = certificateRevocationListPath;
}
public String getCertificateRevocationListPath() {
return certificateRevocationListPath;
}
public void setCaCertificateFile(String caCertificateFile) {
setProperty("caCertificateFile", Type.OPENSSL);
this.caCertificateFile = caCertificateFile;
}
public String getCaCertificateFile() {
return caCertificateFile;
}
public void setCaCertificatePath(String caCertificatePath) {
setProperty("caCertificatePath", Type.OPENSSL);
this.caCertificatePath = caCertificatePath;
}
public String getCaCertificatePath() {
return caCertificatePath;
}
public void setDisableCompression(boolean disableCompression) {
setProperty("disableCompression", Type.OPENSSL);
this.disableCompression = disableCompression;
}
public boolean getDisableCompression() {
return disableCompression;
}
public void setDisableSessionTickets(boolean disableSessionTickets) {
setProperty("disableSessionTickets", Type.OPENSSL);
this.disableSessionTickets = disableSessionTickets;
}
public boolean getDisableSessionTickets() {
return disableSessionTickets;
}
public void setInsecureRenegotiation(boolean insecureRenegotiation) {
setProperty("insecureRenegotiation", Type.OPENSSL);
this.insecureRenegotiation = insecureRenegotiation;
}
public boolean getInsecureRenegotiation() {
return insecureRenegotiation;
}
// --------------------------------------------------------- Support methods
public static String adjustRelativePath(String path) throws FileNotFoundException {
// Empty or null path can't point to anything useful. The assumption is
// that the value is deliberately empty / null so leave it that way.
if (path == null || path.length() == 0) {
return path;
}
String newPath = path;
File f = new File(newPath);
if ( !f.isAbsolute()) {
newPath = System.getProperty(Constants.CATALINA_BASE_PROP) + File.separator + newPath;
f = new File(newPath);
}
if (!f.exists()) {
throw new FileNotFoundException(sm.getString("sslHostConfig.fileNotFound", newPath));
}
return newPath;
}
// ----------------------------------------------------------- Inner classes
public enum Type {
JSSE,
OPENSSL,
EITHER
}
public enum CertificateVerification {
NONE,
OPTIONAL_NO_CA,
OPTIONAL,
REQUIRED;
public static CertificateVerification fromString(String value) {
if ("true".equalsIgnoreCase(value) ||
"yes".equalsIgnoreCase(value) ||
"require".equalsIgnoreCase(value) ||
"required".equalsIgnoreCase(value)) {
return REQUIRED;
} else if ("optional".equalsIgnoreCase(value) ||
"want".equalsIgnoreCase(value)) {
return OPTIONAL;
} else if ("optionalNoCA".equalsIgnoreCase(value) ||
"optional_no_ca".equalsIgnoreCase(value)) {
return OPTIONAL_NO_CA;
} else if ("false".equalsIgnoreCase(value) ||
"no".equalsIgnoreCase(value) ||
"none".equalsIgnoreCase(value)) {
return NONE;
} else {
// Could be a typo. Don't default to NONE since that is not
// secure. Force user to fix config. Could default to REQUIRED
// instead.
throw new IllegalArgumentException(
sm.getString("sslHostConfig.certificateVerificationInvalid", value));
}
}
}
}
| java/org/apache/tomcat/util/net/SSLHostConfig.java | /*
* 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.tomcat.util.net;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.security.KeyStore;
import java.security.UnrecoverableKeyException;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.ObjectName;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.net.openssl.OpenSSLConf;
import org.apache.tomcat.util.net.openssl.ciphers.Cipher;
import org.apache.tomcat.util.net.openssl.ciphers.OpenSSLCipherConfigurationParser;
import org.apache.tomcat.util.res.StringManager;
/**
* Represents the TLS configuration for a virtual host.
*/
public class SSLHostConfig implements Serializable {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(SSLHostConfig.class);
private static final StringManager sm = StringManager.getManager(SSLHostConfig.class);
protected static final String DEFAULT_SSL_HOST_NAME = "_default_";
protected static final Set<String> SSL_PROTO_ALL_SET = new HashSet<>();
static {
/* Default used if protocols is not configured, also used if
* protocols="All"
*/
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_SSLv2Hello);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_1);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_2);
SSL_PROTO_ALL_SET.add(Constants.SSL_PROTO_TLSv1_3);
}
private Type configType = null;
private Type currentConfigType = null;
private Map<Type, Set<String>> configuredProperties = new EnumMap<>(Type.class);
private String hostName = DEFAULT_SSL_HOST_NAME;
private transient Long openSslConfContext = Long.valueOf(0);
// OpenSSL can handle multiple certs in a single config so the reference to
// the context is here at the virtual host level. JSSE can't so the
// reference is held on the certificate.
private transient Long openSslContext = Long.valueOf(0);
// Configuration properties
// Internal
private String[] enabledCiphers;
private String[] enabledProtocols;
private ObjectName oname;
// Need to know if TLS 1.3 has been explicitly requested as a warning needs
// to generated if it is explicitly requested for a JVM that does not
// support it. Uses a set so it is extensible for TLS 1.4 etc.
private Set<String> explicitlyRequestedProtocols = new HashSet<>();
// Nested
private SSLHostConfigCertificate defaultCertificate = null;
private Set<SSLHostConfigCertificate> certificates = new HashSet<>(4);
// Common
private String certificateRevocationListFile;
private CertificateVerification certificateVerification = CertificateVerification.NONE;
private int certificateVerificationDepth = 10;
// Used to track if certificateVerificationDepth has been explicitly set
private boolean certificateVerificationDepthConfigured = false;
private String ciphers = "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!kRSA";
private LinkedHashSet<Cipher> cipherList = null;
private List<String> jsseCipherNames = null;
private boolean honorCipherOrder = false;
private Set<String> protocols = new HashSet<>();
// JSSE
private String keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
private boolean revocationEnabled = false;
private int sessionCacheSize = 0;
private int sessionTimeout = 86400;
private String sslProtocol = Constants.SSL_PROTO_TLS;
private String trustManagerClassName;
private String truststoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
private String truststoreFile = System.getProperty("javax.net.ssl.trustStore");
private String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
private String truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
private String truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
private transient KeyStore truststore = null;
// OpenSSL
private String certificateRevocationListPath;
private String caCertificateFile;
private String caCertificatePath;
private boolean disableCompression = true;
private boolean disableSessionTickets = false;
private boolean insecureRenegotiation = false;
private OpenSSLConf openSslConf = null;
public SSLHostConfig() {
// Set defaults that can't be (easily) set when defining the fields.
setProtocols(Constants.SSL_PROTO_ALL);
}
public Long getOpenSslConfContext() {
return openSslConfContext;
}
public void setOpenSslConfContext(Long openSslConfContext) {
this.openSslConfContext = openSslConfContext;
}
public Long getOpenSslContext() {
return openSslContext;
}
public void setOpenSslContext(Long openSslContext) {
this.openSslContext = openSslContext;
}
// Expose in String form for JMX
public String getConfigType() {
return configType.name();
}
public void setConfigType(Type configType) {
this.configType = configType;
if (configType == Type.EITHER) {
if (configuredProperties.remove(Type.JSSE) == null) {
configuredProperties.remove(Type.OPENSSL);
}
} else {
configuredProperties.remove(configType);
}
for (Map.Entry<Type,Set<String>> entry : configuredProperties.entrySet()) {
for (String property : entry.getValue()) {
log.warn(sm.getString("sslHostConfig.mismatch",
property, getHostName(), entry.getKey(), configType));
}
}
}
void setProperty(String name, Type configType) {
if (this.configType == null) {
Set<String> properties = configuredProperties.get(configType);
if (properties == null) {
properties = new HashSet<>();
configuredProperties.put(configType, properties);
}
properties.add(name);
} else if (this.configType == Type.EITHER) {
if (currentConfigType == null) {
currentConfigType = configType;
} else if (currentConfigType != configType) {
log.warn(sm.getString("sslHostConfig.mismatch",
name, getHostName(), configType, currentConfigType));
}
} else {
if (configType != this.configType) {
log.warn(sm.getString("sslHostConfig.mismatch",
name, getHostName(), configType, this.configType));
}
}
}
// ----------------------------------------------------- Internal properties
/**
* @see SSLUtil#getEnabledProtocols()
*
* @return The protocols enabled for this TLS virtual host
*/
public String[] getEnabledProtocols() {
return enabledProtocols;
}
public void setEnabledProtocols(String[] enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
/**
* @see SSLUtil#getEnabledCiphers()
*
* @return The ciphers enabled for this TLS virtual host
*/
public String[] getEnabledCiphers() {
return enabledCiphers;
}
public void setEnabledCiphers(String[] enabledCiphers) {
this.enabledCiphers = enabledCiphers;
}
public ObjectName getObjectName() {
return oname;
}
public void setObjectName(ObjectName oname) {
this.oname = oname;
}
// ------------------------------------------- Nested configuration elements
private void registerDefaultCertificate() {
if (defaultCertificate == null) {
defaultCertificate = new SSLHostConfigCertificate(
this, SSLHostConfigCertificate.Type.UNDEFINED);
certificates.add(defaultCertificate);
}
}
public void addCertificate(SSLHostConfigCertificate certificate) {
// Need to make sure that if there is more than one certificate, none of
// them have a type of undefined.
if (certificates.size() == 0) {
certificates.add(certificate);
return;
}
if (certificates.size() == 1 &&
certificates.iterator().next().getType() == SSLHostConfigCertificate.Type.UNDEFINED ||
certificate.getType() == SSLHostConfigCertificate.Type.UNDEFINED) {
// Invalid config
throw new IllegalArgumentException(sm.getString("sslHostConfig.certificate.notype"));
}
certificates.add(certificate);
}
public OpenSSLConf getOpenSslConf() {
return openSslConf;
}
public void setOpenSslConf(OpenSSLConf conf) {
if (conf == null) {
throw new IllegalArgumentException(sm.getString("sslHostConfig.opensslconf.null"));
} else if (openSslConf != null) {
throw new IllegalArgumentException(sm.getString("sslHostConfig.opensslconf.alreadySet"));
}
setProperty("<OpenSSLConf>", Type.OPENSSL);
openSslConf = conf;
}
public Set<SSLHostConfigCertificate> getCertificates() {
return getCertificates(false);
}
public Set<SSLHostConfigCertificate> getCertificates(boolean createDefaultIfEmpty) {
if (certificates.size() == 0 && createDefaultIfEmpty) {
registerDefaultCertificate();
}
return certificates;
}
// ----------------------------------------- Common configuration properties
// TODO: This certificate setter can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateKeyPassword() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyPassword();
}
public void setCertificateKeyPassword(String certificateKeyPassword) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyPassword(certificateKeyPassword);
}
public void setCertificateRevocationListFile(String certificateRevocationListFile) {
this.certificateRevocationListFile = certificateRevocationListFile;
}
public String getCertificateRevocationListFile() {
return certificateRevocationListFile;
}
public void setCertificateVerification(String certificateVerification) {
try {
this.certificateVerification =
CertificateVerification.fromString(certificateVerification);
} catch (IllegalArgumentException iae) {
// If the specified value is not recognised, default to the
// strictest possible option.
this.certificateVerification = CertificateVerification.REQUIRED;
throw iae;
}
}
public CertificateVerification getCertificateVerification() {
return certificateVerification;
}
public void setCertificateVerificationAsString(String certificateVerification) {
setCertificateVerification(certificateVerification);
}
public String getCertificateVerificationAsString() {
return certificateVerification.toString();
}
public void setCertificateVerificationDepth(int certificateVerificationDepth) {
this.certificateVerificationDepth = certificateVerificationDepth;
certificateVerificationDepthConfigured = true;
}
public int getCertificateVerificationDepth() {
return certificateVerificationDepth;
}
public boolean isCertificateVerificationDepthConfigured() {
return certificateVerificationDepthConfigured;
}
/**
* Set the new cipher configuration. Note: Regardless of the format used to
* set the configuration, it is always stored in OpenSSL format.
*
* @param ciphersList The new cipher configuration in OpenSSL or JSSE format
*/
public void setCiphers(String ciphersList) {
// Ciphers is stored in OpenSSL format. Convert the provided value if
// necessary.
if (ciphersList != null && !ciphersList.contains(":")) {
StringBuilder sb = new StringBuilder();
// Not obviously in OpenSSL format. May be a single OpenSSL or JSSE
// cipher name. May be a comma separated list of cipher names
String ciphers[] = ciphersList.split(",");
for (String cipher : ciphers) {
String trimmed = cipher.trim();
if (trimmed.length() > 0) {
String openSSLName = OpenSSLCipherConfigurationParser.jsseToOpenSSL(trimmed);
if (openSSLName == null) {
// Not a JSSE name. Maybe an OpenSSL name or alias
openSSLName = trimmed;
}
if (sb.length() > 0) {
sb.append(':');
}
sb.append(openSSLName);
}
}
this.ciphers = sb.toString();
} else {
this.ciphers = ciphersList;
}
this.cipherList = null;
this.jsseCipherNames = null;
}
/**
* @return An OpenSSL cipher string for the current configuration.
*/
public String getCiphers() {
return ciphers;
}
public LinkedHashSet<Cipher> getCipherList() {
if (cipherList == null) {
cipherList = OpenSSLCipherConfigurationParser.parse(ciphers);
}
return cipherList;
}
/**
* Obtain the list of JSSE cipher names for the current configuration.
* Ciphers included in the configuration but not supported by JSSE will be
* excluded from this list.
*
* @return A list of the JSSE cipher names
*/
public List<String> getJsseCipherNames() {
if (jsseCipherNames == null) {
jsseCipherNames = OpenSSLCipherConfigurationParser.convertForJSSE(getCipherList());
}
return jsseCipherNames;
}
public void setHonorCipherOrder(boolean honorCipherOrder) {
this.honorCipherOrder = honorCipherOrder;
}
public boolean getHonorCipherOrder() {
return honorCipherOrder;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getHostName() {
return hostName;
}
public void setProtocols(String input) {
protocols.clear();
explicitlyRequestedProtocols.clear();
// List of protocol names, separated by ",", "+" or "-".
// Semantics is adding ("+") or removing ("-") from left
// to right, starting with an empty protocol set.
// Tokens are individual protocol names or "all" for a
// default set of supported protocols.
// Separator "," is only kept for compatibility and has the
// same semantics as "+", except that it warns about a potentially
// missing "+" or "-".
// Split using a positive lookahead to keep the separator in
// the capture so we can check which case it is.
for (String value: input.split("(?=[-+,])")) {
String trimmed = value.trim();
// Ignore token which only consists of prefix character
if (trimmed.length() > 1) {
if (trimmed.charAt(0) == '+') {
trimmed = trimmed.substring(1).trim();
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.addAll(SSL_PROTO_ALL_SET);
} else {
protocols.add(trimmed);
explicitlyRequestedProtocols.add(trimmed);
}
} else if (trimmed.charAt(0) == '-') {
trimmed = trimmed.substring(1).trim();
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.removeAll(SSL_PROTO_ALL_SET);
} else {
protocols.remove(trimmed);
explicitlyRequestedProtocols.remove(trimmed);
}
} else {
if (trimmed.charAt(0) == ',') {
trimmed = trimmed.substring(1).trim();
}
if (!protocols.isEmpty()) {
log.warn(sm.getString("sslHostConfig.prefix_missing",
trimmed, getHostName()));
}
if (trimmed.equalsIgnoreCase(Constants.SSL_PROTO_ALL)) {
protocols.addAll(SSL_PROTO_ALL_SET);
} else {
protocols.add(trimmed);
explicitlyRequestedProtocols.add(trimmed);
}
}
}
}
}
public Set<String> getProtocols() {
return protocols;
}
boolean isExplicitlyRequestedProtocol(String protocol) {
return explicitlyRequestedProtocols.contains(protocol);
}
// ---------------------------------- JSSE specific configuration properties
// TODO: These certificate setters can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateKeyAlias() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyAlias();
}
public void setCertificateKeyAlias(String certificateKeyAlias) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyAlias(certificateKeyAlias);
}
public String getCertificateKeystoreFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreFile();
}
public void setCertificateKeystoreFile(String certificateKeystoreFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreFile(certificateKeystoreFile);
}
public String getCertificateKeystorePassword() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystorePassword();
}
public void setCertificateKeystorePassword(String certificateKeystorePassword) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystorePassword(certificateKeystorePassword);
}
public String getCertificateKeystoreProvider() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreProvider();
}
public void setCertificateKeystoreProvider(String certificateKeystoreProvider) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreProvider(certificateKeystoreProvider);
}
public String getCertificateKeystoreType() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeystoreType();
}
public void setCertificateKeystoreType(String certificateKeystoreType) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeystoreType(certificateKeystoreType);
}
public void setKeyManagerAlgorithm(String keyManagerAlgorithm) {
setProperty("keyManagerAlgorithm", Type.JSSE);
this.keyManagerAlgorithm = keyManagerAlgorithm;
}
public String getKeyManagerAlgorithm() {
return keyManagerAlgorithm;
}
public void setRevocationEnabled(boolean revocationEnabled) {
setProperty("revocationEnabled", Type.JSSE);
this.revocationEnabled = revocationEnabled;
}
public boolean getRevocationEnabled() {
return revocationEnabled;
}
public void setSessionCacheSize(int sessionCacheSize) {
setProperty("sessionCacheSize", Type.JSSE);
this.sessionCacheSize = sessionCacheSize;
}
public int getSessionCacheSize() {
return sessionCacheSize;
}
public void setSessionTimeout(int sessionTimeout) {
setProperty("sessionTimeout", Type.JSSE);
this.sessionTimeout = sessionTimeout;
}
public int getSessionTimeout() {
return sessionTimeout;
}
public void setSslProtocol(String sslProtocol) {
setProperty("sslProtocol", Type.JSSE);
this.sslProtocol = sslProtocol;
}
public String getSslProtocol() {
return sslProtocol;
}
public void setTrustManagerClassName(String trustManagerClassName) {
setProperty("trustManagerClassName", Type.JSSE);
this.trustManagerClassName = trustManagerClassName;
}
public String getTrustManagerClassName() {
return trustManagerClassName;
}
public void setTruststoreAlgorithm(String truststoreAlgorithm) {
setProperty("truststoreAlgorithm", Type.JSSE);
this.truststoreAlgorithm = truststoreAlgorithm;
}
public String getTruststoreAlgorithm() {
return truststoreAlgorithm;
}
public void setTruststoreFile(String truststoreFile) {
setProperty("truststoreFile", Type.JSSE);
this.truststoreFile = truststoreFile;
}
public String getTruststoreFile() {
return truststoreFile;
}
public void setTruststorePassword(String truststorePassword) {
setProperty("truststorePassword", Type.JSSE);
this.truststorePassword = truststorePassword;
}
public String getTruststorePassword() {
return truststorePassword;
}
public void setTruststoreProvider(String truststoreProvider) {
setProperty("truststoreProvider", Type.JSSE);
this.truststoreProvider = truststoreProvider;
}
public String getTruststoreProvider() {
if (truststoreProvider == null) {
Set<SSLHostConfigCertificate> certificates = getCertificates();
if (certificates.size() == 1) {
return certificates.iterator().next().getCertificateKeystoreProvider();
}
return SSLHostConfigCertificate.DEFAULT_KEYSTORE_PROVIDER;
} else {
return truststoreProvider;
}
}
public void setTruststoreType(String truststoreType) {
setProperty("truststoreType", Type.JSSE);
this.truststoreType = truststoreType;
}
public String getTruststoreType() {
if (truststoreType == null) {
Set<SSLHostConfigCertificate> certificates = getCertificates();
if (certificates.size() == 1) {
String keystoreType = certificates.iterator().next().getCertificateKeystoreType();
// Don't use keystore type as the default if we know it is not
// going to be used as a trust store type
if (!"PKCS12".equalsIgnoreCase(keystoreType)) {
return keystoreType;
}
}
return SSLHostConfigCertificate.DEFAULT_KEYSTORE_TYPE;
} else {
return truststoreType;
}
}
public void setTrustStore(KeyStore truststore) {
this.truststore = truststore;
}
public KeyStore getTruststore() throws IOException {
KeyStore result = truststore;
if (result == null) {
if (truststoreFile != null){
try {
result = SSLUtilBase.getStore(getTruststoreType(), getTruststoreProvider(),
getTruststoreFile(), getTruststorePassword());
} catch (IOException ioe) {
Throwable cause = ioe.getCause();
if (cause instanceof UnrecoverableKeyException) {
// Log a warning we had a password issue
log.warn(sm.getString("jsse.invalid_truststore_password"),
cause);
// Re-try
result = SSLUtilBase.getStore(getTruststoreType(), getTruststoreProvider(),
getTruststoreFile(), null);
} else {
// Something else went wrong - re-throw
throw ioe;
}
}
}
}
return result;
}
// ------------------------------- OpenSSL specific configuration properties
// TODO: These certificate setters can be removed once it is no longer
// necessary to support the old configuration attributes (Tomcat 10?).
public String getCertificateChainFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateChainFile();
}
public void setCertificateChainFile(String certificateChainFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateChainFile(certificateChainFile);
}
public String getCertificateFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateFile();
}
public void setCertificateFile(String certificateFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateFile(certificateFile);
}
public String getCertificateKeyFile() {
registerDefaultCertificate();
return defaultCertificate.getCertificateKeyFile();
}
public void setCertificateKeyFile(String certificateKeyFile) {
registerDefaultCertificate();
defaultCertificate.setCertificateKeyFile(certificateKeyFile);
}
public void setCertificateRevocationListPath(String certificateRevocationListPath) {
setProperty("certificateRevocationListPath", Type.OPENSSL);
this.certificateRevocationListPath = certificateRevocationListPath;
}
public String getCertificateRevocationListPath() {
return certificateRevocationListPath;
}
public void setCaCertificateFile(String caCertificateFile) {
setProperty("caCertificateFile", Type.OPENSSL);
this.caCertificateFile = caCertificateFile;
}
public String getCaCertificateFile() {
return caCertificateFile;
}
public void setCaCertificatePath(String caCertificatePath) {
setProperty("caCertificatePath", Type.OPENSSL);
this.caCertificatePath = caCertificatePath;
}
public String getCaCertificatePath() {
return caCertificatePath;
}
public void setDisableCompression(boolean disableCompression) {
setProperty("disableCompression", Type.OPENSSL);
this.disableCompression = disableCompression;
}
public boolean getDisableCompression() {
return disableCompression;
}
public void setDisableSessionTickets(boolean disableSessionTickets) {
setProperty("disableSessionTickets", Type.OPENSSL);
this.disableSessionTickets = disableSessionTickets;
}
public boolean getDisableSessionTickets() {
return disableSessionTickets;
}
public void setInsecureRenegotiation(boolean insecureRenegotiation) {
setProperty("insecureRenegotiation", Type.OPENSSL);
this.insecureRenegotiation = insecureRenegotiation;
}
public boolean getInsecureRenegotiation() {
return insecureRenegotiation;
}
// --------------------------------------------------------- Support methods
public static String adjustRelativePath(String path) throws FileNotFoundException {
// Empty or null path can't point to anything useful. The assumption is
// that the value is deliberately empty / null so leave it that way.
if (path == null || path.length() == 0) {
return path;
}
String newPath = path;
File f = new File(newPath);
if ( !f.isAbsolute()) {
newPath = System.getProperty(Constants.CATALINA_BASE_PROP) + File.separator + newPath;
f = new File(newPath);
}
if (!f.exists()) {
throw new FileNotFoundException(sm.getString("sslHostConfig.fileNotFound", newPath));
}
return newPath;
}
// ----------------------------------------------------------- Inner classes
public enum Type {
JSSE,
OPENSSL,
EITHER
}
public enum CertificateVerification {
NONE,
OPTIONAL_NO_CA,
OPTIONAL,
REQUIRED;
public static CertificateVerification fromString(String value) {
if ("true".equalsIgnoreCase(value) ||
"yes".equalsIgnoreCase(value) ||
"require".equalsIgnoreCase(value) ||
"required".equalsIgnoreCase(value)) {
return REQUIRED;
} else if ("optional".equalsIgnoreCase(value) ||
"want".equalsIgnoreCase(value)) {
return OPTIONAL;
} else if ("optionalNoCA".equalsIgnoreCase(value) ||
"optional_no_ca".equalsIgnoreCase(value)) {
return OPTIONAL_NO_CA;
} else if ("false".equalsIgnoreCase(value) ||
"no".equalsIgnoreCase(value) ||
"none".equalsIgnoreCase(value)) {
return NONE;
} else {
// Could be a typo. Don't default to NONE since that is not
// secure. Force user to fix config. Could default to REQUIRED
// instead.
throw new IllegalArgumentException(
sm.getString("sslHostConfig.certificateVerificationInvalid", value));
}
}
}
}
| Ensure consistent ordering of certificates
Using a HashSet meant that certificates were not guaranteed to be
returned in the order they were added. This caused inconsistent
behaviour in the unit tests.
| java/org/apache/tomcat/util/net/SSLHostConfig.java | Ensure consistent ordering of certificates | <ide><path>ava/org/apache/tomcat/util/net/SSLHostConfig.java
<ide> private Set<String> explicitlyRequestedProtocols = new HashSet<>();
<ide> // Nested
<ide> private SSLHostConfigCertificate defaultCertificate = null;
<del> private Set<SSLHostConfigCertificate> certificates = new HashSet<>(4);
<add> private Set<SSLHostConfigCertificate> certificates = new LinkedHashSet<>(4);
<ide> // Common
<ide> private String certificateRevocationListFile;
<ide> private CertificateVerification certificateVerification = CertificateVerification.NONE; |
|
Java | agpl-3.0 | 12c7ca58d726cb208175bc37089cb73cf2f0d90f | 0 | geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt2 | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt.client;
import com.google.gwt.i18n.client.LocaleInfo;
import org.geomajas.global.Api;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* Global settings for the Geomajas GWT face.
* </p>
*
* @author Pieter De Graef
* @since 1.6.0
*/
@Api(allMethods = true)
public final class Geomajas {
private Geomajas() {
}
/** Returns the current version of Geomajas as a string. */
public static String getVersion() {
return "1.9.0-SNAPSHOT";
}
/**
* Returns a list of locales that can be used in this version of Geomajas. The default is english, and 'native'
* means that your browsers locale should be used (if supported - default otherwise).
*/
public static Map<String, String> getSupportedLocales() {
Map<String, String> locales = new HashMap<String, String>();
for (String localeName : LocaleInfo.getAvailableLocaleNames()) {
String displayName = LocaleInfo.getLocaleNativeDisplayName(localeName);
locales.put(localeName, displayName);
}
return locales;
}
/**
* Return the base directory for the web application.
*
* @return
*/
public static native String getIsomorphicDir()
/*-{
return $wnd.isomorphicDir;
}-*/;
} | face/geomajas-face-gwt/client/src/main/java/org/geomajas/gwt/client/Geomajas.java | /*
* This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
*
* Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
*
* The program is available in open source according to the GNU Affero
* General Public License. All contributions in this program are covered
* by the Geomajas Contributors License Agreement. For full licensing
* details, see LICENSE.txt in the project root.
*/
package org.geomajas.gwt.client;
import com.google.gwt.i18n.client.LocaleInfo;
import org.geomajas.global.Api;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* Global settings for the Geomajas GWT face.
* </p>
*
* @author Pieter De Graef
* @since 1.6.0
*/
@Api(allMethods = true)
public final class Geomajas {
private Geomajas() {
}
/** Returns the current version of Geomajas as a string. */
public static String getVersion() {
return "1.8.0";
}
/**
* Returns a list of locales that can be used in this version of Geomajas. The default is english, and 'native'
* means that your browsers locale should be used (if supported - default otherwise).
*/
public static Map<String, String> getSupportedLocales() {
Map<String, String> locales = new HashMap<String, String>();
for (String localeName : LocaleInfo.getAvailableLocaleNames()) {
String displayName = LocaleInfo.getLocaleNativeDisplayName(localeName);
locales.put(localeName, displayName);
}
return locales;
}
/**
* Return the base directory for the web application.
*
* @return
*/
public static native String getIsomorphicDir()
/*-{
return $wnd.isomorphicDir;
}-*/;
} | update version cfr 1.8.0 being released
| face/geomajas-face-gwt/client/src/main/java/org/geomajas/gwt/client/Geomajas.java | update version cfr 1.8.0 being released | <ide><path>ace/geomajas-face-gwt/client/src/main/java/org/geomajas/gwt/client/Geomajas.java
<ide>
<ide> /** Returns the current version of Geomajas as a string. */
<ide> public static String getVersion() {
<del> return "1.8.0";
<add> return "1.9.0-SNAPSHOT";
<ide> }
<ide>
<ide> /** |
|
Java | bsd-3-clause | 38fc602c5f2e9965f92b1754be2b21c6e2de77da | 0 | mattunderscorechampion/tree-root | /* Copyright © 2014 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of mattunderscore.com 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 MATTHEW CHAMPION 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 com.mattunderscore.trees.internal;
import com.mattunderscore.trees.Trees;
import com.mattunderscore.trees.common.TreesImpl;
import com.mattunderscore.trees.construction.BottomUpTreeBuilder;
import com.mattunderscore.trees.construction.TopDownTreeRootBuilder;
import com.mattunderscore.trees.construction.TopDownTreeRootBuilder.TopDownTreeBuilder;
import com.mattunderscore.trees.internal.pathcopy.backref.PathCopyTree;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.mutable.MutableTree;
import com.mattunderscore.trees.traversal.TreeIteratorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
/**
* @author matt on 04/11/14.
*/
public class PathCopyTreeTest {
private static TreeIteratorFactory iterators;
private static BottomUpTreeBuilder<String> builder;
private static TopDownTreeRootBuilder<String> topDownBuilder;
@BeforeClass
public static void setUp() {
final Trees trees = new TreesImpl();
iterators = trees.treeIterators();
builder = trees.treeBuilders().bottomUpBuilder();
topDownBuilder = trees.treeBuilders().topDownBuilder();
}
@Test
public void mutateTest() {
final MutableTree<String, MutableNode<String>> tree = builder.build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
final MutableNode<String> root = tree.setRoot("root");
assertFalse(iterator0.hasNext());
assertEquals(0, root.getChildren().size());
final Iterator<String> iterator1 = iterators.inOrderElementsIterator(tree);
root.addChild("child");
assertEquals(0, root.getChildren().size());
assertNotEquals(root, tree.getRoot());
assertEquals(1, tree.getRoot().getChildren().size());
assertTrue(iterator1.hasNext());
assertEquals("root", iterator1.next());
assertFalse(iterator1.hasNext());
final Iterator<String> iterator2 = iterators.inOrderElementsIterator(tree);
final MutableNode<String> newRoot = tree.setRoot("newRoot");
assertTrue(iterator2.hasNext());
assertEquals("child", iterator2.next());
assertEquals("root", iterator2.next());
assertFalse(iterator2.hasNext());
final MutableNode<String> newChild = newRoot.addChild("newChild");
final Iterator<String> iterator3 = iterators.inOrderElementsIterator(tree);
assertTrue(tree.getRoot().removeChild(newChild));
final Iterator<String> iterator4 = iterators.inOrderElementsIterator(tree);
assertTrue(iterator3.hasNext());
assertEquals("newChild", iterator3.next());
assertEquals("newRoot", iterator3.next());
assertFalse(iterator3.hasNext());
assertTrue(iterator4.hasNext());
assertEquals("newRoot", iterator4.next());
assertFalse(iterator4.hasNext());
assertFalse(newRoot.removeChild(root));
}
@Test
public void topDownBuilder() {
final TopDownTreeBuilder<String> builder = topDownBuilder.root("root");
builder.addChild("left");
builder.addChild("right");
final PathCopyTree<String> tree = builder.build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
assertEquals("left", iterator0.next());
assertEquals("root", iterator0.next());
assertEquals("right", iterator0.next());
assertFalse(iterator0.hasNext());
}
@Test
public void bottomUpBuilder() {
final PathCopyTree<String> tree = builder.create(
"root",
builder.create("left"),
builder.create("right")).build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
assertEquals("left", iterator0.next());
assertEquals("root", iterator0.next());
assertEquals("right", iterator0.next());
assertFalse(iterator0.hasNext());
}
@Test
public void mutateOldView() {
final PathCopyTree<String> tree = builder.create(
"root",
builder.create("left"),
builder.create("right",
builder.create("a"))).build(PathCopyTree.class);
final MutableNode<String> root = tree.getRoot();
final Iterator<? extends MutableNode<String>> iterator0 = root.getChildren().iterator();
final MutableNode<String> left = iterator0.next();
final MutableNode<String> right = iterator0.next();
final Iterator<? extends MutableNode<String>> iterator1 = right.getChildren().iterator();
final MutableNode<String> a = iterator1.next();
assertTrue(root.removeChild(right));
assertFalse(right.removeChild(a));
}
}
| trees-internal/src/test/java/com/mattunderscore/trees/internal/PathCopyTreeTest.java | /* Copyright © 2014 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of mattunderscore.com 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 MATTHEW CHAMPION 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 com.mattunderscore.trees.internal;
import com.mattunderscore.trees.Trees;
import com.mattunderscore.trees.common.TreesImpl;
import com.mattunderscore.trees.construction.BottomUpTreeBuilder;
import com.mattunderscore.trees.construction.TopDownTreeRootBuilder;
import com.mattunderscore.trees.construction.TopDownTreeRootBuilder.TopDownTreeBuilder;
import com.mattunderscore.trees.internal.pathcopy.backref.PathCopyTree;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.mutable.MutableTree;
import com.mattunderscore.trees.traversal.TreeIteratorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Iterator;
import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
/**
* @author matt on 04/11/14.
*/
public class PathCopyTreeTest {
private static TreeIteratorFactory iterators;
private static BottomUpTreeBuilder<String> builder;
private static TopDownTreeRootBuilder<String> topDownBuilder;
@BeforeClass
public static void setUp() {
final Trees trees = new TreesImpl();
iterators = trees.treeIterators();
builder = trees.treeBuilders().bottomUpBuilder();
topDownBuilder = trees.treeBuilders().topDownBuilder();
}
@Test
public void mutateTest() {
final MutableTree<String, MutableNode<String>> tree = builder.build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
final MutableNode<String> root = tree.setRoot("root");
assertFalse(iterator0.hasNext());
assertEquals(0, root.getChildren().size());
final Iterator<String> iterator1 = iterators.inOrderElementsIterator(tree);
root.addChild("child");
assertEquals(0, root.getChildren().size());
assertNotEquals(root, tree.getRoot());
assertEquals(1, tree.getRoot().getChildren().size());
assertTrue(iterator1.hasNext());
assertEquals("root", iterator1.next());
assertFalse(iterator1.hasNext());
final Iterator<String> iterator2 = iterators.inOrderElementsIterator(tree);
final MutableNode<String> newRoot = tree.setRoot("newRoot");
assertTrue(iterator2.hasNext());
assertEquals("child", iterator2.next());
assertEquals("root", iterator2.next());
assertFalse(iterator2.hasNext());
final MutableNode<String> newChild = newRoot.addChild("newChild");
final Iterator<String> iterator3 = iterators.inOrderElementsIterator(tree);
assertTrue(tree.getRoot().removeChild(newChild));
final Iterator<String> iterator4 = iterators.inOrderElementsIterator(tree);
assertTrue(iterator3.hasNext());
assertEquals("newChild", iterator3.next());
assertEquals("newRoot", iterator3.next());
assertFalse(iterator3.hasNext());
assertTrue(iterator4.hasNext());
assertEquals("newRoot", iterator4.next());
assertFalse(iterator4.hasNext());
assertFalse(newRoot.removeChild(root));
}
@Test
public void topDownBuilder() {
final TopDownTreeBuilder<String> builder = topDownBuilder.root("root");
builder.addChild("left");
builder.addChild("right");
final PathCopyTree<String> tree = builder.build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
assertEquals("left", iterator0.next());
assertEquals("root", iterator0.next());
assertEquals("right", iterator0.next());
assertFalse(iterator0.hasNext());
}
@Test
public void bottomUpBuilder() {
final PathCopyTree<String> tree = builder.create(
"root",
builder.create("left"),
builder.create("right")).build(PathCopyTree.class);
final Iterator<String> iterator0 = iterators.inOrderElementsIterator(tree);
assertEquals("left", iterator0.next());
assertEquals("root", iterator0.next());
assertEquals("right", iterator0.next());
assertFalse(iterator0.hasNext());
}
}
| Added additional testing
| trees-internal/src/test/java/com/mattunderscore/trees/internal/PathCopyTreeTest.java | Added additional testing | <ide><path>rees-internal/src/test/java/com/mattunderscore/trees/internal/PathCopyTreeTest.java
<ide> assertEquals("right", iterator0.next());
<ide> assertFalse(iterator0.hasNext());
<ide> }
<add>
<add> @Test
<add> public void mutateOldView() {
<add> final PathCopyTree<String> tree = builder.create(
<add> "root",
<add> builder.create("left"),
<add> builder.create("right",
<add> builder.create("a"))).build(PathCopyTree.class);
<add> final MutableNode<String> root = tree.getRoot();
<add> final Iterator<? extends MutableNode<String>> iterator0 = root.getChildren().iterator();
<add> final MutableNode<String> left = iterator0.next();
<add> final MutableNode<String> right = iterator0.next();
<add> final Iterator<? extends MutableNode<String>> iterator1 = right.getChildren().iterator();
<add> final MutableNode<String> a = iterator1.next();
<add>
<add> assertTrue(root.removeChild(right));
<add> assertFalse(right.removeChild(a));
<add> }
<ide> } |
|
Java | apache-2.0 | d92bcac0740985999d7a501a0529136aba22667b | 0 | kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox | /*
* 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.pdfbox.pdfparser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.PushBackInputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdmodel.fdf.FDFDocument;
public class FDFParser extends COSParser
{
private static final Log LOG = LogFactory.getLog(FDFParser.class);
private final RandomAccessBufferedFileInputStream raStream;
private File tempPDFFile;
/**
* Constructs parser for given file using memory buffer.
*
* @param filename the filename of the pdf to be parsed
*
* @throws IOException If something went wrong.
*/
public FDFParser(String filename) throws IOException
{
this(new File(filename));
}
/**
* Constructs parser for given file using given buffer for temporary
* storage.
*
* @param file the pdf to be parsed
*
* @throws IOException If something went wrong.
*/
public FDFParser(File file) throws IOException
{
fileLen = file.length();
raStream = new RandomAccessBufferedFileInputStream(file);
init();
}
/**
* Constructor.
*
* @param input input stream representing the pdf.
* @throws IOException If something went wrong.
*/
public FDFParser(InputStream input) throws IOException
{
tempPDFFile = createTmpFile(input);
fileLen = tempPDFFile.length();
raStream = new RandomAccessBufferedFileInputStream(tempPDFFile);
init();
}
private void init() throws IOException
{
String eofLookupRangeStr = System.getProperty(SYSPROP_EOFLOOKUPRANGE);
if (eofLookupRangeStr != null)
{
try
{
setEOFLookupRange(Integer.parseInt(eofLookupRangeStr));
}
catch (NumberFormatException nfe)
{
LOG.warn("System property " + SYSPROP_EOFLOOKUPRANGE
+ " does not contain an integer value, but: '" + eofLookupRangeStr + "'");
}
}
document = new COSDocument(false);
pdfSource = new PushBackInputStream(raStream, 4096);
}
/**
* The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset)
* to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref
* at the beginning of the file. Last the root object is parsed.
*
* @throws IOException If something went wrong.
*/
private void initialParse() throws IOException
{
COSDictionary trailer = null;
// parse startxref
long startXRefOffset = getStartxrefOffset();
if (startXRefOffset > 0)
{
trailer = parseXref(startXRefOffset);
}
else
{
trailer = rebuildTrailer();
}
COSBase rootObject = parseTrailerValuesDynamically(trailer);
// resolve all objects
// A FDF doesn't have a catalog, all FDF fields are within the root object
if (rootObject instanceof COSDictionary)
{
parseDictObjects((COSDictionary) rootObject, (COSName[]) null);
}
initialParseDone = true;
}
/**
* This will parse the stream and populate the COSDocument object. This will close
* the stream when it is done parsing.
*
* @throws IOException If there is an error reading from the stream or corrupt data
* is found.
*/
public void parse() throws IOException
{
// set to false if all is processed
boolean exceptionOccurred = true;
try
{
if (!parseFDFHeader())
{
throw new IOException( "Error: Header doesn't contain versioninfo" );
}
initialParse();
exceptionOccurred = false;
}
finally
{
IOUtils.closeQuietly(pdfSource);
deleteTempFile();
if (exceptionOccurred && document != null)
{
IOUtils.closeQuietly(document);
document = null;
}
}
}
/**
* This will get the FDF document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public FDFDocument getFDFDocument() throws IOException
{
return new FDFDocument( getDocument() );
}
/**
* Remove the temporary file. A temporary file is created if this class is instantiated with an InputStream
*/
private void deleteTempFile()
{
if (tempPDFFile != null)
{
try
{
if (!tempPDFFile.delete())
{
LOG.warn("Temporary file '" + tempPDFFile.getName() + "' can't be deleted");
}
}
catch (SecurityException e)
{
LOG.warn("Temporary file '" + tempPDFFile.getName() + "' can't be deleted", e);
}
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdfparser/FDFParser.java | /*
* 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.pdfbox.pdfparser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.PushBackInputStream;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdmodel.fdf.FDFDocument;
public class FDFParser extends COSParser
{
private static final Log LOG = LogFactory.getLog(FDFParser.class);
private final RandomAccessBufferedFileInputStream raStream;
private File tempPDFFile;
/**
* Constructs parser for given file using memory buffer.
*
* @param filename the filename of the pdf to be parsed
*
* @throws IOException If something went wrong.
*/
public FDFParser(String filename) throws IOException
{
this(new File(filename));
}
/**
* Constructs parser for given file using given buffer for temporary
* storage.
*
* @param file the pdf to be parsed
*
* @throws IOException If something went wrong.
*/
public FDFParser(File file) throws IOException
{
fileLen = file.length();
raStream = new RandomAccessBufferedFileInputStream(file);
init();
}
/**
* Constructor.
*
* @param input input stream representing the pdf.
* @throws IOException If something went wrong.
*/
public FDFParser(InputStream input) throws IOException
{
tempPDFFile = createTmpFile(input);
fileLen = tempPDFFile.length();
raStream = new RandomAccessBufferedFileInputStream(tempPDFFile);
init();
}
private void init() throws IOException
{
String eofLookupRangeStr = System.getProperty(SYSPROP_EOFLOOKUPRANGE);
if (eofLookupRangeStr != null)
{
try
{
setEOFLookupRange(Integer.parseInt(eofLookupRangeStr));
}
catch (NumberFormatException nfe)
{
LOG.warn("System property " + SYSPROP_EOFLOOKUPRANGE
+ " does not contain an integer value, but: '" + eofLookupRangeStr + "'");
}
}
document = new COSDocument(false);
pdfSource = new PushBackInputStream(raStream, 4096);
}
/**
* The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset)
* to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref
* at the beginning of the file. Last the root object is parsed.
*
* @throws IOException If something went wrong.
*/
private void initialParse() throws IOException
{
COSDictionary trailer = null;
// parse startxref
long startXRefOffset = getStartxrefOffset();
if (startXRefOffset > 0)
{
trailer = parseXref(startXRefOffset);
}
else
{
trailer = rebuildTrailer();
}
COSBase rootObject = parseTrailerValuesDynamically(trailer);
// resolve all objects
// A FDF doesn't have a catalog, all FDF fields are within the root object
if (rootObject instanceof COSDictionary)
{
parseDictObjects((COSDictionary) rootObject, (COSName[]) null);
}
initialParseDone = true;
}
/**
* This will parse the stream and populate the COSDocument object. This will close
* the stream when it is done parsing.
*
* @throws IOException If there is an error reading from the stream or corrupt data
* is found.
*/
public void parse() throws IOException
{
// set to false if all is processed
boolean exceptionOccurred = true;
try
{
if (!parseFDFHeader())
{
throw new IOException( "Error: Header doesn't contain versioninfo" );
}
initialParse();
exceptionOccurred = false;
}
finally
{
IOUtils.closeQuietly(pdfSource);
deleteTempFile();
if (exceptionOccurred && document != null)
{
IOUtils.closeQuietly(document);
document = null;
}
}
}
/**
* This will get the FDF document that was parsed. When you are done with
* this document you must call close() on it to release resources.
*
* @return The document at the PD layer.
*
* @throws IOException If there is an error getting the document.
*/
public FDFDocument getFDFDocument() throws IOException
{
return new FDFDocument( getDocument() );
}
/**
* Remove the temporary file. A temporary file is created if this class is instantiated with an InputStream
*/
private void deleteTempFile()
{
if (tempPDFFile != null)
{
try
{
if (!tempPDFFile.delete())
{
LOG.warn("Temporary file '" + tempPDFFile.getName() + "' can't be deleted");
}
}
catch (SecurityException e)
{
LOG.warn("Temporary file '" + tempPDFFile.getName() + "' can't be deleted", e);
}
}
}
}
| PDFBOX-2576: remove unused import
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1672115 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdfparser/FDFParser.java | PDFBOX-2576: remove unused import | <ide><path>dfbox/src/main/java/org/apache/pdfbox/pdfparser/FDFParser.java
<ide> import org.apache.pdfbox.cos.COSDictionary;
<ide> import org.apache.pdfbox.cos.COSDocument;
<ide> import org.apache.pdfbox.cos.COSName;
<del>import org.apache.pdfbox.cos.COSObject;
<ide> import org.apache.pdfbox.io.IOUtils;
<ide> import org.apache.pdfbox.io.PushBackInputStream;
<ide> import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream; |
|
Java | bsd-3-clause | 2b8869435832ecaaa1a35f01d5f6603366e72bc7 | 0 | picocontainer/PicoContainer1,picocontainer/PicoContainer1 | /*****************************************************************************
* Copyright (c) PicoContainer Organization. All rights reserved. *
* ------------------------------------------------------------------------- *
* The software in this package is published under the terms of the BSD *
* style license a copy of which has been included with this distribution in *
* the LICENSE.txt file. *
* *
* Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant *
*****************************************************************************/
package org.picocontainer.defaults;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.ComponentMonitor;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.Parameter;
import org.picocontainer.PicoContainer;
import org.picocontainer.PicoException;
import org.picocontainer.PicoIntrospectionException;
import org.picocontainer.PicoRegistrationException;
import org.picocontainer.monitors.WriterComponentMonitor;
import org.picocontainer.tck.AbstractPicoContainerTestCase;
import org.picocontainer.testmodel.DecoratedTouchable;
import org.picocontainer.testmodel.SimpleTouchable;
import org.picocontainer.testmodel.Touchable;
/**
* @author Aslak Hellesøy
* @author Paul Hammant
* @author Ward Cunningham
* @author Mauro Talevi
* @version $Revision$
*/
public class DefaultPicoContainerTestCase extends AbstractPicoContainerTestCase {
protected MutablePicoContainer createPicoContainer(PicoContainer parent) {
return new DefaultPicoContainer(parent);
}
// to go to parent testcase ?
public void testBasicInstantiationAndContainment() throws PicoException, PicoRegistrationException {
DefaultPicoContainer pico = (DefaultPicoContainer) createPicoContainerWithTouchableAndDependsOnTouchable();
assertTrue("Component should be instance of Touchable", Touchable.class.isAssignableFrom(pico.getComponentAdapterOfType(Touchable.class).getComponentImplementation()));
}
public void testUpDownDependenciesCannotBeFollowed() {
MutablePicoContainer parent = createPicoContainer(null);
MutablePicoContainer child = createPicoContainer(parent);
// ComponentF -> ComponentA -> ComponentB+c
child.registerComponentImplementation(ComponentF.class);
parent.registerComponentImplementation(ComponentA.class);
child.registerComponentImplementation(ComponentB.class);
child.registerComponentImplementation(ComponentC.class);
Object o = child.getComponentInstance(ComponentF.class);
assertNull(o);
}
public void testComponentsCanBeRemovedByInstance() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(HashMap.class);
pico.registerComponentImplementation(ArrayList.class);
List list = (List) pico.getComponentInstanceOfType(List.class);
pico.unregisterComponentByInstance(list);
assertEquals(1, pico.getComponentAdapters().size());
assertEquals(1, pico.getComponentInstances().size());
assertEquals(HashMap.class, pico.getComponentInstanceOfType(Serializable.class).getClass());
}
public void testComponentInstancesListIsReturnedForNullType(){
MutablePicoContainer pico = createPicoContainer(null);
List componentInstances = pico.getComponentInstancesOfType(null);
assertNotNull(componentInstances);
assertEquals(0, componentInstances.size());
}
/*
When pico tries to instantiate ArrayList, it will attempt to use the constructor that takes a
java.util.Collection. Since both the ArrayList and LinkedList are Collection, it will fail with
AmbiguousComponentResolutionException.
Pico should be smart enough to figure out that it shouldn't consider a component as a candidate parameter for
its own instantiation. This may be fixed by adding an additional parameter to ComponentParameter.resolveAdapter -
namely the ComponentAdapter instance that should be excluded.
AH
Pico-222 is fixed, but activating this will lead to cyclic dependency...
KP
*/
public void TODOtestComponentsWithCommonSupertypeWhichIsAConstructorArgumentCanBeLookedUpByConcreteType() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(LinkedList.class);
pico.registerComponentImplementation(ArrayList.class);
assertEquals(ArrayList.class, pico.getComponentInstanceOfType(ArrayList.class).getClass());
}
/*
When pico tries to resolve DecoratedTouchable it find as dependency itself and SimpleTouchable.
Problem is basically the same as above. Pico should not consider self as solution.
JS
fixed it ( PICO-222 )
KP
*/
public void testUnambiguouSelfDependency() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(SimpleTouchable.class);
pico.registerComponentImplementation(DecoratedTouchable.class);
Touchable t = (Touchable) pico.getComponentInstance(DecoratedTouchable.class);
assertNotNull(t);
}
public static class Thingie {
public Thingie(List c) {
assertNotNull(c);
}
}
public void testThangCanBeInstantiatedWithArrayList() {
MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(Thingie.class);
pico.registerComponentImplementation(ArrayList.class);
assertNotNull(pico.getComponentInstance(Thingie.class));
}
public void getComponentAdaptersOfTypeReturnsUnmodifiableList() {
MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(Thingie.class);
try {
pico.getComponentAdaptersOfType(Thingie.class).add("blah");
fail("Expected an exception!");
} catch (UnsupportedOperationException th) {
}
}
public static class Service {
}
public static class TransientComponent {
private Service service;
public TransientComponent(Service service) {
this.service = service;
}
}
public void testDefaultPicoContainerReturnsNewInstanceForEachCallWhenUsingTransientComponentAdapter() {
DefaultPicoContainer picoContainer = new DefaultPicoContainer();
picoContainer.registerComponentImplementation(Service.class);
picoContainer.registerComponent(new ConstructorInjectionComponentAdapter(TransientComponent.class, TransientComponent.class));
TransientComponent c1 = (TransientComponent) picoContainer.getComponentInstance(TransientComponent.class);
TransientComponent c2 = (TransientComponent) picoContainer.getComponentInstance(TransientComponent.class);
assertNotSame(c1, c2);
assertSame(c1.service, c2.service);
}
public static class DependsOnCollection {
public DependsOnCollection(Collection c) {
}
}
public void testShouldProvideInfoAboutDependingWhenAmbiguityHappens() {
MutablePicoContainer pico = this.createPicoContainer(null);
pico.registerComponentInstance(new ArrayList());
pico.registerComponentInstance(new LinkedList());
pico.registerComponentImplementation(DependsOnCollection.class);
try {
pico.getComponentInstanceOfType(DependsOnCollection.class);
fail();
} catch (AmbiguousComponentResolutionException expected) {
String doc = DependsOnCollection.class.getName();
assertEquals("class " + doc + " has ambiguous dependency on interface java.util.Collection, resolves to multiple classes: [class java.util.ArrayList, class java.util.LinkedList]", expected.getMessage());
}
}
public void testCanChangeMonitor() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer pico = new DefaultPicoContainer(monitor1);
pico.registerComponentImplementation("t1", SimpleTouchable.class);
pico.registerComponentImplementation("t3", SimpleTouchable.class);
Touchable t1 = (Touchable) pico.getComponentInstance("t1");
assertNotNull(t1);
assertTrue("writer not empty", writer1.toString().length() > 0);
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
pico.changeMonitor(monitor2);
pico.registerComponentImplementation("t2", SimpleTouchable.class);
Touchable t2 = (Touchable) pico.getComponentInstance("t2");
assertNotNull(t2);
assertTrue("writer not empty", writer2.toString().length() > 0);
assertTrue("writers of same length", writer1.toString().length() == writer2.toString().length());
Touchable t3 = (Touchable) pico.getComponentInstance("t3");
assertNotNull(t3);
assertTrue("old writer was used", writer1.toString().length() < writer2.toString().length());
}
public void testCanChangeMonitorOfChildContainers() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer parent = new DefaultPicoContainer();
DefaultPicoContainer child = new DefaultPicoContainer(monitor1);
parent.addChildContainer(child);
child.registerComponentImplementation("t1", SimpleTouchable.class);
child.registerComponentImplementation("t3", SimpleTouchable.class);
Touchable t1 = (Touchable) child.getComponentInstance("t1");
assertNotNull(t1);
assertTrue("writer not empty", writer1.toString().length() > 0);
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
parent.changeMonitor(monitor2);
child.registerComponentImplementation("t2", SimpleTouchable.class);
Touchable t2 = (Touchable) child.getComponentInstance("t2");
assertNotNull(t2);
assertTrue("writer not empty", writer2.toString().length() > 0);
assertTrue("writers of same length", writer1.toString().length() == writer2.toString().length());
Touchable t3 = (Touchable) child.getComponentInstance("t3");
assertNotNull(t3);
assertTrue("old writer was used", writer1.toString().length() < writer2.toString().length());
}
public void testCanReturnCurrentMonitor() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer pico = new DefaultPicoContainer(monitor1);
assertEquals(monitor1, pico.currentMonitor());
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
pico.changeMonitor(monitor2);
assertEquals(monitor2, pico.currentMonitor());
}
public void testCannotReturnCurrentMonitor() {
DefaultPicoContainer pico = new DefaultPicoContainer(new ComponentAdapterFactoryWithNoMonitor());
try {
pico.currentMonitor();
fail("PicoIntrospectionException expected");
} catch (PicoIntrospectionException e) {
assertEquals("No component monitor found in container or its children", e.getMessage());
}
}
private static class ComponentAdapterFactoryWithNoMonitor implements ComponentAdapterFactory {
public ComponentAdapter createComponentAdapter(Object componentKey, Class componentImplementation, Parameter[] parameters) throws PicoIntrospectionException, AssignabilityRegistrationException, NotConcreteRegistrationException {
return null;
}
}
public void testMakeChildContainer() {
MutablePicoContainer parent = new DefaultPicoContainer();
parent.registerComponentImplementation("t1", SimpleTouchable.class);
MutablePicoContainer child = parent.makeChildContainer();
Object t1 = child.getParent().getComponentInstance("t1");
assertNotNull(t1);
assertTrue(t1 instanceof SimpleTouchable);
}
} | container/src/test/org/picocontainer/defaults/DefaultPicoContainerTestCase.java | /*****************************************************************************
* Copyright (c) PicoContainer Organization. All rights reserved. *
* ------------------------------------------------------------------------- *
* The software in this package is published under the terms of the BSD *
* style license a copy of which has been included with this distribution in *
* the LICENSE.txt file. *
* *
* Idea by Rachel Davies, Original code by Aslak Hellesoy and Paul Hammant *
*****************************************************************************/
package org.picocontainer.defaults;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.ComponentMonitor;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.Parameter;
import org.picocontainer.PicoContainer;
import org.picocontainer.PicoException;
import org.picocontainer.PicoIntrospectionException;
import org.picocontainer.PicoRegistrationException;
import org.picocontainer.monitors.WriterComponentMonitor;
import org.picocontainer.tck.AbstractPicoContainerTestCase;
import org.picocontainer.testmodel.DecoratedTouchable;
import org.picocontainer.testmodel.SimpleTouchable;
import org.picocontainer.testmodel.Touchable;
/**
* @author Aslak Hellesøy
* @author Paul Hammant
* @author Ward Cunningham
* @author Mauro Talevi
* @version $Revision$
*/
public class DefaultPicoContainerTestCase extends AbstractPicoContainerTestCase {
protected MutablePicoContainer createPicoContainer(PicoContainer parent) {
return new DefaultPicoContainer(parent);
}
// to go to parent testcase ?
public void testBasicInstantiationAndContainment() throws PicoException, PicoRegistrationException {
DefaultPicoContainer pico = (DefaultPicoContainer) createPicoContainerWithTouchableAndDependsOnTouchable();
assertTrue("Component should be instance of Touchable", Touchable.class.isAssignableFrom(pico.getComponentAdapterOfType(Touchable.class).getComponentImplementation()));
}
public void testUpDownDependenciesCannotBeFollowed() {
MutablePicoContainer parent = createPicoContainer(null);
MutablePicoContainer child = createPicoContainer(parent);
// ComponentF -> ComponentA -> ComponentB+c
child.registerComponentImplementation(ComponentF.class);
parent.registerComponentImplementation(ComponentA.class);
child.registerComponentImplementation(ComponentB.class);
child.registerComponentImplementation(ComponentC.class);
Object o = child.getComponentInstance(ComponentF.class);
assertNull(o);
}
public void testComponentsCanBeRemovedByInstance() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(HashMap.class);
pico.registerComponentImplementation(ArrayList.class);
List list = (List) pico.getComponentInstanceOfType(List.class);
pico.unregisterComponentByInstance(list);
assertEquals(1, pico.getComponentAdapters().size());
assertEquals(1, pico.getComponentInstances().size());
assertEquals(HashMap.class, pico.getComponentInstanceOfType(Serializable.class).getClass());
}
/*
When pico tries to instantiate ArrayList, it will attempt to use the constructor that takes a
java.util.Collection. Since both the ArrayList and LinkedList are Collection, it will fail with
AmbiguousComponentResolutionException.
Pico should be smart enough to figure out that it shouldn't consider a component as a candidate parameter for
its own instantiation. This may be fixed by adding an additional parameter to ComponentParameter.resolveAdapter -
namely the ComponentAdapter instance that should be excluded.
AH
Pico-222 is fixed, but activating this will lead to cyclic dependency...
KP
*/
public void TODOtestComponentsWithCommonSupertypeWhichIsAConstructorArgumentCanBeLookedUpByConcreteType() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(LinkedList.class);
pico.registerComponentImplementation(ArrayList.class);
assertEquals(ArrayList.class, pico.getComponentInstanceOfType(ArrayList.class).getClass());
}
/*
When pico tries to resolve DecoratedTouchable it find as dependency itself and SimpleTouchable.
Problem is basically the same as above. Pico should not consider self as solution.
JS
fixed it ( PICO-222 )
KP
*/
public void testUnambiguouSelfDependency() {
MutablePicoContainer pico = createPicoContainer(null);
pico.registerComponentImplementation(SimpleTouchable.class);
pico.registerComponentImplementation(DecoratedTouchable.class);
Touchable t = (Touchable) pico.getComponentInstance(DecoratedTouchable.class);
assertNotNull(t);
}
public static class Thingie {
public Thingie(List c) {
assertNotNull(c);
}
}
public void testThangCanBeInstantiatedWithArrayList() {
MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(Thingie.class);
pico.registerComponentImplementation(ArrayList.class);
assertNotNull(pico.getComponentInstance(Thingie.class));
}
public void getComponentAdaptersOfTypeReturnsUnmodifiableList() {
MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(Thingie.class);
try {
pico.getComponentAdaptersOfType(Thingie.class).add("blah");
fail("Expected an exception!");
} catch (UnsupportedOperationException th) {
}
}
public static class Service {
}
public static class TransientComponent {
private Service service;
public TransientComponent(Service service) {
this.service = service;
}
}
public void testDefaultPicoContainerReturnsNewInstanceForEachCallWhenUsingTransientComponentAdapter() {
DefaultPicoContainer picoContainer = new DefaultPicoContainer();
picoContainer.registerComponentImplementation(Service.class);
picoContainer.registerComponent(new ConstructorInjectionComponentAdapter(TransientComponent.class, TransientComponent.class));
TransientComponent c1 = (TransientComponent) picoContainer.getComponentInstance(TransientComponent.class);
TransientComponent c2 = (TransientComponent) picoContainer.getComponentInstance(TransientComponent.class);
assertNotSame(c1, c2);
assertSame(c1.service, c2.service);
}
public static class DependsOnCollection {
public DependsOnCollection(Collection c) {
}
}
public void testShouldProvideInfoAboutDependingWhenAmbiguityHappens() {
MutablePicoContainer pico = this.createPicoContainer(null);
pico.registerComponentInstance(new ArrayList());
pico.registerComponentInstance(new LinkedList());
pico.registerComponentImplementation(DependsOnCollection.class);
try {
pico.getComponentInstanceOfType(DependsOnCollection.class);
fail();
} catch (AmbiguousComponentResolutionException expected) {
String doc = DependsOnCollection.class.getName();
assertEquals("class " + doc + " has ambiguous dependency on interface java.util.Collection, resolves to multiple classes: [class java.util.ArrayList, class java.util.LinkedList]", expected.getMessage());
}
}
public void testCanChangeMonitor() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer pico = new DefaultPicoContainer(monitor1);
pico.registerComponentImplementation("t1", SimpleTouchable.class);
pico.registerComponentImplementation("t3", SimpleTouchable.class);
Touchable t1 = (Touchable) pico.getComponentInstance("t1");
assertNotNull(t1);
assertTrue("writer not empty", writer1.toString().length() > 0);
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
pico.changeMonitor(monitor2);
pico.registerComponentImplementation("t2", SimpleTouchable.class);
Touchable t2 = (Touchable) pico.getComponentInstance("t2");
assertNotNull(t2);
assertTrue("writer not empty", writer2.toString().length() > 0);
assertTrue("writers of same length", writer1.toString().length() == writer2.toString().length());
Touchable t3 = (Touchable) pico.getComponentInstance("t3");
assertNotNull(t3);
assertTrue("old writer was used", writer1.toString().length() < writer2.toString().length());
}
public void testCanChangeMonitorOfChildContainers() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer parent = new DefaultPicoContainer();
DefaultPicoContainer child = new DefaultPicoContainer(monitor1);
parent.addChildContainer(child);
child.registerComponentImplementation("t1", SimpleTouchable.class);
child.registerComponentImplementation("t3", SimpleTouchable.class);
Touchable t1 = (Touchable) child.getComponentInstance("t1");
assertNotNull(t1);
assertTrue("writer not empty", writer1.toString().length() > 0);
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
parent.changeMonitor(monitor2);
child.registerComponentImplementation("t2", SimpleTouchable.class);
Touchable t2 = (Touchable) child.getComponentInstance("t2");
assertNotNull(t2);
assertTrue("writer not empty", writer2.toString().length() > 0);
assertTrue("writers of same length", writer1.toString().length() == writer2.toString().length());
Touchable t3 = (Touchable) child.getComponentInstance("t3");
assertNotNull(t3);
assertTrue("old writer was used", writer1.toString().length() < writer2.toString().length());
}
public void testCanReturnCurrentMonitor() {
StringWriter writer1 = new StringWriter();
ComponentMonitor monitor1 = new WriterComponentMonitor(writer1);
DefaultPicoContainer pico = new DefaultPicoContainer(monitor1);
assertEquals(monitor1, pico.currentMonitor());
StringWriter writer2 = new StringWriter();
ComponentMonitor monitor2 = new WriterComponentMonitor(writer2);
pico.changeMonitor(monitor2);
assertEquals(monitor2, pico.currentMonitor());
}
public void testCannotReturnCurrentMonitor() {
DefaultPicoContainer pico = new DefaultPicoContainer(new ComponentAdapterFactoryWithNoMonitor());
try {
pico.currentMonitor();
fail("PicoIntrospectionException expected");
} catch (PicoIntrospectionException e) {
assertEquals("No component monitor found in container or its children", e.getMessage());
}
}
private static class ComponentAdapterFactoryWithNoMonitor implements ComponentAdapterFactory {
public ComponentAdapter createComponentAdapter(Object componentKey, Class componentImplementation, Parameter[] parameters) throws PicoIntrospectionException, AssignabilityRegistrationException, NotConcreteRegistrationException {
return null;
}
}
public void testMakeChildContainer() {
MutablePicoContainer parent = new DefaultPicoContainer();
parent.registerComponentImplementation("t1", SimpleTouchable.class);
MutablePicoContainer child = parent.makeChildContainer();
Object t1 = child.getParent().getComponentInstance("t1");
assertNotNull(t1);
assertTrue(t1 instanceof SimpleTouchable);
}
} | Added test
git-svn-id: 39c93fb42c3fce26a4768237af3b74bd47e2a670@2384 ac66bb80-72f5-0310-8d68-9f556cfffb23
| container/src/test/org/picocontainer/defaults/DefaultPicoContainerTestCase.java | Added test | <ide><path>ontainer/src/test/org/picocontainer/defaults/DefaultPicoContainerTestCase.java
<ide> assertEquals(HashMap.class, pico.getComponentInstanceOfType(Serializable.class).getClass());
<ide> }
<ide>
<add> public void testComponentInstancesListIsReturnedForNullType(){
<add> MutablePicoContainer pico = createPicoContainer(null);
<add> List componentInstances = pico.getComponentInstancesOfType(null);
<add> assertNotNull(componentInstances);
<add> assertEquals(0, componentInstances.size());
<add> }
<add>
<ide> /*
<ide> When pico tries to instantiate ArrayList, it will attempt to use the constructor that takes a
<ide> java.util.Collection. Since both the ArrayList and LinkedList are Collection, it will fail with
<ide> assertNotNull(t3);
<ide> assertTrue("old writer was used", writer1.toString().length() < writer2.toString().length());
<ide> }
<del>
<add>
<ide> public void testCanReturnCurrentMonitor() {
<ide> StringWriter writer1 = new StringWriter();
<ide> ComponentMonitor monitor1 = new WriterComponentMonitor(writer1); |
|
Java | apache-2.0 | 7d2b689cf4db75c2e2b66c772fd66808b807b9f9 | 0 | EBIBioStudies/FrontEndUI,EBIBioStudies/FrontEndUI,arrayexpress/ae-interface,arrayexpress/ae-interface,EBIBioStudies/FrontEndUI,arrayexpress/ae-interface | package uk.ac.ebi.arrayexpress.utils.saxon.search;
/*
* Copyright 2009-2012 European Molecular Biology Laboratory
*
* 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.
*
*/
import org.apache.lucene.queryParser.ParseException;
import uk.ac.ebi.arrayexpress.utils.LRUMap;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class QueryPool
{
// logging machinery
//private final Logger logger = LoggerFactory.getLogger(getClass());
private AtomicInteger queryId;
private Map<Integer, QueryInfo> queries = Collections.synchronizedMap(new LRUMap<Integer, QueryInfo>(50));
public QueryPool()
{
this.queryId = new AtomicInteger(0);
}
public Integer addQuery(
IndexEnvironment env
, IQueryConstructor queryConstructor
, Map<String, String[]> queryParams
, String queryString
, IQueryExpander queryExpander )
throws ParseException, IOException
{
QueryInfo info;
if (null != queryExpander) {
info = queryExpander.newQueryInfo();
} else {
info = new QueryInfo();
}
info.setIndexId(env.indexId);
info.setQueryString(queryString);
info.setParams(queryParams);
info.setQuery(queryConstructor.construct(env, queryParams));
if (null != queryExpander) {
info.setQuery(queryExpander.expandQuery(env, info));
}
Integer id;
this.queries.put(id = this.queryId.addAndGet(1), info);
return id;
}
public QueryInfo getQueryInfo( Integer queryId )
{
QueryInfo info = null;
if (queries.containsKey(queryId)) {
info = queries.get(queryId);
}
return info;
}
}
| webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/QueryPool.java | package uk.ac.ebi.arrayexpress.utils.saxon.search;
/*
* Copyright 2009-2012 European Molecular Biology Laboratory
*
* 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.
*
*/
import org.apache.lucene.queryParser.ParseException;
import uk.ac.ebi.arrayexpress.utils.LRUMap;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class QueryPool
{
// logging machinery
//private final Logger logger = LoggerFactory.getLogger(getClass());
private AtomicInteger queryId;
private Map<Integer, QueryInfo> queries = Collections.synchronizedMap(new LRUMap<Integer, QueryInfo>(50));
public QueryPool()
{
this.queryId = new AtomicInteger(0);
}
public Integer addQuery(
IndexEnvironment env
, IQueryConstructor queryConstructor
, Map<String, String[]> queryParams
, String queryString
, IQueryExpander queryExpander )
throws ParseException, IOException
{
QueryInfo info;
if (null != queryExpander) {
info = queryExpander.newQueryInfo();
} else {
info = new QueryInfo();
}
info.setIndexId(env.indexId);
info.setQueryString(queryString);
info.setParams(queryParams);
info.setQuery(queryConstructor.construct(env, queryParams));
if (null != queryExpander) {
info.setQuery(queryExpander.expandQuery(env, info));
}
this.queries.put(this.queryId.addAndGet(1), info);
return this.queryId.get();
}
public QueryInfo getQueryInfo( Integer queryId )
{
QueryInfo info = null;
if (queries.containsKey(queryId)) {
info = queries.get(queryId);
}
return info;
}
}
| - value of queryId may change between two gets so we capture it in local variable
git-svn-id: d21cf3f823a38adcd0967a5aa33e5b271a1966c2@20126 2913f559-6b04-0410-9a09-c530ee9f5186
| webapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/QueryPool.java | - value of queryId may change between two gets so we capture it in local variable | <ide><path>ebapp/src/main/java/uk/ac/ebi/arrayexpress/utils/saxon/search/QueryPool.java
<ide> if (null != queryExpander) {
<ide> info.setQuery(queryExpander.expandQuery(env, info));
<ide> }
<del> this.queries.put(this.queryId.addAndGet(1), info);
<ide>
<del> return this.queryId.get();
<add> Integer id;
<add> this.queries.put(id = this.queryId.addAndGet(1), info);
<add>
<add> return id;
<ide> }
<ide>
<ide> public QueryInfo getQueryInfo( Integer queryId ) |
|
Java | apache-2.0 | feda60559a553d1f08de995becc4c87bd2739269 | 0 | jerrinot/hazelcast-stabilizer,Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator,pveentjer/hazelcast-simulator,jerrinot/hazelcast-stabilizer,pveentjer/hazelcast-simulator,hazelcast/hazelcast-simulator,Donnerbart/hazelcast-simulator,hazelcast/hazelcast-simulator | package com.hazelcast.simulator.coordinator;
import com.hazelcast.simulator.cluster.ClusterLayout;
import com.hazelcast.simulator.cluster.WorkerConfigurationConverter;
import com.hazelcast.simulator.common.JavaProfiler;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.protocol.registry.ComponentRegistry;
import com.hazelcast.simulator.test.TestException;
import com.hazelcast.simulator.utils.Bash;
import com.hazelcast.simulator.utils.CommandLineExitException;
import com.hazelcast.simulator.utils.jars.HazelcastJARs;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.util.HashSet;
import static com.hazelcast.simulator.TestEnvironmentUtils.resetUserDir;
import static com.hazelcast.simulator.TestEnvironmentUtils.setDistributionUserDir;
import static com.hazelcast.simulator.common.JavaProfiler.NONE;
import static com.hazelcast.simulator.common.JavaProfiler.YOURKIT;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingDirectory;
import static com.hazelcast.simulator.utils.FormatUtils.NEW_LINE;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.OUT_OF_THE_BOX;
import static java.util.Collections.singleton;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class CoordinatorUploaderTest {
private ComponentRegistry componentRegistry = new ComponentRegistry();
private ClusterLayout clusterLayout;
private Bash bash = mock(Bash.class);
private HazelcastJARs hazelcastJARs = mock(HazelcastJARs.class);
private WorkerParameters workerParameters = mock(WorkerParameters.class);
private String testSuiteId = "testSuiteId";
private File notExists = new File("notExists");
private File uploadDirectory;
private File workerClassPathFile;
private String workerClassPath;
private CoordinatorUploader coordinatorUploader;
@BeforeClass
public static void setupEnvironment() {
setDistributionUserDir();
}
@AfterClass
public static void resetEnvironment() {
resetUserDir();
}
@Before
public void setUp() {
uploadDirectory = new File("upload").getAbsoluteFile();
ensureExistingDirectory(uploadDirectory);
workerClassPathFile = new File("workerClassPath").getAbsoluteFile();
ensureExistingDirectory(workerClassPathFile);
workerClassPath = workerClassPathFile.getAbsolutePath();
componentRegistry.addAgent("192.168.0.1", "192.168.0.1");
componentRegistry.addAgent("192.168.0.2", "192.168.0.2");
when(workerParameters.getHazelcastVersionSpec()).thenReturn(OUT_OF_THE_BOX);
when(workerParameters.getProfiler()).thenReturn(JavaProfiler.NONE);
ClusterLayoutParameters clusterLayoutParameters = new ClusterLayoutParameters(null, null, 2, 0, 0, 2);
clusterLayout = new ClusterLayout(componentRegistry, workerParameters, clusterLayoutParameters);
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, YOURKIT, testSuiteId);
}
@After
public void tearDown() {
deleteQuiet(uploadDirectory);
deleteQuiet(workerClassPathFile);
}
@Test
public void testRun() {
coordinatorUploader.run();
}
@Test
public void testUploadHazelcastJARs() {
coordinatorUploader.uploadHazelcastJARs();
verify(hazelcastJARs, times(1)).prepare(false);
verify(hazelcastJARs, times(2)).upload(contains("192.168.0."), anyString(), eq(singleton(OUT_OF_THE_BOX)));
verifyNoMoreInteractions(hazelcastJARs);
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadHazelcastJARs_withClusterXml() {
String xml
= "<clusterConfiguration>"
+ NEW_LINE + "\t<workerConfiguration name=\"hz351\" type=\"MEMBER\" hzVersion=\"maven=3.5.1\"/>"
+ NEW_LINE + "\t<workerConfiguration name=\"hz352\" type=\"MEMBER\" hzVersion=\"maven=3.5.2\"/>"
+ NEW_LINE + "\t<nodeConfiguration>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz351\" count=\"1\"/>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz352\" count=\"1\"/>"
+ NEW_LINE + "\t</nodeConfiguration>"
+ NEW_LINE + "\t<nodeConfiguration>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz352\" count=\"1\"/>"
+ NEW_LINE + "\t</nodeConfiguration>"
+ NEW_LINE + "</clusterConfiguration>";
SimulatorProperties simulatorProperties = mock(SimulatorProperties.class);
WorkerConfigurationConverter converter = new WorkerConfigurationConverter(5701, null, workerParameters,
simulatorProperties, componentRegistry);
ClusterLayoutParameters clusterLayoutParameters = new ClusterLayoutParameters(xml, converter, 0, 0, 0, 2);
clusterLayout = new ClusterLayout(componentRegistry, workerParameters, clusterLayoutParameters);
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, YOURKIT, testSuiteId);
coordinatorUploader.uploadHazelcastJARs();
HashSet<String> versionSpecs = new HashSet<String>(2);
versionSpecs.add("maven=3.5.1");
versionSpecs.add("maven=3.5.2");
verify(hazelcastJARs, times(1)).prepare(false);
verify(hazelcastJARs, times(1)).upload(contains("192.168.0.1"), anyString(), eq(versionSpecs));
verify(hazelcastJARs, times(1)).upload(contains("192.168.0.2"), anyString(), eq(singleton("maven=3.5.2")));
verifyNoMoreInteractions(hazelcastJARs);
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadHazelcastJARs_isNull() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, null, true, false, workerClassPath,
YOURKIT, testSuiteId);
coordinatorUploader.uploadHazelcastJARs();
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadUploadDirectory() {
coordinatorUploader.uploadUploadDirectory();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadUploadDirectory_uploadDirectoryNotExists() {
deleteQuiet(uploadDirectory);
coordinatorUploader.uploadUploadDirectory();
verifyNoMoreInteractions(bash);
}
@Test(expected = CommandLineExitException.class)
public void testUploadUploadDirectory_withException() {
TestException exception = new TestException("expected");
doThrow(exception).when(bash).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
coordinatorUploader.uploadUploadDirectory();
}
@Test
public void testUploadWorkerClassPath() {
coordinatorUploader.uploadWorkerClassPath();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadWorkerClassPath_workerClassPathIsNull() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false, null,
YOURKIT, testSuiteId);
coordinatorUploader.uploadWorkerClassPath();
verifyNoMoreInteractions(bash);
}
@Test(expected = CommandLineExitException.class)
public void testUploadWorkerClassPath_workerClassPathNotExists() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
notExists.getAbsolutePath(), YOURKIT, testSuiteId);
coordinatorUploader.uploadWorkerClassPath();
}
@Test
public void testUploadYourKit() {
coordinatorUploader.uploadYourKit();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadYourKit_noYourKitProfiler() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, NONE, testSuiteId);
coordinatorUploader.uploadYourKit();
verifyNoMoreInteractions(bash);
}
}
| simulator/src/test/java/com/hazelcast/simulator/coordinator/CoordinatorUploaderTest.java | package com.hazelcast.simulator.coordinator;
import com.hazelcast.simulator.cluster.ClusterLayout;
import com.hazelcast.simulator.cluster.WorkerConfigurationConverter;
import com.hazelcast.simulator.common.JavaProfiler;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.protocol.registry.ComponentRegistry;
import com.hazelcast.simulator.test.TestException;
import com.hazelcast.simulator.utils.Bash;
import com.hazelcast.simulator.utils.CommandLineExitException;
import com.hazelcast.simulator.utils.jars.HazelcastJARs;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.HashSet;
import static com.hazelcast.simulator.common.JavaProfiler.NONE;
import static com.hazelcast.simulator.common.JavaProfiler.YOURKIT;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingDirectory;
import static com.hazelcast.simulator.utils.FormatUtils.NEW_LINE;
import static com.hazelcast.simulator.utils.jars.HazelcastJARs.OUT_OF_THE_BOX;
import static java.util.Collections.singleton;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.contains;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
public class CoordinatorUploaderTest {
private ComponentRegistry componentRegistry = new ComponentRegistry();
private ClusterLayout clusterLayout;
private Bash bash = mock(Bash.class);
private HazelcastJARs hazelcastJARs = mock(HazelcastJARs.class);
private WorkerParameters workerParameters = mock(WorkerParameters.class);
private String testSuiteId = "testSuiteId";
private File notExists = new File("/notExists");
private File uploadDirectory = ensureExistingDirectory("upload");
private File workerClassPathFile = ensureExistingDirectory("workerClassPath");
private String workerClassPath = workerClassPathFile.getAbsolutePath();
private CoordinatorUploader coordinatorUploader;
@Before
public void setUp() {
componentRegistry.addAgent("192.168.0.1", "192.168.0.1");
componentRegistry.addAgent("192.168.0.2", "192.168.0.2");
when(workerParameters.getHazelcastVersionSpec()).thenReturn(OUT_OF_THE_BOX);
when(workerParameters.getProfiler()).thenReturn(JavaProfiler.NONE);
ClusterLayoutParameters clusterLayoutParameters = new ClusterLayoutParameters(null, null, 2, 0, 0, 2);
clusterLayout = new ClusterLayout(componentRegistry, workerParameters, clusterLayoutParameters);
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, YOURKIT, testSuiteId);
}
@After
public void tearDown() {
deleteQuiet(uploadDirectory);
deleteQuiet(workerClassPathFile);
}
@Test
public void testRun() {
coordinatorUploader.run();
}
@Test
public void testUploadHazelcastJARs() {
coordinatorUploader.uploadHazelcastJARs();
verify(hazelcastJARs, times(1)).prepare(false);
verify(hazelcastJARs, times(2)).upload(contains("192.168.0."), anyString(), eq(singleton(OUT_OF_THE_BOX)));
verifyNoMoreInteractions(hazelcastJARs);
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadHazelcastJARs_withClusterXml() {
String xml
= "<clusterConfiguration>"
+ NEW_LINE + "\t<workerConfiguration name=\"hz351\" type=\"MEMBER\" hzVersion=\"maven=3.5.1\"/>"
+ NEW_LINE + "\t<workerConfiguration name=\"hz352\" type=\"MEMBER\" hzVersion=\"maven=3.5.2\"/>"
+ NEW_LINE + "\t<nodeConfiguration>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz351\" count=\"1\"/>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz352\" count=\"1\"/>"
+ NEW_LINE + "\t</nodeConfiguration>"
+ NEW_LINE + "\t<nodeConfiguration>"
+ NEW_LINE + "\t\t<workerGroup configuration=\"hz352\" count=\"1\"/>"
+ NEW_LINE + "\t</nodeConfiguration>"
+ NEW_LINE + "</clusterConfiguration>";
SimulatorProperties simulatorProperties = mock(SimulatorProperties.class);
WorkerConfigurationConverter converter = new WorkerConfigurationConverter(5701, null, workerParameters,
simulatorProperties, componentRegistry);
ClusterLayoutParameters clusterLayoutParameters = new ClusterLayoutParameters(xml, converter, 0, 0, 0, 2);
clusterLayout = new ClusterLayout(componentRegistry, workerParameters, clusterLayoutParameters);
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, YOURKIT, testSuiteId);
coordinatorUploader.uploadHazelcastJARs();
HashSet<String> versionSpecs = new HashSet<String>(2);
versionSpecs.add("maven=3.5.1");
versionSpecs.add("maven=3.5.2");
verify(hazelcastJARs, times(1)).prepare(false);
verify(hazelcastJARs, times(1)).upload(contains("192.168.0.1"), anyString(), eq(versionSpecs));
verify(hazelcastJARs, times(1)).upload(contains("192.168.0.2"), anyString(), eq(singleton("maven=3.5.2")));
verifyNoMoreInteractions(hazelcastJARs);
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadHazelcastJARs_isNull() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, null, true, false, workerClassPath,
YOURKIT, testSuiteId);
coordinatorUploader.uploadHazelcastJARs();
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadUploadDirectory() {
coordinatorUploader.uploadUploadDirectory();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadUploadDirectory_uploadDirectoryNotExists() {
deleteQuiet(uploadDirectory);
coordinatorUploader.uploadUploadDirectory();
verifyNoMoreInteractions(bash);
}
@Test(expected = CommandLineExitException.class)
public void testUploadUploadDirectory_withException() {
TestException exception = new TestException("expected");
doThrow(exception).when(bash).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
coordinatorUploader.uploadUploadDirectory();
}
@Test
public void testUploadWorkerClassPath() {
coordinatorUploader.uploadWorkerClassPath();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadWorkerClassPath_workerClassPathIsNull() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false, null,
YOURKIT, testSuiteId);
coordinatorUploader.uploadWorkerClassPath();
verifyNoMoreInteractions(bash);
}
@Test(expected = CommandLineExitException.class)
public void testUploadWorkerClassPath_workerClassPathNotExists() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
notExists.getAbsolutePath(), YOURKIT, testSuiteId);
coordinatorUploader.uploadWorkerClassPath();
}
@Test
public void testUploadYourKit() {
coordinatorUploader.uploadYourKit();
verify(bash, times(2)).ssh(contains("192.168.0."), anyString());
verify(bash, times(2)).uploadToRemoteSimulatorDir(contains("192.168.0."), anyString(), anyString());
verifyNoMoreInteractions(bash);
}
@Test
public void testUploadYourKit_noYourKitProfiler() {
coordinatorUploader = new CoordinatorUploader(bash, componentRegistry, clusterLayout, hazelcastJARs, true, false,
workerClassPath, NONE, testSuiteId);
coordinatorUploader.uploadYourKit();
verifyNoMoreInteractions(bash);
}
}
| Fixed creation of folders in CoordinatorUploaderTest.
| simulator/src/test/java/com/hazelcast/simulator/coordinator/CoordinatorUploaderTest.java | Fixed creation of folders in CoordinatorUploaderTest. | <ide><path>imulator/src/test/java/com/hazelcast/simulator/coordinator/CoordinatorUploaderTest.java
<ide> import com.hazelcast.simulator.utils.CommandLineExitException;
<ide> import com.hazelcast.simulator.utils.jars.HazelcastJARs;
<ide> import org.junit.After;
<add>import org.junit.AfterClass;
<ide> import org.junit.Before;
<add>import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide>
<ide> import java.io.File;
<ide> import java.util.HashSet;
<ide>
<add>import static com.hazelcast.simulator.TestEnvironmentUtils.resetUserDir;
<add>import static com.hazelcast.simulator.TestEnvironmentUtils.setDistributionUserDir;
<ide> import static com.hazelcast.simulator.common.JavaProfiler.NONE;
<ide> import static com.hazelcast.simulator.common.JavaProfiler.YOURKIT;
<ide> import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
<ide>
<ide> private String testSuiteId = "testSuiteId";
<ide>
<del> private File notExists = new File("/notExists");
<del> private File uploadDirectory = ensureExistingDirectory("upload");
<del> private File workerClassPathFile = ensureExistingDirectory("workerClassPath");
<del> private String workerClassPath = workerClassPathFile.getAbsolutePath();
<add> private File notExists = new File("notExists");
<add> private File uploadDirectory;
<add> private File workerClassPathFile;
<add> private String workerClassPath;
<ide>
<ide> private CoordinatorUploader coordinatorUploader;
<add>
<add> @BeforeClass
<add> public static void setupEnvironment() {
<add> setDistributionUserDir();
<add> }
<add>
<add> @AfterClass
<add> public static void resetEnvironment() {
<add> resetUserDir();
<add> }
<ide>
<ide> @Before
<ide> public void setUp() {
<add> uploadDirectory = new File("upload").getAbsoluteFile();
<add> ensureExistingDirectory(uploadDirectory);
<add>
<add> workerClassPathFile = new File("workerClassPath").getAbsoluteFile();
<add> ensureExistingDirectory(workerClassPathFile);
<add>
<add> workerClassPath = workerClassPathFile.getAbsolutePath();
<add>
<ide> componentRegistry.addAgent("192.168.0.1", "192.168.0.1");
<ide> componentRegistry.addAgent("192.168.0.2", "192.168.0.2");
<ide> |
|
Java | mit | 84d27cf1c04e57b22184bd8a11d19acdb4d12724 | 0 | zkastl/AcmeCourierService | package view;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.github.lgooddatepicker.components.DatePickerSettings;
import com.github.lgooddatepicker.components.DateTimePicker;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import com.github.lgooddatepicker.components.TimePickerSettings.TimeIncrement;
import com.github.lgooddatepicker.zinternaltools.DateTimeChangeEvent;
import main.Application;
import main.CourierSystem;
import model.Client;
import model.Delivery;
import model.DeliveryStatus;
import model.Employee;
import model.EmployeeRole;
import net.miginfocom.swing.MigLayout;;
public class DeliveryTicketEditor extends JDialog {
private static final long serialVersionUID = 1L;
JComboBox<Client> pickupClient;
JComboBox<Client> deliveryClient;
JLabel blocks;
JLabel price;
JLabel estimatedDeliveryTime;
JLabel departureTime;
Delivery delivery;
JCheckBox billToPickup;
JCheckBox billToDeliver;
TimePicker pickedUpTime;
TimePicker deliveredTime;
JCheckBox bonusEarned;
DeliveryTableModel deliveryTable;
DateTimePicker pickupEditor;
JComboBox<Employee> cbCourier;
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("h:mm a");
private boolean saved = false;
private ChangeListener windowHasChanges = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
saved = false;
}
};
private ActionListener windowHasChanges2 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saved = false;
}
};
public DeliveryTicketEditor(Delivery delivery, DeliveryTableModel deliveryTable) {
super((JFrame) null, "ACME Delivery Ticket Editor", true);
this.delivery = delivery;
this.deliveryTable = deliveryTable;
if (delivery.packageID == 0) {
saved = false;
}
setSize(650, 740);
setAlwaysOnTop(true);
setIconImage(Toolkit.getDefaultToolkit().getImage(Application.class.getResource("/view/courier logo.png")));
setTitle("ACME Delivery Ticket Editor");
setResizable(false);
getContentPane().setLayout(new MigLayout("", "[10%][10%][10%][10%][10%][20%][20%][10%]",
"[][][][5:n][][][20:n][][][][][][20:n][][][][][20:n][][][][][][][20][]"));
pickupClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
pickupClient.setSelectedItem(delivery.pickupClient);
pickupClient.addActionListener(windowHasChanges2);
getContentPane().add(pickupClient, "cell 4 8 2 1,growx");
DatePickerSettings pickupDateSettings = new DatePickerSettings();
TimePickerSettings pickupTimeSettings = new TimePickerSettings();
pickupEditor = new DateTimePicker(pickupDateSettings, pickupTimeSettings);
pickupDateSettings.setAllowEmptyDates(false);
pickupDateSettings.setDateRangeLimits(LocalDate.now(), LocalDate.MAX);
pickupTimeSettings.setAllowEmptyTimes(false);
pickupTimeSettings.generatePotentialMenuTimes(TimeIncrement.FifteenMinutes, LocalTime.of(8, 0),
LocalTime.of(20, 0));
getContentPane().add(pickupEditor, "cell 4 10 3 1,alignx left");
if (delivery.packageID == 0) {
int minutesToAdd = 15 - LocalTime.now().getMinute() % 15;
pickupEditor.timePicker.setTime(LocalTime.now().plusMinutes(minutesToAdd));
} else {
pickupEditor.setDateTimePermissive(delivery.requestedPickupTime);
}
// TODO: ADD PROPER EVENT HERE
pickupEditor.addDateTimeChangeListener(null);
billToPickup = new JCheckBox("", delivery.billToSender);
billToPickup.addChangeListener(windowHasChanges);
getContentPane().add(billToPickup, "cell 4 11");
deliveryClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
deliveryClient.setSelectedItem(delivery.deliveryClient);
deliveryClient.addActionListener(windowHasChanges2);
getContentPane().add(deliveryClient, "cell 4 14 2 1,growx");
billToDeliver = new JCheckBox("", !delivery.billToSender);
billToDeliver.addChangeListener(windowHasChanges);
getContentPane().add(billToDeliver, "cell 4 16");
cbCourier = new JComboBox<Employee>();
for (Employee e : CourierSystem.Employees.values()) {
if (e.role == EmployeeRole.Courier)
cbCourier.addItem(e);
}
cbCourier.setSelectedItem(delivery.assignedCourier);
cbCourier.addActionListener(windowHasChanges2);
getContentPane().add(cbCourier, "cell 6 19,growx");
estimatedDeliveryTime = new JLabel(
delivery.estimatedDeliveryTime != null ? timeFormat.format(delivery.estimatedDeliveryTime) : "");
getContentPane().add(estimatedDeliveryTime, "cell 3 20");
departureTime = new JLabel(
delivery.calculatedDepartureTime != null ? timeFormat.format(delivery.calculatedDepartureTime) : "");
getContentPane().add(departureTime, "cell 6 20");
blocks = new JLabel(String.valueOf(delivery.estimatedDistanceTraveled));
getContentPane().add(blocks, "cell 3 21");
TimePickerSettings actualTimeSettings = new TimePickerSettings();
actualTimeSettings.setAllowEmptyTimes(true);
actualTimeSettings.generatePotentialMenuTimes(TimeIncrement.FifteenMinutes, LocalTime.of(8, 0),
LocalTime.of(20, 0));
pickedUpTime = new TimePicker(actualTimeSettings);
pickedUpTime.setTime(delivery.actualPickupTime != null ? delivery.actualPickupTime.toLocalTime() : null);
getContentPane().add(pickedUpTime, "cell 6 21,alignx left");
price = new JLabel(String.valueOf(delivery.totalDeliveryCost));
getContentPane().add(price, "cell 3 22");
deliveredTime = new TimePicker(actualTimeSettings);
deliveredTime.setTime(delivery.actualDeliveryTime != null ? delivery.actualDeliveryTime.toLocalTime() : null);
getContentPane().add(deliveredTime, "cell 6 22, alignx left");
bonusEarned = new JCheckBox("", delivery.bonusEarned);
bonusEarned.setEnabled(false);
getContentPane().add(bonusEarned, "cell 6 23");
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validInputs()) {
save();
close();
}
}
});
getContentPane().add(btnOk, "cell 0 25,growx");
JButton btnApply = new JButton("Apply");
btnApply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validInputs())
save();
}
});
getContentPane().add(btnApply, "cell 1 25");
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
close();
}
});
getContentPane().add(btnCancel, "cell 2 25");
doBaseLayout();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public boolean validInputs() {
boolean valid = pickupClient.getSelectedItem() != null && deliveryClient.getSelectedItem() != null;
if (!valid)
JOptionPane.showMessageDialog(this,
"Pickup and Delivery clients must be specified before delivery route can be calculated.");
return valid;
}
protected void save() {
try {
if (!saved) {
populateDeliveryInfo();
CourierSystem.SaveDelivery(delivery);
saved = true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
deliveryTable.refresh();
}
}
protected void close() {
dispose();
}
private void populateDeliveryInfo() {
saved = false;
delivery.pickupClient = (Client) pickupClient.getSelectedItem();
delivery.deliveryClient = (Client) deliveryClient.getSelectedItem();
delivery.requestedPickupTime = pickupEditor.getDateTimeStrict();
delivery.billToSender = billToPickup.isSelected();
delivery.calculateDeliveryStatistics();
departureTime.setText(delivery.calculatedDepartureTime.format(timeFormat));
estimatedDeliveryTime.setText(delivery.estimatedDeliveryTime.format(timeFormat));
blocks.setText(Double.toString(delivery.estimatedDistanceTraveled));
price.setText(Double.toString(delivery.totalDeliveryCost));
delivery.assignedCourier = (Employee) cbCourier.getSelectedItem();
delivery.actualPickupTime = (delivery.actualPickupTime != null) ? LocalDateTime.of(delivery.actualPickupTime.toLocalDate(),
delivery.actualPickupTime.toLocalTime()) : null;
delivery.actualDeliveryTime = (delivery.actualDeliveryTime != null) ? LocalDateTime.of(delivery.actualDeliveryTime.toLocalDate(),
delivery.actualDeliveryTime.toLocalTime()) : null;
delivery.calculateBonus();
bonusEarned.setSelected(delivery.bonusEarned);
if (delivery.assignedCourier != null && delivery.actualPickupTime != null
&& delivery.actualDeliveryTime != null)
delivery.status = DeliveryStatus.Completed;
}
@Override
public void dispose() {
if (!saved) {
deliveryTable.removeRow(delivery);
}
super.dispose();
}
private void doBaseLayout() {
JLabel logo = new JLabel("");
logo.setIcon(new ImageIcon(DeliveryTicketEditor.class.getResource("/view/courier logo.png")));
getContentPane().add(logo, "cell 0 0 8 1,alignx center");
JLabel lblAcmeCourierService_1 = new JLabel("ACME Courier Service");
lblAcmeCourierService_1.setFont(new Font("Tahoma", Font.BOLD, 14));
getContentPane().add(lblAcmeCourierService_1, "flowy,cell 0 1 8 1,alignx center,aligny center");
JLabel lblDeliveryTicket = new JLabel("Delivery Ticket");
lblDeliveryTicket.setFont(new Font("Tahoma", Font.BOLD, 14));
getContentPane().add(lblDeliveryTicket, "cell 0 2 8 1,alignx center,aligny center");
JLabel lblDate = new JLabel("Date:" + LocalDate.now().format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));
getContentPane().add(lblDate, "flowx,cell 0 4 8 1,alignx center");
JLabel lblOrderTakenBy = new JLabel("Order taken by:" + CourierSystem.currentUser.name);
getContentPane().add(lblOrderTakenBy, "flowx,cell 0 5 8 1,alignx center");
JLabel lblPickUpInfo = new JLabel("Pick Up Info");
lblPickUpInfo.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblPickUpInfo, "cell 2 7 2 1,alignx left");
JLabel lblClientName = new JLabel("Client Name:");
getContentPane().add(lblClientName, "cell 2 8 2 1,alignx left");
JLabel lblClientId = new JLabel("Client Id:");
getContentPane().add(lblClientId, "cell 2 9 2 1,alignx left");
JLabel pickupClientId = new JLabel("");
getContentPane().add(pickupClientId, "flowx,cell 4 9");
pickupClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pickupClientId.setText(String.valueOf(((Client) pickupClient.getSelectedItem()).clientID));
}
});
JLabel lblRequestedPickup = new JLabel("Requested Pickup Time:");
getContentPane().add(lblRequestedPickup, "cell 2 10 2 1,alignx left");
JLabel lblBillPickupClient = new JLabel("Bill Pickup Client?");
getContentPane().add(lblBillPickupClient, "cell 2 11 2 1,alignx left");
JLabel lblDeliveryInfo = new JLabel("Delivery Info");
lblDeliveryInfo.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblDeliveryInfo, "cell 2 13 2 1,alignx left");
JLabel lblClientName_1 = new JLabel("Client Name:");
getContentPane().add(lblClientName_1, "cell 2 14 2 1,alignx left");
JLabel lblClientId_1 = new JLabel("Client Id:");
getContentPane().add(lblClientId_1, "flowx,cell 2 15 2 1,alignx left");
JLabel deliveryclientId = new JLabel("");
getContentPane().add(deliveryclientId, "cell 4 15,alignx center");
deliveryClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deliveryclientId.setText(String.valueOf(((Client) deliveryClient.getSelectedItem()).clientID));
}
});
JLabel lblBillDeliveryClient = new JLabel("Bill Delivery Client?");
getContentPane().add(lblBillDeliveryClient, "cell 2 16 2 1,alignx left");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(billToPickup);
radioGroup.add(billToDeliver);
JLabel lblEstimatedDeliveryTime = new JLabel("Estimated Delivery Time:");
getContentPane().add(lblEstimatedDeliveryTime, "cell 1 20 2 1,alignx left");
JLabel lblDepartureTime = new JLabel("Departure Time:");
getContentPane().add(lblDepartureTime, "cell 5 20,alignx left");
JLabel lblEstimatedBlocks = new JLabel("Estimated Blocks:");
getContentPane().add(lblEstimatedBlocks, "cell 1 21 2 1,alignx left");
JLabel lblPickedUpTime = new JLabel("Picked Up Time:");
getContentPane().add(lblPickedUpTime, "cell 5 21,alignx left");
JLabel lblQuotedPrice = new JLabel("Quoted Price:");
getContentPane().add(lblQuotedPrice, "cell 1 22 2 1,alignx left");
JLabel lblDeliveredTime = new JLabel("Delivered Time:");
getContentPane().add(lblDeliveredTime, "cell 5 22,alignx left");
JLabel lblBonus = new JLabel("Bonus?");
getContentPane().add(lblBonus, "cell 5 23,alignx left");
JLabel lblTime = new JLabel("Time:" + LocalTime.now().format(DateTimeFormatter.ofPattern("h:mm")));
getContentPane().add(lblTime, "flowx,cell 0 4 8 1,alignx center");
JLabel lblNewLabel = new JLabel("Ticket Info");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblNewLabel, "cell 1 18 2 1,alignx left");
JLabel lblDeliveryInfo_1 = new JLabel("Delivery Info");
lblDeliveryInfo_1.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblDeliveryInfo_1, "cell 5 18 2 1,alignx left");
JLabel lblPackageId = new JLabel("Package Id:");
getContentPane().add(lblPackageId, "cell 1 19 2 1,alignx left");
JLabel packageId = new JLabel(String.valueOf(delivery.packageID));
getContentPane().add(packageId, "cell 3 19,alignx left");
JLabel lblCourier = new JLabel("Courier:");
getContentPane().add(lblCourier, "cell 5 19,alignx left");
}
} | AcmeCourierSystem/src/view/DeliveryTicketEditor.java | package view;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import com.github.lgooddatepicker.components.DatePickerSettings;
import com.github.lgooddatepicker.components.DateTimePicker;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import com.github.lgooddatepicker.components.TimePickerSettings.TimeIncrement;
import main.Application;
import main.CourierSystem;
import model.Client;
import model.Delivery;
import model.DeliveryStatus;
import model.Employee;
import model.EmployeeRole;
import net.miginfocom.swing.MigLayout;;
public class DeliveryTicketEditor extends JDialog {
private static final long serialVersionUID = 1L;
JComboBox<Client> pickupClient;
JComboBox<Client> deliveryClient;
JLabel blocks;
JLabel price;
JLabel estimatedDeliveryTime;
JLabel departureTime;
Delivery delivery;
JCheckBox billToPickup;
JCheckBox billToDeliver;
TimePicker pickedUpTime;
TimePicker deliveredTime;
JCheckBox bonusEarned;
DeliveryTableModel deliveryTable;
DateTimePicker pickupEditor;
JComboBox<Employee> cbCourier;
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("h:mm a");
private boolean saved = false;
public DeliveryTicketEditor(Delivery delivery, DeliveryTableModel deliveryTable) {
super((JFrame) null, "ACME Delivery Ticket Editor", true);
this.delivery = delivery;
this.deliveryTable = deliveryTable;
if (delivery.packageID == 0) {
saved = false;
}
setSize(650, 740);
setAlwaysOnTop(true);
setIconImage(Toolkit.getDefaultToolkit().getImage(Application.class.getResource("/view/courier logo.png")));
setTitle("ACME Delivery Ticket Editor");
setResizable(false);
getContentPane().setLayout(new MigLayout("", "[10%][10%][10%][10%][10%][20%][20%][10%]",
"[][][][5:n][][][20:n][][][][][][20:n][][][][][20:n][][][][][][][20][]"));
pickupClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
pickupClient.setSelectedItem(delivery.pickupClient);
getContentPane().add(pickupClient, "cell 4 8 2 1,growx");
DatePickerSettings pickupDateSettings = new DatePickerSettings();
TimePickerSettings pickupTimeSettings = new TimePickerSettings();
pickupEditor = new DateTimePicker(pickupDateSettings, pickupTimeSettings);
pickupDateSettings.setAllowEmptyDates(false);
pickupDateSettings.setDateRangeLimits(LocalDate.now(), LocalDate.MAX);
pickupTimeSettings.setAllowEmptyTimes(false);
pickupTimeSettings.generatePotentialMenuTimes(TimeIncrement.FifteenMinutes, LocalTime.of(8, 0),
LocalTime.of(20, 0));
getContentPane().add(pickupEditor, "cell 4 10 3 1,alignx left");
if (delivery.packageID == 0) {
int minutesToAdd = 15 - LocalTime.now().getMinute() % 15;
pickupEditor.timePicker.setTime(LocalTime.now().plusMinutes(minutesToAdd));
} else {
pickupEditor.setDateTimePermissive(delivery.requestedPickupTime);
}
billToPickup = new JCheckBox("", delivery.billToSender);
getContentPane().add(billToPickup, "cell 4 11");
deliveryClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
deliveryClient.setSelectedItem(delivery.deliveryClient);
getContentPane().add(deliveryClient, "cell 4 14 2 1,growx");
billToDeliver = new JCheckBox("", !delivery.billToSender);
getContentPane().add(billToDeliver, "cell 4 16");
cbCourier = new JComboBox<Employee>();
for (Employee e : CourierSystem.Employees.values()) {
if (e.role == EmployeeRole.Courier)
cbCourier.addItem(e);
}
cbCourier.setSelectedItem(delivery.assignedCourier);
getContentPane().add(cbCourier, "cell 6 19,growx");
estimatedDeliveryTime = new JLabel(
delivery.estimatedDeliveryTime != null ? timeFormat.format(delivery.estimatedDeliveryTime) : "");
getContentPane().add(estimatedDeliveryTime, "cell 3 20");
departureTime = new JLabel(
delivery.calculatedDepartureTime != null ? timeFormat.format(delivery.calculatedDepartureTime) : "");
getContentPane().add(departureTime, "cell 6 20");
blocks = new JLabel(String.valueOf(delivery.estimatedDistanceTraveled));
getContentPane().add(blocks, "cell 3 21");
TimePickerSettings actualTimeSettings = new TimePickerSettings();
actualTimeSettings.setAllowEmptyTimes(true);
actualTimeSettings.generatePotentialMenuTimes(TimeIncrement.FifteenMinutes, LocalTime.of(8, 0),
LocalTime.of(20, 0));
pickedUpTime = new TimePicker(actualTimeSettings);
pickedUpTime.setTime(delivery.actualPickupTime != null ? delivery.actualPickupTime.toLocalTime() : null);
getContentPane().add(pickedUpTime, "cell 6 21,alignx left");
price = new JLabel(String.valueOf(delivery.totalDeliveryCost));
getContentPane().add(price, "cell 3 22");
deliveredTime = new TimePicker(actualTimeSettings);
deliveredTime.setTime(delivery.actualDeliveryTime != null ? delivery.actualDeliveryTime.toLocalTime() : null);
getContentPane().add(deliveredTime, "cell 6 22, alignx left");
bonusEarned = new JCheckBox("", delivery.bonusEarned);
bonusEarned.setEnabled(false);
getContentPane().add(bonusEarned, "cell 6 23");
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validInputs()) {
save();
close();
}
}
});
getContentPane().add(btnOk, "cell 0 25,growx");
JButton btnApply = new JButton("Apply");
btnApply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (validInputs())
save();
}
});
getContentPane().add(btnApply, "cell 1 25");
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
close();
}
});
getContentPane().add(btnCancel, "cell 2 25");
doBaseLayout();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public boolean validInputs() {
boolean valid = pickupClient.getSelectedItem() != null && deliveryClient.getSelectedItem() != null;
if (!valid)
JOptionPane.showMessageDialog(this,
"Pickup and Delivery clients must be specified before delivery route can be calculated.");
return valid;
}
protected void save() {
try {
if (!saved) {
populateDeliveryInfo();
CourierSystem.SaveDelivery(delivery);
saved = true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
deliveryTable.refresh();
}
}
protected void close() {
dispose();
}
private void populateDeliveryInfo() {
delivery.pickupClient = (Client) pickupClient.getSelectedItem();
delivery.deliveryClient = (Client) deliveryClient.getSelectedItem();
delivery.requestedPickupTime = pickupEditor.getDateTimeStrict();
delivery.billToSender = billToPickup.isSelected();
delivery.calculateDeliveryStatistics();
departureTime.setText(delivery.calculatedDepartureTime.format(timeFormat));
estimatedDeliveryTime.setText(delivery.estimatedDeliveryTime.format(timeFormat));
blocks.setText(Double.toString(delivery.estimatedDistanceTraveled));
price.setText(Double.toString(delivery.totalDeliveryCost));
delivery.assignedCourier = (Employee) cbCourier.getSelectedItem();
delivery.actualPickupTime = (delivery.actualPickupTime != null) ? LocalDateTime.of(delivery.actualPickupTime.toLocalDate(),
delivery.actualPickupTime.toLocalTime()) : null;
delivery.actualDeliveryTime = (delivery.actualDeliveryTime != null) ? LocalDateTime.of(delivery.actualDeliveryTime.toLocalDate(),
delivery.actualDeliveryTime.toLocalTime()) : null;
delivery.calculateBonus();
bonusEarned.setSelected(delivery.bonusEarned);
if (delivery.assignedCourier != null && delivery.actualPickupTime != null
&& delivery.actualDeliveryTime != null)
delivery.status = DeliveryStatus.Completed;
}
@Override
public void dispose() {
if (!saved) {
deliveryTable.removeRow(delivery);
}
super.dispose();
}
private void doBaseLayout() {
JLabel logo = new JLabel("");
logo.setIcon(new ImageIcon(DeliveryTicketEditor.class.getResource("/view/courier logo.png")));
getContentPane().add(logo, "cell 0 0 8 1,alignx center");
JLabel lblAcmeCourierService_1 = new JLabel("ACME Courier Service");
lblAcmeCourierService_1.setFont(new Font("Tahoma", Font.BOLD, 14));
getContentPane().add(lblAcmeCourierService_1, "flowy,cell 0 1 8 1,alignx center,aligny center");
JLabel lblDeliveryTicket = new JLabel("Delivery Ticket");
lblDeliveryTicket.setFont(new Font("Tahoma", Font.BOLD, 14));
getContentPane().add(lblDeliveryTicket, "cell 0 2 8 1,alignx center,aligny center");
JLabel lblDate = new JLabel("Date:" + LocalDate.now().format(DateTimeFormatter.ofPattern("MM/dd/yyyy")));
getContentPane().add(lblDate, "flowx,cell 0 4 8 1,alignx center");
JLabel lblOrderTakenBy = new JLabel("Order taken by:" + CourierSystem.currentUser.name);
getContentPane().add(lblOrderTakenBy, "flowx,cell 0 5 8 1,alignx center");
JLabel lblPickUpInfo = new JLabel("Pick Up Info");
lblPickUpInfo.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblPickUpInfo, "cell 2 7 2 1,alignx left");
JLabel lblClientName = new JLabel("Client Name:");
getContentPane().add(lblClientName, "cell 2 8 2 1,alignx left");
JLabel lblClientId = new JLabel("Client Id:");
getContentPane().add(lblClientId, "cell 2 9 2 1,alignx left");
JLabel pickupClientId = new JLabel("");
getContentPane().add(pickupClientId, "flowx,cell 4 9");
pickupClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pickupClientId.setText(String.valueOf(((Client) pickupClient.getSelectedItem()).clientID));
}
});
JLabel lblRequestedPickup = new JLabel("Requested Pickup Time:");
getContentPane().add(lblRequestedPickup, "cell 2 10 2 1,alignx left");
JLabel lblBillPickupClient = new JLabel("Bill Pickup Client?");
getContentPane().add(lblBillPickupClient, "cell 2 11 2 1,alignx left");
JLabel lblDeliveryInfo = new JLabel("Delivery Info");
lblDeliveryInfo.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblDeliveryInfo, "cell 2 13 2 1,alignx left");
JLabel lblClientName_1 = new JLabel("Client Name:");
getContentPane().add(lblClientName_1, "cell 2 14 2 1,alignx left");
JLabel lblClientId_1 = new JLabel("Client Id:");
getContentPane().add(lblClientId_1, "flowx,cell 2 15 2 1,alignx left");
JLabel deliveryclientId = new JLabel("");
getContentPane().add(deliveryclientId, "cell 4 15,alignx center");
deliveryClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deliveryclientId.setText(String.valueOf(((Client) deliveryClient.getSelectedItem()).clientID));
}
});
JLabel lblBillDeliveryClient = new JLabel("Bill Delivery Client?");
getContentPane().add(lblBillDeliveryClient, "cell 2 16 2 1,alignx left");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(billToPickup);
radioGroup.add(billToDeliver);
JLabel lblEstimatedDeliveryTime = new JLabel("Estimated Delivery Time:");
getContentPane().add(lblEstimatedDeliveryTime, "cell 1 20 2 1,alignx left");
JLabel lblDepartureTime = new JLabel("Departure Time:");
getContentPane().add(lblDepartureTime, "cell 5 20,alignx left");
JLabel lblEstimatedBlocks = new JLabel("Estimated Blocks:");
getContentPane().add(lblEstimatedBlocks, "cell 1 21 2 1,alignx left");
JLabel lblPickedUpTime = new JLabel("Picked Up Time:");
getContentPane().add(lblPickedUpTime, "cell 5 21,alignx left");
JLabel lblQuotedPrice = new JLabel("Quoted Price:");
getContentPane().add(lblQuotedPrice, "cell 1 22 2 1,alignx left");
JLabel lblDeliveredTime = new JLabel("Delivered Time:");
getContentPane().add(lblDeliveredTime, "cell 5 22,alignx left");
JLabel lblBonus = new JLabel("Bonus?");
getContentPane().add(lblBonus, "cell 5 23,alignx left");
JLabel lblTime = new JLabel("Time:" + LocalTime.now().format(DateTimeFormatter.ofPattern("h:mm")));
getContentPane().add(lblTime, "flowx,cell 0 4 8 1,alignx center");
JLabel lblNewLabel = new JLabel("Ticket Info");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblNewLabel, "cell 1 18 2 1,alignx left");
JLabel lblDeliveryInfo_1 = new JLabel("Delivery Info");
lblDeliveryInfo_1.setFont(new Font("Tahoma", Font.BOLD, 12));
getContentPane().add(lblDeliveryInfo_1, "cell 5 18 2 1,alignx left");
JLabel lblPackageId = new JLabel("Package Id:");
getContentPane().add(lblPackageId, "cell 1 19 2 1,alignx left");
JLabel packageId = new JLabel(String.valueOf(delivery.packageID));
getContentPane().add(packageId, "cell 3 19,alignx left");
JLabel lblCourier = new JLabel("Courier:");
getContentPane().add(lblCourier, "cell 5 19,alignx left");
}
} | add event listners for saving
| AcmeCourierSystem/src/view/DeliveryTicketEditor.java | add event listners for saving | <ide><path>cmeCourierSystem/src/view/DeliveryTicketEditor.java
<ide> import javax.swing.JFrame;
<ide> import javax.swing.JLabel;
<ide> import javax.swing.JOptionPane;
<add>import javax.swing.event.ChangeEvent;
<add>import javax.swing.event.ChangeListener;
<ide>
<ide> import com.github.lgooddatepicker.components.DatePickerSettings;
<ide> import com.github.lgooddatepicker.components.DateTimePicker;
<ide> import com.github.lgooddatepicker.components.TimePicker;
<ide> import com.github.lgooddatepicker.components.TimePickerSettings;
<ide> import com.github.lgooddatepicker.components.TimePickerSettings.TimeIncrement;
<add>import com.github.lgooddatepicker.zinternaltools.DateTimeChangeEvent;
<ide>
<ide> import main.Application;
<ide> import main.CourierSystem;
<ide> JComboBox<Employee> cbCourier;
<ide> DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("h:mm a");
<ide> private boolean saved = false;
<add>
<add> private ChangeListener windowHasChanges = new ChangeListener() {
<add> @Override
<add> public void stateChanged(ChangeEvent e) {
<add> saved = false;
<add> }
<add> };
<add>
<add> private ActionListener windowHasChanges2 = new ActionListener() {
<add>
<add> @Override
<add> public void actionPerformed(ActionEvent e) {
<add> saved = false;
<add> }
<add>
<add> };
<ide>
<ide> public DeliveryTicketEditor(Delivery delivery, DeliveryTableModel deliveryTable) {
<ide> super((JFrame) null, "ACME Delivery Ticket Editor", true);
<ide>
<ide> pickupClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
<ide> pickupClient.setSelectedItem(delivery.pickupClient);
<add> pickupClient.addActionListener(windowHasChanges2);
<ide> getContentPane().add(pickupClient, "cell 4 8 2 1,growx");
<ide>
<ide> DatePickerSettings pickupDateSettings = new DatePickerSettings();
<ide> } else {
<ide> pickupEditor.setDateTimePermissive(delivery.requestedPickupTime);
<ide> }
<add> // TODO: ADD PROPER EVENT HERE
<add> pickupEditor.addDateTimeChangeListener(null);
<ide>
<ide> billToPickup = new JCheckBox("", delivery.billToSender);
<add> billToPickup.addChangeListener(windowHasChanges);
<ide> getContentPane().add(billToPickup, "cell 4 11");
<ide>
<ide> deliveryClient = new JComboBox<Client>(CourierSystem.Clients.values().toArray(new Client[0]));
<ide> deliveryClient.setSelectedItem(delivery.deliveryClient);
<add> deliveryClient.addActionListener(windowHasChanges2);
<ide> getContentPane().add(deliveryClient, "cell 4 14 2 1,growx");
<ide>
<ide> billToDeliver = new JCheckBox("", !delivery.billToSender);
<add> billToDeliver.addChangeListener(windowHasChanges);
<ide> getContentPane().add(billToDeliver, "cell 4 16");
<ide>
<ide> cbCourier = new JComboBox<Employee>();
<ide> cbCourier.addItem(e);
<ide> }
<ide> cbCourier.setSelectedItem(delivery.assignedCourier);
<add> cbCourier.addActionListener(windowHasChanges2);
<ide> getContentPane().add(cbCourier, "cell 6 19,growx");
<ide>
<ide> estimatedDeliveryTime = new JLabel(
<ide> deliveredTime.setTime(delivery.actualDeliveryTime != null ? delivery.actualDeliveryTime.toLocalTime() : null);
<ide> getContentPane().add(deliveredTime, "cell 6 22, alignx left");
<ide>
<del> bonusEarned = new JCheckBox("", delivery.bonusEarned);
<del> bonusEarned.setEnabled(false);
<add> bonusEarned = new JCheckBox("", delivery.bonusEarned);
<add> bonusEarned.setEnabled(false);
<ide> getContentPane().add(bonusEarned, "cell 6 23");
<ide>
<ide> JButton btnOk = new JButton("Ok");
<ide> }
<ide>
<ide> private void populateDeliveryInfo() {
<add> saved = false;
<ide> delivery.pickupClient = (Client) pickupClient.getSelectedItem();
<ide> delivery.deliveryClient = (Client) deliveryClient.getSelectedItem();
<ide> delivery.requestedPickupTime = pickupEditor.getDateTimeStrict(); |
|
Java | apache-2.0 | c3daaea1b4062af1480ab62e55329336f8ff392b | 0 | opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development | oscm-app-vmware-service/javasrc/org/oscm/app/vmware/service/VMNotificationService.java | /*******************************************************************************
*
* COPYRIGHT (C) FUJITSU LIMITED - ALL RIGHTS RESERVED.
*
* Creation Date: 2013-05-12
*
*******************************************************************************/
package org.oscm.app.vmware.service;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.oscm.app.vmware.business.trigger.ServiceValidationTask;
import org.oscm.notification.intf.NotificationService;
import org.oscm.notification.vo.VONotification;
import org.oscm.types.enumtypes.UserRoleType;
import org.oscm.vo.VOOrganization;
import org.oscm.vo.VOOrganizationPaymentConfiguration;
import org.oscm.vo.VOParameter;
import org.oscm.vo.VOPaymentType;
import org.oscm.vo.VOService;
import org.oscm.vo.VOServicePaymentConfiguration;
import org.oscm.vo.VOSubscription;
import org.oscm.vo.VOTriggerProcess;
import org.oscm.vo.VOUsageLicense;
import org.oscm.vo.VOUser;
import org.oscm.vo.VOUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebService(serviceName = "VMwareNotificationService", portName = "StubServicePort", targetNamespace = "http://oscm.org/xsd", endpointInterface = "org.oscm.notification.intf.NotificationService")
public class VMNotificationService implements NotificationService {
private final static Logger log = LoggerFactory
.getLogger(VMNotificationService.class);
@Override
public void billingPerformed(String xmlBillingData) {
log.debug("");
}
@Override
public void onActivateProduct(VOTriggerProcess process, VOService product) {
log.debug("product: " + product.getNameToDisplay() + " productId: "
+ product.getServiceId() + " technicalId: "
+ product.getTechnicalId() + " sellerId: "
+ product.getSellerId());
ServiceValidationTask task = new ServiceValidationTask();
task.validate(process, product);
}
@Override
public void onAddRevokeUser(VOTriggerProcess process, String subscriptionId,
List<VOUsageLicense> usersToBeAdded,
List<VOUser> usersToBeRevoked) {
}
@Override
public void onAddSupplier(VOTriggerProcess process, String supplierId) {
log.debug("supplierId: " + supplierId);
}
@Override
public void onDeactivateProduct(VOTriggerProcess process,
VOService product) {
log.debug("product: " + product.getNameToDisplay());
}
@Override
public void onModifySubscription(VOTriggerProcess process,
VOSubscription subscription, List<VOParameter> parameters) {
log.debug("subscriptionId:" + subscription.getSubscriptionId());
}
@Override
public void onRegisterCustomer(VOTriggerProcess process,
VOOrganization organization, VOUserDetails user,
Properties properties) {
log.debug("");
}
@Override
public void onRegisterUserInOwnOrganization(VOTriggerProcess process,
VOUserDetails user, List<UserRoleType> roles,
String marketplaceId) {
log.debug("marketplaceId: " + marketplaceId);
}
@Override
public void onRemoveSupplier(VOTriggerProcess process, String supplierId) {
log.debug("supplierId: " + supplierId);
}
@Override
public void onSaveCustomerPaymentConfiguration(VOTriggerProcess process,
VOOrganizationPaymentConfiguration configuration) {
log.debug("");
}
@Override
public void onSaveDefaultPaymentConfiguration(VOTriggerProcess process,
Set<VOPaymentType> configuration) {
log.debug("");
}
@Override
public void onSaveServiceDefaultPaymentConfiguration(
VOTriggerProcess process, Set<VOPaymentType> configuration) {
log.debug("");
}
@Override
public void onSaveServicePaymentConfiguration(VOTriggerProcess process,
VOServicePaymentConfiguration configuration) {
log.debug("");
}
@Override
public void onSubscribeToProduct(VOTriggerProcess process,
VOSubscription subscription, VOService product,
List<VOUsageLicense> users) {
log.debug("product: " + product.getNameToDisplay());
}
@Override
public void onSubscriptionCreation(VOTriggerProcess process,
VOService product, List<VOUsageLicense> usersToBeAdded,
VONotification notification) {
log.debug("product: " + product.getNameToDisplay());
}
@Override
public void onSubscriptionModification(VOTriggerProcess process,
List<VOParameter> parameter, VONotification notification) {
log.debug("");
}
@Override
public void onSubscriptionTermination(VOTriggerProcess process,
VONotification notification) {
log.debug("");
}
@Override
public void onUnsubscribeFromProduct(VOTriggerProcess process,
String subscriptionId) {
log.debug("subscriptionId: " + subscriptionId);
}
@Override
public void onUpgradeSubscription(VOTriggerProcess process,
VOSubscription subscription, VOService product) {
log.debug("");
}
@Override
public void onCancelAction(@WebParam(name = "actionKey") long arg0) {
log.debug("actionKey: " + arg0);
}
}
| remove trigger notification service for validation of service parameter
when trigger "activate service" is fired. | oscm-app-vmware-service/javasrc/org/oscm/app/vmware/service/VMNotificationService.java | remove trigger notification service for validation of service parameter when trigger "activate service" is fired. | <ide><path>scm-app-vmware-service/javasrc/org/oscm/app/vmware/service/VMNotificationService.java
<del>/*******************************************************************************
<del> *
<del> * COPYRIGHT (C) FUJITSU LIMITED - ALL RIGHTS RESERVED.
<del> *
<del> * Creation Date: 2013-05-12
<del> *
<del> *******************************************************************************/
<del>package org.oscm.app.vmware.service;
<del>
<del>import java.util.List;
<del>import java.util.Properties;
<del>import java.util.Set;
<del>
<del>import javax.jws.WebParam;
<del>import javax.jws.WebService;
<del>
<del>import org.oscm.app.vmware.business.trigger.ServiceValidationTask;
<del>import org.oscm.notification.intf.NotificationService;
<del>import org.oscm.notification.vo.VONotification;
<del>import org.oscm.types.enumtypes.UserRoleType;
<del>import org.oscm.vo.VOOrganization;
<del>import org.oscm.vo.VOOrganizationPaymentConfiguration;
<del>import org.oscm.vo.VOParameter;
<del>import org.oscm.vo.VOPaymentType;
<del>import org.oscm.vo.VOService;
<del>import org.oscm.vo.VOServicePaymentConfiguration;
<del>import org.oscm.vo.VOSubscription;
<del>import org.oscm.vo.VOTriggerProcess;
<del>import org.oscm.vo.VOUsageLicense;
<del>import org.oscm.vo.VOUser;
<del>import org.oscm.vo.VOUserDetails;
<del>import org.slf4j.Logger;
<del>import org.slf4j.LoggerFactory;
<del>
<del>@WebService(serviceName = "VMwareNotificationService", portName = "StubServicePort", targetNamespace = "http://oscm.org/xsd", endpointInterface = "org.oscm.notification.intf.NotificationService")
<del>public class VMNotificationService implements NotificationService {
<del>
<del> private final static Logger log = LoggerFactory
<del> .getLogger(VMNotificationService.class);
<del>
<del> @Override
<del> public void billingPerformed(String xmlBillingData) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onActivateProduct(VOTriggerProcess process, VOService product) {
<del> log.debug("product: " + product.getNameToDisplay() + " productId: "
<del> + product.getServiceId() + " technicalId: "
<del> + product.getTechnicalId() + " sellerId: "
<del> + product.getSellerId());
<del> ServiceValidationTask task = new ServiceValidationTask();
<del> task.validate(process, product);
<del> }
<del>
<del> @Override
<del> public void onAddRevokeUser(VOTriggerProcess process, String subscriptionId,
<del> List<VOUsageLicense> usersToBeAdded,
<del> List<VOUser> usersToBeRevoked) {
<del> }
<del>
<del> @Override
<del> public void onAddSupplier(VOTriggerProcess process, String supplierId) {
<del> log.debug("supplierId: " + supplierId);
<del> }
<del>
<del> @Override
<del> public void onDeactivateProduct(VOTriggerProcess process,
<del> VOService product) {
<del> log.debug("product: " + product.getNameToDisplay());
<del> }
<del>
<del> @Override
<del> public void onModifySubscription(VOTriggerProcess process,
<del> VOSubscription subscription, List<VOParameter> parameters) {
<del> log.debug("subscriptionId:" + subscription.getSubscriptionId());
<del> }
<del>
<del> @Override
<del> public void onRegisterCustomer(VOTriggerProcess process,
<del> VOOrganization organization, VOUserDetails user,
<del> Properties properties) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onRegisterUserInOwnOrganization(VOTriggerProcess process,
<del> VOUserDetails user, List<UserRoleType> roles,
<del> String marketplaceId) {
<del> log.debug("marketplaceId: " + marketplaceId);
<del> }
<del>
<del> @Override
<del> public void onRemoveSupplier(VOTriggerProcess process, String supplierId) {
<del> log.debug("supplierId: " + supplierId);
<del> }
<del>
<del> @Override
<del> public void onSaveCustomerPaymentConfiguration(VOTriggerProcess process,
<del> VOOrganizationPaymentConfiguration configuration) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onSaveDefaultPaymentConfiguration(VOTriggerProcess process,
<del> Set<VOPaymentType> configuration) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onSaveServiceDefaultPaymentConfiguration(
<del> VOTriggerProcess process, Set<VOPaymentType> configuration) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onSaveServicePaymentConfiguration(VOTriggerProcess process,
<del> VOServicePaymentConfiguration configuration) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onSubscribeToProduct(VOTriggerProcess process,
<del> VOSubscription subscription, VOService product,
<del> List<VOUsageLicense> users) {
<del> log.debug("product: " + product.getNameToDisplay());
<del> }
<del>
<del> @Override
<del> public void onSubscriptionCreation(VOTriggerProcess process,
<del> VOService product, List<VOUsageLicense> usersToBeAdded,
<del> VONotification notification) {
<del> log.debug("product: " + product.getNameToDisplay());
<del> }
<del>
<del> @Override
<del> public void onSubscriptionModification(VOTriggerProcess process,
<del> List<VOParameter> parameter, VONotification notification) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onSubscriptionTermination(VOTriggerProcess process,
<del> VONotification notification) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onUnsubscribeFromProduct(VOTriggerProcess process,
<del> String subscriptionId) {
<del> log.debug("subscriptionId: " + subscriptionId);
<del> }
<del>
<del> @Override
<del> public void onUpgradeSubscription(VOTriggerProcess process,
<del> VOSubscription subscription, VOService product) {
<del> log.debug("");
<del> }
<del>
<del> @Override
<del> public void onCancelAction(@WebParam(name = "actionKey") long arg0) {
<del> log.debug("actionKey: " + arg0);
<del> }
<del>
<del>} |
||
Java | epl-1.0 | 928aacb7b561b90dc240eb0633ab92d30e72f1dd | 0 | sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.expression;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.JavascriptEvalUtil;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.ResultIterator;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.birt.data.engine.script.DataExceptionMocker;
import org.eclipse.birt.data.engine.script.JSRowObject;
import org.eclipse.birt.data.engine.script.NEvaluator;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
*
*/
public class ExprEvaluateUtil
{
/**
* @param dataExpr
* @param odiResult
* @param scope
* @param logger
* @return
* @throws BirtException
*/
public static Object evaluateExpression( IBaseExpression dataExpr,
IResultIterator odiResult, Scriptable scope, Logger logger )
throws BirtException
{
Object exprValue = null;
//TODO here the dataExpr should not be null.
//This is only a temporary solution.
if( dataExpr == null )
throw new DataException(ResourceConstants.BAD_DATA_EXPRESSION);
Object handle = dataExpr.getHandle( );
if ( handle instanceof CompiledExpression )
{
CompiledExpression expr = (CompiledExpression) handle;
Object value = evaluateCompiledExpression( expr, odiResult, scope );
try
{
exprValue = DataTypeUtil.convert( value, dataExpr.getDataType( ) );
}
catch ( BirtException e )
{
throw new DataException( ResourceConstants.INCONVERTIBLE_DATATYPE,
new Object[]{
value,
value.getClass( ),
DataType.getClass( dataExpr.getDataType( ) )
} );
}
}
else if ( handle instanceof ConditionalExpression )
{
ConditionalExpression ce = (ConditionalExpression) handle;
Object resultExpr = evaluateExpression( ce.getExpression( ),
odiResult,
scope,
logger );
Object resultOp1 = ce.getOperand1( ) != null
? evaluateExpression( ce.getOperand1( ), odiResult, scope, logger )
: null;
Object resultOp2 = ce.getOperand2( ) != null
? evaluateExpression( ce.getOperand2( ), odiResult, scope, logger )
: null;
String op1Text = ce.getOperand1( ) != null ? ce.getOperand1( )
.getText( ) : null;
String op2Text = ce.getOperand2( ) != null ? ce.getOperand2( )
.getText( ) : null;
exprValue = ScriptEvalUtil.evalConditionalExpr( resultExpr,
ce.getOperator( ),
ScriptEvalUtil.newExprInfo( op1Text, resultOp1 ),
ScriptEvalUtil.newExprInfo( op2Text, resultOp2 ) );
}
else
{
DataException e = new DataException( ResourceConstants.INVALID_EXPR_HANDLE );
logger.logp( Level.FINE,
ResultIterator.class.getName( ),
"getValue",
"Invalid expression handle.",
e );
throw e;
}
// the result might be a DataExceptionMocker.
if ( exprValue instanceof DataExceptionMocker )
{
throw ( (DataExceptionMocker) exprValue ).getCause( );
}
return exprValue;
}
/**
* @param expr
* @param odiResult
* @param scope
* @return
* @throws DataException
*/
public static Object evaluateCompiledExpression( CompiledExpression expr,
IResultIterator odiResult, Scriptable scope ) throws DataException
{
// Special case for DirectColRefExpr: it's faster to directly access
// column value using the Odi IResultIterator.
if ( expr instanceof ColumnReferenceExpression )
{
// Direct column reference
ColumnReferenceExpression colref = (ColumnReferenceExpression) expr;
if ( colref.isIndexed( ) )
{
int idx = colref.getColumnindex( );
// Special case: row[0] refers to internal rowID
if ( idx == 0 )
return new Integer( odiResult.getCurrentResultIndex( ) );
else if ( odiResult.getCurrentResult( ) != null )
return odiResult.getCurrentResult( )
.getFieldValue( idx );
else
return null;
}
else
{
String name = colref.getColumnName( );
// Special case: row._rowPosition refers to internal rowID
if ( JSRowObject.ROW_POSITION.equals( name ) )
return new Integer( odiResult.getCurrentResultIndex( ) );
else if ( odiResult.getCurrentResult( ) != null )
return odiResult.getCurrentResult( )
.getFieldValue( name );
else
return null;
}
}
else
{
Context cx = Context.enter();
try
{
return expr.evaluate( cx, scope );
}
finally
{
Context.exit();
}
}
}
/**
* Evaluate non-compiled expression
*
* @param dataExpr
* @param scope
* @return value of dataExpr
* @throws BirtException
*/
public static Object evaluateRawExpression( IBaseExpression dataExpr,
Scriptable scope ) throws BirtException
{
if ( dataExpr == null )
return null;
try
{
Context cx = Context.enter( );
if ( dataExpr instanceof IScriptExpression )
{
Object value = JavascriptEvalUtil.evaluateRawScript( cx,
scope,
( (IScriptExpression) dataExpr ).getText( ),
"source",
0 );
value = DataTypeUtil.convert( value, dataExpr.getDataType( ) );
return value;
}
else if ( dataExpr instanceof IConditionalExpression )
{
if( dataExpr.getHandle( )!= null )
return new Boolean(((NEvaluator)dataExpr.getHandle( )).evaluate( cx, scope ));
IScriptExpression opr = ( (IConditionalExpression) dataExpr ).getExpression( );
int oper = ( (IConditionalExpression) dataExpr ).getOperator( );
IScriptExpression operand1 = ( (IConditionalExpression) dataExpr ).getOperand1( );
IScriptExpression operand2 = ( (IConditionalExpression) dataExpr ).getOperand2( );
return ScriptEvalUtil.evalConditionalExpr( evaluateRawExpression( opr,
scope ),
oper,
evaluateRawExpression( operand1, scope ),
evaluateRawExpression( operand2, scope ) );
}
else
{
assert false;
return null;
}
}
finally
{
Context.exit( );
}
}
}
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/expression/ExprEvaluateUtil.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.expression;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.JavascriptEvalUtil;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.ResultIterator;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.birt.data.engine.script.DataExceptionMocker;
import org.eclipse.birt.data.engine.script.JSRowObject;
import org.eclipse.birt.data.engine.script.NEvaluator;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
*
*/
public class ExprEvaluateUtil
{
/**
* @param dataExpr
* @param odiResult
* @param scope
* @param logger
* @return
* @throws BirtException
*/
public static Object evaluateExpression( IBaseExpression dataExpr,
IResultIterator odiResult, Scriptable scope, Logger logger )
throws BirtException
{
Object exprValue = null;
//TODO here the dataExpr should not be null.
//This is only a temporary solution.
if( dataExpr == null )
throw new DataException(ResourceConstants.BAD_DATA_EXPRESSION);
Object handle = dataExpr.getHandle( );
if ( handle instanceof CompiledExpression )
{
CompiledExpression expr = (CompiledExpression) handle;
Object value = evaluateCompiledExpression( expr, odiResult, scope );
try
{
exprValue = DataTypeUtil.convert( value, dataExpr.getDataType( ) );
}
catch ( BirtException e )
{
throw new DataException( ResourceConstants.INCONVERTIBLE_DATATYPE,
new Object[]{
value,
value.getClass( ),
DataType.getClass( dataExpr.getDataType( ) )
} );
}
}
else if ( handle instanceof ConditionalExpression )
{
ConditionalExpression ce = (ConditionalExpression) handle;
Object resultExpr = evaluateExpression( ce.getExpression( ),
odiResult,
scope,
logger );
Object resultOp1 = ce.getOperand1( ) != null
? evaluateExpression( ce.getOperand1( ), odiResult, scope, logger )
: null;
Object resultOp2 = ce.getOperand2( ) != null
? evaluateExpression( ce.getOperand2( ), odiResult, scope, logger )
: null;
String op1Text = ce.getOperand1( ) != null ? ce.getOperand1( )
.getText( ) : null;
String op2Text = ce.getOperand2( ) != null ? ce.getOperand2( )
.getText( ) : null;
exprValue = ScriptEvalUtil.evalConditionalExpr( resultExpr,
ce.getOperator( ),
ScriptEvalUtil.newExprInfo( op1Text, resultOp1 ),
ScriptEvalUtil.newExprInfo( op2Text, resultOp2 ) );
}
else
{
DataException e = new DataException( ResourceConstants.INVALID_EXPR_HANDLE );
logger.logp( Level.FINE,
ResultIterator.class.getName( ),
"getValue",
"Invalid expression handle.",
e );
throw e;
}
// the result might be a DataExceptionMocker.
if ( exprValue instanceof DataExceptionMocker )
{
throw ( (DataExceptionMocker) exprValue ).getCause( );
}
return exprValue;
}
/**
* @param expr
* @param odiResult
* @param scope
* @return
* @throws DataException
*/
public static Object evaluateCompiledExpression( CompiledExpression expr,
IResultIterator odiResult, Scriptable scope ) throws DataException
{
// Special case for DirectColRefExpr: it's faster to directly access
// column value using the Odi IResultIterator.
if ( expr instanceof ColumnReferenceExpression )
{
// Direct column reference
ColumnReferenceExpression colref = (ColumnReferenceExpression) expr;
if ( colref.isIndexed( ) )
{
int idx = colref.getColumnindex( );
// Special case: row[0] refers to internal rowID
if ( idx == 0 )
return new Integer( odiResult.getCurrentResultIndex( ) );
else if ( odiResult.getCurrentResult( ) != null )
return odiResult.getCurrentResult( )
.getFieldValue( idx );
else
return null;
}
else
{
String name = colref.getColumnName( );
// Special case: row._rowPosition refers to internal rowID
if ( JSRowObject.ROW_POSITION.equals( name ) )
return new Integer( odiResult.getCurrentResultIndex( ) );
else if ( odiResult.getCurrentResult( ) != null )
return odiResult.getCurrentResult( )
.getFieldValue( name );
else
return null;
}
}
else
{
Context cx = Context.enter();
try
{
return expr.evaluate( cx, scope );
}
finally
{
Context.exit();
}
}
}
/**
* Evaluate non-compiled expression
*
* @param dataExpr
* @param scope
* @return value of dataExpr
* @throws BirtException
*/
public static Object evaluateRawExpression( IBaseExpression dataExpr,
Scriptable scope ) throws BirtException
{
if ( dataExpr == null )
return null;
try
{
Context cx = Context.enter( );
if ( dataExpr instanceof IScriptExpression )
{
Object value = JavascriptEvalUtil.evaluateScript( cx,
scope,
( (IScriptExpression) dataExpr ).getText( ),
"source",
0 );
value = DataTypeUtil.convert( value, dataExpr.getDataType( ) );
return value;
}
else if ( dataExpr instanceof IConditionalExpression )
{
if( dataExpr.getHandle( )!= null )
return new Boolean(((NEvaluator)dataExpr.getHandle( )).evaluate( cx, scope ));
IScriptExpression opr = ( (IConditionalExpression) dataExpr ).getExpression( );
int oper = ( (IConditionalExpression) dataExpr ).getOperator( );
IScriptExpression operand1 = ( (IConditionalExpression) dataExpr ).getOperand1( );
IScriptExpression operand2 = ( (IConditionalExpression) dataExpr ).getOperand2( );
return ScriptEvalUtil.evalConditionalExpr( evaluateRawExpression( opr,
scope ),
oper,
evaluateRawExpression( operand1, scope ),
evaluateRawExpression( operand2, scope ) );
}
else
{
assert false;
return null;
}
}
finally
{
Context.exit( );
}
}
}
| Fix 135492: Map/Highlight didn't take effect for a single data(new date())
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/expression/ExprEvaluateUtil.java | Fix 135492: Map/Highlight didn't take effect for a single data(new date()) | <ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/expression/ExprEvaluateUtil.java
<ide> Context cx = Context.enter( );
<ide> if ( dataExpr instanceof IScriptExpression )
<ide> {
<del> Object value = JavascriptEvalUtil.evaluateScript( cx,
<add> Object value = JavascriptEvalUtil.evaluateRawScript( cx,
<ide> scope,
<ide> ( (IScriptExpression) dataExpr ).getText( ),
<ide> "source", |
|
Java | agpl-3.0 | 023a9cbc354de9fbd729385be9f7bcc65791a357 | 0 | barspi/jPOS-EE,jpos/jPOS-EE,jpos/jPOS-EE,jrfinc/jPOS-EE,jpos/jPOS-EE,jrfinc/jPOS-EE,barspi/jPOS-EE,jrfinc/jPOS-EE,barspi/jPOS-EE | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2019 jPOS Software SRL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.ee;
import org.hibernate.query.criteria.internal.OrderImpl;
import javax.persistence.NoResultException;
import javax.persistence.criteria.*;
import org.hibernate.query.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DBManager<T> {
protected DB db;
private Class<T> clazz;
public DBManager(DB db, Class<T> clazz) {
this.db = db;
this.clazz = clazz;
}
/** Convenience method */
public T byId(Long id) {
return db.session().get(clazz, id);
}
public int getItemCount() {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
Root<T> root = query.from(clazz);
Predicate[] predicates = buildFilters(root);
if (predicates != null)
query.where(predicates);
query.select(criteriaBuilder.count(root));
return db.session().createQuery(query).getSingleResult().intValue();
}
public List<T> getAll(int offset, int limit, Map<String,Boolean> orders) {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);
Root<T> root = query.from(clazz);
List<Order> orderList = new ArrayList<>();
//ORDERS
if (orders != null) {
for (Map.Entry<String, Boolean> entry : orders.entrySet()) {
OrderImpl order = new OrderImpl(root.get(entry.getKey()), entry.getValue());
orderList.add(order);
}
}
Predicate[] predicates = buildFilters(root);
if (predicates != null)
query.where(predicates);
query.select(root);
query.orderBy(orderList);
Query<T> queryImp = db.session().createQuery(query);
if (limit != -1) {
queryImp.setMaxResults(limit);
}
List<T> list = queryImp
.setFirstResult(offset)
.getResultList();
return list;
}
public List<T> getAll() {
return this.getAll(0,-1,null);
}
public T getItemByParam(String param, Object value) {
return getItemByParam(param,value,false);
}
public T getItemByParam(String param, Object value, boolean withFilter) {
try {
CriteriaQuery<T> query = createQueryByParam(param, value, withFilter);
return db.session().createQuery(query).getSingleResult();
} catch (NoResultException nre) {
return null;
}
}
public List<T> getItemsByParam(String param, Object value) {
return getItemsByParam(param,value,false);
}
public List<T> getItemsByParam(String param, Object value, boolean withFilter) {
try {
CriteriaQuery<T> query = createQueryByParam(param, value, withFilter);
return db.session().createQuery(query).list();
} catch (NoResultException nre) {
return null;
}
}
private CriteriaQuery<T> createQueryByParam(String param, Object value, boolean withFilter) {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);
Root<T> root = query.from(clazz);
Predicate equals = criteriaBuilder.equal(root.get(param), value);
query.where(equals);
if (withFilter) {
Predicate[] predicates = buildFilters(root);
if (predicates != null) {
//overrides previous predicates
query.where(criteriaBuilder.and(criteriaBuilder.and(predicates), equals));
}
}
query.select(root);
return query;
}
protected Predicate[] buildFilters(Root<T> root) { return null; }
}
| modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2019 jPOS Software SRL
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.ee;
import org.hibernate.query.criteria.internal.OrderImpl;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DBManager<T> {
protected DB db;
private Class<T> clazz;
public DBManager(DB db, Class<T> clazz) {
this.db = db;
this.clazz = clazz;
}
public int getItemCount() {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
Root<T> root = query.from(clazz);
Predicate[] predicates = buildFilters(root);
if (predicates != null)
query.where(predicates);
query.select(criteriaBuilder.count(root));
return db.session().createQuery(query).getSingleResult().intValue();
}
public List<T> getAll(int offset, int limit, Map<String,Boolean> orders) {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);
Root<T> root = query.from(clazz);
List<Order> orderList = new ArrayList<>();
//ORDERS
if (orders != null) {
for (Map.Entry<String, Boolean> entry : orders.entrySet()) {
OrderImpl order = new OrderImpl(root.get(entry.getKey()), entry.getValue());
orderList.add(order);
}
}
Predicate[] predicates = buildFilters(root);
if (predicates != null)
query.where(predicates);
query.select(root);
query.orderBy(orderList);
Query queryImp = db.session().createQuery(query);
if (limit != -1) {
queryImp.setMaxResults(limit);
}
List<T> list = queryImp
.setFirstResult(offset)
.getResultList();
return list;
}
public List<T> getAll() {
return this.getAll(0,-1,null);
}
public T getItemByParam(String param, Object value) {
return getItemByParam(param,value,false);
}
public T getItemByParam(String param, Object value, boolean withFilter) {
try {
CriteriaQuery<T> query = createQueryByParam(param, value, withFilter);
return db.session().createQuery(query).getSingleResult();
} catch (NoResultException nre) {
return null;
}
}
public List<T> getItemsByParam(String param, Object value) {
return getItemsByParam(param,value,false);
}
public List<T> getItemsByParam(String param, Object value, boolean withFilter) {
try {
CriteriaQuery<T> query = createQueryByParam(param, value, withFilter);
return db.session().createQuery(query).list();
} catch (NoResultException nre) {
return null;
}
}
private CriteriaQuery<T> createQueryByParam(String param, Object value, boolean withFilter) {
CriteriaBuilder criteriaBuilder = db.session().getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);
Root<T> root = query.from(clazz);
Predicate equals = criteriaBuilder.equal(root.get(param), value);
query.where(equals);
if (withFilter) {
Predicate[] predicates = buildFilters(root);
if (predicates != null) {
//overrides previous predicates
query.where(criteriaBuilder.and(criteriaBuilder.and(predicates), equals));
}
}
query.select(root);
return query;
}
protected Predicate[] buildFilters(Root<T> root) { return null; }
}
| DBManager.byId() convenience method, and fix unchecked assignment
| modules/dbsupport/src/main/java/org/jpos/ee/DBManager.java | DBManager.byId() convenience method, and fix unchecked assignment | <ide><path>odules/dbsupport/src/main/java/org/jpos/ee/DBManager.java
<ide> import org.hibernate.query.criteria.internal.OrderImpl;
<ide>
<ide> import javax.persistence.NoResultException;
<del>import javax.persistence.Query;
<ide> import javax.persistence.criteria.*;
<add>import org.hibernate.query.Query;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public DBManager(DB db, Class<T> clazz) {
<ide> this.db = db;
<ide> this.clazz = clazz;
<add> }
<add>
<add> /** Convenience method */
<add> public T byId(Long id) {
<add> return db.session().get(clazz, id);
<ide> }
<ide>
<ide> public int getItemCount() {
<ide> query.where(predicates);
<ide> query.select(root);
<ide> query.orderBy(orderList);
<del> Query queryImp = db.session().createQuery(query);
<add> Query<T> queryImp = db.session().createQuery(query);
<ide> if (limit != -1) {
<ide> queryImp.setMaxResults(limit);
<ide> } |
|
Java | bsd-3-clause | 3fb43f021e0a5674dcbfc8146ed500c22b33fd6b | 0 | krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen | package com.krishagni.catissueplus.core.administrative.services.impl;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import com.krishagni.catissueplus.core.administrative.domain.ContainerType;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainerPosition;
import com.krishagni.catissueplus.core.administrative.domain.factory.StorageContainerErrorCode;
import com.krishagni.catissueplus.core.administrative.domain.factory.StorageContainerFactory;
import com.krishagni.catissueplus.core.administrative.events.ContainerCriteria;
import com.krishagni.catissueplus.core.administrative.events.ContainerHierarchyDetail;
import com.krishagni.catissueplus.core.administrative.events.ContainerQueryCriteria;
import com.krishagni.catissueplus.core.administrative.events.ContainerReplicationDetail;
import com.krishagni.catissueplus.core.administrative.events.ContainerReplicationDetail.DestinationDetail;
import com.krishagni.catissueplus.core.administrative.events.PositionsDetail;
import com.krishagni.catissueplus.core.administrative.events.ReservePositionsOp;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerDetail;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerPositionDetail;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerSummary;
import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary;
import com.krishagni.catissueplus.core.administrative.events.TenantDetail;
import com.krishagni.catissueplus.core.administrative.events.VacantPositionsOp;
import com.krishagni.catissueplus.core.administrative.repository.StorageContainerListCriteria;
import com.krishagni.catissueplus.core.administrative.services.ContainerMapExporter;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionRule;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionStrategy;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionStrategyFactory;
import com.krishagni.catissueplus.core.administrative.services.ScheduledTaskManager;
import com.krishagni.catissueplus.core.administrative.services.StorageContainerService;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpErrorCode;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenInfo;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.biospecimen.repository.SpecimenListCriteria;
import com.krishagni.catissueplus.core.biospecimen.services.SpecimenResolver;
import com.krishagni.catissueplus.core.common.Pair;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.RollbackTransaction;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.errors.ErrorCode;
import com.krishagni.catissueplus.core.common.errors.ErrorType;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.ExportedFileDetail;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.LabelGenerator;
import com.krishagni.catissueplus.core.common.service.ObjectStateParamsResolver;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.de.domain.Filter;
import com.krishagni.catissueplus.core.de.domain.SavedQuery;
import com.krishagni.catissueplus.core.de.events.ExecuteQueryEventOp;
import com.krishagni.catissueplus.core.de.events.QueryDataExportResult;
import com.krishagni.catissueplus.core.de.services.QueryService;
import com.krishagni.catissueplus.core.de.services.SavedQueryErrorCode;
import com.krishagni.catissueplus.core.exporter.domain.ExportJob;
import com.krishagni.catissueplus.core.exporter.services.ExportService;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import edu.common.dynamicextensions.query.WideRowMode;
public class StorageContainerServiceImpl implements StorageContainerService, ObjectStateParamsResolver, InitializingBean {
private static final Log logger = LogFactory.getLog(StorageContainerServiceImpl.class);
private DaoFactory daoFactory;
private com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory;
private StorageContainerFactory containerFactory;
private ContainerMapExporter mapExporter;
private LabelGenerator nameGenerator;
private SpecimenResolver specimenResolver;
private ContainerSelectionStrategyFactory selectionStrategyFactory;
private ScheduledTaskManager taskManager;
private QueryService querySvc;
private ExportService exportSvc;
public DaoFactory getDaoFactory() {
return daoFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
public void setDeDaoFactory(com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory) {
this.deDaoFactory = deDaoFactory;
}
public StorageContainerFactory getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(StorageContainerFactory containerFactory) {
this.containerFactory = containerFactory;
}
public void setMapExporter(ContainerMapExporter mapExporter) {
this.mapExporter = mapExporter;
}
public void setNameGenerator(LabelGenerator nameGenerator) {
this.nameGenerator = nameGenerator;
}
public void setSpecimenResolver(SpecimenResolver specimenResolver) {
this.specimenResolver = specimenResolver;
}
public void setSelectionStrategyFactory(ContainerSelectionStrategyFactory selectionStrategyFactory) {
this.selectionStrategyFactory = selectionStrategyFactory;
}
public void setTaskManager(ScheduledTaskManager taskManager) {
this.taskManager = taskManager;
}
public void setQuerySvc(QueryService querySvc) {
this.querySvc = querySvc;
}
public void setExportSvc(ExportService exportSvc) {
this.exportSvc = exportSvc;
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getStorageContainers(RequestEvent<StorageContainerListCriteria> req) {
try {
StorageContainerListCriteria crit = addContainerListCriteria(req.getPayload());
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getStorageContainers(crit);
List<StorageContainerSummary> result = StorageContainerSummary.from(containers, crit.includeChildren());
setStoredSpecimensCount(crit, result);
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getStorageContainersCount(RequestEvent<StorageContainerListCriteria> req) {
try {
StorageContainerListCriteria crit = addContainerListCriteria(req.getPayload());
return ResponseEvent.response(daoFactory.getStorageContainerDao().getStorageContainersCount(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> getStorageContainer(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
StorageContainerDetail detail = StorageContainerDetail.from(container);
if (req.getPayload().includeStats()) {
detail.setSpecimensByType(daoFactory.getStorageContainerDao().getSpecimensCountByType(detail.getId()));
}
return ResponseEvent.response(detail);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> getOccupiedPositions(RequestEvent<Long> req) {
try {
StorageContainer container = getContainer(req.getPayload(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenInfo>> getSpecimens(RequestEvent<SpecimenListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().ancestorContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
SpecimenListCriteria crit = addSiteCpRestrictions(req.getPayload(), container);
List<Specimen> specimens = daoFactory.getStorageContainerDao().getSpecimens(crit, !container.isDimensionless());
return ResponseEvent.response(SpecimenInfo.from(specimens));
}
@Override
@PlusTransactional
public ResponseEvent<Long> getSpecimensCount(RequestEvent<SpecimenListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().ancestorContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
SpecimenListCriteria crit = addSiteCpRestrictions(req.getPayload(), container);
Long count = daoFactory.getStorageContainerDao().getSpecimensCount(crit);
return ResponseEvent.response(count);
}
@Override
@PlusTransactional
public ResponseEvent<QueryDataExportResult> getSpecimensReport(RequestEvent<ContainerQueryCriteria> req) {
ContainerQueryCriteria crit = req.getPayload();
StorageContainer container = getContainer(crit.getId(), crit.getName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
Integer queryId = ConfigUtil.getInstance().getIntSetting("common", "cont_spmns_report_query", -1);
if (queryId == -1) {
return ResponseEvent.userError(StorageContainerErrorCode.SPMNS_RPT_NOT_CONFIGURED);
}
SavedQuery query = deDaoFactory.getSavedQueryDao().getQuery(queryId.longValue());
if (query == null) {
return ResponseEvent.userError(SavedQueryErrorCode.NOT_FOUND, queryId);
}
return new ResponseEvent<>(exportResult(container, query));
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> createStorageContainer(RequestEvent<StorageContainerDetail> req) {
try {
return ResponseEvent.response(StorageContainerDetail.from(createStorageContainer(null, req.getPayload())));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> updateStorageContainer(RequestEvent<StorageContainerDetail> req) {
return updateStorageContainer(req, false);
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> patchStorageContainer(RequestEvent<StorageContainerDetail> req) {
return updateStorageContainer(req, true);
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> isAllowed(RequestEvent<TenantDetail> req) {
try {
TenantDetail detail = req.getPayload();
StorageContainer container = getContainer(detail.getContainerId(), detail.getContainerName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
CollectionProtocol cp = new CollectionProtocol();
cp.setId(detail.getCpId());
String specimenClass = detail.getSpecimenClass();
String type = detail.getSpecimenType();
boolean isAllowed = container.canContainSpecimen(cp, specimenClass, type);
if (!isAllowed) {
return ResponseEvent.userError(
StorageContainerErrorCode.CANNOT_HOLD_SPECIMEN,
container.getName(),
Specimen.getDesc(specimenClass, type));
} else {
return ResponseEvent.response(isAllowed);
}
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ExportedFileDetail> exportMap(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DIMLESS_NO_MAP, container.getName());
}
File file = mapExporter.exportToFile(container);
return ResponseEvent.response(new ExportedFileDetail(container.getName(), file));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> assignPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail op = req.getPayload();
StorageContainer container = getContainer(op.getContainerId(), op.getContainerName());
List<StorageContainerPosition> positions = op.getPositions().stream()
.map(posDetail -> createPosition(container, posDetail, op.getVacateOccupant()))
.collect(Collectors.toList());
container.assignPositions(positions, op.getVacateOccupant());
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getDependentEntities(RequestEvent<Long> req) {
try {
StorageContainer existing = getContainer(req.getPayload(), null);
return ResponseEvent.response(existing.getDependentEntities());
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> deleteStorageContainers(RequestEvent<BulkDeleteEntityOp> req) {
try {
Set<Long> containerIds = req.getPayload().getIds();
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getByIds(containerIds);
if (containerIds.size() != containers.size()) {
containers.forEach(container -> containerIds.remove(container.getId()));
throw OpenSpecimenException.userError(StorageContainerErrorCode.NOT_FOUND, containerIds, containerIds.size());
}
List<StorageContainer> ancestors = getAncestors(containers);
ancestors.forEach(AccessCtrlMgr.getInstance()::ensureDeleteContainerRights);
ancestors.forEach(StorageContainer::delete);
//
// returning summary of all containers given by user instead of only ancestor containers
//
return ResponseEvent.response(StorageContainerSummary.from(containers));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> replicateStorageContainer(RequestEvent<ContainerReplicationDetail> req) {
try {
ContainerReplicationDetail replDetail = req.getPayload();
StorageContainer srcContainer = getContainer(
replDetail.getSourceContainerId(),
replDetail.getSourceContainerName(),
null,
StorageContainerErrorCode.SRC_ID_OR_NAME_REQ);
for (DestinationDetail dest : replDetail.getDestinations()) {
replicateContainer(srcContainer, dest);
}
return ResponseEvent.response(true);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> createContainerHierarchy(RequestEvent<ContainerHierarchyDetail> req) {
ContainerHierarchyDetail input = req.getPayload();
List<StorageContainer> containers = new ArrayList<>();
try {
StorageContainer container = containerFactory.createStorageContainer("dummyName", input);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
container.validateRestrictions();
StorageContainer parentContainer = container.getParentContainer();
if (parentContainer != null && !parentContainer.hasFreePositionsForReservation(input.getNumOfContainers())) {
return ResponseEvent.userError(StorageContainerErrorCode.NO_FREE_SPACE, parentContainer.getName());
}
boolean setCapacity = true;
for (int i = 1; i <= input.getNumOfContainers(); i++) {
StorageContainer cloned = null;
if (i == 1) {
cloned = container;
} else {
cloned = container.copy();
setPosition(cloned);
}
generateName(cloned);
ensureUniqueConstraints(null, cloned);
if (cloned.isStoreSpecimenEnabled() && setCapacity) {
cloned.setFreezerCapacity();
setCapacity = false;
}
createContainerHierarchy(cloned.getType().getCanHold(), cloned);
daoFactory.getStorageContainerDao().saveOrUpdate(cloned);
containers.add(cloned);
}
return ResponseEvent.response(StorageContainerDetail.from(containers));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> createMultipleContainers(RequestEvent<List<StorageContainerDetail>> req) {
try {
List<StorageContainerSummary> result = new ArrayList<>();
for (StorageContainerDetail detail : req.getPayload()) {
if (StringUtils.isNotBlank(detail.getTypeName()) || detail.getTypeId() != null) {
detail.setName("dummy");
}
StorageContainer container = containerFactory.createStorageContainer(detail);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
if (container.getType() != null) {
generateName(container);
}
ensureUniqueConstraints(null, container);
container.validateRestrictions();
daoFactory.getStorageContainerDao().saveOrUpdate(container);
result.add(StorageContainerSummary.from(container));
}
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> blockPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail opDetail = req.getPayload();
if (CollectionUtils.isEmpty(opDetail.getPositions())) {
return ResponseEvent.response(Collections.emptyList());
}
StorageContainer container = getContainer(opDetail.getContainerId(), opDetail.getContainerName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DL_POS_BLK_NP, container.getName());
}
List<StorageContainerPosition> positions = opDetail.getPositions().stream()
.map(detail -> container.createPosition(detail.getPosOne(), detail.getPosTwo()))
.collect(Collectors.toList());
container.blockPositions(positions);
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> unblockPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail opDetail = req.getPayload();
if (CollectionUtils.isEmpty(opDetail.getPositions())) {
return ResponseEvent.response(Collections.emptyList());
}
StorageContainer container = getContainer(opDetail.getContainerId(), opDetail.getContainerName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DL_POS_BLK_NP, container.getName());
}
List<StorageContainerPosition> positions = opDetail.getPositions().stream()
.map(detail -> container.createPosition(detail.getPosOne(), detail.getPosTwo()))
.collect(Collectors.toList());
container.unblockPositions(positions);
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageLocationSummary>> reservePositions(RequestEvent<ReservePositionsOp> req) {
long t1 = System.currentTimeMillis();
try {
ReservePositionsOp op = req.getPayload();
if (StringUtils.isNotBlank(op.getReservationToCancel())) {
cancelReservation(new RequestEvent<>(op.getReservationToCancel()));
}
Long cpId = op.getCpId();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND, cpId);
}
if (StringUtils.isBlank(cp.getContainerSelectionStrategy())) {
return ResponseEvent.response(Collections.emptyList());
}
ContainerSelectionStrategy strategy = selectionStrategyFactory.getStrategy(cp.getContainerSelectionStrategy());
if (strategy == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_CONT_SEL_STRATEGY, cp.getContainerSelectionStrategy());
}
Set<Pair<Long, Long>> allowedSiteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps(cpId);
if (allowedSiteCps != null && allowedSiteCps.isEmpty()) {
return ResponseEvent.response(Collections.emptyList());
}
Set<Pair<Long, Long>> reqSiteCps = getRequiredSiteCps(allowedSiteCps, Collections.singleton(cpId));
if (CollectionUtils.isEmpty(reqSiteCps)) {
return ResponseEvent.response(Collections.emptyList());
}
String reservationId = StorageContainer.getReservationId();
Date reservationTime = Calendar.getInstance().getTime();
List<StorageContainerPosition> reservedPositions = new ArrayList<>();
for (ContainerCriteria criteria : op.getCriteria()) {
criteria.siteCps(reqSiteCps);
if (StringUtils.isNotBlank(criteria.ruleName())) {
ContainerSelectionRule rule = selectionStrategyFactory.getRule(criteria.ruleName());
if (rule == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_CONT_SEL_RULE, criteria.ruleName());
}
criteria.rule(rule);
}
boolean allAllocated = false;
while (!allAllocated) {
long t2 = System.currentTimeMillis();
StorageContainer container = strategy.getContainer(criteria, cp.getAliquotsInSameContainer());
if (container == null) {
ResponseEvent<List<StorageLocationSummary>> resp = new ResponseEvent<>(Collections.emptyList());
resp.setRollback(true);
return resp;
}
int numPositions = criteria.minFreePositions();
if (numPositions <= 0) {
numPositions = 1;
}
List<StorageContainerPosition> positions = container.reservePositions(reservationId, reservationTime, numPositions);
reservedPositions.addAll(positions);
numPositions -= positions.size();
if (numPositions == 0) {
allAllocated = true;
} else {
criteria.minFreePositions(numPositions);
}
System.err.println("***** Allocation time: " + (System.currentTimeMillis() - t2) + " ms");
}
}
return ResponseEvent.response(StorageLocationSummary.from(reservedPositions));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
} finally {
System.err.println("***** Call time: " + (System.currentTimeMillis() - t1) + " ms");
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> cancelReservation(RequestEvent<String> req) {
try {
int vacatedPositions = daoFactory.getStorageContainerDao()
.deleteReservedPositions(Collections.singletonList(req.getPayload()));
return ResponseEvent.response(vacatedPositions);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerSummary> getAncestorsHierarchy(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
StorageContainerSummary summary = null;
if (container.getParentContainer() == null) {
summary = new StorageContainerSummary();
summary.setId(container.getId());
summary.setName(container.getName());
summary.setNoOfRows(container.getNoOfRows());
summary.setNoOfColumns(container.getNoOfColumns());
} else {
summary = daoFactory.getStorageContainerDao().getAncestorsHierarchy(container.getId());
}
return ResponseEvent.response(summary);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getChildContainers(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.response(Collections.emptyList());
} else {
return ResponseEvent.response(daoFactory.getStorageContainerDao()
.getChildContainers(container.getId(), container.getNoOfColumns()));
}
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getDescendantContainers(RequestEvent<StorageContainerListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().parentContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getDescendantContainers(req.getPayload());
return ResponseEvent.response(StorageContainerSummary.from(containers));
}
@Override
@RollbackTransaction
public ResponseEvent<List<StorageLocationSummary>> getVacantPositions(RequestEvent<VacantPositionsOp> req) {
try {
VacantPositionsOp detail = req.getPayload();
StorageContainer container = getContainer(detail.getContainerId(), detail.getContainerName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
int numPositions = detail.getRequestedPositions();
if (numPositions <= 0) {
numPositions = 1;
}
List<StorageContainerPosition> vacantPositions = new ArrayList<>();
for (int i = 0; i < numPositions; ++i) {
StorageContainerPosition position = null;
if (i == 0) {
if (StringUtils.isNotBlank(detail.getStartRow()) && StringUtils.isNotBlank(detail.getStartColumn())) {
position = container.nextAvailablePosition(detail.getStartRow(), detail.getStartColumn());
} else if (detail.getStartPosition() > 0) {
position = container.nextAvailablePosition(detail.getStartPosition());
} else {
position = container.nextAvailablePosition();
}
} else {
position = container.nextAvailablePosition(true);
}
if (position == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
container.addPosition(position);
vacantPositions.add(position);
}
return ResponseEvent.response(
vacantPositions.stream().map(StorageLocationSummary::from).collect(Collectors.toList()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
public StorageContainer createStorageContainer(StorageContainer base, StorageContainerDetail input) {
StorageContainer container = containerFactory.createStorageContainer(base, input);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
ensureUniqueConstraints(null, container);
container.validateRestrictions();
if (container.isStoreSpecimenEnabled()) {
container.setFreezerCapacity();
}
if (container.getPosition() != null) {
container.getPosition().occupy();
}
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return container;
}
@Override
public String getObjectName() {
return "container";
}
@Override
@PlusTransactional
public Map<String, Object> resolve(String key, Object value) {
if (key.equals("id")) {
value = Long.valueOf(value.toString());
}
return daoFactory.getStorageContainerDao().getContainerIds(key, value);
}
@Override
public void afterPropertiesSet() throws Exception {
taskManager.scheduleWithFixedDelay(
new Runnable() {
@Override
@PlusTransactional
public void run() {
try {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -5);
int count = daoFactory.getStorageContainerDao().deleteReservedPositionsOlderThan(cal.getTime());
if (count > 0) {
logger.info(String.format("Cleaned up %d stale container slot reservations", count));
}
} catch (Exception e) {
logger.error("Error deleting older reserved container slots", e);
}
}
}, 5
);
exportSvc.registerObjectsGenerator("storageContainer", this::getContainersGenerator);
}
private StorageContainerListCriteria addContainerListCriteria(StorageContainerListCriteria crit) {
Set<Pair<Long, Long>> allowedSiteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps();
if (allowedSiteCps != null && allowedSiteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
if (CollectionUtils.isNotEmpty(crit.cpIds())) {
allowedSiteCps = getRequiredSiteCps(allowedSiteCps, crit.cpIds());
if (allowedSiteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
return crit.siteCps(allowedSiteCps);
}
private Set<Pair<Long, Long>> getRequiredSiteCps(Set<Pair<Long, Long>> allowedSiteCps, Set<Long> cpIds) {
Set<Pair<Long, Long>> reqSiteCps = daoFactory.getCollectionProtocolDao().getSiteCps(cpIds);
if (allowedSiteCps == null) {
allowedSiteCps = reqSiteCps;
} else {
allowedSiteCps = getSiteCps(allowedSiteCps, reqSiteCps);
}
return allowedSiteCps;
}
private Set<Pair<Long, Long>> getSiteCps(Set<Pair<Long, Long>> allowed, Set<Pair<Long, Long>> required) {
Set<Pair<Long, Long>> result = new HashSet<>();
for (Pair<Long, Long> reqSiteCp : required) {
for (Pair<Long, Long> allowedSiteCp : allowed) {
if (!allowedSiteCp.first().equals(reqSiteCp.first())) {
continue;
}
if (allowedSiteCp.second() != null && !allowedSiteCp.second().equals(reqSiteCp.second())) {
continue;
}
result.add(reqSiteCp);
}
}
return result;
}
private void setStoredSpecimensCount(StorageContainerListCriteria crit, List<StorageContainerSummary> containers) {
if (!crit.includeStat() || !crit.topLevelContainers()) {
return;
}
List<Long> containerIds = containers.stream().map(StorageContainerSummary::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(containerIds)) {
return;
}
Map<Long, Integer> countMap = daoFactory.getStorageContainerDao().getRootContainerSpecimensCount(containerIds);
containers.forEach(c -> c.setStoredSpecimens(countMap.get(c.getId())));
}
private StorageContainer getContainer(ContainerQueryCriteria crit) {
return getContainer(crit.getId(), crit.getName(), crit.getBarcode());
}
private StorageContainer getContainer(Long id, String name) {
return getContainer(id, name, null);
}
private StorageContainer getContainer(Long id, String name, String barcode) {
return getContainer(id, name, barcode, StorageContainerErrorCode.ID_NAME_OR_BARCODE_REQ);
}
private StorageContainer getContainer(Long id, String name, String barcode, ErrorCode requiredErrCode) {
StorageContainer container = null;
Object key = null;
if (id != null) {
container = daoFactory.getStorageContainerDao().getById(id);
key = id;
} else {
if (StringUtils.isNotBlank(name)) {
container = daoFactory.getStorageContainerDao().getByName(name);
key = name;
}
if (container == null && StringUtils.isNotBlank(barcode)) {
container = daoFactory.getStorageContainerDao().getByBarcode(barcode);
key = barcode;
}
}
if (key == null) {
throw OpenSpecimenException.userError(requiredErrCode);
} else if (container == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NOT_FOUND, key, 1);
}
return container;
}
private ResponseEvent<StorageContainerDetail> updateStorageContainer(RequestEvent<StorageContainerDetail> req, boolean partial) {
try {
StorageContainerDetail input = req.getPayload();
StorageContainer existing = getContainer(input.getId(), input.getName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(existing);
input.setId(existing.getId());
StorageContainer container = null;
if (partial) {
container = containerFactory.createStorageContainer(existing, input);
} else {
container = containerFactory.createStorageContainer(input);
}
ensureUniqueConstraints(existing, container);
existing.update(container);
daoFactory.getStorageContainerDao().saveOrUpdate(existing, true);
return ResponseEvent.response(StorageContainerDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
private void ensureUniqueConstraints(StorageContainer existing, StorageContainer newContainer) {
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
if (!isUniqueName(existing, newContainer)) {
ose.addError(StorageContainerErrorCode.DUP_NAME, newContainer.getName());
}
if (!isUniqueBarcode(existing, newContainer)) {
ose.addError(StorageContainerErrorCode.DUP_BARCODE);
}
ose.checkAndThrow();
}
private boolean isUniqueName(StorageContainer existingContainer, StorageContainer newContainer) {
if (existingContainer != null && existingContainer.getName().equals(newContainer.getName())) {
return true;
}
return isUniqueName(newContainer.getName());
}
private boolean isUniqueName(String name) {
StorageContainer container = daoFactory.getStorageContainerDao().getByName(name);
return container == null;
}
private boolean isUniqueBarcode(StorageContainer existingContainer, StorageContainer newContainer) {
if (StringUtils.isBlank(newContainer.getBarcode())) {
return true;
}
if (existingContainer != null && newContainer.getBarcode().equals(existingContainer.getBarcode())) {
return true;
}
StorageContainer container = daoFactory.getStorageContainerDao().getByBarcode(newContainer.getBarcode());
return container == null;
}
private StorageContainerPosition createPosition(StorageContainer container, StorageContainerPositionDetail pos, boolean vacateOccupant) {
if (StringUtils.isBlank(pos.getPosOne()) ^ StringUtils.isBlank(pos.getPosTwo())) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_POS, container.getName(), pos.getPosOne(), pos.getPosTwo());
}
String entityType = pos.getOccuypingEntity();
if (StringUtils.isBlank(entityType)) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INVALID_ENTITY_TYPE, "none");
}
if (StringUtils.isBlank(pos.getOccupyingEntityName()) && pos.getOccupyingEntityId() == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.OCCUPYING_ENTITY_ID_OR_NAME_REQUIRED);
}
if (entityType.equalsIgnoreCase("specimen")) {
return createSpecimenPosition(container, pos, vacateOccupant);
} else if (entityType.equalsIgnoreCase("container")) {
return createChildContainerPosition(container, pos);
}
throw OpenSpecimenException.userError(StorageContainerErrorCode.INVALID_ENTITY_TYPE, entityType);
}
private StorageContainerPosition createSpecimenPosition(
StorageContainer container,
StorageContainerPositionDetail pos,
boolean vacateOccupant) {
Specimen specimen = getSpecimen(pos);
AccessCtrlMgr.getInstance().ensureCreateOrUpdateSpecimenRights(specimen, false);
StorageContainerPosition position = null;
if (!container.isDimensionless() && (StringUtils.isBlank(pos.getPosOne()) || StringUtils.isBlank(pos.getPosTwo()))) {
position = new StorageContainerPosition();
position.setOccupyingSpecimen(specimen);
return position;
}
if (!container.canContain(specimen)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.CANNOT_HOLD_SPECIMEN, container.getName(), specimen.getLabelOrDesc());
}
if (!container.canSpecimenOccupyPosition(specimen.getId(), pos.getPosOne(), pos.getPosTwo(), vacateOccupant)) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
position = container.createPosition(pos.getPosOne(), pos.getPosTwo());
position.setOccupyingSpecimen(specimen);
return position;
}
private Specimen getSpecimen(StorageContainerPositionDetail pos) {
return specimenResolver.getSpecimen(
pos.getOccupyingEntityId(),
pos.getCpShortTitle(),
pos.getOccupyingEntityName()
);
}
private SpecimenListCriteria addSiteCpRestrictions(SpecimenListCriteria crit, StorageContainer container) {
Set<Pair<Long, Long>> siteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps();
if (siteCps != null) {
List<Pair<Long, Long>> contSiteCps = siteCps.stream()
.filter(siteCp -> siteCp.first().equals(container.getSite().getId()))
.collect(Collectors.toList());
crit.siteCps(contSiteCps);
}
return crit;
}
private StorageContainerPosition createChildContainerPosition(
StorageContainer container,
StorageContainerPositionDetail pos) {
StorageContainer childContainer = getContainer(pos.getOccupyingEntityId(), pos.getOccupyingEntityName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(childContainer);
if (!container.canContain(childContainer)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.CANNOT_HOLD_CONTAINER,
container.getName(),
childContainer.getName());
}
if (!container.canContainerOccupyPosition(childContainer.getId(), pos.getPosOne(), pos.getPosTwo())) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
StorageContainerPosition position = container.createPosition(pos.getPosOne(), pos.getPosTwo());
position.setOccupyingContainer(childContainer);
return position;
}
private void replicateContainer(StorageContainer srcContainer, DestinationDetail dest) {
StorageContainerDetail detail = new StorageContainerDetail();
detail.setName(dest.getName());
detail.setSiteName(dest.getSiteName());
StorageLocationSummary storageLocation = new StorageLocationSummary();
storageLocation.setId(dest.getParentContainerId());
storageLocation.setName(dest.getParentContainerName());
storageLocation.setPositionX(dest.getPosOne());
storageLocation.setPositionY(dest.getPosTwo());
storageLocation.setPosition(dest.getPosition());
detail.setStorageLocation(storageLocation);
createStorageContainer(getContainerCopy(srcContainer), detail);
}
private void createContainerHierarchy(ContainerType containerType, StorageContainer parentContainer) {
if (containerType == null) {
return;
}
StorageContainer container = containerFactory.createStorageContainer("dummyName", containerType, parentContainer);
int noOfContainers = parentContainer.getNoOfRows() * parentContainer.getNoOfColumns();
boolean setCapacity = true;
for (int i = 1; i <= noOfContainers; i++) {
StorageContainer cloned = null;
if (i == 1) {
cloned = container;
} else {
cloned = container.copy();
setPosition(cloned);
}
generateName(cloned);
parentContainer.addChildContainer(cloned);
if (cloned.isStoreSpecimenEnabled() && setCapacity) {
cloned.setFreezerCapacity();
setCapacity = false;
}
createContainerHierarchy(containerType.getCanHold(), cloned);
}
}
private List<StorageContainer> getAncestors(List<StorageContainer> containers) {
Set<Long> descContIds = containers.stream()
.flatMap(c -> c.getDescendentContainers().stream().filter(d -> !d.equals(c)))
.map(StorageContainer::getId)
.collect(Collectors.toSet());
return containers.stream()
.filter(c -> !descContIds.contains(c.getId()))
.collect(Collectors.toList());
}
private void generateName(StorageContainer container) {
ContainerType type = container.getType();
String name = nameGenerator.generateLabel(type.getNameFormat(), container);
if (StringUtils.isBlank(name)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.INCORRECT_NAME_FMT,
type.getNameFormat(),
type.getName());
}
container.setName(name);
}
private void setPosition(StorageContainer container) {
StorageContainer parentContainer = container.getParentContainer();
if (parentContainer == null) {
return;
}
StorageContainerPosition position = parentContainer.nextAvailablePosition(true);
if (position == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, parentContainer.getName());
}
position.setOccupyingContainer(container);
container.setPosition(position);
}
private StorageContainer getContainerCopy(StorageContainer source) {
StorageContainer copy = new StorageContainer();
copy.setTemperature(source.getTemperature());
copy.setNoOfColumns(source.getNoOfColumns());
copy.setNoOfRows(source.getNoOfRows());
copy.setColumnLabelingScheme(source.getColumnLabelingScheme());
copy.setRowLabelingScheme(source.getRowLabelingScheme());
copy.setComments(source.getComments());
copy.setAllowedSpecimenClasses(new HashSet<String>(source.getAllowedSpecimenClasses()));
copy.setAllowedSpecimenTypes(new HashSet<String>(source.getAllowedSpecimenTypes()));
copy.setAllowedCps(new HashSet<CollectionProtocol>(source.getAllowedCps()));
copy.setCompAllowedSpecimenClasses(copy.computeAllowedSpecimenClasses());
copy.setCompAllowedSpecimenTypes(copy.computeAllowedSpecimenTypes());
copy.setCompAllowedCps(copy.computeAllowedCps());
copy.setStoreSpecimenEnabled(source.isStoreSpecimenEnabled());
copy.setCreatedBy(AuthUtil.getCurrentUser());
return copy;
}
private QueryDataExportResult exportResult(final StorageContainer container, SavedQuery query) {
Filter filter = new Filter();
filter.setField("Specimen.specimenPosition.allAncestors.ancestorId");
filter.setOp(Filter.Op.EQ);
filter.setValues(new String[] { container.getId().toString() });
ExecuteQueryEventOp execReportOp = new ExecuteQueryEventOp();
execReportOp.setDrivingForm("Participant");
execReportOp.setAql(query.getAql(new Filter[] { filter }));
execReportOp.setWideRowMode(WideRowMode.DEEP.name());
execReportOp.setRunType("Export");
return querySvc.exportQueryData(execReportOp, new QueryService.ExportProcessor() {
@Override
public String filename() {
return "container_" + container.getId() + "_" + UUID.randomUUID().toString();
}
@Override
public void headers(OutputStream out) {
Map<String, String> headers = new LinkedHashMap<String, String>() {{
String notSpecified = msg("common_not_specified");
put(msg("container_name"), container.getName());
put(msg("container_site"), container.getSite().getName());
if (container.getParentContainer() != null) {
put(msg("container_parent_container"), container.getParentContainer().getName());
}
if (container.getType() != null) {
put(msg("container_type"), container.getType().getName());
}
put("", ""); // blank line
}};
Utility.writeKeyValuesToCsv(out, headers);
}
});
}
private Function<ExportJob, List<? extends Object>> getContainersGenerator() {
return new Function<ExportJob, List<? extends Object>>() {
private boolean loadTopLevelContainers = true;
private boolean endOfContainers;
private int startAt;
private StorageContainerListCriteria topLevelCrit;
private StorageContainerListCriteria descendantsCrit;
private List<StorageContainerDetail> topLevelContainers = new ArrayList<>();
@Override
public List<StorageContainerDetail> apply(ExportJob job) {
if (endOfContainers) {
return Collections.emptyList();
}
if (topLevelContainers.isEmpty()) {
if (topLevelCrit == null) {
topLevelCrit = new StorageContainerListCriteria().topLevelContainers(true).ids(job.getRecordIds());
addContainerListCriteria(topLevelCrit);
}
if (loadTopLevelContainers) {
topLevelContainers = getContainers(topLevelCrit.startAt(startAt));
startAt += topLevelContainers.size();
loadTopLevelContainers = CollectionUtils.isEmpty(job.getRecordIds());
}
}
if (topLevelContainers.isEmpty()) {
endOfContainers = true;
return Collections.emptyList();
}
if (descendantsCrit == null) {
descendantsCrit = new StorageContainerListCriteria()
.siteCps(topLevelCrit.siteCps()).maxResults(100000);
}
StorageContainerDetail topLevelContainer = topLevelContainers.remove(0);
descendantsCrit.parentContainerId(topLevelContainer.getId());
List<StorageContainer> descendants = daoFactory.getStorageContainerDao().getDescendantContainers(descendantsCrit);
Map<Long, List<StorageContainer>> childContainersMap = new HashMap<>();
for (StorageContainer container : descendants) {
Long parentId = container.getParentContainer() == null ? null : container.getParentContainer().getId();
List<StorageContainer> childContainers = childContainersMap.get(parentId);
if (childContainers == null) {
childContainers = new ArrayList<>();
childContainersMap.put(parentId, childContainers);
}
childContainers.add(container);
}
List<StorageContainerDetail> workList = new ArrayList<>();
workList.addAll(toDetailList(childContainersMap.get(null)));
List<StorageContainerDetail> result = new ArrayList<>();
while (!workList.isEmpty()) {
StorageContainerDetail containerDetail = workList.remove(0);
result.add(containerDetail);
List<StorageContainer> childContainers = childContainersMap.get(containerDetail.getId());
if (childContainers != null) {
workList.addAll(0, toDetailList(childContainers));
}
}
return result;
}
private List<StorageContainerDetail> getContainers(StorageContainerListCriteria crit) {
return toDetailList(daoFactory.getStorageContainerDao().getStorageContainers(crit));
}
private List<StorageContainerDetail> toDetailList(List<StorageContainer> containers) {
return containers.stream()
.sorted((c1, c2) -> {
if (c1.getPosition() == null && c2.getPosition() == null) {
return c1.getId().intValue() - c2.getId().intValue();
} else if (c1.getPosition() == null) {
return -1;
} else if (c2.getPosition() == null) {
return 1;
} else {
return c1.getPosition().getPosition() - c2.getPosition().getPosition();
}
})
.map(StorageContainerDetail::from).collect(Collectors.toList());
}
};
}
private String msg(String code) {
return MessageUtil.getInstance().getMessage(code);
}
}
| WEB-INF/src/com/krishagni/catissueplus/core/administrative/services/impl/StorageContainerServiceImpl.java | package com.krishagni.catissueplus.core.administrative.services.impl;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import com.krishagni.catissueplus.core.administrative.domain.ContainerType;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainerPosition;
import com.krishagni.catissueplus.core.administrative.domain.factory.StorageContainerErrorCode;
import com.krishagni.catissueplus.core.administrative.domain.factory.StorageContainerFactory;
import com.krishagni.catissueplus.core.administrative.events.ContainerCriteria;
import com.krishagni.catissueplus.core.administrative.events.ContainerHierarchyDetail;
import com.krishagni.catissueplus.core.administrative.events.ContainerQueryCriteria;
import com.krishagni.catissueplus.core.administrative.events.ContainerReplicationDetail;
import com.krishagni.catissueplus.core.administrative.events.ContainerReplicationDetail.DestinationDetail;
import com.krishagni.catissueplus.core.administrative.events.PositionsDetail;
import com.krishagni.catissueplus.core.administrative.events.ReservePositionsOp;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerDetail;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerPositionDetail;
import com.krishagni.catissueplus.core.administrative.events.StorageContainerSummary;
import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary;
import com.krishagni.catissueplus.core.administrative.events.TenantDetail;
import com.krishagni.catissueplus.core.administrative.events.VacantPositionsOp;
import com.krishagni.catissueplus.core.administrative.repository.StorageContainerListCriteria;
import com.krishagni.catissueplus.core.administrative.services.ContainerMapExporter;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionRule;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionStrategy;
import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionStrategyFactory;
import com.krishagni.catissueplus.core.administrative.services.ScheduledTaskManager;
import com.krishagni.catissueplus.core.administrative.services.StorageContainerService;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpErrorCode;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenInfo;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.biospecimen.repository.SpecimenListCriteria;
import com.krishagni.catissueplus.core.biospecimen.services.SpecimenResolver;
import com.krishagni.catissueplus.core.common.Pair;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.RollbackTransaction;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.errors.ErrorCode;
import com.krishagni.catissueplus.core.common.errors.ErrorType;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.ExportedFileDetail;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.LabelGenerator;
import com.krishagni.catissueplus.core.common.service.ObjectStateParamsResolver;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.de.domain.Filter;
import com.krishagni.catissueplus.core.de.domain.SavedQuery;
import com.krishagni.catissueplus.core.de.events.ExecuteQueryEventOp;
import com.krishagni.catissueplus.core.de.events.QueryDataExportResult;
import com.krishagni.catissueplus.core.de.services.QueryService;
import com.krishagni.catissueplus.core.de.services.SavedQueryErrorCode;
import com.krishagni.catissueplus.core.exporter.domain.ExportJob;
import com.krishagni.catissueplus.core.exporter.services.ExportService;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import edu.common.dynamicextensions.query.WideRowMode;
public class StorageContainerServiceImpl implements StorageContainerService, ObjectStateParamsResolver, InitializingBean {
private static final Log logger = LogFactory.getLog(StorageContainerServiceImpl.class);
private DaoFactory daoFactory;
private com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory;
private StorageContainerFactory containerFactory;
private ContainerMapExporter mapExporter;
private LabelGenerator nameGenerator;
private SpecimenResolver specimenResolver;
private ContainerSelectionStrategyFactory selectionStrategyFactory;
private ScheduledTaskManager taskManager;
private QueryService querySvc;
private ExportService exportSvc;
public DaoFactory getDaoFactory() {
return daoFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
public void setDeDaoFactory(com.krishagni.catissueplus.core.de.repository.DaoFactory deDaoFactory) {
this.deDaoFactory = deDaoFactory;
}
public StorageContainerFactory getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(StorageContainerFactory containerFactory) {
this.containerFactory = containerFactory;
}
public void setMapExporter(ContainerMapExporter mapExporter) {
this.mapExporter = mapExporter;
}
public void setNameGenerator(LabelGenerator nameGenerator) {
this.nameGenerator = nameGenerator;
}
public void setSpecimenResolver(SpecimenResolver specimenResolver) {
this.specimenResolver = specimenResolver;
}
public void setSelectionStrategyFactory(ContainerSelectionStrategyFactory selectionStrategyFactory) {
this.selectionStrategyFactory = selectionStrategyFactory;
}
public void setTaskManager(ScheduledTaskManager taskManager) {
this.taskManager = taskManager;
}
public void setQuerySvc(QueryService querySvc) {
this.querySvc = querySvc;
}
public void setExportSvc(ExportService exportSvc) {
this.exportSvc = exportSvc;
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getStorageContainers(RequestEvent<StorageContainerListCriteria> req) {
try {
StorageContainerListCriteria crit = addContainerListCriteria(req.getPayload());
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getStorageContainers(crit);
List<StorageContainerSummary> result = StorageContainerSummary.from(containers, crit.includeChildren());
setStoredSpecimensCount(crit, result);
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getStorageContainersCount(RequestEvent<StorageContainerListCriteria> req) {
try {
StorageContainerListCriteria crit = addContainerListCriteria(req.getPayload());
return ResponseEvent.response(daoFactory.getStorageContainerDao().getStorageContainersCount(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> getStorageContainer(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
StorageContainerDetail detail = StorageContainerDetail.from(container);
if (req.getPayload().includeStats()) {
detail.setSpecimensByType(daoFactory.getStorageContainerDao().getSpecimensCountByType(detail.getId()));
}
return ResponseEvent.response(detail);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> getOccupiedPositions(RequestEvent<Long> req) {
try {
StorageContainer container = getContainer(req.getPayload(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenInfo>> getSpecimens(RequestEvent<SpecimenListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().ancestorContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
SpecimenListCriteria crit = addSiteCpRestrictions(req.getPayload(), container);
List<Specimen> specimens = daoFactory.getStorageContainerDao().getSpecimens(crit, !container.isDimensionless());
return ResponseEvent.response(SpecimenInfo.from(specimens));
}
@Override
@PlusTransactional
public ResponseEvent<Long> getSpecimensCount(RequestEvent<SpecimenListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().ancestorContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
SpecimenListCriteria crit = addSiteCpRestrictions(req.getPayload(), container);
Long count = daoFactory.getStorageContainerDao().getSpecimensCount(crit);
return ResponseEvent.response(count);
}
@Override
@PlusTransactional
public ResponseEvent<QueryDataExportResult> getSpecimensReport(RequestEvent<ContainerQueryCriteria> req) {
ContainerQueryCriteria crit = req.getPayload();
StorageContainer container = getContainer(crit.getId(), crit.getName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
Integer queryId = ConfigUtil.getInstance().getIntSetting("common", "cont_spmns_report_query", -1);
if (queryId == -1) {
return ResponseEvent.userError(StorageContainerErrorCode.SPMNS_RPT_NOT_CONFIGURED);
}
SavedQuery query = deDaoFactory.getSavedQueryDao().getQuery(queryId.longValue());
if (query == null) {
return ResponseEvent.userError(SavedQueryErrorCode.NOT_FOUND, queryId);
}
return new ResponseEvent<>(exportResult(container, query));
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> createStorageContainer(RequestEvent<StorageContainerDetail> req) {
try {
return ResponseEvent.response(StorageContainerDetail.from(createStorageContainer(null, req.getPayload())));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> updateStorageContainer(RequestEvent<StorageContainerDetail> req) {
return updateStorageContainer(req, false);
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerDetail> patchStorageContainer(RequestEvent<StorageContainerDetail> req) {
return updateStorageContainer(req, true);
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> isAllowed(RequestEvent<TenantDetail> req) {
try {
TenantDetail detail = req.getPayload();
StorageContainer container = getContainer(detail.getContainerId(), detail.getContainerName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
CollectionProtocol cp = new CollectionProtocol();
cp.setId(detail.getCpId());
String specimenClass = detail.getSpecimenClass();
String type = detail.getSpecimenType();
boolean isAllowed = container.canContainSpecimen(cp, specimenClass, type);
if (!isAllowed) {
return ResponseEvent.userError(
StorageContainerErrorCode.CANNOT_HOLD_SPECIMEN,
container.getName(),
Specimen.getDesc(specimenClass, type));
} else {
return ResponseEvent.response(isAllowed);
}
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ExportedFileDetail> exportMap(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DIMLESS_NO_MAP, container.getName());
}
File file = mapExporter.exportToFile(container);
return ResponseEvent.response(new ExportedFileDetail(container.getName(), file));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> assignPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail op = req.getPayload();
StorageContainer container = getContainer(op.getContainerId(), op.getContainerName());
List<StorageContainerPosition> positions = op.getPositions().stream()
.map(posDetail -> createPosition(container, posDetail, op.getVacateOccupant()))
.collect(Collectors.toList());
container.assignPositions(positions, op.getVacateOccupant());
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getDependentEntities(RequestEvent<Long> req) {
try {
StorageContainer existing = getContainer(req.getPayload(), null);
return ResponseEvent.response(existing.getDependentEntities());
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> deleteStorageContainers(RequestEvent<BulkDeleteEntityOp> req) {
try {
Set<Long> containerIds = req.getPayload().getIds();
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getByIds(containerIds);
if (containerIds.size() != containers.size()) {
containers.forEach(container -> containerIds.remove(container.getId()));
throw OpenSpecimenException.userError(StorageContainerErrorCode.NOT_FOUND, containerIds, containerIds.size());
}
List<StorageContainer> ancestors = getAncestors(containers);
ancestors.forEach(AccessCtrlMgr.getInstance()::ensureDeleteContainerRights);
ancestors.forEach(StorageContainer::delete);
//
// returning summary of all containers given by user instead of only ancestor containers
//
return ResponseEvent.response(StorageContainerSummary.from(containers));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> replicateStorageContainer(RequestEvent<ContainerReplicationDetail> req) {
try {
ContainerReplicationDetail replDetail = req.getPayload();
StorageContainer srcContainer = getContainer(
replDetail.getSourceContainerId(),
replDetail.getSourceContainerName(),
null,
StorageContainerErrorCode.SRC_ID_OR_NAME_REQ);
for (DestinationDetail dest : replDetail.getDestinations()) {
replicateContainer(srcContainer, dest);
}
return ResponseEvent.response(true);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> createContainerHierarchy(RequestEvent<ContainerHierarchyDetail> req) {
ContainerHierarchyDetail input = req.getPayload();
List<StorageContainer> containers = new ArrayList<>();
try {
StorageContainer container = containerFactory.createStorageContainer("dummyName", input);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
container.validateRestrictions();
StorageContainer parentContainer = container.getParentContainer();
if (parentContainer != null && !parentContainer.hasFreePositionsForReservation(input.getNumOfContainers())) {
return ResponseEvent.userError(StorageContainerErrorCode.NO_FREE_SPACE, parentContainer.getName());
}
boolean setCapacity = true;
for (int i = 1; i <= input.getNumOfContainers(); i++) {
StorageContainer cloned = null;
if (i == 1) {
cloned = container;
} else {
cloned = container.copy();
setPosition(cloned);
}
generateName(cloned);
ensureUniqueConstraints(null, cloned);
if (cloned.isStoreSpecimenEnabled() && setCapacity) {
cloned.setFreezerCapacity();
setCapacity = false;
}
createContainerHierarchy(cloned.getType().getCanHold(), cloned);
daoFactory.getStorageContainerDao().saveOrUpdate(cloned);
containers.add(cloned);
}
return ResponseEvent.response(StorageContainerDetail.from(containers));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> createMultipleContainers(RequestEvent<List<StorageContainerDetail>> req) {
try {
List<StorageContainerSummary> result = new ArrayList<>();
for (StorageContainerDetail detail : req.getPayload()) {
if (StringUtils.isNotBlank(detail.getTypeName()) || detail.getTypeId() != null) {
detail.setName("dummy");
}
StorageContainer container = containerFactory.createStorageContainer(detail);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
if (container.getType() != null) {
generateName(container);
}
ensureUniqueConstraints(null, container);
container.validateRestrictions();
daoFactory.getStorageContainerDao().saveOrUpdate(container);
result.add(StorageContainerSummary.from(container));
}
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> blockPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail opDetail = req.getPayload();
if (CollectionUtils.isEmpty(opDetail.getPositions())) {
return ResponseEvent.response(Collections.emptyList());
}
StorageContainer container = getContainer(opDetail.getContainerId(), opDetail.getContainerName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DL_POS_BLK_NP, container.getName());
}
List<StorageContainerPosition> positions = opDetail.getPositions().stream()
.map(detail -> container.createPosition(detail.getPosOne(), detail.getPosTwo()))
.collect(Collectors.toList());
container.blockPositions(positions);
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerPositionDetail>> unblockPositions(RequestEvent<PositionsDetail> req) {
try {
PositionsDetail opDetail = req.getPayload();
if (CollectionUtils.isEmpty(opDetail.getPositions())) {
return ResponseEvent.response(Collections.emptyList());
}
StorageContainer container = getContainer(opDetail.getContainerId(), opDetail.getContainerName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.userError(StorageContainerErrorCode.DL_POS_BLK_NP, container.getName());
}
List<StorageContainerPosition> positions = opDetail.getPositions().stream()
.map(detail -> container.createPosition(detail.getPosOne(), detail.getPosTwo()))
.collect(Collectors.toList());
container.unblockPositions(positions);
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return ResponseEvent.response(StorageContainerPositionDetail.from(container.getOccupiedPositions()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageLocationSummary>> reservePositions(RequestEvent<ReservePositionsOp> req) {
long t1 = System.currentTimeMillis();
try {
ReservePositionsOp op = req.getPayload();
if (StringUtils.isNotBlank(op.getReservationToCancel())) {
cancelReservation(new RequestEvent<>(op.getReservationToCancel()));
}
Long cpId = op.getCpId();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND, cpId);
}
if (StringUtils.isBlank(cp.getContainerSelectionStrategy())) {
return ResponseEvent.response(Collections.emptyList());
}
ContainerSelectionStrategy strategy = selectionStrategyFactory.getStrategy(cp.getContainerSelectionStrategy());
if (strategy == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_CONT_SEL_STRATEGY, cp.getContainerSelectionStrategy());
}
Set<Pair<Long, Long>> allowedSiteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps(cpId);
if (allowedSiteCps != null && allowedSiteCps.isEmpty()) {
return ResponseEvent.response(Collections.emptyList());
}
Set<Pair<Long, Long>> reqSiteCps = getRequiredSiteCps(allowedSiteCps, Collections.singleton(cpId));
if (CollectionUtils.isEmpty(reqSiteCps)) {
return ResponseEvent.response(Collections.emptyList());
}
String reservationId = StorageContainer.getReservationId();
Date reservationTime = Calendar.getInstance().getTime();
List<StorageContainerPosition> reservedPositions = new ArrayList<>();
for (ContainerCriteria criteria : op.getCriteria()) {
criteria.siteCps(reqSiteCps);
if (StringUtils.isNotBlank(criteria.ruleName())) {
ContainerSelectionRule rule = selectionStrategyFactory.getRule(criteria.ruleName());
if (rule == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_CONT_SEL_RULE, criteria.ruleName());
}
criteria.rule(rule);
}
boolean allAllocated = false;
while (!allAllocated) {
long t2 = System.currentTimeMillis();
StorageContainer container = strategy.getContainer(criteria, cp.getAliquotsInSameContainer());
if (container == null) {
ResponseEvent<List<StorageLocationSummary>> resp = new ResponseEvent<>(Collections.emptyList());
resp.setRollback(true);
return resp;
}
int numPositions = criteria.minFreePositions();
if (numPositions <= 0) {
numPositions = 1;
}
List<StorageContainerPosition> positions = container.reservePositions(reservationId, reservationTime, numPositions);
numPositions -= positions.size();
if (numPositions == 0) {
allAllocated = true;
} else {
criteria.minFreePositions(numPositions);
}
System.err.println("***** Allocation time: " + (System.currentTimeMillis() - t2) + " ms");
}
}
return ResponseEvent.response(StorageLocationSummary.from(reservedPositions));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
} finally {
System.err.println("***** Call time: " + (System.currentTimeMillis() - t1) + " ms");
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> cancelReservation(RequestEvent<String> req) {
try {
int vacatedPositions = daoFactory.getStorageContainerDao()
.deleteReservedPositions(Collections.singletonList(req.getPayload()));
return ResponseEvent.response(vacatedPositions);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<StorageContainerSummary> getAncestorsHierarchy(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
StorageContainerSummary summary = null;
if (container.getParentContainer() == null) {
summary = new StorageContainerSummary();
summary.setId(container.getId());
summary.setName(container.getName());
summary.setNoOfRows(container.getNoOfRows());
summary.setNoOfColumns(container.getNoOfColumns());
} else {
summary = daoFactory.getStorageContainerDao().getAncestorsHierarchy(container.getId());
}
return ResponseEvent.response(summary);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getChildContainers(RequestEvent<ContainerQueryCriteria> req) {
try {
StorageContainer container = getContainer(req.getPayload());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
if (container.isDimensionless()) {
return ResponseEvent.response(Collections.emptyList());
} else {
return ResponseEvent.response(daoFactory.getStorageContainerDao()
.getChildContainers(container.getId(), container.getNoOfColumns()));
}
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<StorageContainerSummary>> getDescendantContainers(RequestEvent<StorageContainerListCriteria> req) {
StorageContainer container = getContainer(req.getPayload().parentContainerId(), null);
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
List<StorageContainer> containers = daoFactory.getStorageContainerDao().getDescendantContainers(req.getPayload());
return ResponseEvent.response(StorageContainerSummary.from(containers));
}
@Override
@RollbackTransaction
public ResponseEvent<List<StorageLocationSummary>> getVacantPositions(RequestEvent<VacantPositionsOp> req) {
try {
VacantPositionsOp detail = req.getPayload();
StorageContainer container = getContainer(detail.getContainerId(), detail.getContainerName());
AccessCtrlMgr.getInstance().ensureReadContainerRights(container);
int numPositions = detail.getRequestedPositions();
if (numPositions <= 0) {
numPositions = 1;
}
List<StorageContainerPosition> vacantPositions = new ArrayList<>();
for (int i = 0; i < numPositions; ++i) {
StorageContainerPosition position = null;
if (i == 0) {
if (StringUtils.isNotBlank(detail.getStartRow()) && StringUtils.isNotBlank(detail.getStartColumn())) {
position = container.nextAvailablePosition(detail.getStartRow(), detail.getStartColumn());
} else if (detail.getStartPosition() > 0) {
position = container.nextAvailablePosition(detail.getStartPosition());
} else {
position = container.nextAvailablePosition();
}
} else {
position = container.nextAvailablePosition(true);
}
if (position == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
container.addPosition(position);
vacantPositions.add(position);
}
return ResponseEvent.response(
vacantPositions.stream().map(StorageLocationSummary::from).collect(Collectors.toList()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
public StorageContainer createStorageContainer(StorageContainer base, StorageContainerDetail input) {
StorageContainer container = containerFactory.createStorageContainer(base, input);
AccessCtrlMgr.getInstance().ensureCreateContainerRights(container);
ensureUniqueConstraints(null, container);
container.validateRestrictions();
if (container.isStoreSpecimenEnabled()) {
container.setFreezerCapacity();
}
if (container.getPosition() != null) {
container.getPosition().occupy();
}
daoFactory.getStorageContainerDao().saveOrUpdate(container, true);
return container;
}
@Override
public String getObjectName() {
return "container";
}
@Override
@PlusTransactional
public Map<String, Object> resolve(String key, Object value) {
if (key.equals("id")) {
value = Long.valueOf(value.toString());
}
return daoFactory.getStorageContainerDao().getContainerIds(key, value);
}
@Override
public void afterPropertiesSet() throws Exception {
taskManager.scheduleWithFixedDelay(
new Runnable() {
@Override
@PlusTransactional
public void run() {
try {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -5);
int count = daoFactory.getStorageContainerDao().deleteReservedPositionsOlderThan(cal.getTime());
if (count > 0) {
logger.info(String.format("Cleaned up %d stale container slot reservations", count));
}
} catch (Exception e) {
logger.error("Error deleting older reserved container slots", e);
}
}
}, 5
);
exportSvc.registerObjectsGenerator("storageContainer", this::getContainersGenerator);
}
private StorageContainerListCriteria addContainerListCriteria(StorageContainerListCriteria crit) {
Set<Pair<Long, Long>> allowedSiteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps();
if (allowedSiteCps != null && allowedSiteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
if (CollectionUtils.isNotEmpty(crit.cpIds())) {
allowedSiteCps = getRequiredSiteCps(allowedSiteCps, crit.cpIds());
if (allowedSiteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
return crit.siteCps(allowedSiteCps);
}
private Set<Pair<Long, Long>> getRequiredSiteCps(Set<Pair<Long, Long>> allowedSiteCps, Set<Long> cpIds) {
Set<Pair<Long, Long>> reqSiteCps = daoFactory.getCollectionProtocolDao().getSiteCps(cpIds);
if (allowedSiteCps == null) {
allowedSiteCps = reqSiteCps;
} else {
allowedSiteCps = getSiteCps(allowedSiteCps, reqSiteCps);
}
return allowedSiteCps;
}
private Set<Pair<Long, Long>> getSiteCps(Set<Pair<Long, Long>> allowed, Set<Pair<Long, Long>> required) {
Set<Pair<Long, Long>> result = new HashSet<>();
for (Pair<Long, Long> reqSiteCp : required) {
for (Pair<Long, Long> allowedSiteCp : allowed) {
if (!allowedSiteCp.first().equals(reqSiteCp.first())) {
continue;
}
if (allowedSiteCp.second() != null && !allowedSiteCp.second().equals(reqSiteCp.second())) {
continue;
}
result.add(reqSiteCp);
}
}
return result;
}
private void setStoredSpecimensCount(StorageContainerListCriteria crit, List<StorageContainerSummary> containers) {
if (!crit.includeStat() || !crit.topLevelContainers()) {
return;
}
List<Long> containerIds = containers.stream().map(StorageContainerSummary::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(containerIds)) {
return;
}
Map<Long, Integer> countMap = daoFactory.getStorageContainerDao().getRootContainerSpecimensCount(containerIds);
containers.forEach(c -> c.setStoredSpecimens(countMap.get(c.getId())));
}
private StorageContainer getContainer(ContainerQueryCriteria crit) {
return getContainer(crit.getId(), crit.getName(), crit.getBarcode());
}
private StorageContainer getContainer(Long id, String name) {
return getContainer(id, name, null);
}
private StorageContainer getContainer(Long id, String name, String barcode) {
return getContainer(id, name, barcode, StorageContainerErrorCode.ID_NAME_OR_BARCODE_REQ);
}
private StorageContainer getContainer(Long id, String name, String barcode, ErrorCode requiredErrCode) {
StorageContainer container = null;
Object key = null;
if (id != null) {
container = daoFactory.getStorageContainerDao().getById(id);
key = id;
} else {
if (StringUtils.isNotBlank(name)) {
container = daoFactory.getStorageContainerDao().getByName(name);
key = name;
}
if (container == null && StringUtils.isNotBlank(barcode)) {
container = daoFactory.getStorageContainerDao().getByBarcode(barcode);
key = barcode;
}
}
if (key == null) {
throw OpenSpecimenException.userError(requiredErrCode);
} else if (container == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NOT_FOUND, key, 1);
}
return container;
}
private ResponseEvent<StorageContainerDetail> updateStorageContainer(RequestEvent<StorageContainerDetail> req, boolean partial) {
try {
StorageContainerDetail input = req.getPayload();
StorageContainer existing = getContainer(input.getId(), input.getName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(existing);
input.setId(existing.getId());
StorageContainer container = null;
if (partial) {
container = containerFactory.createStorageContainer(existing, input);
} else {
container = containerFactory.createStorageContainer(input);
}
ensureUniqueConstraints(existing, container);
existing.update(container);
daoFactory.getStorageContainerDao().saveOrUpdate(existing, true);
return ResponseEvent.response(StorageContainerDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
private void ensureUniqueConstraints(StorageContainer existing, StorageContainer newContainer) {
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
if (!isUniqueName(existing, newContainer)) {
ose.addError(StorageContainerErrorCode.DUP_NAME, newContainer.getName());
}
if (!isUniqueBarcode(existing, newContainer)) {
ose.addError(StorageContainerErrorCode.DUP_BARCODE);
}
ose.checkAndThrow();
}
private boolean isUniqueName(StorageContainer existingContainer, StorageContainer newContainer) {
if (existingContainer != null && existingContainer.getName().equals(newContainer.getName())) {
return true;
}
return isUniqueName(newContainer.getName());
}
private boolean isUniqueName(String name) {
StorageContainer container = daoFactory.getStorageContainerDao().getByName(name);
return container == null;
}
private boolean isUniqueBarcode(StorageContainer existingContainer, StorageContainer newContainer) {
if (StringUtils.isBlank(newContainer.getBarcode())) {
return true;
}
if (existingContainer != null && newContainer.getBarcode().equals(existingContainer.getBarcode())) {
return true;
}
StorageContainer container = daoFactory.getStorageContainerDao().getByBarcode(newContainer.getBarcode());
return container == null;
}
private StorageContainerPosition createPosition(StorageContainer container, StorageContainerPositionDetail pos, boolean vacateOccupant) {
if (StringUtils.isBlank(pos.getPosOne()) ^ StringUtils.isBlank(pos.getPosTwo())) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INV_POS, container.getName(), pos.getPosOne(), pos.getPosTwo());
}
String entityType = pos.getOccuypingEntity();
if (StringUtils.isBlank(entityType)) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.INVALID_ENTITY_TYPE, "none");
}
if (StringUtils.isBlank(pos.getOccupyingEntityName()) && pos.getOccupyingEntityId() == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.OCCUPYING_ENTITY_ID_OR_NAME_REQUIRED);
}
if (entityType.equalsIgnoreCase("specimen")) {
return createSpecimenPosition(container, pos, vacateOccupant);
} else if (entityType.equalsIgnoreCase("container")) {
return createChildContainerPosition(container, pos);
}
throw OpenSpecimenException.userError(StorageContainerErrorCode.INVALID_ENTITY_TYPE, entityType);
}
private StorageContainerPosition createSpecimenPosition(
StorageContainer container,
StorageContainerPositionDetail pos,
boolean vacateOccupant) {
Specimen specimen = getSpecimen(pos);
AccessCtrlMgr.getInstance().ensureCreateOrUpdateSpecimenRights(specimen, false);
StorageContainerPosition position = null;
if (!container.isDimensionless() && (StringUtils.isBlank(pos.getPosOne()) || StringUtils.isBlank(pos.getPosTwo()))) {
position = new StorageContainerPosition();
position.setOccupyingSpecimen(specimen);
return position;
}
if (!container.canContain(specimen)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.CANNOT_HOLD_SPECIMEN, container.getName(), specimen.getLabelOrDesc());
}
if (!container.canSpecimenOccupyPosition(specimen.getId(), pos.getPosOne(), pos.getPosTwo(), vacateOccupant)) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
position = container.createPosition(pos.getPosOne(), pos.getPosTwo());
position.setOccupyingSpecimen(specimen);
return position;
}
private Specimen getSpecimen(StorageContainerPositionDetail pos) {
return specimenResolver.getSpecimen(
pos.getOccupyingEntityId(),
pos.getCpShortTitle(),
pos.getOccupyingEntityName()
);
}
private SpecimenListCriteria addSiteCpRestrictions(SpecimenListCriteria crit, StorageContainer container) {
Set<Pair<Long, Long>> siteCps = AccessCtrlMgr.getInstance().getReadAccessContainerSiteCps();
if (siteCps != null) {
List<Pair<Long, Long>> contSiteCps = siteCps.stream()
.filter(siteCp -> siteCp.first().equals(container.getSite().getId()))
.collect(Collectors.toList());
crit.siteCps(contSiteCps);
}
return crit;
}
private StorageContainerPosition createChildContainerPosition(
StorageContainer container,
StorageContainerPositionDetail pos) {
StorageContainer childContainer = getContainer(pos.getOccupyingEntityId(), pos.getOccupyingEntityName());
AccessCtrlMgr.getInstance().ensureUpdateContainerRights(childContainer);
if (!container.canContain(childContainer)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.CANNOT_HOLD_CONTAINER,
container.getName(),
childContainer.getName());
}
if (!container.canContainerOccupyPosition(childContainer.getId(), pos.getPosOne(), pos.getPosTwo())) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, container.getName());
}
StorageContainerPosition position = container.createPosition(pos.getPosOne(), pos.getPosTwo());
position.setOccupyingContainer(childContainer);
return position;
}
private void replicateContainer(StorageContainer srcContainer, DestinationDetail dest) {
StorageContainerDetail detail = new StorageContainerDetail();
detail.setName(dest.getName());
detail.setSiteName(dest.getSiteName());
StorageLocationSummary storageLocation = new StorageLocationSummary();
storageLocation.setId(dest.getParentContainerId());
storageLocation.setName(dest.getParentContainerName());
storageLocation.setPositionX(dest.getPosOne());
storageLocation.setPositionY(dest.getPosTwo());
storageLocation.setPosition(dest.getPosition());
detail.setStorageLocation(storageLocation);
createStorageContainer(getContainerCopy(srcContainer), detail);
}
private void createContainerHierarchy(ContainerType containerType, StorageContainer parentContainer) {
if (containerType == null) {
return;
}
StorageContainer container = containerFactory.createStorageContainer("dummyName", containerType, parentContainer);
int noOfContainers = parentContainer.getNoOfRows() * parentContainer.getNoOfColumns();
boolean setCapacity = true;
for (int i = 1; i <= noOfContainers; i++) {
StorageContainer cloned = null;
if (i == 1) {
cloned = container;
} else {
cloned = container.copy();
setPosition(cloned);
}
generateName(cloned);
parentContainer.addChildContainer(cloned);
if (cloned.isStoreSpecimenEnabled() && setCapacity) {
cloned.setFreezerCapacity();
setCapacity = false;
}
createContainerHierarchy(containerType.getCanHold(), cloned);
}
}
private List<StorageContainer> getAncestors(List<StorageContainer> containers) {
Set<Long> descContIds = containers.stream()
.flatMap(c -> c.getDescendentContainers().stream().filter(d -> !d.equals(c)))
.map(StorageContainer::getId)
.collect(Collectors.toSet());
return containers.stream()
.filter(c -> !descContIds.contains(c.getId()))
.collect(Collectors.toList());
}
private void generateName(StorageContainer container) {
ContainerType type = container.getType();
String name = nameGenerator.generateLabel(type.getNameFormat(), container);
if (StringUtils.isBlank(name)) {
throw OpenSpecimenException.userError(
StorageContainerErrorCode.INCORRECT_NAME_FMT,
type.getNameFormat(),
type.getName());
}
container.setName(name);
}
private void setPosition(StorageContainer container) {
StorageContainer parentContainer = container.getParentContainer();
if (parentContainer == null) {
return;
}
StorageContainerPosition position = parentContainer.nextAvailablePosition(true);
if (position == null) {
throw OpenSpecimenException.userError(StorageContainerErrorCode.NO_FREE_SPACE, parentContainer.getName());
}
position.setOccupyingContainer(container);
container.setPosition(position);
}
private StorageContainer getContainerCopy(StorageContainer source) {
StorageContainer copy = new StorageContainer();
copy.setTemperature(source.getTemperature());
copy.setNoOfColumns(source.getNoOfColumns());
copy.setNoOfRows(source.getNoOfRows());
copy.setColumnLabelingScheme(source.getColumnLabelingScheme());
copy.setRowLabelingScheme(source.getRowLabelingScheme());
copy.setComments(source.getComments());
copy.setAllowedSpecimenClasses(new HashSet<String>(source.getAllowedSpecimenClasses()));
copy.setAllowedSpecimenTypes(new HashSet<String>(source.getAllowedSpecimenTypes()));
copy.setAllowedCps(new HashSet<CollectionProtocol>(source.getAllowedCps()));
copy.setCompAllowedSpecimenClasses(copy.computeAllowedSpecimenClasses());
copy.setCompAllowedSpecimenTypes(copy.computeAllowedSpecimenTypes());
copy.setCompAllowedCps(copy.computeAllowedCps());
copy.setStoreSpecimenEnabled(source.isStoreSpecimenEnabled());
copy.setCreatedBy(AuthUtil.getCurrentUser());
return copy;
}
private QueryDataExportResult exportResult(final StorageContainer container, SavedQuery query) {
Filter filter = new Filter();
filter.setField("Specimen.specimenPosition.allAncestors.ancestorId");
filter.setOp(Filter.Op.EQ);
filter.setValues(new String[] { container.getId().toString() });
ExecuteQueryEventOp execReportOp = new ExecuteQueryEventOp();
execReportOp.setDrivingForm("Participant");
execReportOp.setAql(query.getAql(new Filter[] { filter }));
execReportOp.setWideRowMode(WideRowMode.DEEP.name());
execReportOp.setRunType("Export");
return querySvc.exportQueryData(execReportOp, new QueryService.ExportProcessor() {
@Override
public String filename() {
return "container_" + container.getId() + "_" + UUID.randomUUID().toString();
}
@Override
public void headers(OutputStream out) {
Map<String, String> headers = new LinkedHashMap<String, String>() {{
String notSpecified = msg("common_not_specified");
put(msg("container_name"), container.getName());
put(msg("container_site"), container.getSite().getName());
if (container.getParentContainer() != null) {
put(msg("container_parent_container"), container.getParentContainer().getName());
}
if (container.getType() != null) {
put(msg("container_type"), container.getType().getName());
}
put("", ""); // blank line
}};
Utility.writeKeyValuesToCsv(out, headers);
}
});
}
private Function<ExportJob, List<? extends Object>> getContainersGenerator() {
return new Function<ExportJob, List<? extends Object>>() {
private boolean loadTopLevelContainers = true;
private boolean endOfContainers;
private int startAt;
private StorageContainerListCriteria topLevelCrit;
private StorageContainerListCriteria descendantsCrit;
private List<StorageContainerDetail> topLevelContainers = new ArrayList<>();
@Override
public List<StorageContainerDetail> apply(ExportJob job) {
if (endOfContainers) {
return Collections.emptyList();
}
if (topLevelContainers.isEmpty()) {
if (topLevelCrit == null) {
topLevelCrit = new StorageContainerListCriteria().topLevelContainers(true).ids(job.getRecordIds());
addContainerListCriteria(topLevelCrit);
}
if (loadTopLevelContainers) {
topLevelContainers = getContainers(topLevelCrit.startAt(startAt));
startAt += topLevelContainers.size();
loadTopLevelContainers = CollectionUtils.isEmpty(job.getRecordIds());
}
}
if (topLevelContainers.isEmpty()) {
endOfContainers = true;
return Collections.emptyList();
}
if (descendantsCrit == null) {
descendantsCrit = new StorageContainerListCriteria()
.siteCps(topLevelCrit.siteCps()).maxResults(100000);
}
StorageContainerDetail topLevelContainer = topLevelContainers.remove(0);
descendantsCrit.parentContainerId(topLevelContainer.getId());
List<StorageContainer> descendants = daoFactory.getStorageContainerDao().getDescendantContainers(descendantsCrit);
Map<Long, List<StorageContainer>> childContainersMap = new HashMap<>();
for (StorageContainer container : descendants) {
Long parentId = container.getParentContainer() == null ? null : container.getParentContainer().getId();
List<StorageContainer> childContainers = childContainersMap.get(parentId);
if (childContainers == null) {
childContainers = new ArrayList<>();
childContainersMap.put(parentId, childContainers);
}
childContainers.add(container);
}
List<StorageContainerDetail> workList = new ArrayList<>();
workList.addAll(toDetailList(childContainersMap.get(null)));
List<StorageContainerDetail> result = new ArrayList<>();
while (!workList.isEmpty()) {
StorageContainerDetail containerDetail = workList.remove(0);
result.add(containerDetail);
List<StorageContainer> childContainers = childContainersMap.get(containerDetail.getId());
if (childContainers != null) {
workList.addAll(0, toDetailList(childContainers));
}
}
return result;
}
private List<StorageContainerDetail> getContainers(StorageContainerListCriteria crit) {
return toDetailList(daoFactory.getStorageContainerDao().getStorageContainers(crit));
}
private List<StorageContainerDetail> toDetailList(List<StorageContainer> containers) {
return containers.stream()
.sorted((c1, c2) -> {
if (c1.getPosition() == null && c2.getPosition() == null) {
return c1.getId().intValue() - c2.getId().intValue();
} else if (c1.getPosition() == null) {
return -1;
} else if (c2.getPosition() == null) {
return 1;
} else {
return c1.getPosition().getPosition() - c2.getPosition().getPosition();
}
})
.map(StorageContainerDetail::from).collect(Collectors.toList());
}
};
}
private String msg(String code) {
return MessageUtil.getInstance().getMessage(code);
}
}
| OPSMN-4043: During code refactoring, inadvertently removed the instruction
that accumulated the reserved slots/positions. As a result, the reservation
API is always returning empty list.
Fixed the code to accumulate reserved slots and send in API response.
| WEB-INF/src/com/krishagni/catissueplus/core/administrative/services/impl/StorageContainerServiceImpl.java | OPSMN-4043: During code refactoring, inadvertently removed the instruction that accumulated the reserved slots/positions. As a result, the reservation API is always returning empty list. | <ide><path>EB-INF/src/com/krishagni/catissueplus/core/administrative/services/impl/StorageContainerServiceImpl.java
<ide> }
<ide>
<ide> List<StorageContainerPosition> positions = container.reservePositions(reservationId, reservationTime, numPositions);
<add> reservedPositions.addAll(positions);
<ide> numPositions -= positions.size();
<ide> if (numPositions == 0) {
<ide> allAllocated = true; |
|
Java | apache-2.0 | 7ee8ff79926a677a9e98d4a1673cdaeee5de0036 | 0 | Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core,Sable/mclab-core | // =========================================================================== //
// //
// Copyright 2008-2015 Andrew Casey, Jun Li, Jesse Doherty, //
// Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, //
// Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, //
// Sameer Jagdale, Laurie Hendren, Clark Verbrugge and McGill University. //
// //
// 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 natlab.options;
import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.Parameter;
/**
* Contains the command line options supported by McLab-Core.
* Supports various options for the parsers, McSAF, Tamer and Tamer+.
* The JCommander command line parsing tool is used to parse and generarate the options. The command line options that are supported are defined using annotations. The set of valid values for each command line options are defined by the type of the class member which the annotation manipulates.
* @author Sameer Jagdale
*/
public class Options {
/** Command line options and the variables which are manipulated.
* The Parameter annotation is used the define the possible command line arguments for which the value of the member variable will be changed. The description string gives the description of the command line option, which is used when printing out usage
*/
// General Options
// Help needs to be set to true in the annotation too allow JCommander to indentify this as the help option.
@Parameter(names={"--help", "-h"},description="Display help and exit",help=true)
protected boolean help=false;
@Parameter(names={"-p", "--pretty"}, description="Prettyprint the files")
protected boolean pretty=false;
@Parameter(names={"--simplify", "-s"}, description="Simplify the AST after parsing")
protected boolean simplify=false;
@Parameter(names={"--xml", "-x"},description="Prints the XML IR")
protected boolean xml=false;
@Parameter(names={"--json","j"}, description="Prints the JSON IR")
protected boolean json=false;
@Parameter(names={"--matlab", "-m"}, description="No-op, allowed for backwards compatibility")
protected boolean matlab=false;
@Parameter(names={"--quiet", "-q"}, description="Suppress all information messages")
protected boolean quiet=false;
@Parameter(names={"--natlab","-n"}, description="Use Natlab input")
protected boolean natlab=false;
@Parameter(names={"--outdir", "od"}, description="Output everything to this dir rather than stdout")
protected String od="";
// Server Options
@Parameter(names={"--server"},description="Run frontend in server mode on a given port, default is 47146")
protected boolean server=false;
@Parameter(names={"--sport","-sp"}, description="Set the port the server runs on")
protected String sp="";
/**
* The server will no longer try to detect broken connections using a the heartbeat
*/
//signal.
@Parameter(names={"-nh","--noheart"},description="Turns off the need for a heartbeat signal")
protected boolean noheart=false;
/**
* Tells the version of the source code from which this jar file was compiled.
*/
@Parameter(names={"-v", "--version"},description="Get the current version of Natlab")
protected boolean version=false;
//McLint Options
/**
* Runs the McLint static analyzer and refactoring helper.
*/
@Parameter(names={"--mclint"},description="Run McLint")
protected boolean mclint=false;
//Tamer Options
/**
* Runs the Tamer on a program, and will output a full Matlab program either as a single file or in a directory (via -outdir/od). The programs will be transformed
*/
@Parameter(names={"-t","--tamer"},description="Tame a Matlab program")
protected boolean tamer=false;
/**
* Inlines a whole Matlab program into one function, if it is non-recursive and does not include ambiguous call edges (i.e. overloading).
*/
@Parameter(names="--inline",description="Inline the whole Matlab program in one function, if possible")
protected boolean inline=false;
/**
* Specifies the type of the arguments to the main function.
* The default is "double", i.e. one double. For now this uses the
* same syntax as the class specification language for builtin functions.
*/
@Parameter(names={"--args","--arguments"}, description="Specifies type of arguments to the main function (default is 'double')")
protected String arguments="";
//Tamer+ Options
/**
* Transform the program in Tamer IR to Tamer+ IR.
*/
@Parameter(names={"tamerplus"}, description="Get the Tamer+ version of a program")
protected boolean tamerplus=false;
//Path and File Options
/**
* Path of locations to find matlab files.
*/
@Parameter(names={"--lpath","-lp"}, description="Path of locations to fine Matlab files")
protected List<String> lp=new ArrayList<String>();
/**
* Files to be used as input.
* If no main file is specified then the first file is taken to be the main.
*/
@Parameter(names={"--in"}, description="Files to be used as input")
protected List<String> in = new ArrayList<String>();
/**
*File taken to be the main file and entry point of the program.
* Note: this can also be specified by a single file as argument to the compiler.
*/
@Parameter(names={"--main"}, description="File taken to be the main file and entry point of the program.Note: this can also be specified by a single file as argument to the compiler.")
protected String main="";
//Setting Natlab Stored Preferences
/**
*performs the specified preference operation(s), then exits
*/
@Parameter(names={"--pref", "--preferences"}, description=" performs the specified preference operation(s), then exits")
protected boolean pref=false;
/**
* Set Path ( all path directories) of a Matlab installation
*/
@Parameter(names={"--set_matlab_path"},description="Set Path ( all path directories) of a Matlab installation")
protected List<String> set_matlab_path = new ArrayList<String>();
/**
* Adds the given paths to the Matlab installation path
*/
@Parameter(names={"--add_matlab_path"},description="adds the given paths to the Matlab installation path")
protected List<String> add_matlab_path = new ArrayList<String>();
/**
* Adds given paths to the Natlab path
*/
@Parameter(names={"--add_natlab_path"},description="Adds given paths to the Natlab path")
protected List<String> add_natlab_path = new ArrayList<String>();
/**
* Displays all stored preferences
*/
@Parameter(names={"--short_pref", "--show_preferences"},description ="Displays all stored preferences")
protected boolean show_pref = false;
}
| languages/Natlab/src/natlab/options/Options.java | // =========================================================================== //
// //
// Copyright 2008-2015 Andrew Casey, Jun Li, Jesse Doherty, //
// Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, //
// Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, //
// Sameer Jagdale, Laurie Hendren, Clark Verbrugge and McGill University. //
// //
// 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 natlab.options;
import java.util.ArrayList;
import java.util.List;
import com.beust.jcommander.Parameter;
/**
* Contains the command line options supported by McLab-Core.
* Supports various options for the parsers, McSAF, Tamer and Tamer+.
* The JCommander command line parsing tool is used to parse and generarate the options. The command line options that are supported are defined using annotations. The set of valid values for each command line options are defined by the type of the class member which the annotation manipulates.
* @author Sameer Jagdale
*/
public class Options {
/** Command line options and the variables which are manipulated.
* The Parameter annotation is used the define the possible command line arguments for which the value of the member variable will be changed. The description string gives the description of the command line option, which is used when printing out usage
*/
// General Options
// Help needs to be set to true in the annotation too allow JCommander to indentify this as the help option.
@Parameter(names={"--help", "-h"},description="Display help and exit",help=true)
protected boolean help=false;
@Parameter(names={"-p", "--pretty"}, description="Prettyprint the files")
protected boolean pretty=false;
@Parameter(names={"--simplify", "-s"}, description="Simplify the AST after parsing")
protected boolean simplify=false;
@Parameter(names={"--xml", "-x"},description="Prints the XML IR")
protected boolean xml=false;
@Parameter(names={"--json","j"}, description="Prints the JSON IR")
protected boolean json=false;
@Parameter(names={"--matlab", "-m"}, description="No-op, allowed for backwards compatibility")
protected boolean matlab=false;
@Parameter(names={"--quiet", "-q"}, description="Suppress all information messages")
protected boolean quiet=false;
@Parameter(names={"--natlab","-n"}, description="Use Natlab input")
protected boolean natlab=false;
@Parameter(names={"--outdir", "od"}, description="Output everything to this dir rather than stdout")
protected String od="";
// Server Options
@Parameter(names={"--server"},description="Run frontend in server mode on a given port, default is 47146")
protected boolean server=false;
@Parameter(names={"--sport","-sp"}, description="Set the port the server runs on")
protected String sp="";
/**
* The server will no longer try to detect broken connections using a the heartbeat
*/
//signal.
@Parameter(names={"-nh","--noheart"},description="Turns off the need for a heartbeat signal")
protected boolean noheart=false;
/**
* Tells the version of the source code from which this jar file was compiled.
*/
@Parameter(names={"-v", "--version"},description="Get the current version of Natlab")
protected boolean version=false;
//McLint Options
/**
* Runs the McLint static analyzer and refactoring helper.
*/
@Parameter(names={"--mclint"},description="Run McLint")
protected boolean mclint=false;
//Tamer Options
/**
* Runs the Tamer on a program, and will output a full Matlab program either as a single file or in a directory (via -outdir/od). The programs will be transformed
*/
@Parameter(names={"-t","--tamer"},description="Tame a Matlab program")
protected boolean tamer=false;
/**
* Inlines a whole Matlab program into one function, if it is non-recursive and does not include ambiguous call edges (i.e. overloading).
*/
@Parameter(names="--inline",description="Inline the whole Matlab program in one function, if possible")
protected boolean inline=false;
/**
* Specifies the type of the arguments to the main function.
* The default is "double", i.e. one double. For now this uses the
* same syntax as the class specification language for builtin functions.
*/
@Parameter(names={"--args","--arguments"}, description="Specifies type of arguments to the main function (default is 'double')")
protected String arguments="";
//Tamer+ Options
/**
* Transform the program in Tamer IR to Tamer+ IR.
*/
@Parameter(names={"tamerplus"}, description="Get the Tamer+ version of a program")
protected boolean tamerplus=false;
//Path and File Options
/**
* Path of locations to find matlab files.
*/
@Parameter(names={"--lpath","-lp"}, description="Path of locations to fine Matlab files")
List<String> lp=new ArrayList<String>();
}
| Added new options to the OPtions class.
| languages/Natlab/src/natlab/options/Options.java | Added new options to the OPtions class. | <ide><path>anguages/Natlab/src/natlab/options/Options.java
<ide> * Path of locations to find matlab files.
<ide> */
<ide> @Parameter(names={"--lpath","-lp"}, description="Path of locations to fine Matlab files")
<del> List<String> lp=new ArrayList<String>();
<add> protected List<String> lp=new ArrayList<String>();
<add> /**
<add> * Files to be used as input.
<add> * If no main file is specified then the first file is taken to be the main.
<add> */
<add> @Parameter(names={"--in"}, description="Files to be used as input")
<add> protected List<String> in = new ArrayList<String>();
<add> /**
<add> *File taken to be the main file and entry point of the program.
<add> * Note: this can also be specified by a single file as argument to the compiler.
<add> */
<add> @Parameter(names={"--main"}, description="File taken to be the main file and entry point of the program.Note: this can also be specified by a single file as argument to the compiler.")
<add> protected String main="";
<add>
<add> //Setting Natlab Stored Preferences
<add> /**
<add> *performs the specified preference operation(s), then exits
<add> */
<add> @Parameter(names={"--pref", "--preferences"}, description=" performs the specified preference operation(s), then exits")
<add> protected boolean pref=false;
<add> /**
<add> * Set Path ( all path directories) of a Matlab installation
<add> */
<add> @Parameter(names={"--set_matlab_path"},description="Set Path ( all path directories) of a Matlab installation")
<add> protected List<String> set_matlab_path = new ArrayList<String>();
<add> /**
<add> * Adds the given paths to the Matlab installation path
<add> */
<add> @Parameter(names={"--add_matlab_path"},description="adds the given paths to the Matlab installation path")
<add> protected List<String> add_matlab_path = new ArrayList<String>();
<add> /**
<add> * Adds given paths to the Natlab path
<add> */
<add> @Parameter(names={"--add_natlab_path"},description="Adds given paths to the Natlab path")
<add> protected List<String> add_natlab_path = new ArrayList<String>();
<add> /**
<add> * Displays all stored preferences
<add> */
<add> @Parameter(names={"--short_pref", "--show_preferences"},description ="Displays all stored preferences")
<add> protected boolean show_pref = false;
<ide> } |
|
Java | apache-2.0 | 7edb7e34f86ed1cf0ae83a9e3d02f57272e2acfa | 0 | sdinot/hipparchus,apache/commons-math,apache/commons-math,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,sdinot/hipparchus,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus | /*
* 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.commons.math.optimization.linear;
import java.util.Collection;
import org.apache.commons.math.MaxIterationsExceededException;
import org.apache.commons.math.optimization.GoalType;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.RealPointValuePair;
/**
* Base class for implementing linear optimizers.
* <p>This base class handles the boilerplate methods associated to thresholds
* settings and iterations counters.</p>
* @version $Revision$ $Date$
* @since 2.0
*
*/
public abstract class AbstractLinearOptimizer implements LinearOptimizer {
/** Serializable version identifier */
private static final long serialVersionUID = 8581325080951819398L;
/** Default maximal number of iterations allowed. */
public static final int DEFAULT_MAX_ITERATIONS = 100;
/** Maximal number of iterations allowed. */
private int maxIterations;
/** Number of iterations already performed. */
private int iterations;
/** Linear objective function. */
protected LinearObjectiveFunction f;
/** Linear constraints. */
protected Collection<LinearConstraint> constraints;
/** Type of optimization goal: either {@link GoalType#MAXIMIZE} or {@link GoalType#MINIMIZE}. */
protected GoalType goalType;
/** Whether to restrict the variables to non-negative values. */
protected boolean restrictToNonNegative;
/** Simple constructor with default settings.
* <p>The maximal number of evaluation is set to its default value.</p>
*/
protected AbstractLinearOptimizer() {
setMaxIterations(DEFAULT_MAX_ITERATIONS);
}
/** {@inheritDoc} */
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
/** {@inheritDoc} */
public int getMaxIterations() {
return maxIterations;
}
/** {@inheritDoc} */
public int getIterations() {
return iterations;
}
/** Increment the iterations counter by 1.
* @exception OptimizationException if the maximal number
* of iterations is exceeded
*/
protected void incrementIterationsCounter()
throws OptimizationException {
if (++iterations > maxIterations) {
if (++iterations > maxIterations) {
throw new OptimizationException(new MaxIterationsExceededException(maxIterations));
}
}
}
/** {@inheritDoc} */
public RealPointValuePair optimize(final LinearObjectiveFunction f,
final Collection<LinearConstraint> constraints,
final GoalType goalType, final boolean restrictToNonNegative)
throws OptimizationException {
// store linear problem characteristics
this.f = f;
this.constraints = constraints;
this.goalType = goalType;
this.restrictToNonNegative = restrictToNonNegative;
iterations = 0;
// solve the problem
return doOptimize();
}
/** Perform the bulk of optimization algorithm.
* @return the point/value pair giving the optimal value for objective function
* @exception OptimizationException if no solution fulfilling the constraints
* can be found in the allowed number of iterations
*/
abstract protected RealPointValuePair doOptimize()
throws OptimizationException;
} | src/java/org/apache/commons/math/optimization/linear/AbstractLinearOptimizer.java | /*
* 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.commons.math.optimization.linear;
import java.util.Collection;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.MaxIterationsExceededException;
import org.apache.commons.math.optimization.GoalType;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.RealPointValuePair;
/**
* Base class for implementing linear optimizers.
* <p>This base class handles the boilerplate methods associated to thresholds
* settings and iterations counters.</p>
* @version $Revision$ $Date$
* @since 2.0
*
*/
public abstract class AbstractLinearOptimizer implements LinearOptimizer {
/** Serializable version identifier */
private static final long serialVersionUID = 8581325080951819398L;
/** Default maximal number of iterations allowed. */
public static final int DEFAULT_MAX_ITERATIONS = 100;
/** Maximal number of iterations allowed. */
private int maxIterations;
/** Number of iterations already performed. */
private int iterations;
/** Linear objective function. */
protected LinearObjectiveFunction f;
/** Linear constraints. */
protected Collection<LinearConstraint> constraints;
/** Type of optimization goal: either {@link GoalType#MAXIMIZE} or {@link GoalType#MINIMIZE}. */
protected GoalType goalType;
/** Whether to restrict the variables to non-negative values. */
protected boolean restrictToNonNegative;
/** Simple constructor with default settings.
* <p>The maximal number of evaluation is set to its default value.</p>
*/
protected AbstractLinearOptimizer() {
setMaxIterations(DEFAULT_MAX_ITERATIONS);
}
/** {@inheritDoc} */
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
/** {@inheritDoc} */
public int getMaxIterations() {
return maxIterations;
}
/** {@inheritDoc} */
public int getIterations() {
return iterations;
}
/** Increment the iterations counter by 1.
* @exception OptimizationException if the maximal number
* of iterations is exceeded
*/
protected void incrementIterationsCounter()
throws OptimizationException {
if (++iterations > maxIterations) {
if (++iterations > maxIterations) {
throw new OptimizationException(new MaxIterationsExceededException(maxIterations));
}
}
}
/** {@inheritDoc} */
public RealPointValuePair optimize(final LinearObjectiveFunction f,
final Collection<LinearConstraint> constraints,
final GoalType goalType, final boolean restrictToNonNegative)
throws OptimizationException {
// store linear problem characteristics
this.f = f;
this.constraints = constraints;
this.goalType = goalType;
this.restrictToNonNegative = restrictToNonNegative;
iterations = 0;
// solve the problem
return doOptimize();
}
/** Perform the bulk of optimization algorithm.
* @return the point/value pair giving the optimal value for objective function
* @exception OptimizationException if no solution fulfilling the constraints
* can be found in the allowed number of iterations
*/
abstract protected RealPointValuePair doOptimize()
throws OptimizationException;
} | removed spurious import clause
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@758923 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/commons/math/optimization/linear/AbstractLinearOptimizer.java | removed spurious import clause | <ide><path>rc/java/org/apache/commons/math/optimization/linear/AbstractLinearOptimizer.java
<ide>
<ide> import java.util.Collection;
<ide>
<del>import org.apache.commons.math.FunctionEvaluationException;
<ide> import org.apache.commons.math.MaxIterationsExceededException;
<ide> import org.apache.commons.math.optimization.GoalType;
<ide> import org.apache.commons.math.optimization.OptimizationException; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.